repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xiaoxinghu/swift-org | Sources/Paragraph.swift | 1 | 1061 | //
// Paragraph.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 21/09/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
public struct Paragraph: Node {
public var lines: [String]
public var text: String {
return lines.joined(separator: " ")
}
public var parsed: [InlineToken] {
return InlineLexer(text: text).tokenize()
}
public var description: String {
return "Paragraph(text: \(text))"
}
}
extension OrgParser {
func parseParagraph(_ startWith: String? = nil) throws -> Paragraph? {
var paragraph: Paragraph? = nil
if let firstLine = startWith {
paragraph = Paragraph(lines: [firstLine])
}
while let (_, token) = tokens.peek() {
if case .line(let t) = token {
paragraph = paragraph ?? Paragraph(lines: [])
paragraph?.lines.append(t)
_ = tokens.dequeue()
} else {
break
}
}
return paragraph
}
}
| mit | 181d0daec451df5f4839a39408fb88f5 | 24.238095 | 74 | 0.55 | 4.344262 | false | false | false | false |
dymx101/BallDown | BallDown/Board/BoardStick.swift | 1 | 3147 | //
// BoardStick.swift
// BallDown
//
// Copyright © 2015 ones. All rights reserved.
//
import Foundation
import SpriteKit
class BoardSticks: BoardAbstract {
let boardRadius = Boards.radius
let stickWidth = 20
let stickHeight = 25
let stickColor = SKColor(hue: CGFloat(0) / 360.0, saturation: 0.15, brightness: 0.9, alpha: 1)
let stickStrokeColor = SKColor(hue: CGFloat(0) / 360.0, saturation: 0.15, brightness: 0.7, alpha: 1)
var boardCollideMask: UInt32!
var stickCollideMask: UInt32!
override func newNode(boardTemplate: BoardTemplate, boardSize: CGSize) -> SKNode {
boardCollideMask = boardTemplate.collideMaskFirst
stickCollideMask = boardTemplate.collideMaskSecond
let board = SKShapeNode(rectOfSize: boardSize, cornerRadius: boardRadius)
board.name = "BoardStick.board"
board.physicsBody = SKPhysicsBody(rectangleOfSize: board.frame.size)
board.physicsBody!.categoryBitMask = boardCollideMask
board.physicsBody!.dynamic = false
board.position.x = board.frame.width / 2
board.fillColor = Boards.normalBoardColor
board.strokeColor = Boards.normalBoardStrokeColor
board.bind = self
let boardAvaliableWidth = board.frame.width - boardRadius * 2
let sticks = makeSticks(boardAvaliableWidth)
sticks.name = "BoardStick.sticks"
sticks.userData = NSMutableDictionary()
sticks.userData!.setValue(self, forKey: Boards.DATA_BOARD_NAME)
sticks.position.x = -sticks.frame.width / 2
sticks.position.y = board.frame.height / 2
sticks.fillColor = stickColor
sticks.strokeColor = stickStrokeColor
sticks.bind = self
board.addChild(sticks)
return board
}
override func onBeginContact(board: SKNode, ball: Ball, contact: SKPhysicsContact, game: GameDelegate) {
if board.physicsBody!.categoryBitMask == self.stickCollideMask {
game.stopGame()
}
}
override func playCollideSound(fromFloor: Int, toFloor: Int) {
}
private func makeSticks(boardAvaliableWidth: CGFloat)-> SKShapeNode {
let stickCount = Int(floor(boardAvaliableWidth / CGFloat(stickWidth)))
var drawX = CGFloat(0)
let sticksPath = CGPathCreateMutable()
CGPathMoveToPoint(sticksPath, nil, drawX, CGFloat(0))
for _ in 0 ..< stickCount {
drawX += CGFloat(stickWidth / 2)
CGPathAddLineToPoint(sticksPath, nil, drawX, CGFloat(stickHeight))
drawX += CGFloat(stickWidth / 2)
CGPathAddLineToPoint(sticksPath, nil, drawX, CGFloat(0))
}
CGPathCloseSubpath(sticksPath)
let sticks = SKShapeNode(path: sticksPath)
sticks.physicsBody = SKPhysicsBody(rectangleOfSize: sticks.frame.size, center: CGPoint(x: sticks.frame.width / 2, y: sticks.frame.height / 2))
sticks.physicsBody!.categoryBitMask = stickCollideMask
sticks.physicsBody!.dynamic = false
return sticks
}
} | mit | 076adb278369e1df992d86227a208dc4 | 35.593023 | 150 | 0.652575 | 4.268657 | false | false | false | false |
ibhupi/cksapp | ios-app/cksapp/AppDelegate.swift | 1 | 3163 | //
// AppDelegate.swift
// cksapp
//
// Created by Bhupendra Singh on 7/2/16.
// Copyright © 2016 Bhupendra Singh. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if let userID = NSUserDefaults.standardUserDefaults().stringForKey("currentUserID") {
CurrentUser.id = userID
CurrentUserSchduele.userID = CurrentUser.id
GameService.sharedInstance.AllGames({ (items) in
GameService.sharedInstance.fetchCurrentUserSchedule()
})
} else {
APIService.UserFromAPI({ (items) in
if let item = items?.first {
CurrentUser.id = item.id
NSUserDefaults.standardUserDefaults().setObject(CurrentUser.id, forKey: "currentUserID")
NSUserDefaults.standardUserDefaults().synchronize()
CurrentUserSchduele.userID = CurrentUser.id
GameService.sharedInstance.AllGames({ (items) in
GameService.sharedInstance.fetchCurrentUserSchedule()
})
}
})
}
let _ = LocationServices.sharedInstance
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 6658aec793a402b84534aaed9e75290f | 45.5 | 285 | 0.691018 | 5.707581 | false | false | false | false |
OscarSwanros/swift | tools/SwiftSyntax/SyntaxCollection.swift | 5 | 4631 | //===-------------- SyntaxCollection.swift - Syntax Collection ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// Represents a collection of Syntax nodes of a specific type. SyntaxCollection
/// behaves as a regular Swift collection, and has accessors that return new
/// versions of the collection with different children.
public class SyntaxCollection<SyntaxElement: Syntax>: Syntax {
/// Creates a new SyntaxCollection by replacing the underlying layout with
/// a different set of raw syntax nodes.
///
/// - Parameter layout: The new list of raw syntax nodes underlying this
/// collection.
/// - Returns: A new SyntaxCollection with the new layout underlying it.
internal func replacingLayout(
_ layout: [RawSyntax]) -> SyntaxCollection<SyntaxElement> {
let newRaw = data.raw.replacingLayout(layout)
let (newRoot, newData) = data.replacingSelf(newRaw)
return SyntaxCollection<SyntaxElement>(root: newRoot, data: newData)
}
/// Creates a new SyntaxCollection by appending the provided syntax element
/// to the children.
///
/// - Parameter syntax: The element to append.
/// - Returns: A new SyntaxCollection with that element appended to the end.
public func appending(
_ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> {
var newLayout = data.raw.layout
newLayout.append(syntax.raw)
return replacingLayout(newLayout)
}
/// Creates a new SyntaxCollection by prepending the provided syntax element
/// to the children.
///
/// - Parameter syntax: The element to prepend.
/// - Returns: A new SyntaxCollection with that element prepended to the
/// beginning.
public func prepending(
_ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> {
return inserting(syntax, at: 0)
}
/// Creates a new SyntaxCollection by inserting the provided syntax element
/// at the provided index in the children.
///
/// - Parameters:
/// - syntax: The element to insert.
/// - index: The index at which to insert the element in the collection.
///
/// - Returns: A new SyntaxCollection with that element appended to the end.
public func inserting(_ syntax: SyntaxElement,
at index: Int) -> SyntaxCollection<SyntaxElement> {
var newLayout = data.raw.layout
/// Make sure the index is a valid insertion index (0 to 1 past the end)
precondition((newLayout.startIndex...newLayout.endIndex).contains(index),
"inserting node at invalid index \(index)")
newLayout.insert(syntax.raw, at: index)
return replacingLayout(newLayout)
}
/// Creates a new SyntaxCollection by removing the syntax element at the
/// provided index.
///
/// - Parameter index: The index of the element to remove from the collection.
/// - Returns: A new SyntaxCollection with the element at the provided index
/// removed.
public func removing(childAt index: Int) -> SyntaxCollection<SyntaxElement> {
var newLayout = data.raw.layout
newLayout.remove(at: index)
return replacingLayout(newLayout)
}
/// Creates a new SyntaxCollection by removing the first element.
///
/// - Returns: A new SyntaxCollection with the first element removed.
public func removingFirst() -> SyntaxCollection<SyntaxElement> {
var newLayout = data.raw.layout
newLayout.removeFirst()
return replacingLayout(newLayout)
}
/// Creates a new SyntaxCollection by removing the last element.
///
/// - Returns: A new SyntaxCollection with the last element removed.
public func removingLast() -> SyntaxCollection<SyntaxElement> {
var newLayout = data.raw.layout
newLayout.removeLast()
return replacingLayout(newLayout)
}
}
/// Conformance for SyntaxCollection to the Collection protocol.
extension SyntaxCollection: Collection {
public var startIndex: Int {
return data.childCaches.startIndex
}
public var endIndex: Int {
return data.childCaches.endIndex
}
public func index(after i: Int) -> Int {
return data.childCaches.index(after: i)
}
public subscript(_ index: Int) -> SyntaxElement {
return child(at: index)! as! SyntaxElement
}
} | apache-2.0 | bbaebbb681973d9206168bc10755a05f | 37.280992 | 80 | 0.689484 | 4.61255 | false | false | false | false |
supermarin/Swifternalization | SwifternalizationTests/ExpressionTests.swift | 1 | 1266 | //
// ExpressionTests.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import UIKit
import XCTest
import Swifternalization
class ExpressionTests: XCTestCase {
func testThatInequalityExpressionShouldBeCreated() {
XCTAssertTrue(Expression.expressionFromString("abc{ie:%d=2}") != nil, "Expression should be created")
}
func testThatInequalityExtendedExpressionShouldBeCreated() {
XCTAssertTrue(Expression.expressionFromString("abc{iex:4<%d<=5}") != nil, "Expression should be created")
}
func testThatRegexExpressionShouldBeCreated() {
XCTAssertTrue(Expression.expressionFromString("abc{exp:.*}") != nil, "Expression should be created")
}
func testThatExpressionCannotBeCreated() {
XCTAssertTrue(Expression.expressionFromString("abc") == nil, "There is no expression here")
}
func testThatExpressionCannotBeFound() {
XCTAssertFalse(Expression.parseExpressionPattern("{abc}") == nil, "Expression should not be found")
}
func testThatExpressionCanBeFound() {
XCTAssertTrue(Expression.parseExpressionPattern("{ie:%d>2}") != nil, "Expression should be found")
}
}
| mit | 76957bce42dd6f1a9ec28b29e46764d4 | 32.315789 | 113 | 0.703791 | 4.741573 | false | true | false | false |
boolkybear/SWCraftMU-BowlingKata-160527 | SWCraftMu-KataBowling-160527/SWCraftMu-KataBowling-160527Tests/SWCraftMu-KataBowling-160527-strikes.swift | 1 | 2050 | //
// SWCraftMu-KataBowling-160527-strikes.swift
// SWCraftMu-KataBowling-160527
//
// Created by Jose on 29/5/16.
// Copyright © 2016 ByBDesigns. All rights reserved.
//
import XCTest
@testable import SWCraftMu_KataBowling_160527
class SWCraftMu_KataBowling_160527_strikes: 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 testExample() {
// // This is an example of a functional test case.
// // Use XCTAssert and related functions to verify your tests produce the correct results.
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measureBlock {
// // Put the code you want to measure the time of here.
// }
// }
func testAllStrikes() {
let counter = BowlingCounter("XXXXXXXXXXXX")
XCTAssert(counter.score == 30*10)
}
func testOnlyFirstStrike() {
let counter = BowlingCounter("X------------------")
XCTAssert(counter.score == 10)
}
func testRandomStrikesAndRolls() {
let counter = BowlingCounter("X12X34X54X32X1-")
XCTAssert(counter.score == 10 + 1 + 2 +
1 + 2 +
10 + 3 + 4 +
3 + 4 +
10 + 5 + 4 +
5 + 4 +
10 + 3 + 2 +
3 + 2 +
10 + 1 +
1)
}
func testEndsWithStrikeAndRoll() {
let counter = BowlingCounter("XXXXXXXXXX12")
XCTAssert(counter.score == (10 + 10 + 10) * 8 +
(10 + 10 + 1) +
(10 + 1 + 2))
}
func testEndsWithStrikes() {
let counter = BowlingCounter("------------------XXX")
XCTAssert(counter.score == 30)
}
func testEndsWithStrikeAndSpare() {
let counter = BowlingCounter("------------------X-/")
XCTAssert(counter.score == 20)
}
}
| mit | eb3d816364218fc96161f93e7c2bcbd5 | 23.987805 | 111 | 0.587604 | 3.449495 | false | true | false | false |
johnlui/Swift-MMP | Frameworks/Pitaya/Source/Pitaya.swift | 1 | 7349 | // The MIT License (MIT)
// Copyright (c) 2015 JohnLui <[email protected]> https://github.com/johnlui
// 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.
//
// Pitaya.swift
// Pitaya
//
// Created by JohnLui on 15/5/14.
//
import Foundation
/// make your code looks tidier
public typealias Pita = Pitaya
open class Pitaya {
/// if set to true, Pitaya will log all information in a NSURLSession lifecycle
open static var DEBUG = false
var pitayaManager: PitayaManager!
/**
the only init method to fire a HTTP / HTTPS request
- parameter method: the HTTP method you want
- parameter url: the url you want
- parameter timeout: time out setting
- returns: a Pitaya object
*/
open static func build(HTTPMethod method: HTTPMethod, url: String) -> Pitaya {
let p = Pitaya()
p.pitayaManager = PitayaManager.build(method, url: url)
return p
}
open static func build(HTTPMethod method: HTTPMethod, url: String, timeout: Double, execution: Execution = .async) -> Pitaya {
let p = Pitaya()
p.pitayaManager = PitayaManager.build(method, url: url, timeout: timeout, execution: execution)
return p
}
/**
add params to self (Pitaya object)
- parameter params: what params you want to add in the request. Pitaya will do things right whether methed is GET or POST.
- returns: self (Pitaya object)
*/
open func addParams(_ params: [String: Any]) -> Pitaya {
self.pitayaManager.addParams(params)
return self
}
/**
add files to self (Pitaya object), POST only
- parameter params: add some files to request
- returns: self (Pitaya object)
*/
open func addFiles(_ files: [File]) -> Pitaya {
self.pitayaManager.addFiles(files)
return self
}
/**
add a SSL pinning to check whether undering the Man-in-the-middle attack
- parameter data: data of certification file, .cer format
- parameter SSLValidateErrorCallBack: error callback closure
- returns: self (Pitaya object)
*/
open func addSSLPinning(LocalCertData data: Data, SSLValidateErrorCallBack: (()->Void)? = nil) -> Pitaya {
self.pitayaManager.addSSLPinning(LocalCertData: [data], SSLValidateErrorCallBack: SSLValidateErrorCallBack)
return self
}
/**
add a SSL pinning to check whether undering the Man-in-the-middle attack
- parameter LocalCertDataArray: data array of certification file, .cer format
- parameter SSLValidateErrorCallBack: error callback closure
- returns: self (Pitaya object)
*/
open func addSSLPinning(LocalCertDataArray dataArray: [Data], SSLValidateErrorCallBack: (()->Void)? = nil) -> Pitaya {
self.pitayaManager.addSSLPinning(LocalCertData: dataArray, SSLValidateErrorCallBack: SSLValidateErrorCallBack)
return self
}
/**
set a custom HTTP header
- parameter key: HTTP header key
- parameter value: HTTP header value
- returns: self (Pitaya object)
*/
open func setHTTPHeader(Name key: String, Value value: String) -> Pitaya {
self.pitayaManager.setHTTPHeader(Name: key, Value: value)
return self
}
/**
set HTTP body to what you want. This method will discard any other HTTP body you have built.
- parameter string: HTTP body string you want
- parameter isJSON: is JSON or not: will set "Content-Type" of HTTP request to "application/json" or "text/plain;charset=UTF-8"
- returns: self (Pitaya object)
*/
open func setHTTPBodyRaw(_ string: String, isJSON: Bool = false) -> Pitaya {
self.pitayaManager.sethttpBodyRaw(string, isJSON: isJSON)
return self
}
/**
set username and password of HTTP Basic Auth to the HTTP request header
- parameter username: username
- parameter password: password
- returns: self (Pitaya object)
*/
open func setBasicAuth(_ username: String, password: String) -> Pitaya {
self.pitayaManager.setBasicAuth((username, password))
return self
}
/**
add error callback to self (Pitaya object).
this will called only when network error, if we can receive any data from server, responseData() will be fired.
- parameter errorCallback: errorCallback Closure
- returns: self (Pitaya object)
*/
open func onNetworkError(_ errorCallback: @escaping ((_ error: NSError) -> Void)) -> Pitaya {
self.pitayaManager.addErrorCallback(errorCallback)
return self
}
/**
async response the http body in NSData type
- parameter callback: callback Closure
- parameter response: void
*/
open func responseData(_ callback: ((_ data: Data?, _ response: HTTPURLResponse?) -> Void)?) {
self.pitayaManager?.fire(callback)
}
/**
async response the http body in String type
- parameter callback: callback Closure
- parameter response: void
*/
open func responseString(_ callback: ((_ string: String?, _ response: HTTPURLResponse?) -> Void)?) {
self.responseData { (data, response) -> Void in
var string = ""
if let d = data,
let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue) as String? {
string = s
}
callback?(string, response)
}
}
/**
async response the http body in JSON type use JSONNeverDie(https://github.com/johnlui/JSONNeverDie).
- parameter callback: callback Closure
- parameter response: void
*/
open func responseJSON(_ callback: ((_ json: JSONND, _ response: HTTPURLResponse?) -> Void)?) {
self.responseString { (string, response) in
var json = JSONND()
if let s = string {
json = JSONND(string: s)
}
callback?(json, response)
}
}
/**
cancel the request.
- parameter callback: callback Closure
*/
open func cancel(_ callback: (() -> Void)?) {
self.pitayaManager.cancelCallback = callback
self.pitayaManager.task.cancel()
}
}
| mit | 8f8f568459e8c8d7807f1999301aec67 | 33.181395 | 131 | 0.647979 | 4.397965 | false | false | false | false |
rushabh55/NaviTag-iOS | iOS/SwiftExample/AppDelegate.swift | 1 | 5242 |
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate{
var window: UIWindow?
var userName = String()
var lat : Double = Double()
var long : Double = Double()
var locationManager: CLLocationManager!
var myLong: Double = 0.0
var myLat: Double = 0.0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
return true
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
print(error)
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var str: String
switch(status){
case .NotDetermined: str = "NotDetermined"
case .Restricted: str = "Restricted"
case .Denied: str = "Denied"
case .Authorized: str = "Authorized"
case .AuthorizedWhenInUse: str = "AuthorizedWhenInUse"
}
//println("locationManager auth status changed, \(str)")
if( status == .Authorized || status == .AuthorizedWhenInUse ) {
locationManager.startUpdatingLocation()
println("startUpdatingLocation")
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("found \(locations.count) placemarks.")
if( locations.count > 0 ){
let location = locations[0] as CLLocation;
//locationManager.stopUpdatingLocation()
//self.L1 = location
myLong = location.coordinate.latitude
myLat = location.coordinate.longitude
println("location updated, lat:\(location.coordinate.latitude), lon:\(location.coordinate.longitude), stop updating.")
}
}
func update() {
if self.userName != "" {
let url: NSURL = NSURL(string: "http://rushg.me/TreasureHunt/User.php?q=editUser&username=" + self.userName + "&location=" + myLat.description + "," + myLong.description)!
// debugPrint(url)
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
// debugPrint(NSString(data: data, encoding: NSUTF8StringEncoding))
}
}
}
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.
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
}
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.
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
}
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.
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
}
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.
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
println("start \(__FUNCTION__)")
println("end \(__FUNCTION__)")
}
}
| apache-2.0 | dbe1ffd3536047250b6cf7f391062d7a | 43.05042 | 285 | 0.64937 | 5.741512 | false | false | false | false |
MenloHacks/ios-app | Menlo Hacks/Pods/PushNotifications/Sources/PersistenceService.swift | 1 | 2873 | import Foundation
struct PersistenceService: InterestPersistable, UserPersistable {
let service: UserDefaults
private let prefix = Constants.PersistanceService.prefix
func persist(interest: String) -> Bool {
guard !self.interestExists(interest: interest) else {
return false
}
service.set(interest, forKey: self.prefixInterest(interest))
return true
}
func persist(interests: [String]) -> Bool {
guard
let persistedInterests = self.getSubscriptions(),
persistedInterests.sorted().elementsEqual(interests.sorted())
else {
self.removeAllSubscriptions()
for interest in interests {
_ = self.persist(interest: interest)
}
return true
}
return false
}
func setUserId(userId: String) -> Bool {
guard !self.userIdExists(userId: userId) else {
return false
}
service.set(userId, forKey: Constants.PersistanceService.userId)
return true
}
func getUserId() -> String? {
return service.object(forKey: Constants.PersistanceService.userId) as? String
}
func removeUserId() {
service.removeObject(forKey: Constants.PersistanceService.userId)
}
func remove(interest: String) -> Bool {
guard self.interestExists(interest: interest) else {
return false
}
service.removeObject(forKey: self.prefixInterest(interest))
return true
}
func removeAllSubscriptions() {
self.removeFromPersistanceStore(prefix: prefix)
}
func removeAll() {
self.removeFromPersistanceStore(prefix: "com.pusher.sdk")
}
func getSubscriptions() -> [String]? {
return service.dictionaryRepresentation().filter { $0.key.hasPrefix(prefix) }.map { String(describing: ($0.value)) }
}
func persistServerConfirmedInterestsHash(_ hash: String) {
service.set(hash, forKey: Constants.PersistanceService.hashKey)
}
func getServerConfirmedInterestsHash() -> String {
return service.value(forKey: Constants.PersistanceService.hashKey) as? String ?? ""
}
private func interestExists(interest: String) -> Bool {
return service.object(forKey: self.prefixInterest(interest)) != nil
}
private func userIdExists(userId: String) -> Bool {
return service.object(forKey: Constants.PersistanceService.userId) != nil
}
private func prefixInterest(_ interest: String) -> String {
return "\(prefix):\(interest)"
}
private func removeFromPersistanceStore(prefix: String) {
for element in service.dictionaryRepresentation() {
if element.key.hasPrefix(prefix) {
service.removeObject(forKey: element.key)
}
}
}
}
| mit | ec1e9ddfe9135a16be469b9589551d65 | 28.316327 | 124 | 0.636269 | 4.82047 | false | false | false | false |
ahoppen/swift | test/AutoDiff/compiler_crashers_fixed/sr14290-missing-debug-scopes-in-pullback-trampoline.swift | 11 | 1334 | // RUN: %target-build-swift %s
// RUN: %target-swift-frontend -c -g -Xllvm -verify-di-holes=true %s
// rdar://74876596 ([SR-14290]: SIL verification fails when differentiating a function of [[Double]])
import _Differentiation
let values: [[Double]] = [[0, 0], [0, 0]]
let const = 1.12345
let result = add(const, to: values)
@differentiable(reverse)
func add(_ const: Double, to values: [[Double]]) -> [[Double]] {
var result = values
for i in withoutDerivative(at: values.indices) {
for j in withoutDerivative(at: values.indices) {
result.updated(at: i, j, with: values[i][j] + const)
}
}
return result
}
extension Array where Element == [Double] {
@differentiable(reverse)
mutating func updated(at i: Int, _ j: Int, with newValue: Double) {
self[i][j] = newValue
}
@derivative(of: updated)
mutating func vjpUpdated(at i: Int, _ j: Int, with newValue: Double)
-> (value: Void, pullback: (inout TangentVector) -> (Double.TangentVector)) {
self.updated(at: i, j, with: newValue)
func pullback(dSelf: inout TangentVector) -> (Double.TangentVector) {
let dElement = dSelf[i][j]
dSelf.base[i].base[j] = 0
return dElement
}
let value: Void = ()
return (value, pullback)
}
}
| apache-2.0 | 3912fc73b0424270a58dc55dbc0c0143 | 28.644444 | 101 | 0.610195 | 3.538462 | false | false | false | false |
EliNextMobile/detectAppExist | DetectAppExistence/DetectAppExistence/lib/CheckAppExistence.swift | 1 | 3049 | //
// CheckAppExistence.swift
// DetectApplication
//
// Created by Quan Quach on 9/17/15.
// Copyright (c) 2015 Quan Quach. All rights reserved.
//
import UIKit
class CheckAppExistence: NSObject {
//// The static array containing all url schema of INSTALLED application
static var foundedArr:NSMutableArray!
//// The static array containing all url schma of NOT INSTALLED application
static var notFoundedArr:NSMutableArray!
////
static var successDownloadArr: NSMutableArray!
static var notSuccessDownloadArr: NSMutableArray!
//// verify the list of url schema and arrange them into two sub-categories: INSTALLED AND NOT INSTALL application
//// bundleInfos - the input array consists of all unverified url schema of applications. This argument must not be nil
//// Returns a string of result
static func detectRelatedApplicationWithURLSchema(bundleInfos:NSMutableArray!) -> String {
var url:NSURL!
foundedArr = NSMutableArray()
notFoundedArr = NSMutableArray()
successDownloadArr = NSMutableArray()
notSuccessDownloadArr = NSMutableArray()
for (var i = 0;i < bundleInfos.count;++i) {
let bundleInfo = bundleInfos.objectAtIndex(i) as! NSDictionary
let schema = String(format: "%@://", bundleInfo.objectForKey("appScheme") as! String)
url = NSURL(string: schema)
if (UIApplication.sharedApplication().canOpenURL(url)) {
foundedArr.addObject(bundleInfo.objectForKey("appScheme") as! String)
}
else {
notFoundedArr.addObject(bundleInfo.objectForKey("appScheme") as! String)
if ((bundleInfo.objectForKey("image")) == nil) {
let data = NSData(contentsOfURL: NSURL(string: bundleInfo.objectForKey("imageURL") as! String)!)
if (data != nil) {
let dict = NSMutableDictionary(dictionary: bundleInfo)
let image = UIImage(data: data!)
if (image != nil) {
dict.setObject(data!, forKey: "image")
bundleInfos.replaceObjectAtIndex(i, withObject: dict)
successDownloadArr.addObject(dict.objectForKey("appScheme") as! String)
}
else {
notSuccessDownloadArr.addObject(bundleInfo.objectForKey("appScheme") as! String)
}
}
else {
notSuccessDownloadArr.addObject(bundleInfo.objectForKey("appScheme") as! String)
}
}
}
}
let message = NSString(format: "Installed app: %@\rNot installed ap:%@\rSuccessfully download:%@\rNot successfully download:%@", self.foundedArr,self.notFoundedArr,self.successDownloadArr,self.notSuccessDownloadArr)
return message as String
}
}
| mit | f227d9c59f4bdafa5e0bb6b975be739c | 44.507463 | 223 | 0.599213 | 5.132997 | false | false | false | false |
dreamsxin/swift | test/IRGen/module_hash.swift | 9 | 2870 | // RUN: rm -rf %t && mkdir -p %t
// Test with a single output file
// RUN: echo "single-threaded initial" >%t/log
// RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: single-threaded initial
// CHECK: test.o: MD5=[[TEST_MD5:[0-9a-f]+]]
// CHECK-NOT: prev MD5
// RUN: echo "single-threaded same compilation" >>%t/log
// RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: single-threaded same compilation
// CHECK: test.o: MD5=[[TEST_MD5]]
// CHECK: test.o: prev MD5=[[TEST_MD5]] skipping
// RUN: echo "single-threaded file changed" >>%t/log
// RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple2.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: single-threaded file changed
// CHECK: test.o: MD5=[[TEST2_MD5:[0-9a-f]+]]
// CHECK: test.o: prev MD5=[[TEST_MD5]] recompiling
// RUN: echo "single-threaded option changed" >>%t/log
// RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple2.swift -disable-llvm-optzns -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: single-threaded option changed
// CHECK: test.o: MD5=[[TEST3_MD5:[0-9a-f]+]]
// CHECK: test.o: prev MD5=[[TEST2_MD5]] recompiling
// Test with multiple output files
// RUN: echo "multi-threaded initial" >>%t/log
// RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: multi-threaded initial
// CHECK-DAG: test.o: MD5=[[TEST4_MD5:[0-9a-f]+]]
// CHECK-DAG: test.o: prev MD5=[[TEST3_MD5]] recompiling
// CHECK-DAG: simple.o: MD5=[[SIMPLE_MD5:[0-9a-f]+]]
// RUN: echo "multi-threaded same compilation" >>%t/log
// RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: multi-threaded same compilation
// CHECK-DAG: test.o: MD5=[[TEST4_MD5]]
// CHECK-DAG: test.o: prev MD5=[[TEST4_MD5]] skipping
// CHECK-DAG: simple.o: MD5=[[SIMPLE_MD5]]
// CHECK-DAG: simple.o: prev MD5=[[SIMPLE_MD5]] skipping
// RUN: echo "multi-threaded one file changed" >>%t/log
// RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple2.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log
// CHECK-LABEL: multi-threaded one file changed
// CHECK-DAG: test.o: MD5=[[TEST4_MD5]]
// CHECK-DAG: test.o: prev MD5=[[TEST4_MD5]] skipping
// CHECK-DAG: simple.o: MD5=[[SIMPLE2_MD5:[0-9a-f]+]]
// CHECK-DAG: simple.o: prev MD5=[[SIMPLE_MD5]] recompiling
// RUN: FileCheck %s < %t/log
// REQUIRES: asserts
public func test_func1() {
print("Hello")
}
| apache-2.0 | 0d6a24ad93d9c386936c21be71071d16 | 40.594203 | 164 | 0.667596 | 2.633028 | false | true | false | false |
UTBiomedicalInformaticsLab/ProbabilityWheeliOS | Probability Wheel/Controllers/OptionTableViewCell.swift | 1 | 3314 | //
// OptionTableViewCell.swift
// Probability Wheel
//
// Created by Allen Wang on 11/1/15.
// Copyright © 2015 UT Biomedical Informatics Lab. All rights reserved.
//
import UIKit
protocol OptionCellUpdater {
func updateTable()
}
class OptionTableViewCell: UITableViewCell, UITextFieldDelegate {
let maxStringLength = 25
let sharedInfo = SharedInfo.sharedInstance
let activeColor = UIColor(red: 82 / 255 , green: 144 / 255, blue: 252 / 255, alpha: 1)
let inactiveColor = UIColor(red: 111 / 255, green: 113 / 255, blue: 120 / 255, alpha: 1)
@IBOutlet weak var ActiveButton: UIButton!
@IBOutlet weak var UserText: UITextField!
@IBOutlet weak var Percentage: UILabel!
var delegate: OptionCellUpdater?
var option : Option? {
didSet {
updateUI()
}
}
@IBAction func ActivationToggled(sender: UIButton) {
if self.option != nil {
if self.option!.isActive() {
if sharedInfo.activeOptionsCount() <= 2 {
return
}
self.option!.setInactive()
sender.setTitleColor(inactiveColor, forState: UIControlState.Normal)
print("Option \(option!.getIndex()) set inactive")
} else {
self.option!.setActive()
sender.setTitleColor(activeColor, forState: UIControlState.Normal)
print("Option \(option!.getIndex()) set active")
}
delegate?.updateTable()
}
}
@IBAction func UserTextChanged(sender: UITextField) {
if self.option != nil {
let oldText = option!.getText()
option!.setText(sender.text!)
print("Text in Option \(option!.getIndex()) changed from \(oldText) to \(sender.text!)")
delegate?.updateTable()
}
}
// This delegate will limit the text field's input to a number of characters
// as defined in the constant maxStringLength
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool
{
let currentString: NSString = textField.text!
let newString: NSString =
currentString.stringByReplacingCharactersInRange(range, withString: string)
return newString.length <= maxStringLength
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.UserText.endEditing(true)
return false
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.UserText.endEditing(true)
}
func updateUI() {
if let option = self.option {
UserText.delegate = self
UserText?.text = option.getText()
let displayedPercentage = option.getPercentage() * 100
let displayString = String(format: "%.1f", displayedPercentage) + "%"
Percentage?.text = displayString
if (option.isActive()) {
ActiveButton?.backgroundColor = option.getColor()
} else {
ActiveButton?.backgroundColor = inactiveColor
}
}
}
func getOption() -> Option? {
return option
}
}
| mit | c8770fa3144dc895dd4b4fbb2e4bb88a | 31.480392 | 100 | 0.597646 | 5.050305 | false | false | false | false |
icerockdev/IRPDFKit | IRPDFKit/Classes/Search/IRPDFSearchResult.swift | 1 | 2286 | //
// Created by Aleksey Mikhailov on 12/10/16.
// Copyright © 2016 IceRock Development. All rights reserved.
//
import Foundation
public struct IRPDFSearchResultPart: Equatable {
public let startX: Float
public let endX: Float
public let width: Float
public let height: Float
public let transform: [Float]
public init(startX: Float, endX: Float, width: Float, height: Float, transform: [Float]) {
self.startX = startX
self.endX = endX
self.width = width
self.height = height
self.transform = transform
}
}
public struct IRPDFSearchResult: Equatable {
public let page: Int
public let contextString: String
public let queryInContextRange: Range<String.Index>
public let startPosition: Int
public let endPosition: Int
public let parts: [IRPDFSearchResultPart]
public init(page: Int,
contextString: String,
queryInContextRange: Range<String.Index>,
startPosition: Int,
endPosition: Int,
parts: [IRPDFSearchResultPart]) {
self.page = page
self.contextString = contextString
self.queryInContextRange = queryInContextRange
self.startPosition = startPosition
self.endPosition = endPosition
self.parts = parts
}
}
public func ==(lhs: IRPDFSearchResult, rhs: IRPDFSearchResult) -> Bool {
if lhs.page != rhs.page {
return false
}
if lhs.contextString != rhs.contextString {
return false
}
if lhs.queryInContextRange != rhs.queryInContextRange {
return false
}
if lhs.startPosition != rhs.startPosition {
return false
}
if lhs.endPosition != rhs.endPosition {
return false
}
if lhs.parts.count != rhs.parts.count {
return false
}
if lhs.parts.count > 0 {
for i in (0 ... lhs.parts.count - 1) {
if lhs.parts[i] != rhs.parts[i] {
return false
}
}
}
return true
}
public func ==(lhs: IRPDFSearchResultPart, rhs: IRPDFSearchResultPart) -> Bool {
if lhs.startX != rhs.startX {
return false
}
if lhs.endX != rhs.endX {
return false
}
if lhs.width != rhs.width {
return false
}
if lhs.height != rhs.height {
return false
}
if lhs.transform != rhs.transform {
return false
}
return true
}
| mit | 9016131ae43d4599637e1fd5504164b4 | 20.761905 | 92 | 0.650766 | 4.001751 | false | false | false | false |
satoshi0212/GeoFenceDemo | GeoFenceDemo/Models/GeoFenceItem.swift | 1 | 2518 | //
// GeoFenceItem.swift
// GeoFenceDemo
//
// Created by Satoshi Hattori on 2016/08/08.
// Copyright © 2016年 Satoshi Hattori. All rights reserved.
//
import MapKit
import CoreLocation
let GEO_FENCE_ITEM_LatitudeKey = "latitude"
let GEO_FENCE_ITEM_LongitudeKey = "longitude"
let GEO_FENCE_ITEM_RadiusKey = "radius"
let GEO_FENCE_ITEM_IdentifierKey = "identifier"
let GEO_FENCE_ITEM_NoteKey = "note"
let GEO_FENCE_ITEM_EventTypeKey = "eventType"
enum EventType: Int {
case OnEntry = 0
case OnExit
}
class GeoFenceItem: NSObject, NSCoding, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var radius: CLLocationDistance
var identifier: String
var note: String
var eventType: EventType
var title: String? {
if note.isEmpty {
return "No Note"
}
return note
}
var subtitle: String? {
let eventTypeString = eventType == .OnEntry ? "On Entry" : "On Exit"
return "Radius: \(radius)m - \(eventTypeString)"
}
init(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String, note: String, eventType: EventType) {
self.coordinate = coordinate
self.radius = radius
self.identifier = identifier
self.note = note
self.eventType = eventType
}
// MARK: NSCoding
required init?(coder decoder: NSCoder) {
let latitude = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_LatitudeKey)
let longitude = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_LongitudeKey)
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
radius = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_RadiusKey)
identifier = decoder.decodeObjectForKey(GEO_FENCE_ITEM_IdentifierKey) as! String
note = decoder.decodeObjectForKey(GEO_FENCE_ITEM_NoteKey) as! String
eventType = EventType(rawValue: decoder.decodeIntegerForKey(GEO_FENCE_ITEM_EventTypeKey))!
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeDouble(coordinate.latitude, forKey: GEO_FENCE_ITEM_LatitudeKey)
coder.encodeDouble(coordinate.longitude, forKey: GEO_FENCE_ITEM_LongitudeKey)
coder.encodeDouble(radius, forKey: GEO_FENCE_ITEM_RadiusKey)
coder.encodeObject(identifier, forKey: GEO_FENCE_ITEM_IdentifierKey)
coder.encodeObject(note, forKey: GEO_FENCE_ITEM_NoteKey)
coder.encodeInt(Int32(eventType.rawValue), forKey: GEO_FENCE_ITEM_EventTypeKey)
}
}
| mit | e4f6d890295bda4d19aa61c768dde001 | 33.930556 | 130 | 0.694235 | 4.143328 | false | false | false | false |
tottokotkd/PopUpPickerView | PopUpPickerViewBase.swift | 1 | 2375 | //
// PopUpPickerViewBase.swift
// AITravel-iOS
//
// Created by 村田 佑介 on 2016/06/27.
// Copyright © 2016年 Best10, Inc. All rights reserved.
//
import UIKit
class PopUpPickerViewBase: UIView {
var pickerToolbar: UIToolbar!
var toolbarItems = [UIBarButtonItem]()
lazy var doneButtonItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.endPicker))
}()
// MARK: Initializer
init() {
super.init(frame: CGRect.zero)
initFunc()
}
override init(frame: CGRect) {
super.init(frame: frame)
initFunc()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initFunc()
}
private func initFunc() {
let screenSize = UIScreen.mainScreen().bounds.size
self.backgroundColor = UIColor.blackColor()
pickerToolbar = UIToolbar()
pickerToolbar.translucent = true
self.bounds = CGRectMake(0, 0, screenSize.width, 260)
self.frame = CGRectMake(0, parentViewHeight(), screenSize.width, 260)
pickerToolbar.bounds = CGRectMake(0, 0, screenSize.width, 44)
pickerToolbar.frame = CGRectMake(0, 0, screenSize.width, 44)
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
space.width = 12
let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(PopUpPickerView.cancelPicker))
let flexSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
toolbarItems = [space, cancelItem, flexSpaceItem, doneButtonItem, space]
pickerToolbar.setItems(toolbarItems, animated: false)
self.addSubview(pickerToolbar)
}
// MARK: Actions
func showPicker() {
}
func cancelPicker() {
}
func endPicker() {
}
func hidePicker() {
let screenSize = UIScreen.mainScreen().bounds.size
UIView.animateWithDuration(0.2) {
self.frame = CGRectMake(0, self.parentViewHeight(), screenSize.width, 260.0)
}
}
func parentViewHeight() -> CGFloat {
return superview?.frame.height ?? UIScreen.mainScreen().bounds.size.height
}
}
| unlicense | 4403ab16df460788966bbf5f6f8a6cc4 | 29.307692 | 154 | 0.666244 | 4.468809 | false | false | false | false |
MattLewin/Interview-Prep | Cracking the Coding Interview.playground/Sources/Trees and Graphs.swift | 1 | 5407 | import Foundation
//: # Trees and Graphs
/*: ---
Helper methods and data structures
*/
public class BinaryTreeNode<Element>: CustomStringConvertible {
public var value: Element
public var left: BinaryTreeNode<Element>?
public var right: BinaryTreeNode<Element>?
public var parent: BinaryTreeNode<Element>?
/// An optional function to be executed when "visiting" this node
public var visit: (() -> Void)?
public init(value: Element) {
self.value = value
}
// MARK: CustomStringConvertible
public var description: String {
return String(describing: value)
}
}
// MARK: Binary Tree Traversal
/// Perform in-order traversal of `node`. (i.e., left branch, current node, right branch)
///
/// - Parameters
/// - node: the node to be traversed
/// - debug: whether to print the tree while traversing (defaults to `false`)
/// - indent: the indentation string used in debug output
public func inOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") {
guard let root = node else { return }
inOrderTraversal(root.left, debug: debug, indent: indent + "L")
if debug { print("\(indent) \(root.value)") }
if let visitor = root.visit {
visitor()
}
inOrderTraversal(root.right, debug: debug, indent: indent + "R")
}
/// Perform pre-order traversal of `node`. (i.e., current node, left branch, right branch)
///
/// - Parameters
/// - node: the node to be traversed
/// - debug: whether to print the tree while traversing (defaults to `false`)
/// - indent: the indentation string used in debug output
public func preOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") {
guard let root = node else { return }
if debug { print("\(indent) \(root.value)") }
if let visitor = root.visit {
visitor()
}
preOrderTraversal(root.left, debug: debug, indent: indent + "L")
preOrderTraversal(root.right, debug: debug, indent: indent + "R")
}
/// Perform post-order traversal of `node`. (i.e., left branch, right branch, current node)
///
/// - Parameters
/// - node: the node to be traversed
/// - debug: whether to print the tree while traversing (defaults to `false`)
/// - indent: the indentation string used in debug output
public func postOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") {
guard let root = node else { return }
postOrderTraversal(root.left, debug: debug, indent: indent + "L")
postOrderTraversal(root.right, debug: debug, indent: indent + "$")
if debug { print("\(indent) \(root.value)") }
if let visitor = root.visit {
visitor()
}
}
/// Make a complete binary tree from the provided text
///
/// - Parameter string: the text to transform into a binary tree
/// - Returns: the root node of the binary tree
public func makeBinaryTree(from string: String) -> BinaryTreeNode<Character>? {
var rootNode: BinaryTreeNode<Character>?
var nodeQueue = [BinaryTreeNode<Character>]()
func hasBothChildren<T>(_ node: BinaryTreeNode<T>) -> Bool {
return node.left != nil && node.right != nil
}
for char in string
{
let newNode = BinaryTreeNode(value: char)
if rootNode == nil {
rootNode = newNode
}
else {
if nodeQueue.first?.left == nil {
nodeQueue.first?.left = newNode
}
else if nodeQueue.first?.right == nil {
nodeQueue.first?.right = newNode
}
if hasBothChildren(nodeQueue.first!) {
nodeQueue.removeFirst()
}
}
nodeQueue.append(newNode)
}
return rootNode
}
// MARK: -
public class Graph<Element>: CustomStringConvertible {
public var nodes = [GraphNode<Element>]()
// MARK: CustomStringConvertible
public var description: String {
return "*** DESCRIPTION NOT YET IMPLEMENTED ***"
}
}
public class GraphNode<Element>: CustomStringConvertible {
public var value: Element
public var adjacent = [GraphNode<Element>]()
public var visit: (() -> Void)?
public var visited = false
public init(value: Element) {
self.value = value
}
// MARK: CustomStringConvertible
public var description: String {
let elementType = String(describing: Element.self)
return "GraphNode<\(elementType)> { value:\(value), adjacent nodes:\(adjacent.count) }"
}
}
// MARK: Graph Search / Traversal
public func depthFirstSearch<T>(_ root: GraphNode<T>?) {
guard let root = root else { return }
if let visitor = root.visit {
visitor()
}
root.visited = true
for node in root.adjacent {
if !node.visited {
depthFirstSearch(node)
}
}
}
public func breadthFirstSearch<T>(_ root: GraphNode<T>?) {
guard let root = root else { return }
let toProcess = Queue<GraphNode<T>>()
root.visited = true
toProcess.enqueue(root)
repeat {
let head = try! toProcess.dequeue()
if let visitor = head.visit {
visitor()
}
for node in head.adjacent {
if node.visited == false {
node.visited = true
toProcess.enqueue(node)
}
}
} while !toProcess.isEmpty()
}
| unlicense | ac48884dcee606478c470a7cbf810a7e | 27.457895 | 105 | 0.621972 | 4.244113 | false | false | false | false |
mapsme/omim | iphone/Maps/Core/DeepLink/Strategies/DeepLinkSearchStrategy.swift | 5 | 1076 | class DeepLinkSearchStrategy: IDeepLinkHandlerStrategy{
var deeplinkURL: DeepLinkURL
private var data: DeepLinkSearchData
init(url: DeepLinkURL, data: DeepLinkSearchData) {
self.deeplinkURL = url
self.data = data
}
func execute() {
let kSearchInViewportZoom: Int32 = 16;
// Set viewport only when cll parameter was provided in url.
if (data.centerLat != 0.0 && data.centerLon != 0.0) {
MapViewController.setViewport(data.centerLat, lon: data.centerLon, zoomLevel: kSearchInViewportZoom)
// We need to update viewport for search api manually because of drape engine
// will not notify subscribers when search view is shown.
if (!data.isSearchOnMap) {
data.onViewportChanged(kSearchInViewportZoom)
}
}
if (data.isSearchOnMap) {
MWMMapViewControlsManager.manager()?.searchText(onMap: data.query, forInputLocale: data.locale)
} else {
MWMMapViewControlsManager.manager()?.searchText(data.query, forInputLocale: data.locale)
}
sendStatisticsOnSuccess(type: kStatSearch)
}
}
| apache-2.0 | 41dbdabca1595ee84e2fe0c584300550 | 33.709677 | 106 | 0.715613 | 4.10687 | false | false | false | false |
dbaldwin/DronePan | DronePanTests/PanoramaControllerTests.swift | 1 | 4012 | /*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import XCTest
@testable import DronePan
class PanoramaControllerTests: XCTestCase {
let panoramaController = PanoramaController()
func testPitchesForAircraftMaxPitch0False() {
let value = panoramaController.pitchesForLoop(maxPitch: 0, maxPitchEnabled: false, type: .Aircraft, rowCount: 3)
XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 0 ac false \(value)")
}
func testPitchesForAircraftMaxPitch0True() {
let value = panoramaController.pitchesForLoop(maxPitch: 0, maxPitchEnabled: true, type: .Aircraft, rowCount: 3)
XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 0 ac true \(value)")
}
func testPitchesForAircraftMaxPitch30False() {
let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: false, type: .Aircraft, rowCount: 3)
XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 30 ac false \(value)")
}
func testPitchesForAircraftMaxPitch30True() {
let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Aircraft, rowCount: 3)
XCTAssertEqual([30, -10, -50], value, "Incorrect pitches for max pitch 30 ac true \(value)")
}
func testPitchesForAircraftMaxPitch305Rows() {
let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Aircraft, rowCount: 5)
XCTAssertEqual([30, 6, -18, -42, -66], value, "Incorrect pitches for max pitch 30 row count 5 ac \(value)")
}
func testPitchesForHandheldMaxPitch30() {
let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Handheld, rowCount: 4)
XCTAssertEqual([-60, -30, 0, 30], value, "Incorrect pitches for max pitch 30 handheld \(value)")
}
func testYawAnglesForCount10WithHeading0() {
let value = panoramaController.yawAngles(count: 10, heading: 0)
XCTAssertEqual([36, 72, 108, 144, 180, 216, 252, 288, 324, 360], value, "Incorrect angles for count 10 heading 0 \(value)")
}
func testYawAnglesForCount6WithHeading0() {
let value = panoramaController.yawAngles(count: 6, heading: 0)
XCTAssertEqual([60, 120, 180, 240, 300, 360], value, "Incorrect angles for count 6 heading 0 \(value)")
}
func testYawAnglesForCount10WithHeading84() {
let value = panoramaController.yawAngles(count: 10, heading: 84)
XCTAssertEqual([120, 156, 192, 228, 264, 300, 336, 12, 48, 84], value, "Incorrect angles for count 10 heading 84 \(value)")
}
func testYawAnglesForCount6WithHeadingNeg84() {
let value = panoramaController.yawAngles(count: 6, heading: -84)
XCTAssertEqual([-24, 36, 96, 156, 216, 276], value, "Incorrect angles for count 6 heading -84 \(value)")
}
func testHeadingTo360() {
let value = panoramaController.headingTo360(0)
XCTAssertEqual(0, value, "Incorrect heading for 0 \(value)")
}
func testHeadingTo360Negative() {
let value = panoramaController.headingTo360(-117)
XCTAssertEqual(243, value, "Incorrect heading for -117 \(value)")
}
func testHeadingTo360Positive() {
let value = panoramaController.headingTo360(117)
XCTAssertEqual(117, value, "Incorrect heading for 117 \(value)")
}
}
| gpl-3.0 | 127a7973391bafac2634ec2a1b4a0f1d | 39.12 | 131 | 0.694417 | 4.007992 | false | true | false | false |
ti-gars/BugTracker | macOS/BugTracker_macOS/BugTracker_macOS/GlobalVariables.swift | 1 | 342 | //
// GlobalVariables.swift
// BugTracker_macOS
//
// Created by Charles-Olivier Demers on 2015-09-20.
// Copyright (c) 2015 Charles-Olivier Demers. All rights reserved.
//
import Foundation
var ISSUETYPE_BUG = 0
var ISSUETYPE_FEATURES = 1
var ISSUETYPE_TOTRY = 2
var globalIssue: [Issue] = [Issue]()
var globalUsers: [User] = [User]() | mit | 541fd07d94a8a6cdbb3852e74b4e26e5 | 20.4375 | 67 | 0.707602 | 2.923077 | false | false | false | false |
joerocca/GitHawk | Pods/Tabman/Sources/Tabman/Utilities/ColorUtils.swift | 1 | 1241 | //
// ColorUtils.swift
// Tabman
//
// Created by Merrick Sapsford on 22/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
internal extension UIColor {
static func interpolate(betweenColor colorA: UIColor,
and colorB: UIColor,
percent: CGFloat) -> UIColor? {
var redA: CGFloat = 0.0
var greenA: CGFloat = 0.0
var blueA: CGFloat = 0.0
var alphaA: CGFloat = 0.0
guard colorA.getRed(&redA, green: &greenA, blue: &blueA, alpha: &alphaA) else {
return nil
}
var redB: CGFloat = 0.0
var greenB: CGFloat = 0.0
var blueB: CGFloat = 0.0
var alphaB: CGFloat = 0.0
guard colorB.getRed(&redB, green: &greenB, blue: &blueB, alpha: &alphaB) else {
return nil
}
let iRed = CGFloat(redA + percent * (redB - redA))
let iBlue = CGFloat(blueA + percent * (blueB - blueA))
let iGreen = CGFloat(greenA + percent * (greenB - greenA))
let iAlpha = CGFloat(alphaA + percent * (alphaB - alphaA))
return UIColor(red: iRed, green: iGreen, blue: iBlue, alpha: iAlpha)
}
}
| mit | d4e4e89eb4cfda7e9de820601819e536 | 30.794872 | 87 | 0.555645 | 3.746224 | false | false | false | false |
prebid/prebid-mobile-ios | InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/MAX/PrebidMAXInterstitialController.swift | 1 | 7821 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import AppLovinSDK
import PrebidMobile
import PrebidMobileMAXAdapters
class PrebidMAXInterstitialController: NSObject, AdaptedController, PrebidConfigurableController {
var prebidConfigId: String = ""
var storedAuctionResponse = ""
var maxAdUnitId = ""
var adFormats: Set<AdFormat>?
private var adUnit: MediationInterstitialAdUnit?
private var mediationDelegate: MAXMediationInterstitialUtils?
private var interstitial: MAInterstitialAd?
private weak var adapterViewController: AdapterViewController?
private let fetchDemandFailedButton = EventReportContainer()
private let didLoadAdButton = EventReportContainer()
private let didFailToLoadAdForAdUnitIdentifierButton = EventReportContainer()
private let didFailToDisplayButton = EventReportContainer()
private let didDisplayAdButton = EventReportContainer()
private let didHideAdButton = EventReportContainer()
private let didClickAdButton = EventReportContainer()
private let configIdLabel = UILabel()
// Custom video configuarion
var maxDuration: Int?
var closeButtonArea: Double?
var closeButtonPosition: Position?
var skipButtonArea: Double?
var skipButtonPosition: Position?
var skipDelay: Double?
// MARK: - AdaptedController
required init(rootController: AdapterViewController) {
self.adapterViewController = rootController
super.init()
setupAdapterController()
}
deinit {
Prebid.shared.storedAuctionResponse = nil
}
func configurationController() -> BaseConfigurationController? {
return BaseConfigurationController(controller: self)
}
func loadAd() {
Prebid.shared.storedAuctionResponse = storedAuctionResponse
configIdLabel.isHidden = false
configIdLabel.text = "Config ID: \(prebidConfigId)"
interstitial = MAInterstitialAd(adUnitIdentifier: maxAdUnitId)
interstitial?.delegate = self
mediationDelegate = MAXMediationInterstitialUtils(interstitialAd: interstitial!)
adUnit = MediationInterstitialAdUnit(configId: prebidConfigId,
minSizePercentage: CGSize(width: 30, height: 30),
mediationDelegate: mediationDelegate!)
// Custom video configuarion
if let maxDuration = maxDuration {
adUnit?.videoParameters.maxDuration = SingleContainerInt(integerLiteral: maxDuration)
}
if let closeButtonArea = closeButtonArea {
adUnit?.closeButtonArea = closeButtonArea
}
if let closeButtonPosition = closeButtonPosition {
adUnit?.closeButtonPosition = closeButtonPosition
}
if let skipButtonArea = skipButtonArea {
adUnit?.skipButtonArea = skipButtonArea
}
if let skipButtonPosition = skipButtonPosition {
adUnit?.skipButtonPosition = skipButtonPosition
}
if let skipDelay = skipDelay {
adUnit?.skipDelay = skipDelay
}
if let adFormats = adFormats {
adUnit?.adFormats = adFormats
}
if let adUnitContext = AppConfiguration.shared.adUnitContext {
for dataPair in adUnitContext {
adUnit?.addContextData(dataPair.value, forKey: dataPair.key)
}
}
if let userData = AppConfiguration.shared.userData {
for dataPair in userData {
let appData = PBMORTBContentData()
appData.ext = [dataPair.key: dataPair.value]
adUnit?.addUserData([appData])
}
}
if let appData = AppConfiguration.shared.appContentData {
for dataPair in appData {
let appData = PBMORTBContentData()
appData.ext = [dataPair.key: dataPair.value]
adUnit?.addAppContentData([appData])
}
}
adUnit?.fetchDemand { [weak self] result in
guard let self = self else { return }
if result != .prebidDemandFetchSuccess {
self.fetchDemandFailedButton.isEnabled = true
}
self.interstitial?.load()
}
}
// MARK: - Private Methods
private func setupAdapterController() {
adapterViewController?.bannerView.isHidden = true
setupShowButton()
setupActions()
configIdLabel.isHidden = true
adapterViewController?.actionsView.addArrangedSubview(configIdLabel)
}
private func setupShowButton() {
adapterViewController?.showButton.isEnabled = false
adapterViewController?.showButton.addTarget(self, action:#selector(self.showButtonClicked), for: .touchUpInside)
}
private func setupActions() {
adapterViewController?.setupAction(fetchDemandFailedButton, "fetchDemandFailed called")
adapterViewController?.setupAction(didLoadAdButton, "didLoadAd called")
adapterViewController?.setupAction(didFailToLoadAdForAdUnitIdentifierButton, "didFailToLoadAdForAdUnitIdentifier called")
adapterViewController?.setupAction(didFailToDisplayButton, "didFailToDisplay called")
adapterViewController?.setupAction(didDisplayAdButton, "didDisplayAd called")
adapterViewController?.setupAction(didHideAdButton, "didHideAd called")
adapterViewController?.setupAction(didClickAdButton, "didClickAd called")
}
private func resetEvents() {
fetchDemandFailedButton.isEnabled = false
didLoadAdButton.isEnabled = false
didFailToLoadAdForAdUnitIdentifierButton.isEnabled = false
didFailToDisplayButton.isEnabled = false
didDisplayAdButton.isEnabled = false
didHideAdButton.isEnabled = false
didClickAdButton.isEnabled = false
}
@IBAction func showButtonClicked() {
if let interstitial = interstitial, interstitial.isReady {
adapterViewController?.showButton.isEnabled = false
interstitial.show()
}
}
}
extension PrebidMAXInterstitialController: MAAdDelegate {
func didLoad(_ ad: MAAd) {
resetEvents()
didLoadAdButton.isEnabled = true
adapterViewController?.showButton.isEnabled = true
}
func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
Log.error(error.message)
resetEvents()
didFailToLoadAdForAdUnitIdentifierButton.isEnabled = true
}
func didFail(toDisplay ad: MAAd, withError error: MAError) {
Log.error(error.message)
resetEvents()
didFailToDisplayButton.isEnabled = true
}
func didDisplay(_ ad: MAAd) {
didDisplayAdButton.isEnabled = true
}
func didHide(_ ad: MAAd) {
didHideAdButton.isEnabled = true
}
func didClick(_ ad: MAAd) {
didClickAdButton.isEnabled = true
}
}
| apache-2.0 | cfd2749f04db45c334a9b2b093855817 | 33.866071 | 129 | 0.658643 | 5.503876 | false | true | false | false |
sbooth/SFBAudioEngine | Output/SFBOutputSource.swift | 1 | 3938 | //
// Copyright (c) 2020 - 2021 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
extension OutputSource {
/// Reads bytes from the input
/// - parameter buffer: A buffer to receive data
/// - parameter length: The maximum number of bytes to read
/// - returns: The number of bytes actually read
/// - throws: An `NSError` object if an error occurs
public func read(_ buffer: UnsafeMutableRawPointer, length: Int) throws -> Int {
var bytesRead = 0
try __readBytes(buffer, length: length, bytesRead: &bytesRead)
return bytesRead
}
/// Writes bytes to the output
/// - parameter buffer: A buffer of data to write
/// - parameter length: The maximum number of bytes to write
/// - returns:The number of bytes actually written
/// - throws: An `NSError` object if an error occurs
public func write(_ buffer: UnsafeRawPointer, length: Int) throws -> Int {
var bytesWritten = 0
try __writeBytes(buffer, length: length, bytesWritten: &bytesWritten)
return bytesWritten
}
/// Returns the current offset in the output, in bytes
/// - throws: An `NSError` object if an error occurs
public func offset() throws -> Int {
var offset = 0
try __getOffset(&offset)
return offset
}
/// Returns the length of the output, in bytes
/// - throws: An `NSError` object if an error occurs
public func length() throws -> Int {
var length = 0
try __getLength(&length)
return length
}
/// Writes bytes to the output
/// - parameter data: The data to write
/// - throws: An `NSError` object if an error occurs
public func write(_ data: Data) throws {
let bytesWritten = try data.withUnsafeBytes { (bufptr) -> Int in
guard let baseAddress = bufptr.baseAddress else {
return 0
}
return try write(baseAddress, length: data.count)
}
if bytesWritten != data.count {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(EIO), userInfo: nil)
}
}
/// Writes a binary integer to the output
/// - parameter i: The value to write
/// - throws: An `NSError` object if an error occurs
public func write<T: BinaryInteger>(_ i: T) throws {
let size = MemoryLayout<T>.size
var tmp = i
let bytesWritten = try write(&tmp, length: size)
if bytesWritten != size {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(EIO), userInfo: nil)
}
}
/// Writes a 16-bit integer to the output in big-endian format
/// - parameter ui16: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui16: UInt16) throws {
try write(CFSwapInt16HostToBig(ui16))
}
/// Writes a 32-bit integer to the output in big-endian format
/// - parameter ui32: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui32: UInt32) throws {
try write(CFSwapInt32HostToBig(ui32))
}
/// Writes a 64-bit integer to the output in little-endian format
/// - parameter ui64: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui64: UInt64) throws {
try write(CFSwapInt64HostToBig(ui64))
}
/// Writes a 16-bit integer to the output in big-endian format
/// - parameter ui16: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui16: UInt16) throws {
try write(CFSwapInt16HostToLittle(ui16))
}
/// Writes a 32-bit integer to the output in little-endian format
/// - parameter ui32: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui32: UInt32) throws {
try write(CFSwapInt32HostToLittle(ui32))
}
/// Writes a 64-bit integer to the output in little-endian format
/// - parameter ui64: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui64: UInt64) throws {
try write(CFSwapInt64HostToLittle(ui64))
}
}
| mit | 4335193535676f6233c00cab89f53bd4 | 31.816667 | 81 | 0.700863 | 3.541367 | false | false | false | false |
LYM-mg/MGDS_Swift | MGDS_Swift/MGDS_Swift/Class/Music/Controller/SearchMusicViewController.swift | 1 | 17891 | //
// SearchViewController.swift
// ProductionReport
//
// Created by i-Techsys.com on 17/2/13.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
private let KSearchResultCellID = "KSearchResultCellID"
private let KSearchHistoryCellID = "KSearchHistoryCellID"
private let KHeaderReusableViewID = "KHeaderReusableViewID"
private let KHotSearchCellID = "KHotSearchCellID"
private let KHistoryHeaderViewID = "KHistoryHeaderViewID"
private let KSearchResultHeaderViewID = "KSearchResultHeaderViewID"
class SearchMusicViewController: UIViewController {
fileprivate var hotSearchView: HotSearchView?
// MARK: - 懒加载属性
fileprivate lazy var tableView: UITableView = { [unowned self] in
// let tb = UITableView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: self.view.mg_height))
let tb = UITableView()
tb.backgroundColor = UIColor.white
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
tb.isHidden = true
tb.rowHeight = 60
tb.tableFooterView = UIView()
// tb.estimatedRowHeight = 60 // 设置估算高度
// tb.rowHeight = UITableView.automaticDimension // 告诉tableView我们cell的高度是自动的
tb.keyboardDismissMode = UIScrollView.KeyboardDismissMode.onDrag
tb.register(UINib(nibName: "SearchResultHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: KSearchResultHeaderViewID)
return tb
}()
@objc fileprivate lazy var collectionView: UICollectionView = { [unowned self] in
let fl = UICollectionViewFlowLayout()
fl.minimumLineSpacing = 4
fl.minimumInteritemSpacing = 0
fl.headerReferenceSize = CGSize(width: MGScreenW, height: 35)
fl.itemSize = CGSize(width: MGScreenW, height: 44)
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: fl)
cv.frame = CGRect(x: 0, y: 0, width: MGScreenW, height: self.view.mg_height)
cv.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
cv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cv.dataSource = self
cv.delegate = self
cv.alwaysBounceVertical = true
cv.keyboardDismissMode = UIScrollView.KeyboardDismissMode.interactive
cv.register(SearchHistoryCell.classForCoder(), forCellWithReuseIdentifier: KSearchHistoryCellID)
cv.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: KHotSearchCellID)
cv.register(UINib(nibName: "HistoryHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: KHistoryHeaderViewID)
return cv
}()
fileprivate lazy var SearchMusicVM = SearchMusicViewModel()
let searchBar = UISearchBar()
fileprivate lazy var historyData = [[String: Any]]()
fileprivate lazy var hotSearchArr: [String] = {[unowned self] in
let hotArr = [String]()
return hotArr
}()
fileprivate lazy var songSearchArr = [SearchModel]()
// MARK: - 系统方法
override func viewDidLoad() {
super.viewDidLoad()
setUpMainView()
loadHotSearchData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadHistorySearchData()
}
deinit {
debugPrint("SearchViewController--deinit")
}
}
// MARK: - setUpUI
extension SearchMusicViewController {
fileprivate func setUpMainView() {
view.backgroundColor = UIColor.white
buildSearchBar()
view.addSubview(collectionView)
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(MGNavHeight)
make.bottom.left.right.equalToSuperview()
}
}
fileprivate func buildSearchBar() {
searchBar.frame = CGRect(x: -10, y: 0, width: MGScreenW * 0.9, height: 30)
searchBar.placeholder = "请输入关键字查询歌曲"
searchBar.barTintColor = UIColor.white
searchBar.keyboardType = UIKeyboardType.default
searchBar.delegate = self
navigationItem.titleView = searchBar
for view in searchBar.subviews {
for subView in view.subviews {
if NSStringFromClass(subView.classForCoder) == "UINavigationButton" {
let btn = subView as? UIButton
btn?.setTitle("取消" , for: .normal)
}
if NSStringFromClass(subView.classForCoder) == "UISearchBarTextField" {
let textField = subView as? UITextField
textField?.tintColor = UIColor.gray
}
}
}
}
}
// MARK: - 加载数据
extension SearchMusicViewController {
// 加载历史数据
fileprivate func loadHistorySearchData() {
DispatchQueue.global().async {
if self.historyData.count > 0 {
self.historyData.removeAll()
}
guard var historySearch = SaveTools.mg_getLocalData(key: MGSearchMusicHistorySearchArray) as? [[String : Any]] else { return }
if historySearch.count > 15 {
historySearch.removeLast()
}
self.historyData = historySearch
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
// loadHotSearchData
fileprivate func loadHotSearchData() {
hotSearchArr.removeAll()
let parameters = ["from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json","method":"baidu.ting.search.hot","page_num":"15"]
NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters, succeed: { (response, err) in
guard let result = response as? [String: Any] else { return }
let dictArr = result["result"] as! [[String: Any]]
for dict in dictArr {
self.hotSearchArr.append(dict["word"] as! String)
}
self.collectionView.reloadData()
}) { (err) in
}
}
}
// MARK: - TableView数据源 和 代理
extension SearchMusicViewController: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
if songSearchArr.count == 0 { return 0 }
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if songSearchArr.count == 0 { return 0 }
if section == 0 {
return songSearchArr.first!.songArray.count
}else if section == 1 {
return songSearchArr.first!.albumArray.count
}else if section == 2 {
return songSearchArr.first!.artistArray.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: KSearchResultCellID)
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: KSearchResultCellID)
}
if indexPath.section == 0 {
let model = songSearchArr.first!.songArray[indexPath.row]
cell!.imageView?.image = #imageLiteral(resourceName: "default-user")
cell!.textLabel?.text = model.songname
cell!.detailTextLabel?.text = model.artistname
}else if indexPath.section == 1 {
let model = songSearchArr.first!.albumArray[indexPath.row]
cell!.textLabel?.text = model.albumname
cell!.detailTextLabel?.text = model.artistname
cell!.imageView?.setImageWithURLString(model.artistpic, placeholder: #imageLiteral(resourceName: "default-user"))
}else if indexPath.section == 2 {
let model = songSearchArr.first!.artistArray[indexPath.row]
cell!.textLabel?.text = model.artistname
cell!.imageView?.setImageWithURLString(model.artistpic, placeholder: #imageLiteral(resourceName: "default-user"))
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var text = ""
if indexPath.section == 0 {
let model = songSearchArr.first!.songArray[indexPath.row]
text = model.songname
}else if indexPath.section == 1 {
let model = songSearchArr.first!.albumArray[indexPath.row]
text = model.albumname
}else if indexPath.section == 2 {
let model = songSearchArr.first!.artistArray[indexPath.row]
text = model.artistname
}
pushTosearchResultView(withText: text)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let head = tableView.dequeueReusableHeaderFooterView(withIdentifier: KSearchResultHeaderViewID) as! SearchResultHeaderView
if (section == 0) {
head.titleLabel.text = "歌曲"
} else if(section == 1){
head.titleLabel.text = "专辑"
} else{
head.titleLabel.text = "歌手"
}
return head;
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
}
// MARK: - collectionView数据源 和 代理
extension SearchMusicViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return historyData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KHotSearchCellID, for: indexPath)
if hotSearchArr.count > 0 {
if hotSearchView == nil {
let hotSearchView = HotSearchView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 200), searchTitleText: "热门搜索", searchButtonTitleTexts: hotSearchArr, searchButton: {[unowned self] (btn) in
self.searchBar.text = btn?.currentTitle
self.loadProductsWithKeyword(self.searchBar.text!)
self.tableView.isHidden = false
self.searchBar.resignFirstResponder()
})
cell.addSubview(hotSearchView!)
self.hotSearchView = hotSearchView!
print(hotSearchView!.searchHeight)
// cell.frame = hotSearchView!.frame
// cell.layoutIfNeeded()
// IndexSet(index: 0)
let indexSet = IndexSet(integer: 0)
collectionView.reloadSections(indexSet)
}
}
return cell
}else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KSearchHistoryCellID, for: indexPath) as! SearchHistoryCell
let dict = historyData[indexPath.item]
cell.historyLabel.text = dict["searchFilter"] as! String?
return cell
}
}
// 清除历史搜索记录
@objc fileprivate func clearHistorySearch() {
SaveTools.mg_removeLocalData(key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var dict = historyData[indexPath.item]
searchBar.text = dict["searchFilter"] as? String
self.loadProductsWithKeyword(self.searchBar.text!)
dict = self.historyData.remove(at: indexPath.item)
historyData.insert(dict, at: 0)
SaveTools.mg_SaveToLocal(value: historyData, key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
tableView.isHidden = false
searchBar.resignFirstResponder()
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//如果是headerView
if kind == UICollectionView.elementKindSectionHeader {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KHistoryHeaderViewID, for: indexPath) as! HistoryHeaderView
headerView.titleLabel.text = (indexPath.section == 0) ? "热门搜索" : "历史搜索"
headerView.iconImageView.image = (indexPath.section == 0) ? #imageLiteral(resourceName: "home_header_hot"): #imageLiteral(resourceName: "search_history")
headerView.moreBtn.isHidden = (indexPath.section == 0)
headerView.moreBtnClcikOperation = {
self.clearHistorySearch()
}
return headerView
}
return HistoryHeaderView()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 0 {
return CGSize(width: MGScreenW, height: (self.hotSearchView == nil) ? 200 : (self.hotSearchView?.searchHeight)!)
}
return CGSize(width: MGScreenW, height: 44)
}
//设定页脚的尺寸为0
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: MGScreenW, height: 0)
}
}
// MARK: - UISearchBarDelegate
extension SearchMusicViewController: UISearchBarDelegate,UIScrollViewDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
tableView.isHidden = true
searchBar.showsCancelButton = false
songSearchArr.removeAll()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
tableView.isHidden = false
// 写入到本地
writeHistorySearchToUserDefault(searchFilter: searchBar.text!)
//去除搜索字符串左右和中间的空格
searchBar.text = searchBar.text!.trimmingCharacters(in: CharacterSet.whitespaces)
// 加载数据
loadProductsWithKeyword(searchBar.text!)
tableView.reloadData()
searchBar.resignFirstResponder()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.count == 0 {
// 将tableView隐藏
tableView.isHidden = true
collectionView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
// MARK: - 搜索网络加载数据
extension SearchMusicViewController {
// MARK: - 本地数据缓存
fileprivate func writeHistorySearchToUserDefault(searchFilter: String) {
var historySearchs = SaveTools.mg_getLocalData(key: MGSearchMusicHistorySearchArray) as? [[String: Any]]
if historySearchs != nil {
for dict in historySearchs! {
if dict["searchFilter"] as? String == searchFilter { print("已经缓存") ; return }
}
}else {
historySearchs = [[String: Any]]()
}
var dict = [String: Any]()
dict["searchFilter"] = searchFilter
historySearchs?.insert(dict, at: 0)
SaveTools.mg_SaveToLocal(value: historySearchs!, key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
}
// MARK: - 搜索网络加载数据
fileprivate func loadProductsWithKeyword(_ keyword: String) {
songSearchArr.removeAll()
// 1.显示指示器
self.showHudInViewWithMode(view: self.view, hint: "正在查询数据", mode: .indeterminate, imageName: nil)
let parameters = ["from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json","method":"baidu.ting.search.catalogSug","query":keyword]
NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters, succeed: {[weak self] (response, err) in
self?.hideHud()
guard let result = response as? [String: Any] else { return }
let model = SearchModel(dict: result)
if model.songArray.isEmpty && model.albumArray.isEmpty && model.artistArray.isEmpty {
self?.showHint(hint: "没有查询到结果")
self?.tableView.reloadData()
return
}
self?.songSearchArr.append(model)
self?.tableView.reloadData()
}) { (err) in
self.hideHud()
self.showHint(hint: "请求数据失败", imageName: "sad_face_icon")
}
}
}
// 跳转到下一个控制器搜索🔍
extension SearchMusicViewController {
func pushTosearchResultView(withText text: String) {
let result = MGSearchMusicResultVC()
result.searchText = text
navigationController?.pushViewController(result, animated: false)
}
}
| mit | 313a44901c3fe402ccfb2f4cf718f96c | 40.801909 | 213 | 0.640822 | 4.942156 | false | false | false | false |
wibosco/ASOS-Consumer | ASOSConsumer/Networking/Product/Parsers/Product/ProductParser.swift | 1 | 1083 | //
// ProductParser.swift
// ASOSConsumer
//
// Created by William Boles on 07/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class ProductParser: NSObject {
//MARK: - Product
func parseProduct(productResponse: Dictionary<String, AnyObject>) -> Product {
let product = Product()
product.productID = productResponse["ProductId"] as? Int
product.displayPrice = productResponse["CurrentPrice"] as? String
product.price = productResponse["BasePrice"] as? NSDecimal
product.brand = productResponse["Brand"] as? String
product.displayDescription = productResponse["Description"] as? String
product.title = productResponse["Title"] as? String
let mediaResponse = productResponse["ProductImageUrls"] as! Array<String>
for mediaRemoteURL: String in mediaResponse {
let media = Media()
media.remoteURL = mediaRemoteURL
product.medias.append(media)
}
return product
}
}
| mit | 90570cf217260efd4647c009feff0b1f | 29.055556 | 82 | 0.633087 | 4.745614 | false | false | false | false |
banxi1988/BXiOSUtils | Pod/Classes/QRCodeUtils.swift | 4 | 1075 | //
// QRCodeUtils.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/23.
// Copyright © 2015年 xiyili. All rights reserved.
//
import UIKit
public struct QRCodeUtils {
public static func generateQRCodeImage(_ text:String,imageSize:CGSize=CGSize(width: 200, height: 200)) -> UIImage?{
if let ciImage = generateQRCode(text){
NSLog("QRCode imageSize \(imageSize)")
let scaleX = imageSize.width / ciImage.extent.width
let scaleY = imageSize.height / ciImage.extent.height
let transformedImage = ciImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
return UIImage(ciImage:transformedImage)
}else{
NSLog("generateQRCode Failed \(text)")
}
return nil
}
public static func generateQRCode(_ text:String) -> CIImage?{
let data = text.data(using: String.Encoding.isoLatin1, allowLossyConversion: true)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
return filter?.outputImage
}
}
| mit | 7893896fcdeb9aaea0f6dca92d93fcba | 29.628571 | 117 | 0.702425 | 4.203922 | false | false | false | false |
NelsonLeDuc/JSACollection | JSACollection/Classes/Public/Swift/Mapper.swift | 1 | 2335 | //
// Mapper.swift
// JSACollection
//
// Created by Nelson LeDuc on 12/23/15.
// Copyright © 2015 Nelson LeDuc. All rights reserved.
//
import Foundation
public class ObjectMapper<T: NSObject>: ClassSerializer {
public typealias ObjectType = T
public var allowNonStandard = false {
didSet { _objectMapper.allowNonStandardTypes = allowNonStandard }
}
public var setterBlock: ((KeyValueAccessible, T) -> T?)? {
didSet {
let wrapper: JSACObjectMapperObjectSetterBlock?
if let setter = setterBlock {
wrapper = { (dict, object) in
guard let model = object as? T, let dict = dict else { return nil }
return setter(dict, model)
}
} else {
wrapper = nil
}
_objectMapper.setterBlock = wrapper
}
}
public var dateFormatter: NSDateFormatter? {
didSet { _objectMapper.dateFormatter = dateFormatter }
}
public var customKeyDictionary: [String : String]? {
didSet { _objectMapper.setCustomKeyDictionary(customKeyDictionary) }
}
public init(_ type: T.Type) {
}
public func addSetter(name: String, setterBlock: (AnyObject, T) -> Void) -> Self {
//Work around for compiler crash
let wrapper: JSACObjectMapperPropertySetterBlock = { (value, object) in
if let value = value, let object = object as? T {
setterBlock(value, object)
}
}
_objectMapper.addSetterForPropertyWithName(name, withBlock: wrapper)
return self
}
public func addSubMapper<S: NSObject>(name: String, mapper: ObjectMapper<S>) -> Self {
_objectMapper.addSubObjectMapper(mapper._objectMapper, forPropertyName: name)
return self
}
// MARK: ClassSerializer
public func listOfKeys() -> [String] {
return _objectMapper.listOfKeys() as? [String] ?? []
}
public func object(dictionary: KeyValueAccessible, serializer: JSACCollectionSerializer) -> ObjectType? {
let object = _objectMapper.objectForDictionary(dictionary, forCollectionSerializer: serializer) as? ObjectType
return object
}
internal let _objectMapper = JSACObjectMapper(forClass: T.self)
}
| mit | b4cddc0ab4486adcff1095491104458e | 32.826087 | 118 | 0.618252 | 4.724696 | false | false | false | false |
Yalantis/PixPic | PixPic/Classes/Services/ErrorHandler.swift | 1 | 2292 | //
// ErrorHandler.swift
// PixPic
//
// Created by anna on 1/21/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import Foundation
class ErrorHandler {
static func handle(error: NSError) {
var message: String
let errorCode = error.code
if error.domain == FBSDKErrorDomain {
switch errorCode {
case FBSDKErrorCode.NetworkErrorCode.rawValue:
message = "The request failed due to a network error"
case FBSDKErrorCode.UnknownErrorCode.rawValue:
message = "The error code for unknown errors"
default:
message = error.localizedDescription
break
}
} else if error.domain == NSURLErrorDomain {
switch (error.domain, error.code) {
case (NSURLErrorDomain, NSURLErrorCancelled):
return
case (NSURLErrorDomain, NSURLErrorCannotFindHost),
(NSURLErrorDomain, NSURLErrorDNSLookupFailed),
(NSURLErrorDomain, NSURLErrorCannotConnectToHost),
(NSURLErrorDomain, NSURLErrorNetworkConnectionLost),
(NSURLErrorDomain, NSURLErrorNotConnectedToInternet):
message = "The Internet connection appears to be offline"
default:
message = error.localizedDescription
}
} else if error.domain == PFParseErrorDomain {
switch errorCode {
case PFErrorCode.ErrorConnectionFailed.rawValue:
message = "Connection is failed"
case PFErrorCode.ErrorFacebookIdMissing.rawValue:
message = "Facebook id is missed in request"
case PFErrorCode.ErrorObjectNotFound.rawValue:
message = "Object Not Found"
case PFErrorCode.ErrorFacebookInvalidSession.rawValue:
message = "Facebook session is invalid"
default:
message = error.localizedDescription
break
}
} else if error.domain == NSBundle.mainBundle().bundleIdentifier {
message = error.localizedDescription
}
message = error.localizedDescription
AlertManager.sharedInstance.showSimpleAlert(message)
}
}
| mit | e7605370d542fe4336b144837dcbe8c7 | 30.819444 | 74 | 0.606722 | 5.981723 | false | false | false | false |
JornWu/ZhiBo_Swift | ZhiBo_Swift/Class/BaseVC/LiveRoom/LiveRoomViewController.swift | 1 | 9884 | //
// LiveRoomViewController.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/4/26.
// Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import Result
protocol LiveRoomViewControllerDelegate {
///
/// 这是LiveRoomViewController必须实现的三个方法
///
///
/// 给直播控制器传入数据
///
func setRoomDatas(withDataAr dataAr: [AnyObject])
///
/// 设置当前的直播间
///
func setCurrentRoomIndex(index: Int)
///
/// 打开要进入的直播间
///
func openCurrentRoom()
}
private let instance = LiveRoomViewController()
final class LiveRoomViewController:
UIViewController,
LiveRoomViewControllerDelegate,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UIScrollViewDelegate {
///---------------------------------------------------
/// Singleton
///
///
/// 单例的实现
/// static let shareLiveRoomViewController = LiveRoomViewController()
///
/// static var shareLiveRoomViewController: LiveRoomViewController {
/// struct Singleton {
/// static var instance = LiveRoomViewController()
/// }
/// return Singleton.instance
/// }
///
final class var shareLiveRoomViewController: LiveRoomViewController {
return instance
}
///
/// 私有化构造方法,避免外部调用
///
private init() {
super.init(nibName: nil, bundle: nil)
}
///
/// 私有化构造方法,避免外部调用
///
private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
///
/// 私有化构造方法,避免外部调用
///
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
///---------------------------------------------------
/// property
///
///
/// 直播间数据
///
private lazy var roomDataAr: [LiveRoomModel] = {
return [LiveRoomModel]()
}()
///
/// 直播间列表
///
private var roomCollectionView: UICollectionView!
///
/// 直播间(播放视图)
///
private lazy var liveRoomView: LiveRoomView = {
return LiveRoomView.shareLiveRoomView
}()
///
/// 当前房间(用于定位初始化进入的直播间)
///
public var currentRoomIndex: Int = 0
///
/// 当前直播间数据模型(信号)
///
public lazy var currentRoomModeSignalPipe: (output: Signal<LiveRoomModel, NoError>, input: Observer<LiveRoomModel, NoError>) = {
return Signal<LiveRoomModel, NoError>.pipe()
}()
///
/// ViewModel
///
private lazy var liveRoomViewControllerViewModel: LiveRoomViewControllerViewModel = {
return LiveRoomViewControllerViewModel()
}()
///---------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
}
///
/// 退出直播列表
///
override func viewWillDisappear(_ animated: Bool) {
liveRoomView.stop()
currentRoomIndex = 0
}
///
/// 进入点击的直播间
///
override func viewDidAppear(_ animated: Bool) {
openCurrentRoom()
}
///---------------------------------------------------
/// LiveRoomViewControllerDelegate
///
public func setRoomDatas(withDataAr dataAr: [AnyObject]) {
self.roomDataAr.removeAll()
for item in dataAr {
self.roomDataAr.append(LiveRoomModel.modelWith(item))
}
if roomCollectionView != nil {
roomCollectionView.reloadData()
}
else {
self.setupCollectionView()
}
}
public func setCurrentRoomIndex(index: Int) {
currentRoomIndex = index
}
internal func openCurrentRoom() {
if self.roomCollectionView != nil {
self.roomCollectionView.contentOffset = CGPoint(x: 0, y: Int(self.view.frame.height) * currentRoomIndex)
///
/// 这种方法返回的cell回空,不好使
///
/// let roomCell = roomCollectionView.cellForItem(at: IndexPath(row: currentRoomIndex,
/// section: 0))
/// if let cell = roomCell {
/// cell.contentView.addSubview(self.liveRoomView)
/// self.liveRoomView.snp.makeConstraints { (make) in
/// make.edges.height.equalToSuperview()
/// }
/// }
///
let cells = roomCollectionView.visibleCells
if cells.count > 0 {
cells[0].contentView.addSubview(self.liveRoomView)
self.liveRoomView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
print("------cells[0].contentView:", cells[0].contentView)
}
/// 这个方法要放在self.liveRoomView之后,因为self.liveRoomView会调用懒加载
/// 在LiveRoomView.shareLiveRoomView内部中会监听currentRoomModeSignalPipe的信号
/// 否则会漏掉第一次发送的数据
/// ## 如果roomDataAr[currentRoomIndex]是值类型,其实可以使用reactive的KOV来实现,或者监听方法来实现 ##
self.currentRoomModeSignalPipe.input.send(value: self.roomDataAr[currentRoomIndex])
}
}
///---------------------------------------------------------------
/// 构建热门主视图
///
private func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.view.frame.size
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
roomCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
roomCollectionView.dataSource = self
roomCollectionView.delegate = self
roomCollectionView.bounces = false
roomCollectionView.isPagingEnabled = true
roomCollectionView.backgroundColor = UIColor.orange
self.view.addSubview(roomCollectionView)
roomCollectionView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
roomCollectionView.register(LiveRoomCollectionViewCell.self, forCellWithReuseIdentifier: "LiveRoomCell")
NotificationCenter.default
.reactive
.notifications(forName: NSNotification.Name.UIDeviceOrientationDidChange)
.observeValues { (noti) in
self.roomCollectionView.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return roomDataAr.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let dataItem = roomDataAr[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LiveRoomCell",
for: indexPath) as! LiveRoomCollectionViewCell
cell.setupCell(withImageURLString: dataItem.bigpic ?? dataItem.photo ?? "",
flvLinkString: dataItem.flv ?? "")
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.view.frame.size
}
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
let index = Int((collectionView.contentOffset.y + 5) / collectionView.frame.height)
if currentRoomIndex != index {
currentRoomIndex = index
///
/// 从前一个cell中移出
///
self.liveRoomView.removeFromSuperview()
///
/// 如果roomDataAr[currentRoomIndex]是值类型,可以直接调用setter,产生信号
///
self.currentRoomModeSignalPipe.input.send(value: self.roomDataAr[currentRoomIndex])
let cell = roomCollectionView.cellForItem(at: IndexPath(row: currentRoomIndex, section: 0))
cell?.contentView.addSubview(self.liveRoomView)
if cell != nil {
self.liveRoomView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
}
}
}
///---------------------------------------------------
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 9ff8f27f0549f90aac4f14a6f4872c78 | 29.275081 | 132 | 0.566542 | 5.120416 | false | false | false | false |
qutheory/vapor | Tests/VaporTests/PipelineTests.swift | 2 | 5056 | @testable import Vapor
import XCTest
final class PipelineTests: XCTestCase {
func testEchoHandlers() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
request.body.drain { body in
switch body {
case .buffer(let buffer):
return writer.write(.buffer(buffer))
case .error(let error):
return writer.write(.error(error))
case .end:
return writer.write(.end)
}
}
}))
}
let channel = EmbeddedChannel()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n1\r\na\r\n"))
let chunk = try channel.readOutbound(as: ByteBuffer.self)?.string
XCTAssertContains(chunk, "HTTP/1.1 200 OK")
XCTAssertContains(chunk, "connection: keep-alive")
XCTAssertContains(chunk, "transfer-encoding: chunked")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "a")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "1\r\nb\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "b")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "1\r\nc\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "c")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "0\r\n\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "0\r\n\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
}
func testEOFFraming() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
request.body.drain { body in
switch body {
case .buffer(let buffer):
return writer.write(.buffer(buffer))
case .error(let error):
return writer.write(.error(error))
case .end:
return writer.write(.end)
}
}
}))
}
let channel = EmbeddedChannel()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\n\r\n"))
try XCTAssertContains(channel.readOutbound(as: ByteBuffer.self)?.string, "HTTP/1.1 200 OK")
}
func testBadStreamLength() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
writer.write(.buffer(.init(string: "a")), promise: nil)
writer.write(.end, promise: nil)
}, count: 2))
}
let channel = EmbeddedChannel()
try channel.connect(to: .init(unixDomainSocketPath: "/foo")).wait()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
XCTAssertEqual(channel.isActive, true)
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\n\r\n"))
XCTAssertEqual(channel.isActive, false)
try XCTAssertContains(channel.readOutbound(as: ByteBuffer.self)?.string, "HTTP/1.1 200 OK")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "a")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
}
override class func setUp() {
XCTAssert(isLoggingConfigured)
}
}
| mit | 2cc3e3b94cb0c398b6338615fa018f36 | 41.847458 | 123 | 0.597903 | 4.396522 | false | true | false | false |
qiang437587687/Brother | Brother/Brother/MoreOptional.swift | 1 | 1653 | //
// MoreOptional.swift
// Brother
//
// Created by zhang on 15/11/30.
// Copyright © 2015年 zhang. All rights reserved.
//
import Foundation
class MoreOptional {
func test() {
var string : String? = "string"
//下面的这两个是等效的~
var anotherString : String?? = string
var literalOptional : String?? = "string"
var aNil : String? = nil
//下面这两个是不等效的~
var anotherNil : String?? = aNil
var literalNil : String?? = nil
//下面这个是 在lldb 控制台中 打印的信息 fr v -R anotherNil 其中 anotherNil = Some literalNil = None
/*
fr v -R anotherNil
(Swift.Optional<Swift.Optional<Swift.String>>) anotherNil = Some {
Some = None {
Some = {
_core = {
_baseAddress = {
_rawValue = 0x0000000000000000
}
_countAndFlags = {
value = 0
}
_owner = None {
Some = {
instance_type = 0x0000000000000000
}
}
}
}
}
}
fr v -R literalNil
(Swift.Optional<Swift.Optional<Swift.String>>) literalNil = None {
Some = Some {
Some = {
_core = {
_baseAddress = {
_rawValue = 0x0000000000000000
}
_countAndFlags = {
value = 0
}
_owner = None {
Some = {
instance_type = 0x0000000000000000
}
}
}
}
}
}
*/
}
} | mit | 14d6580fc7ef630776f5eb8edf1eb7ee | 18.962025 | 91 | 0.44797 | 4.365651 | false | false | false | false |
mergesort/Anchorman | Sources/Anchorman/Anchorable.swift | 1 | 14081 | import UIKit
/// A protocol for anything that provides a set `NSLayoutAnchor`s found in `UIView` and `UILayoutGuide`.
public protocol Anchorable {
var topAnchor: NSLayoutYAxisAnchor { get }
var bottomAnchor: NSLayoutYAxisAnchor { get }
var leadingAnchor: NSLayoutXAxisAnchor { get }
var trailingAnchor: NSLayoutXAxisAnchor { get }
var leftAnchor: NSLayoutXAxisAnchor { get }
var rightAnchor: NSLayoutXAxisAnchor { get }
var centerXAnchor: NSLayoutXAxisAnchor { get }
var centerYAnchor: NSLayoutYAxisAnchor { get }
var widthAnchor: NSLayoutDimension { get }
var heightAnchor: NSLayoutDimension { get }
}
extension UIView: Anchorable {}
extension UILayoutGuide: Anchorable {}
public extension Anchorable {
/// A function that allows you to add a `SizeAnchor` to an `Anchorable`.
///
/// - Parameters:
/// - sizeAnchor: The `SizeAnchor` we want to add to an `Anchorable`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(size sizeAnchor: SizeAnchor, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> NSLayoutConstraint {
let currentDimension = sizeAnchor.layoutDimensionForAnchorable(anchorable: self)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = currentDimension.constraint(greaterThanOrEqualToConstant: sizeAnchor.constant)
} else if relation == .lessThanOrEqual {
constraint = currentDimension.constraint(lessThanOrEqualToConstant: sizeAnchor.constant)
} else {
constraint = currentDimension.constraint(equalToConstant: sizeAnchor.constant)
}
constraint.priority = sizeAnchor.priority
constraint.isActive = isActive
return constraint
}
/// A function that allows you to add a `[SizeAnchor]` to an `Anchorable`.
///
/// - Parameters:
/// - sizeAnchors: The `[SizeAnchor]` we want to add to an `Anchorable`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `[NSLayoutConstraint]` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(size sizeAnchors: [SizeAnchor] = [ SizeAnchor.width, SizeAnchor.height ], relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> [NSLayoutConstraint] {
return sizeAnchors.map { return self.set(size: $0, relation: relation, isActive: isActive) }
}
}
extension Anchorable {
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - edges: The `EdgeAnchor`s we wish to create `NSLayoutConstraint`s for.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `[NSLayoutConstraint]` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func pin(toAnchorable anchorable: Anchorable, edges: [EdgeAnchor] = EdgeAnchor.allSides, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> [NSLayoutConstraint] {
func addConstraint(edge: EdgeAnchor) -> NSLayoutConstraint? {
guard edges.contains(edge) else {
return nil
}
let constant: CGFloat
let priority: UILayoutPriority
if let index = edges.firstIndex(of: edge) {
let currentEdge = edges[index]
constant = currentEdge.constant
priority = currentEdge.priority
} else {
constant = 0.0
priority = .required
}
let currentAnchor = edge.layoutAnchorForAnchorable(anchorable: self)
let viewAnchor = edge.layoutAnchorForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = currentAnchor.constraint(greaterThanOrEqualTo: viewAnchor, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = currentAnchor.constraint(lessThanOrEqualTo: viewAnchor, constant: constant)
} else {
constraint = currentAnchor.constraint(equalTo: viewAnchor, constant: constant)
}
constraint.priority = priority
return constraint
}
let leadingConstraint = addConstraint(edge: .leading)
let trailingConstraint = addConstraint(edge: .trailing)
let topConstraint = addConstraint(edge: .top)
let bottomConstraint = addConstraint(edge: .bottom)
let centerXConstraint = addConstraint(edge: .centerX)
let centerYConstraint = addConstraint(edge: .centerY)
let widthConstraint = addConstraint(edge: .width)
let heightConstraint = addConstraint(edge: .height)
let viewConstraints = [ leadingConstraint, trailingConstraint, topConstraint, bottomConstraint, centerXConstraint, centerYConstraint, widthConstraint, heightConstraint ].compactMap { $0 }
viewConstraints.forEach { $0.isActive = isActive }
return viewConstraints
}
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - Parameters:
/// - edge: The `EdgeAnchor` of the current `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - toEdge: The `EdgeAnchor` of the `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - constant: The constant for the underlying `NSLayoutConstraint`.
/// - priority: The priority for the underlying `NSLayoutConstraint`. Default argument is `.required`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func pin(edge: EdgeAnchor, toEdge: EdgeAnchor, ofAnchorable anchorable: Anchorable, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0, priority: UILayoutPriority = .required, isActive: Bool = true) -> NSLayoutConstraint {
let fromAnchor = edge.layoutAnchorForAnchorable(anchorable: self)
let toAnchor = toEdge.layoutAnchorForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = fromAnchor.constraint(greaterThanOrEqualTo: toAnchor, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = fromAnchor.constraint(lessThanOrEqualTo: toAnchor, constant: constant)
} else {
constraint = fromAnchor.constraint(equalTo: toAnchor, constant: constant)
}
constraint.priority = priority
constraint.isActive = isActive
return constraint
}
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - sizeAnchor: The `SizeAnchor` of the current `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - toSizeAnchor: The `SizeAnchor` of the `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - multiplier: The multiplier for the underlying `NSLayoutConstraint`.
/// - constant: The constant for the underlying `NSLayoutConstraint`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(relativeSize sizeAnchor: SizeAnchor, toSizeAnchor: SizeAnchor, ofAnchorable anchorable: Anchorable, multiplier: CGFloat, constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> NSLayoutConstraint {
let fromDimension = sizeAnchor.layoutDimensionForAnchorable(anchorable: self)
let toDimension = toSizeAnchor.layoutDimensionForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = fromDimension.constraint(greaterThanOrEqualTo: toDimension, multiplier: multiplier, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = fromDimension.constraint(lessThanOrEqualTo: toDimension, multiplier: multiplier, constant: constant)
} else {
constraint = fromDimension.constraint(equalTo: toDimension, multiplier: multiplier, constant: constant)
}
constraint.priority = sizeAnchor.priority
constraint.isActive = isActive
return constraint
}
}
private extension EdgeAnchor {
func layoutAnchorForAnchorable(anchorable: Anchorable) -> TypedAnchor {
switch self {
case EdgeAnchor.leading:
return .x(anchorable.leadingAnchor)
case EdgeAnchor.trailing:
return .x(anchorable.trailingAnchor)
case EdgeAnchor.top:
return .y(anchorable.topAnchor)
case EdgeAnchor.bottom:
return .y(anchorable.bottomAnchor)
case EdgeAnchor.centerX:
return .x(anchorable.centerXAnchor)
case EdgeAnchor.centerY:
return .y(anchorable.centerYAnchor)
case EdgeAnchor.width:
return .dimension(anchorable.widthAnchor)
case EdgeAnchor.height:
return .dimension(anchorable.heightAnchor)
default:
fatalError("There is an unhandled edge case with edges. Get it? Edge case… 😂")
}
}
}
private extension SizeAnchor {
func layoutDimensionForAnchorable(anchorable: Anchorable) -> NSLayoutDimension {
switch self {
case SizeAnchor.width:
return anchorable.widthAnchor
case SizeAnchor.height:
return anchorable.heightAnchor
default:
fatalError("There is an unhandled size. Have you considered inventing another dimension? 📐")
}
}
}
/// A typed anchor allows for creating only valid constraints along the same axis or dimension.
/// We want to prevent you from being able to pin a `.top` anchor to a `.leading`, since that is
/// an invalid combination.
///
/// - x: Anchors that are typed as `NSLayoutXAxisAnchor`.
/// - y: Anchors that are typed as `NSLayoutYAxisAnchor`.
/// - dimension: Anchors that are typed as `NSLayoutDimension`.
private enum TypedAnchor {
case x(NSLayoutXAxisAnchor)
case y(NSLayoutYAxisAnchor)
case dimension(NSLayoutDimension)
func constraint(equalTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
func constraint(greaterThanOrEqualTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
func constraint(lessThanOrEqualTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
}
| mit | b2591d30980f217e8d014dbea656ff05 | 44.076923 | 247 | 0.654366 | 5.195419 | false | false | false | false |
taaviteska/CoreDataManager | Pod/Classes/Serializers.swift | 1 | 1348 | //
// Serializers.swift
// Pods
//
// Created by Taavi Teska on 12/09/15.
//
//
import CoreData
import SwiftyJSON
public typealias CDMValidator = (_ data:JSON) -> JSON?
open class CDMSerializer<T:NSManagedObject> {
open var identifiers = [String]()
open var forceInsert = false
open var insertMissing = true
open var updateExisting = true
open var deleteMissing = true
open var mapping: [String: CDMAttribute]
public init() {
self.mapping = [String: CDMAttribute]()
}
open func getValidators() -> [CDMValidator] {
return [CDMValidator]()
}
open func getGroupers() -> [NSPredicate] {
return [NSPredicate]()
}
open func addAttributes(_ attributes: JSON, toObject object: NSManagedObject) {
for (key, attribute) in self.mapping {
var newValue: Any?
if attribute.needsContext {
if let context = object.managedObjectContext {
newValue = attribute.valueFrom(attributes, inContext: context)
} else {
fatalError("Object has to have a managed object context")
}
} else {
newValue = attribute.valueFrom(attributes)
}
object.setValue(newValue, forKey: key)
}
}
}
| mit | c0bcd982f6bcf3fcdcf8eadd0f5e2a1a | 23.509091 | 83 | 0.580861 | 4.600683 | false | false | false | false |
ismailbozkurt77/ZendeskClient | ZendeskExercise/Modules/TicketList/Mapper/TicketMapper.swift | 1 | 1045 | //
// TicketMapper.swift
// ZendeskExercise
//
// Created by Ismail on 07/01/2017.
// Copyright © 2017 Zendesk. All rights reserved.
//
import UIKit
class TicketMapper {
private lazy var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
func ticketViewModel(model: Ticket) -> TicketViewModel {
let viewModel = TicketViewModel()
viewModel.status = model.status
viewModel.ticketDescription = model.ticketDescription
viewModel.subject = model.subject
if let ticketId = model.ticketId {
let ticketNumber = NSNumber(value: ticketId)
viewModel.ticketId = numberFormatter.string(from: ticketNumber)
}
return viewModel
}
func ticketViewModelArray(models: [Ticket]) -> [TicketViewModel] {
let viewModels = models.flatMap {
self.ticketViewModel(model: $0)
}
return viewModels
}
}
| mit | 5e2ef49d8582570ce6bcf77355d8e692 | 25.769231 | 75 | 0.630268 | 4.81106 | false | false | false | false |
pinterest/plank | Sources/Core/ObjectiveCDebugExtension.swift | 1 | 4584 | //
// ObjectiveCDebugExtension.swift
// plank
//
// Created by Rahul Malik on 2/28/17.
//
//
import Foundation
extension ObjCModelRenderer {
func renderDebugDescription() -> ObjCIR.Method {
let props = properties.filter { (_, schema) -> Bool in
!schema.schema.isBoolean()
}.map { (param, prop) -> String in
ObjCIR.ifStmt("props.\(dirtyPropertyOption(propertyName: param, className: self.className))") {
let ivarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), \(renderDebugStatement(param, prop.schema))]];"]
}
}.joined(separator: "\n")
let boolProps = properties.filter { (_, schema) -> Bool in
schema.schema.isBoolean()
}.map { (param, _) -> String in
ObjCIR.ifStmt("props.\(dirtyPropertyOption(propertyName: param, className: self.className))") {
let ivarName = "_\(booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: param, className: self.className))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), @(\(ivarName))]];"]
}
}
let printFormat = "\(className) = {\\n%@\\n}".objcLiteral()
return ObjCIR.method("- (NSString *)debugDescription", debug: true) { [
"NSArray<NSString *> *parentDebugDescription = [[super debugDescription] componentsSeparatedByString:\("\\n".objcLiteral())];",
"NSMutableArray *descriptionFields = [NSMutableArray arrayWithCapacity:\(self.properties.count)];",
"[descriptionFields addObject:parentDebugDescription];",
!self.properties.isEmpty ? "struct \(self.dirtyPropertyOptionName) props = _\(self.dirtyPropertiesIVarName);" : "",
props,
] + boolProps + ["return [NSString stringWithFormat:\(printFormat), debugDescriptionForFields(descriptionFields)];"] }
}
}
extension ObjCADTRenderer {
func renderDebugDescription() -> ObjCIR.Method {
let props = properties.map { (param, prop) -> String in
ObjCIR.ifStmt("self.internalType == \(self.renderInternalEnumTypeCase(name: ObjCADTRenderer.objectName(prop.schema)))") {
let ivarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), \(renderDebugStatement(param, prop.schema))]];"]
}
}.joined(separator: "\n")
let printFormat = "\(className) = {\\n%@\\n}".objcLiteral()
return ObjCIR.method("- (NSString *)debugDescription") { [
"NSArray<NSString *> *parentDebugDescription = [[super debugDescription] componentsSeparatedByString:\("\\n".objcLiteral())];",
"NSMutableArray *descriptionFields = [NSMutableArray arrayWithCapacity:\(self.properties.count)];",
"[descriptionFields addObject:parentDebugDescription];",
props,
"return [NSString stringWithFormat:\(printFormat), debugDescriptionForFields(descriptionFields)];",
] }
}
}
extension ObjCFileRenderer {
fileprivate func renderDebugStatement(_ param: String, _ schema: Schema) -> String {
let propIVarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
switch schema {
case .enumT(.string):
return enumToStringMethodName(propertyName: param, className: className) + "(\(propIVarName))"
case .boolean:
return "@(_.\(booleanPropertyOption(propertyName: param, className: className)))"
case .float, .integer:
return "@(\(propIVarName))"
case .enumT(.integer):
return "@(\(propIVarName))"
case .string(format: _):
return propIVarName
case .array(itemType: _):
return propIVarName
case .set(itemType: _):
return propIVarName
case .map(valueType: _):
return propIVarName
case .object:
return propIVarName
case .oneOf(types: _):
return propIVarName
case let .reference(with: ref):
switch ref.force() {
case let .some(.object(schemaRoot)):
return renderDebugStatement(param, .object(schemaRoot))
default:
fatalError("Bad reference found in schema for class: \(className)")
}
}
}
}
| apache-2.0 | 5d8a6aeecabe3d13cd9191213ec04db1 | 47.252632 | 166 | 0.618674 | 4.653807 | false | false | false | false |
vanyaland/Popular-Movies | iOS/PopularMovies/PopularMovies/MoviesCollectionViewDataSource.swift | 1 | 3803 | /**
* Copyright (c) 2016 Ivan Magda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import AlamofireImage
// MARK: MoviesCollectionViewDataSource: NSObject
final class MoviesCollectionViewDataSource: NSObject {
var movies: [Movie]?
var didSelect: ((Movie) -> ())? = { _ in }
fileprivate var currentOrientation: UIDeviceOrientation!
override init() {
super.init()
let device = UIDevice.current
device.beginGeneratingDeviceOrientationNotifications()
let nc = NotificationCenter.default
nc.addObserver(forName: NSNotification.Name("UIDeviceOrientationDidChangeNotification"),
object: device, queue: nil, using: handleOrientationChange)
}
convenience init(_ movies: [Movie]) {
self.init()
self.movies = movies
}
deinit {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
NotificationCenter.default.removeObserver(self)
}
private func handleOrientationChange(_ notification: Notification) {
if let device = notification.object as? UIDevice {
currentOrientation = device.orientation
}
}
}
// MARK: MoviesCollectionViewDataSource: UICollectionViewDataSource
extension MoviesCollectionViewDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: MovieCollectionViewCell.reuseIdentifier,
for: indexPath) as! MovieCollectionViewCell
configure(cell: cell, atIndexPath: indexPath)
return cell
}
private func configure(cell: MovieCollectionViewCell, atIndexPath indexPath: IndexPath) {
let viewModel = MovieCellViewModel(movie: movies![indexPath.row])
cell.configure(with: viewModel)
}
}
// MARK: - MoviesCollectionViewDataSource: UICollectionViewDelegateFlowLayout -
extension MoviesCollectionViewDataSource: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return MovieCellViewModel.sizeForItem(with: currentOrientation,
andRootViewSize: collectionView.bounds.size)
}
}
// MARK: - MoviesCollectionViewDataSource: UICollectionViewDelegate -
extension MoviesCollectionViewDataSource: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelect?(movies![indexPath.row])
}
}
| mit | 75503010f98faec69f9d8c96618e392f | 36.653465 | 158 | 0.750723 | 5.527616 | false | false | false | false |
killerpsyco/Parameter-Calculator-of-Transistor | TFT Performance/CalculatorViewController.swift | 1 | 6741 | //
// CalculatorViewController.swift
// TFT Performance
//
// Created by dyx on 15/7/21.
// Copyright (c) 2015年 dyx. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var sumInMemory: Double = 0.0
var sumSoFar: Double = 0.0
var factorSoFar: Double = 0.0
var pendingAdditiveOperator = ""
var pendingMultiplicativeOperator = ""
var waitingForOperand = true
var displayValue: Double {
set {
let intValue = Int(newValue)
if (Double(intValue) == newValue) {
display.text = "\(intValue)"
} else {
display.text = "\(newValue)"
}
}
get {
return (display.text! as NSString).doubleValue
}
}
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.
}
func calculate(rightOperand: Double, pendingOperator: String) -> Bool {
var result = false
switch pendingOperator {
case "+":
sumSoFar += rightOperand
result = true
case "-":
sumSoFar -= rightOperand
result = true
case "*":
factorSoFar *= rightOperand
result = true
case "/":
if rightOperand != 0.0 {
factorSoFar /= rightOperand
result = true
}
default:
break
}
return result
}
func abortOperation() {
clearAll()
display.text = "####"
}
@IBAction func digitClicked(sender: UIButton) {
let digitValue = sender.currentTitle?.toInt()
if display.text!.toInt() == 0 && digitValue == 0 {
return
}
if waitingForOperand {
display.text = ""
waitingForOperand = false
}
display.text = display.text! + sender.currentTitle!
}
@IBAction func changeSignClicked() {
displayValue *= -1
}
@IBAction func backspaceClicked() {
if waitingForOperand {
return
}
var strValue = display.text!
display.text = dropLast(strValue)
if display.text!.isEmpty {
displayValue = 0.0
waitingForOperand = true
}
}
@IBAction func clear() {
if waitingForOperand {
return
}
displayValue = 0
waitingForOperand = true
}
@IBAction func clearAll() {
sumSoFar = 0.0
factorSoFar = 0.0
pendingAdditiveOperator = ""
pendingMultiplicativeOperator = ""
displayValue = 0.0
waitingForOperand = true
}
@IBAction func clearMemory() {
sumInMemory = 0.0
}
@IBAction func readMemory() {
displayValue = sumInMemory
waitingForOperand = true
}
@IBAction func setMemory() {
equalClicked()
sumInMemory = displayValue
}
@IBAction func addToMemory() {
equalClicked()
sumInMemory += displayValue
}
@IBAction func multiplicativeOperatorClicked(sender: UIButton) {
var clickedOperator = sender.currentTitle!
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
displayValue = factorSoFar
} else {
factorSoFar = operand
}
pendingMultiplicativeOperator = clickedOperator
waitingForOperand = true
}
@IBAction func additiveOperatorClicked(sender: UIButton) {
let clickedOperator = sender.currentTitle!
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
displayValue = factorSoFar
factorSoFar = 0.0
pendingMultiplicativeOperator = ""
}
if !pendingAdditiveOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingAdditiveOperator) {
abortOperation()
return
}
displayValue = sumSoFar
} else {
sumSoFar = operand
}
pendingAdditiveOperator = clickedOperator
waitingForOperand = true
}
@IBAction func unaryOperatorClicked(sender: UIButton) {
let clickedOperator = sender.currentTitle!
var result: Double = 0
if clickedOperator == "Sqrt" {
if displayValue < 0 {
abortOperation()
return
}
result = sqrt(displayValue)
} else if clickedOperator == "x^2" {
result = pow(displayValue, 2)
} else if clickedOperator == "1/x" {
if displayValue == 0 {
abortOperation()
return
}
result = 1.0 / displayValue
}
displayValue = result
waitingForOperand = true
}
@IBAction func equalClicked() {
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
operand = factorSoFar
factorSoFar = 0.0
pendingMultiplicativeOperator = ""
}
if !pendingAdditiveOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingAdditiveOperator) {
abortOperation()
return
}
pendingAdditiveOperator = ""
} else {
sumSoFar = operand
}
displayValue = sumSoFar
sumSoFar = 0.0
waitingForOperand = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| epl-1.0 | 2cd145c4795caae6e30af446155087b0 | 26.618852 | 106 | 0.545778 | 5.478862 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Expand/Extensions/General/UIColor+ysAdd.swift | 1 | 2699 | //
// UIColor+ysAdd.swift
//
// Created by YangShen on 2017/7/19.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
extension UIColor {
class func ysColor(red:CGFloat,green:CGFloat,blue:CGFloat,alpha:CGFloat) -> UIColor {
return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha)
}
/** 16进制转UIColor */
class func ysHexColor(hex: String) -> UIColor {
return proceesHex(hex: hex, alpha: 1)
}
/** 16进制转UIColor */
class func ysHexColorWithAlpha(hex: String, alpha: CGFloat) -> UIColor {
return proceesHex(hex: hex, alpha: alpha)
}
/// 随机色
class func ysRandomColor() -> UIColor {
let r = CGFloat(arc4random_uniform(256))
let g = CGFloat(arc4random_uniform(256))
let b = CGFloat(arc4random_uniform(256))
return ysColor(red: r, green: g, blue: b, alpha: 1)
}
}
// MARK: - 主要逻辑
fileprivate func proceesHex(hex: String, alpha: CGFloat) -> UIColor{
/** 如果传入的字符串为空 */
if hex.isEmpty {
return UIColor.clear
}
/** 传进来的值。 去掉了可能包含的空格、特殊字符, 并且全部转换为大写 */
let set = CharacterSet.whitespacesAndNewlines
var hHex = hex.trimmingCharacters(in: set).uppercased()
/** 如果处理过后的字符串少于6位 */
if hHex.characters.count < 6 {
return UIColor.clear
}
/** 开头是用0x开始的 */
if hHex.hasPrefix("0X") {
hHex = (hHex as NSString).substring(from: 2)
}
/** 开头是以#开头的 */
if hHex.hasPrefix("#") {
hHex = (hHex as NSString).substring(from: 1)
}
/** 开头是以##开始的 */
if hHex.hasPrefix("##") {
hHex = (hHex as NSString).substring(from: 2)
}
/** 截取出来的有效长度是6位, 所以不是6位的直接返回 */
if hHex.characters.count != 6 {
return UIColor.clear
}
/** R G B */
var range = NSMakeRange(0, 2)
/** R */
let rHex = (hHex as NSString).substring(with: range)
/** G */
range.location = 2
let gHex = (hHex as NSString).substring(with: range)
/** B */
range.location = 4
let bHex = (hHex as NSString).substring(with: range)
/** 类型转换 */
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
| mit | 32315aa793a70a1d5826f3da95dbcf2e | 26.355556 | 110 | 0.587734 | 3.527221 | false | false | false | false |
kazmasaurus/SwiftTransforms | SmokeTest/SmokeTest.swift | 1 | 1426 | //
// SmokeTest.swift
// SmokeTest
//
// Created by Zak Remer on 7/19/15.
// Copyright (c) 2015 Zak. All rights reserved.
//
import UIKit
import XCTest
class SmokeTest: XCTestCase {
// This is a smoke test to see if any of this functionality has been included by Apple.
// Every line here represents functionality provided by this library.
// Any line _not_ throwing a build error has been added by Apple and can be removed.
typealias Transform = CGAffineTransform
static let xi = 10
static let yi = 11
typealias S = SmokeTest
let x = CGFloat(S.xi)
let y = CGFloat(S.yi)
let xd = Double(S.xi)
let yd = Double(S.yi)
let xi: Int = S.xi
let yi: Int = S.yi
func testCompilation() {
Transform() == Transform()
Transform.identityTransform
Transform(scalex: x, y: y)
Transform(scalex: xd, y: yd)
Transform(scalex: xi, y: yi)
Transform(translatex: x, y: y)
Transform(translatex: xd, y: yd)
Transform(translatex: xi, y: yi)
Transform(rotate: x)
Transform(rotate: xd)
Transform(rotate: xi)
Transform().translate(x, ty: y)
Transform().translate(xd, ty: yd)
Transform().translate(xi, ty: yi)
Transform().scale(x, sy: y)
Transform().scale(xd, sy: yd)
Transform().scale(xi, sy: yi)
Transform().rotate(x)
Transform().rotate(xd)
Transform().rotate(xi)
Transform().invert()
Transform().inverse
Transform().concat(Transform())
Transform() * Transform()
}
}
| mit | 7205c0055c70bc8f37accfdd424fdd13 | 20.606061 | 88 | 0.676718 | 3.079914 | false | true | false | false |
michaello/Aloha | AlohaGIF/Promise/Promise.swift | 1 | 7256 | //
// Promise.swift
// Promise
//
// Created by Soroush Khanlou on 7/21/16.
//
//
import Foundation
public protocol ExecutionContext {
func execute(_ work: @escaping () -> Void)
}
extension DispatchQueue: ExecutionContext {
public func execute(_ work: @escaping () -> Void) {
self.async(execute: work)
}
}
public final class InvalidatableQueue: ExecutionContext {
private var valid = true
private let queue: DispatchQueue
public init(queue: DispatchQueue = .main) {
self.queue = queue
}
public func invalidate() {
valid = false
}
public func execute(_ work: @escaping () -> Void) {
guard valid else { return }
self.queue.async(execute: work)
}
}
struct Callback<Value> {
let onFulfilled: (Value) -> ()
let onRejected: (Error) -> ()
let queue: ExecutionContext
func callFulfill(_ value: Value) {
queue.execute({
self.onFulfilled(value)
})
}
func callReject(_ error: Error) {
queue.execute({
self.onRejected(error)
})
}
}
enum State<Value>: CustomStringConvertible {
/// The promise has not completed yet.
/// Will transition to either the `fulfilled` or `rejected` state.
case pending
/// The promise now has a value.
/// Will not transition to any other state.
case fulfilled(value: Value)
/// The promise failed with the included error.
/// Will not transition to any other state.
case rejected(error: Error)
var isPending: Bool {
if case .pending = self {
return true
} else {
return false
}
}
var isFulfilled: Bool {
if case .fulfilled = self {
return true
} else {
return false
}
}
var isRejected: Bool {
if case .rejected = self {
return true
} else {
return false
}
}
var value: Value? {
if case let .fulfilled(value) = self {
return value
}
return nil
}
var error: Error? {
if case let .rejected(error) = self {
return error
}
return nil
}
var description: String {
switch self {
case .fulfilled(let value):
return "Fulfilled (\(value))"
case .rejected(let error):
return "Rejected (\(error))"
case .pending:
return "Pending"
}
}
}
public final class Promise<Value> {
private var state: State<Value>
private let lockQueue = DispatchQueue(label: "promise_lock_queue", qos: .userInitiated)
private var callbacks: [Callback<Value>] = []
public init() {
state = .pending
}
public init(value: Value) {
state = .fulfilled(value: value)
}
public init(error: Error) {
state = .rejected(error: error)
}
public convenience init(queue: DispatchQueue = DispatchQueue.global(qos: .userInitiated), work: @escaping (_ fulfill: @escaping (Value) -> (), _ reject: @escaping (Error) -> () ) throws -> ()) {
self.init()
queue.async(execute: {
do {
try work(self.fulfill, self.reject)
} catch let error {
self.reject(error)
}
})
}
/// - note: This one is "flatMap"
@discardableResult
public func then<NewValue>(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) throws -> Promise<NewValue>) -> Promise<NewValue> {
return Promise<NewValue>(work: { fulfill, reject in
self.addCallbacks(
on: queue,
onFulfilled: { value in
do {
try onFulfilled(value).then(fulfill, reject)
} catch let error {
reject(error)
}
},
onRejected: reject
)
})
}
/// - note: This one is "map"
@discardableResult
public func then<NewValue>(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) throws -> NewValue) -> Promise<NewValue> {
return then(on: queue, { (value) -> Promise<NewValue> in
do {
return Promise<NewValue>(value: try onFulfilled(value))
} catch let error {
return Promise<NewValue>(error: error)
}
})
}
@discardableResult
public func then(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) -> (), _ onRejected: @escaping (Error) -> () = { _ in }) -> Promise<Value> {
_ = Promise<Value>(work: { fulfill, reject in
self.addCallbacks(
on: queue,
onFulfilled: { value in
fulfill(value)
onFulfilled(value)
},
onRejected: { error in
reject(error)
onRejected(error)
}
)
})
return self
}
@discardableResult
public func `catch`(on queue: ExecutionContext = DispatchQueue.main, _ onRejected: @escaping (Error) -> ()) -> Promise<Value> {
return then(on: queue, { _ in }, onRejected)
}
public func reject(_ error: Error) {
updateState(.rejected(error: error))
}
public func fulfill(_ value: Value) {
updateState(.fulfilled(value: value))
}
public var isPending: Bool {
return !isFulfilled && !isRejected
}
public var isFulfilled: Bool {
return value != nil
}
public var isRejected: Bool {
return error != nil
}
public var value: Value? {
return lockQueue.sync(execute: {
return self.state.value
})
}
public var error: Error? {
return lockQueue.sync(execute: {
return self.state.error
})
}
private func updateState(_ state: State<Value>) {
guard self.isPending else { return }
lockQueue.sync(execute: {
self.state = state
})
fireCallbacksIfCompleted()
}
private func addCallbacks(on queue: ExecutionContext = DispatchQueue.main, onFulfilled: @escaping (Value) -> (), onRejected: @escaping (Error) -> ()) {
let callback = Callback(onFulfilled: onFulfilled, onRejected: onRejected, queue: queue)
lockQueue.async(execute: {
self.callbacks.append(callback)
})
fireCallbacksIfCompleted()
}
private func fireCallbacksIfCompleted() {
lockQueue.async(execute: {
guard !self.state.isPending else { return }
self.callbacks.forEach { callback in
switch self.state {
case let .fulfilled(value):
callback.callFulfill(value)
case let .rejected(error):
callback.callReject(error)
default:
break
}
}
self.callbacks.removeAll()
})
}
}
| mit | 4e89454c3426983ef3baa09c3fde2338 | 25.578755 | 198 | 0.533765 | 4.773684 | false | false | false | false |
sathishkraj/SwiftLazyLoading | SwiftLazyLoading/ParseOperation.swift | 1 | 4318 | //
// ParseOperation.swift
// SwiftLazyLoading
//
// Copyright (c) 2015 Sathish Kumar
//
// 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
let kIDStr: NSString = "id"
let kNameStr: NSString = "im:name";
let kImageStr: NSString = "im:image";
let kArtistStr: NSString = "im:artist";
let kEntryStr: NSString = "entry";
class ParseOperation: NSOperation , NSXMLParserDelegate {
var errorHandler: ((error: NSError?) -> ())? = nil
var appRecordList: NSArray? = nil
var dataToParse: NSData? = nil
var workingArray: NSMutableArray? = nil
var workingEntry: AppRecord? = nil
var workingPropertyString: NSMutableString? = nil
var elementsToParse: NSArray? = nil
var storingCharacterData: Bool = false
init(data: NSData?) {
super.init()
self.dataToParse = data
self.elementsToParse = NSArray(objects: kIDStr, kNameStr, kImageStr, kArtistStr)
}
override func main() {
self.workingArray = NSMutableArray()
self.workingPropertyString = NSMutableString()
let parser = NSXMLParser(data: self.dataToParse!)
parser.delegate = self
parser.parse()
if !self.cancelled {
self.appRecordList = NSArray(array: self.workingArray!)
}
self.workingArray = nil;
self.workingPropertyString = nil;
self.dataToParse = nil;
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == kEntryStr {
self.workingEntry = AppRecord()
}
self.storingCharacterData = self.elementsToParse!.containsObject(elementName)
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if self.workingEntry != nil {
if self.storingCharacterData
{
let trimmedString: NSString = self.workingPropertyString!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
self.workingPropertyString!.setString("")
if elementName == kIDStr {
self.workingEntry!.appURLString = trimmedString
} else if elementName == kNameStr {
self.workingEntry!.appName = trimmedString
} else if elementName == kImageStr {
self.workingEntry!.imageURLString = trimmedString
} else if elementName == kArtistStr {
self.workingEntry!.artist = trimmedString
}
}
else if elementName == kEntryStr
{
self.workingArray!.addObject(self.workingEntry!)
self.workingEntry = nil;
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if self.storingCharacterData {
self.workingPropertyString!.appendString(string)
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if (self.errorHandler != nil) {
self.errorHandler!(error: parseError)
}
}
}
| mit | 33c6d25ff32c089d4153baa3163e1c95 | 38.254545 | 173 | 0.655628 | 4.835386 | false | false | false | false |
jaredsinclair/sodes-audio-example | Sodes/SodesAudio/ResourceLoaderDelegate.swift | 1 | 24946 | //
// ResourceLoaderDelegate.swift
// SodesAudio
//
// Created by Jared Sinclair on 7/14/16.
//
//
import Foundation
import AVFoundation
import CommonCryptoSwift
import SodesFoundation
import SwiftableFileHandle
protocol ResourceLoaderDelegateDelegate: class {
func resourceLoaderDelegate(_ delegate: ResourceLoaderDelegate, didEncounter error: Error?)
func resourceLoaderDelegate(_ delegate: ResourceLoaderDelegate, didUpdateLoadedByteRanges ranges: [ByteRange])
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate
///-----------------------------------------------------------------------------
/// Custom AVAssetResourceLoaderDelegate which stores downloaded audio data to
/// re-usable scratch files on disk. This class thus allows an audio file to be
/// streamed across multiple app sessions with the least possible amount of
/// redownloaded data.
///
/// ResourceLoaderDelegate does not currently keep data for more than one
/// resource at a time. If the user frequently changes audio sources this class
/// will be of limited benefit. In the future, it might be wise to provide a
/// dynamic maximum number of cached sources, perhaps keeping data for the most
/// recent 3 to 5 sources.
internal class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate {
/// Enough said.
internal enum ErrorStatus {
case none
case error(Error?)
}
// MARK: Internal Properties
/// The ResourceLoaderDelegate's, err..., delegate.
internal weak var delegate: ResourceLoaderDelegateDelegate?
/// The current error status
internal fileprivate(set) var errorStatus: ErrorStatus = .none
// MARK: Private Properties (Immutable)
/// Used to store the URL for the most-recently used audio source.
fileprivate let defaults: UserDefaults
/// The directory where all scratch file subdirectories are stored.
fileprivate let resourcesDirectory: URL
/// A loading scheme used to ensure that the AVAssetResourceLoader routes
/// its requests to this class.
fileprivate let customLoadingScheme: String
/// A serial queue on which AVAssetResourceLoader will call delegate methods.
fileprivate let loaderQueue: DispatchQueue
/// A date formatter used when parsing Last-Modified header values.
fileprivate let formatter = RFC822Formatter()
/// A throttle used to limit how often we save scratch file metadata (byte
/// ranges, cache validation header info) to disk.
fileprivate let byteRangeThrottle = Throttle(
minimumInterval: 1.0,
qualityOfService: .background
)
// MARK: Private Properties (Mutable)
/// The current resource loader. We can't assume that the same one will
/// always be used, so keeping a reference to it here helps us avoid
/// cross-talk between audio sessions.
fileprivate var currentAVAssetResourceLoader: AVAssetResourceLoader?
/// The info for the scratch file for the current session.
fileprivate var scratchFileInfo: ScratchFileInfo? {
didSet {
if let oldValue = oldValue {
if oldValue.resourceUrl != scratchFileInfo?.resourceUrl {
unprepare(oldValue)
}
}
}
}
/// The request wrapper object containg references to all the info needed
/// to process the current AVAssetResourceLoadingRequest.
fileprivate var currentRequest: Request? {
didSet {
// Under conditions that I don't know how to reproduce, AVFoundation
// sometimes fails to cancel previous requests that cover ~90% of
// of the previous. It seems to happen when repeatedly seeking, but
// it could have been programmer error. Either way, in my testing, I
// found that cancelling (by finishing early w/out data) the
// previous request, I can keep the activity limited to a single
// request and vastly improve loading times, especially on poor
// networks.
oldValue?.cancel()
}
}
// MARK: Init/Deinit
/// Designated initializer.
internal init(customLoadingScheme: String, resourcesDirectory: URL, defaults: UserDefaults) {
SodesLog(resourcesDirectory)
self.defaults = defaults
self.resourcesDirectory = resourcesDirectory
self.customLoadingScheme = customLoadingScheme
self.loaderQueue = DispatchQueue(label: "com.SodesAudio.ResourceLoaderDelegate.loaderQueue")
super.init()
// Remove zombie scratch file directories in case of a premature exit
// during a previous session.
if let mostRecentResourceUrl = defaults.mostRecentResourceUrl {
let directoryToKeep = scratchFileDirectory(for: mostRecentResourceUrl).lastPathComponent
if let contents = try? FileManager.default.contentsOfDirectory(atPath: resourcesDirectory.path) {
for directoryName in contents.filter({$0 != directoryToKeep && !$0.hasPrefix(".")}) {
SodesLog("Removing zombie scratch directory at: \(directoryName)")
let url = resourcesDirectory.appendingPathComponent(directoryName, isDirectory: true)
_ = FileManager.default.removeDirectory(url)
}
}
}
}
// MARK: Internal Methods
/// Prepares an AVURLAsset, configuring the resource loader's delegate, etc.
/// This method returns nil if the receiver cannot prepare an asset that it
/// can handle.
internal func prepareAsset(for url: URL) -> AVURLAsset? {
errorStatus = .none
guard url.hasPathExtension("mp3") else {
SodesLog("Bad url: \(url)\nResourceLoaderDelegate only supports urls with an .mp3 path extension.")
return nil
}
guard let redirectUrl = url.convertToRedirectURL(prefix: customLoadingScheme) else {
SodesLog("Bad url: \(url)\nCould not convert the url to a redirect url.")
return nil
}
currentAVAssetResourceLoader = nil
// If there's no scratch file info, that means that playback has not yet
// begun during this app session. A previous session could still have
// its scratchfile data on disk. If the most recent resource url is the
// same as `url`, then leave it as-is so we can re-use the data.
// Otherwise, remove that data from disk.
if scratchFileInfo == nil {
if let previous = defaults.mostRecentResourceUrl, previous != url {
removeFiles(for: previous)
}
}
loaderQueue.sync {
currentRequest = nil
scratchFileInfo = prepareScratchFileInfo(for: url)
}
guard scratchFileInfo != nil else {
assertionFailure("Could not create scratch file info for: \(url)")
defaults.mostRecentResourceUrl = nil
return nil
}
delegate?.resourceLoaderDelegate(self, didUpdateLoadedByteRanges: scratchFileInfo!.loadedByteRanges)
defaults.mostRecentResourceUrl = url
let asset = AVURLAsset(url: redirectUrl)
asset.resourceLoader.setDelegate(self, queue: loaderQueue)
currentAVAssetResourceLoader = asset.resourceLoader
return asset
}
// MARK: Private Methods
/// Convenience method for handling a content info request.
fileprivate func handleContentInfoRequest(for loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
SodesLog("Will attempt to handle content info request.")
guard let infoRequest = loadingRequest.contentInformationRequest else {return false}
guard let redirectURL = loadingRequest.request.url else {return false}
guard let originalURL = redirectURL.convertFromRedirectURL(prefix: customLoadingScheme) else {return false}
guard let scratchFileInfo = self.scratchFileInfo else {return false}
SodesLog("Will handle content info request.")
// Even though we re-use the downloaded bytes from a previous session,
// we should always make a roundtrip for the content info requests so
// that we can use HTTP cache validation header values to see if we need
// to redownload the data. Podcast MP3s can be replaced without changing
// the URL for the episode (adding new commercials to old episodes, etc.)
let request: URLRequest = {
var request = URLRequest(url: originalURL)
if let dataRequest = loadingRequest.dataRequest {
// Nota Bene: Even though the content info request is often
// accompanied by a data request, **do not** invoke the data
// requests `respondWithData()` method as this will put the
// asset loading request into an undefined state. This isn't
// documented anywhere, but beware.
request.setByteRangeHeader(for: dataRequest.byteRange)
}
return request
}()
let task = URLSession.shared.downloadTask(with: request) { (tempUrl, response, error) in
// I'm using strong references to `self` because I don't know if
// AVFoundation could recover if `self` became nil before cancelling
// all active requests. Retaining `self` here is easier than the
// alternatives. Besides, this class has been designed to accompany
// a singleton PlaybackController.
self.loaderQueue.async {
// Bail early if the content info request was cancelled.
guard !loadingRequest.isCancelled else
{
SodesLog("Bailing early because the loading request was cancelled.")
return
}
guard let request = self.currentRequest as? ContentInfoRequest,
loadingRequest === request.loadingRequest else
{
SodesLog("Bailing early because the loading request has changed.")
return
}
guard let delayedScratchFileInfo = self.scratchFileInfo,
delayedScratchFileInfo === scratchFileInfo else
{
SodesLog("Bailing early because the scratch file info has changed.")
return
}
if let response = response, error == nil {
// Check the Etag and Last-Modified header values to see if
// the file has changed since the last cache info was
// fetched (if this is the first time we're seeing this
// file, the existing info will be blank, which is fine). If
// the cached info is no longer valid, wipe the loaded byte
// ranges from the metadata and update the metadata with the
// new Etag/Last-Modified header values.
//
// If the content provider never provides cache validation
// values, this means we will always re-download the data.
//
// Note that we're not removing the bytes from the actual
// scratch file on disk. This may turn out to be a bad idea,
// but for now lets assume that our byte range metadata is
// always up-to-date, and that by resetting the loaded byte
// ranges here we will prevent future subrequests from
// reading byte ranges that have since been invalidated.
// This works because DataRequestLoader will not create any
// scratch file subrequests if the loaded byte ranges are
// empty.
let cacheInfo = response.cacheInfo(using: self.formatter)
if !delayedScratchFileInfo.cacheInfo.isStillValid(comparedTo: cacheInfo) {
delayedScratchFileInfo.cacheInfo = cacheInfo
self.saveUpdatedScratchFileMetaData(immediately: true)
SodesLog("Reset the scratch file meta data since the cache validation values have changed.")
}
SodesLog("Item completed: content request: \(response)")
infoRequest.update(with: response)
loadingRequest.finishLoading()
}
else {
// Do not update the scratch file meta data here since the
// request could have failed for any number of reasons.
// Let's only reset meta data if we receive a successful
// response.
SodesLog("Failed with error: \(error)")
self.finish(loadingRequest, with: error)
}
if self.currentRequest === request {
// Nil-out `currentRequest` since we're done with it, but
// only if the value of self.currentRequest didn't change
// (since we just called `loadingRequest.finishLoading()`.
self.currentRequest = nil
}
}
}
self.currentRequest = ContentInfoRequest(
resourceUrl: originalURL,
loadingRequest: loadingRequest,
infoRequest: infoRequest,
task: task
)
task.resume()
return true
}
/// Convenience method for handling a data request. Uses a DataRequestLoader
/// to load data from either the scratch file or the network, optimizing for
/// the former to prevent unnecessary network usage.
fileprivate func handleDataRequest(for loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
SodesLog("Will attempt to handle data request.")
guard let avDataRequest = loadingRequest.dataRequest else {return false}
guard let redirectURL = loadingRequest.request.url else {return false}
guard let originalURL = redirectURL.convertFromRedirectURL(prefix: customLoadingScheme) else {return false}
guard let scratchFileInfo = scratchFileInfo else {return false}
SodesLog("Can handle this data request.")
let lowerBound = avDataRequest.requestedOffset // e.g. 0, for Range(0..<4)
let length = avDataRequest.requestedLength // e.g. 3, for Range(0..<4)
let upperBound = lowerBound + length // e.g. 4, for Range(0..<4)
let dataRequest: DataRequest = {
let loader = DataRequestLoader(
resourceUrl: originalURL,
requestedRange: (lowerBound..<upperBound),
delegate: self,
callbackQueue: loaderQueue,
scratchFileHandle: scratchFileInfo.fileHandle,
scratchFileRanges: scratchFileInfo.loadedByteRanges
)
return DataRequest(
resourceUrl: originalURL,
loadingRequest: loadingRequest,
dataRequest: avDataRequest,
loader: loader
)
}()
self.currentRequest = dataRequest
dataRequest.loader.start()
return true
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: AVAssetResourceLoaderDelegate
///-----------------------------------------------------------------------------
extension ResourceLoaderDelegate {
/// Initiates a new loading request. This could be either a content info or
/// a data request. This method returns `false` if the request cannot be
/// handled.
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
guard currentAVAssetResourceLoader === resourceLoader else {return false}
if let _ = loadingRequest.contentInformationRequest {
return handleContentInfoRequest(for: loadingRequest)
} else if let _ = loadingRequest.dataRequest {
return handleDataRequest(for: loadingRequest)
} else {
return false
}
}
/// Not used. Throws a fatal error when hit. ResourceLoaderDelegate has not
/// been designed to be used with assets that require authentication.
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool {
fatalError()
}
/// Cancels the current request.
@objc(resourceLoader:didCancelLoadingRequest:) func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
guard let request = currentRequest as? DataRequest else {return}
guard loadingRequest === request.loadingRequest else {return}
currentRequest = nil
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: Scratch File Info Handling
///-----------------------------------------------------------------------------
fileprivate extension ResourceLoaderDelegate {
/// Returns a unique id for `url`.
func identifier(for url: URL) -> String {
return Hash.MD5(url.absoluteString)!
}
/// Returns the desired URL for the scratch file subdirectory for `resourceUrl`.
func scratchFileDirectory(for resourceUrl: URL) -> URL {
let directoryName = identifier(for: resourceUrl)
return resourcesDirectory.appendingPathComponent(directoryName, isDirectory: true)
}
/// Prepares a subdirectory for the scratch file and its metadata, as well
/// as a file handle for reading/writing. This method returns nil if there
/// was an unrecoverable error during setup.
func prepareScratchFileInfo(for resourceUrl: URL) -> ScratchFileInfo? {
let directory = scratchFileDirectory(for: resourceUrl)
let scratchFileUrl = directory.appendingPathComponent("scratch", isDirectory: false)
let metaDataUrl = directory.appendingPathComponent("metadata.xml", isDirectory: false)
guard FileManager.default.createDirectoryAt(directory) else {return nil}
if !FileManager.default.fileExists(atPath: scratchFileUrl.path) {
FileManager.default.createFile(atPath: scratchFileUrl.path, contents: nil)
}
guard let fileHandle = SODSwiftableFileHandle(url: scratchFileUrl) else {return nil}
let (ranges, cacheInfo): ([ByteRange], ScratchFileInfo.CacheInfo)
if let (r,c) = FileManager.default.readRanges(at: metaDataUrl) {
(ranges, cacheInfo) = (r, c)
} else {
(ranges, cacheInfo) = ([], .none)
}
SodesLog("Prepared info using directory:\n\(directory)\ncacheInfo: \(cacheInfo)")
return ScratchFileInfo(
resourceUrl: resourceUrl,
directory: directory,
scratchFileUrl: scratchFileUrl,
metaDataUrl: metaDataUrl,
fileHandle: fileHandle,
cacheInfo: cacheInfo,
loadedByteRanges: ranges
)
}
/// Closes the file handle and removes the scratch file subdirectory.
func unprepare(_ info: ScratchFileInfo) {
info.fileHandle.closeFile()
_ = FileManager.default.removeDirectory(info.directory)
}
/// Removes the scratch file subdirectory for `resourceUrl`, if any.
func removeFiles(for resourceUrl: URL) {
let directory = scratchFileDirectory(for: resourceUrl)
_ = FileManager.default.removeDirectory(directory)
}
/// Updates the loaded byte ranges for the current scratch file info. This
/// is done by combining all contiguous/overlapping ranges. This also saves
/// the result to disk using `throttle`.
func updateLoadedByteRanges(additionalRange: ByteRange) {
guard let info = scratchFileInfo else {return}
info.loadedByteRanges.append(additionalRange)
info.loadedByteRanges = combine(info.loadedByteRanges)
saveUpdatedScratchFileMetaData()
}
/// Convenience method for saving the current scratch file metadata.
///
/// - parameter immediately: Forces the throttle to process the save now.
/// Passing `false` will use the default throttling mechanism.
func saveUpdatedScratchFileMetaData(immediately: Bool = false) {
guard let currentUrl = currentRequest?.resourceUrl else {return}
guard let info = scratchFileInfo else {return}
byteRangeThrottle.enqueue(immediately: immediately) { [weak self] in
guard let this = self else {return}
guard currentUrl == this.currentRequest?.resourceUrl else {return}
guard let delayedInfo = this.scratchFileInfo else {return}
let combinedRanges = combine(info.loadedByteRanges)
_ = FileManager.default.save(
byteRanges: combinedRanges,
cacheInfo: info.cacheInfo,
to: delayedInfo.metaDataUrl
)
this.delegate?.resourceLoaderDelegate(this, didUpdateLoadedByteRanges: combinedRanges)
}
}
func finish(_ loadingRequest: AVAssetResourceLoadingRequest, with error: Error?) {
self.errorStatus = .error(error)
loadingRequest.finishLoading(with: error as? NSError)
DispatchQueue.main.async {
if case .error(_) = self.errorStatus {
self.delegate?.resourceLoaderDelegate(self, didEncounter: error)
}
}
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: DataRequestLoaderDelegate
///-----------------------------------------------------------------------------
extension ResourceLoaderDelegate: DataRequestLoaderDelegate {
/// Updates the loaded byte ranges for the scratch file info, and appends
/// the data to the current data request. This method will only be called
/// after `data` has already been successfully written to the scratch file.
func dataRequestLoader(_ loader: DataRequestLoader, didReceive data: Data, forSubrange subrange: ByteRange) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
updateLoadedByteRanges(additionalRange: subrange)
request.dataRequest.respond(with: data)
}
/// Called with the DataRequestLoader has finished all subrequests.
func dataRequestLoaderDidFinish(_ loader: DataRequestLoader) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
request.loadingRequest.finishLoading()
}
/// Called when the DataRequestLoader encountered an error. It will not
/// proceed with pending subrequests if it encounters an error while
/// handling a given subrequest.
func dataRequestLoader(_ loader: DataRequestLoader, didFailWithError error: Error?) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
finish(request.loadingRequest, with: error)
}
}
///-----------------------------------------------------------------------------
/// UserDefaults: Convenience Methods
///-----------------------------------------------------------------------------
fileprivate let mostRecentResourceUrlKey = "com.sodesaudio.ResourceLoaderDelegate.mostRecentResourceUrl"
fileprivate extension UserDefaults {
/// Stores the URL for the most-recently used audio source.
var mostRecentResourceUrl: URL? {
get {
if let string = self.string(forKey: mostRecentResourceUrlKey) {
return URL(string: string)
} else {
return nil
}
}
set { set(newValue?.absoluteString, forKey: mostRecentResourceUrlKey) }
}
}
| mit | dd0873376d7dd5edfd46f668fb62e67f | 43.152212 | 170 | 0.611641 | 5.665682 | false | false | false | false |
oneCup/MyWeiBo | MyWeiBoo/MyWeiBoo/AppDelegate.swift | 1 | 4768 | //
// AppDelegate.swift
// MyWeiBoo
//
// Created by 李永方 on 15/10/8.
// Copyright © 2015年 李永方. All rights reserved.
//
import UIKit
let YFRootViewControollerSwithNotifacation = "YFRootViewControollerSwithNotifacation"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
SQLiteManager.sharedManager
print(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist"))
//注册一个通知中心
NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: YFRootViewControollerSwithNotifacation, object: nil)
// print(YFUserAcount.sharedAcount)
//设置外观对象,一旦设置全局共享,越早设置越好
setApperance()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defultViewController()
window?.makeKeyAndVisible()
return true
}
//程序结束才会被只执行,不写不会影响程序的执行,因为通知也是一个单例
deinit {
//注销一个通知 - 知识一个习惯
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/// 切换控制器(通过通知实现)
func switchViewController(n:NSNotification) {
print("切换控制器\(n)")
//判断是否为true
let mainVC = n.object as! Bool
print(mainVC)
window?.rootViewController = mainVC ? YFMainController() : YFWelcomViewController()
}
/// 返回默认的控制器
private func defultViewController() -> UIViewController {
//1.判断用户,没有登录则进入主界面
if !YFUserAcount.userLogin {
return YFMainController()
}
//2.判断是否有更新版本,有,则进入新特性界面,没有则进入欢迎界面
return isUpDateVersion() ? YFNewFutureController() : YFWelcomViewController()
}
/// 判断版本号
func isUpDateVersion()->Bool {
//1.获取软件的版本号
let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
//2.获取沙盒文件中的版本号
//2.1设置软件版本的key
let sandBoxVersionkey = "sandBoxVersionkey"
//2.2 从沙盒中获取版本
let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandBoxVersionkey)
//2.3将版本存放在沙盒中
NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandBoxVersionkey)
//3.返回比较结果
return currentVersion > sandBoxVersion
}
//设置外观对象
func setApperance() {
//获取外观单例对象并设置代理
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
}
//MAEK:清除数据库缓存,在用户推出后台会清理缓存
func applicationDidEnterBackground(application: UIApplication) {
YFStatusDAL.clearDateCache()
}
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 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:.
}
}
| mit | 15b0fc525a1cc3a3bd54fea51d8dbc45 | 33.572581 | 285 | 0.685794 | 4.716172 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | App_VolksWagenFinal-/App_VolksWagenFinal-/VWConcesionarioTableViewController.swift | 1 | 3393 | //
// VWConcesionarioTableViewController.swift
// App_VolksWagenFinal_CICE
//
// Created by Formador on 3/10/16.
// Copyright © 2016 icologic. All rights reserved.
//
import UIKit
import Kingfisher
class VWConcesionarioTableViewController: UITableViewController {
//MARK: - VARIABLES LOCALES GLOBALES
var refreshTVC = UIRefreshControl()
var arrayConcesionarios = [VWConcesionariosModel]()
override func viewDidLoad() {
super.viewDidLoad()
refreshTVC.backgroundColor = UIColor(red: 255/255, green: 128/255, blue: 0/255, alpha: 1.0)
refreshTVC.attributedTitle = NSAttributedString(string: CONSTANTES.TEXTO_RECARGA_TABLA)
refreshTVC.addTarget(self, action: Selector(refreshFunction(tableView, endRefreshTVC: refreshTVC)), forControlEvents: .EditingDidEnd)
tableView.addSubview(refreshTVC)
//Aqui alimentamos nuestro array
arrayConcesionarios = VWAPIManager.sharedInstance.getConcesionarioParse()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayConcesionarios.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VWConcesionarioCustomCell
let concesionarioData = arrayConcesionarios[indexPath.row]
cell.myNombreConcesionario.text = concesionarioData.Nombre
cell.myDireccionConcesionario.text = concesionarioData.Ubicacion
cell.myWebConcesionario.text = concesionarioData.Provincia_Nombre
cell.hacerLlamada.setTitle("\(concesionarioData.telefono!)", forState: .Normal)
cell.hacerLlamada.tag = indexPath.row
cell.hacerLlamada.addTarget(self, action: #selector(VWConcesionarioTableViewController.muestraTelefono(_:)), forControlEvents: .TouchUpInside)
cell.myImagenConcesionario.kf_setImageWithURL(NSURL(string: getImagePath(concesionarioData.Imagen!)))
return cell
}
@IBAction func muestraTelefono(sender : UIButton){
let concesionarioData = arrayConcesionarios[sender.tag].telefono
let url = NSURL(string: "tel://\(concesionarioData!)")
UIApplication.sharedApplication().openURL(url!)
print("estoy haciendo una llamada")
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detalleConcesionarioVC = self.storyboard?.instantiateViewControllerWithIdentifier("detalleConcesionarios") as! VWDetalleConcesionarioViewController
detalleConcesionarioVC.arrayConcesionariosData = arrayConcesionarios[indexPath.row]
navigationController?.pushViewController(detalleConcesionarioVC, animated: true)
}
}
| apache-2.0 | c246b76def6ec88d65d5f2f35bfcd954 | 37.11236 | 159 | 0.717866 | 4.422425 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/Rx.playground/Pages/Mathematical_and_Aggregate_Operators.xcplaygroundpage/Contents.swift | 3 | 2598 | /*:
> # IMPORTANT: To use **Rx.playground**:
1. Open **Rx.xcworkspace**.
1. Build the **RxSwift-OSX** scheme (**Product** → **Build**).
1. Open **Rx** playground in the **Project navigator**.
1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**).
----
[Previous](@previous) - [Table of Contents](Table_of_Contents)
*/
import RxSwift
/*:
# Mathematical and Aggregate Operators
Operators that operate on the entire sequence of items emitted by an `Observable`.
## `toArray`
Converts an `Observable` sequence into an array, emits that array as a new single-element `Observable` sequence, and then terminates. [More info](http://reactivex.io/documentation/operators/to.html)

*/
example("toArray") {
let disposeBag = DisposeBag()
Observable.range(start: 1, count: 10)
.toArray()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
}
/*:
----
## `reduce`
Begins with an initial seed value, and then applies an accumulator closure to all elements emitted by an `Observable` sequence, and returns the aggregate result as a single-element `Observable` sequence. [More info](http://reactivex.io/documentation/operators/reduce.html)

*/
example("reduce") {
let disposeBag = DisposeBag()
Observable.of(10, 100, 1000)
.reduce(1, accumulator: +)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `concat`
Joins elements from inner `Observable` sequences of an `Observable` sequence in a sequential manner, waiting for each sequence to terminate successfully before emitting elements from the next sequence. [More info](http://reactivex.io/documentation/operators/concat.html)

*/
example("concat") {
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "🍎")
let subject2 = BehaviorSubject(value: "🐶")
let variable = Variable(subject1)
variable.asObservable()
.concat()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
subject1.onNext("🍐")
subject1.onNext("🍊")
variable.value = subject2
subject2.onNext("I would be ignored")
subject2.onNext("🐱")
subject1.onCompleted()
subject2.onNext("🐭")
}
//: [Next](@next) - [Table of Contents](Table_of_Contents)
| mit | eb607eca976fa57e40c936952bb13881 | 34.75 | 273 | 0.675214 | 4.178571 | false | false | false | false |
akshayg13/Game | Games/ImageModel.swift | 1 | 1949 | //
// ImageModel.swift
// Games
//
// Created by Appinventiv on 21/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import Foundation
import SwiftyJSON
struct ImageModel {
let id : String!
var isFav = false
var comments = 0
var downloads = 0
var favorites = 0
var likes = 0
var views = 0
var pageURL : String = ""
var userImageURL : String = ""
var webformatURL : String = ""
var previewURL : String = ""
init(withJSON json: JSON) {
self.id = json["id"].stringValue
self.comments = json["comments"].intValue
self.downloads = json["downloads"].intValue
self.favorites = json["favorites"].intValue
self.likes = json["likes"].intValue
self.views = json["views"].intValue
self.pageURL = json["pageURL"].stringValue
self.userImageURL = json["userImageURL"].stringValue
self.webformatURL = json["webformatURL"].stringValue
self.previewURL = json["previewURL"].stringValue
}
}
//{
// "imageHeight" : 3122,
// "user" : "jarmoluk",
// "previewWidth" : 150,
// "imageWidth" : 4714,
// "likes" : 29,
// "previewHeight" : 99,
// "webformatHeight" : 423,
// "tags" : "gokart, action, umpteen",
// "type" : "photo",
// "downloads" : 2211,
// "webformatURL" : "https:\/\/pixabay.com\/get\/e835b90f2cfd033ed95c4518b7484096eb7fe1d404b0154992f6c77da5e9b5_640.jpg",
// "views" : 5857,
// "id" : 1080492,
// "favorites" : 28,
// "webformatWidth" : 640,
// "pageURL" : "https:\/\/pixabay.com\/en\/gokart-action-umpteen-motor-speed-1080492\/",
// "previewURL" : "https:\/\/cdn.pixabay.com\/photo\/2015\/12\/07\/10\/24\/gokart-1080492_150.jpg",
// "comments" : 4,
// "user_id" : 143740,
// "userImageURL" : "https:\/\/cdn.pixabay.com\/user\/2015\/04\/13\/12-35-01-432_250x250.jpg"
//}
| mit | 2d011a239a6f48285f73358738807042 | 26.43662 | 124 | 0.584189 | 3.241265 | false | false | false | false |
avaidyam/Parrot | MochaUI/CGSSpace.swift | 1 | 2458 | import AppKit
import Mocha
/// Small Spaces API wrapper.
public final class CGSSpace {
private let identifier: CGSSpaceID
public var windows: Set<NSWindow> = [] {
didSet {
let remove = oldValue.subtracting(self.windows)
let add = self.windows.subtracting(oldValue)
CGSRemoveWindowsFromSpaces(_CGSDefaultConnection(),
remove.map { $0.windowNumber } as NSArray,
[self.identifier])
CGSAddWindowsToSpaces(_CGSDefaultConnection(),
add.map { $0.windowNumber } as NSArray,
[self.identifier])
}
}
/// Initialized `CGSSpace`s *MUST* be de-initialized upon app exit!
public init(level: Int = 0) {
let flag = 0x1 // this value MUST be 1, otherwise, Finder decides to draw desktop icons
self.identifier = CGSSpaceCreate(_CGSDefaultConnection(), flag, nil)
CGSSpaceSetAbsoluteLevel(_CGSDefaultConnection(), self.identifier, level/*400=facetime?*/)
CGSShowSpaces(_CGSDefaultConnection(), [self.identifier])
}
deinit {
CGSHideSpaces(_CGSDefaultConnection(), [self.identifier])
CGSSpaceDestroy(_CGSDefaultConnection(), self.identifier)
}
}
// CGSSpace stuff:
fileprivate typealias CGSConnectionID = UInt
fileprivate typealias CGSSpaceID = UInt64
@_silgen_name("_CGSDefaultConnection")
fileprivate func _CGSDefaultConnection() -> CGSConnectionID
@_silgen_name("CGSSpaceCreate")
fileprivate func CGSSpaceCreate(_ cid: CGSConnectionID, _ unknown: Int, _ options: NSDictionary?) -> CGSSpaceID
@_silgen_name("CGSSpaceDestroy")
fileprivate func CGSSpaceDestroy(_ cid: CGSConnectionID, _ space: CGSSpaceID)
@_silgen_name("CGSSpaceSetAbsoluteLevel")
fileprivate func CGSSpaceSetAbsoluteLevel(_ cid: CGSConnectionID, _ space: CGSSpaceID, _ level: Int)
@_silgen_name("CGSAddWindowsToSpaces")
fileprivate func CGSAddWindowsToSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray)
@_silgen_name("CGSRemoveWindowsFromSpaces")
fileprivate func CGSRemoveWindowsFromSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray)
@_silgen_name("CGSHideSpaces")
fileprivate func CGSHideSpaces(_ cid: CGSConnectionID, _ spaces: NSArray)
@_silgen_name("CGSShowSpaces")
fileprivate func CGSShowSpaces(_ cid: CGSConnectionID, _ spaces: NSArray)
| mpl-2.0 | 409c1e41ce9a9531862c26dc63b1112c | 43.690909 | 111 | 0.679821 | 4.335097 | false | false | false | false |
valentinknabel/StateMachine | Sources/Transition.swift | 1 | 2270 | //
// Transition.swift
// StateMachine
//
// Created by Valentin Knabel on 19.02.15.
// Copyright (c) 2015 Valentin Knabel. All rights reserved.
//
/**
The Transition class represents a transition from a given state to a targeted state.
There are three types of transitions:
1. Absolute Transitions have a source and a target state set.
2. Relative Transitions have only one state set.
3. Nil Transitions have none states set and will be ignored.
*/
public struct Transition<T: Hashable>: Hashable, CustomStringConvertible {
/// Nil transitions will be ignored.
public static var nilTransition: Transition<T> {
return Transition<T>(from: nil, to: nil)
}
/// The source state.
public var from: T?
/// The targeted state.
public var to: T?
/**
Constructs an absolute, relative or nil transition.
- parameter from: The source state.
- parameter to: The target state.
*/
public init(from: T?, to: T?) {
self.from = from
self.to = to
}
/**
All more general transitions include itself except the nil transition.
- returns: All general transitions.
- Generals of an absolute transition is itself and relative transitions.
- Generals of a relative transition is only itself.
- Nil transitions have no generals.
*/
public var generalTransitions: Set<Transition> {
var generals = Set<Transition>([self, Transition(from: from, to: nil), Transition(from: nil, to: to)])
generals.remove(.nilTransition)
return generals
}
public var description: String {
let f = from != nil ? String(describing: from!) : "any"
let t = to != nil ? String(describing: to!) : "any"
return "\(f) -> \(t)"
}
#if swift(>=4.2)
// Synthesized by compiler
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(from)
hasher.combine(to)
}
#else
/// :nodoc:
public var hashValue: Int {
return (from?.hashValue ?? 0) + (to?.hashValue ?? 0)
}
#endif
}
/// :nodoc:
public func == <T>(lhs: Transition<T>, rhs: Transition<T>) -> Bool {
return lhs.from == rhs.from && lhs.to == rhs.to
}
| mit | 449cc5da7ef335058aeb172f96d1ca3a | 27.734177 | 110 | 0.617181 | 4.112319 | false | false | false | false |
steelwheels/Coconut | CoconutData/Source/Value/CNValuePath.swift | 1 | 8580 | /**
* @file CNValuePath.swift
* @brief Define CNValuePath class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public class CNValuePath
{
public enum Element {
case member(String) // member name
case index(Int) // array index to select array element
case keyAndValue(String, CNValue) // key and it's value to select array element
static func isSame(source0 src0: Element, source1 src1: Element) -> Bool {
let result: Bool
switch src0 {
case .member(let memb0):
switch src1 {
case .member(let memb1):
result = memb0 == memb1
case .index(_), .keyAndValue(_, _):
result = false
}
case .index(let idx0):
switch src1 {
case .member(_), .keyAndValue(_, _):
result = false
case .index(let idx1):
result = idx0 == idx1
}
case .keyAndValue(let key0, let val0):
switch src1 {
case .member(_), .index(_):
result = false
case .keyAndValue(let key1, let val1):
if key0 == key1 {
switch CNCompareValue(nativeValue0: val0, nativeValue1: val1){
case .orderedAscending, .orderedDescending:
result = false
case .orderedSame:
result = true
}
} else {
result = false
}
}
}
return result
}
}
private struct Elements {
var firstIdent: String?
var elements: Array<Element>
public init(firstIdentifier fidt: String?, elements elms: Array<Element>){
firstIdent = fidt
elements = elms
}
}
private var mIdentifier: String?
private var mElements: Array<Element>
private var mExpression: String
public var identifier: String? { get {
return mIdentifier
}}
public var elements: Array<Element> { get {
return mElements
}}
public var expression: String { get {
return mExpression
}}
public init(identifier ident: String?, elements elms: Array<Element>){
mIdentifier = ident
mElements = elms
mExpression = CNValuePath.toExpression(identifier: ident, elements: elms)
}
public init(identifier ident: String?, member memb: String){
mIdentifier = ident
mElements = [ .member(memb) ]
mExpression = CNValuePath.toExpression(identifier: ident, elements: mElements)
}
public init(path pth: CNValuePath, subPath subs: Array<Element>){
mIdentifier = pth.identifier
mElements = []
for src in pth.elements {
mElements.append(src)
}
for subs in subs {
mElements.append(subs)
}
mExpression = CNValuePath.toExpression(identifier: pth.identifier, elements: mElements)
}
public func isIncluded(in targ: CNValuePath) -> Bool {
let selms = self.mElements
let telms = targ.mElements
if selms.count <= telms.count {
for i in 0..<selms.count {
if !Element.isSame(source0: selms[i], source1: telms[i]) {
return false
}
}
return true
} else {
return false
}
}
public var description: String { get {
var result = ""
var is1st = true
for elm in mElements {
switch elm {
case .member(let str):
if is1st {
is1st = false
} else {
result += "."
}
result += "\(str)"
case .index(let idx):
result += "[\(idx)]"
case .keyAndValue(let key, let val):
result += "[\(key):\(val.description)]"
}
}
return result
}}
public static func toExpression(identifier ident: String?, elements elms: Array<Element>) -> String {
var result: String = ""
var is1st: Bool = true
if let str = ident {
result = "@" + str
is1st = false
}
for elm in elms {
switch elm {
case .member(let str):
if is1st {
is1st = false
} else {
result += "."
}
result += str
case .index(let idx):
result += "[\(idx)]"
case .keyAndValue(let key, let val):
let path: String
let quote = "\""
switch val {
case .stringValue(let str):
path = quote + str + quote
default:
path = quote + val.description + quote
}
result += "[\(key):\(path)]"
}
}
return result
}
public static func pathExpression(string str: String) -> Result<CNValuePath, NSError> {
let conf = CNParserConfig(allowIdentiferHasPeriod: false)
switch CNStringToToken(string: str, config: conf) {
case .ok(let tokens):
let stream = CNTokenStream(source: tokens)
switch pathExpression(stream: stream) {
case .success(let elms):
let path = CNValuePath(identifier: elms.firstIdent, elements: elms.elements)
return .success(path)
case .failure(let err):
return .failure(err)
}
case .error(let err):
return .failure(err)
}
}
private static func pathExpression(stream strm: CNTokenStream) -> Result<Elements, NSError> {
switch pathExpressionIdentifier(stream: strm) {
case .success(let identp):
switch pathExpressionMembers(stream: strm, hasIdentifier: identp != nil) {
case .success(let elms):
return .success(Elements(firstIdentifier: identp, elements: elms))
case .failure(let err):
return .failure(err)
}
case .failure(let err):
return .failure(err)
}
}
private static func pathExpressionIdentifier(stream strm: CNTokenStream) -> Result<String?, NSError> {
if strm.requireSymbol(symbol: "@") {
if let ident = strm.getIdentifier() {
return .success(ident)
} else {
let _ = strm.unget() // unget symbol
CNLog(logLevel: .error, message: "Identifier is required for label", atFunction: #function, inFile: #file)
}
}
return .success(nil)
}
private static func pathExpressionMembers(stream strm: CNTokenStream, hasIdentifier hasident: Bool) -> Result<Array<Element>, NSError> {
var is1st: Bool = !hasident
var result: Array<Element> = []
while !strm.isEmpty() {
/* Parse comma */
if is1st {
is1st = false
} else if !strm.requireSymbol(symbol: ".") {
return .failure(NSError.parseError(message: "Period is expected between members \(near(stream: strm))"))
}
/* Parse member */
guard let member = strm.getIdentifier() else {
return .failure(NSError.parseError(message: "Member for path expression is required \(near(stream: strm))"))
}
result.append(.member(member))
/* Check "[" symbol */
while strm.requireSymbol(symbol: "[") {
switch pathExpressionIndex(stream: strm) {
case .success(let elm):
result.append(elm)
case .failure(let err):
return .failure(err)
}
if !strm.requireSymbol(symbol: "]") {
return .failure(NSError.parseError(message: "']' is expected"))
}
}
}
return .success(result)
}
private static func pathExpressionIndex(stream strm: CNTokenStream) -> Result<Element, NSError> {
if let index = strm.requireUInt() {
return .success(.index(Int(index)))
} else if let ident = strm.requireIdentifier() {
if strm.requireSymbol(symbol: ":") {
switch requireAnyValue(stream: strm) {
case .success(let val):
return .success(.keyAndValue(ident, val))
case .failure(let err):
return .failure(err)
}
} else {
return .failure(NSError.parseError(message: "':' is required between dictionary key and value \(near(stream: strm))"))
}
} else {
return .failure(NSError.parseError(message: "Invalid index \(near(stream: strm))"))
}
}
private static func requireAnyValue(stream strm: CNTokenStream) -> Result<CNValue, NSError> {
if let ival = strm.requireUInt() {
return .success(.numberValue(NSNumber(integerLiteral: Int(ival))))
} else if let sval = strm.requireIdentifier() {
return .success(.stringValue(sval))
} else if let sval = strm.requireString() {
return .success(.stringValue(sval))
} else {
return .failure(NSError.parseError(message: "immediate value is required for value in key-value index"))
}
}
public static func description(of val: Dictionary<String, Array<CNValuePath.Element>>) -> CNText {
let sect = CNTextSection()
sect.header = "{" ; sect.footer = "}"
for (key, elm) in val {
let subsect = CNTextSection()
subsect.header = "\(key): {" ; subsect.footer = "}"
let desc = toExpression(identifier: nil, elements: elm)
let line = CNTextLine(string: desc)
subsect.add(text: line)
sect.add(text: subsect)
}
return sect
}
private static func near(stream strm: CNTokenStream) -> String {
if let token = strm.peek(offset: 0) {
return "near " + token.toString()
} else {
return ""
}
}
public func compare(_ val: CNValuePath) -> ComparisonResult {
let selfstr = self.mExpression
let srcstr = val.mExpression
if selfstr == srcstr {
return .orderedSame
} else if selfstr > srcstr {
return .orderedDescending
} else {
return .orderedAscending
}
}
}
| lgpl-2.1 | ff548c1bb3597ceabac9d5f1f6f361e6 | 26.324841 | 138 | 0.654079 | 3.311463 | false | false | false | false |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/Classes/Home/View/AmuseViewCell.swift | 1 | 1731 | //
// AmuseViewCell.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/19.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
private let amuseViewGameCellId = "amuseViewCellId"
class AmuseViewCell: UICollectionViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var anchorGroups:[AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "GameViewCell", bundle: nil), forCellWithReuseIdentifier: amuseViewGameCellId)
collectionView.dataSource = self
}
override func layoutSubviews() {
super.layoutSubviews()
let itemW = collectionView.bounds.width / CGFloat(4)
let itemH = collectionView.bounds.height / CGFloat(2)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return anchorGroups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: amuseViewGameCellId, for: indexPath) as! GameViewCell
cell.anchorGroup = self.anchorGroups![indexPath.item]
return cell
}
}
| mit | 0a1834474fb2a40718773f64a4538fca | 26.774194 | 128 | 0.666667 | 5.449367 | false | false | false | false |
bengottlieb/ios | FiveCalls/FiveCalls/RemoteImageView.swift | 3 | 3119 | //
// RemoteImageView.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/4/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
typealias RemoteImageCallback = (UIImage) -> Void
@IBDesignable
class RemoteImageView : UIImageView {
@IBInspectable
var defaultImage: UIImage?
lazy var session: URLSession = {
let session = URLSession(configuration: URLSessionConfiguration.default)
return session
}()
var currentTask: URLSessionDataTask?
private var currentImageURL: URL?
func setRemoteImage(url: URL) {
setRemoteImage(url: url) { [weak self] image in
self?.image = image
}
}
func setRemoteImage(url: URL, completion: @escaping RemoteImageCallback) {
setRemoteImage(preferred: defaultImage, url: url, completion: completion)
}
func setRemoteImage(preferred preferredImage: UIImage?, url: URL, completion: @escaping RemoteImageCallback) {
if let cachedImage = ImageCache.shared.image(forKey: url) {
image = cachedImage
return
}
image = preferredImage
guard preferredImage == nil || preferredImage == defaultImage else {
return completion(preferredImage!)
}
currentTask?.cancel()
currentTask = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self,
strongSelf.currentTask!.state != .canceling else {
return
}
if let e = error as NSError? {
if e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled {
// ignore cancellation errors
} else {
print("Error loading image: \(e.localizedDescription)")
}
} else {
guard let http = response as? HTTPURLResponse else { return }
if http.statusCode == 200 {
if let data = data, let image = UIImage(data: data) {
strongSelf.currentImageURL = url
ImageCache.shared.set(image: image, forKey: url)
if strongSelf.currentImageURL == url {
DispatchQueue.main.async {
completion(image)
}
}
}
} else {
print("HTTP \(http.statusCode) received for \(url)")
}
}
})
currentTask?.resume()
}
}
private struct ImageCache {
static var shared = ImageCache()
private let cache: NSCache<NSString, UIImage>
init() {
cache = NSCache()
}
func image(forKey key:URL) -> UIImage? {
return cache.object(forKey: key.absoluteString as NSString)
}
func set(image: UIImage, forKey key: URL) {
cache.setObject(image, forKey: key.absoluteString as NSString)
}
}
| mit | 16df83fa9c46115916ca097c1f483e24 | 29.871287 | 114 | 0.543618 | 5.348199 | false | false | false | false |
rc2server/appserverSwift | Sources/servermodel/Variable+JSON.swift | 1 | 7324 | //
// Variable+JSON.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Rc2Model
import Freddy
import MJLLogger
struct VariableError: Error {
let reason: String
let nestedError: Error?
init(_ reason: String, error: Error? = nil) {
self.reason = reason
self.nestedError = error
}
}
extension Variable {
static let rDateFormatter: ISO8601DateFormatter = { var f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate, .withDashSeparatorInDate]; return f}()
/// Parses a legacy compute json dictionary into a Variable
public static func makeFromLegacy(json: JSON) throws -> Variable {
do {
let vname = try json.getString(at: "name")
let className = try json.getString(at: "class")
let summary = try json.getString(at: "summary", or: "")
let vlen = try json.getInt(at: "length", or: 1)
var vtype: VariableType
if try json.getBool(at: "primitive", or: false) {
vtype = .primitive(try makePrimitive(json: json))
} else if try json.getBool(at: "s4", or: false) {
vtype = .s4Object
} else {
switch className {
case "Date":
do {
guard let vdate = rDateFormatter.date(from: try json.getString(at: "value"))
else { throw VariableError("invalid date value") }
vtype = .date(vdate)
} catch {
throw VariableError("invalid date value", error: error)
}
case "POSIXct", "POSIXlt":
do {
vtype = .dateTime(Date(timeIntervalSince1970: try json.getDouble(at: "value")))
} catch {
throw VariableError("invalid date value", error: error)
}
case "function":
do {
vtype = .function(try json.getString(at: "body"))
} catch {
throw VariableError("function w/o body", error: error)
}
case "factor", "ordered factor":
do {
vtype = .factor(values: try json.decodedArray(at: "value"), levelNames: try json.decodedArray(at: "levels", or: []))
} catch {
throw VariableError("factor missing values", error: error)
}
case "matrix":
vtype = .matrix(try parseMatrix(json: json))
case "environment":
vtype = .environment // FIXME: need to parse key/value pairs sent as value
case "data.frame":
vtype = .dataFrame(try parseDataFrame(json: json))
case "list":
vtype = .list([]) // FIXME: need to parse
default:
//make sure it is an object we can handle
guard try json.getBool(at: "generic", or: false) else { throw VariableError("unknown parsing error \(className)") }
var attrs = [String: Variable]()
let rawValues = try json.getDictionary(at: "value")
for aName in try json.decodedArray(at: "names", type: String.self) {
if let attrJson = rawValues[aName], let value = try? makeFromLegacy(json: attrJson) {
attrs[aName] = value
}
}
vtype = .generic(attrs)
}
}
return Variable(name: vname, length: vlen, type: vtype, className: className, summary: summary)
} catch let verror as VariableError {
throw verror
} catch {
Log.warn("error parsing legacy variable: \(error)")
throw VariableError("error parsing legacy variable", error: error)
}
}
static func parseDataFrame(json: JSON) throws -> DataFrameData {
do {
let numCols = try json.getInt(at: "ncol")
let numRows = try json.getInt(at: "nrow")
let rowNames: [String]? = try json.decodedArray(at: "row.names", alongPath: .missingKeyBecomesNil)
let rawColumns = try json.getArray(at: "columns")
let columns = try rawColumns.map { (colJson: JSON) -> DataFrameData.Column in
let colName = try colJson.getString(at: "name")
return DataFrameData.Column(name: colName, value: try makePrimitive(json: colJson, valueKey: "values"))
}
guard columns.count == numCols
else { throw VariableError("data does not match num cols/rows") }
return DataFrameData(columns: columns, rowCount: numRows, rowNames: rowNames)
} catch let verror as VariableError {
throw verror
} catch {
throw VariableError("error parsing data frame", error: error)
}
}
static func parseMatrix(json: JSON) throws -> MatrixData {
do {
let numCols = try json.getInt(at: "ncol")
let numRows = try json.getInt(at: "nrow")
let rowNames: [String]? = try? json.decodedArray(at: "dimnames", 0)
let colNames: [String]? = try? json.decodedArray(at: "dimnames", 1)
guard rowNames == nil || rowNames!.count == numRows
else { throw VariableError("row names do not match length") }
guard colNames == nil || colNames!.count == numCols
else { throw VariableError("col names do not match length") }
let values = try makePrimitive(json: json)
return MatrixData(value: values, rowCount: numRows, colCount: numCols, colNames: colNames, rowNames: rowNames)
} catch let verror as VariableError {
throw verror
} catch {
throw VariableError("error parsing matrix data", error: error)
}
}
// parses array of doubles, "Inf", "-Inf", and "NaN" into [Double]
static func parseDoubles(json: [JSON]) throws -> [Double?] {
return try json.map { (aVal) in
switch aVal {
case .double(let dval):
return dval
case .int(let ival):
return Double(ival)
case .string(let sval):
switch sval {
case "Inf": return Double.infinity
case "-Inf": return -Double.infinity
case "NaN": return Double.nan
default: throw VariableError("invalid string as double value \(aVal)")
}
case .null:
return nil
default:
throw VariableError("invalid value type in double array")
}
}
}
// returns a PrimitiveValue based on the contents of json
static func makePrimitive(json: JSON, valueKey: String = "value") throws -> PrimitiveValue {
guard let ptype = try? json.getString(at: "type")
else { throw VariableError("invalid primitive type") }
guard let rawValues = try json.getArray(at: valueKey, alongPath: .missingKeyBecomesNil)
else { throw VariableError("invalid value") }
var pvalue: PrimitiveValue
switch ptype {
case "n":
pvalue = .null
case "b":
let bval: [Bool?] = try rawValues.map { (aVal: JSON) -> Bool? in
if case .null = aVal { return nil }
if case let .bool(aBool) = aVal { return aBool }
throw VariableError("invalid bool variable \(aVal)")
}
pvalue = .boolean(bval)
case "i":
let ival: [Int?] = try rawValues.map { (aVal: JSON) -> Int? in
if case .null = aVal { return nil }
if case let .int(anInt) = aVal { return anInt }
throw VariableError("invalid int variable \(aVal)")
}
pvalue = .integer(ival)
case "d":
pvalue = .double(try parseDoubles(json: json.getArray(at: valueKey, alongPath: .nullBecomesNil)!))
case "s":
let sval: [String?] = try rawValues.map { (aVal: JSON) -> String? in
if case .null = aVal { return nil }
if case let .string(aStr) = aVal { return aStr }
throw VariableError("invalid string variable \(aVal)")
}
pvalue = .string(sval)
case "c":
let cval: [String?] = try rawValues.map { (aVal: JSON) -> String? in
if case .null = aVal { return nil }
if case let .string(aStr) = aVal { return aStr }
throw VariableError("invalid complex variable \(aVal)")
}
pvalue = .complex(cval)
case "r":
pvalue = .raw
default:
throw VariableError("unknown primitive type: \(ptype)")
}
return pvalue
}
}
| isc | c73941c1be57b00b9416375c3e72b4a3 | 34.897059 | 157 | 0.660795 | 3.351487 | false | false | false | false |
53ningen/todo | TODO/UI/UIStoryboardExtensions.swift | 1 | 1666 | import UIKit
import RxSwift
extension UIStoryboard {
static func selectLabelsViewController(_ selectedLabels: Variable<[Label]>) -> SelectLabelsViewController {
let vc = UIViewController.of(SelectLabelsViewController.self)
vc.modalTransitionStyle = UIModalTransitionStyle.coverVertical
vc.setViewModel(SelectLabelsViewModel(selected: selectedLabels))
return vc
}
static func issueViewController(_ id: Id<Issue>) -> IssueViewController {
let vc = UIViewController.of(IssueViewController.self)
vc.setViewModel(IssueViewModel(id: id))
vc.hidesBottomBarWhenPushed = true
return vc
}
static func editIssueViewController(_ issue: Issue? = nil) -> EditIssueViewController {
let vc = UIViewController.of(EditIssueViewController.self)
issue.forEach { vc.setViewModel(EditIssueViewModel(issue: $0)) }
return vc
}
static var addLabelViewController: EditLabelViewController {
return UIViewController.of(EditLabelViewController.self)
}
static var addMilestoneViewController: EditMilestoneViewController {
return UIViewController.of(EditMilestoneViewController.self)
}
static func issuesViewController(_ query: IssuesQuery) -> IssuesViewController {
let vc = UIViewController.of(IssuesViewController.self)
vc.setViewModel(IssuesViewModel(query: query))
return vc
}
static var licenseViewController: LicensesViewController {
let vc = UIViewController.of(LicensesViewController.self)
vc.hidesBottomBarWhenPushed = true
return vc
}
}
| mit | c95b814d793c9c5fbdb1bfddddd03c73 | 35.217391 | 111 | 0.708283 | 5.356913 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/WhistlesVsZombies/Zombie/Item/Type/MOptionWhistlesVsZombiesZombieItemCop.swift | 1 | 1065 | import SpriteKit
class MOptionWhistlesVsZombiesZombieItemCop:MOptionWhistlesVsZombiesZombieItemProtocol
{
private(set) weak var textureStand:MGameTexture!
private(set) weak var animatedWalking:SKAction!
private(set) var animatedDefeat:SKAction!
private(set) var verticalDelta:CGFloat
private(set) var speed:Int
private(set) var intelligence:Int
private(set) var life:Int
private(set) var coins:Int
private let kVerticalDelta:CGFloat = 2
private let kSpeed:Int = 5
private let kIntelligence:Int = 7
private let kLife:Int = 35
private let kCoins:Int = 2
required init(
textures:MOptionWhistlesVsZombiesTextures,
actions:MOptionWhistlesVsZombiesActions)
{
textureStand = textures.zombieCopStand
animatedWalking = actions.actionZombieCopWalkingAnimation
animatedDefeat = actions.actionZombieCopDefeatedAnimation
verticalDelta = kVerticalDelta
speed = kSpeed
intelligence = kIntelligence
life = kLife
coins = kCoins
}
}
| mit | 7dab43a1747be05b942b97d389b09e81 | 32.28125 | 86 | 0.723005 | 4.61039 | false | false | false | false |
Nosrac/Dictater | Dictater/DictaterWindow.swift | 1 | 2473 | //
// DictateAssistWindow.swift
// Dictate Assist
//
// Created by Kyle Carson on 9/1/15.
// Copyright © 2015 Kyle Carson. All rights reserved.
//
import Foundation
import Cocoa
class DictaterWindow : NSWindow
{
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag)
// self.styleMask = NSBorderlessWindowMask
self.isOpaque = false
self.backgroundColor = NSColor.clear
self.level = NSWindow.Level.floating
NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterFullScreen), name: NSNotification.Name(rawValue: TeleprompterWindowDelegate.FullScreenEnteredEvent), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.didExitFullScreen), name: NSNotification.Name(rawValue: TeleprompterWindowDelegate.FullScreenExitedEvent), object: nil)
}
@objc func didEnterFullScreen()
{
self.orderOut(self)
}
@objc func didExitFullScreen()
{
self.orderFront(self)
}
// required init?(coder: NSCoder) {
// super.init(coder: coder)
// }
override var contentView : NSView? {
set {
if let view = newValue
{
view.wantsLayer = true
view.layer?.frame = view.frame
view.layer?.cornerRadius = 6.0
view.layer?.masksToBounds = true
}
super.contentView = newValue
}
get {
return super.contentView
}
}
override var canBecomeMain : Bool
{
get {
return true
}
}
override var canBecomeKey : Bool
{
get {
return true
}
}
// Drag Windows
var initialLocation : NSPoint?
override func mouseDown(with event: NSEvent) {
initialLocation = event.locationInWindow
}
override func mouseDragged(with event: NSEvent) {
if let screenVisibleFrame = NSScreen.main?.visibleFrame,
let initialLocation = self.initialLocation
{
let windowFrame = self.frame
var newOrigin = windowFrame.origin
let currentLocation = event.locationInWindow
newOrigin.x += (currentLocation.x - initialLocation.x)
newOrigin.y += (currentLocation.y - initialLocation.y)
if (newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)
{
newOrigin.y = screenVisibleFrame.origin.y + screenVisibleFrame.size.height - windowFrame.size.height
}
self.setFrameOrigin(newOrigin)
}
}
}
| mit | 525d1450ea26344c09eabaa638a2e571 | 23.969697 | 193 | 0.726133 | 3.717293 | false | false | false | false |
dangquochoi2007/cleancodeswift | CleanStore/CleanStore/App/Services/ImageMemoryStore.swift | 1 | 1836 | //
// ImageMemoryStore.swift
// CleanStore
//
// Created by hoi on 1/6/17.
// Copyright © 2017 hoi. All rights reserved.
//
import UIKit
/// _ImageMemoryStore_ is an image store backed by an in-memory cache
class ImageMemoryStore: ImageStoreProtocol {
fileprivate var imageCache = [String: UIImage]()
// MARK: - Initializers
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleMemoryNotification), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
}
/// Loads an image from the cache if found otherwise returns nil
///
/// - parameter url: The image URL
/// - parameter completion: The closure to trigger when the image is found or not
func loadImage(url: URL, completion: @escaping (UIImage?, Error?) -> ()) {
let cacheKey = key(url: url)
let image = imageCache[cacheKey]
completion(image, nil)
}
/// Saves an image to the cache
///
/// - parameter image: The image to save (cache)
/// - parameter url: The URL of the image (used as a key)
func saveImage(image: UIImage?, url: URL) {
let cacheKey = key(url: url)
imageCache[cacheKey] = image
}
/// Removes all images from the memory cache
func removeAllImages() {
self.imageCache.removeAll()
}
//
// MARK: - Private
private func key(url: URL) -> String {
return url.absoluteString
}
@objc func handleMemoryNotification() {
self.removeAllImages()
}
}
| mit | 7d20ba436d6eec9353eddccb2260a1fc | 25.214286 | 176 | 0.60327 | 4.791123 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_RegexParser/Regex/Printing/PrintAsCanonical.swift | 1 | 9703 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org 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 https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// TODO: Round-tripping tests
extension AST {
/// Renders using Swift's preferred regex literal syntax.
public func renderAsCanonical(
showDelimiters delimiters: Bool = false,
terminateLine: Bool = false
) -> String {
var printer = PrettyPrinter()
printer.printAsCanonical(
self,
delimiters: delimiters,
terminateLine: terminateLine)
return printer.finish()
}
}
extension AST.Node {
/// Renders using Swift's preferred regex literal syntax.
public func renderAsCanonical(
showDelimiters delimiters: Bool = false,
terminateLine: Bool = false
) -> String {
AST(self, globalOptions: nil, diags: Diagnostics()).renderAsCanonical(
showDelimiters: delimiters, terminateLine: terminateLine)
}
}
extension PrettyPrinter {
/// Outputs a regular expression abstract syntax tree in canonical form,
/// indenting and terminating the line, and updating its internal state.
///
/// - Parameter ast: The abstract syntax tree of the regular expression being output.
/// - Parameter delimiters: Whether to include commas between items.
/// - Parameter terminateLine: Whether to include terminate the line.
public mutating func printAsCanonical(
_ ast: AST,
delimiters: Bool = false,
terminateLine terminate: Bool = true
) {
indent()
if delimiters { output("'/") }
if let opts = ast.globalOptions {
outputAsCanonical(opts)
}
outputAsCanonical(ast.root)
if delimiters { output("/'") }
if terminate {
terminateLine()
}
}
/// Outputs a regular expression abstract syntax tree in canonical form,
/// without indentation, line termation, or affecting its internal state.
mutating func outputAsCanonical(_ ast: AST.Node) {
switch ast {
case let .alternation(a):
for idx in a.children.indices {
outputAsCanonical(a.children[idx])
if a.children.index(after: idx) != a.children.endIndex {
output("|")
}
}
case let .concatenation(c):
c.children.forEach { outputAsCanonical($0) }
case let .group(g):
output(g.kind.value._canonicalBase)
outputAsCanonical(g.child)
output(")")
case let .conditional(c):
output("(")
outputAsCanonical(c.condition)
outputAsCanonical(c.trueBranch)
output("|")
outputAsCanonical(c.falseBranch)
case let .quantification(q):
outputAsCanonical(q.child)
output(q.amount.value._canonicalBase)
output(q.kind.value._canonicalBase)
case let .quote(q):
output(q._canonicalBase)
case let .trivia(t):
output(t._canonicalBase)
case let .interpolation(i):
output(i._canonicalBase)
case let .atom(a):
output(a._canonicalBase)
case let .customCharacterClass(ccc):
outputAsCanonical(ccc)
case let .absentFunction(abs):
outputAsCanonical(abs)
case .empty:
output("")
}
}
mutating func outputAsCanonical(
_ ccc: AST.CustomCharacterClass
) {
output(ccc.start.value._canonicalBase)
ccc.members.forEach { outputAsCanonical($0) }
output("]")
}
mutating func outputAsCanonical(
_ member: AST.CustomCharacterClass.Member
) {
// TODO: Do we need grouping or special escape rules?
switch member {
case .custom(let ccc):
outputAsCanonical(ccc)
case .range(let r):
output(r.lhs._canonicalBase)
output("-")
output(r.rhs._canonicalBase)
case .atom(let a):
output(a._canonicalBase)
case .quote(let q):
output(q._canonicalBase)
case .trivia(let t):
output(t._canonicalBase)
case .setOperation:
output("/* TODO: set operation \(self) */")
}
}
mutating func outputAsCanonical(_ condition: AST.Conditional.Condition) {
output("(/*TODO: conditional \(condition) */)")
}
mutating func outputAsCanonical(_ abs: AST.AbsentFunction) {
output("(?~")
switch abs.kind {
case .repeater(let a):
outputAsCanonical(a)
case .expression(let a, _, let child):
output("|")
outputAsCanonical(a)
output("|")
outputAsCanonical(child)
case .stopper(let a):
output("|")
outputAsCanonical(a)
case .clearer:
output("|")
}
output(")")
}
mutating func outputAsCanonical(_ opts: AST.GlobalMatchingOptionSequence) {
for opt in opts.options {
output(opt._canonicalBase)
}
}
}
extension AST.Quote {
var _canonicalBase: String {
// TODO: Is this really what we want?
"\\Q\(literal)\\E"
}
}
extension AST.Interpolation {
var _canonicalBase: String {
"<{\(contents)}>"
}
}
extension AST.Group.Kind {
var _canonicalBase: String {
switch self {
case .capture: return "("
case .namedCapture(let n): return "(?<\(n.value)>"
case .balancedCapture(let b): return "(?<\(b._canonicalBase)>"
case .nonCapture: return "(?:"
case .nonCaptureReset: return "(?|"
case .atomicNonCapturing: return "(?>"
case .lookahead: return "(?="
case .negativeLookahead: return "(?!"
case .nonAtomicLookahead: return "(?*"
case .lookbehind: return "(?<="
case .negativeLookbehind: return "(?<!"
case .nonAtomicLookbehind: return "(?<*"
case .scriptRun: return "(*sr:"
case .atomicScriptRun: return "(*asr:"
case .changeMatchingOptions:
return "(/* TODO: matchign options in canonical form */"
}
}
}
extension AST.Quantification.Amount {
var _canonicalBase: String {
switch self {
case .zeroOrMore: return "*"
case .oneOrMore: return "+"
case .zeroOrOne: return "?"
case let .exactly(n): return "{\(n._canonicalBase)}"
case let .nOrMore(n): return "{\(n._canonicalBase),}"
case let .upToN(n): return "{,\(n._canonicalBase)}"
case let .range(lower, upper):
return "{\(lower),\(upper)}"
}
}
}
extension AST.Quantification.Kind {
var _canonicalBase: String { self.rawValue }
}
extension AST.Atom.Number {
var _canonicalBase: String {
value.map { "\($0)" } ?? "<#number#>"
}
}
extension AST.Atom {
var _canonicalBase: String {
if let lit = self.literalStringValue {
// FIXME: We may have to re-introduce escapes
// For example, `\.` will come back as "." instead
// For now, catch the most common offender
if lit == "." { return "\\." }
return lit
}
switch self.kind {
case .caretAnchor:
return "^"
case .dollarAnchor:
return "$"
case .escaped(let e):
return "\\\(e.character)"
case .backreference(let br):
return br._canonicalBase
default:
return "/* TODO: atom \(self) */"
}
}
}
extension AST.Reference {
var _canonicalBase: String {
if self.recursesWholePattern {
return "(?R)"
}
switch kind {
case .absolute(let i):
// TODO: Which should we prefer, this or `\g{n}`?
return "\\\(i)"
case .relative:
return "/* TODO: relative reference \(self) */"
case .named:
return "/* TODO: named reference \(self) */"
}
}
}
extension AST.CustomCharacterClass.Start {
var _canonicalBase: String { self.rawValue }
}
extension AST.Group.BalancedCapture {
var _canonicalBase: String {
"\(name?.value ?? "")-\(priorName.value)"
}
}
extension AST.GlobalMatchingOption.NewlineMatching {
var _canonicalBase: String {
switch self {
case .carriageReturnOnly: return "CR"
case .linefeedOnly: return "LF"
case .carriageAndLinefeedOnly: return "CRLF"
case .anyCarriageReturnOrLinefeed: return "ANYCRLF"
case .anyUnicode: return "ANY"
case .nulCharacter: return "NUL"
}
}
}
extension AST.GlobalMatchingOption.NewlineSequenceMatching {
var _canonicalBase: String {
switch self {
case .anyCarriageReturnOrLinefeed: return "BSR_ANYCRLF"
case .anyUnicode: return "BSR_UNICODE"
}
}
}
extension AST.GlobalMatchingOption.Kind {
var _canonicalBase: String {
switch self {
case .limitDepth(let i): return "LIMIT_DEPTH=\(i._canonicalBase)"
case .limitHeap(let i): return "LIMIT_HEAP=\(i._canonicalBase)"
case .limitMatch(let i): return "LIMIT_MATCH=\(i._canonicalBase)"
case .notEmpty: return "NOTEMPTY"
case .notEmptyAtStart: return "NOTEMPTY_ATSTART"
case .noAutoPossess: return "NO_AUTO_POSSESS"
case .noDotStarAnchor: return "NO_DOTSTAR_ANCHOR"
case .noJIT: return "NO_JIT"
case .noStartOpt: return "NO_START_OPT"
case .utfMode: return "UTF"
case .unicodeProperties: return "UCP"
case .newlineMatching(let m): return m._canonicalBase
case .newlineSequenceMatching(let m): return m._canonicalBase
}
}
}
extension AST.GlobalMatchingOption {
var _canonicalBase: String { "(*\(kind._canonicalBase))"}
}
extension AST.Trivia {
var _canonicalBase: String {
// TODO: We might want to output comments...
""
}
}
| apache-2.0 | 8c628563e8672735e21b624aa7133ed4 | 27.454545 | 87 | 0.607956 | 4.037869 | false | false | false | false |
braintree/braintree_ios | UnitTests/BraintreePayPalTests/BTPayPalDriver_Tests.swift | 1 | 32734 | import XCTest
import BraintreePayPal
import BraintreeTestShared
class BTPayPalDriver_Tests: XCTestCase {
var mockAPIClient: MockAPIClient!
var payPalDriver: BTPayPalDriver!
override func setUp() {
super.setUp()
mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"paypalEnabled": true,
"paypal": [
"environment": "offline"
]
])
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "http://fakeURL.com"
]
])
payPalDriver = BTPayPalDriver(apiClient: mockAPIClient)
}
func testTokenizePayPalAccount_whenAPIClientIsNil_callsBackWithError() {
payPalDriver.apiClient = nil
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.integration.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenRequestIsNotExpectedSubclass_callsBackWithError() {
let request = BTPayPalRequest() // not one of our subclasses
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.integration.rawValue)
XCTAssertEqual(error.localizedDescription, "BTPayPalDriver failed because request is not of type BTPayPalCheckoutRequest or BTPayPalVaultRequest.")
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenRemoteConfigurationFetchFails_callsBackWithConfigurationError() {
mockAPIClient.cannedConfigurationResponseBody = nil
mockAPIClient.cannedConfigurationResponseError = NSError(domain: "", code: 0, userInfo: nil)
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error, self.mockAPIClient.cannedConfigurationResponseError)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenPayPalNotEnabledInConfiguration_callsBackWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"paypalEnabled": false
])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.disabled.rawValue)
XCTAssertEqual(error.localizedDescription, "PayPal is not enabled for this merchant")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
// MARK: - POST request to Hermes endpoint
func testRequestOneTimePayment_whenRemoteConfigurationFetchSucceeds_postsToCorrectEndpoint() {
let request = BTPayPalCheckoutRequest(amount: "1")
request.intent = .sale
payPalDriver.requestOneTimePayment(request) { _,_ -> Void in }
XCTAssertEqual("v1/paypal_hermes/create_payment_resource", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else { XCTFail(); return }
XCTAssertEqual(lastPostParameters["intent"] as? String, "sale")
XCTAssertEqual(lastPostParameters["amount"] as? String, "1")
XCTAssertEqual(lastPostParameters["return_url"] as? String, "sdk.ios.braintree://onetouch/v1/success")
XCTAssertEqual(lastPostParameters["cancel_url"] as? String, "sdk.ios.braintree://onetouch/v1/cancel")
}
func testRequestBillingAgreement_whenRemoteConfigurationFetchSucceeds_postsToCorrectEndpoint() {
let request = BTPayPalVaultRequest()
request.billingAgreementDescription = "description"
payPalDriver.requestBillingAgreement(request) { _,_ -> Void in }
XCTAssertEqual("v1/paypal_hermes/setup_billing_agreement", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else { XCTFail(); return }
XCTAssertEqual(lastPostParameters["description"] as? String, "description")
XCTAssertEqual(lastPostParameters["return_url"] as? String, "sdk.ios.braintree://onetouch/v1/success")
XCTAssertEqual(lastPostParameters["cancel_url"] as? String, "sdk.ios.braintree://onetouch/v1/cancel")
}
func testTokenizePayPalAccount_whenPaymentResourceCreationFails_callsBackWithError() {
mockAPIClient.cannedResponseError = NSError(domain: "", code: 0, userInfo: nil)
let dummyRequest = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: dummyRequest) { (_, error) -> Void in
XCTAssertEqual(error! as NSError, self.mockAPIClient.cannedResponseError!)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
// MARK: - PayPal approval URL to present in browser
func testTokenizePayPalAccount_checkout_whenUserActionIsNotSet_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_vault_whenUserActionIsNotSet_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"agreementSetup": [
"approvalUrl": "https://checkout.paypal.com/one-touch-login-sandbox"
]
])
let request = BTPayPalVaultRequest()
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://checkout.paypal.com/one-touch-login-sandbox", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToDefault_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.default
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToCommit_approvalUrlIsModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.commit
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value&useraction=commit", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToCommit_andNoQueryParamsArePresent_approvalUrlIsModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.commit
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?useraction=commit", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenApprovalUrlIsNotHTTP_returnsError() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "file://some-url.com"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Returns error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
XCTAssertNil(nonce)
XCTAssertEqual((error! as NSError).domain, BTPayPalDriverErrorDomain)
XCTAssertEqual((error! as NSError).code, BTPayPalDriverErrorType.unknown.rawValue)
XCTAssertEqual((error! as NSError).localizedDescription, "Attempted to open an invalid URL in ASWebAuthenticationSession: file://")
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
// MARK: - Browser switch
func testTokenizePayPalAccount_whenPayPalPayLaterOffered_performsSwitchCorrectly() {
let request = BTPayPalCheckoutRequest(amount: "1")
request.currencyCode = "GBP"
request.offerPayLater = true
payPalDriver.tokenizePayPalAccount(with: request) { _,_ in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
// Ensure the payment resource had the correct parameters
XCTAssertEqual("v1/paypal_hermes/create_payment_resource", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
XCTAssertEqual(lastPostParameters["offer_pay_later"] as? Bool, true)
// Make sure analytics event was sent when switch occurred
let postedAnalyticsEvents = mockAPIClient.postedAnalyticsEvents
XCTAssertTrue(postedAnalyticsEvents.contains("ios.paypal-single-payment.webswitch.paylater.offered.started"))
}
func testTokenizePayPalAccount_whenPayPalCreditOffered_performsSwitchCorrectly() {
let request = BTPayPalVaultRequest()
request.offerCredit = true
payPalDriver.tokenizePayPalAccount(with: request) { _,_ in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
// Ensure the payment resource had the correct parameters
XCTAssertEqual("v1/paypal_hermes/setup_billing_agreement", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
XCTAssertEqual(lastPostParameters["offer_paypal_credit"] as? Bool, true)
// Make sure analytics event was sent when switch occurred
let postedAnalyticsEvents = mockAPIClient.postedAnalyticsEvents
XCTAssertTrue(postedAnalyticsEvents.contains("ios.paypal-ba.webswitch.credit.offered.started"))
}
func testTokenizePayPalAccount_whenPayPalPaymentCreationSuccessful_performsAppSwitch() {
let request = BTPayPalCheckoutRequest(amount: "1")
payPalDriver.tokenizePayPalAccount(with: request) { _,_ -> Void in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
XCTAssertNotNil(payPalDriver.clientMetadataID)
}
// MARK: - handleBrowserSwitchReturn
func testHandleBrowserSwitchReturn_whenBrowserSwitchCancels_callsBackWithNoResultAndError() {
let returnURL = URL(string: "bar://onetouch/v1/cancel?token=hermes_token")!
let expectation = self.expectation(description: "completion block called")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (nonce, error) in
XCTAssertNil(nonce)
XCTAssertEqual((error! as NSError).domain, BTPayPalDriverErrorDomain)
XCTAssertEqual((error! as NSError).code, BTPayPalDriverErrorType.canceled.rawValue)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchHasInvalidReturnURL_callsBackWithError() {
let returnURL = URL(string: "bar://onetouch/v1/invalid")!
let continuationExpectation = self.expectation(description: "Continuation called")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertNotNil(error)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.unknown.rawValue)
continuationExpectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_tokenizesPayPalCheckout() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let paypalAccount = lastPostParameters["paypal_account"] as! [String:Any]
let options = paypalAccount["options"] as! [String:Any]
XCTAssertFalse(options["validate"] as! Bool)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_intentShouldExistAsPayPalAccountParameter() {
let payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
payPalRequest.intent = .sale
payPalDriver.payPalRequest = payPalRequest
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let paypalAccount = lastPostParameters["paypal_account"] as! [String:Any]
XCTAssertEqual(paypalAccount["intent"] as? String, "sale")
let options = paypalAccount["options"] as! [String:Any]
XCTAssertFalse(options["validate"] as! Bool)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_merchantAccountIdIsSet() {
let merchantAccountID = "alternate-merchant-account-id"
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
payPalDriver.payPalRequest.merchantAccountID = merchantAccountID
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
XCTAssertEqual(lastPostParameters["merchant_account_id"] as? String, merchantAccountID)
}
func testHandleBrowserSwitchReturn_whenCreditFinancingNotReturned_shouldNotSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "[email protected]",
"details": [
"email": "[email protected]",
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertFalse(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-single-payment.credit.accepted"))
}
func testHandleBrowserSwitchReturn_whenCreditFinancingReturned_shouldSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "[email protected]",
"details": [
"email": "[email protected]",
"creditFinancingOffered": [
"cardAmountImmutable": true,
"monthlyPayment": [
"currency": "USD",
"value": "13.88",
],
"payerAcceptance": true,
"term": 18,
"totalCost": [
"currency": "USD",
"value": "250.00",
],
"totalInterest": [
"currency": "USD",
"value": "0.00",
],
],
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-single-payment.credit.accepted"))
}
// MARK: - Tokenization
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_sendsCorrectParametersForTokenization() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
guard let paypalAccount = lastPostParameters["paypal_account"] as? [String:Any] else {
XCTFail()
return
}
let client = paypalAccount["client"] as? [String:String]
XCTAssertEqual(client?["paypal_sdk_version"], "version")
XCTAssertEqual(client?["platform"], "iOS")
XCTAssertEqual(client?["product_name"], "PayPal")
let response = paypalAccount["response"] as? [String:String]
XCTAssertEqual(response?["webURL"], "bar://onetouch/v1/success?token=hermes_token")
XCTAssertEqual(paypalAccount["response_type"] as? String, "web")
}
func testTokenizedPayPalAccount_containsPayerInfo() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "a-nonce",
"description": "A description",
"details": [
"email": "[email protected]",
"payerInfo": [
"firstName": "Some",
"lastName": "Dude",
"phone": "867-5309",
"payerId": "FAKE-PAYER-ID",
"accountAddress": [
"street1": "1 Foo Ct",
"street2": "Apt Bar",
"city": "Fubar",
"state": "FU",
"postalCode": "42",
"country": "USA"
],
"billingAddress": [
"recipientName": "Bar Foo",
"line1": "2 Foo Ct",
"line2": "Apt Foo",
"city": "Barfoo",
"state": "BF",
"postalCode": "24",
"countryCode": "ASU"
],
"shippingAddress": [
"recipientName": "Some Dude",
"line1": "3 Foo Ct",
"line2": "Apt 5",
"city": "Dudeville",
"state": "CA",
"postalCode": "24",
"countryCode": "US"
]
]
]
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) in
XCTAssertEqual(tokenizedPayPalAccount!.nonce, "a-nonce")
XCTAssertEqual(tokenizedPayPalAccount!.firstName, "Some")
XCTAssertEqual(tokenizedPayPalAccount!.lastName, "Dude")
XCTAssertEqual(tokenizedPayPalAccount!.phone, "867-5309")
XCTAssertEqual(tokenizedPayPalAccount!.email, "[email protected]")
XCTAssertEqual(tokenizedPayPalAccount!.payerID, "FAKE-PAYER-ID")
let billingAddress = tokenizedPayPalAccount!.billingAddress!
XCTAssertEqual(billingAddress.recipientName, "Bar Foo")
XCTAssertEqual(billingAddress.streetAddress, "2 Foo Ct")
XCTAssertEqual(billingAddress.extendedAddress, "Apt Foo")
XCTAssertEqual(billingAddress.locality, "Barfoo")
XCTAssertEqual(billingAddress.region, "BF")
XCTAssertEqual(billingAddress.postalCode, "24")
XCTAssertEqual(billingAddress.countryCodeAlpha2, "ASU")
let shippingAddress = tokenizedPayPalAccount!.shippingAddress!
XCTAssertEqual(shippingAddress.recipientName, "Some Dude")
XCTAssertEqual(shippingAddress.streetAddress, "3 Foo Ct")
XCTAssertEqual(shippingAddress.extendedAddress, "Apt 5")
XCTAssertEqual(shippingAddress.locality, "Dudeville")
XCTAssertEqual(shippingAddress.region, "CA")
XCTAssertEqual(shippingAddress.postalCode, "24")
XCTAssertEqual(shippingAddress.countryCodeAlpha2, "US")
}
}
func testTokenizedPayPalAccount_whenTokenizationResponseDoesNotHaveShippingAddress_returnsAccountAddressAsShippingAddress() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "a-nonce",
"description": "A description",
"details": [
"email": "[email protected]",
"payerInfo": [
"firstName": "Some",
"lastName": "Dude",
"phone": "867-5309",
"payerId": "FAKE-PAYER-ID",
"accountAddress": [
"recipientName": "Grace Hopper",
"street1": "1 Foo Ct",
"street2": "Apt Bar",
"city": "Fubar",
"state": "FU",
"postalCode": "42",
"country": "USA"
],
"billingAddress": [
"recipientName": "Bar Foo",
"line1": "2 Foo Ct",
"line2": "Apt Foo",
"city": "Barfoo",
"state": "BF",
"postalCode": "24",
"countryCode": "ASU"
]
]
]
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) in
let shippingAddress = tokenizedPayPalAccount!.shippingAddress!
XCTAssertEqual(shippingAddress.recipientName, "Grace Hopper")
XCTAssertEqual(shippingAddress.streetAddress, "1 Foo Ct")
XCTAssertEqual(shippingAddress.extendedAddress, "Apt Bar")
XCTAssertEqual(shippingAddress.locality, "Fubar")
XCTAssertEqual(shippingAddress.region, "FU")
XCTAssertEqual(shippingAddress.postalCode, "42")
XCTAssertEqual(shippingAddress.countryCodeAlpha2, "USA")
}
}
func testTokenizedPayPalAccount_whenEmailAddressIsNestedInsidePayerInfoJSON_usesNestedEmailAddress() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "fake-nonce",
"details": [
"email": "[email protected]",
"payerInfo": [
"email": "[email protected]",
]
],
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) -> Void in
XCTAssertEqual(tokenizedPayPalAccount!.email, "[email protected]")
}
}
// MARK: - _meta parameter
func testMetadata_whenCheckoutBrowserSwitchIsSuccessful_isPOSTedToServer() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let metaParameters = lastPostParameters["_meta"] as! [String:Any]
XCTAssertEqual(metaParameters["source"] as? String, "paypal-browser")
XCTAssertEqual(metaParameters["integration"] as? String, "custom")
XCTAssertEqual(metaParameters["sessionId"] as? String, mockAPIClient.metadata.sessionID)
}
// MARK: - Analytics
func testAPIClientMetadata_hasIntegrationSetToCustom() {
let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id")!
let payPalDriver = BTPayPalDriver(apiClient: apiClient)
XCTAssertEqual(payPalDriver.apiClient?.metadata.integration, BTClientMetadataIntegrationType.custom)
}
func testHandleBrowserSwitchReturn_vault_whenCreditFinancingNotReturned_shouldNotSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "[email protected]",
"details": [
"email": "[email protected]",
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalVaultRequest()
let returnURL = URL(string: "bar://hello/world")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertFalse(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-ba.credit.accepted"))
}
func testHandleBrowserSwitchReturn_vault_whenCreditFinancingReturned_shouldSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(
value: [ "paypalAccounts": [
[
"description": "[email protected]",
"details": [
"email": "[email protected]",
"creditFinancingOffered": [
"cardAmountImmutable": true,
"monthlyPayment": [
"currency": "USD",
"value": "13.88",
],
"payerAcceptance": true,
"term": 18,
"totalCost": [
"currency": "USD",
"value": "250.00",
],
"totalInterest": [
"currency": "USD",
"value": "0.00",
],
],
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalVaultRequest()
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-ba.credit.accepted"))
}
func testTokenizePayPalAccountWithPayPalRequest_whenNetworkConnectionLost_sendsAnalytics() {
mockAPIClient.cannedResponseError = NSError(domain: NSURLErrorDomain, code: -1005, userInfo: [NSLocalizedDescriptionKey: "The network connection was lost."])
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [ "paypalEnabled": true ])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Callback envoked")
payPalDriver.tokenizePayPalAccount(with: request) { nonce, error in
XCTAssertNotNil(error)
expectation.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal.tokenize.network-connection.failure"))
}
func testHandleBrowserSwitchReturnURL_whenNetworkConnectionLost_sendsAnalytics() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
mockAPIClient.cannedResponseError = NSError(domain: NSURLErrorDomain, code: -1005, userInfo: [NSLocalizedDescriptionKey: "The network connection was lost."])
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [ "paypalEnabled": true ])
let expectation = self.expectation(description: "Callback envoked")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { nonce, error in
XCTAssertNotNil(error)
expectation.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal.handle-browser-switch.network-connection.failure"))
}
}
| mit | de9743fd35f640f9de9a411d274418ce | 44.212707 | 165 | 0.609214 | 5.022863 | false | true | false | false |
taipingeric/Leet-Code-In-Swift | Example/125.Valid Palindrome.playground/Contents.swift | 1 | 369 | import Foundation
class Solution {
func isPalindrome(s: String) -> Bool {
let lowString = s.lowercaseString
let string = lowString.utf8.filter{ char in
let isaToz = char >= 97 && char <= 122
let is0To9 = char >= 48 && char <= 57
return isaToz || is0To9
}
return string == string.reverse()
}
} | mit | d84cd0544ab40189637590e8faffd446 | 27.461538 | 51 | 0.552846 | 4.054945 | false | false | false | false |
Breinify/brein-api-library-ios | BreinifyApi/engine/URLSessionEngine.swift | 1 | 13122 | //
// Created by Marco Recchioni
// Copyright (c) 2020 Breinify. All rights reserved.
//
import Foundation
public class URLSessionEngine: IRestEngine {
/// some handy aliases
public typealias apiSuccess = (_ result: BreinResult) -> Void
public typealias apiFailure = (_ error: NSDictionary) -> Void
/**
Configures the rest engine
- parameter breinConfig: configuration object
*/
public func configure(_ breinConfig: BreinConfig) {
}
public func executeSavedRequests() {
BreinLogger.shared.log("Breinify executeSavedRequests invoked")
// 1. loop over entries
// contains a copy of the missedRequests from BreinRequestManager
let missedRequests = BreinRequestManager.shared.getMissedRequests()
BreinLogger.shared.log("Breinify number of elements in queue is: \(missedRequests.count)")
for (uuid, entry) in (missedRequests) {
BreinLogger.shared.log("Breinify working on UUID: \(uuid)")
// 1. is this entry in time range?
let considerEntry = BreinRequestManager.shared.checkIfValid(currentEntry: entry)
if considerEntry == true {
let urlString = entry.fullUrl
let jsonData:String = entry.jsonBody
// 2. send it
var request = URLRequest(url: URL(string: urlString!)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// add the uuid to identify the request on response
request.setValue(uuid, forHTTPHeaderField: "uuid")
request.httpBody = jsonData.data(using: .utf8)
// replace start
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
if let resp = response as? HTTPURLResponse {
let uuidEntryAny = resp.allHeaderFields["uuid"]
if let uuidEntry = uuidEntryAny as? String {
BreinLogger.shared.log("Breinify successfully (resend): \(String(describing: jsonData))")
BreinRequestManager.shared.removeEntry(uuidEntry)
}
}
}
}
task.resume()
// replace end
} else {
BreinLogger.shared.log("Breinify removing from queue: \(uuid)")
BreinRequestManager.shared.removeEntry(uuid)
}
}
}
/**
Invokes the post request for activities
- parameter breinActivity: activity object
- parameter success: will be invoked in case of success
- parameter failure: will be invoked in case of an error
*/
public func doRequest(_ breinActivity: BreinActivity,
success: @escaping apiSuccess,
failure: @escaping apiFailure) throws {
try validate(breinActivity)
let url = try getFullyQualifiedUrl(breinActivity)
let body = try getRequestBody(breinActivity)
var jsonString = ""
var jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: body as Any, options: [.prettyPrinted])
jsonString = String(data: jsonData, encoding: .utf8) ?? ""
let activity:[String: Any] = body?["activity"] as! [String : Any]
let actTyp:String = activity["type"] as! String
BreinLogger.shared.log("Breinify doRequest for activityType: \(actTyp) -- json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doRequest with error: \(error)")
let canResend = breinActivity.getConfig()?.getResendFailedActivities()
// add for resending later..
if canResend == true {
if let data = data, let dataString = String(data: data, encoding: .utf8) {
BreinLogger.shared.log("Breinify response data string: \(dataString)")
let urlRequest = url
let creationTime = Int(NSDate().timeIntervalSince1970)
// add to BreinRequestManager in case of an error
BreinRequestManager.shared.addMissedRequest(timeStamp: creationTime,
fullUrl: urlRequest, json: dataString)
}
}
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for lookups
- parameter breinLookup: lookup object
- parameter success success: will be invoked in case of success
- parameter failure failure: will be invoked in case of an error
*/
public func doLookup(_ breinLookup: BreinLookup,
success: @escaping apiSuccess,
failure: @escaping apiFailure) throws {
try validate(breinLookup)
let url = try getFullyQualifiedUrl(breinLookup)
let body = try getRequestBody(breinLookup)
var jsonString = ""
var jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: body as Any, options: [.prettyPrinted])
jsonString = String(data: jsonData, encoding: .utf8) ?? ""
BreinLogger.shared.log("Breinify doLookup - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doLookup with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for recommendations
- parameter breinRecommendation: recommendation object
- parameter success: will be invoked in case of success
- parameter failure: will be invoked in case of an error
*/
public func doRecommendation(_ breinRecommendation: BreinRecommendation,
success: @escaping (_ result: BreinResult) -> Void,
failure: @escaping (_ error: NSDictionary) -> Void) throws {
try validate(breinRecommendation)
let url = try getFullyQualifiedUrl(breinRecommendation)
let body = try getRequestBody(breinRecommendation)
var jsonData:Data
do {
jsonData = try! JSONSerialization.data(withJSONObject: body as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
BreinLogger.shared.log("Breinify doRecommendation - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doRecommendation with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for temporalData
- parameter breinTemporalData: temporalData object
- parameter success successBlock: will be invoked in case of success
- parameter failure failureBlock: will be invoked in case of an error
*/
public func doTemporalDataRequest(_ breinTemporalData: BreinTemporalData,
success successBlock: @escaping apiSuccess,
failure failureBlock: @escaping apiFailure) throws {
try validate(breinTemporalData)
let url = try getFullyQualifiedUrl(breinTemporalData)
let body = try getRequestBody(breinTemporalData)
var jsonData:Data
do {
jsonData = try! JSONSerialization.data(withJSONObject: body as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
BreinLogger.shared.log("Breinify doTemporalDataRequest - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doTemporalDataRequest with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failureBlock(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
successBlock(breinResult)
}
}
}
task.resume()
}
/// Terminates whatever would need to be stopped
public func terminate() {
}
}
| mit | a4459af0cdd93405ec71acc85fb1b7d8 | 39.5 | 136 | 0.577656 | 5.143865 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Protocols/Designable/SideImageDesignable.swift | 3 | 3158 | //
// Created by Jake Lin on 12/8/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
/// Protocol for designing side image
public protocol SideImageDesignable: class {
/**
* The left image
*/
var leftImage: UIImage? { get set }
/**
* Left padding of the left image, default value is CGFloat.nan
*/
var leftImageLeftPadding: CGFloat { get set }
/**
* Right padding of the left image, default value is CGFloat.nan
*/
var leftImageRightPadding: CGFloat { get set }
/**
* Top padding of the left image, default value is CGFloat.nan
*/
var leftImageTopPadding: CGFloat { get set }
/**
* The right image
*/
var rightImage: UIImage? { get set }
/**
* Left padding of the right image, default value is CGFloat.nan
*/
var rightImageLeftPadding: CGFloat { get set }
/**
* Right padding of the right image, default value is CGFloat.nan
*/
var rightImageRightPadding: CGFloat { get set }
/**
* Top padding of the right image, default value is CGFloat.nan
*/
var rightImageTopPadding: CGFloat { get set }
}
public extension SideImageDesignable where Self: UITextField {
public func configureImages() {
configureLeftImage()
configureRightImage()
}
}
fileprivate extension SideImageDesignable where Self: UITextField {
func configureLeftImage() {
guard let leftImage = leftImage else {
return
}
let sideView = makeSideView(with: leftImage,
leftPadding: leftImageLeftPadding,
rightPadding: leftImageRightPadding,
topPadding: leftImageTopPadding)
leftViewMode = .always
leftView = sideView
}
func configureRightImage() {
guard let rightImage = rightImage else {
return
}
let sideView = makeSideView(with: rightImage,
leftPadding: rightImageLeftPadding,
rightPadding: rightImageRightPadding,
topPadding: rightImageTopPadding)
rightViewMode = .always
rightView = sideView
}
func makeSideView(with image: UIImage, leftPadding: CGFloat, rightPadding: CGFloat, topPadding: CGFloat) -> UIView {
let imageView = UIImageView(image: image)
// If not set, use 0 as default value
var leftPaddingValue: CGFloat = 0.0
if !leftPadding.isNaN {
leftPaddingValue = leftPadding
}
// If not set, use 0 as default value
var rightPaddingValue: CGFloat = 0.0
if !rightPadding.isNaN {
rightPaddingValue = rightPadding
}
// If does not specify `topPadding`, then center it in the middle
if topPadding.isNaN {
imageView.frame.origin = CGPoint(x: leftPaddingValue, y: (bounds.height - imageView.bounds.height) / 2)
} else {
imageView.frame.origin = CGPoint(x: leftPaddingValue, y: topPadding)
}
let padding = rightPaddingValue + imageView.bounds.size.width + leftPaddingValue
let sideView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: bounds.height))
sideView.addSubview(imageView)
return sideView
}
}
| mit | 7395fb4fb43ac1a34d98039c655c8bac | 27.1875 | 118 | 0.653152 | 4.726048 | false | false | false | false |
WilliamHester/Breadit-iOS | Breadit/ViewControllers/GifViewController.swift | 1 | 1809 | //
// PreviewViewController.swift
// Breadit
//
// Created by William Hester on 5/30/16.
// Copyright © 2016 William Hester. All rights reserved.
//
import UIKit
import Alamofire
import FLAnimatedImage
class GifViewController: UIViewController {
var imageUrl: String!
private var imageView: FLAnimatedImageView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
imageView = FLAnimatedImageView()
view.addSubview(imageView)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
view.addGestureRecognizer(tapRecognizer)
Alamofire.request(.GET, imageUrl).responseData { response in
let image = FLAnimatedImage(animatedGIFData: response.data)
self.fixFrame(image.size)
self.imageView.animatedImage = image
self.imageView.center = self.view.center
}
}
private func fixFrame(imageSize: CGSize) {
var imageFrame = view.frame
let frameSize = imageFrame.size
let frameAspectRatio = frameSize.width / frameSize.height
let imageAspectRatio = imageSize.width / imageSize.height
if frameAspectRatio > imageAspectRatio {
let heightRatio = frameSize.height / imageSize.height
imageFrame.size.width = heightRatio * imageSize.width
} else {
let widthRatio = frameSize.width / imageSize.width
imageFrame.size.height = widthRatio * imageSize.height
}
imageView.frame = imageFrame
}
func onTap(gestureRecognizer: UITapGestureRecognizer) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | 775c2de4d27e2e29b09a5b57851832d5 | 30.172414 | 94 | 0.659292 | 5.397015 | false | false | false | false |
sdduursma/Scenic | Scenic/SceneRetainer.swift | 1 | 551 | import Foundation
class SceneRetainer {
let sceneName: String
let scene: Scene
let children: [SceneRetainer]
init(sceneName: String, scene: Scene, children: [SceneRetainer]) {
self.sceneName = sceneName
self.scene = scene
self.children = children
}
}
extension SceneRetainer {
func sceneRetainer(forSceneName name: String) -> SceneRetainer? {
if sceneName == name {
return self
}
return children.flatMap { $0.sceneRetainer(forSceneName: name) } .first
}
}
| mit | 687f1d63ba1daef3c5b9462581f6ae7d | 20.192308 | 79 | 0.635209 | 4.142857 | false | false | false | false |
eneko/DSAA | Sources/DataStructures/List.swift | 1 | 4186 | //
// List.swift
// DSAA
//
// Created by Eneko Alonso on 2/11/16.
// Copyright © 2016 Eneko Alonso. All rights reserved.
//
/// List is an Abstract Data Type
///
/// Single linked list implementation
class Item<T> {
var value: T
var next: Item<T>?
init(value: T) {
self.value = value
}
}
public struct List<T: Equatable> : Equatable {
var firstItem: Item<T>?
public mutating func append(element: T) {
guard var item = firstItem else {
firstItem = Item<T>(value: element)
return
}
while true {
guard let next = item.next else {
item.next = Item<T>(value: element)
break
}
item = next
}
}
public mutating func insertAt(index: UInt, element: T) {
if index == 0 {
let newItem = Item<T>(value: element)
newItem.next = firstItem
firstItem = newItem
} else if let item = itemAt(index - 1) {
let newItem = Item<T>(value: element)
newItem.next = item.next
item.next = newItem
}
}
public func first() -> T? {
return firstItem?.value
}
public func last() -> T? {
guard var item = firstItem else {
return nil
}
var value: T? = nil
while true {
guard let next = item.next else {
value = item.value
break
}
item = next
}
return value
}
func itemAt(index: UInt) -> Item<T>? {
var current: UInt = 0
var item = firstItem
while current < index {
guard let next = item?.next else {
return nil
}
item = next
current++
}
return item
}
public func elementAt(index: UInt) -> T? {
return itemAt(index)?.value
}
public mutating func removeFirst() -> T? {
let value = firstItem?.value
firstItem = firstItem?.next
return value
}
public mutating func removeLast() -> T? {
if firstItem?.next == nil {
let value = firstItem?.value
firstItem = nil
return value
}
var item = firstItem
var value: T? = nil
while true {
if item?.next?.next == nil {
value = item?.next?.value
item?.next = nil
break
}
item = item?.next
}
return value
}
public mutating func removeAt(index: UInt) -> T? {
if index == 0 {
return removeFirst()
}
let item = itemAt(index - 1)
let value = item?.next?.value
item?.next = item?.next?.next
return value
}
public func count() -> UInt {
guard var item = firstItem else {
return 0
}
var count: UInt = 1
while true {
guard let next = item.next else {
break
}
item = next
count++
}
return count
}
public func isEmpty() -> Bool {
return count() == 0
}
public mutating func reverse() {
guard let item = firstItem else {
return
}
var head = item
while true {
guard let next = item.next else {
firstItem = head
break
}
item.next = next.next
next.next = head
head = next
}
}
public func copy() -> List<T> {
var newList = List<T>()
var item = firstItem
while let value = item?.value {
newList.append(value)
item = item?.next
}
return newList
}
}
public func == <T: Equatable> (lhs: List<T>, rhs: List<T>) -> Bool {
let leftCount = lhs.count()
let rightCount = rhs.count()
if leftCount != rightCount {
return false
}
for i in 0..<leftCount {
if lhs.elementAt(i) != rhs.elementAt(i) {
return false
}
}
return true
}
| mit | 8b54e413c9b3535b20aba6ca578beda0 | 21.621622 | 68 | 0.472401 | 4.534128 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/Scrumdinger/Scrumdinger/Models/ScrumTimer.swift | 1 | 3501 | //
// ScrumTimer.swift
// Scrumdinger
//
// Created by jourhuang on 2021/1/3.
//
import Foundation
class ScrumTimer: ObservableObject {
struct Speaker: Identifiable {
let name: String
var isCompleted: Bool
let id = UUID()
}
@Published var activeSpeaker = ""
@Published var secondsElapsed = 0
@Published var secondsRemaining = 0
@Published var speakers: [Speaker] = []
var lengthInMinutes: Int
var speakerChangedAction: (() -> Void)?
private var timer: Timer?
private var timerStopped = false
private var frequency: TimeInterval { 1.0 / 60.0 }
private var lengthInSeconds: Int { lengthInMinutes * 60 }
private var secondsPerSpeaker: Int {
(lengthInMinutes * 60) / speakers.count
}
private var secondsElapsedForSpeaker: Int = 0
private var speakerIndex: Int = 0
private var speakerText: String {
return "Speaker \(speakerIndex + 1): " + speakers[speakerIndex].name
}
private var startDate: Date?
init(lengthInMinutes: Int = 0, attendees: [String] = []) {
self.lengthInMinutes = lengthInMinutes
self.speakers = attendees.isEmpty ? [Speaker(name: "Player 1", isCompleted: false)] : attendees.map { Speaker(name: $0, isCompleted: false) }
secondsRemaining = lengthInSeconds
activeSpeaker = speakerText
}
func startScrum() {
changeToSpeaker(at: 0)
}
func stopScrum() {
timer?.invalidate()
timer = nil
timerStopped = true
}
func skipSpeaker() {
changeToSpeaker(at: speakerIndex + 1)
}
private func changeToSpeaker(at index: Int) {
if index > 0 {
let previousSpeakerIndex = index - 1
speakers[previousSpeakerIndex].isCompleted = true
}
secondsElapsedForSpeaker = 0
guard index < speakers.count else { return }
speakerIndex = index
activeSpeaker = speakerText
secondsElapsed = index * secondsPerSpeaker
secondsRemaining = lengthInSeconds - secondsElapsed
startDate = Date()
timer = Timer.scheduledTimer(withTimeInterval: frequency, repeats: true) { [weak self] timer in
if let self = self, let startDate = self.startDate {
let secondsElapsed = Date().timeIntervalSince1970 - startDate.timeIntervalSince1970
self.update(secondsElapsed: Int(secondsElapsed))
}
}
}
private func update(secondsElapsed: Int) {
secondsElapsedForSpeaker = secondsElapsed
self.secondsElapsed = secondsPerSpeaker * speakerIndex + secondsElapsedForSpeaker
guard secondsElapsed <= secondsPerSpeaker else {
return
}
secondsRemaining = max(lengthInSeconds - self.secondsElapsed, 0)
guard !timerStopped else { return }
if secondsElapsedForSpeaker >= secondsPerSpeaker {
changeToSpeaker(at: speakerIndex + 1)
speakerChangedAction?()
}
}
func reset(lengthInMinutes: Int, attendees: [String]) {
self.lengthInMinutes = lengthInMinutes
self.speakers = attendees.isEmpty ? [Speaker(name: "Player 1", isCompleted: false)] : attendees.map { Speaker(name: $0, isCompleted: false) }
secondsRemaining = lengthInSeconds
activeSpeaker = speakerText
}
}
extension DailyScrum {
var timer: ScrumTimer {
ScrumTimer(lengthInMinutes: lengthInMinutes, attendees: attendees)
}
}
| mit | b72d3c990fb2132ad4d15d6fa8a7fc7a | 32.342857 | 149 | 0.644102 | 4.668 | false | false | false | false |
tejasranade/KinveyHealth | SportShop/SettingsController.swift | 1 | 1931 | //
// SettingsController.swift
// SportShop
//
// Created by Tejas on 1/31/17.
// Copyright © 2017 Kinvey. All rights reserved.
//
import Foundation
import UIKit
import Kinvey
import FBSDKLoginKit
class SettingsController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var email: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var phoneNumber: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let user = Kinvey.sharedClient.activeUser as? HealthUser {
email.text = user.email
firstName.text = user.firstname
lastName.text = user.lastname
phoneNumber.text = user.phone
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
@IBAction func dismiss(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func save(_ sender: Any) {
if let user = Kinvey.sharedClient.activeUser as? HealthUser{
user.email = email.text
user.firstname = firstName.text
user.lastname = lastName.text
user.phone = phoneNumber.text
//user.save()
}
}
@IBAction func logout(_ sender: Any) {
Kinvey.sharedClient.activeUser?.logout()
self.dismiss(animated:true, completion: nil)
NotificationCenter.default.post(name: Notification.Name("kinveyUserChanged"), object: nil)
// User.login(username: "Guest", password: "kinvey") { user, error in
// if let _ = user {
// NotificationCenter.default.post(name: Notification.Name("kinveyUserChanged"), object: nil)
// self.dismiss(animated:true, completion: nil)
// }
// }
}
}
| apache-2.0 | b20e4cef2adc490778afba31532f9b4a | 29.15625 | 108 | 0.612953 | 4.661836 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ResourceGroupsTaggingAPI/ResourceGroupsTaggingAPI_Error.swift | 1 | 4134 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ResourceGroupsTaggingAPI
public struct ResourceGroupsTaggingAPIErrorType: AWSErrorType {
enum Code: String {
case concurrentModificationException = "ConcurrentModificationException"
case constraintViolationException = "ConstraintViolationException"
case internalServiceException = "InternalServiceException"
case invalidParameterException = "InvalidParameterException"
case paginationTokenExpiredException = "PaginationTokenExpiredException"
case throttledException = "ThrottledException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ResourceGroupsTaggingAPI
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The target of the operation is currently being modified by a different request. Try again later.
public static var concurrentModificationException: Self { .init(.concurrentModificationException) }
/// The request was denied because performing this operation violates a constraint. Some of the reasons in the following list might not apply to this specific operation. You must meet the prerequisites for using tag policies. For information, see Prerequisites and Permissions for Using Tag Policies in the AWS Organizations User Guide. You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) to integrate with AWS Organizations For information, see EnableAWSServiceAccess. You must have a tag policy attached to the organization root, an OU, or an account.
public static var constraintViolationException: Self { .init(.constraintViolationException) }
/// The request processing failed because of an unknown error, exception, or failure. You can retry the request.
public static var internalServiceException: Self { .init(.internalServiceException) }
/// This error indicates one of the following: A parameter is missing. A malformed string was supplied for the request parameter. An out-of-range value was supplied for the request parameter. The target ID is invalid, unsupported, or doesn't exist. You can't access the Amazon S3 bucket for report storage. For more information, see Additional Requirements for Organization-wide Tag Compliance Reports in the AWS Organizations User Guide.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// A PaginationToken is valid for a maximum of 15 minutes. Your request was denied because the specified PaginationToken has expired.
public static var paginationTokenExpiredException: Self { .init(.paginationTokenExpiredException) }
/// The request was denied to limit the frequency of submitted requests.
public static var throttledException: Self { .init(.throttledException) }
}
extension ResourceGroupsTaggingAPIErrorType: Equatable {
public static func == (lhs: ResourceGroupsTaggingAPIErrorType, rhs: ResourceGroupsTaggingAPIErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ResourceGroupsTaggingAPIErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | b106814074876120deb5e4b672f6974e | 56.416667 | 596 | 0.727866 | 5.239544 | false | false | false | false |
xuduo/socket.io-push-ios | source/SocketIOClientSwift/SocketIOClient.swift | 1 | 17018 | //
// SocketIOClient.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 11/23/14.
//
// 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 final class SocketIOClient: NSObject, SocketEngineClient {
public let socketURL: String
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var connectParams: [String: AnyObject]?
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
self.options = options
if socketURL["https://"].matches().count != 0 {
self.options.insertIgnore(.Secure(true))
}
self.socketURL = socketURL["https?://"] ~= ""
for option in options ?? [] {
switch option {
case .ConnectParams(let params):
connectParams = params
case .Reconnects(let reconnects):
self.reconnects = reconnects
case .ReconnectAttempts(let attempts):
reconnectAttempts = attempts
case .ReconnectWait(let wait):
reconnectWait = abs(wait)
case .Nsp(let nsp):
self.nsp = nsp
case .Log(let log):
DefaultSocketLogger.Logger.log = log
case .Logger(let logger):
DefaultSocketLogger.Logger = logger
case .HandleQueue(let queue):
handleQueue = queue
case .ForceNew(let force):
forceNew = force
default:
continue
}
}
self.options.insertIgnore(.Path("/socket.io"))
super.init()
}
/**
Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
If using Swift it's recommended to use `init(var socketURL: String, opts: SocketOptionsDictionary? = nil)`
*/
public convenience init(socketURL: String, options: NSDictionary?) {
self.init(socketURL: socketURL,
options: Set<SocketIOClientOption>.NSDictionaryToSocketOptionsSet(options ?? [:]))
}
deinit {
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
engine?.close()
}
private func addEngine() -> SocketEngine {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
let newEngine = SocketEngine(client: self, url: socketURL, options: options ?? [])
engine = newEngine
return newEngine
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
reconnects = false
didDisconnect("Closed")
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter: Int,
withTimeoutHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket",
type: logType)
return
}
status = .Connecting
if engine == nil || forceNew {
addEngine().open(connectParams)
} else {
engine?.open(connectParams)
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close()
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: [], isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close()
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason: AnyObject) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect() {
close()
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: AnyObject?) {
guard status == .Connected else {return}
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack,
items: (data as? [AnyObject]) ?? (data != nil ? [data!] : []))
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool,
withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
}
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(data, withAck: ack, withSocket: self)
}
}
}
/**
Leaves nsp and goes back to /
*/
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
nsp = "/"
}
}
/**
Joins nsp if it is not /
*/
public func joinNamespace() {
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
if nsp != "/" {
engine?.send("0\(nsp)", withData: [])
}
}
/**
Joins namespace /
*/
public func joinNamespace(namespace: String) {
self.nsp = namespace
joinNamespace()
}
/**
Removes handler(s)
*/
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
public func off(id id: NSUUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter { $0.id != id }
}
/**
Adds a handler for an event.
Returns: A unique id for the handler
*/
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else {return}
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
public func open() {
connect()
}
public func parseSocketMessage(msg: String) {
dispatch_async(parseQueue) {
SocketParser.parseSocketMessage(msg, socket: self)
}
}
public func parseBinaryData(data: NSData) {
dispatch_async(parseQueue) {
SocketParser.parseBinaryData(data, socket: self)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
self.reconnectTimer?.fire()
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt++
connect()
}
}
// Test extensions
extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
}
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
}
}
| mit | 3af12eae4cd5e607fef06779020dbe56 | 31.353612 | 118 | 0.570631 | 4.919919 | false | false | false | false |
yoichitgy/SwinjectMVVMExample_ForBlog | Carthage/Checkouts/Himotoki/Tests/RawRepresentableTest.swift | 3 | 1277 | //
// RawRepresentableTest.swift
// Himotoki
//
// Created by Syo Ikeda on 9/27/15.
// Copyright © 2015 Syo Ikeda. All rights reserved.
//
import XCTest
import Himotoki
enum StringEnum: String {
case A, B, C
}
enum IntEnum: Int {
case Zero, One
}
enum DoubleEnum: Double {
case One = 1.0
case Two = 2.0
}
extension StringEnum: Decodable {}
extension IntEnum: Decodable {}
extension DoubleEnum: Decodable {}
class RawRepresentableTest: XCTestCase {
func testRawRepresentable() {
let JSON: [String: AnyObject] = [
"string_1": "A",
"string_2": "D",
"int_1": 1,
"int_2": 3,
"double_1": 2.0,
"double_2": 4.0,
]
let e: Extractor = try! decode(JSON)
let A: StringEnum? = try? e <| "string_1"
let D: StringEnum? = try? e <| "string_2"
XCTAssert(A == .A)
XCTAssert(D == nil)
let int1: IntEnum? = try? e <| "int_1"
let int3: IntEnum? = try? e <| "int_3"
XCTAssert(int1 == .One)
XCTAssert(int3 == nil)
let double2: DoubleEnum? = try? e <| "double_1"
let double4: DoubleEnum? = try? e <| "double_2"
XCTAssert(double2 == .Two)
XCTAssert(double4 == nil)
}
}
| mit | f43ac5b67a7b6626584d6d6f571aaf86 | 20.627119 | 55 | 0.543103 | 3.411765 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/SegmentedView/SegmentedTabViewController/SegmentedTabViewController.swift | 1 | 3730 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxRelay
import RxSwift
import ToolKit
/// `SegmentedTabViewController` should be a `child` of `SegmentedViewController`.
/// The `UITabBar` is hidden. Upon selecting an index of the `UISegmentedControl`
/// we select the appropriate `UIViewController`. Having a `UITabBarController` gives us
/// lifecycle events that are the same as a `UITabBarController` while using the segmented control.
/// This also gives us the option to include custom transitions.
public final class SegmentedTabViewController: UITabBarController {
// MARK: - Public Properties
let itemIndexSelectedRelay = PublishRelay<(index: Int, animated: Bool)>()
public var segmentedViewControllers: [SegmentedViewScreenViewController] {
items.map(\.viewController)
}
// MARK: - Private Properties
private let items: [SegmentedViewScreenItem]
private let disposeBag = DisposeBag()
// MARK: - Init
required init?(coder: NSCoder) { unimplemented() }
public init(items: [SegmentedViewScreenItem]) {
self.items = items
super.init(nibName: nil, bundle: nil)
}
// MARK: - Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
setViewControllers(
items.map(\.viewController),
animated: false
)
tabBar.isHidden = true
itemIndexSelectedRelay
.map(weak: self) { (self, value) in
(self.viewControllers?[value.index], value.animated)
}
.bindAndCatch(weak: self) { (self, value) in
guard let vc = value.0 else { return }
self.setSelectedViewController(vc, animated: value.1)
}
.disposed(by: disposeBag)
}
private func setSelectedViewController(_ viewController: UIViewController, animated: Bool) {
guard animated else {
selectedViewController = viewController
return
}
guard let fromView = selectedViewController?.view,
let toView = viewController.view,
fromView != toView,
let controllerIndex = viewControllers?.firstIndex(of: viewController)
else {
return
}
let viewSize = fromView.frame
let scrollRight = controllerIndex > selectedIndex
// Avoid UI issues when switching tabs fast
guard fromView.superview?.subviews.contains(toView) == false else {
return
}
fromView.superview?.addSubview(toView)
let screenWidth = view.frame.width
toView.frame = CGRect(
x: scrollRight ? screenWidth : -screenWidth,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
UIView.animate(
withDuration: 0.25,
delay: 0,
options: [.curveEaseOut, .preferredFramesPerSecond60],
animations: {
fromView.frame = CGRect(
x: scrollRight ? -screenWidth : screenWidth,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
toView.frame = CGRect(
x: 0,
y: viewSize.origin.y,
width: screenWidth,
height: viewSize.size.height
)
},
completion: { [weak self] finished in
if finished {
fromView.removeFromSuperview()
self?.selectedIndex = controllerIndex
}
}
)
}
}
| lgpl-3.0 | ec14eace0e8950dbeb747fa44d225783 | 32 | 99 | 0.583266 | 5.43586 | false | false | false | false |
rahulnadella/CalculationUtility | src/CalculationUtility.swift | 1 | 46741 | /*
The MIT License (MIT)
Copyright (c) 2015 Rahul Nadella http://github.com/rahulnadella
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import CoreGraphics
import Foundation
/*
The NumericType protocol has the common requirements for types that support
arithmetic operators that take numerical values (either literals or variables)
as their operands and return a single numerical value. The standard arithmetic
operators are addition (+), subtraction (-), multiplication (*), and division (/).
:version 1.0
*/
protocol NumericType
{
/*
Add `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func +(lhs: Self, rhs: Self) -> Self
/*
Subtract `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func -(lhs: Self, rhs: Self) -> Self
/*
Multiply `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func *(lhs: Self, rhs: Self) -> Self
/*
Divide `lhs` and `rhs`, returns a result and trapping in case of
arithmetic overflow.
*/
func /(lhs: Self, rhs: Self) -> Self
/*
Divide `lhs` and `rhs`, returns the remainder and trapping in case of
arithmetic overflow.
*/
func %(lhs: Self, rhs: Self) -> Self
/*
`lhs` is less than 'rhs' returns true otherwise false
*/
func <(lhs: Self, rhs: Self) -> Bool
/*
`lhs` is greater than 'rhs' returns true otherwise false
*/
func >(lhs: Self, rhs: Self) -> Bool
/*
Initializer for NumericType that currently takes not arguments
*/
init()
}
/*
All of the numeric types already implement these, but at this point the compiler
doesn’t know that they conform to the new NumericType protocol. This done through
an Extension (in Swift also known as a Category in Objective-C).
Apple calls this “declaring protocol adoption with an extension.”
*/
extension Double : NumericType {}
extension Float : NumericType {}
extension Int : NumericType {}
extension Int8 : NumericType {}
extension Int16 : NumericType {}
extension Int32 : NumericType {}
extension Int64 : NumericType {}
extension UInt : NumericType {}
extension UInt8 : NumericType {}
extension UInt16 : NumericType {}
extension UInt32 : NumericType {}
extension UInt64 : NumericType {}
//MARK: ###########################Summation Functions###########################
/* The SUMMATION Prefix (similiar to ++counter) */
prefix operator ∑ {}
/*
The prefix of the sum function using an Array.
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
prefix func ∑<T: NumericType>(input: [T]) -> T
{
return sumOf(input)
}
/*
The prefix of the sum function using a specific section of MutableCollectionType
:param T
The MutableCollectionType (Array, etc.) of specific NumericType
(using the NumericType protocol as a generic constraint, and call
it with any numeric type we like for instance, Double, Float, Int, etc.)
*/
prefix func ∑<T: NumericType>(input : ArraySlice<T>) -> T
{
return sumOf(input)
}
/*
The sumOf function using variable arguments of specific NumericType (Double, Float, Int, etc.).
:param T
The variable arguments of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func sumOf<T: NumericType>(input : T...) -> T
{
return sumOf(input)
}
/*
The sumOf function using MutableCollectionType (for instance, Array, Set, etc.) of specific
NumericType (Double, Float, Int, etc.).
:param T
The MutableCollectionType of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.))
*/
func sumOf<T: NumericType>(input : ArraySlice<T>) -> T
{
return sumOf([] + input)
}
/*
The sumOf function of the array of specific NumericType (Double, Float, Int, etc.).
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func sumOf<T: NumericType>(input : [T]) -> T
{
return reduce(input, T()) {$0 + $1}
}
//MARK: ################################Factorial################################
/* The FACTORIAL Postfix (similiar to counter++) */
postfix operator ~! {}
/*
The prefix of the factorial function using an IntegerType.
:param T
The specific Integer (greater than 0) value used to calculate the factorial value
:return The factorial of a positive Integer greater than 1
*/
postfix public func ~! <T: IntegerType>(var num: T) -> T
{
assert(num > 0, "Factorial function can not receive a number less than 1")
var result: T = 1
while (num > 1)
{
result = result * num
num--
}
return result
}
//MARK: ###########################Multiplication Functions###########################
/* The MULTIPLY Prefix (similiar to ++counter) */
prefix operator ∏ {}
/*
The prefix of the multiply function using an Array.
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
prefix func ∏<T: NumericType>(input: [T]) -> T
{
return productOf(input)
}
/*
The prefix of the multiply function using a specific section of MutableCollectionType
:param T
The MutableCollectionType (Array, etc.) of specific NumericType
(using the NumericType protocol as a generic constraint, and call
it with any numeric type we like for instance, Double, Float, Int, etc.)
*/
prefix func ∏<T: NumericType>(input : ArraySlice<T>) -> T
{
return productOf(input)
}
/*
The productOf function using variable arguments of specific NumericType (Double, Float, Int, etc.).
:param T
The variable arguments of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func productOf<T: NumericType>(input : T...) -> T
{
return productOf(input)
}
/*
The productOf function using MutableCollectionType (for instance, Array, Set, etc.) of specific
NumericType (Double, Float, Int, etc.).
:param T
The MutableCollectionType of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.))
*/
func productOf<T: NumericType>(input : ArraySlice<T>) -> T
{
return productOf([] + input)
}
/*
The productOf function of the array of specific NumericType (Double, Float, Int, etc.).
:param T
The Array of specific NumericType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func productOf<T: NumericType>(var input : [T]) -> T
{
return input.count == 0 ? T() : reduce(input[1..<input.count], input[0]) {$0 * $1}
}
//MARK: ###########Additional Functions for Calculated Numerical Values###########
/*
The squared function returns a NumericType² (n² = n x n)
:param T
The specific NumberType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func squared<T : NumericType>(number: T) -> T
{
/* Uses * Operator */
return number * number
}
/*
The cubic function returns a NumericType³ (n³ = n × n × n).
:param T
The specific NumberType (using the NumericType protocol as a
generic constraint, and call it with any numeric type we like for instance,
Double, Float, Int, etc.)
*/
func cubed<T : NumericType>(number : T) -> T
{
return number * number * number
}
/*
The min function returns the minimum value within the Collection
:param T
The Collection consisting of specific values
*/
func min<T : Comparable> (input : [T]) -> T
{
return reduce(input, input[0]) {$0 > $1 ? $1 : $0}
}
/*
The max function returns the maximum value within the Collection
:param T
The Collection consisting of specific values
*/
func max<T : Comparable> (input : [T]) -> T
{
return reduce(input, input[0]) {$0 < $1 ? $1 : $0}
}
//MARK: ####################Explicit Addition (+) Cast Functions####################
/*
The + function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Integer value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Integer value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: Int) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Integer value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func +(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Integer value
:return An explicitly cast Float value
*/
func +(lhs: Float, rhs: Int) -> Float
{
return lhs + Float(rhs)
}
/*
The + function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: Float) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func +(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func +(lhs: Double, rhs: UInt) -> Double
{
return lhs + Double(rhs)
}
/*
The + function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func +(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) + rhs
}
/*
The + function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func +(lhs: Float, rhs: UInt) -> Float
{
return lhs + Float(rhs)
}
//MARK: ####################Explicit Subtraction (-) Cast Functions####################
/*
The - function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Integer value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Integer value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: Int) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func -(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func -(lhs: Float, rhs: Int) -> Float
{
return lhs - Float(rhs)
}
/*
The - function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: Float) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func -(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func -(lhs: Double, rhs: UInt) -> Double
{
return lhs - Double(rhs)
}
/*
The - function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func -(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) - rhs
}
/*
The - function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func -(lhs: Float, rhs: UInt) -> Float
{
return lhs - Float(rhs)
}
//MARK: ####################Explicit Multiplication (*) Cast Functions####################
/*
The * function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: Int) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func *(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func *(lhs: Float, rhs: Int) -> Float
{
return lhs * Float(rhs)
}
/*
The * function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: Float) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func *(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func *(lhs: Double, rhs: UInt) -> Double
{
return lhs * Double(rhs)
}
/*
The * function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func *(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) * rhs
}
/*
The * function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func *(lhs: Float, rhs: UInt) -> Float
{
return lhs * Float(rhs)
}
//MARK: ####################Explicit Division (/) Cast Functions####################
/*
The / function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: Int) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func /(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func /(lhs: Float, rhs: Int) -> Float
{
return lhs / Float(rhs)
}
/*
The / function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: Float) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func /(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func /(lhs: Double, rhs: UInt) -> Double
{
return lhs / Double(rhs)
}
/*
The / function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func /(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) / rhs
}
/*
The / function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func /(lhs: Float, rhs: UInt) -> Float
{
return lhs / Float(rhs)
}
//MARK: ####################Explicit Modulus (%) Cast Functions####################
/*
The % function overloaded to take the parameters of Int,Double and return
an explicit conversion of a Double.
:param lhs
The Int value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: Int, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,Int and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Int value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: Int) -> Double
{
return lhs % Double(rhs)
}
/*
The % function overloaded to take the parameters of Int,Float and return
an explicit conversion of a Float.
:param lhs
The Int value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func %(lhs: Int, rhs: Float) -> Float
{
return Float(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Float,Int and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The Int value
:return An explicitly cast Float value
*/
func %(lhs: Float, rhs: Int) -> Float
{
return lhs % Float(rhs)
}
/*
The % function overloaded to take the parameters of Float,Double and return
an explicit conversion of a Double.
:param lhs
The Float value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: Float, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,Float and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The Float value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: Float) -> Double
{
return lhs % Float(rhs)
}
/*
The % function overloaded to take the parameters of UInt,Double and return
an explicit conversion of a Double.
:param lhs
The UInt value
:param rhs
The Double value
:return An explicitly cast Double value
*/
func %(lhs: UInt, rhs: Double) -> Double
{
return Double(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Double,UInt and return
an explicit conversion of a Double.
:param lhs
The Double value
:param rhs
The UInt value
:return An explicitly cast Double value
*/
func %(lhs: Double, rhs: UInt) -> Double
{
return lhs % Double(rhs)
}
/*
The % function overloaded to take the parameters of UInt,Float and return
an explicit conversion of a Float.
:param lhs
The UInt value
:param rhs
The Float value
:return An explicitly cast Float value
*/
func %(lhs: UInt, rhs: Float) -> Float
{
return Float(lhs) % rhs
}
/*
The % function overloaded to take the parameters of Float,UInt and return
an explicit conversion of a Float.
:param lhs
The Float value
:param rhs
The UInt value
:return An explicitly cast Float value
*/
func %(lhs: Float, rhs: UInt) -> Float
{
return lhs % Float(rhs)
}
//MARK: ####################Explicit Less Than (<) Cast Functions####################
/*
The < function overloaded to take the parameters of Int,Double and return
a Boolean value to indicate a true (if Int is less than Double) otherwise
false (Double greater than Int)
:param lhs
The Int value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (Int less than Double) otherwise false
*/
func <(lhs: Int, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,Int and return
a Boolean value to indicate a true (if Double is less than Int) otherwise
false (Int greater than Double)
:param lhs
The Double value
:param rhs
The Int value
:return An explicit cast less than Boolean value of true (Double less than Int) otherwise false
*/
func <(lhs: Double, rhs: Int) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of Int,Float and return
a Boolean value to indicate a true (if Int is less than Float) otherwise
false (Float greater than Int)
:param lhs
The Int value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (Int less than Float) otherwise false
*/
func <(lhs: Int, rhs: Float) -> Bool
{
return Float(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Float,Int and return
a Boolean value to indicate a true (if Float is less than Int) otherwise
false (Int greater than Float)
:param lhs
The Float value
:param rhs
The Int value
:return An explicit cast less than Boolean value of true (Float less than Int) otherwise false
*/
func <(lhs: Float, rhs: Int) -> Bool
{
return lhs < Float(rhs)
}
/*
The < function overloaded to take the parameters of Float,Double and return
a Boolean value to indicate a true (if Float is less than Double) otherwise
false (Double greater than Float)
:param lhs
The Float value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (Float less than Double) otherwise false
*/
func <(lhs: Float, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,Float and return
a Boolean value to indicate a true (if Double is less than Float) otherwise
false (Float greater than Double)
:param lhs
The Double value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (Double less than Float) otherwise false
*/
func <(lhs: Double, rhs: Float) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of UInt,Double and return
a Boolean value to indicate a true (if UInt is less than Double) otherwise
false (Double greater than UInt)
:param lhs
The UInt value
:param rhs
The Double value
:return An explicit cast less than Boolean value of true (UInt less than Double) otherwise false
*/
func <(lhs: UInt, rhs: Double) -> Bool
{
return Double(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Double,UInt and return
a Boolean value to indicate a true (if Double is less than UInt) otherwise
false (UInt greater than Double)
:param lhs
The Double value
:param rhs
The UInt value
:return An explicit cast less than Boolean value of true (Double less than UInt) otherwise false
*/
func <(lhs: Double, rhs: UInt) -> Bool
{
return lhs < Double(rhs)
}
/*
The < function overloaded to take the parameters of UInt,Float and return
a Boolean value to indicate a true (if UInt is less than Float) otherwise
false (Float greater than UInt)
:param lhs
The UInt value
:param rhs
The Float value
:return An explicit cast less than Boolean value of true (UInt less than Float) otherwise false
*/
func <(lhs: UInt, rhs:Float) -> Bool
{
return Float(lhs) < rhs
}
/*
The < function overloaded to take the parameters of Float,UInt and return
a Boolean value to indicate a true (if Float is less than UInt) otherwise
false (UInt greater than Float)
:param lhs
The Float value
:param rhs
The UInt value
:return An explicit cast less than Boolean value of true (Float less than UInt) otherwise false
*/
func <(lhs: Float, rhs:UInt) -> Bool
{
return lhs < Float(rhs)
}
//MARK: ####################Explicit Greater Than (>) Cast Functions####################
/*
The > function overloaded to take the parameters of Int,Double and return
a Boolean value to indicate a true (if Int is greater than Double) otherwise
false (Double less than Int)
:param lhs
The Int value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (Int greater than Double) otherwise false
*/
func >(lhs: Int, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,Int and return
a Boolean value to indicate a true (if Double is greater than Int) otherwise
false (Int less than Double)
:param lhs
The Double value
:param rhs
The Int value
:return An explicit cast greater than Boolean value of true (Double greater than Int) otherwise false
*/
func >(lhs: Double, rhs: Int) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of Int,Float and return
a Boolean value to indicate a true (if Int is greater than Float) otherwise
false (Float less than Int)
:param lhs
The Int value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (Int greater than Float) otherwise false
*/
func >(lhs: Int, rhs: Float) -> Bool
{
return Float(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Float,Int and return
a Boolean value to indicate a true (if Float is greater than Int) otherwise
false (Int less than Float)
:param lhs
The Float value
:param rhs
The Int value
:return An explicit cast greater than Boolean value of true (Float greater than Int) otherwise false
*/
func >(lhs: Float, rhs: Int) -> Bool
{
return lhs > Float(rhs)
}
/*
The > function overloaded to take the parameters of Float,Double and return
a Boolean value to indicate a true (if Float is greater than Double) otherwise
false (Double less than Float)
:param lhs
The Float value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (Float greater than Double) otherwise false
*/
func >(lhs: Float, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,Float and return
a Boolean value to indicate a true (if Double is greater than Float) otherwise
false (Float less than Double)
:param lhs
The Double value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (Double greater than Float) otherwise false
*/
func >(lhs: Double, rhs: Float) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of UInt,Double and return
a Boolean value to indicate a true (if UInt is greater than Double) otherwise
false (Double less than UInt)
:param lhs
The UInt value
:param rhs
The Double value
:return An explicit cast greater than Boolean value of true (UInt greater than Double) otherwise false
*/
func >(lhs: UInt, rhs: Double) -> Bool
{
return Double(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Double,UInt and return
a Boolean value to indicate a true (if Double is greater than UInt) otherwise
false (UInt less than Double)
:param lhs
The Double value
:param rhs
The UInt value
:return An explicit cast greater than Boolean value of true (Double greater than UInt) otherwise false
*/
func >(lhs: Double, rhs: UInt) -> Bool
{
return lhs > Double(rhs)
}
/*
The > function overloaded to take the parameters of UInt,Float and return
a Boolean value to indicate a true (if UInt is greater than Float) otherwise
false (Float less than UInt)
:param lhs
The UInt value
:param rhs
The Float value
:return An explicit cast greater than Boolean value of true (UInt greater than Float) otherwise false
*/
func >(lhs: UInt, rhs:Float) -> Bool
{
return Float(lhs) > rhs
}
/*
The > function overloaded to take the parameters of Float,UInt and return
a Boolean value to indicate a true (if Float is greater than UInt) otherwise
false (UInt less than Float)
:param lhs
The Float value
:param rhs
The UInt value
:return An explicit cast greater than Boolean value of true (Float greater than UInt) otherwise false
*/
func >(lhs: Float, rhs:UInt) -> Bool
{
return lhs > Float(rhs)
}
//MARK: ##################Explicit CGFloat Addition (+) Cast Functions##################
/*
The + function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
/*
The + function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func +(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs + CGFloat(rhs)
}
/*
The + function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func +(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) + rhs
}
//MARK: ##################Explicit CGFloat Subtraction (-) Cast Functions##################
/*
The - function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
/*
The - function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func -(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs - CGFloat(rhs)
}
/*
The - function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func -(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) - rhs
}
//MARK: ##################Explicit CGFloat Multiplication (*) Cast Functions##################
/*
The * function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
/*
The * function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func *(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs * CGFloat(rhs)
}
/*
The * function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func *(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) * rhs
}
//MARK: ##################Explicit CGFloat Division (/) Cast Functions##################
/*
The / function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
/*
The / function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func /(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs / CGFloat(rhs)
}
/*
The / function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func /(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) / rhs
}
//MARK: ##################Explicit CGFloat Modulus (%) Cast Functions##################
/*
The % function overloaded to take the parameters of CGFloat,Float and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Float value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Float) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Float,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Float value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Float, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,Double and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Double value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Double) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Double,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Double value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Double, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,Int and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The Int value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: Int) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of Int,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The Int value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: Int, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
}
/*
The % function overloaded to take the parameters of CGFloat,UInt and return
an explicit conversion of a CGFloat.
:param lhs
The CGFloat value
:param rhs
The UInt value
:return An explicitly cast CGFloat value
*/
func %(lhs: CGFloat, rhs: UInt) -> CGFloat
{
return lhs % CGFloat(rhs)
}
/*
The % function overloaded to take the parameters of UInt,CGFloat and return
an explicit conversion of a CGFloat.
:param lhs
The UInt value
:param rhs
The CGFloat value
:return An explicitly cast CGFloat value
*/
func %(lhs: UInt, rhs: CGFloat) -> CGFloat
{
return CGFloat(lhs) % rhs
} | mit | 88a26c0e60aa1e4ef5718ce6eaed14ca | 22.300748 | 103 | 0.687587 | 4.019012 | false | false | false | false |
scalessec/Toast-Swift | Example/ViewController.swift | 1 | 9630 | //
// ViewController.swift
// Toast-Swift
//
// Copyright (c) 2015-2019 Charles Scalesse.
//
// 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 ViewController: UITableViewController {
fileprivate var showingActivity = false
fileprivate struct ReuseIdentifiers {
static let switchCellId = "switchCell"
static let exampleCellId = "exampleCell"
}
// MARK: - Constructors
override init(style: UITableView.Style) {
super.init(style: style)
self.title = "Toast-Swift"
}
required init?(coder aDecoder: NSCoder) {
fatalError("not used")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ReuseIdentifiers.exampleCellId)
}
// MARK: - Events
@objc
private func handleTapToDismissToggled() {
ToastManager.shared.isTapToDismissEnabled = !ToastManager.shared.isTapToDismissEnabled
}
@objc
private func handleQueueToggled() {
ToastManager.shared.isQueueEnabled = !ToastManager.shared.isQueueEnabled
}
}
// MARK: - UITableViewDelegate & DataSource Methods
extension ViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 11
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "SETTINGS"
} else {
return "EXAMPLES"
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
var cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.switchCellId)
if indexPath.row == 0 {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let tapToDismissSwitch = UISwitch()
tapToDismissSwitch.onTintColor = .darkBlue
tapToDismissSwitch.isOn = ToastManager.shared.isTapToDismissEnabled
tapToDismissSwitch.addTarget(self, action: #selector(ViewController.handleTapToDismissToggled), for: .valueChanged)
cell?.accessoryView = tapToDismissSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Tap to dismiss"
} else {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let queueSwitch = UISwitch()
queueSwitch.onTintColor = .darkBlue
queueSwitch.isOn = ToastManager.shared.isQueueEnabled
queueSwitch.addTarget(self, action: #selector(ViewController.handleQueueToggled), for: .valueChanged)
cell?.accessoryView = queueSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Queue toast"
}
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.exampleCellId, for: indexPath)
cell.textLabel?.numberOfLines = 2
cell.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
cell.accessoryType = .disclosureIndicator
switch indexPath.row {
case 0: cell.textLabel?.text = "Make toast"
case 1: cell.textLabel?.text = "Make toast on top for 3 seconds"
case 2: cell.textLabel?.text = "Make toast with a title"
case 3: cell.textLabel?.text = "Make toast with an image"
case 4: cell.textLabel?.text = "Make toast with a title, image, and completion closure"
case 5: cell.textLabel?.text = "Make toast with a custom style"
case 6: cell.textLabel?.text = "Show a custom view as toast"
case 7: cell.textLabel?.text = "Show an image as toast at point\n(110, 110)"
case 8: cell.textLabel?.text = showingActivity ? "Hide toast activity" : "Show toast activity"
case 9: cell.textLabel?.text = "Hide toast"
case 10: cell.textLabel?.text = "Hide all toasts"
default: cell.textLabel?.text = nil
}
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section > 0 else { return }
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
// Make Toast
self.navigationController?.view.makeToast("This is a piece of toast")
case 1:
// Make toast with a duration and position
self.navigationController?.view.makeToast("This is a piece of toast on top for 3 seconds", duration: 3.0, position: .top)
case 2:
// Make toast with a title
self.navigationController?.view.makeToast("This is a piece of toast with a title", duration: 2.0, position: .top, title: "Toast Title", image: nil)
case 3:
// Make toast with an image
self.navigationController?.view.makeToast("This is a piece of toast with an image", duration: 2.0, position: .center, title: nil, image: UIImage(named: "toast.png"))
case 4:
// Make toast with an image, title, and completion closure
self.navigationController?.view.makeToast("This is a piece of toast with a title, image, and completion closure", duration: 2.0, position: .bottom, title: "Toast Title", image: UIImage(named: "toast.png")) { didTap in
if didTap {
print("completion from tap")
} else {
print("completion without tap")
}
}
case 5:
// Make toast with a custom style
var style = ToastStyle()
style.messageFont = UIFont(name: "Zapfino", size: 14.0)!
style.messageColor = UIColor.red
style.messageAlignment = .center
style.backgroundColor = UIColor.yellow
self.navigationController?.view.makeToast("This is a piece of toast with a custom style", duration: 3.0, position: .bottom, style: style)
case 6:
// Show a custom view as toast
let customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 400.0))
customView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
customView.backgroundColor = .lightBlue
self.navigationController?.view.showToast(customView, duration: 2.0, position: .center)
case 7:
// Show an image view as toast, on center at point (110,110)
let toastView = UIImageView(image: UIImage(named: "toast.png"))
self.navigationController?.view.showToast(toastView, duration: 2.0, point: CGPoint(x: 110.0, y: 110.0))
case 8:
// Make toast activity
if !showingActivity {
self.navigationController?.view.makeToastActivity(.center)
} else {
self.navigationController?.view.hideToastActivity()
}
showingActivity.toggle()
tableView.reloadData()
case 9:
// Hide toast
self.navigationController?.view.hideToast()
case 10:
// Hide all toasts
self.navigationController?.view.hideAllToasts()
default:
break
}
}
}
| mit | 01ba67aa131ae02cbafd82971145b4f0 | 41.610619 | 229 | 0.609553 | 5.015625 | false | false | false | false |
soffes/Static | Sources/Static/Row.swift | 1 | 6164 | import UIKit
/// Row or Accessory selection callback.
public typealias Selection = () -> Void
public typealias ValueChange = (Bool) -> ()
public typealias SegmentedControlValueChange = (Int, Any?) -> ()
/// Representation of a table row.
public struct Row: Hashable, Equatable {
// MARK: - Types
/// Representation of a row accessory.
public enum Accessory: Equatable {
/// No accessory
case none
/// Chevron
case disclosureIndicator
/// Info button with chevron. Handles selection.
case detailDisclosureButton(Selection)
/// Checkmark
case checkmark
/// Checkmark Placeholder.
/// Allows spacing to continue to work when switching back & forth between checked states.
case checkmarkPlaceholder
/// Info button. Handles selection.
case detailButton(Selection)
/// Switch. Handles value change.
case switchToggle(value: Bool, ValueChange)
/// Segmented control. Handles value change.
case segmentedControl(items: [Any], selectedIndex: Int, SegmentedControlValueChange)
/// Custom view
case view(UIView)
/// Table view cell accessory type
public var type: UITableViewCell.AccessoryType {
switch self {
case .disclosureIndicator: return .disclosureIndicator
case .detailDisclosureButton(_): return .detailDisclosureButton
case .checkmark: return .checkmark
case .detailButton(_): return .detailButton
default: return .none
}
}
/// Accessory view
public var view: UIView? {
switch self {
case .view(let view): return view
case .switchToggle(let value, let valueChange):
return SwitchAccessory(initialValue: value, valueChange: valueChange)
case .checkmarkPlaceholder:
return UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
case .segmentedControl(let items, let selectedIndex, let valueChange):
return SegmentedControlAccessory(items: items, selectedIndex: selectedIndex, valueChange: valueChange)
default: return nil
}
}
/// Selection block for accessory buttons
public var selection: Selection? {
switch self {
case .detailDisclosureButton(let selection): return selection
case .detailButton(let selection): return selection
default: return nil
}
}
}
public typealias Context = [String: Any]
public typealias EditActionSelection = (IndexPath) -> ()
/// Representation of an editing action, when swiping to edit a cell.
public struct EditAction {
/// Title of the action's button.
public let title: String
/// Styling for button's action, used primarily for destructive actions.
public let style: UITableViewRowAction.Style
/// Background color of the button.
public let backgroundColor: UIColor?
/// Visual effect to be applied to the button's background.
public let backgroundEffect: UIVisualEffect?
/// Invoked when selecting the action.
public let selection: EditActionSelection?
public init(title: String, style: UITableViewRowAction.Style = .default, backgroundColor: UIColor? = nil, backgroundEffect: UIVisualEffect? = nil, selection: EditActionSelection? = nil) {
self.title = title
self.style = style
self.backgroundColor = backgroundColor
self.backgroundEffect = backgroundEffect
self.selection = selection
}
}
// MARK: - Properties
/// The row's accessibility identifier.
public var accessibilityIdentifier: String?
/// Unique identifier for the row.
public let uuid: String
/// The row's primary text.
public var text: String?
/// The row's secondary text.
public var detailText: String?
/// Accessory for the row.
public var accessory: Accessory
/// Image for the row
public var image: UIImage?
/// Action to run when the row is selected.
public var selection: Selection?
/// View to be used for the row.
public var cellClass: Cell.Type
/// Additional information for the row.
public var context: Context?
/// Actions to show when swiping the cell, such as Delete.
public var editActions: [EditAction]
var canEdit: Bool {
return editActions.count > 0
}
var isSelectable: Bool {
return selection != nil
}
var cellIdentifier: String {
return cellClass.description()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(uuid)
}
// MARK: - Initializers
public init(text: String? = nil, detailText: String? = nil, selection: Selection? = nil,
image: UIImage? = nil, accessory: Accessory = .none, cellClass: Cell.Type? = nil, context: Context? = nil, editActions: [EditAction] = [], uuid: String = UUID().uuidString, accessibilityIdentifier: String? = nil) {
self.accessibilityIdentifier = accessibilityIdentifier
self.uuid = uuid
self.text = text
self.detailText = detailText
self.selection = selection
self.image = image
self.accessory = accessory
self.cellClass = cellClass ?? Value1Cell.self
self.context = context
self.editActions = editActions
}
}
public func ==(lhs: Row, rhs: Row) -> Bool {
return lhs.uuid == rhs.uuid
}
public func ==(lhs: Row.Accessory, rhs: Row.Accessory) -> Bool {
switch (lhs, rhs) {
case (.none, .none): return true
case (.disclosureIndicator, .disclosureIndicator): return true
case (.detailDisclosureButton(_), .detailDisclosureButton(_)): return true
case (.checkmark, .checkmark): return true
case (.detailButton(_), .detailButton(_)): return true
case (.view(let l), .view(let r)): return l == r
default: return false
}
}
| mit | 4b6e7e29ffa8f6b9103d9752f0597ad1 | 31.613757 | 222 | 0.62865 | 5.206081 | false | false | false | false |
lifcio/youtube-app-syncano | youtube-app-syncano/ViewController.swift | 1 | 3770 | //
// ViewController.swift
// youtube-app-syncano
//
// Created by Mariusz Wisniewski on 9/2/15.
// Copyright (c) 2015 Mariusz Wisniewski. All rights reserved.
//
import UIKit
import MediaPlayer
let instanceName = ""
let apiKey = ""
let channelName = "youtube_videos"
class ViewController: UIViewController {
var videos : [Video] = []
let syncano = Syncano.sharedInstanceWithApiKey(apiKey, instanceName: instanceName)
let channel = SCChannel(name: channelName)
@IBOutlet weak var tableView: UITableView!
@IBAction func refreshPressed(sender: UIBarButtonItem) {
self.downloadVideosFromSyncano()
}
override func viewDidLoad() {
super.viewDidLoad()
self.channel.delegate = self
self.channel.subscribeToChannel()
self.downloadVideosFromSyncano()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func removeVideoWithId(objectId: Int?) {
self.videos = self.videos.filter {
return $0.objectId != objectId
}
}
}
//MARK - Syncano
extension ViewController {
func downloadVideosFromSyncano() {
Video.please().giveMeDataObjectsWithCompletion { objects, error in
if let youtubeVideos = objects {
self.videos.removeAll(keepCapacity: true)
for item in youtubeVideos {
if let video = item as? Video {
self.videos.append(video)
}
}
self.tableView.reloadData()
}
}
}
}
//MARK - SCChannelDelegate
extension ViewController : SCChannelDelegate {
func chanellDidReceivedNotificationMessage(notificationMessage: SCChannelNotificationMessage!) {
switch(notificationMessage.action) {
case .Create:
let video = Video.fromDictionary(notificationMessage.payload)
self.videos += [video]
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: (self.videos.count - 1), inSection: 0), atScrollPosition: .Bottom, animated: true)
break
case .Delete:
self.removeVideoWithId(notificationMessage.payload["id"] as! Int?)
self.tableView.reloadData()
break
case .Update:
break
default:
break
}
}
}
//MARK - UITableViewDelegate
extension ViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let sourceId = self.videos[indexPath.row].sourceId {
let videoPlayerViewController = XCDYouTubeVideoPlayerViewController(videoIdentifier: sourceId)
self.presentMoviePlayerViewControllerAnimated(videoPlayerViewController)
}
}
}
//MARK - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.videos.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! UITableViewCell?
if (cell == nil) {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: identifier)
}
cell?.textLabel?.text = videos[indexPath.row].title
cell?.detailTextLabel?.text = videos[indexPath.row].videoDescription
return cell!
}
}
| mit | 554c5772da0a7e608693361e952e99d4 | 31.222222 | 152 | 0.649602 | 5.122283 | false | false | false | false |
yosan/AwsChat | AwsChat/AppDelegate.swift | 1 | 3792 | //
// AppDelegate.swift
// AwsChat
//
// Created by Takahashi Yosuke on 2016/07/09.
// Copyright © 2016年 Yosan. All rights reserved.
//
import UIKit
import FBSDKLoginKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
/**
Called when user allows push notification
- parameter application: application
- parameter notificationSettings: notificationSettings
*/
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}
/**
Called when device token is provided
- parameter application: application
- parameter deviceToken: deviceToken
*/
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = "\(deviceToken)"
.trimmingCharacters(in: CharacterSet(charactersIn:"<>"))
.replacingOccurrences(of: " ", with: "")
let notification = Notification(name: Notification.Name(rawValue: "DeviceTokenUpdated"), object: self, userInfo: ["token" : deviceTokenString])
NotificationCenter.default.post(notification)
}
/**
Called when token registration is failed
- parameter application: application
- parameter error: error
*/
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
let error = error as NSError
print("error: \(error.code), \(error.description)")
// Simulate device token is received for iOS Simulator.
if TARGET_OS_SIMULATOR != 0 {
let dummy = "0000000000000000000000000000000000000000000000000000000000000000"
let notification = Notification(name: Notification.Name(rawValue: "DeviceTokenUpdated"), object: self, userInfo: ["token" : dummy])
NotificationCenter.default.post(notification)
}
}
/**
Called when remote notification is received. (DynamoDB's message table is updated in this case)
- parameter application: application
- parameter userInfo: userInfo
*/
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
let notification = Notification(name: Notification.Name(rawValue: "MessageUpdated"), object: self, userInfo: userInfo)
NotificationCenter.default.post(notification)
}
/**
Call FBSDKAppEvents.activateApp() for Facebool login.
- parameter application: application
*/
func applicationDidBecomeActive(_ application: UIApplication) {
FBSDKAppEvents.activateApp()
}
/**
Call FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) for Facebook login.
- parameter application: application
- parameter url: url
- parameter sourceApplication: sourceApplication
- parameter annotation: annotation
- returns: return value
*/
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
FBSDKProfile.enableUpdates(onAccessTokenChange: true)
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
}
| mit | a708ef88116931f9c7e20fb22c1613a5 | 36.89 | 172 | 0.692267 | 5.874419 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Build/BuildOperationBuildSystemDelegateHandler.swift | 2 | 39444 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2018-2020 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 Dispatch
import Foundation
import LLBuildManifest
import PackageModel
import SPMBuildCore
import SPMLLBuild
import TSCBasic
import class TSCUtility.IndexStore
import class TSCUtility.IndexStoreAPI
import protocol TSCUtility.ProgressAnimationProtocol
#if canImport(llbuildSwift)
typealias LLBuildBuildSystemDelegate = llbuildSwift.BuildSystemDelegate
#else
typealias LLBuildBuildSystemDelegate = llbuild.BuildSystemDelegate
#endif
typealias Diagnostic = TSCBasic.Diagnostic
class CustomLLBuildCommand: SPMLLBuild.ExternalCommand {
let context: BuildExecutionContext
required init(_ context: BuildExecutionContext) {
self.context = context
}
func getSignature(_ command: SPMLLBuild.Command) -> [UInt8] {
return []
}
func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
fatalError("subclass responsibility")
}
}
private extension IndexStore.TestCaseClass.TestMethod {
var allTestsEntry: String {
let baseName = name.hasSuffix("()") ? String(name.dropLast(2)) : name
return "(\"\(baseName)\", \(isAsync ? "asyncTest(\(baseName))" : baseName ))"
}
}
final class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand {
private func write(
tests: [IndexStore.TestCaseClass],
forModule module: String,
to path: AbsolutePath
) throws {
let stream = try LocalFileOutputByteStream(path)
let testsByClassNames = Dictionary(grouping: tests, by: { $0.name }).sorted(by: { $0.key < $1.key })
stream <<< "import XCTest" <<< "\n"
stream <<< "@testable import " <<< module <<< "\n"
for iterator in testsByClassNames {
let className = iterator.key
let testMethods = iterator.value.flatMap{ $0.testMethods }
stream <<< "\n"
stream <<< "fileprivate extension " <<< className <<< " {" <<< "\n"
stream <<< indent(4) <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
// 'className' provides uniqueness for derived class.
stream <<< indent(4) <<< "static let __allTests__\(className) = [" <<< "\n"
for method in testMethods {
stream <<< indent(8) <<< method.allTestsEntry <<< ",\n"
}
stream <<< indent(4) <<< "]" <<< "\n"
stream <<< "}" <<< "\n"
}
stream <<< """
@available(*, deprecated, message: "Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings")
func __\(module)__allTests() -> [XCTestCaseEntry] {
return [\n
"""
for iterator in testsByClassNames {
let className = iterator.key
stream <<< indent(8) <<< "testCase(\(className).__allTests__\(className)),\n"
}
stream <<< """
]
}
"""
stream.flush()
}
private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestDiscoveryTool) throws {
let index = self.context.buildParameters.indexStore
let api = try self.context.indexStoreAPI.get()
let store = try IndexStore.open(store: index, api: api)
// FIXME: We can speed this up by having one llbuild command per object file.
let tests = try store.listTests(in: tool.inputs.map{ try AbsolutePath(validating: $0.name) })
let outputs = tool.outputs.compactMap{ try? AbsolutePath(validating: $0.name) }
let testsByModule = Dictionary(grouping: tests, by: { $0.module.spm_mangledToC99ExtendedIdentifier() })
func isMainFile(_ path: AbsolutePath) -> Bool {
return path.basename == LLBuildManifest.TestDiscoveryTool.mainFileName
}
var maybeMainFile: AbsolutePath?
// Write one file for each test module.
//
// We could write everything in one file but that can easily run into type conflicts due
// in complex packages with large number of test targets.
for file in outputs {
if maybeMainFile == nil && isMainFile(file) {
maybeMainFile = file
continue
}
// FIXME: This is relying on implementation detail of the output but passing the
// the context all the way through is not worth it right now.
let module = file.basenameWithoutExt.spm_mangledToC99ExtendedIdentifier()
guard let tests = testsByModule[module] else {
// This module has no tests so just write an empty file for it.
try fileSystem.writeFileContents(file, bytes: "")
continue
}
try write(tests: tests, forModule: module, to: file)
}
guard let mainFile = maybeMainFile else {
throw InternalError("main output (\(LLBuildManifest.TestDiscoveryTool.mainFileName)) not found")
}
let testsKeyword = tests.isEmpty ? "let" : "var"
// Write the main file.
let stream = try LocalFileOutputByteStream(mainFile)
stream <<< "import XCTest" <<< "\n\n"
stream <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
stream <<< "public func __allDiscoveredTests() -> [XCTestCaseEntry] {" <<< "\n"
stream <<< indent(4) <<< "\(testsKeyword) tests = [XCTestCaseEntry]()" <<< "\n\n"
for module in testsByModule.keys {
stream <<< indent(4) <<< "tests += __\(module)__allTests()" <<< "\n"
}
stream <<< "\n"
stream <<< indent(4) <<< "return tests" <<< "\n"
stream <<< "}" <<< "\n"
stream.flush()
}
override func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.testDiscoveryCommands[command.name] else {
throw InternalError("command \(command.name) not registered")
}
try execute(fileSystem: self.context.fileSystem, tool: tool)
return true
} catch {
self.context.observabilityScope.emit(error)
return false
}
}
}
final class TestEntryPointCommand: CustomLLBuildCommand, TestBuildCommand {
private func execute(fileSystem: TSCBasic.FileSystem, tool: LLBuildManifest.TestEntryPointTool) throws {
// Find the inputs, which are the names of the test discovery module(s)
let inputs = tool.inputs.compactMap { try? AbsolutePath(validating: $0.name) }
let discoveryModuleNames = inputs.map { $0.basenameWithoutExt }
let outputs = tool.outputs.compactMap { try? AbsolutePath(validating: $0.name) }
// Find the main output file
guard let mainFile = outputs.first(where: { path in
path.basename == LLBuildManifest.TestEntryPointTool.mainFileName
}) else {
throw InternalError("main file output (\(LLBuildManifest.TestEntryPointTool.mainFileName)) not found")
}
// Write the main file.
let stream = try LocalFileOutputByteStream(mainFile)
stream <<< "import XCTest" <<< "\n"
for discoveryModuleName in discoveryModuleNames {
stream <<< "import \(discoveryModuleName)" <<< "\n"
}
stream <<< "\n"
stream <<< "@main" <<< "\n"
stream <<< "@available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")" <<< "\n"
stream <<< "struct Runner" <<< " {" <<< "\n"
stream <<< indent(4) <<< "static func main()" <<< " {" <<< "\n"
stream <<< indent(8) <<< "XCTMain(__allDiscoveredTests())" <<< "\n"
stream <<< indent(4) <<< "}" <<< "\n"
stream <<< "}" <<< "\n"
stream.flush()
}
override func execute(
_ command: SPMLLBuild.Command,
_ buildSystemCommandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.testEntryPointCommands[command.name] else {
throw InternalError("command \(command.name) not registered")
}
try execute(fileSystem: self.context.fileSystem, tool: tool)
return true
} catch {
self.context.observabilityScope.emit(error)
return false
}
}
}
private protocol TestBuildCommand {}
/// Functionality common to all build commands related to test targets.
extension TestBuildCommand {
/// Returns a value containing `spaces` number of space characters.
/// Intended to facilitate indenting generated code a specified number of levels.
fileprivate func indent(_ spaces: Int) -> ByteStreamable {
return Format.asRepeating(string: " ", count: spaces)
}
}
private final class InProcessTool: Tool {
let context: BuildExecutionContext
let type: CustomLLBuildCommand.Type
init(_ context: BuildExecutionContext, type: CustomLLBuildCommand.Type) {
self.context = context
self.type = type
}
func createCommand(_ name: String) -> ExternalCommand? {
return type.init(self.context)
}
}
/// Contains the description of the build that is needed during the execution.
public struct BuildDescription: Codable {
public typealias CommandName = String
public typealias TargetName = String
public typealias CommandLineFlag = String
/// The Swift compiler invocation targets.
let swiftCommands: [BuildManifest.CmdName : SwiftCompilerTool]
/// The Swift compiler frontend invocation targets.
let swiftFrontendCommands: [BuildManifest.CmdName : SwiftFrontendTool]
/// The map of test discovery commands.
let testDiscoveryCommands: [BuildManifest.CmdName: LLBuildManifest.TestDiscoveryTool]
/// The map of test entry point commands.
let testEntryPointCommands: [BuildManifest.CmdName: LLBuildManifest.TestEntryPointTool]
/// The map of copy commands.
let copyCommands: [BuildManifest.CmdName: LLBuildManifest.CopyTool]
/// A flag that inidcates this build should perform a check for whether targets only import
/// their explicitly-declared dependencies
let explicitTargetDependencyImportCheckingMode: BuildParameters.TargetDependencyImportCheckingMode
/// Every target's set of dependencies.
let targetDependencyMap: [TargetName: [TargetName]]
/// A full swift driver command-line invocation used to dependency-scan a given Swift target
let swiftTargetScanArgs: [TargetName: [CommandLineFlag]]
/// A set of all targets with generated source
let generatedSourceTargetSet: Set<TargetName>
/// The built test products.
public let builtTestProducts: [BuiltTestProduct]
/// Distilled information about any plugins defined in the package.
let pluginDescriptions: [PluginDescription]
public init(
plan: BuildPlan,
swiftCommands: [BuildManifest.CmdName : SwiftCompilerTool],
swiftFrontendCommands: [BuildManifest.CmdName : SwiftFrontendTool],
testDiscoveryCommands: [BuildManifest.CmdName: LLBuildManifest.TestDiscoveryTool],
testEntryPointCommands: [BuildManifest.CmdName: LLBuildManifest.TestEntryPointTool],
copyCommands: [BuildManifest.CmdName: LLBuildManifest.CopyTool],
pluginDescriptions: [PluginDescription]
) throws {
self.swiftCommands = swiftCommands
self.swiftFrontendCommands = swiftFrontendCommands
self.testDiscoveryCommands = testDiscoveryCommands
self.testEntryPointCommands = testEntryPointCommands
self.copyCommands = copyCommands
self.explicitTargetDependencyImportCheckingMode = plan.buildParameters.explicitTargetDependencyImportCheckingMode
self.targetDependencyMap = try plan.targets.reduce(into: [TargetName: [TargetName]]()) {
let deps = try $1.target.recursiveDependencies(satisfying: plan.buildParameters.buildEnvironment).compactMap { $0.target }.map { $0.c99name }
$0[$1.target.c99name] = deps
}
var targetCommandLines: [TargetName: [CommandLineFlag]] = [:]
var generatedSourceTargets: [TargetName] = []
for (target, description) in plan.targetMap {
guard case .swift(let desc) = description else {
continue
}
targetCommandLines[target.c99name] =
try desc.emitCommandLine(scanInvocation: true) + ["-driver-use-frontend-path",
plan.buildParameters.toolchain.swiftCompilerPath.pathString]
if case .discovery = desc.testTargetRole {
generatedSourceTargets.append(target.c99name)
}
}
generatedSourceTargets.append(contentsOf: plan.graph.allTargets.filter {$0.type == .plugin}
.map { $0.c99name })
self.swiftTargetScanArgs = targetCommandLines
self.generatedSourceTargetSet = Set(generatedSourceTargets)
self.builtTestProducts = plan.buildProducts.filter{ $0.product.type == .test }.map { desc in
return BuiltTestProduct(
productName: desc.product.name,
binaryPath: desc.binaryPath
)
}
self.pluginDescriptions = pluginDescriptions
}
public func write(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws {
let encoder = JSONEncoder.makeWithDefaults()
let data = try encoder.encode(self)
try fileSystem.writeFileContents(path, bytes: ByteString(data))
}
public static func load(fileSystem: TSCBasic.FileSystem, path: AbsolutePath) throws -> BuildDescription {
let contents: Data = try fileSystem.readFileContents(path)
let decoder = JSONDecoder.makeWithDefaults()
return try decoder.decode(BuildDescription.self, from: contents)
}
}
/// A provider of advice about build errors.
public protocol BuildErrorAdviceProvider {
/// Invoked after a command fails and an error message is detected in the output. Should return a string containing advice or additional information, if any, based on the build plan.
func provideBuildErrorAdvice(for target: String, command: String, message: String) -> String?
}
/// The context available during build execution.
public final class BuildExecutionContext {
/// Reference to the index store API.
var indexStoreAPI: Result<IndexStoreAPI, Error> {
indexStoreAPICache.getValue(self)
}
/// The build parameters.
let buildParameters: BuildParameters
/// The build description.
///
/// This is optional because we might not have a valid build description when performing the
/// build for PackageStructure target.
let buildDescription: BuildDescription?
/// The package structure delegate.
let packageStructureDelegate: PackageStructureDelegate
/// Optional provider of build error resolution advice.
let buildErrorAdviceProvider: BuildErrorAdviceProvider?
let fileSystem: TSCBasic.FileSystem
let observabilityScope: ObservabilityScope
public init(
_ buildParameters: BuildParameters,
buildDescription: BuildDescription? = nil,
fileSystem: TSCBasic.FileSystem,
observabilityScope: ObservabilityScope,
packageStructureDelegate: PackageStructureDelegate,
buildErrorAdviceProvider: BuildErrorAdviceProvider? = nil
) {
self.buildParameters = buildParameters
self.buildDescription = buildDescription
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope
self.packageStructureDelegate = packageStructureDelegate
self.buildErrorAdviceProvider = buildErrorAdviceProvider
}
// MARK:- Private
private var indexStoreAPICache = LazyCache(createIndexStoreAPI)
private func createIndexStoreAPI() -> Result<IndexStoreAPI, Error> {
Result {
#if os(Windows)
// The library's runtime component is in the `bin` directory on
// Windows rather than the `lib` directory as on unicies. The `lib`
// directory contains the import library (and possibly static
// archives) which are used for linking. The runtime component is
// not (necessarily) part of the SDK distributions.
//
// NOTE: the library name here `libIndexStore.dll` is technically
// incorrect as per the Windows naming convention. However, the
// library is currently installed as `libIndexStore.dll` rather than
// `IndexStore.dll`. In the future, this may require a fallback
// search, preferring `IndexStore.dll` over `libIndexStore.dll`.
let indexStoreLib = buildParameters.toolchain.swiftCompilerPath
.parentDirectory
.appending(component: "libIndexStore.dll")
#else
let ext = buildParameters.hostTriple.dynamicLibraryExtension
let indexStoreLib = try buildParameters.toolchain.toolchainLibDir.appending(component: "libIndexStore" + ext)
#endif
return try IndexStoreAPI(dylib: indexStoreLib)
}
}
}
public protocol PackageStructureDelegate {
func packageStructureChanged() -> Bool
}
final class PackageStructureCommand: CustomLLBuildCommand {
override func getSignature(_ command: SPMLLBuild.Command) -> [UInt8] {
let encoder = JSONEncoder.makeWithDefaults()
// Include build parameters and process env in the signature.
var hash = Data()
hash += try! encoder.encode(self.context.buildParameters)
hash += try! encoder.encode(ProcessEnv.vars)
return [UInt8](hash)
}
override func execute(
_ command: SPMLLBuild.Command,
_ commandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
return self.context.packageStructureDelegate.packageStructureChanged()
}
}
final class CopyCommand: CustomLLBuildCommand {
override func execute(
_ command: SPMLLBuild.Command,
_ commandInterface: SPMLLBuild.BuildSystemCommandInterface
) -> Bool {
do {
// This tool will never run without the build description.
guard let buildDescription = self.context.buildDescription else {
throw InternalError("unknown build description")
}
guard let tool = buildDescription.copyCommands[command.name] else {
throw StringError("command \(command.name) not registered")
}
let input = try AbsolutePath(validating: tool.inputs[0].name)
let output = try AbsolutePath(validating: tool.outputs[0].name)
try self.context.fileSystem.createDirectory(output.parentDirectory, recursive: true)
try self.context.fileSystem.removeFileTree(output)
try self.context.fileSystem.copy(from: input, to: output)
} catch {
self.context.observabilityScope.emit(error)
return false
}
return true
}
}
/// Convenient llbuild build system delegate implementation
final class BuildOperationBuildSystemDelegateHandler: LLBuildBuildSystemDelegate, SwiftCompilerOutputParserDelegate {
private let outputStream: ThreadSafeOutputByteStream
private let progressAnimation: ProgressAnimationProtocol
var commandFailureHandler: (() -> Void)?
private let logLevel: Basics.Diagnostic.Severity
private weak var delegate: SPMBuildCore.BuildSystemDelegate?
private let buildSystem: SPMBuildCore.BuildSystem
private let queue = DispatchQueue(label: "org.swift.swiftpm.build-delegate")
private var taskTracker = CommandTaskTracker()
private var errorMessagesByTarget: [String: [String]] = [:]
private let observabilityScope: ObservabilityScope
/// Swift parsers keyed by llbuild command name.
private var swiftParsers: [String: SwiftCompilerOutputParser] = [:]
/// Buffer to accumulate non-swift output until command is finished
private var nonSwiftMessageBuffers: [String: [UInt8]] = [:]
/// The build execution context.
private let buildExecutionContext: BuildExecutionContext
init(
buildSystem: SPMBuildCore.BuildSystem,
buildExecutionContext: BuildExecutionContext,
outputStream: OutputByteStream,
progressAnimation: ProgressAnimationProtocol,
logLevel: Basics.Diagnostic.Severity,
observabilityScope: ObservabilityScope,
delegate: SPMBuildCore.BuildSystemDelegate?
) {
self.buildSystem = buildSystem
self.buildExecutionContext = buildExecutionContext
// FIXME: Implement a class convenience initializer that does this once they are supported
// https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924
self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)
self.progressAnimation = progressAnimation
self.logLevel = logLevel
self.observabilityScope = observabilityScope
self.delegate = delegate
let swiftParsers = buildExecutionContext.buildDescription?.swiftCommands.mapValues { tool in
SwiftCompilerOutputParser(targetName: tool.moduleName, delegate: self)
} ?? [:]
self.swiftParsers = swiftParsers
self.taskTracker.onTaskProgressUpdateText = { progressText, _ in
self.queue.async {
self.delegate?.buildSystem(self.buildSystem, didUpdateTaskProgress: progressText)
}
}
}
// MARK: llbuildSwift.BuildSystemDelegate
var fs: SPMLLBuild.FileSystem? {
return nil
}
func lookupTool(_ name: String) -> Tool? {
switch name {
case TestDiscoveryTool.name:
return InProcessTool(buildExecutionContext, type: TestDiscoveryCommand.self)
case TestEntryPointTool.name:
return InProcessTool(buildExecutionContext, type: TestEntryPointCommand.self)
case PackageStructureTool.name:
return InProcessTool(buildExecutionContext, type: PackageStructureCommand.self)
case CopyTool.name:
return InProcessTool(buildExecutionContext, type: CopyCommand.self)
default:
return nil
}
}
func hadCommandFailure() {
self.commandFailureHandler?()
}
func handleDiagnostic(_ diagnostic: SPMLLBuild.Diagnostic) {
switch diagnostic.kind {
case .note:
self.observabilityScope.emit(info: diagnostic.message)
case .warning:
self.observabilityScope.emit(warning: diagnostic.message)
case .error:
self.observabilityScope.emit(error: diagnostic.message)
@unknown default:
self.observabilityScope.emit(info: diagnostic.message)
}
}
func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {
guard !self.logLevel.isVerbose else { return }
guard command.shouldShowStatus else { return }
guard !swiftParsers.keys.contains(command.name) else { return }
queue.async {
self.taskTracker.commandStatusChanged(command, kind: kind)
self.updateProgress()
}
}
func commandPreparing(_ command: SPMLLBuild.Command) {
queue.async {
self.delegate?.buildSystem(self.buildSystem, willStartCommand: BuildSystemCommand(command))
}
}
func commandStarted(_ command: SPMLLBuild.Command) {
guard command.shouldShowStatus else { return }
queue.async {
self.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(command))
if self.logLevel.isVerbose {
self.outputStream <<< command.verboseDescription <<< "\n"
self.outputStream.flush()
}
}
}
func shouldCommandStart(_ command: SPMLLBuild.Command) -> Bool {
return true
}
func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult) {
guard command.shouldShowStatus else { return }
guard !swiftParsers.keys.contains(command.name) else { return }
queue.async {
self.delegate?.buildSystem(self.buildSystem, didFinishCommand: BuildSystemCommand(command))
if !self.logLevel.isVerbose {
let targetName = self.swiftParsers[command.name]?.targetName
self.taskTracker.commandFinished(command, result: result, targetName: targetName)
self.updateProgress()
}
}
}
func commandHadError(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(error: message)
}
func commandHadNote(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(info: message)
}
func commandHadWarning(_ command: SPMLLBuild.Command, message: String) {
self.observabilityScope.emit(warning: message)
}
func commandCannotBuildOutputDueToMissingInputs(
_ command: SPMLLBuild.Command,
output: BuildKey,
inputs: [BuildKey]
) {
self.observabilityScope.emit(.missingInputs(output: output, inputs: inputs))
}
func cannotBuildNodeDueToMultipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) {
self.observabilityScope.emit(.multipleProducers(output: output, commands: commands))
}
func commandProcessStarted(_ command: SPMLLBuild.Command, process: ProcessHandle) {
}
func commandProcessHadError(_ command: SPMLLBuild.Command, process: ProcessHandle, message: String) {
self.observabilityScope.emit(.commandError(command: command, message: message))
}
func commandProcessHadOutput(_ command: SPMLLBuild.Command, process: ProcessHandle, data: [UInt8]) {
guard command.shouldShowStatus else { return }
if let swiftParser = swiftParsers[command.name] {
swiftParser.parse(bytes: data)
} else {
queue.async {
self.nonSwiftMessageBuffers[command.name, default: []] += data
}
}
}
func commandProcessFinished(
_ command: SPMLLBuild.Command,
process: ProcessHandle,
result: CommandExtendedResult
) {
queue.async {
if let buffer = self.nonSwiftMessageBuffers[command.name] {
self.progressAnimation.clear()
self.outputStream <<< buffer
self.outputStream.flush()
self.nonSwiftMessageBuffers[command.name] = nil
}
}
if result.result == .failed {
// The command failed, so we queue up an asynchronous task to see if we have any error messages from the target to provide advice about.
queue.async {
guard let target = self.swiftParsers[command.name]?.targetName else { return }
guard let errorMessages = self.errorMessagesByTarget[target] else { return }
for errorMessage in errorMessages {
// Emit any advice that's provided for each error message.
if let adviceMessage = self.buildExecutionContext.buildErrorAdviceProvider?.provideBuildErrorAdvice(for: target, command: command.name, message: errorMessage) {
self.outputStream <<< "note: " <<< adviceMessage <<< "\n"
self.outputStream.flush()
}
}
}
}
}
func cycleDetected(rules: [BuildKey]) {
self.observabilityScope.emit(.cycleError(rules: rules))
queue.async {
self.delegate?.buildSystemDidDetectCycleInRules(self.buildSystem)
}
}
func shouldResolveCycle(rules: [BuildKey], candidate: BuildKey, action: CycleAction) -> Bool {
return false
}
/// Invoked right before running an action taken before building.
func preparationStepStarted(_ name: String) {
queue.async {
self.taskTracker.buildPreparationStepStarted(name)
self.updateProgress()
}
}
/// Invoked when an action taken before building emits output.
func preparationStepHadOutput(_ name: String, output: String) {
queue.async {
self.progressAnimation.clear()
if self.logLevel.isVerbose {
self.outputStream <<< output.spm_chomp() <<< "\n"
self.outputStream.flush()
}
}
}
/// Invoked right after running an action taken before building. The result
/// indicates whether the action succeeded, failed, or was cancelled.
func preparationStepFinished(_ name: String, result: CommandResult) {
queue.async {
self.taskTracker.buildPreparationStepFinished(name)
self.updateProgress()
}
}
// MARK: SwiftCompilerOutputParserDelegate
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage) {
queue.async {
if self.logLevel.isVerbose {
if let text = message.verboseProgressText {
self.outputStream <<< text <<< "\n"
self.outputStream.flush()
}
} else {
self.taskTracker.swiftCompilerDidOutputMessage(message, targetName: parser.targetName)
self.updateProgress()
}
if let output = message.standardOutput {
// first we want to print the output so users have it handy
if !self.logLevel.isVerbose {
self.progressAnimation.clear()
}
self.outputStream <<< output
self.outputStream.flush()
// next we want to try and scoop out any errors from the output (if reasonable size, otherwise this will be very slow),
// so they can later be passed to the advice provider in case of failure.
if output.utf8.count < 1024 * 10 {
let regex = try! RegEx(pattern: #".*(error:[^\n]*)\n.*"#, options: .dotMatchesLineSeparators)
for match in regex.matchGroups(in: output) {
self.errorMessagesByTarget[parser.targetName] = (self.errorMessagesByTarget[parser.targetName] ?? []) + [match[0]]
}
}
}
}
}
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error) {
let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
self.observabilityScope.emit(.swiftCompilerOutputParsingError(message))
self.commandFailureHandler?()
}
func buildStart(configuration: BuildConfiguration) {
queue.sync {
self.progressAnimation.clear()
self.outputStream <<< "Building for \(configuration == .debug ? "debugging" : "production")...\n"
self.outputStream.flush()
}
}
func buildComplete(success: Bool, duration: DispatchTimeInterval) {
queue.sync {
self.progressAnimation.complete(success: success)
if success {
self.progressAnimation.clear()
self.outputStream <<< "Build complete! (\(duration.descriptionInSeconds))\n"
self.outputStream.flush()
}
}
}
// MARK: Private
private func updateProgress() {
if let progressText = taskTracker.latestFinishedText {
self.progressAnimation.update(
step: taskTracker.finishedCount,
total: taskTracker.totalCount,
text: progressText
)
}
}
}
/// Tracks tasks based on command status and swift compiler output.
fileprivate struct CommandTaskTracker {
private(set) var totalCount = 0
private(set) var finishedCount = 0
private var swiftTaskProgressTexts: [Int: String] = [:]
/// The last task text before the task list was emptied.
private(set) var latestFinishedText: String?
var onTaskProgressUpdateText: ((_ text: String, _ targetName: String?) -> Void)?
mutating func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {
switch kind {
case .isScanning:
self.totalCount += 1
case .isUpToDate:
self.totalCount -= 1
case .isComplete:
self.finishedCount += 1
@unknown default:
assertionFailure("unhandled command status kind \(kind) for command \(command)")
break
}
}
mutating func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult, targetName: String?) {
let progressTextValue = progressText(of: command, targetName: targetName)
self.onTaskProgressUpdateText?(progressTextValue, targetName)
self.latestFinishedText = progressTextValue
}
mutating func swiftCompilerDidOutputMessage(_ message: SwiftCompilerMessage, targetName: String) {
switch message.kind {
case .began(let info):
if let text = progressText(of: message, targetName: targetName) {
swiftTaskProgressTexts[info.pid] = text
onTaskProgressUpdateText?(text, targetName)
}
totalCount += 1
case .finished(let info):
if let progressText = swiftTaskProgressTexts[info.pid] {
latestFinishedText = progressText
swiftTaskProgressTexts[info.pid] = nil
}
finishedCount += 1
case .unparsableOutput, .signalled, .skipped:
break
}
}
private func progressText(of command: SPMLLBuild.Command, targetName: String?) -> String {
// Transforms descriptions like "Linking ./.build/x86_64-apple-macosx/debug/foo" into "Linking foo".
if let firstSpaceIndex = command.description.firstIndex(of: " "),
let lastDirectorySeparatorIndex = command.description.lastIndex(of: "/")
{
let action = command.description[..<firstSpaceIndex]
let fileNameStartIndex = command.description.index(after: lastDirectorySeparatorIndex)
let fileName = command.description[fileNameStartIndex...]
if let targetName = targetName {
return "\(action) \(targetName) \(fileName)"
} else {
return "\(action) \(fileName)"
}
} else {
return command.description
}
}
private func progressText(of message: SwiftCompilerMessage, targetName: String) -> String? {
if case .began(let info) = message.kind {
switch message.name {
case "compile":
if let sourceFile = info.inputs.first {
let sourceFilePath = try! AbsolutePath(validating: sourceFile)
return "Compiling \(targetName) \(sourceFilePath.components.last!)"
}
case "link":
return "Linking \(targetName)"
case "merge-module":
return "Merging module \(targetName)"
case "emit-module":
return "Emitting module \(targetName)"
case "generate-dsym":
return "Generating \(targetName) dSYM"
case "generate-pch":
return "Generating \(targetName) PCH"
default:
break
}
}
return nil
}
mutating func buildPreparationStepStarted(_ name: String) {
self.totalCount += 1
}
mutating func buildPreparationStepFinished(_ name: String) {
latestFinishedText = name
self.finishedCount += 1
}
}
extension SwiftCompilerMessage {
fileprivate var verboseProgressText: String? {
switch kind {
case .began(let info):
return ([info.commandExecutable] + info.commandArguments).joined(separator: " ")
case .skipped, .finished, .signalled, .unparsableOutput:
return nil
}
}
fileprivate var standardOutput: String? {
switch kind {
case .finished(let info),
.signalled(let info):
return info.output
case .unparsableOutput(let output):
return output
case .skipped, .began:
return nil
}
}
}
private extension Basics.Diagnostic {
static func cycleError(rules: [BuildKey]) -> Self {
.error("build cycle detected: " + rules.map{ $0.key }.joined(separator: ", "))
}
static func missingInputs(output: BuildKey, inputs: [BuildKey]) -> Self {
let missingInputs = inputs.map{ $0.key }.joined(separator: ", ")
return .error("couldn't build \(output.key) because of missing inputs: \(missingInputs)")
}
static func multipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) -> Self {
let producers = commands.map{ $0.description }.joined(separator: ", ")
return .error("couldn't build \(output.key) because of missing producers: \(producers)")
}
static func commandError(command: SPMLLBuild.Command, message: String) -> Self {
.error("command \(command.description) failed: \(message)")
}
static func swiftCompilerOutputParsingError(_ error: String) -> Self {
.error("failed parsing the Swift compiler output: \(error)")
}
}
private extension BuildSystemCommand {
init(_ command: SPMLLBuild.Command) {
self.init(
name: command.name,
description: command.description,
verboseDescription: command.verboseDescription
)
}
}
| apache-2.0 | 9052f81a4333cb2f96d0a79bde1f25f4 | 38.762097 | 227 | 0.640782 | 4.891976 | false | true | false | false |
CodaFi/PersistentStructure.swift | Persistent/LazilyPersistentVector.swift | 1 | 860 | //
// LazilyPersistentVector.swift
// Persistent
//
// Created by Robert Widmann on 12/22/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
class LazilyPersistentVector {
class func createOwning(items: Array<AnyObject>) -> IPersistentVector {
if items.count == 0 {
return PersistentVector.empty
} else if items.count <= 32 {
return PersistentVector(cnt: items.count, shift: 5, root: (PersistentVector.emptyNode as? INode)!, tail: items)
}
return PersistentVector.createWithItems(items)
}
class func create(collec: ICollection?) -> IPersistentVector {
guard let coll = collec as? ISeq else {
return LazilyPersistentVector.createOwning(collec?.toArray ?? [])
}
if coll.count <= 32 {
return LazilyPersistentVector.createOwning(collec?.toArray ?? [])
}
return PersistentVector.createWithSeq(Utils.seq(coll))
}
}
| mit | 6ff8bf641772b595601c1be69e028aee | 28.62069 | 114 | 0.719441 | 3.534979 | false | false | false | false |
White-Label/Swift-SDK | WhiteLabel/CoreData/WLLabel+CoreDataClass.swift | 1 | 2623 | //
// WLLabel+CoreDataClass.swift
//
// Created by Alex Givens http://alexgivens.com on 7/24/17
// Copyright © 2017 Noon Pacific LLC http://noonpacific.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreData
@objc(WLLabel)
final public class WLLabel: NSManagedObject, ResponseObjectSerializable, ResponseCollectionSerializable {
public static let entityName = "WLLabel"
convenience init?(response: HTTPURLResponse, representation: Any) {
let context = CoreDataStack.shared.backgroundManagedObjectContext
let entity = NSEntityDescription.entity(forEntityName: WLLabel.entityName, in: context)!
self.init(entity: entity, insertInto: context)
guard
let representation = representation as? [String: Any],
let id = representation["id"] as? Int32,
let slug = representation["slug"] as? String,
let name = representation["name"] as? String
// let serviceRepresentation = representation["service"]
else {
return nil
}
self.id = id
self.slug = slug
self.name = name
iconURL = representation["icon"] as? String
// self.service = WLService(response: response, representation: serviceRepresentation)
}
func updateInstanceWith(response: HTTPURLResponse, representation: Any) {
}
static func existingInstance(response: HTTPURLResponse, representation: Any) -> Self? {
return nil
}
}
| mit | b9001bdca53bed45f4c87db3053f637e | 38.134328 | 105 | 0.688787 | 4.732852 | false | false | false | false |
Xopoko/SpaceView | Example/ViewController.swift | 1 | 4781 | //
// ViewController.swift
// SpaceViewExample
//
// Created by user on 25.12.16.
// Copyright © 2016 horoko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timeStepper: UIStepper!
@IBOutlet weak var autohideTimeLabel: UILabel!
private var timeToAutoHide = 3.0
private var shouldAutoHide = true
private var leftSwipeAccepted = true
private var topSwipeAccepted = true
private var rightSwipeAccepted = true
private var botSwipeAccepted = true
private var spaceStyle: SpaceStyles? = nil
private var spaceTitle = "Title"
private var spaceDescr = "Description"
private var image: UIImage? = nil
private var withImage = false
private var spacePosition: SpacePosition = .top
var possibleDirectionsToHide: [HideDirection] = []
override func viewDidLoad() {
super.viewDidLoad()
autohideTimeLabel.text = String(timeStepper.value)
timeToAutoHide = timeStepper.value
}
@IBAction func positionsChanged(_ sender: Any) {
if let sc = sender as? UISegmentedControl {
switch sc.selectedSegmentIndex {
case 0:
spacePosition = .top
case 1:
spacePosition = .bot
default:
break
}
}
}
@IBAction func styleChanged(_ sender: Any) {
if let sc = sender as? UISegmentedControl {
switch sc.selectedSegmentIndex {
case 0:
spaceStyle = .success
case 1:
spaceStyle = .error
case 2:
spaceStyle = .warning
case 3:
spaceStyle = nil
default:
break
}
}
}
@IBAction func showSpace(_ sender: Any) {
image = nil
possibleDirectionsToHide.removeAll()
if spaceStyle != nil {
switch spaceStyle! {
case .success:
if withImage {
image = UIImage(named: "ic_success")
}
spaceTitle = "Success"
spaceDescr = "Operation complete"
case .error:
if withImage {
image = UIImage(named: "ic_error")
}
spaceTitle = "Error"
spaceDescr = "Operation failed"
case .warning:
if withImage {
image = UIImage(named: "ic_warning")
}
spaceTitle = "Warning!"
spaceDescr = "Look at this!"
}
}
if leftSwipeAccepted {
possibleDirectionsToHide.append(.left)
}
if rightSwipeAccepted {
possibleDirectionsToHide.append(.right)
}
if topSwipeAccepted {
possibleDirectionsToHide.append(.top)
}
if botSwipeAccepted {
possibleDirectionsToHide.append(.bot)
}
self.showSpace(title: spaceTitle, description: spaceDescr, spaceOptions: [
.spaceHideTimer(timer: timeToAutoHide),
.possibleDirectionToHide(possibleDirectionsToHide),
.shouldAutoHide(should: shouldAutoHide),
.spaceStyle(style: spaceStyle),
.image(img: image),
.spacePosition(position: spacePosition),
.swipeAction {print("SWIPE")},
])
}
@IBAction func withImageSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
withImage = switcher.isOn
}
}
@IBAction func stepperAutohide(_ sender: Any) {
if let stepper = sender as? UIStepper {
timeToAutoHide = stepper.value
autohideTimeLabel.text = String(stepper.value)
}
}
@IBAction func BotSwipeDirectionSwitch(_ sender: UISwitch) {
botSwipeAccepted = sender.isOn
}
@IBAction func TopSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
topSwipeAccepted = switcher.isOn
}
}
@IBAction func RightSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
rightSwipeAccepted = switcher.isOn
}
}
@IBAction func LeftSwipeDirectionSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
leftSwipeAccepted = switcher.isOn
}
}
@IBAction func shouldAutohideSwitch(_ sender: Any) {
if let switcher = sender as? UISwitch {
shouldAutoHide = switcher.isOn
}
}
}
| mit | 1dc4161239620f3b867aa30464403954 | 28.689441 | 82 | 0.543096 | 5.201306 | false | false | false | false |
Mrwerdo/QuickShare | QuickShare/QuickShare/VibrantWindow.swift | 1 | 1801 | //
// VibrantWindow.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// 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 Cocoa
class VibrantWindow : NSWindow {
var titleItem: NSToolbarItem? {
if let items = self.toolbar?.items {
return items[1]
}
return nil
}
override var title: String {
didSet {
let textfield = titleItem?.view as? NSTextField
textfield?.stringValue = title
textfield?.needsDisplay = true
}
}
override func awakeFromNib() {
self.titlebarAppearsTransparent = true
self.appearance = NSAppearance(named: NSAppearanceNameVibrantLight)
self.titleVisibility = .Hidden
}
} | mit | ce99b0eca8f547c19fb7675a587bba73 | 35.04 | 81 | 0.693504 | 4.606138 | false | false | false | false |
contentful-labs/markdown-example-ios | Code/MDTextViewController.swift | 1 | 1252 | //
// MDTextViewController.swift
// Markdown
//
// Created by Boris Bügling on 01/12/15.
// Copyright © 2015 Contentful GmbH. All rights reserved.
//
import CocoaMarkdown
import UIKit
class MDTextViewController: UIViewController {
var entryId = "4bJdF7zhwkwcWq202gmkuM"
convenience init() {
self.init(nibName: nil, bundle: nil)
self.tabBarItem = UITabBarItem(title: "TextView", image: UIImage(named: "lightning"), tag: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: view.bounds)
textView.isEditable = false
view.addSubview(textView)
client.fetchEntry(identifier: entryId).1.next { (entry) in
if let markdown = entry.fields["body"] as? String {
let data = markdown.data(using: String.Encoding.utf8)
let document = CMDocument(data: data, options: [])
let renderer = CMAttributedStringRenderer(document: document, attributes: CMTextAttributes())
DispatchQueue.main.async {
textView.attributedText = renderer?.render()
}
}
}.error { (error) in
showError(error, self)
}
}
}
| mit | be98154e198fad5ee66eb500f5b2398f | 28.761905 | 109 | 0.6128 | 4.385965 | false | false | false | false |
IngmarStein/swift | test/ClangModules/MixedSource/mixed-nsuinteger.swift | 4 | 1525 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/user-module -parse %s -verify
// REQUIRES: objc_interop
// Type checker should not report any errors in the code below.
import Foundation
import user
var ui: UInt = 5
var i: Int = 56
var p: UnsafeMutablePointer<NSFastEnumerationState>?
var pp: AutoreleasingUnsafeMutablePointer<AnyObject?>?
var userTypedObj = NSUIntTest()
// Check that the NSUInteger comes across as UInt from user Obj C modules.
var ur: UInt = userTypedObj.myCustomMethodThatOperates(onNSUIntegers: ui)
userTypedObj.intProp = ui
userTypedObj.typedefProp = ui
ur = testFunction(ui)
testFunctionInsideMacro(ui)
// Test that nesting works.
var pui: UnsafeMutablePointer<UInt>
ur = testFunctionWithPointerParam(pui)
// NSUIntTest is a user class that conforms to a system defined protocol.
// The types are treated as system types when working with objects having
// protocol type.
var a: [NSFastEnumeration] = [NSUIntTest(), NSUIntTest()]
var r: Int = a[0].countByEnumerating(with: p!, objects: pp!, count: i)
// When working with instances typed as user-defined, NSUInteger comes
// across as UInt.
var rr: UInt = userTypedObj.countByEnumerating(with: p!, objects: pp!, count: ui)
// Check exercising protocol conformance.
func gen<T:NSFastEnumeration>(_ t:T) {
let i: Int = 56
let p: UnsafeMutablePointer<NSFastEnumerationState>?
let pp: AutoreleasingUnsafeMutablePointer<AnyObject?>?
t.countByEnumerating(with: p!, objects: pp!, count: i)
}
gen(userTypedObj)
| apache-2.0 | d136bed2c18471435488b147ea8f8d72 | 30.770833 | 104 | 0.76 | 3.692494 | false | true | false | false |
evilpunisher24/HooperPics | HooperPics/HooperPicsDigger.swift | 1 | 838 | //
// HooperPicsDigger.swift
// HooperPics
//
// Created by YeYiquan on 15/12/1.
// Copyright (c) 2015年 YeYiquan. All rights reserved.
//
import Foundation
import UIKit
class HooperPicsDigger{
let homePage = "http://tu.hupu.com"
var picsAddress = [String]()//存储从网页上截取的图片ip地址数据
init() {
let url = NSURL(string: homePage)!
let data = NSData(contentsOfURL: url)!
let htmlDoc = TFHpple(HTMLData: data)
let txtNodes = htmlDoc.searchWithXPathQuery("//a[@class='img-a']")
for eachTxtNodes in txtNodes{
if let elements = eachTxtNodes.childrenWithTagName("img"){
for eachElement in elements {
picsAddress.append(eachElement.objectForKey("src")!)
}
}
}
}
} | mit | d2d38055cee4f036231cce34ec8cc81b | 25.9 | 74 | 0.593052 | 3.766355 | false | false | false | false |
chai2010/ptyy | ios-app/yjyy-swift/MainViewController.swift | 1 | 7920 | // Copyright 2016 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import UIKit
class MainViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var refreshControl = UIRefreshControl()
var db:DataEngin = DataEngin()
var results = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
let footerBar = UILabel()
footerBar.text = "共 N 个结果\n"
footerBar.textAlignment = NSTextAlignment.Center
footerBar.numberOfLines = 0
footerBar.lineBreakMode = NSLineBreakMode.ByWordWrapping
footerBar.textColor = UIColor.darkGrayColor()
footerBar.sizeToFit()
self.tableView.tableFooterView = footerBar
self.tableView.dataSource = self
self.tableView.delegate = self
self.refreshControl.addTarget(self, action: #selector(MainViewController.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(self.refreshControl)
// 注册TableViewCell
self.tableView.registerClass(MyCustomMenuCell.self, forCellReuseIdentifier: MyCustomMenuCell.ReuseIdentifier)
// 生成初始列表
self.searchBarSearchButtonClicked(searchBar)
}
// 刷新数据
func refreshData() {
NSThread.sleepForTimeInterval(1.0)
self.refreshControl.endRefreshing()
}
// 分享App
@IBAction func onShareApp(sender: UIBarButtonItem) {
let utlTilte = "野鸡医院 - 莆田系医院查询"
let urlStr = "https://appsto.re/cn/QH8ocb.i"
let appStoreUrl = NSURL(string: urlStr.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLQueryAllowedCharacterSet())!)
let activity = UIActivityViewController(activityItems: [utlTilte, appStoreUrl!], applicationActivities: nil)
self.presentViewController(activity, animated: true, completion: nil)
// 修复 iPad 上崩溃问题
if #available(iOS 8.0, *) {
let presentationController = activity.popoverPresentationController
presentationController?.sourceView = view
}
}
// 关于按钮
@IBAction func onAbout(sender: UIBarButtonItem) {
let title = "关于 野鸡医院"
let message = "" +
"用于查询中国大陆较常见的非公有或私人承包的野鸡医院或科室(以莆田系为主),支持 拼音/汉字/数字/正则 查询。\n" +
"\n" +
"查询数据来源于互联网, 本应用并不保证数据的真实性和准确性,查询结果只作为就医前的一个参考。\n" +
"\n" +
"版权 2016 @chaishushan"
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let githubAction = UIAlertAction(title: "Github", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
let urlStr = "https://github.com/chai2010/ptyy"
let githubUrl = NSURL(string: urlStr.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLQueryAllowedCharacterSet())!)
UIApplication.sharedApplication().openURL(githubUrl!)
}
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
// OK
}
alertController.addAction(githubAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
}
// -------------------------------------------------------
// UITableViewDataSource
// -------------------------------------------------------
// 表格单元数目
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.results.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.results[section].count
}
// 表格单元
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(MyCustomMenuCell.ReuseIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = self.results[indexPath.section][indexPath.row]
return cell
}
// 右侧索引
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
var keys:[String] = []
for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".characters {
keys.append("\(ch)")
}
return keys
}
// -------------------------------------------------------
// UITableViewDelegate
// -------------------------------------------------------
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return action == MenuAction.Copy.selector() || MenuAction.supportedAction(action)
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == #selector(NSObject.copy(_:)) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
UIPasteboard.generalPasteboard().string = cell!.textLabel!.text
}
}
// 选择列时隐藏搜索键盘
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.searchBar.showsCancelButton = false
// 更新检索栏状态
self.searchBar.resignFirstResponder()
// 已经选择的话, 则取消选择
if indexPath == tableView.indexPathForSelectedRow {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// -------------------------------------------------------
// UISearchBarDelegate
// -------------------------------------------------------
// 检索栏状态
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
// 点击搜索按钮
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// 根据查询条件查询结果
self.results = self.db.SearchV2(searchBar.text!)
self.searchBar.showsCancelButton = false
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "共 \(self.numberOfResult()) 个结果\n"
// 更新列表视图
self.tableView.reloadData()
self.searchBar.resignFirstResponder()
}
// 检索词发生变化
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// 根据查询条件查询结果
self.results = self.db.SearchV2(searchBar.text!)
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "共 \(self.numberOfResult()) 个结果\n"
// 更新列表视图
self.tableView.reloadData()
}
// 取消搜索
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// 隐藏取消按钮
self.searchBar.showsCancelButton = false
self.searchBar.text = ""
// 根据查询条件查询结果(没有查询条件)
self.results = self.db.SearchV2("")
let footerBar = self.tableView.tableFooterView as? UILabel
footerBar!.text = "共 \(self.numberOfResult()) 个结果\n"
// 更新列表视图
self.tableView.reloadData()
// 更新检索栏状态
self.searchBar.resignFirstResponder()
}
// -------------------------------------------------------
// 辅助函数
// -------------------------------------------------------
// 结果总数
private func numberOfResult() -> Int {
var sum:Int = 0
for x in self.results {
sum += x.count
}
return sum
}
// -------------------------------------------------------
// END
// -------------------------------------------------------
}
| bsd-3-clause | 6d8fe9f00e04443b96d9aba56cf6819e | 30.459227 | 157 | 0.687858 | 4.045254 | false | false | false | false |
haifengkao/NightWatch | Example/StationModel.swift | 1 | 2000 | //
// StationModel.swift
// UbikeTracer
//
// Created by rosa on 2017/7/21.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import CoreLocation
import Foundation
struct StationModel {
let id: String
let name: String
let coordinate: CLLocationCoordinate2D
let numberOfSpaces: Int
let numberOfBikes: Int
let updateTime: Date
var distance: Double = 0.0
var bikesHistory: [Int] = []
var predict30MinChange: Int = 0
var fullPercent: Double {
return Double(self.numberOfBikes) / (Double(self.numberOfSpaces) + Double(self.numberOfBikes))
}
}
extension StationModel {
enum ParseDataError: Error { case Missingid, MissingName, MissingCoor, MissingData, MissingTime }
init(dict: [String:Any] ) throws {
guard let id = dict["sno"] as? String else { throw ParseDataError.Missingid }
self.id = id
guard let name = dict["sna"] as? String else { throw ParseDataError.MissingName }
self.name = name
guard let latStr = dict["lat"] as? String,
let lngStr = dict["lng"] as? String,
let lat = Double(latStr),
let lng = Double(lngStr) else { throw ParseDataError.MissingCoor }
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
guard let spacesStr = dict["bemp"] as? String,
let bikesStr = dict["sbi"] as? String,
let spaces = Int(spacesStr),
let bikes = Int(bikesStr) else { throw ParseDataError.MissingData }
self.numberOfSpaces = spaces
self.numberOfBikes = bikes
guard let time = dict["mday"] as? String else { throw ParseDataError.MissingTime }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from: time)!
self.updateTime = date
}
}
| mit | 5d54eecf1c2bf08858cebb2ed78ce884 | 28.80597 | 102 | 0.62694 | 4.276231 | false | false | false | false |
mcddx330/Pumpkin | Pumpkin/PKFileManage.swift | 1 | 1546 | //
// PKFileManage.swift
// Pumpkin
//
// Created by dimbow. on 2/6/15.
// Copyright (c) 2015 dimbow. All rights reserved.
//
import Foundation
public typealias PKSaveData = Dictionary<String,AnyObject>;
public class PKFileManage{
private var domainPaths:NSArray!;
private var docDir:NSString!;
private var filePath:NSString!;
private var fileData:NSData!;
private var DestinationFileName:String = "DefaultGameData.plist";
public var saveData = PKSaveData();
public init(plistName:String!){
if(plistName != nil){
DestinationFileName = plistName!;
}
domainPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray;
docDir = domainPaths!.objectAtIndex(0) as? NSString;
filePath = docDir!.stringByAppendingPathComponent(DestinationFileName);
}
}
extension PKFileManage {
public func Save()->Bool{
fileData = NSKeyedArchiver.archivedDataWithRootObject(saveData);
return fileData.writeToFile(filePath as! String, atomically: true);
}
public func Load()->PKSaveData{
let fileManager = NSFileManager.defaultManager();
var res = PKSaveData();
if(!fileManager.fileExistsAtPath(filePath! as! String)){
res = ["Result":false];
}else{
let data = NSData(contentsOfFile: filePath! as! String);
res = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! PKSaveData;
}
return res;
}
}
| mit | 3e46a3189e3fd265ba51fe3e26378b1c | 29.313725 | 112 | 0.661061 | 4.742331 | false | false | false | false |
natecook1000/swift | stdlib/public/core/StringBridge.swift | 2 | 13735 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
/// Effectively an untyped NSString that doesn't require foundation.
public typealias _CocoaString = AnyObject
@inlinable // FIXME(sil-serialize-all)
public // @testable
func _stdlib_binary_CFStringCreateCopy(
_ source: _CocoaString
) -> _CocoaString {
let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject
return result
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public // @testable
func _stdlib_binary_CFStringGetLength(
_ source: _CocoaString
) -> Int {
return _swift_stdlib_CFStringGetLength(source)
}
@inlinable // FIXME(sil-serialize-all)
public // @testable
func _stdlib_binary_CFStringGetCharactersPtr(
_ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return UnsafeMutablePointer(
mutating: _swift_stdlib_CFStringGetCharactersPtr(source))
}
/// Loading Foundation initializes these function variables
/// with useful values
/// Copies the entire contents of a _CocoaString into contiguous
/// storage of sufficient capacity.
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringReadAll(
_ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_swift_stdlib_CFStringGetCharacters(
source, _swift_shims_CFRange(
location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination)
}
/// Copies a slice of a _CocoaString into contiguous storage of
/// sufficient capacity.
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringCopyCharacters(
from source: _CocoaString,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_swift_stdlib_CFStringGetCharacters(
source,
_swift_shims_CFRange(location: range.lowerBound, length: range.count),
destination)
}
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringSlice(
_ target: _CocoaString, _ bounds: Range<Int>
) -> _CocoaString {
let cfSelf: _swift_shims_CFStringRef = target
_sanityCheck(
_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
let cfResult = _swift_stdlib_CFStringCreateWithSubstring(
nil, cfSelf, _swift_shims_CFRange(
location: bounds.lowerBound, length: bounds.count)) as AnyObject
return cfResult
}
@usableFromInline // FIXME(sil-serialize-all)
@inline(never) // Hide the CF dependency
internal func _cocoaStringSubscript(
_ target: _CocoaString, _ position: Int
) -> UTF16.CodeUnit {
let cfSelf: _swift_shims_CFStringRef = target
_sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position)
}
//
// Conversion from NSString to Swift's native representation
//
@inlinable // FIXME(sil-serialize-all)
internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x0600 }
}
@inlinable // FIXME(sil-serialize-all)
internal var kCFStringEncodingUTF8 : _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x8000100 }
}
@usableFromInline // @opaque
internal func _bridgeASCIICocoaString(
_ cocoa: _CocoaString,
intoUTF8 bufPtr: UnsafeMutableRawBufferPointer
) -> Int? {
let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked.assumingMemoryBound(
to: UInt8.self)
let length = _stdlib_binary_CFStringGetLength(cocoa)
var count = 0
let numCharWritten = _swift_stdlib_CFStringGetBytes(
cocoa, _swift_shims_CFRange(location: 0, length: length),
kCFStringEncodingUTF8, 0, 0, ptr, bufPtr.count, &count)
return length == numCharWritten ? count : nil
}
@usableFromInline
internal func _bridgeToCocoa(_ small: _SmallUTF8String) -> _CocoaString {
return small.withUTF8CodeUnits { bufPtr in
return _swift_stdlib_CFStringCreateWithBytes(
nil, bufPtr.baseAddress._unsafelyUnwrappedUnchecked,
bufPtr.count,
small.isASCII ? kCFStringEncodingASCII : kCFStringEncodingUTF8, 0)
as AnyObject
}
}
internal func _getCocoaStringPointer(
_ cfImmutableValue: _CocoaString
) -> (UnsafeRawPointer?, isUTF16: Bool) {
// Look first for null-terminated ASCII
// Note: the code in clownfish appears to guarantee
// nul-termination, but I'm waiting for an answer from Chris Kane
// about whether we can count on it for all time or not.
let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr(
cfImmutableValue, kCFStringEncodingASCII)
// start will hold the base pointer of contiguous storage, if it
// is found.
var start: UnsafeRawPointer?
let isUTF16 = (nulTerminatedASCII == nil)
if isUTF16 {
let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)
start = UnsafeRawPointer(utf16Buf)
} else {
start = UnsafeRawPointer(nulTerminatedASCII)
}
return (start, isUTF16: isUTF16)
}
@usableFromInline
@inline(never) // Hide the CF dependency
internal
func _makeCocoaStringGuts(_ cocoaString: _CocoaString) -> _StringGuts {
if let ascii = cocoaString as? _ASCIIStringStorage {
return _StringGuts(_large: ascii)
} else if let utf16 = cocoaString as? _UTF16StringStorage {
return _StringGuts(_large: utf16)
} else if let wrapped = cocoaString as? _NSContiguousString {
return wrapped._guts
} else if _isObjCTaggedPointer(cocoaString) {
guard let small = _SmallUTF8String(_cocoaString: cocoaString) else {
fatalError("Internal invariant violated: large tagged NSStrings")
}
return _StringGuts(small)
}
// "copy" it into a value to be sure nobody will modify behind
// our backs. In practice, when value is already immutable, this
// just does a retain.
let immutableCopy
= _stdlib_binary_CFStringCreateCopy(cocoaString) as AnyObject
if _isObjCTaggedPointer(immutableCopy) {
guard let small = _SmallUTF8String(_cocoaString: cocoaString) else {
fatalError("Internal invariant violated: large tagged NSStrings")
}
return _StringGuts(small)
}
let (start, isUTF16) = _getCocoaStringPointer(immutableCopy)
let length = _StringGuts.getCocoaLength(
_unsafeBitPattern: Builtin.reinterpretCast(immutableCopy))
return _StringGuts(
_largeNonTaggedCocoaObject: immutableCopy,
count: length,
isSingleByte: !isUTF16,
start: start)
}
extension String {
public // SPI(Foundation)
init(_cocoaString: AnyObject) {
self._guts = _makeCocoaStringGuts(_cocoaString)
}
}
// At runtime, this class is derived from `_SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@_fixed_layout // FIXME(sil-serialize-all)
@objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase)
public class _SwiftNativeNSString {
@usableFromInline // FIXME(sil-serialize-all)
@objc
internal init() {}
deinit {}
}
/// A shadow for the "core operations" of NSString.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSString` subclass.
@objc
public protocol _NSStringCore : _NSCopying /* _NSFastEnumeration */ {
// The following methods should be overridden when implementing an
// NSString subclass.
@objc(length)
var length: Int { get }
@objc(characterAtIndex:)
func character(at index: Int) -> UInt16
// We also override the following methods for efficiency.
@objc(getCharacters:range:)
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange)
@objc(_fastCharacterContents)
func _fastCharacterContents() -> UnsafePointer<UInt16>?
}
/// An `NSString` built around a slice of contiguous Swift `String` storage.
@_fixed_layout // FIXME(sil-serialize-all)
public final class _NSContiguousString : _SwiftNativeNSString, _NSStringCore {
public let _guts: _StringGuts
@inlinable // FIXME(sil-serialize-all)
public init(_ _guts: _StringGuts) {
_sanityCheck(!_guts._isOpaque,
"_NSContiguousString requires contiguous storage")
self._guts = _guts
super.init()
}
@inlinable // FIXME(sil-serialize-all)
public init(_unmanaged guts: _StringGuts) {
_sanityCheck(!guts._isOpaque,
"_NSContiguousString requires contiguous storage")
if guts.isASCII {
self._guts = _StringGuts(_large: guts._unmanagedASCIIView)
} else {
self._guts = _StringGuts(_large: guts._unmanagedUTF16View)
}
super.init()
}
@inlinable // FIXME(sil-serialize-all)
public init(_unmanaged guts: _StringGuts, range: Range<Int>) {
_sanityCheck(!guts._isOpaque,
"_NSContiguousString requires contiguous storage")
if guts.isASCII {
self._guts = _StringGuts(_large: guts._unmanagedASCIIView[range])
} else {
self._guts = _StringGuts(_large: guts._unmanagedUTF16View[range])
}
super.init()
}
@usableFromInline // FIXME(sil-serialize-all)
@objc
init(coder aDecoder: AnyObject) {
_sanityCheckFailure("init(coder:) not implemented for _NSContiguousString")
}
@inlinable // FIXME(sil-serialize-all)
deinit {}
@inlinable
@objc(length)
public var length: Int {
return _guts.count
}
@inlinable
@objc(characterAtIndex:)
public func character(at index: Int) -> UInt16 {
defer { _fixLifetime(self) }
return _guts.codeUnit(atCheckedOffset: index)
}
@inlinable
@objc(getCharacters:range:)
public func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange) {
_precondition(aRange.location >= 0 && aRange.length >= 0)
let range: Range<Int> = aRange.location ..< aRange.location + aRange.length
_precondition(range.upperBound <= Int(_guts.count))
if _guts.isASCII {
_guts._unmanagedASCIIView[range]._copy(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count))
} else {
_guts._unmanagedUTF16View[range]._copy(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count))
}
_fixLifetime(self)
}
@inlinable
@objc(_fastCharacterContents)
public func _fastCharacterContents() -> UnsafePointer<UInt16>? {
guard !_guts.isASCII else { return nil }
return _guts._unmanagedUTF16View.start
}
@objc(copyWithZone:)
public func copy(with zone: _SwiftNSZone?) -> AnyObject {
// Since this string is immutable we can just return ourselves.
return self
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape the object referenced by the opaque pointer passed to it or
/// anything transitively reachable form this object. Doing so
/// will result in undefined behavior.
@inlinable // FIXME(sil-serialize-all)
@_semantics("self_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointer<Result>(
_ body: (OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
defer {
_fixLifetime(self)
}
return try body(selfAsPointer)
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape either object referenced by the opaque pointer pair passed to it or
/// transitively reachable objects. Doing so will result in undefined
/// behavior.
@inlinable // FIXME(sil-serialize-all)
@_semantics("pair_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointerPair<Result>(
_ rhs: _NSContiguousString,
_ body: (OpaquePointer, OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self)
defer {
_fixLifetime(self)
_fixLifetime(rhs)
}
return try body(selfAsPointer, rhsAsPointer)
}
}
extension String {
/// Same as `_bridgeToObjectiveC()`, but located inside the core standard
/// library.
@inlinable // FIXME(sil-serialize-all)
public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject {
if _guts._isSmall {
return _bridgeToCocoa(_guts._smallUTF8String)
}
if let cocoa = _guts._underlyingCocoaString {
return cocoa
}
return _NSContiguousString(_guts)
}
@inline(never) // Hide the CF dependency
public func _bridgeToObjectiveCImpl() -> AnyObject {
return _stdlib_binary_bridgeToObjectiveCImpl()
}
}
// Called by the SwiftObject implementation to get the description of a value
// as an NSString.
@_silgen_name("swift_stdlib_getDescription")
public func _getDescription<T>(_ x: T) -> AnyObject {
return String(reflecting: x)._bridgeToObjectiveCImpl()
}
#else // !_runtime(_ObjC)
@_fixed_layout // FIXME(sil-serialize-all)
public class _SwiftNativeNSString {
@usableFromInline // FIXME(sil-serialize-all)
internal init() {}
deinit {}
}
public protocol _NSStringCore: class {}
#endif
| apache-2.0 | 4c945227ace0e40f13fa36c49d6d3d60 | 31.091121 | 81 | 0.713506 | 4.316468 | false | false | false | false |
cocoa-ai/FacesVisionDemo | Faces/ClassificationService.swift | 1 | 2409 | import CoreML
import Vision
import VisionLab
/// Delegate protocol used for `ClassificationService`
protocol ClassificationServiceDelegate: class {
func classificationService(_ service: ClassificationService, didDetectGender gender: String)
func classificationService(_ service: ClassificationService, didDetectAge age: String)
func classificationService(_ service: ClassificationService, didDetectEmotion emotion: String)
}
/// Service used to perform gender, age and emotion classification
final class ClassificationService: ClassificationServiceProtocol {
/// The service's delegate
weak var delegate: ClassificationServiceDelegate?
/// Array of vision requests
private var requests = [VNRequest]()
/// Create CoreML model and classification requests
func setup() {
do {
// Gender request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: GenderNet().model),
completionHandler: handleGenderClassification
))
// Age request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: AgeNet().model),
completionHandler: handleAgeClassification
))
// Emotions request
requests.append(VNCoreMLRequest(
model: try VNCoreMLModel(for: CNNEmotions().model),
completionHandler: handleEmotionClassification
))
} catch {
assertionFailure("Can't load Vision ML model: \(error)")
}
}
/// Run individual requests one by one.
func classify(image: CIImage) {
do {
for request in self.requests {
let handler = VNImageRequestHandler(ciImage: image)
try handler.perform([request])
}
} catch {
print(error)
}
}
// MARK: - Handling
@objc private func handleGenderClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectGender: result)
}
@objc private func handleAgeClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectAge: result)
}
@objc private func handleEmotionClassification(request: VNRequest, error: Error?) {
let result = extractClassificationResult(from: request, count: 1)
delegate?.classificationService(self, didDetectEmotion: result)
}
}
| mit | 7ffbc539bd98846b7b8b692e0279f3da | 33.414286 | 96 | 0.722707 | 4.723529 | false | false | false | false |
litt1e-p/LPStatusBarBackgroundColor-swift | LPStatusBarBackgroundColorSample/LPStatusBarBackgroundColor/NavigationController.swift | 1 | 1933 | //
// NavigationController.swift
// LPStatusBarBackgroundColor
//
// Created by litt1e-p on 16/1/6.
// Copyright © 2016年 litt1e-p. All rights reserved.
//
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.statusBarBackgroundColor = UIColor.blackColor()
var barSize: CGSize = CGSizeMake(self.navigationBar.frame.size.width, 44)
self.navigationBar.setBackgroundImage(self.imageWithColor(UIColor.purpleColor(), andSize: &barSize), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
}
func imageWithColor(color: UIColor, inout andSize imageSize: CGSize) -> UIImage {
if CGSizeEqualToSize(imageSize, CGSizeZero) {
imageSize = CGSizeMake(1, 1)
}
let rect: CGRect = CGRectMake(0, 0, imageSize.width, imageSize.height)
UIGraphicsBeginImageContext(rect.size)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | c85c867b9331935a04e73c6b37fa1c3f | 34.740741 | 177 | 0.697409 | 5.331492 | false | false | false | false |
jamesjmtaylor/weg-ios | weg-ios/Animations/LoadingView.swift | 1 | 1456 | //
// LoadingView.swift
// weg-ios
//
// Created by Taylor, James on 5/24/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import UIKit
import Lottie
class LoadingView: UIView {
@IBOutlet weak var loadingView: LoadingView!
var animationView : LOTAnimationView?
static func getAndStartLoadingView() -> LoadingView {
guard let rootView = UIApplication.shared.keyWindow?.rootViewController?.view else {
return LoadingView()
}
guard let loadingView = Bundle.main.loadNibNamed("LoadingView",
owner: self,
options: nil)?.first as? LoadingView else {
return LoadingView()
}
loadingView.frame = rootView.frame
rootView.addSubview(loadingView)
loadingView.startAnimation()
loadingView.startAnimation()
return loadingView
}
func startAnimation(){
animationView = LOTAnimationView(name: "loading")
animationView?.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
loadingView.addSubview(animationView!)
animationView?.loopAnimation = true
animationView?.play()
}
func stopAnimation(){
DispatchQueue.main.asyncAfter(deadline: .now() + 2){
self.removeFromSuperview()
}
}
}
| mit | 1665e5a48f1c57ace991516956b1e862 | 32.068182 | 100 | 0.573196 | 5.469925 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/uiKit/uiKitCatalog/UIKitCatalog/TextViewController.swift | 3 | 7511 | /*
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 UITextView.
*/
import UIKit
class TextViewController: UIViewController, UITextViewDelegate {
// MARK: - Properties
@IBOutlet weak var textView: UITextView!
/// Used to adjust the text view's height when the keyboard hides and shows.
@IBOutlet weak var textViewBottomLayoutGuideConstraint: NSLayoutConstraint!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureTextView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Listen for changes to keyboard visibility so that we can adjust the text view accordingly.
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(TextViewController.handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(TextViewController.handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// MARK: - Keyboard Event Notifications
func handleKeyboardNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
// Get information about the animation.
let animationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let rawAnimationCurveValue = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).uintValue
let animationCurve = UIViewAnimationOptions(rawValue: rawAnimationCurveValue)
// Convert the keyboard frame from screen to view coordinates.
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewBeginFrame = view.convert(keyboardScreenBeginFrame, from: view.window)
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y
// The text view should be adjusted, update the constant for this constraint.
textViewBottomLayoutGuideConstraint.constant -= originDelta
// Inform the view that its autolayout constraints have changed and the layout should be updated.
view.setNeedsUpdateConstraints()
// Animate updating the view's layout by calling layoutIfNeeded inside a UIView animation block.
let animationOptions: UIViewAnimationOptions = [animationCurve, .beginFromCurrentState]
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOptions, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
// Scroll to the selected text once the keyboard frame changes.
let selectedRange = textView.selectedRange
textView.scrollRangeToVisible(selectedRange)
}
// MARK: - Configuration
func configureTextView() {
let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
let bodyFont = UIFont(descriptor: bodyFontDescriptor, size: 0)
textView.font = bodyFont
textView.textColor = UIColor.black
textView.backgroundColor = UIColor.white
textView.isScrollEnabled = true
/*
Let's modify some of the attributes of the attributed string.
You can modify these attributes yourself to get a better feel for what they do.
Note that the initial text is visible in the storyboard.
*/
let attributedText = NSMutableAttributedString(attributedString: textView.attributedText!)
/*
Use NSString so the result of rangeOfString is an NSRange, not Range<String.Index>.
This will then be the correct type to then pass to the addAttribute method of
NSMutableAttributedString.
*/
let text = textView.text! as NSString
// Find the range of each element to modify.
let boldRange = text.range(of: NSLocalizedString("bold", comment: ""))
let highlightedRange = text.range(of: NSLocalizedString("highlighted", comment: ""))
let underlinedRange = text.range(of: NSLocalizedString("underlined", comment: ""))
let tintedRange = text.range(of: NSLocalizedString("tinted", comment: ""))
/*
Add bold. Take the current font descriptor and create a new font descriptor
with an additional bold trait.
*/
let boldFontDescriptor = textView.font!.fontDescriptor.withSymbolicTraits(.traitBold)
let boldFont = UIFont(descriptor: boldFontDescriptor!, size: 0)
attributedText.addAttribute(NSFontAttributeName, value: boldFont, range: boldRange)
// Add highlight.
attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.applicationGreenColor, range: highlightedRange)
// Add underline.
attributedText.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: underlinedRange)
// Add tint.
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.applicationBlueColor, range: tintedRange)
// Add image attachment.
let textAttachment = NSTextAttachment()
let image = UIImage(named: "text_view_attachment")!
textAttachment.image = image
textAttachment.bounds = CGRect(origin: CGPoint.zero, size: image.size)
let textAttachmentString = NSAttributedString(attachment: textAttachment)
attributedText.append(textAttachmentString)
// Append a space with matching font of the rest of the body text.
let appendedSpace = NSMutableAttributedString.init(string: " ")
appendedSpace.addAttribute(NSFontAttributeName, value: bodyFont, range: NSMakeRange(0, 1))
attributedText.append(appendedSpace)
textView.attributedText = attributedText
}
// MARK: - UITextViewDelegate
func textViewDidBeginEditing(_ textView: UITextView) {
/*
Provide a "Done" button for the user to select to signify completion
with writing text in the text view.
*/
let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(TextViewController.doneBarButtonItemClicked))
navigationItem.setRightBarButton(doneBarButtonItem, animated: true)
}
// MARK: - Actions
func doneBarButtonItemClicked() {
// Dismiss the keyboard by removing it as the first responder.
textView.resignFirstResponder()
navigationItem.setRightBarButton(nil, animated: true)
}
}
| mit | 94e836d41db1b9454bc667ef1920f5d7 | 43.431953 | 175 | 0.707151 | 5.852689 | false | false | false | false |
pentateu/SpeedTracker | SpeedTracker/RunViewController.swift | 1 | 3478 | //
// ViewController.swift
// SpeedTracker
//
// Created by Rafael Almeida on 23/07/15.
// Copyright (c) 2015 ISWE. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class RunViewController: UIViewController, MovementTrackerDelegate, MKMapViewDelegate {
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var maxSpeedLabel: UILabel!
@IBOutlet weak var avgSpeedLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var statusLabel: UILabel!
let tracker = MovementTracker()
override func viewDidLoad() {
super.viewDidLoad()
setupMapView();
tracker.delegate = self
if(CLLocationManager.locationServicesEnabled()){
statusLabel.text = "starting ..."
tracker.start()
}
else{
statusLabel.text = "Location services disabled ;-("
}
}
func setupMapView(){
self.mapView.delegate = self
}
func updateSpeedDisplay(tracker:MovementTracker, locationInfo:LocationInfo){
maxSpeedLabel.text = "\(tracker.maxSpeed) km/h"
avgSpeedLabel.text = "\(tracker.averageSpeed) km/h"
speedLabel.text = "\(locationInfo.speed) km/h"
}
func calculateMapRegion(latitudeRange:MinMax, longitudeRange:MinMax) -> MKCoordinateRegion {
let lat = (latitudeRange.min + latitudeRange.max) / 2
let lng = (longitudeRange.min + longitudeRange.max) / 2
let center = CLLocationCoordinate2DMake(lat, lng)
let latitudeDelta = (latitudeRange.max - latitudeRange.min) * 1.1 // 10% padding
let longitudeDelta = (longitudeRange.max - longitudeRange.min) * 1.1 // 10% padding
let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)
let region = MKCoordinateRegionMake(center, span)
return region
}
func createPolyline() -> MKPolyline {
var coordinates = [
tracker.locations[tracker.locations.count - 2].location.coordinate,
tracker.locations[tracker.locations.count - 1].location.coordinate
]
return MKPolyline(coordinates: &coordinates , count: 2)
}
func updateMapDisplay(tracker:MovementTracker, locationInfo:LocationInfo){
let mapRegion = calculateMapRegion(tracker.latitudeRange, longitudeRange: tracker.longitudeRange)
self.mapView.region = mapRegion
if tracker.locations.count > 1 {
self.mapView.addOverlay(createPolyline())
}
}
//MovementTrackerDelegate
func locationAdded(tracker:MovementTracker, locationInfo:LocationInfo){
updateSpeedDisplay(tracker, locationInfo: locationInfo)
updateMapDisplay(tracker, locationInfo: locationInfo)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Map Delegate
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if let polyLine = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyLine)
renderer.strokeColor = UIColor.blackColor()
renderer.lineWidth = 3
return renderer
}
return nil
}
}
| mit | ce98d7fa532efc2af470966e4a85c251 | 29.778761 | 105 | 0.63916 | 5.160237 | false | false | false | false |
indragiek/INDLinkLabel | INDLinkLabel.swift | 1 | 10646 | //
// INDLinkLabel.swift
// INDLinkLabel
//
// Created by Indragie on 12/31/14.
// Copyright (c) 2014 Indragie Karunaratne. 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 UIKit
@objc public protocol INDLinkLabelDelegate {
/// Called when a link is tapped.
@objc optional func linkLabel(_ label: INDLinkLabel, didTapLinkWithURL URL: URL)
/// Called when a link is long pressed.
@objc optional func linkLabel(_ label: INDLinkLabel, didLongPressLinkWithURL URL: URL)
/// Called when parsing links from attributed text.
/// The delegate may determine whether to use the text's original attributes,
/// use the proposed INDLinkLabel attributes (blue text color, and underlined),
/// or supply a completely custom set of attributes for the given link.
@objc optional func linkLabel(_ label: INDLinkLabel, attributesForURL URL: URL, originalAttributes: [String: AnyObject], proposedAttributes: [String: AnyObject]) -> [String: AnyObject]
}
/// A simple UILabel subclass that allows for tapping and long pressing on links
/// (i.e. anything marked with `NSLinkAttributeName`)
@IBDesignable open class INDLinkLabel: UILabel {
@IBOutlet open weak var delegate: INDLinkLabelDelegate?
// MARK: Styling
override open var attributedText: NSAttributedString? {
didSet { processLinks() }
}
override open var lineBreakMode: NSLineBreakMode {
didSet { textContainer.lineBreakMode = lineBreakMode }
}
/// The color of the highlight that appears over a link when tapping on it
@IBInspectable open var linkHighlightColor: UIColor = UIColor(white: 0, alpha: 0.2)
/// The corner radius of the highlight that appears over a link when
/// tapping on it
@IBInspectable open var linkHighlightCornerRadius: CGFloat = 2
// MARK: Text Layout
override open var numberOfLines: Int {
didSet {
textContainer.maximumNumberOfLines = numberOfLines
}
}
override open var adjustsFontSizeToFitWidth: Bool {
didSet {
if adjustsFontSizeToFitWidth {
fatalError("INDLinkLabel does not support the adjustsFontSizeToFitWidth property")
}
}
}
// MARK: Private
fileprivate var layoutManager = NSLayoutManager()
fileprivate var textStorage = NSTextStorage()
fileprivate var textContainer = NSTextContainer()
fileprivate struct LinkRange {
let URL: Foundation.URL
let glyphRange: NSRange
}
fileprivate var linkRanges: [LinkRange]?
fileprivate var tappedLinkRange: LinkRange? {
didSet {
setNeedsDisplay()
}
}
// MARK: Initialization
fileprivate func commonInit() {
precondition(!adjustsFontSizeToFitWidth, "INDLinkLabel does not support the adjustsFontSizeToFitWidth property")
textContainer.maximumNumberOfLines = numberOfLines
textContainer.lineBreakMode = lineBreakMode
textContainer.lineFragmentPadding = 0
layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
textStorage = NSTextStorage()
textStorage.addLayoutManager(layoutManager)
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(INDLinkLabel.handleTap(_:))))
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(INDLinkLabel.handleLongPress(_:))))
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: Attributes
fileprivate struct DefaultLinkAttributes {
static let Color = UIColor.blue
static let UnderlineStyle = NSUnderlineStyle.styleSingle
}
fileprivate func processLinks() {
var ranges = [LinkRange]()
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
textStorage.enumerateAttribute(NSLinkAttributeName, in: NSRange(location: 0, length: textStorage.length), options: []) { (value, range, _) in
// Because NSLinkAttributeName supports both NSURL and NSString
// values. *sigh*
let URL: Foundation.URL? = {
if let string = value as? String {
return Foundation.URL(string: string)
} else {
return value as? Foundation.URL
}
}()
if let URL = URL {
let glyphRange = self.layoutManager.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
ranges.append(LinkRange(URL: URL, glyphRange: glyphRange))
// Remove `NSLinkAttributeName` to prevent `UILabel` from applying
// the default styling.
self.textStorage.removeAttribute(NSLinkAttributeName, range: range)
let originalAttributes = self.textStorage.attributes(at: range.location, effectiveRange: nil)
var proposedAttributes = originalAttributes
if originalAttributes[NSForegroundColorAttributeName] == nil {
proposedAttributes[NSForegroundColorAttributeName] = DefaultLinkAttributes.Color
}
if originalAttributes[NSUnderlineStyleAttributeName] == nil {
proposedAttributes[NSUnderlineStyleAttributeName] = DefaultLinkAttributes.UnderlineStyle.rawValue
}
let acceptedAttributes = self.delegate?.linkLabel?(self, attributesForURL: URL, originalAttributes: originalAttributes as [String : AnyObject], proposedAttributes: proposedAttributes as [String : AnyObject])
?? proposedAttributes;
self.textStorage.setAttributes(acceptedAttributes, range: range)
}
}
}
linkRanges = ranges
super.attributedText = textStorage
}
// MARK: Drawing
open override func draw(_ rect: CGRect) {
super.draw(rect)
if let linkRange = tappedLinkRange {
linkHighlightColor.setFill()
for rect in highlightRectsForGlyphRange(linkRange.glyphRange) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: linkHighlightCornerRadius)
path.fill()
}
}
}
fileprivate func highlightRectsForGlyphRange(_ range: NSRange) -> [CGRect] {
var rects = [CGRect]()
layoutManager.enumerateLineFragments(forGlyphRange: range) { (_, rect, _, effectiveRange, _) in
let boundingRect = self.layoutManager.boundingRect(forGlyphRange: NSIntersectionRange(range, effectiveRange), in: self.textContainer)
rects.append(boundingRect)
}
return rects
}
// MARK: Touches
fileprivate func linkRangeAtPoint(_ point: CGPoint) -> LinkRange? {
if let linkRanges = linkRanges {
// Passing in the UILabel's fitting size here doesn't work, the height
// needs to be unrestricted for it to correctly lay out all the text.
// Might be due to a difference in the computed text sizes of `UILabel`
// and `NSLayoutManager`.
textContainer.size = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
layoutManager.ensureLayout(for: textContainer)
let boundingRect = layoutManager.boundingRect(forGlyphRange: layoutManager.glyphRange(for: textContainer), in: textContainer)
if boundingRect.contains(point) {
let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer)
for linkRange in linkRanges {
if NSLocationInRange(glyphIndex, linkRange.glyphRange) {
return linkRange
}
}
}
}
return nil
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Any taps that don't hit a link are ignored and passed to the next
// responder.
return linkRangeAtPoint(point) != nil
}
@objc fileprivate func handleTap(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .ended:
tappedLinkRange = linkRangeAtPoint(gestureRecognizer.location(ofTouch: 0, in: self))
default:
tappedLinkRange = nil
}
if let linkRange = tappedLinkRange {
delegate?.linkLabel?(self, didTapLinkWithURL: linkRange.URL)
tappedLinkRange = nil
}
}
@objc fileprivate func handleLongPress(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
tappedLinkRange = linkRangeAtPoint(gestureRecognizer.location(ofTouch: 0, in: self))
default:
tappedLinkRange = nil
}
if let linkRange = tappedLinkRange {
delegate?.linkLabel?(self, didLongPressLinkWithURL: linkRange.URL)
}
}
}
| mit | a8ef11231c454a3a10e668157a642a09 | 40.263566 | 227 | 0.638738 | 5.641759 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Home/LeftRefreshView.swift | 1 | 4363 | //
// LeftRefreshView.swift
// PinGo
//
// Created by GaoWanli on 16/1/31.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
enum LeftRefreshViewState {
case `default`, pulling, refreshing
}
private let kLeftRefreshViewWidth: CGFloat = 65.0
class LeftRefreshView: UIControl {
fileprivate var scrollView: UIScrollView?
fileprivate var beforeState: LeftRefreshViewState = .default
fileprivate var refreshState: LeftRefreshViewState = .default {
didSet {
switch refreshState {
case .default:
imageView.shouldAnimating = false
if beforeState == .refreshing {
UIView.animate(withDuration: 0.25, animations: { () in
var contentInset = self.scrollView!.contentInset
contentInset.left -= kLeftRefreshViewWidth
self.scrollView?.contentInset = contentInset
debugPrint("\(type(of: self)) \(#function) \(#line)")
})
}
case .pulling:
imageView.shouldAnimating = true
debugPrint("\(type(of: self)) \(#function) \(#line)")
case .refreshing:
UIView.animate(withDuration: 0.25, animations: { () in
var contentInset = self.scrollView!.contentInset
contentInset.left += kLeftRefreshViewWidth
self.scrollView?.contentInset = contentInset
debugPrint("\(type(of: self)) \(#function) \(#line)")
})
// 调用刷新的方法
sendActions(for: .valueChanged)
}
beforeState = refreshState
}
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if let s = newSuperview, s.isKind(of: UIScrollView.self) {
s.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
scrollView = s as? UIScrollView
frame = CGRect(x: -kLeftRefreshViewWidth, y: 0, width: kLeftRefreshViewWidth, height: s.bounds.height)
addSubview(imageView)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let leftInset = scrollView!.contentInset.left
let offsetX = scrollView!.contentOffset.x
let criticalValue = -leftInset - bounds.width
// 拖动
if scrollView!.isDragging {
if refreshState == .default && offsetX < criticalValue {
// 完全显示出来
refreshState = .pulling
}else if refreshState == .pulling && offsetX >= criticalValue {
// 没有完全显示出来/没有显示出来
refreshState = .default
}
}else {
// 结束拖动
if refreshState == .pulling {
refreshState = .refreshing
}
}
}
func endRefresh() {
refreshState = .default
}
deinit {
if let s = scrollView {
s.removeObserver(self, forKeyPath: "contentOffset")
}
}
// MARK: lazy loading
fileprivate lazy var imageView: LeftImageView = {
let y = (self.bounds.height - kLeftRefreshViewWidth) * 0.5 - self.scrollView!.contentInset.top - kTabBarHeight
let i = LeftImageView(frame: CGRect(x: 0, y: y, width: kLeftRefreshViewWidth, height: kLeftRefreshViewWidth))
i.image = UIImage(named: "loading0")
i.contentMode = .center
return i
}()
}
private class LeftImageView: UIImageView {
var shouldAnimating: Bool = false {
didSet {
if shouldAnimating {
if !isAnimating {
var images = [UIImage]()
for i in 0..<3 {
images.append(UIImage(named: "loading\(i)")!)
}
self.animationImages = images
self.animationDuration = 1.0
startAnimating()
}
}else {
stopAnimating()
}
}
}
}
| mit | de2c01f467492859aaee68345801a99a | 33.910569 | 151 | 0.54681 | 5.294698 | false | false | false | false |
PerfectlySoft/Perfect-Authentication | Sources/OAuth2/OAuth2.swift | 1 | 4942 | //
// OAuth2.swift
// Based on Turnstile's oAuth2
//
// Created by Edward Jiang on 8/7/16.
//
// Modified by Jonathan Guthrie 18 Jan 2017
// Intended to work more independantly of Turnstile
import Foundation
import PerfectHTTP
/**
OAuth 2 represents the base API Client for an OAuth 2 server that implements the
authorization code grant type. This is the typical redirect based login flow.
Since OAuth doesn't define token validation, implementing it is up to a subclass.
*/
open class OAuth2 {
/// The Client ID for the OAuth 2 Server
public let clientID: String
/// The Client Secret for the OAuth 2 Server
public let clientSecret: String
/// The Authorization Endpoint of the OAuth 2 Server
public let authorizationURL: String
/// The Token Endpoint of the OAuth 2 Server
public let tokenURL: String
/// Creates the OAuth 2 client
public init(clientID: String, clientSecret: String, authorizationURL: String, tokenURL: String) {
self.clientID = clientID
self.clientSecret = clientSecret
self.authorizationURL = authorizationURL
self.tokenURL = tokenURL
}
/// Gets the login link for the OAuth 2 server. Redirect the end user to this URL
///
/// - parameter redirectURL: The URL for the server to redirect the user back to after login.
/// You will need to configure this in the admin console for the OAuth provider's site.
/// - parameter state: A randomly generated string to prevent CSRF attacks.
/// Verify this when validating the Authorization Code
/// - parameter scopes: A list of OAuth scopes you'd like the user to grant
open func getLoginLink(redirectURL: String, state: String, scopes: [String] = []) -> String {
var url = "\(authorizationURL)?response_type=code"
url += "&client_id=\(clientID.stringByEncodingURL)"
url += "&redirect_uri=\(redirectURL.stringByEncodingURL)"
url += "&state=\(state.stringByEncodingURL)"
url += "&scope=\((scopes.joined(separator: " ")).stringByEncodingURL)"
return url
}
/// Exchanges an authorization code for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
open func exchange(authorizationCode: AuthorizationCode) throws -> OAuth2Token {
let postBody = ["grant_type": "authorization_code",
"client_id": clientID,
"client_secret": clientSecret,
"redirect_uri": authorizationCode.redirectURL,
"code": authorizationCode.code]
// let (_, data, _, _) = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
let data = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
guard let token = OAuth2Token(json: data) else {
if let error = OAuth2Error(json: data) {
throw error
} else {
throw InvalidAPIResponse()
}
}
return token
}
/// Parses a URL and exchanges the OAuth 2 access token and exchanges it for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
/// - throws: OAuth2Error() if the oauth server calls back with an error
open func exchange(request: HTTPRequest, state: String, redirectURL: String) throws -> OAuth2Token {
//request.param(name: "state") == state
guard let code = request.param(name: "code")
else {
print("Where's the code?")
throw InvalidAPIResponse()
}
return try exchange(authorizationCode: AuthorizationCode(code: code, redirectURL: redirectURL))
}
// TODO: add refresh token support
}
extension URLComponents {
var queryDictionary: [String: String] {
var result = [String: String]()
guard let components = query?.components(separatedBy: "&") else {
return result
}
components.forEach { component in
let queryPair = component.components(separatedBy: "=")
if queryPair.count == 2 {
result[queryPair[0]] = queryPair[1]
} else {
result[queryPair[0]] = ""
}
}
return result
}
}
extension URLComponents {
mutating func setQueryItems(dict: [String: String]) {
query = dict.map { (key, value) in
return key + "=" + value
}.joined(separator: "&")
}
}
| apache-2.0 | afd210aa2f9419d0a999973661dfc3fd | 38.222222 | 105 | 0.637798 | 4.724665 | false | false | false | false |
jackmc-xx/firefox-ios | Client/Frontend/Login/PasswordTextField.swift | 3 | 1561 | // 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
private let ImagePathReveal = "visible-text.png"
class PasswordTextField: ImageTextField {
required override init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitView()
}
override init(frame: CGRect) {
super.init(frame: frame)
didInitView()
}
override init() {
// init() calls init(frame) with a 0 rect.
super.init()
}
private func didInitView() {
let image = UIImage(named: ImagePathReveal)!
// TODO: We should resize the raw image instead of programmatically scaling it.
let scale: CGFloat = 0.7
let button = UIButton(frame: CGRectMake(0, 0, image.size.width * scale, image.size.height * scale))
button.setImage(image, forState: UIControlState.Normal)
let padding: CGFloat = 10
let paddingView = UIView(frame: CGRectMake(0, 0, button.bounds.width + padding, button.bounds.height))
button.center = paddingView.center
paddingView.addSubview(button)
rightView = paddingView
rightViewMode = UITextFieldViewMode.Always
button.addTarget(self, action: "didClickPasswordReveal", forControlEvents: UIControlEvents.TouchUpInside)
}
// Referenced as button selector.
func didClickPasswordReveal() {
secureTextEntry = !secureTextEntry
}
}
| mpl-2.0 | 260be89624e9570cccc8c0d5c975e8a5 | 33.688889 | 113 | 0.671365 | 4.397183 | false | false | false | false |
byss/KBAPISupport | KBAPISupport/Core/Internal/UTIdentifier.swift | 1 | 4985 | //
// UTIdentifier.swift
// Copyright © 2018 Kirill byss Bystrov. 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
#if os (iOS) || os (tvOS) || os (watchOS)
import MobileCoreServices
#elseif os (macOS)
import CoreServices
#else
#error ("Unsupported platform")
#endif
internal struct UTIdentifier {
private let rawValue: CFString;
}
internal extension UTIdentifier {
internal static let data = UTIdentifier (rawValue: kUTTypeData);
private static let isDeclared = UTTypeIsDeclared;
private static let isDynamic = UTTypeIsDynamic;
internal var value: String {
return self.rawValue as String;
}
internal var isDeclared: Bool {
return UTIdentifier.isDeclared (self.rawValue);
}
internal var isDynamic: Bool {
return UTIdentifier.isDynamic (self.rawValue);
}
internal var declaration: [String: Any]? {
guard let rawDeclaration = UTTypeCopyDeclaration (self.rawValue) else {
return nil;
}
return rawDeclaration.takeUnretainedValue () as NSDictionary as? [String: Any];
}
internal var bundleURL: URL? {
return UTTypeCopyDeclaringBundleURL (self.rawValue)?.takeUnretainedValue () as URL?;
}
internal static func preferred (forTag tag: Tag, withValue tagValue: String, conformingTo otherIdentifier: UTIdentifier?) -> UTIdentifier? {
return (UTTypeCreatePreferredIdentifierForTag (tag.rawValue, tagValue as CFString, otherIdentifier?.rawValue)?.takeUnretainedValue ()).map (UTIdentifier.init);
}
internal static func allIdentifiers (forTag tag: Tag, withValue tagValue: String, conformingTo otherIdentifier: UTIdentifier?) -> [UTIdentifier]? {
guard let rawIdentifiers = UTTypeCreateAllIdentifiersForTag (tag.rawValue, tagValue as CFString, otherIdentifier?.rawValue) else {
return nil;
}
return CFArrayWrapper (rawIdentifiers.takeUnretainedValue ()).map (UTIdentifier.init);
}
internal static func isDeclared (_ identifierValue: String) -> Bool {
return self.isDeclared (identifierValue as CFString);
}
internal static func isDynamic (_ identifierValue: String) -> Bool {
return self.isDynamic (identifierValue as CFString);
}
internal init? (string: String) {
guard !string.isEmpty else {
return nil;
}
self.init (rawValue: string as CFString);
}
internal func conforms (to identifier: UTIdentifier) -> Bool {
return UTTypeConformsTo (self.rawValue, identifier.rawValue);
}
internal func preferredValue (ofTag tag: Tag) -> String? {
return UTTypeCopyPreferredTagWithClass (self.rawValue, tag.rawValue)?.takeUnretainedValue () as String?;
}
internal func allValues (ofTag tag: Tag) -> [String]? {
return (UTTypeCopyAllTagsWithClass (self.rawValue, tag.rawValue)?.takeUnretainedValue ()).map (CFArrayWrapper <CFString>.init)?.map { $0 as String };
}
}
internal extension UTIdentifier {
internal enum Tag {
case mimeType;
case filenameExtension;
fileprivate var rawValue: CFString {
switch (self) {
case .mimeType:
return kUTTagClassMIMEType;
case .filenameExtension:
return kUTTagClassFilenameExtension;
}
}
}
}
extension UTIdentifier: Equatable {
internal static func == (lhs: UTIdentifier, rhs: UTIdentifier) -> Bool {
return UTTypeEqual (lhs.rawValue, rhs.rawValue);
}
}
extension UTIdentifier: CustomStringConvertible {
internal var description: String {
return (UTTypeCopyDescription (self.rawValue)?.takeUnretainedValue () ?? self.rawValue) as String;
}
}
private struct CFArrayWrapper <Element> {
private let wrapped: CFArray;
fileprivate init (_ array: CFArray) {
self.wrapped = array;
}
}
extension CFArrayWrapper: RandomAccessCollection {
fileprivate var startIndex: CFIndex {
return 0;
}
fileprivate var endIndex: CFIndex {
return CFArrayGetCount (self.wrapped);
}
fileprivate subscript (index: CFIndex) -> Element {
return CFArrayGetValueAtIndex (self.wrapped, index)!.assumingMemoryBound (to: Element.self).pointee;
}
}
| mit | b9b164a1eafe63ac64a51a60b05024a5 | 31.363636 | 161 | 0.748194 | 4.125828 | false | false | false | false |
dfelber/SwiftStringScore | SwiftStringScore/SwiftStringScore.playground/Contents.swift | 1 | 2087 | //
// String+Score.playground
//
// Created by Dominik Felber on 07.04.2016.
// Copyright (c) 2016 Dominik Felber. All rights reserved.
//
// If you have problems importing 'SwiftStringScore' please ensure that you:
// * are using the workspace
// * built the framework target 'SwiftStringScore-iOS' once
@testable import SwiftStringScore
"hello world".scoreAgainst("axl") // => 0
"hello world".scoreAgainst("ow") // => 0.3545455
// Single letter match
"hello world".scoreAgainst("e") // => 0.1090909
// Single letter match plus bonuses for beginning of word and beginning of phrase
"hello world".scoreAgainst("h") // => 0.5863637
"hello world".scoreAgainst("w") // => 0.5454546
"hello world".scoreAgainst("he") // => 0.6227273
"hello world".scoreAgainst("hel") // => 0.6590909
"hello world".scoreAgainst("hell") // => 0.6954546
"hello world".scoreAgainst("hello") // => 0.7318182
"hello world".scoreAgainst("hello ") // => 0.7681818
"hello world".scoreAgainst("hello w") // => 0.8045455
"hello world".scoreAgainst("hello wo") // => 0.8409091
"hello world".scoreAgainst("hello wor") // => 0.8772728
"hello world".scoreAgainst("hello worl") // => 0.9136364
"hello world".scoreAgainst("hello world") // => 1.0
// Using a "1" in place of an "l" is a mismatch unless the score is fuzzy
"hello world".scoreAgainst("hello wor1") // => 0
"hello world".scoreAgainst("hello wor1", fuzziness: 0.5) // => 0.6145455 (fuzzy)
// Finding a match in a shorter string is more significant.
"Hello".scoreAgainst("h") // => 0.5700001
"He".scoreAgainst("h") // => 0.6750001
// Same case matches better than wrong case
"Hello".scoreAgainst("h") // => 0.5700001
"Hello".scoreAgainst("H") // => 0.63
// Acronyms are given a little more weight
"Hillsdale Michigan".scoreAgainst("HiMi") > "Hillsdale Michigan".scoreAgainst("Hills")
"Hillsdale Michigan".scoreAgainst("HiMi") < "Hillsdale Michigan".scoreAgainst("Hillsd")
// Unicode supported
"🐱".scoreAgainst("🐱") // => 1
"🐱".scoreAgainst("🐼") // => 0
"🐱🙃".scoreAgainst("🙃") // => 0.15
"🐱🙃".scoreAgainst("🐱") // => 0.75
| mit | cb0bcfe96238853604f346be0bd0a421 | 36.4 | 87 | 0.678172 | 3.179289 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBAActiveTask.swift | 1 | 14712 | //
// SBAActiveTaskFactory.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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 ResearchKit
import BridgeSDK
import AVFoundation
public enum SBAActiveTaskType {
case custom(String?)
case memory
case tapping
case voice
case walking
case tremor
case moodSurvey
init(name: String?) {
guard let type = name else { self = .custom(nil); return }
switch(type) {
case "tapping" : self = .tapping
case "memory" : self = .memory
case "voice" : self = .voice
case "walking" : self = .walking
case "tremor" : self = .tremor
case "moodSurvey" : self = .moodSurvey
default : self = .custom(name)
}
}
func isNilType() -> Bool {
if case .custom(let customType) = self {
return (customType == nil)
}
return false
}
}
extension ORKPredefinedTaskHandOption {
init(name: String?) {
let name = name ?? "both"
switch name {
case "right" : self = .right
case "left" : self = .left
default : self = .both
}
}
}
extension ORKTremorActiveTaskOption {
init(excludes: [String]?) {
guard let excludes = excludes else {
self.init(rawValue: 0)
return
}
let rawValue: UInt = excludes.map({ (exclude) -> ORKTremorActiveTaskOption in
switch exclude {
case "inLap" : return .excludeHandInLap
case "shoulderHeight" : return .excludeHandAtShoulderHeight
case "elbowBent" : return .excludeHandAtShoulderHeightElbowBent
case "touchNose" : return .excludeHandToNose
case "queenWave" : return .excludeQueenWave
default : return []
}
}).reduce(0) { (raw, option) -> UInt in
return option.rawValue | raw
}
self.init(rawValue: rawValue)
}
}
extension ORKMoodSurveyFrequency {
init(name: String?) {
let name = name ?? "daily"
switch name {
case "weekly" : self = .weekly
default : self = .daily
}
}
}
public protocol SBAActiveTask: SBABridgeTask, SBAStepTransformer {
var taskType: SBAActiveTaskType { get }
var intendedUseDescription: String? { get }
var taskOptions: [String : AnyObject]? { get }
var predefinedExclusions: ORKPredefinedTaskOption? { get }
var localizedSteps: [SBASurveyItem]? { get }
var optional: Bool { get }
}
extension SBAActiveTask {
func createDefaultORKActiveTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask? {
let predefinedExclusions = self.predefinedExclusions ?? options
// Map known active tasks
var task: ORKOrderedTask!
switch self.taskType {
case .tapping:
task = tappingTask(predefinedExclusions)
case .memory:
task = memoryTask(predefinedExclusions)
case .voice:
task = voiceTask(predefinedExclusions)
case .walking:
task = walkingTask(predefinedExclusions)
case .tremor:
task = tremorTask(predefinedExclusions)
case .moodSurvey:
task = moodSurvey(predefinedExclusions)
default:
// exit early if not supported by base implementation
return nil
}
// Modify the instruction step if this is an optional task
if self.optional {
task = taskWithSkipAction(task)
}
// map the localized steps
mapLocalizedSteps(task)
return task
}
func taskWithSkipAction(_ task: ORKOrderedTask) -> ORKOrderedTask {
guard type(of: task) === ORKOrderedTask.self else {
assertionFailure("Handling of an optional task is not implemented for any class other than ORKOrderedTask")
return task
}
guard let introStep = task.steps.first as? ORKInstructionStep else {
assertionFailure("Handling of an optional task is not implemented for tasks that do not start with ORKIntructionStep")
return task
}
guard let conclusionStep = task.steps.last as? ORKInstructionStep else {
assertionFailure("Handling of an optional task is not implemented for tasks that do not end with ORKIntructionStep")
return task
}
// Replace the intro step with a direct navigation step that has a skip button
// to skip to the conclusion
let replaceStep = SBAInstructionStep(identifier: introStep.identifier)
replaceStep.title = introStep.title
replaceStep.text = introStep.text
let skipExplanation = Localization.localizedString("SBA_SKIP_ACTIVITY_INSTRUCTION")
let detail = introStep.detailText ?? ""
replaceStep.detailText = "\(detail)\n\(skipExplanation)\n"
replaceStep.learnMoreAction = SBASkipAction(identifier: conclusionStep.identifier)
replaceStep.learnMoreAction!.learnMoreButtonText = Localization.localizedString("SBA_SKIP_ACTIVITY")
var steps: [ORKStep] = task.steps
steps.removeFirst()
steps.insert(replaceStep, at: 0)
// Return a navigable ordered task
return SBANavigableOrderedTask(identifier: task.identifier, steps: steps)
}
func mapLocalizedSteps(_ task: ORKOrderedTask) {
// Map the title, text and detail from the localizedSteps to their matching step from the
// base factory method defined
if let items = self.localizedSteps {
for item in items {
if let step = task.steps.find({ return $0.identifier == item.identifier }) {
step.title = item.stepTitle ?? step.title
step.text = item.stepText ?? step.text
if let instructionItem = item as? SBAInstructionStepSurveyItem,
let detail = instructionItem.stepDetail,
let instructionStep = step as? ORKInstructionStep {
instructionStep.detailText = detail
}
if let activeStep = step as? ORKActiveStep,
let activeItem = item as? SBAActiveStepSurveyItem {
if let spokenInstruction = activeItem.stepSpokenInstruction {
activeStep.spokenInstruction = spokenInstruction
}
if let finishedSpokenInstruction = activeItem.stepFinishedSpokenInstruction {
activeStep.finishedSpokenInstruction = finishedSpokenInstruction
}
}
}
}
}
}
func tappingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String)
return ORKOrderedTask.twoFingerTappingIntervalTask(
withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
duration: duration,
handOptions: handOptions,
options: options)
}
func memoryTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let initialSpan: Int = taskOptions?["initialSpan"] as? Int ?? 3
let minimumSpan: Int = taskOptions?["minimumSpan"] as? Int ?? 2
let maximumSpan: Int = taskOptions?["maximumSpan"] as? Int ?? 15
let playSpeed: TimeInterval = taskOptions?["playSpeed"] as? TimeInterval ?? 1.0
let maxTests: Int = taskOptions?["maxTests"] as? Int ?? 5
let maxConsecutiveFailures: Int = taskOptions?["maxConsecutiveFailures"] as? Int ?? 3
var customTargetImage: UIImage? = nil
if let imageName = taskOptions?["customTargetImageName"] as? String {
customTargetImage = SBAResourceFinder.shared.image(forResource: imageName)
}
let customTargetPluralName: String? = taskOptions?["customTargetPluralName"] as? String
let requireReversal: Bool = taskOptions?["requireReversal"] as? Bool ?? false
return ORKOrderedTask.spatialSpanMemoryTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
initialSpan: initialSpan,
minimumSpan: minimumSpan,
maximumSpan: maximumSpan,
playSpeed: playSpeed,
maximumTests: maxTests,
maximumConsecutiveFailures: maxConsecutiveFailures,
customTargetImage: customTargetImage,
customTargetPluralName: customTargetPluralName,
requireReversal: requireReversal,
options: options)
}
func voiceTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let speechInstruction: String? = taskOptions?["speechInstruction"] as? String
let shortSpeechInstruction: String? = taskOptions?["shortSpeechInstruction"] as? String
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let recordingSettings: [String: AnyObject]? = taskOptions?["recordingSettings"] as? [String: AnyObject]
return ORKOrderedTask.audioTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
speechInstruction: speechInstruction,
shortSpeechInstruction: shortSpeechInstruction,
duration: duration,
recordingSettings: recordingSettings,
checkAudioLevel: true,
options: options)
}
func walkingTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
// The walking activity is assumed to be walking back and forth rather than trying to walk down a long hallway.
let walkDuration: TimeInterval = taskOptions?["walkDuration"] as? TimeInterval ?? 30.0
let restDuration: TimeInterval = taskOptions?["restDuration"] as? TimeInterval ?? 30.0
return ORKOrderedTask.walkBackAndForthTask(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
walkDuration: walkDuration,
restDuration: restDuration,
options: options)
}
func tremorTask(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let duration: TimeInterval = taskOptions?["duration"] as? TimeInterval ?? 10.0
let handOptions = ORKPredefinedTaskHandOption(name: taskOptions?["handOptions"] as? String)
let excludeOptions = ORKTremorActiveTaskOption(excludes: taskOptions?["excludePostions"] as? [String])
return ORKOrderedTask.tremorTest(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
activeStepDuration: duration,
activeTaskOptions: excludeOptions,
handOptions: handOptions,
options: options)
}
func moodSurvey(_ options: ORKPredefinedTaskOption) -> ORKOrderedTask {
let frequency = ORKMoodSurveyFrequency(name: taskOptions?["frequency"] as? String)
let customQuestionText = taskOptions?["customQuestionText"] as? String
return ORKOrderedTask.moodSurvey(withIdentifier: self.schemaIdentifier,
intendedUseDescription: self.intendedUseDescription,
frequency: frequency,
customQuestionText: customQuestionText,
options: options)
}
}
| bsd-3-clause | d5e755e49b6d8e41aad6831e392f3e01 | 45.701587 | 130 | 0.589627 | 5.452557 | false | false | false | false |
appsquickly/backdrop | source/CommandLine/CommandLine.swift | 2 | 9396 | /*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for setlocale(3) */
@exported import Darwin
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
private struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(s: String) {
fputs(s, stderr)
}
}
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
public class CommandLine {
private var _arguments: [String]
private var _options: [Option] = [Option]()
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: ErrorType, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joinWithSeparator(", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Process.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(flagIndex: Int) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
/* Grab attached arg, if any */
var attachedArg = _arguments[flagIndex].splitByCharacter(ArgumentAttacher, maxSplits: 1)
if attachedArg.count > 1 {
args.append(attachedArg[1])
}
for var i = flagIndex + 1; i < _arguments.count; i++ {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(option: Option) {
_options.append(option)
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(options: [Option]) {
_options += options
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(options: Option...) {
_options += options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(options: [Option]) {
_options = options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(options: Option...) {
_options = options
}
/**
* Parses command-line arguments into their matching Option values. Throws `ParseError` if
* argument parsing fails.
*
* - parameter strict: Fail if any unrecognized arguments are present (default: false).
*/
public func parse(strict: Bool = false) throws {
for (idx, arg) in _arguments.enumerate() {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count
let flagWithArg = arg[Range(start: arg.startIndex.advancedBy(skipChars), end: arg.endIndex)]
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let flag = flagWithArg.splitByCharacter(ArgumentAttacher, maxSplits: 1)[0]
var flagMatched = false
for option in _options where option.flagMatch(flag) {
let vals = self._getFlagValues(idx)
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.characters.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
for (i, c) in flag.characters.enumerate() {
for option in _options where option.flagMatch(String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(idx) : [String]()
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(inout to: TargetStream) {
let name = _arguments[0]
var flagWidth = 0
for opt in _options {
flagWidth = max(flagWidth, " \(opt.flagDescription):".characters.count)
}
print("Usage: \(name) [options]", toStream: &to)
for opt in _options {
let flags = " \(opt.flagDescription):".paddedToWidth(flagWidth)
print("\(flags)\n \(opt.helpMessage)", toStream: &to)
}
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(error: ErrorType, inout to: TargetStream) {
print("\(error)\n", toStream: &to)
printUsage(&to)
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
public func printUsage(error: ErrorType) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
/**
* Prints a usage message.
*/
public func printUsage() {
var out = StderrOutputStream.stream
printUsage(&out)
}
}
| apache-2.0 | 51e918ed76f99da44407b75253e2ba93 | 30.743243 | 101 | 0.645168 | 4.402999 | false | false | false | false |
Subsets and Splits