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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LipliStyle/Liplis-iOS | Liplis/StringBuilder.swift | 1 | 2400 | //
// StringBuilder.swift
// Liplis
//
// StringBuilder JavaやC#のStringBuilderを模したクラス
//
//アップデート履歴
// 2015/04/27 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
//
// Created by sachin on 2015/04/27.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import Foundation
/**
Supports creation of a String from pieces
*/
public class StringBuilder {
private var stringValue: String
/**
Construct with initial String contents
- parameter string: Initial value; defaults to empty string
*/
public init(string: String = "") {
self.stringValue = string
}
/**
Return the String object
:return: String
*/
public func toString() -> String {
return stringValue
}
/**
Return the current length of the String object
*/
public var length: Int {
return stringValue.characters.count
}
/**
Append a String to the object
- parameter string: String
:return: reference to this StringBuilder instance
*/
public func append(string: String) -> StringBuilder {
stringValue += string
return self
}
/**
Append a Printable to the object
- parameter value: a value supporting the Printable protocol
:return: reference to this StringBuilder instance
*/
public func append<T: CustomStringConvertible>(value: T) -> StringBuilder {
stringValue += value.description
return self
}
/**
Append a String and a newline to the object
- parameter string: String
:return: reference to this StringBuilder instance
*/
public func appendLine(string: String) -> StringBuilder {
stringValue += string + "\n"
return self
}
/**
Append a Printable and a newline to the object
- parameter value: a value supporting the Printable protocol
:return: reference to this StringBuilder instance
*/
public func appendLine<T: CustomStringConvertible>(value: T) -> StringBuilder {
stringValue += value.description + "\n"
return self
}
/**
Reset the object to an empty string
:return: reference to this StringBuilder instance
*/
public func clear() -> StringBuilder {
stringValue = ""
return self
}
} | mit | 0d01359ba8d03565f49099a61683cd2e | 21.625 | 83 | 0.616922 | 4.780488 | false | false | false | false |
mandrean/BusyDuino | OSX/BusyDuino/AppDelegate.swift | 1 | 757 | /**
* @module AppDelegate
* @author Sebastian Mandrean
* @date 10 Aug 2015
* @copyright Sebastian Mandrean 2015
* @license MIT
*/
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
var busyDuino = BusyDuino()
func applicationDidFinishLaunching(aNotification: NSNotification) {
let icon = NSImage(named: "statusIcon")
icon!.setTemplate(true)
statusItem.image = icon
statusItem.menu = statusMenu
}
@IBAction func clickedMenu(sender: NSMenuItem) {
busyDuino.setStatus(String(sender.tag))
}
}
| mit | f8fdc58056a25485cd189223efc8db8a | 22.65625 | 75 | 0.700132 | 4.452941 | false | false | false | false |
icotting/Phocalstream.iOS | Phocalstream/ViewController.swift | 1 | 5282 | //
// ViewController.swift
// Phocalstream
//
// Created by Ian Cottingham on 5/18/15.
// Copyright (c) 2015 JS Raikes School. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate, AuthenticationDelegate {
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var browseSitesButton: UIButton!
@IBOutlet weak var gradientView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.gradientView.bounds
let clearColor = UIColor.clearColor().CGColor as CGColorRef
let darkColor = UIColor.blackColor().CGColor as CGColorRef
gradientLayer.colors = [clearColor, darkColor]
gradientLayer.locations = [0.0, 0.70]
self.gradientView.layer.addSublayer(gradientLayer)
// color button - #009688
browseSitesButton.backgroundColor = UIColor(red: 106.0/255.0, green: 170.0/255.0, blue: 195.0/255.0, alpha: 1.0)
browseSitesButton.layer.cornerRadius = 4
browseSitesButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
// Load Background Image
let request = NSMutableURLRequest(URL: NSURL(string: String(format: "http://images.plattebasintimelapse.org/api/photo/medium/%d", 235364))!)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.backgroundImage.image = UIImage(data: data!)
self.view.setNeedsDisplay()
})
})
task.resume()
}
override func viewDidAppear(animated: Bool) {
if ( FBSDKAccessToken.currentAccessToken() == nil ) {
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
}
else {
let auth = AuthenticationManager(delegate: self)
auth.login(FBSDKAccessToken.currentAccessToken().tokenString)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Fb Delegate Methods
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if ((error) != nil)
{
self.didFailAuthentication(FailureType.PASSTHROUGH, message: "Error logging in with Facebook. Please try again.")
}
else if result.isCancelled {
self.didFailAuthentication(FailureType.PASSTHROUGH, message: "Logging in with Facebook was cancelled. Please try again.")
}
else {
let auth = AuthenticationManager(delegate: self)
auth.login(result.token.tokenString)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { }
// MARK: Authentication Delegate Methods
func didAuthenticate()
{
print("Logged in!")
self.performSegueWithIdentifier("LOADSITES", sender: self)
}
func didFailAuthentication(type: FailureType, message: String)
{
var alertView: UIAlertController? = nil
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { action -> Void in
// simply cancel the alert
})
switch type {
case .FORBIDDEN:
alertView = UIAlertController(title: "No Account", message: "You do not have a Phocalstream account. Visit the Phocalstream site to create one.", preferredStyle: UIAlertControllerStyle.Alert)
alertView?.addAction(cancelAction)
alertView?.addAction(UIAlertAction(title: "Visit Site", style: UIAlertActionStyle.Default, handler: { action -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: "http://images.plattebasintimelapse.com/account/login")!)
}))
break
case .UNAUTHORIZED:
alertView = UIAlertController(title: "Authentication Failed", message: "Facebook failed to validate your login. Please try again.", preferredStyle: UIAlertControllerStyle.Alert)
alertView?.addAction(cancelAction)
break
case .PASSTHROUGH:
alertView = UIAlertController(title: "Authentication Failed", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertView?.addAction(cancelAction)
break
default:
alertView = UIAlertController(title: "Error", message: "An error occurred verifying your account with Phocalstream.", preferredStyle: UIAlertControllerStyle.Alert)
alertView?.addAction(cancelAction)
}
self.presentViewController(alertView!, animated: true, completion: nil)
}
// MARK: AlertView Delegate Methods
}
| apache-2.0 | 15100e9066698b3dddb647838bdef798 | 39.320611 | 203 | 0.652404 | 5.168297 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV2/Models/QueryTimesliceAggregation.swift | 1 | 1828 | /**
* (C) Copyright IBM Corp. 2019, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
A specialized histogram aggregation that uses dates to create interval segments.
Enums with an associated value of QueryTimesliceAggregation:
QueryAggregation
*/
public struct QueryTimesliceAggregation: Codable, Equatable {
/**
The type of aggregation command used. Options include: term, histogram, timeslice, nested, filter, min, max, sum,
average, unique_count, and top_hits.
*/
public var type: String
/**
The date field name used to create the timeslice.
*/
public var field: String
/**
The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years.
*/
public var interval: String
/**
Identifier specified in the query request of this aggregation.
*/
public var name: String?
/**
Array of aggregation results.
*/
public var results: [QueryTimesliceAggregationResult]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
case field = "field"
case interval = "interval"
case name = "name"
case results = "results"
}
}
| apache-2.0 | 321233ecab3c6f0c003ceb1fdffc52f8 | 28.483871 | 118 | 0.685449 | 4.447689 | false | false | false | false |
webim/webim-client-sdk-ios | Example/Tests/OperatorFactoryTests.swift | 1 | 2533 | //
// OperatorFactoryTests.swift
// WebimClientLibrary_Tests
//
// Created by Nikita Lazarev-Zubov on 19.02.18.
// Copyright © 2018 Webim. 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
@testable import WebimClientLibrary
import XCTest
class OperatorFactoryTests: XCTestCase {
// MARK: - Constants
private static let serverURLString = "http://demo.webim.ru"
// MARK: - Properties
private let operatorFactory = OperatorFactory(withServerURLString: serverURLString)
// MARK: - Tests
func testCreateOperator() {
let operatorItemDictionary = try! JSONSerialization.jsonObject(with: OPERATOR_ITEM_JSON_STRING.data(using: .utf8)!,
options: []) as! [String : Any?]
var operatorItem = OperatorItem(jsonDictionary: operatorItemDictionary)
let `operator` = operatorFactory.createOperatorFrom(operatorItem: operatorItem)
XCTAssertEqual(`operator`!.getID(),
operatorItem!.getID())
XCTAssertEqual(`operator`!.getName(),
operatorItem!.getFullName())
XCTAssertEqual(URL(string: (OperatorFactoryTests.serverURLString + operatorItem!.getAvatarURLString()!)),
`operator`!.getAvatarURL()!)
operatorItem = nil
XCTAssertNil(operatorFactory.createOperatorFrom(operatorItem: operatorItem))
}
}
| mit | ec796857a5df1202b04e1c852228fd7c | 43.421053 | 123 | 0.690363 | 4.813688 | false | true | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/Storage.swift | 2 | 9023 | //
// Storage.swift
// Neocom
//
// Created by Artem Shimanski on 21.08.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import CloudData
import CoreData
import Futures
import EVEAPI
import Expressible
class Storage: PersistentContainer<StorageContext> {
private var oAuth2TokenDidRefreshObserver: NotificationObserver?
class func `default`() -> Storage {
let container = NSPersistentContainer(name: "Storage", managedObjectModel: NSManagedObjectModel(contentsOf: Bundle.main.url(forResource: "Storage", withExtension: "momd")!)!)
let directory = URL.init(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)[0])
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
let url = directory.appendingPathComponent("store.sqlite")
let description = NSPersistentStoreDescription()
description.url = url
//description.type = CloudStoreType
description.setOption("Neocom" as NSString, forKey: CloudStoreOptions.recordZoneKey)
description.setOption(CompressionMethod.zlibDefault as NSNumber, forKey: CloudStoreOptions.binaryDataCompressionMethod)
description.setOption(NSMergePolicy.overwrite, forKey: CloudStoreOptions.mergePolicy)
container.persistentStoreDescriptions = [description]
var isLoaded = false
container.loadPersistentStores { (_, error) in
isLoaded = error == nil
}
if !isLoaded {
try? FileManager.default.removeItem(at: url)
container.loadPersistentStores { (_, _) in
}
}
return Storage(persistentContainer: container)
}
#if DEBUG
class func testing() -> Storage {
let container = NSPersistentContainer(name: "Store", managedObjectModel: NSManagedObjectModel(contentsOf: Bundle.main.url(forResource: "Storage", withExtension: "momd")!)!)
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("store.sqlite")
try? FileManager.default.removeItem(at: url)
let description = NSPersistentStoreDescription()
description.url = url
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { (description, error) in
if let error = error {
fatalError(error.localizedDescription)
}
}
return Storage(persistentContainer: container)
}
#endif
private static let backwardCompatibility: Void = {
NSKeyedUnarchiver.setClass(LoadoutDescription.self, forClassName: "Neocom.NCFittingLoadout")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.self, forClassName: "Neocom.NCFittingLoadoutItem")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.Module.self, forClassName: "Neocom.NCFittingLoadoutModule")
NSKeyedUnarchiver.setClass(LoadoutDescription.Item.Drone.self, forClassName: "Neocom.NCFittingLoadoutDrone")
NSKeyedUnarchiver.setClass(FleetDescription.self, forClassName: "Neocom.NCFleetConfiguration")
NSKeyedUnarchiver.setClass(ImplantSetDescription.self, forClassName: "Neocom.NCImplantSetData")
NSKeyedArchiver.setClassName("Neocom.NCFittingLoadout", for: LoadoutDescription.self)
NSKeyedArchiver.setClassName("Neocom.NCFittingLoadoutItem", for: LoadoutDescription.Item.self)
NSKeyedArchiver.setClassName("Neocom.NCFittingLoadoutModule", for: LoadoutDescription.Item.Module.self)
NSKeyedArchiver.setClassName("Neocom.NCFittingLoadoutDrone", for: LoadoutDescription.Item.Drone.self)
NSKeyedArchiver.setClassName("Neocom.NCFleetConfiguration", for: FleetDescription.self)
NSKeyedArchiver.setClassName("Neocom.NCImplantSetData", for: ImplantSetDescription.self)
}()
override init(persistentContainer: NSPersistentContainer) {
_ = Storage.backwardCompatibility
super.init(persistentContainer: persistentContainer)
oAuth2TokenDidRefreshObserver = NotificationCenter.default.addNotificationObserver(forName: .OAuth2TokenDidRefresh, object: nil, queue: .main) { [weak self] (note) in
guard let token = note.object as? OAuth2Token else {return}
guard let account = self?.viewContext.account(with: token) else {return}
account.oAuth2Token = token
try? self?.viewContext.save()
}
}
}
struct StorageContext: PersistentContext {
var managedObjectContext: NSManagedObjectContext
var accounts: [Account] {
return (try? managedObjectContext.from(Account.self).fetch()) ?? []
}
func account(with token: OAuth2Token) -> Account? {
return (try? managedObjectContext.from(Account.self).filter(\Account.characterID == token.characterID).first()) ?? nil
}
func newAccount(with token: OAuth2Token) -> Account {
let account = Account(context: managedObjectContext)
account.oAuth2Token = token
account.uuid = UUID().uuidString
return account
}
func newFolder(named name: String) -> AccountsFolder {
let folder = AccountsFolder(context: managedObjectContext)
folder.name = name
return folder
}
var currentAccount: Account? {
guard let url = Services.settings.currentAccount else {return nil}
guard let objectID = Services.storage.managedObjectID(forURIRepresentation: url) else {return nil}
return (try? existingObject(with: objectID)) ?? nil
}
func setCurrentAccount(_ account: Account?) -> Void {
Services.settings.currentAccount = account?.objectID.uriRepresentation()
NotificationCenter.default.post(name: .didChangeAccount, object: account)
}
func marketQuickItems() -> [MarketQuickItem]? {
return (try? managedObjectContext.from(MarketQuickItem.self).fetch()) ?? nil
}
func marketQuickItem(with typeID: Int) -> MarketQuickItem? {
return (try? managedObjectContext
.from(MarketQuickItem.self)
.filter(\MarketQuickItem.typeID == typeID).first()) ?? nil
}
}
extension Account {
var oAuth2Token: OAuth2Token? {
get {
let scopes = (self.scopes as? Set<Scope>)?.compactMap {
return $0.name
} ?? []
guard let accessToken = accessToken,
let refreshToken = refreshToken,
let tokenType = tokenType,
let characterName = characterName,
let realm = realm else {return nil}
let token = OAuth2Token(accessToken: accessToken, refreshToken: refreshToken, tokenType: tokenType, expiresOn: expiresOn as Date? ?? Date.distantPast, characterID: characterID, characterName: characterName, realm: realm, scopes: scopes)
return token
}
set {
guard let managedObjectContext = managedObjectContext else {return}
if let token = newValue {
if accessToken != token.accessToken {accessToken = token.accessToken}
if refreshToken != token.refreshToken {refreshToken = token.refreshToken}
if tokenType != token.tokenType {tokenType = token.tokenType}
if characterID != token.characterID {characterID = token.characterID}
if characterName != token.characterName {characterName = token.characterName}
if realm != token.realm {realm = token.realm}
if expiresOn != token.expiresOn {expiresOn = token.expiresOn}
let newScopes = Set<String>(token.scopes)
let toInsert: Set<String>
if var scopes = self.scopes as? Set<Scope> {
let toDelete = scopes.filter {
guard let name = $0.name else {return true}
return !newScopes.contains(name)
}
for scope in toDelete {
managedObjectContext.delete(scope)
scopes.remove(scope)
}
toInsert = newScopes.symmetricDifference(scopes.compactMap {return $0.name})
}
else {
toInsert = newScopes
}
for name in toInsert {
let scope = Scope(context: managedObjectContext)
scope.name = name
scope.account = self
}
}
}
}
var activeSkillPlan: SkillPlan? {
if let skillPlan = (try? managedObjectContext?.from(SkillPlan.self).filter(\SkillPlan.account == self && \SkillPlan.active == true).first()) ?? nil {
return skillPlan
}
else if let skillPlan = skillPlans?.anyObject() as? SkillPlan {
skillPlan.active = true
return skillPlan
}
else if let managedObjectContext = managedObjectContext {
let skillPlan = SkillPlan(context: managedObjectContext)
skillPlan.active = true
skillPlan.account = self
skillPlan.name = NSLocalizedString("Default", comment: "")
return skillPlan
}
else {
return nil
}
}
}
struct Pair<A, B> {
var a: A
var b: B
init(_ a: A, _ b: B) {
self.a = a
self.b = b
}
}
extension Pair: Equatable where A: Equatable, B: Equatable {}
extension Pair: Hashable where A: Hashable, B: Hashable {}
extension SkillPlan {
func add(_ trainingQueue: TrainingQueue) {
let skills = self.skills?.allObjects as? [SkillPlanSkill]
var position: Int32 = (skills?.map{$0.position}.max()).map{$0 + 1} ?? 0
var queued = (skills?.map{Pair(Int($0.typeID), Int($0.level))}).map{Set($0)} ?? Set()
for i in trainingQueue.queue {
let key = Pair(i.skill.typeID, i.targetLevel)
guard !queued.contains(key) else {continue}
queued.insert(key)
let skill = SkillPlanSkill(context: managedObjectContext!)
skill.skillPlan = self
skill.typeID = Int32(key.a)
skill.level = Int16(key.b)
skill.position = position
position += 1
}
}
}
| lgpl-2.1 | abccc3c3646a4db2a46dfef6a2c5101c | 35.088 | 239 | 0.742075 | 4.004439 | false | false | false | false |
ntian2/NTDownload | NTDownload/download/NTDownload/NTDownloadManager.swift | 1 | 9350 | //
// NTDownloadManager.swift
//
// Created by ntian on 2017/5/1.
// Copyright © 2017年 ntian. All rights reserved.
//
import UIKit
open class NTDownloadManager: URLSessionDownloadTask {
open static let shared = NTDownloadManager()
open weak var delegate: NTDownloadManagerDelegate?
open var unFinishedList: [NTDownloadTask] {
return taskList.filter { $0.status != .NTFinishedDownload }
}
open var finishedList: [NTDownloadTask] {
return taskList.filter { $0.status == .NTFinishedDownload }
}
private lazy var taskList = [NTDownloadTask]()
private let configuration = URLSessionConfiguration.background(withIdentifier: "NTDownload")
private var session: URLSession!
private let plistPath = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/NTDownload.plist"
override init() {
super.init()
self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
self.loadTaskList()
// debugPrint(plistPath)
}
public func addDownloadTask(urlString: String, fileName: String? = nil, fileImage: String? = nil) {
let url = URL(string: urlString)!
let request = URLRequest(url: url)
let downloadTask = session.downloadTask(with: request)
downloadTask.resume()
let status = NTDownloadStatus(rawValue: downloadTask.state.rawValue)!.status
let fileName = fileName ?? (url.absoluteString as NSString).lastPathComponent
let task = NTDownloadTask(fileURL: url, fileName: fileName, fileImage: fileImage)
task.status = status
task.task = downloadTask
self.taskList.append(task)
delegate?.addDownloadRequest?(downloadTask: task)
self.saveTaskList()
}
public func pauseTask(downloadTask: NTDownloadTask) {
if downloadTask.status != .NTDownloading {
return
}
var task = downloadTask.task
if task == nil {
task = session.downloadTask(with: downloadTask.fileURL)
downloadTask.task = task
}
task?.suspend()
downloadTask.status = NTDownloadStatus(rawValue: (task?.state.rawValue)!)!.status
delegate?.downloadRequestDidPaused?(downloadTask: downloadTask)
}
public func resumeTask(downloadTask: NTDownloadTask) {
if downloadTask.status != .NTPauseDownload {
return
}
var task = downloadTask.task
if task == nil {
task = session.downloadTask(with: downloadTask.fileURL)
downloadTask.task = task
}
task?.resume()
downloadTask.status = NTDownloadStatus(rawValue: (task?.state.rawValue)!)!.status
delegate?.downloadRequestDidStarted?(downloadTask: downloadTask)
}
public func resumeAllTask() {
for task in unFinishedList {
resumeTask(downloadTask: task)
}
}
public func pauseAllTask() {
for task in unFinishedList {
pauseTask(downloadTask: task)
}
}
public func removeTask(downloadTask: NTDownloadTask) {
for (index, task) in taskList.enumerated() {
if task.fileURL == downloadTask.fileURL {
if downloadTask.status == .NTFinishedDownload {
try? FileManager.default.removeItem(atPath: downloadTask.destinationPath!)
} else {
downloadTask.task?.cancel()
}
taskList.remove(at: index)
saveTaskList()
break
}
}
}
public func removeAllTask() {
for task in taskList {
removeTask(downloadTask: task)
}
}
public func clearTmp() {
do {
let tmpDirectory = try FileManager.default.contentsOfDirectory(atPath: NSTemporaryDirectory())
try tmpDirectory.forEach { file in
let path = String.init(format: "%@/%@", NSTemporaryDirectory(), file)
try FileManager.default.removeItem(atPath: path)
}
} catch {
print(error)
}
}
}
// MARK: - Private Function
private extension NTDownloadManager {
func saveTaskList() {
let jsonArray = NSMutableArray()
for task in taskList {
let jsonItem = NSMutableDictionary()
jsonItem["fileURL"] = task.fileURL.absoluteString
jsonItem["fileName"] = task.fileName
jsonItem["fileImage"] = task.fileImage
if task.status == .NTFinishedDownload {
jsonItem["statusCode"] = NTDownloadStatus.NTFinishedDownload.rawValue
jsonItem["fileSize.size"] = task.fileSize?.size
jsonItem["fileSize.unit"] = task.fileSize?.unit
}
jsonArray.add(jsonItem)
}
jsonArray.write(toFile: plistPath, atomically: true)
}
func loadTaskList() {
guard let jsonArray = NSArray(contentsOfFile: plistPath) else {
return
}
for jsonItem in jsonArray {
guard let item = jsonItem as? NSDictionary, let fileName = item["fileName"] as? String, let urlString = item["fileURL"] as? String else {
return
}
let fileURL = URL(string: urlString)!
let fileImage = item["fileImage"] as? String
let statusCode = item["statusCode"] as? Int
let task = NTDownloadTask(fileURL: fileURL, fileName: fileName, fileImage: fileImage)
if let statusCode = statusCode {
let status = NTDownloadStatus(rawValue: statusCode)
let fileSize = item["fileSize.size"] as? Float
let fileSizeUnit = item["fileSize.unit"] as? String
task.status = status
task.fileSize = (fileSize, fileSizeUnit) as? (size: Float, unit: String)
} else {
task.status = .NTPauseDownload
}
self.taskList.append(task)
}
}
}
// MARK: - URLSessionDownloadDelegate
extension NTDownloadManager: URLSessionDownloadDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let error = error as NSError?
var downloadTask = task as! URLSessionDownloadTask
if (error?.userInfo[NSURLErrorBackgroundTaskCancelledReasonKey] as? Int) == NSURLErrorCancelledReasonUserForceQuitApplication || (error?.userInfo[NSURLErrorBackgroundTaskCancelledReasonKey] as? Int) == NSURLErrorCancelledReasonBackgroundUpdatesDisabled {
let task = unFinishedList.filter { $0.fileURL == downloadTask.currentRequest?.url || $0.fileURL == downloadTask.originalRequest?.url }.first
let fileURL = task?.fileURL
let resumeData = error?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
if resumeData == nil {
downloadTask = session.downloadTask(with: fileURL!)
} else {
downloadTask = session.downloadTask(withResumeData: resumeData!)
}
task?.status = NTDownloadStatus(rawValue: downloadTask.state.rawValue)!.status
task?.task = downloadTask
} else {
for task in unFinishedList {
if downloadTask.isEqual(task.task) {
if error != nil {
task.status = .NTFailed
task.fileSize = nil
task.downloadedFileSize = nil
delegate?.downloadRequestDidFailedWithError?(error: error!, downloadTask: task)
}
}
}
}
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
for task in unFinishedList {
if downloadTask.isEqual(task.task) {
task.status = .NTFinishedDownload
let destUrl = documentUrl.appendingPathComponent(task.fileName)
do {
try FileManager.default.moveItem(at: location, to: destUrl)
delegate?.downloadRequestFinished?(downloadTask: task)
} catch {
delegate?.downloadRequestDidFailedWithError?(error: error, downloadTask: task)
}
}
}
saveTaskList()
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
for task in unFinishedList {
if downloadTask.isEqual(task.task) {
task.fileSize = (NTCommonHelper.calculateFileSize(totalBytesExpectedToWrite), NTCommonHelper.calculateUnit(totalBytesExpectedToWrite))
task.downloadedFileSize = (NTCommonHelper.calculateFileSize(totalBytesWritten),NTCommonHelper.calculateUnit(totalBytesWritten))
task.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
delegate?.downloadRequestUpdateProgress?(downloadTask: task)
}
}
}
}
| mit | 6bb40788fe4a8a716bf5931719633566 | 41.486364 | 262 | 0.619343 | 5.265915 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Utility/Views/TextView.swift | 2 | 8618 | //
// TextView.swift
// Neocom
//
// Created by Artem Shimanski on 2/18/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
struct TextView: View {
enum Style {
case `default`
case preferredMaxLayoutWidth(CGFloat)
case fixedLayoutWidth(CGFloat)
var preferredMaxLayoutWidth: CGFloat? {
guard case let .preferredMaxLayoutWidth(width) = self else {return nil}
return width
}
}
@Binding var text: NSAttributedString
var selectedRange: Binding<NSRange>? = nil
var typingAttributes: [NSAttributedString.Key: Any] = [:]
var placeholder: NSAttributedString = NSAttributedString()
var style: Style = .default
var onBeginEditing: ((UITextView) -> Void)? = nil
var onEndEditing: ((UITextView) -> Void)? = nil
var body: some View {
TextViewRepresentation(text: $text, selectedRange: selectedRange, typingAttributes: typingAttributes, placeholder: placeholder, style: style, onBeginEditing: onBeginEditing, onEndEditing: onEndEditing)
}
}
private struct TextViewRepresentation: UIViewRepresentable {
@Binding var text: NSAttributedString
var selectedRange: Binding<NSRange>?
var typingAttributes: [NSAttributedString.Key: Any]
var placeholder: NSAttributedString
var style: TextView.Style
var onBeginEditing: ((UITextView) -> Void)?
var onEndEditing: ((UITextView) -> Void)?
class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<NSAttributedString>
var selectedRange: Binding<NSRange>?
var placeholder: NSAttributedString
var typingAttributes: [NSAttributedString.Key: Any]
var onBeginEditing: ((UITextView) -> Void)?
var onEndEditing: ((UITextView) -> Void)?
var textView: SelfSizedTextView?
private var attachments = [TextAttachmentViewProtocol]()
init(text: Binding<NSAttributedString>, selectedRange: Binding<NSRange>?, placeholder: NSAttributedString, typingAttributes: [NSAttributedString.Key: Any], onBeginEditing: ((UITextView) -> Void)?, onEndEditing: ((UITextView) -> Void)?) {
self.text = text
self.selectedRange = selectedRange
self.placeholder = placeholder
self.typingAttributes = typingAttributes
self.onBeginEditing = onBeginEditing
self.onEndEditing = onEndEditing
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardWillChangeFrame(_ note: Notification) {
guard let textView = textView else {return}
guard let keyboardFrame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {return}
guard let localFrame = textView.superview?.convert(textView.frame, to: nil) else {return}
textView.contentInset.bottom = keyboardFrame.intersection(localFrame).height
}
func textViewDidBeginEditing(_ textView: UITextView) {
textView.attributedText = text.wrappedValue
textView.typingAttributes = typingAttributes
onBeginEditing?(textView)
}
func textViewDidEndEditing(_ textView: UITextView) {
if text.wrappedValue.length == 0 {
textView.attributedText = placeholder
}
onEndEditing?(textView)
}
func textViewDidChange(_ textView: UITextView) {
text.wrappedValue = textView.attributedText//.copy() as! NSAttributedString
}
func textViewDidChangeSelection(_ textView: UITextView) {
DispatchQueue.main.async {
self.selectedRange?.wrappedValue = textView.selectedRange
}
}
}
func makeUIView(context: UIViewRepresentableContext<TextViewRepresentation>) -> SelfSizedTextView {
let textView = SelfSizedTextView()
textView.delegate = context.coordinator
context.coordinator.textView = textView
textView.typingAttributes = typingAttributes
textView.style = style
textView.attributedText = text
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = .clear
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.layoutManager.usesFontLeading = false
textView.layoutManager.delegate = context.coordinator
if case .default = style {
textView.isScrollEnabled = true
}
else {
textView.isScrollEnabled = false
textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
textView.setContentHuggingPriority(.defaultHigh, for: .vertical)
}
return textView
}
func updateUIView(_ uiView: SelfSizedTextView, context: UIViewRepresentableContext<TextViewRepresentation>) {
context.coordinator.text = $text
context.coordinator.selectedRange = selectedRange
func attributes() -> [NSAttributedString.Key: Any] {
var attributes = self.typingAttributes
attributes[.foregroundColor] = UIColor.secondaryLabel
return attributes
}
if !uiView.isFirstResponder {
uiView.attributedText = text.length > 0 ? text : placeholder
}
else if !uiView.attributedText.isEqual(to: text) {
uiView.attributedText = text
}
uiView.typingAttributes = typingAttributes
uiView.style = style
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $text, selectedRange: selectedRange, placeholder: placeholder, typingAttributes: typingAttributes, onBeginEditing: onBeginEditing, onEndEditing: onEndEditing)
}
}
struct TextViewPreview: View {
@State var text: NSAttributedString = NSAttributedString(string: "")
var body: some View {
GeometryReader { geometry in
VStack {
TextView(text: self.$text, placeholder: NSAttributedString(string: "Placeholder", attributes: [.foregroundColor: UIColor.secondaryLabel]))
.background(Color.gray)
}.padding().background(Color.green)
}
}
}
struct TextView_Previews: PreviewProvider {
static var previews: some View {
TextViewPreview()
}
}
class SelfSizedTextView: UITextView {
var style: TextView.Style = .default
override var intrinsicContentSize: CGSize {
switch style {
case .default:
return super.intrinsicContentSize
case let .preferredMaxLayoutWidth(width):
return sizeThatFits(CGSize(width: width, height: .infinity))
case let .fixedLayoutWidth(width):
var size = sizeThatFits(CGSize(width: width, height: .infinity))
size.width = width
size.height = max(size.height, 24)
return size
}
}
}
extension TextViewRepresentation.Coordinator: NSLayoutManagerDelegate {
func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
guard let textView = textView else {return}
let storage = textView.textStorage
var currentAttachments = [TextAttachmentViewProtocol]()
storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in
guard let attachment = value as? NSTextAttachment & TextAttachmentViewProtocol else {return}
currentAttachments.append(attachment)
if !attachments.contains(where: {$0 === attachment}) {
textView.addSubview(attachment.view)
}
attachment.view.frame = layoutManager.boundingRect(forGlyphRange: range, in: textView.textContainer).inset(by: -attachment.insets)
}
for attachment in attachments {
if (!currentAttachments.contains(where: {$0 === attachment})) {
attachment.view.removeFromSuperview()
}
}
attachments = currentAttachments
}
}
| lgpl-2.1 | 00298b7f90864055a36989450900b58d | 39.646226 | 245 | 0.65951 | 5.665352 | false | false | false | false |
jlyu/swift-demo | Nerdfeed/Nerdfeed/Model/RSSItem.swift | 1 | 3975 | //
// RSSItem.swift
// Nerdfeed
//
// Created by chain on 14-7-16.
// Copyright (c) 2014 chain. All rights reserved.
//
import UIKit
class RSSItem: NSObject, NSCoding,
NSXMLParserDelegate, JSONSerializable {
var parentParserDelegate: RSSChannel?
var title: String = String()
var link: String = String()
var publicationDate: NSDate?
var publication: String = String()
//class var dateFormatter: NSDateFormatter? {
// return nil
//}
init() {
super.init()
}
var parseTag: String!
let titleTag = "title"
let linkTag = "link"
let itemTag = "item"
let entryTag = "entry"
let pubDateTag = "pubDate"
// - Method
override func isEqual(object: AnyObject!) -> Bool {
if !object.isKindOfClass(RSSItem) {
return false
}
return self.link == object.link
}
// - Conform JSONSerializable
func readFromJSONDictionary(d: NSDictionary) {
var title: NSDictionary = d.objectForKey("title") as NSDictionary
self.title = title.objectForKey("label") as String
var links: NSArray = d.objectForKey("link") as NSArray
if links.count > 1 {
var tmpDict: NSDictionary = links.objectAtIndex(1) as NSDictionary
var sampleDict = tmpDict.objectForKey("attributes") as NSDictionary
self.link = sampleDict.objectForKey("href") as String
}
}
// Conform NSXMLParserDelegate
func parser(parser: NSXMLParser!,
didStartElement elementName: String!,
namespaceURI: String!,
qualifiedName qName: String!,
attributes attributeDict: NSDictionary!) {
//println("\(self) found \(elementName)")
if elementName == titleTag {
parseTag = elementName
} else if elementName == linkTag {
parseTag = elementName
} else if elementName == pubDateTag {
parseTag = elementName
}
}
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
//println("foundCharacter: \(string)")
if parseTag? == titleTag {
self.title += string
} else if parseTag? == linkTag {
self.link += string
} else if parseTag? == pubDateTag { // ??
self.publication += string
}
}
func parser(parser: NSXMLParser!,
didEndElement elementName: String!,
namespaceURI: String!,
qualifiedName qName: String!) {
if (elementName == pubDateTag) {
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
publicationDate = dateFormatter.dateFromString(publication)
}
parseTag = nil
if (elementName == itemTag) || (elementName == entryTag) {
parser.delegate = parentParserDelegate!
}
}
// - Archiving
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(link, forKey: "link")
aCoder.encodeObject(publicationDate, forKey: "publicationDate")
}
init(coder aDecoder: NSCoder!) {
super.init()
if self != nil {
title = aDecoder.decodeObjectForKey("title") as String
link = aDecoder.decodeObjectForKey("link") as String
publicationDate = aDecoder.decodeObjectForKey("publicationDate") as? NSDate
}
}
}
| mit | 83006da25e8a74e349c90a35a495a9c4 | 25.604167 | 87 | 0.530063 | 5.467675 | false | false | false | false |
mikaoj/BSImagePicker | Sources/Scene/Assets/NumberView.swift | 1 | 1741 | // The MIT License (MIT)
//
// Copyright (c) 2020 Joakim Gyllström
//
// 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 NumberView: UILabel {
override var tintColor: UIColor! {
didSet {
textColor = tintColor
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(frame: .zero)
font = UIFont.boldSystemFont(ofSize: 12)
numberOfLines = 1
adjustsFontSizeToFitWidth = true
baselineAdjustment = .alignCenters
textAlignment = .center
}
override func draw(_ rect: CGRect) {
super.drawText(in: rect)
}
}
| mit | 5d45baa1c7804ff8558d40fdc876d98f | 33.8 | 81 | 0.695402 | 4.677419 | false | false | false | false |
DanielZakharin/Shelfie | Shelfie/Pods/PieCharts/PieCharts/Layer/Impl/View/PieCustomViewsLayer.swift | 3 | 2482 | //
// PieViewLayer.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
open class PieCustomViewsLayerSettings {
public var viewRadius: CGFloat?
public var hideOnOverflow = true // NOTE: Considers only space defined by angle with origin at the center of the pie chart. Arcs (inner/outer radius) are ignored.
public init() {}
}
open class PieCustomViewsLayer: PieChartLayer {
public weak var chart: PieChart?
public var settings: PieCustomViewsLayerSettings = PieCustomViewsLayerSettings()
public var onNotEnoughSpace: ((UIView, CGSize) -> Void)?
fileprivate var sliceViews = [PieSlice: UIView]()
public var animator: PieViewLayerAnimator = AlphaPieViewLayerAnimator()
public var viewGenerator: ((PieSlice, CGPoint) -> UIView)?
public init() {}
public func onEndAnimation(slice: PieSlice) {
addItems(slice: slice)
}
public func addItems(slice: PieSlice) {
guard sliceViews[slice] == nil else {return}
let center = settings.viewRadius.map{slice.view.midPoint(radius: $0)} ?? slice.view.arcCenter
guard let view = viewGenerator?(slice, center) else {print("Need a view generator to create views!"); return}
let size = view.frame.size
let availableSize = CGSize(width: slice.view.maxRectWidth(center: center, height: size.height), height: size.height)
if !settings.hideOnOverflow || availableSize.contains(size) {
view.center = center
chart?.addSubview(view)
} else {
onNotEnoughSpace?(view, availableSize)
}
animator.animate(view)
sliceViews[slice] = view
}
public func onSelected(slice: PieSlice, selected: Bool) {
guard let label = sliceViews[slice] else {print("Invalid state: slice not in dictionary"); return}
let p = slice.view.calculatePosition(angle: slice.view.midAngle, p: label.center, offset: selected ? slice.view.selectedOffset : -slice.view.selectedOffset)
UIView.animate(withDuration: 0.15) {
label.center = p
}
}
public func clear() {
for (_, view) in sliceViews {
view.removeFromSuperview()
}
sliceViews.removeAll()
}
}
| gpl-3.0 | e130e30c2a3bf25301625df88886b596 | 29.62963 | 166 | 0.621927 | 4.654784 | false | false | false | false |
tkremenek/swift | test/decl/init/resilience-cross-module.swift | 29 | 1372 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -typecheck -swift-version 4 -verify -I %t %s
// RUN: %target-swift-frontend -typecheck -swift-version 4 -verify -enable-library-evolution -I %t %s
// RUN: %target-swift-frontend -typecheck -swift-version 5 -verify -I %t %s
// RUN: %target-swift-frontend -typecheck -swift-version 5 -verify -enable-library-evolution -I %t %s
import resilient_struct
import resilient_protocol
// Size is not @frozen, so we cannot define a new designated initializer
extension Size {
init(ww: Int, hh: Int) {
self.w = ww
self.h = hh // expected-error {{'let' property 'h' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
// This is OK
init(www: Int, hhh: Int) {
self.init(w: www, h: hhh)
}
// This is OK
init(other: Size) {
self = other
}
}
// Protocol extension initializers are OK too
extension OtherResilientProtocol {
public init(other: Self) {
self = other
}
}
| apache-2.0 | cecf4d04038831a150237117c2edfd7c | 35.105263 | 194 | 0.697522 | 3.404467 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSFileHandle.swift | 1 | 11267 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
open class FileHandle : NSObject, NSSecureCoding {
internal var _fd: Int32
internal var _closeOnDealloc: Bool
internal var _closed: Bool = false
open var availableData: Data {
return _readDataOfLength(Int.max, untilEOF: false)
}
open func readDataToEndOfFile() -> Data {
return readData(ofLength: Int.max)
}
open func readData(ofLength length: Int) -> Data {
return _readDataOfLength(length, untilEOF: true)
}
internal func _readDataOfLength(_ length: Int, untilEOF: Bool) -> Data {
var statbuf = stat()
var dynamicBuffer: UnsafeMutableRawPointer? = nil
var total = 0
if _closed || fstat(_fd, &statbuf) < 0 {
fatalError("Unable to read file")
}
if statbuf.st_mode & S_IFMT != S_IFREG {
/* We get here on sockets, character special files, FIFOs ... */
var currentAllocationSize: size_t = 1024 * 8
dynamicBuffer = malloc(currentAllocationSize)
var remaining = length
while remaining > 0 {
let amountToRead = min(1024 * 8, remaining)
// Make sure there is always at least amountToRead bytes available in the buffer.
if (currentAllocationSize - total) < amountToRead {
currentAllocationSize *= 2
dynamicBuffer = _CFReallocf(dynamicBuffer!, currentAllocationSize)
if dynamicBuffer == nil {
fatalError("unable to allocate backing buffer")
}
}
let amtRead = read(_fd, dynamicBuffer!.advanced(by: total), amountToRead)
if 0 > amtRead {
free(dynamicBuffer)
fatalError("read failure")
}
if 0 == amtRead {
break // EOF
}
total += amtRead
remaining -= amtRead
if total == length || !untilEOF {
break // We read everything the client asked for.
}
}
} else {
let offset = lseek(_fd, 0, SEEK_CUR)
if offset < 0 {
fatalError("Unable to fetch current file offset")
}
if off_t(statbuf.st_size) > offset {
var remaining = size_t(statbuf.st_size - offset)
remaining = min(remaining, size_t(length))
dynamicBuffer = malloc(remaining)
if dynamicBuffer == nil {
fatalError("Malloc failure")
}
while remaining > 0 {
let count = read(_fd, dynamicBuffer!.advanced(by: total), remaining)
if count < 0 {
free(dynamicBuffer)
fatalError("Unable to read from fd")
}
if count == 0 {
break
}
total += count
remaining -= count
}
}
}
if length == Int.max && total > 0 {
dynamicBuffer = _CFReallocf(dynamicBuffer!, total)
}
if (0 == total) {
free(dynamicBuffer)
}
if total > 0 {
let bytePtr = dynamicBuffer!.bindMemory(to: UInt8.self, capacity: total)
return Data(bytesNoCopy: bytePtr, count: total, deallocator: .none)
}
return Data()
}
open func write(_ data: Data) {
data.enumerateBytes() { (bytes, range, stop) in
do {
try NSData.write(toFileDescriptor: self._fd, path: nil, buf: UnsafeRawPointer(bytes.baseAddress!), length: bytes.count)
} catch {
fatalError("Write failure")
}
}
}
// TODO: Error handling.
open var offsetInFile: UInt64 {
return UInt64(lseek(_fd, 0, SEEK_CUR))
}
open func seekToEndOfFile() -> UInt64 {
return UInt64(lseek(_fd, 0, SEEK_END))
}
open func seek(toFileOffset offset: UInt64) {
lseek(_fd, off_t(offset), SEEK_SET)
}
open func truncateFile(atOffset offset: UInt64) {
if lseek(_fd, off_t(offset), SEEK_SET) == 0 {
ftruncate(_fd, off_t(offset))
}
}
open func synchronizeFile() {
fsync(_fd)
}
open func closeFile() {
if !_closed {
close(_fd)
_closed = true
}
}
public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) {
_fd = fd
_closeOnDealloc = closeopt
}
internal init?(path: String, flags: Int32, createMode: Int) {
_fd = _CFOpenFileWithMode(path, flags, mode_t(createMode))
_closeOnDealloc = true
super.init()
if _fd < 0 {
return nil
}
}
deinit {
if _fd >= 0 && _closeOnDealloc && !_closed {
close(_fd)
}
}
public required init?(coder: NSCoder) {
NSUnimplemented()
}
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public static var supportsSecureCoding: Bool {
return true
}
}
extension FileHandle {
internal static var _stdinFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDIN_FILENO, closeOnDealloc: false)
}()
open class var standardInput: FileHandle {
return _stdinFileHandle
}
internal static var _stdoutFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDOUT_FILENO, closeOnDealloc: false)
}()
open class var standardOutput: FileHandle {
return _stdoutFileHandle
}
internal static var _stderrFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDERR_FILENO, closeOnDealloc: false)
}()
open class var standardError: FileHandle {
return _stderrFileHandle
}
open class var nullDevice: FileHandle {
NSUnimplemented()
}
public convenience init?(forReadingAtPath path: String) {
self.init(path: path, flags: O_RDONLY, createMode: 0)
}
public convenience init?(forWritingAtPath path: String) {
self.init(path: path, flags: O_WRONLY, createMode: 0)
}
public convenience init?(forUpdatingAtPath path: String) {
self.init(path: path, flags: O_RDWR, createMode: 0)
}
internal static func _openFileDescriptorForURL(_ url : URL, flags: Int32, reading: Bool) throws -> Int32 {
let path = url.path
let fd = _CFOpenFile(path, flags)
if fd < 0 {
throw _NSErrorWithErrno(errno, reading: reading, url: url)
}
return fd
}
public convenience init(forReadingFrom url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDONLY, reading: true)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forWritingTo url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_WRONLY, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forUpdating url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDWR, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
}
extension NSExceptionName {
public static let fileHandleOperationException = "" // NSUnimplemented
}
extension Notification.Name {
public static let NSFileHandleReadToEndOfFileCompletion = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleConnectionAccepted = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleDataAvailable = Notification.Name(rawValue: "") // NSUnimplemented
public static let NSFileHandleReadCompletion = Notification.Name(rawValue: "") // NSUnimplemented
}
public let NSFileHandleNotificationDataItem: String = "" // NSUnimplemented
public let NSFileHandleNotificationFileHandleItem: String = "" // NSUnimplemented
extension FileHandle {
open func readInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readInBackgroundAndNotify() {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify() {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify() {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify() {
NSUnimplemented()
}
open var readabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
open var writeabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
}
extension FileHandle {
public convenience init(fileDescriptor fd: Int32) {
self.init(fileDescriptor: fd, closeOnDealloc: false)
}
open var fileDescriptor: Int32 {
return _fd
}
}
open class Pipe: NSObject {
private let readHandle: FileHandle
private let writeHandle: FileHandle
public override init() {
/// the `pipe` system call creates two `fd` in a malloc'ed area
var fds = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
defer {
free(fds)
}
/// If the operating system prevents us from creating file handles, stop
guard pipe(fds) == 0 else { fatalError("Could not open pipe file handles") }
/// The handles below auto-close when the `NSFileHandle` is deallocated, so we
/// don't need to add a `deinit` to this class
/// Create the read handle from the first fd in `fds`
self.readHandle = FileHandle(fileDescriptor: fds.pointee, closeOnDealloc: true)
/// Advance `fds` by one to create the write handle from the second fd
self.writeHandle = FileHandle(fileDescriptor: fds.successor().pointee, closeOnDealloc: true)
super.init()
}
open var fileHandleForReading: FileHandle {
return self.readHandle
}
open var fileHandleForWriting: FileHandle {
return self.writeHandle
}
}
| apache-2.0 | 8717e1e947afb5d940c9d99c953e59d6 | 30.560224 | 135 | 0.58516 | 4.841856 | false | false | false | false |
danielgindi/Charts | ChartsDemo-macOS/ChartsDemo-macOS/Demos/PieDemoViewController.swift | 2 | 2330 | //
// PieDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class PieDemoViewController: NSViewController
{
@IBOutlet var pieChartView: PieChartView!
override open func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) * 100.0 }
let yse1 = ys1.enumerated().map { x, y in return PieChartDataEntry(value: y, label: String(x)) }
let data = PieChartData()
let ds1 = PieChartDataSet(entries: yse1, label: "Hello")
ds1.colors = ChartColorTemplates.vordiplom()
data.append(ds1)
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "Charts\nby Daniel Cohen Gindi")
centerText.setAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-Light", size: 15.0)!, NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSMakeRange(0, centerText.length))
centerText.addAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-Light", size: 13.0)!, NSAttributedString.Key.foregroundColor: NSColor.gray], range: NSMakeRange(10, centerText.length - 10))
centerText.addAttributes([NSAttributedString.Key.font: NSFont(name: "HelveticaNeue-LightItalic", size: 13.0)!, NSAttributedString.Key.foregroundColor: NSColor(red: 51 / 255.0, green: 181 / 255.0, blue: 229 / 255.0, alpha: 1.0)], range: NSMakeRange(centerText.length - 19, 19))
self.pieChartView.centerAttributedText = centerText
self.pieChartView.data = data
self.pieChartView.chartDescription.text = "Piechart Demo"
}
override open func viewWillAppear()
{
self.pieChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0)
}
}
| apache-2.0 | 1e3d6460492ec25de3db299112702638 | 42.148148 | 284 | 0.687983 | 4.559687 | false | false | false | false |
GhostSK/SpriteKitPractice | particlesystem/particlesystem/GameScene.swift | 1 | 3276 | //
// GameScene.swift
// particleSystem
//
// Created by 胡杨林 on 17/3/15.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var emitterNode = SKEmitterNode()
override func didMove(to view: SKView) {
// let snow = SKEmitterNode(fileNamed: "MyParticle.sks")
// snow?.position = CGPoint(x: 400, y: 600)
// addChild(snow!)
let background:SKSpriteNode = SKSpriteNode(imageNamed: "1.png")
background.position = CGPoint(x: 500, y: 380)
addChild(background)
//使用关键帧序列配置粒子属性
let rainTexture = SKTexture(imageNamed: "rainDrop.png")
emitterNode.particleTexture = rainTexture
emitterNode.particleBirthRate = 80.0
emitterNode.particleColor = SKColor.white
emitterNode.particleSpeed = -450
emitterNode.particleSpeedRange = 150
emitterNode.particleLifetime = 2
emitterNode.particleScale = 0.2
emitterNode.particleAlpha = 0.75
emitterNode.particleAlphaRange = 0.5
emitterNode.particleColorBlendFactor = 1
emitterNode.particleScale = 0.2
emitterNode.particleScaleRange = 0.5
emitterNode.particleScaleSpeed = -0.1
//设置发射器位置
emitterNode.position = CGPoint(x: (self.view?.frame.midX)!, y: (self.view?.frame.height)! + 10)
emitterNode.particlePositionRange = CGVector(dx: 736, dy: 0)
addChild(emitterNode)
let btn = UIButton(frame: CGRect(x: 20, y: 30, width: 160, height: 30))
btn.setTitle("关键帧控制", for: .normal)
btn.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
self.view?.addSubview(btn)
}
func btnAction() {
let scaleSequence:SKKeyframeSequence = SKKeyframeSequence(keyframeValues: [0.2,0.7,0.1], times: [0.0,0.250,0.750]) //每个粒子会执行 时间0-scale0.2 时间0.250-scale0.7 时间0.750-scale0.1的顺序变化
emitterNode.particleScaleSequence = scaleSequence
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let rainTexture = SKTexture(imageNamed: "snow.png")
let emitterNode = SKEmitterNode()
emitterNode.particleTexture = rainTexture
emitterNode.particleBirthRate = 80.0 //设置每秒创建的粒子数
emitterNode.particleColor = SKColor.white //粒子的颜色
emitterNode.particleSpeed = -450 //粒子的平均初始速度
emitterNode.particleSpeedRange = 150 //粒子的初始速度,这个值是一个允许的值域范围内的随机值
emitterNode.particleLifetime = 2.0 //生命周期
emitterNode.particleScale = 0.2 //缩放因子
emitterNode.particleAlpha = 0.75 //平均初始透明度
emitterNode.particleAlphaRange = 0.5
emitterNode.particleColorBlendFactor = 1 //颜色混合因子
emitterNode.particleScaleRange = 0.5
emitterNode.position = CGPoint(x: (self.view?.frame.midX)!, y: (self.view?.frame.midY)!)
emitterNode.particlePositionRange = CGVector(dx: (self.view?.frame.maxX)!, dy: 0)
addChild(emitterNode)
}
}
| apache-2.0 | 3954513c8b7698b6828962839ff0c568 | 39.986486 | 187 | 0.656775 | 3.781796 | false | false | false | false |
taqun/HBR | HBR/Classes/ViewController/Setting/ExpireSettingViewController.swift | 1 | 2153 | //
// ExpireSettingViewController.swift
// HBR
//
// Created by taqun on 2014/11/21.
// Copyright (c) 2014年 envoixapp. All rights reserved.
//
import UIKit
class ExpireSettingViewController: UITableViewController {
let expireInterval = [
EntryExpireInterval.ThreeDays,
EntryExpireInterval.OneWeek,
EntryExpireInterval.OneMonth,
EntryExpireInterval.None
]
/*
* Initialize
*/
override func viewDidLoad() {
super.viewDidLoad()
}
/*
* UIViewController Method
*/
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = "エントリーの保存期間"
Logger.sharedInstance.track("SettingView/ExpireSettingView")
}
/*
* UITableViewDataSource Protocol
*/
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
var index = indexPath.indexAtPosition(1)
var currentInterval = ModelManager.sharedInstance.entryExpireInterval
if expireInterval[index] == currentInterval{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
/*
* UITableViewDelegate Protocol
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let index = indexPath.indexAtPosition(1)
ModelManager.sharedInstance.entryExpireInterval = expireInterval[index]
tableView.reloadData()
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44;
}
}
| mit | edf9532b8b6a5920d1425f1c9c81146a | 26.675325 | 118 | 0.656969 | 5.593176 | false | false | false | false |
zendobk/RealmMapper | Sources/Operator.swift | 1 | 2315 | //
// Operator.swift
// RealmMapper
//
// Created by DaoNV on 5/15/17.
// Copyright © 2017 AsianTech Inc. All rights reserved.
//
import RealmSwift
import ObjectMapper
/**
Map to optional BaseMappable Object.
- parammeter T: BaseMappable Object.
- parameter left: Optional variable.
- parameter right: Map object.
*/
public func <- <T: Object>(left: inout T?, right: Map) where T: BaseMappable {
if right.mappingType == MappingType.fromJSON {
if !right.isKeyPresent { return }
guard let value = right.currentValue else {
left = nil
return
}
guard let json = value as? [String: Any],
let obj = Mapper<T>().map(JSON: json) else { return }
left = obj
} else {
left <- (right, ObjectTransform<T>())
}
}
/**
Map to implicitly unwrapped optional BaseMappable Object.
- parammeter T: BaseMappable Object.
- parameter left: Implicitly unwrapped optional variable.
- parameter right: Map object.
*/
public func <- <T: Object>(left: inout T!, right: Map) where T: BaseMappable {
var object: T? = left
object <- right
}
/**
Map to List of BaseMappable Object.
- parammeter T: BaseMappable Object.
- parameter left: mapped variable.
- parameter right: Map object.
*/
public func <- <T: Object>(left: List<T>, right: Map) where T: BaseMappable {
if right.mappingType == MappingType.fromJSON {
if !right.isKeyPresent { return }
left.removeAll()
guard let json = right.currentValue as? [[String: Any]] else { return }
let maps: [T]? = Mapper<T>().mapArray(JSONArray: json)
guard let objs = maps else { return }
left.append(objectsIn: objs)
} else {
var _left = left
_left <- (right, ListTransform<T>())
}
}
// MARK: - Deprecated
/**
Relation must be marked as being optional or implicitly unwrapped optional.
- parammeter T: BaseMappable Object.
- parameter left: mapped variable.
- parameter right: Map object.
*/
@available( *, deprecated: 1, message: "Relation must be marked as being optional or implicitly unwrapped optional.")
public func <- <T: Object>(left: inout T, right: Map) where T: BaseMappable {
fatalError("Deprecated: Relation must be marked as being optional or implicitly unwrapped optional.")
}
| mit | b63ce26c160248b59c67d0c8c3e12547 | 29.853333 | 117 | 0.654278 | 4.102837 | false | false | false | false |
zigglzworth/GitHub-Trends | GitHub-Trends/GitConnect.swift | 1 | 7282 | //
// GitConnect.swift
// GitHub-Trends
//
// Created by noasis on 10/1/17.
// Copyright © 2017 iyedah. All rights reserved.
//
/*
GitConnect manages communication with the GitHub API from the app
*/
import UIKit
import ReachabilitySwift
enum GitSearchTimeRange: Int {
case lastDay, lastWeek, lastMonth, none
}
class GitConnect: NSObject {
static let shared: GitConnect = GitConnect()
let reachability = Reachability()!
var currentSearchRequest:APIEndpointRequest?
private override init() {
super.init()
}
// MARK: SEARCHING GIT WITH SEARCH TEXT - Currently unused but ready for future use
func searchGit(searchText: String, completion:@escaping(GitSearchResult) ->()) {
let endpointRequest:APIEndpointRequest = APIEndpointRequest.init()
endpointRequest.endpointURLString = GitAPIConstants.GITSEARCHBASEURLPATH
endpointRequest.params[GitAPIConstants.kGITSearchQuerySortKey] = "stars"
endpointRequest.params[GitAPIConstants.kGITSearchQueryOrderKey] = "desc"
endpointRequest.params[GitAPIConstants.kGITSearchQueryKey] = searchText
self.searchGit(request: endpointRequest) { (gitSearchResult) in
completion(gitSearchResult)
}
}
// MARK: SEARCHING GIT WITH FOR TRENDING REPOS IN TIME RANGE
func searchGit(timeRange: GitSearchTimeRange, completion:@escaping(GitSearchResult) ->()) {
let endpointRequest:APIEndpointRequest = APIEndpointRequest.init()
endpointRequest.endpointURLString = GitAPIConstants.GITSEARCHBASEURLPATH
endpointRequest.params[GitAPIConstants.kGITSearchQuerySortKey] = "stars"
endpointRequest.params[GitAPIConstants.kGITSearchQueryOrderKey] = "desc"
let formatter = ISO8601DateFormatter()
var date:Date?
switch timeRange {
case .lastDay:
date = Calendar.current.date(byAdding: .day, value: -1, to: Date())
break
case .lastWeek:
date = Calendar.current.date(byAdding: .day, value: -7, to: Date())
break
case .lastMonth:
date = Calendar.current.date(byAdding: .month, value: -1, to: Date())
break
default:
date = Calendar.current.date(byAdding: .month, value: -1, to: Date())
break
}
let dateString = formatter.string(from: date!)
endpointRequest.params[GitAPIConstants.kGITSearchQueryKey] = "created:>" + dateString
self.searchGit(request: endpointRequest) { (gitSearchResult) in
completion(gitSearchResult)
}
}
// MARK: CORE SEARCHING GIT OPERATION SUING AN APIEndpointRequest
func searchGit(request: APIEndpointRequest, completion:@escaping(GitSearchResult) ->()) {
if self.currentSearchRequest != nil {
self.currentSearchRequest?.cancel()
}
self.currentSearchRequest = request
let gitSearchResult = GitSearchResult.init()
if reachability.isReachable == true {
request.sendRequest { (data, response, error) in
if error == nil {
if let dict = self.DataToDictionary(data: data!) as? [AnyHashable : Any] {
if let array = dict["items"] {
let items = array as! Array <[AnyHashable : Any]>
for dictionary in items {
let repo:GitRepoInfo = GitRepoInfo(dictionary: dictionary)
gitSearchResult.resultsArray.append(repo)
}
}
else {
}
}
if response != nil {
gitSearchResult.nextPageRequest = self.extractNextPagerequest(response: response!)
}
}
completion(gitSearchResult)
}
}
else {
completion(gitSearchResult)
}
}
// MARK: GETTING A SINGLE REPO - For updating stored favouites etc
func getRepo(fullName: String, completion:@escaping([AnyHashable:Any]?) ->()) {
let endpointRequest:APIEndpointRequest = APIEndpointRequest.init()
endpointRequest.endpointURLString = GitAPIConstants.GITREPOBASEURLPATH + fullName
endpointRequest.sendRequest { (data, response, error) in
if error == nil {
if let dict = self.DataToDictionary(data: data!) as? [AnyHashable : Any] {
completion(dict)
}
else {
completion(nil)
}
}
else {
completion(nil)
}
}
}
// MARK: CONVERTING DATA TO DICTIONARY
func DataToDictionary(data: Data) -> Any? {
do {
return try JSONSerialization.jsonObject(with: data, options: [])
} catch {
print(error.localizedDescription)
}
return nil
}
// MARK: CREATING A GET NEXT PAGE REQUEST
func extractNextPagerequest(response:URLResponse) -> APIEndpointRequest? {
let httpResponse = response as? HTTPURLResponse
if let linkField = httpResponse?.allHeaderFields["Link"] as? String {
let parts = linkField.components(separatedBy: ",")
for part in parts {
if part.contains("rel=\"next\"") == true {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: part, options: [], range: NSRange(location: 0, length: part.utf16.count))
for match in matches {
if let url = match.url {
let endpointRequest:APIEndpointRequest = APIEndpointRequest.init()
endpointRequest.url = url
return endpointRequest
}
}
}
}
}
return nil
}
}
| mit | 139c35f1ff5ec93eccc902142e3c3885 | 27.665354 | 128 | 0.489905 | 5.943673 | false | false | false | false |
wayfair/brickkit-ios | Example/Source/Examples/Interactive/AdvancedRepeatViewController.swift | 1 | 2711 | //
// AdvancedRepeatViewController.swift
// BrickKit
//
// Created by Ruben Cagnie on 6/23/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
private let Item = "Item"
private let ItemsSection = "ItemsSection"
private let Title = "Title"
private let TitleSection = "TitleSection"
private let LoadButton = "LoadButton"
private let LoadButtonSection = "LoadButtonSection"
private let WholeSection = "WholeSection"
class AdvancedRepeatViewController: BrickApp.BaseBrickController, HasTitle {
class var brickTitle: String {
return "Advanced Repeat"
}
class var subTitle: String {
return "How to repeat bricks in bulk"
}
var items = [String]()
var loadButton : ButtonBrick!
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = .brickBackground
registerBrickClass(LabelBrick.self)
registerBrickClass(ButtonBrick.self)
loadButton = ButtonBrick(LoadButton, title: "Load Items".uppercased(), configureButtonBlock: { cell in
cell.configure()
}) { cell in
self.loadItems()
}
let section = BrickSection(WholeSection, bricks: [
BrickSection(LoadButtonSection, backgroundColor: .brickGray5, bricks: [
loadButton
]),
BrickSection(ItemsSection, backgroundColor: .brickGray1, bricks: [
LabelBrick(Item, width: .ratio(ratio: 1/2), height: .auto(estimate: .fixed(size: 38)), backgroundColor: .brickGray3, dataSource: self),
], inset: 5, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)),
])
section.repeatCountDataSource = self
setSection(section)
}
func loadItems() {
if items.isEmpty {
loadButton.title = "Remove items".uppercased()
items = []
for index in 0..<30 {
items.append("BRICK \(index + 1)")
}
} else {
loadButton.title = "Load items".uppercased()
items.removeAll()
}
self.brickCollectionView.invalidateBricks()
}
}
extension AdvancedRepeatViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == Item {
return items.count
} else {
return 1
}
}
}
extension AdvancedRepeatViewController: LabelBrickCellDataSource {
func configureLabelBrickCell(_ cell: LabelBrickCell) {
cell.label.text = items[cell.index]
cell.configure()
}
}
| apache-2.0 | 93eb87f058883e44a6d84c4c83adc7a1 | 26.653061 | 151 | 0.631365 | 4.616695 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Low-Frequency Oscillating of Parameters.xcplaygroundpage/Contents.swift | 1 | 1265 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Low-Frequency Oscillation of Parameters
//: ### Oftentimes we want rhythmic changing of parameters that varying in a standard way.
//: ### This is traditionally done with Low-Frequency Oscillators, LFOs.
import AudioKitPlaygrounds
import AudioKit
let generator = AKOperationGenerator { _ in
let frequencyLFO = AKOperation.square(frequency: 1)
.scale(minimum: 440, maximum: 880)
let carrierLFO = AKOperation.triangle(frequency: 1)
.scale(minimum: 1, maximum: 2)
let modulatingMultiplierLFO = AKOperation.sawtooth(frequency: 1)
.scale(minimum: 0.1, maximum: 2)
let modulatingIndexLFO = AKOperation.reverseSawtooth(frequency: 1)
.scale(minimum: 0.1, maximum: 20)
return AKOperation.fmOscillator(
baseFrequency: frequencyLFO,
carrierMultiplier: carrierLFO,
modulatingMultiplier: modulatingMultiplierLFO,
modulationIndex: modulatingIndexLFO,
amplitude: 0.2)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 9b32bf15fe04bf13d299a50b3feafc3f | 34.138889 | 90 | 0.711462 | 4.003165 | false | false | false | false |
oliverbarreto/PersonalFavs | PersonalFavs/PersonalFavs/Classes/Views/GroupCell.swift | 1 | 2900 | //
// GroupCell.swift
// PersonalFavs
//
// Created by David Oliver Barreto Rodríguez on 4/6/17.
// Copyright © 2017 David Oliver Barreto Rodríguez. All rights reserved.
//
import UIKit
class GroupCell: BaseCell {
// MARK: Model
var group: Group? {
didSet {
updateUI()
}
}
func updateUI() {
groupTitle.text = group?.name!
if let image = UIImage(named: (group?.iconPath!)!) {
groupIcon.image = image.withRenderingMode(.alwaysTemplate)
} else {
let image = #imageLiteral(resourceName: "Icon_FriendsGroup3").withRenderingMode(.alwaysTemplate)
groupIcon.image = image
}
let color = UIColor(hex: (group?.color!)!)
self.backgroundColor = color
}
// MARK: - View & Autolayout Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
// self.backgroundColor = UIColor.orange
self.layer.cornerRadius = 5
}
// MARK: - Layout Lifecycle Custom Methods
lazy var groupTitle: UILabel = {
let titleLabel = UILabel()
titleLabel.text = "Family"
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.systemFont(ofSize: 28, weight: UIFontWeightLight)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
// titleLabel.backgroundColor = UIColor.red
return titleLabel
}()
let groupIcon: UIImageView = {
let imageView = UIImageView()
let image = #imageLiteral(resourceName: "Icon_Family").withRenderingMode(.alwaysTemplate)
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageView.tintColor = UIColor.white
imageView.clipsToBounds = true
imageView.tintColor = UIColor.white
// imageView.backgroundColor = UIColor.black
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
// MARK: - Custom methods
override func setupViews() {
super.setupViews()
addSubview(groupTitle)
addSubview(groupIcon)
_ = groupTitle.anchorWithSizeAndConstantsTo(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: CGFloat(Config.CollectionViewLayout.HomeVC.groupCardPaddingTop), leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
_ = groupIcon.anchorWithSizeAndConstantsTo(top: groupTitle.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: CGFloat(Config.CollectionViewLayout.HomeVC.groupCardPaddingBottom), rightConstant: 0, widthConstant: 0, heightConstant: 60)
}
}
| apache-2.0 | 91601a98c007a2eb0743a167ea3800b9 | 31.550562 | 313 | 0.641698 | 5.182469 | false | false | false | false |
AgentFeeble/pgoapi | Pods/ProtocolBuffers-Swift/Source/CodedInputStream.swift | 2 | 25258 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
let DEFAULT_RECURSION_LIMIT:Int = 64
let DEFAULT_SIZE_LIMIT:Int = 64 << 20 // 64MB
let BUFFER_SIZE:Int = 4096
public class CodedInputStream {
public var buffer:Data
private var input:InputStream?
private var bufferSize:Int = 0
private var bufferSizeAfterLimit:Int = 0
private var bufferPos:Int = 0
private var lastTag:Int32 = 0
private var totalBytesRetired:Int = 0
private var currentLimit:Int = 0
private var recursionDepth:Int = 0
private var recursionLimit:Int = 0
private var sizeLimit:Int = 0
public init (data:Data) {
buffer = data
bufferSize = buffer.count
currentLimit = Int.max
recursionLimit = DEFAULT_RECURSION_LIMIT
sizeLimit = DEFAULT_SIZE_LIMIT
}
public init (stream:InputStream) {
buffer = Data(count: BUFFER_SIZE)
bufferSize = 0
input = stream
input?.open()
//
currentLimit = Int.max
recursionLimit = DEFAULT_RECURSION_LIMIT
sizeLimit = DEFAULT_SIZE_LIMIT
}
private func isAtEnd() throws -> Bool {
if bufferPos == bufferSize {
if !(try refillBuffer(mustSucceed: false)) {
return true
}
}
return false
}
private func refillBuffer(mustSucceed:Bool) throws -> Bool {
guard bufferPos >= bufferSize else {
throw ProtocolBuffersError.illegalState("RefillBuffer called when buffer wasn't empty.")
}
if (totalBytesRetired + bufferSize == currentLimit) {
guard !mustSucceed else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
return false
}
totalBytesRetired += bufferSize
bufferPos = 0
bufferSize = 0
if let input = self.input {
let pointer = UnsafeMutablePointerUInt8From(data: buffer)
bufferSize = input.read(pointer, maxLength:buffer.count)
}
if bufferSize <= 0 {
bufferSize = 0
guard !mustSucceed else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
return false
} else {
recomputeBufferSizeAfterLimit()
let totalBytesRead = totalBytesRetired + bufferSize + bufferSizeAfterLimit
guard totalBytesRead <= sizeLimit || totalBytesRead >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Size Limit Exceeded")
}
return true
}
}
public func readRawData(size:Int) throws -> Data {
let pointer = UnsafeMutablePointerUInt8From(data: buffer)
guard size >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
if totalBytesRetired + bufferPos + size > currentLimit {
try skipRawData(size: currentLimit - totalBytesRetired - bufferPos)
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if (size <= bufferSize - bufferPos) {
let data = Data(bytes: pointer + bufferPos, count: size)
bufferPos += size
return data
} else if (size < BUFFER_SIZE) {
let bytes = Data(count: size)
var pos = bufferSize - bufferPos
let byPointer = UnsafeMutablePointerUInt8From(data: bytes)
memcpy(byPointer, pointer + bufferPos, pos)
bufferPos = bufferSize
_ = try refillBuffer(mustSucceed: true)
while size - pos > bufferSize {
memcpy(byPointer + pos,pointer, bufferSize)
pos += bufferSize
bufferPos = bufferSize
_ = try refillBuffer(mustSucceed: true)
}
memcpy(byPointer + pos, pointer, size - pos)
bufferPos = size - pos
return bytes
} else {
let originalBufferPos = bufferPos
let originalBufferSize = bufferSize
totalBytesRetired += bufferSize
bufferPos = 0
bufferSize = 0
var sizeLeft = size - (originalBufferSize - originalBufferPos)
var chunks:Array<Data> = Array<Data>()
while (sizeLeft > 0) {
var chunk = Data(count:min(sizeLeft, BUFFER_SIZE))
var pos:Int = 0
while pos < chunk.count {
var n:Int = 0
if input != nil {
let pointer = UnsafeMutablePointerUInt8From(data: chunk)
n = input!.read(pointer + pos, maxLength:chunk.count - pos)
}
guard n > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
totalBytesRetired += n
pos += n
}
sizeLeft -= chunk.count
chunks.append(chunk)
}
let bytes = Data(count: size)
let byPointer = UnsafeMutablePointerUInt8From(data: bytes)
var pos = originalBufferSize - originalBufferPos
memcpy(byPointer, pointer + originalBufferPos, pos)
for chunk in chunks {
let chPointer = UnsafeMutablePointerUInt8From(data: chunk)
memcpy(byPointer + pos, chPointer, chunk.count)
pos += chunk.count
}
return bytes
}
}
// public func readRawData(size:Int) throws -> Data {
//
// guard size >= 0 else {
// throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
// }
//
// if totalBytesRetired + bufferPos + size > currentLimit {
// try skipRawData(size: currentLimit - totalBytesRetired - bufferPos)
// throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
// }
//
// if size <= bufferSize - bufferPos {
// let pointer = UnsafePointer<UInt8>((buffer as NSData).bytes)
// let data = Data(bytes: UnsafePointer<UInt8>(pointer + Int(bufferPos)), count: Int(size))
// bufferPos += size
// return data
// } else if (size < BUFFER_SIZE) {
//
// let bytes = Data(bytes: [0], count: size)
// var pos = bufferSize - bufferPos
// let pointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes)
// let bpointer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes)
// memcpy(pointer, bpointer + bufferPos, pos)
//
//// buffer.copyBytes(to: pointer, from: bufferPos..<bufferPos+pos)
// bufferPos = bufferSize
//
// _ = try refillBuffer(mustSucceed: true)
//
// while (size - pos > bufferSize) {
//
//// let pointerBuffer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes)
// memcpy(pointer + pos, bpointer, bufferSize)
//
//// bytes.copyBytes(to: pointerBuffer, from: pos..<pos + bufferSize)
// pos += bufferSize
// bufferPos = bufferSize
// _ = try refillBuffer(mustSucceed: true)
// }
//
// let pointerBuffer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes)
//// bytes.copyBytes(to: pointerBuffer, from: pos..<(pos + bufferSize) - size - pos)
// memcpy(pointer + pos, bpointer, size - pos)
// bufferPos = size - pos
// return bytes
//
// } else {
//
// let originalBufferPos = bufferPos
// let originalBufferSize = bufferSize
//
// totalBytesRetired += bufferSize
// bufferPos = 0
// bufferSize = 0
// let bpointer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes)
// var sizeLeft = size - (originalBufferSize - originalBufferPos)
// var chunks:Array<Data> = Array<Data>()
//
// while (sizeLeft > 0) {
// var chunk = Data(bytes: [0], count: BUFFER_SIZE)
// var pos:Int = 0
// while (pos < chunk.count) {
//
// var n:Int = 0
// if let input = self.input {
// let pointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes)
// n = input.read(pointer + pos, maxLength:chunk.count - pos)
// }
// guard n > 0 else {
// throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
// }
// totalBytesRetired += n
// pos += n
// }
// sizeLeft -= chunk.count
// chunks.append(chunk)
// }
//
//
// var bytes = Data(bytes: [0], count: 0)
// var pos:Int = originalBufferSize - originalBufferPos
// let cpointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes)
// memcpy(cpointer, bpointer + Int(originalBufferPos), pos)
//// bytes[0..<pos] = buffer[originalBufferPos..<originalBufferPos+pos]
//
// for chunk in chunks {
// let chpointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes)
// memcpy(pointer + pos, cpointer, chunk.count)
//// bytes[pos..<pos+chunk.count] = chunk[0..<chunk.count]
// pos += chunk.count
// }
//
// return bytes
// }
// }
public func skipRawData(size:Int) throws{
guard size >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
if (totalBytesRetired + bufferPos + size > currentLimit) {
try skipRawData(size: currentLimit - totalBytesRetired - bufferPos)
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if (size <= (bufferSize - bufferPos)) {
bufferPos += size
}
else
{
var pos:Int = bufferSize - bufferPos
totalBytesRetired += pos
bufferPos = 0
bufferSize = 0
while (pos < size) {
let data = Data(bytes: [0], count: size - pos)
var n:Int = 0
guard let input = self.input else {
n = -1
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
let pointer = UnsafeMutablePointerUInt8From(data: data)
n = input.read(pointer, maxLength:Int(size - pos))
pos += n
totalBytesRetired += n
}
}
}
public func readRawLittleEndian32() throws -> Int32 {
let b1:Int8 = try readRawByte()
let b2:Int8 = try readRawByte()
let b3:Int8 = try readRawByte()
let b4:Int8 = try readRawByte()
var result:Int32 = (Int32(b1) & 0xff)
result |= ((Int32(b2) & 0xff) << 8)
result |= ((Int32(b3) & 0xff) << 16)
result |= ((Int32(b4) & 0xff) << 24)
return result
}
public func readRawLittleEndian64() throws -> Int64 {
let b1:Int8 = try readRawByte()
let b2:Int8 = try readRawByte()
let b3:Int8 = try readRawByte()
let b4:Int8 = try readRawByte()
let b5:Int8 = try readRawByte()
let b6:Int8 = try readRawByte()
let b7:Int8 = try readRawByte()
let b8:Int8 = try readRawByte()
var result:Int64 = (Int64(b1) & 0xff)
result |= ((Int64(b2) & 0xff) << 8)
result |= ((Int64(b3) & 0xff) << 16)
result |= ((Int64(b4) & 0xff) << 24)
result |= ((Int64(b5) & 0xff) << 32)
result |= ((Int64(b6) & 0xff) << 40)
result |= ((Int64(b7) & 0xff) << 48)
result |= ((Int64(b8) & 0xff) << 56)
return result
}
public func readTag() throws -> Int32 {
if (try isAtEnd())
{
lastTag = 0
return 0
}
let tag = lastTag
lastTag = try readRawVarint32()
guard lastTag != 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(tag)")
}
return lastTag
}
public func checkLastTagWas(value:Int32) throws {
guard lastTag == value else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(lastTag)")
}
}
public func skipField(tag:Int32) throws -> Bool {
let wireFormat = WireFormat.getTagWireType(tag: tag)
guard let format = WireFormat(rawValue: wireFormat) else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type")
}
switch format {
case .varint:
_ = try readInt32()
return true
case .fixed64:
_ = try readRawLittleEndian64()
return true
case .lengthDelimited:
try skipRawData(size: Int(try readRawVarint32()))
return true
case .startGroup:
try skipMessage()
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: WireFormat.getTagFieldNumber(tag: tag)))
return true
case .endGroup:
return false
case .fixed32:
_ = try readRawLittleEndian32()
return true
default:
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type")
}
}
private func skipMessage() throws {
while (true) {
let tag:Int32 = try readTag()
let fieldSkip = try skipField(tag: tag)
if tag == 0 || !fieldSkip
{
break
}
}
}
public func readDouble() throws -> Double {
let convert:Int64 = try readRawLittleEndian64()
var result:Double = 0.0
result = WireFormat.convertTypes(convertValue: convert, defaultValue: result)
return result
}
public func readFloat() throws -> Float {
let convert:Int32 = try readRawLittleEndian32()
var result:Float = 0.0
result = WireFormat.convertTypes(convertValue: convert, defaultValue: result)
return result
}
public func readUInt64() throws -> UInt64 {
var retvalue:UInt64 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawVarint64(), defaultValue:retvalue)
return retvalue
}
public func readInt64() throws -> Int64 {
return try readRawVarint64()
}
public func readInt32() throws -> Int32 {
return try readRawVarint32()
}
public func readFixed64() throws -> UInt64 {
var retvalue:UInt64 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian64(), defaultValue:retvalue)
return retvalue
}
public func readFixed32() throws -> UInt32 {
var retvalue:UInt32 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian32(), defaultValue:retvalue)
return retvalue
}
public func readBool() throws ->Bool {
return try readRawVarint32() != 0
}
public func readRawByte() throws -> Int8 {
if (bufferPos == bufferSize) {
_ = try refillBuffer(mustSucceed: true)
}
let pointer = UnsafeMutablePointerInt8From(data: buffer)
let res = pointer[Int(bufferPos)]
bufferPos+=1
return res
}
public class func readRawVarint32(firstByte:UInt8, inputStream:InputStream) throws -> Int32
{
if ((Int32(firstByte) & 0x80) == 0) {
return Int32(firstByte)
}
var result:Int32 = Int32(firstByte) & 0x7f
var offset:Int32 = 7
while offset < 32 {
var b:UInt8 = UInt8()
guard inputStream.read(&b, maxLength: 1) > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
result |= (Int32(b) & 0x7f) << offset
if ((b & 0x80) == 0) {
return result
}
offset += 7
}
while offset < 64 {
var b:UInt8 = UInt8()
guard inputStream.read(&b, maxLength: 1) > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if ((b & 0x80) == 0) {
return result
}
offset += 7
}
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
public func readRawVarint32() throws -> Int32 {
var tmp : Int8 = try readRawByte();
if (tmp >= 0) {
return Int32(tmp);
}
var result : Int32 = Int32(tmp) & 0x7f;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 7;
} else {
result |= (Int32(tmp) & 0x7f) << 7;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 14;
} else {
result |= (Int32(tmp) & 0x7f) << 14;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 21;
} else {
result |= (Int32(tmp) & 0x7f) << 21;
tmp = try readRawByte()
result |= (Int32(tmp) << 28);
if (tmp < 0) {
// Discard upper 32 bits.
for _ in 0..<5 {
let byte = try readRawByte()
if (byte >= 0) {
return result;
}
}
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
}
}
}
return result;
}
public func readRawVarint64() throws -> Int64 {
var shift:Int64 = 0
var result:Int64 = 0
while (shift < 64) {
let b = try readRawByte()
result |= (Int64(b & 0x7F) << shift)
if ((Int32(b) & 0x80) == 0) {
return result
}
shift += 7
}
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
public func readString() throws -> String {
let size = Int(try readRawVarint32())
if size <= (bufferSize - bufferPos) && size > 0 {
let pointer = UnsafeMutablePointerInt8From(data: buffer)
let result = String(bytesNoCopy: pointer + bufferPos, length: size, encoding: String.Encoding.utf8, freeWhenDone: false)
bufferPos += size
return result!
} else {
let data = try readRawData(size: size)
return String(data: data, encoding: String.Encoding.utf8)!
}
}
public func readData() throws -> Data {
let size = Int(try readRawVarint32())
if size < bufferSize - bufferPos && size > 0 {
let pointer = UnsafeMutablePointerInt8From(data: buffer)
let unsafeRaw = UnsafeRawPointer(pointer+bufferPos)
let data = Data(bytes: unsafeRaw, count: size)
bufferPos += size
return data
} else {
return try readRawData(size: size)
}
}
public func readUInt32() throws -> UInt32 {
let value:Int32 = try readRawVarint32()
var retvalue:UInt32 = 0
retvalue = WireFormat.convertTypes(convertValue: value, defaultValue:retvalue)
return retvalue
}
public func readEnum() throws -> Int32 {
return try readRawVarint32()
}
public func readSFixed32() throws -> Int32 {
return try readRawLittleEndian32()
}
public func readSFixed64() throws -> Int64 {
return try readRawLittleEndian64()
}
public func readSInt32() throws -> Int32 {
return WireFormat.decodeZigZag32(n: try readRawVarint32())
}
public func readSInt64() throws -> Int64 {
return WireFormat.decodeZigZag64(n: try readRawVarint64())
}
public func setRecursionLimit(limit:Int) throws -> Int {
guard limit >= 0 else {
throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative")
}
let oldLimit:Int = recursionLimit
recursionLimit = limit
return oldLimit
}
public func setSizeLimit(limit:Int) throws -> Int {
guard limit >= 0 else {
throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative")
}
let oldLimit:Int = sizeLimit
sizeLimit = limit
return oldLimit
}
private func resetSizeCounter() {
totalBytesRetired = 0
}
private func recomputeBufferSizeAfterLimit() {
bufferSize += bufferSizeAfterLimit
let bufferEnd:Int = totalBytesRetired + bufferSize
if (bufferEnd > currentLimit) {
bufferSizeAfterLimit = bufferEnd - currentLimit
bufferSize -= bufferSizeAfterLimit
} else {
bufferSizeAfterLimit = 0
}
}
public func pushLimit(byteLimit:Int) throws -> Int {
guard byteLimit >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
let newByteLimit = byteLimit + totalBytesRetired + bufferPos
let oldLimit = currentLimit
guard newByteLimit <= oldLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
currentLimit = newByteLimit
recomputeBufferSizeAfterLimit()
return oldLimit
}
public func popLimit(oldLimit:Int) {
currentLimit = oldLimit
recomputeBufferSizeAfterLimit()
}
public func bytesUntilLimit() ->Int {
if currentLimit == Int.max {
return -1
}
let currentAbsolutePosition:Int = totalBytesRetired + bufferPos
return currentLimit - currentAbsolutePosition
}
public func readGroup(fieldNumber:Int, builder:ProtocolBuffersMessageBuilder, extensionRegistry:ExtensionRegistry) throws {
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry)
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: Int32(fieldNumber)))
recursionDepth-=1
}
public func readUnknownGroup(fieldNumber:Int32, builder:UnknownFieldSet.Builder) throws {
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self)
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: fieldNumber))
recursionDepth-=1
}
public func readMessage(builder:ProtocolBuffersMessageBuilder, extensionRegistry:ExtensionRegistry) throws {
let length = try readRawVarint32()
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
let oldLimit = try pushLimit(byteLimit: Int(length))
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry)
try checkLastTagWas(value: 0)
recursionDepth-=1
popLimit(oldLimit: oldLimit)
}
}
| apache-2.0 | 4396835c7b345d1df42f0891a3cf9073 | 34.725601 | 132 | 0.547589 | 4.835918 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Execution/REPRL.swift | 1 | 7501 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import libreprl
/// Read-Eval-Print-Reset-Loop: a script runner that reuses the same process for multiple
/// scripts, but resets the global state in between executions.
public class REPRL: ComponentBase, ScriptRunner {
/// Kill and restart the child process after this many script executions
private let maxExecsBeforeRespawn = 1000
/// Commandline arguments for the executable
public private(set) var processArguments: [String]
/// Environment variables for the child process
private var env = [String]()
/// Number of script executions since start of child process
private var execsSinceReset = 0
/// Number of execution failures since the last successfully executed program
private var recentlyFailedExecutions = 0
/// The opaque REPRL context used by the C library
fileprivate var reprlContext: OpaquePointer? = nil
/// Essentially counts the number of run() invocations
fileprivate var lastExecId = 0
/// Buffer to hold scripts, this lets us debug issues that arise if
/// previous scripts corrupted any state which is discovered in
/// future executions. This is only used if diagnostics mode is enabled.
private var scriptBuffer = String()
public init(executable: String, processArguments: [String], processEnvironment: [String: String]) {
self.processArguments = [executable] + processArguments
super.init(name: "REPRL")
for (key, value) in processEnvironment {
env.append(key + "=" + value)
}
}
override func initialize() {
reprlContext = libreprl.reprl_create_context()
if reprlContext == nil {
logger.fatal("Failed to create REPRL context")
}
let argv = convertToCArray(processArguments)
let envp = convertToCArray(env)
if reprl_initialize_context(reprlContext, argv, envp, /* capture stdout */ 1, /* capture stderr: */ 1) != 0 {
logger.fatal("Failed to initialize REPRL context: \(String(cString: reprl_get_last_error(reprlContext)))")
}
freeCArray(argv, numElems: processArguments.count)
freeCArray(envp, numElems: env.count)
fuzzer.registerEventListener(for: fuzzer.events.Shutdown) { _ in
reprl_destroy_context(self.reprlContext)
}
}
public func setEnvironmentVariable(_ key: String, to value: String) {
env.append(key + "=" + value)
}
public func run(_ script: String, withTimeout timeout: UInt32) -> Execution {
// Log the current script into the buffer if diagnostics are enabled.
if fuzzer.config.enableDiagnostics {
self.scriptBuffer += script + "\n"
}
lastExecId += 1
let execution = REPRLExecution(from: self)
guard script.count <= REPRL_MAX_DATA_SIZE else {
logger.error("Script too large to execute. Assuming timeout...")
execution.outcome = .timedOut
return execution
}
execsSinceReset += 1
var freshInstance: Int32 = 0
if execsSinceReset > maxExecsBeforeRespawn {
freshInstance = 1
execsSinceReset = 0
if fuzzer.config.enableDiagnostics {
scriptBuffer.removeAll(keepingCapacity: true)
}
}
var execTime: UInt64 = 0 // In microseconds
let timeout = UInt64(timeout) * 1000 // In microseconds
var status: Int32 = 0
script.withCString {
status = reprl_execute(reprlContext, $0, UInt64(script.count), UInt64(timeout), &execTime, freshInstance)
// If we fail, we retry after a short timeout and with a fresh instance. If we still fail, we give up trying
// to execute this program. If we repeatedly fail to execute any program, we abort.
if status < 0 {
logger.warning("Script execution failed: \(String(cString: reprl_get_last_error(reprlContext))). Retrying in 1 second...")
if fuzzer.config.enableDiagnostics {
fuzzer.dispatchEvent(fuzzer.events.DiagnosticsEvent, data: (name: "REPRLFail", content: scriptBuffer))
}
Thread.sleep(forTimeInterval: 1)
status = reprl_execute(reprlContext, $0, UInt64(script.count), UInt64(timeout), &execTime, 1)
}
}
if status < 0 {
logger.error("Script execution failed again: \(String(cString: reprl_get_last_error(reprlContext))). Giving up")
// If we weren't able to successfully execute a script in the last N attempts, abort now...
recentlyFailedExecutions += 1
if recentlyFailedExecutions >= 10 {
logger.fatal("Too many consecutive REPRL failures")
}
execution.outcome = .failed(1)
return execution
}
recentlyFailedExecutions = 0
if RIFEXITED(status) != 0 {
let code = REXITSTATUS(status)
if code == 0 {
execution.outcome = .succeeded
} else {
execution.outcome = .failed(Int(code))
}
} else if RIFSIGNALED(status) != 0 {
execution.outcome = .crashed(Int(RTERMSIG(status)))
} else if RIFTIMEDOUT(status) != 0 {
execution.outcome = .timedOut
} else {
fatalError("Unknown REPRL exit status \(status)")
}
execution.execTime = Double(execTime) / 1_000_000
return execution
}
}
class REPRLExecution: Execution {
private var cachedStdout: String? = nil
private var cachedStderr: String? = nil
private var cachedFuzzout: String? = nil
private unowned let reprl: REPRL
private let execId: Int
var outcome = ExecutionOutcome.succeeded
var execTime: TimeInterval = 0
init(from reprl: REPRL) {
self.reprl = reprl
self.execId = reprl.lastExecId
}
// The output streams (stdout, stderr, fuzzout) can only be accessed before
// the next REPRL execution. This function can be used to verify that.
private var outputStreamsAreValid: Bool {
return execId == reprl.lastExecId
}
var stdout: String {
assert(outputStreamsAreValid)
if cachedStdout == nil {
cachedStdout = String(cString: reprl_fetch_stdout(reprl.reprlContext))
}
return cachedStdout!
}
var stderr: String {
assert(outputStreamsAreValid)
if cachedStderr == nil {
cachedStderr = String(cString: reprl_fetch_stderr(reprl.reprlContext))
}
return cachedStderr!
}
var fuzzout: String {
assert(outputStreamsAreValid)
if cachedFuzzout == nil {
cachedFuzzout = String(cString: reprl_fetch_fuzzout(reprl.reprlContext))
}
return cachedFuzzout!
}
}
| apache-2.0 | 268f31cac368f331a31ffa97bbe7b97e | 36.318408 | 138 | 0.636982 | 4.412353 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Solutions/Functions 1_Exercises_Solution.playground/Contents.swift | 1 | 4665 | //: ## Functions 1 Exercises
//: In these exercise, you will be given the description for functions and their expected output assuming they are implemented correctly. It will be your job to finish the implementations.
//: ### Exercise 1
//: The function `emojiLove` should take two `String` parameters and use them to print a `String` with the format "stringParameterOne ❤️ stringParameterTwo".
func emojiLove(s1: String, s2: String) {
print(s1 + " ❤️ " + s2)
}
/* Example Function Call
emojiLove(s1: "cats", s2: "dogs") // prints "cats ❤️ dogs"
emojiLove(s1: "udacity", s2: "students") // prints "udacity ❤️ students"
emojiLove(s1: "peanut butter", s2: "jelly") // prints "peanut butter ❤️ jelly"
emojiLove(s1: "ying", s2: "yang") // prints "ying ❤️ yang"
*/
emojiLove(s1: "cats", s2: "dogs")
emojiLove(s1: "udacity", s2: "students")
emojiLove(s1: "peanut butter", s2: "jelly")
emojiLove(s1: "ying", s2: "yang")
//: ### Exercise 2
//: The function `median` should take three `Int` parameters and return the `Int` value in the middle.
func median(num1: Int, num2: Int, num3: Int) -> Int {
if num1 < num2 { // partial order = num1, num2
if num2 < num3 {
return num2 // known order = num1, num2, num3
} else {
if num1 < num3 {
return num3 // known order = num1, num3, num2
} else {
return num1 // known order = num3, num1, num2
}
}
} else { // partial order = num2, num1
if num3 < num2 {
return num2 // known order = num3, num2, num1
} else {
if num3 > num1 {
return num1 // known order = num2, num1, num3
} else {
return num3 // known order = num2, num3, num1
}
}
}
}
/* Example Function Call
median(num1: 1, num2: 5, num3: 6) // 5
median(num1: 2, num2: 1, num3: 4) // 2
median(num1: 3, num2: 6, num3: 6) // 6
median(num1: -10, num2: 10, num3: 0) // 0
median(num1: 0, num2: 0, num3: 0) // 0
median(num1: 2, num2: 3, num3: 1) // 2
median(num1: 2, num2: 2, num3: 1) // 2
*/
median(num1: 1, num2: 5, num3: 6)
median(num1: 2, num2: 1, num3: 4)
median(num1: 3, num2: 6, num3: 6)
median(num1: -10, num2: 10, num3: 0)
median(num1: 0, num2: 0, num3: 0)
median(num1: 2, num2: 3, num3: 1)
median(num1: 2, num2: 2, num3: 1)
/*:
### Exercise 3
The function `beginsWithVowel` should take a single `String` parameter and return a `Bool` indicating whether the input string begins with a vowel. If the input string begins with a vowel return true, otherwise return false.
First, you will want to test if the input string is "". If the input string is "", then return false. Otherwise, you can access the first character of a `String` by using `nameOfString.characters[nameOfString.startIndex]`.
**It is assumed that the input string is given in English.**
*/
func beginsWithVowel(string: String) -> Bool {
if string == "" {
return false
} else {
switch(string.characters[string.startIndex]) {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
return true
default:
return false
}
}
}
/* Example Function Call
beginsWithVowel(string: "Apples") // true
beginsWithVowel(string: "pIG") // false
beginsWithVowel(string: "oink") // true
beginsWithVowel(string: "udacity") // true
beginsWithVowel(string: "") // false
*/
beginsWithVowel(string: "Apples")
beginsWithVowel(string: "pIG")
beginsWithVowel(string: "oink")
beginsWithVowel(string: "udacity")
beginsWithVowel(string: "")
/*:
### Exercise 4
The function `funWithWords` should take a single `String` parameter and return a new `String` that is uppercased if it begins with a vowel or lowercased if it begins with a consonant.
To uppercase a `String`, use `nameOfString.uppercased()`. To lowercase a `String`, use `nameOfString.lowercased()`.
**It is assumed that the input string is given in English.**
Hint: Re-use the `beginsWithVowel` function.
*/
func funWithWords(string: String) -> String {
if beginsWithVowel(string: string) {
return string.uppercased()
} else {
return string.lowercased()
}
}
/* Example Function Call
funWithWords(string: "Apples") // "APPLES"
funWithWords(string: "pIG") // "pig"
funWithWords(string: "oink") // "OINK"
funWithWords(string: "udacity") // "UDACITY"
funWithWords(string: "") // ""
*/
funWithWords(string: "Apples")
funWithWords(string: "pIG")
funWithWords(string: "oink")
funWithWords(string: "udacity")
funWithWords(string: "")
| mit | 3520113dc8c6a5ff2e1b614f81e17706 | 31.229167 | 224 | 0.625512 | 3.194081 | false | false | false | false |
xiaoleixy/Cocoa_swift | DrawingFun/DrawingFun/AppDelegate.swift | 1 | 8304 | //
// AppDelegate.swift
// DrawingFun
//
// Created by xiaolei3 on 15/3/2.
// Copyright (c) 2015年 michael. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var stretchView: StretchView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func showOpenPanel(sender: AnyObject)
{
weak var panel = NSOpenPanel()
panel?.allowedFileTypes = NSImage.imageFileTypes()
panel?.beginSheetModalForWindow(self.stretchView.window!, completionHandler: { (result) -> Void in
if NSOKButton == result
{
if let url:NSURL = panel?.URL {
var image = NSImage(contentsOfURL: url)
self.stretchView.image = image
}
}
panel = nil
})
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.michael.DrawingFun" in the user's Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let appSupportURL = urls[urls.count - 1] as NSURL
return appSupportURL.URLByAppendingPathComponent("com.michael.DrawingFun")
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("DrawingFun", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
let fileManager = NSFileManager.defaultManager()
var shouldFail = false
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
// Make sure the application files directory is there
let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
if let properties = propertiesOpt {
if !properties[NSURLIsDirectoryKey]!.boolValue {
failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
shouldFail = true
}
} else if error!.code == NSFileReadNoSuchFileError {
error = nil
fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
}
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator?
if !shouldFail && (error == nil) {
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("DrawingFun.storedata")
if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
}
}
if shouldFail || (error != nil) {
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
if error != nil {
dict[NSUnderlyingErrorKey] = error
}
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSApplication.sharedApplication().presentError(error!)
return nil
} else {
return coordinator
}
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving and Undo support
@IBAction func saveAction(sender: AnyObject!) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
if let moc = self.managedObjectContext {
if !moc.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
}
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
NSApplication.sharedApplication().presentError(error!)
}
}
}
func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
if let moc = self.managedObjectContext {
return moc.undoManager
} else {
return nil
}
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.
if let moc = managedObjectContext {
if !moc.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
return .TerminateCancel
}
if !moc.hasChanges {
return .TerminateNow
}
var error: NSError? = nil
if !moc.save(&error) {
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(error!)
if (result) {
return .TerminateCancel
}
let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
let alert = NSAlert()
alert.messageText = question
alert.informativeText = info
alert.addButtonWithTitle(quitButton)
alert.addButtonWithTitle(cancelButton)
let answer = alert.runModal()
if answer == NSAlertFirstButtonReturn {
return .TerminateCancel
}
}
}
// If we got here, it is time to quit.
return .TerminateNow
}
}
| mit | 491066d25615f10a5f2ebbd40479158d | 44.867403 | 346 | 0.641412 | 5.887943 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGeometry/ShapeRegion/ShapeRegionOp.swift | 1 | 8897 | //
// ShapeRegionOp.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
extension Shape.Component {
fileprivate func _union(_ other: Shape.Component, reference: Double) -> ShapeRegion? {
switch process(other, reference: reference) {
case .equal, .superset: return ShapeRegion(solid: ShapeRegion.Solid(solid: self))
case .subset: return ShapeRegion(solid: ShapeRegion.Solid(solid: other))
case .none: return nil
case let .regions(left, right): return left.union(right, reference: reference)
case let .loops(outer, _):
let _solid = outer.lazy.filter { $0.solid.area.sign == self.area.sign }.max { abs($0.area) }
guard let solid = _solid?.solid else { return ShapeRegion() }
let holes = ShapeRegion(solids: outer.filter { $0.solid.area.sign != self.area.sign })
return ShapeRegion(solids: [ShapeRegion.Solid(solid: solid, holes: holes)])
}
}
fileprivate func _intersection(_ other: Shape.Component, reference: Double) -> ShapeRegion {
switch process(other, reference: reference) {
case .equal, .subset: return ShapeRegion(solid: ShapeRegion.Solid(solid: self))
case .superset: return ShapeRegion(solid: ShapeRegion.Solid(solid: other))
case .none: return ShapeRegion()
case let .regions(left, right): return left.intersection(right, reference: reference)
case let .loops(_, inner): return ShapeRegion(solids: inner)
}
}
fileprivate func _subtracting(_ other: Shape.Component, reference: Double) -> (ShapeRegion?, Bool) {
switch process(other, reference: reference) {
case .equal, .subset: return (ShapeRegion(), false)
case .superset: return (nil, true)
case .none: return (nil, false)
case let .regions(left, right): return (left.subtracting(right, reference: reference), false)
case let .loops(outer, _): return (ShapeRegion(solids: outer), false)
}
}
}
extension ShapeRegion.Solid {
private var _solid: ShapeRegion.Solid {
return ShapeRegion.Solid(solid: self.solid)
}
fileprivate func union(_ other: ShapeRegion.Solid, reference: Double) -> [ShapeRegion.Solid]? {
if !self.boundary.isIntersect(other.boundary) {
return nil
}
let other = self.solid.area.sign == other.solid.area.sign ? other : other.reversed()
guard let union = self.solid._union(other.solid, reference: reference) else { return nil }
let a = self.holes.intersection(other.holes, reference: reference).solids
let b = self.holes.subtracting(other._solid, reference: reference)
let c = other.holes.subtracting(self._solid, reference: reference)
return union.subtracting(ShapeRegion(solids: chain(chain(a, b), c)), reference: reference).solids
}
fileprivate func intersection(_ other: ShapeRegion.Solid, reference: Double) -> [ShapeRegion.Solid] {
if !self.boundary.isIntersect(other.boundary) {
return []
}
let other = self.solid.area.sign == other.solid.area.sign ? other : other.reversed()
let intersection = self.solid._intersection(other.solid, reference: reference)
if !intersection.isEmpty {
return intersection.subtracting(self.holes, reference: reference).subtracting(other.holes, reference: reference).solids
} else {
return []
}
}
fileprivate func subtracting(_ other: ShapeRegion.Solid, reference: Double) -> [ShapeRegion.Solid] {
if !self.boundary.isIntersect(other.boundary) {
return [self]
}
let other = self.solid.area.sign == other.solid.area.sign ? other.reversed() : other
let (_subtracting, superset) = self.solid._subtracting(other.solid, reference: reference)
if superset {
return [ShapeRegion.Solid(solid: self.solid, holes: self.holes.union(ShapeRegion(solid: other), reference: reference))]
} else if let subtracting = _subtracting {
let a = chain(subtracting, other.holes.intersection(self._solid, reference: reference))
return self.holes.isEmpty ? Array(a) : ShapeRegion(solids: a).subtracting(self.holes, reference: reference).solids
} else {
return [self]
}
}
}
extension ShapeRegion {
fileprivate func intersection(_ other: ShapeRegion.Solid, reference: Double) -> [ShapeRegion.Solid] {
if self.isEmpty || !self.boundary.isIntersect(other.boundary) {
return []
}
return self.solids.flatMap { $0.intersection(other, reference: reference) }
}
fileprivate func subtracting(_ other: ShapeRegion.Solid, reference: Double) -> [ShapeRegion.Solid] {
if self.isEmpty {
return []
}
if !self.boundary.isIntersect(other.boundary) {
return self.solids
}
return self.solids.flatMap { $0.subtracting(other, reference: reference) }
}
}
extension ShapeRegion {
@usableFromInline
func union(_ other: ShapeRegion, reference: Double) -> ShapeRegion {
if self.isEmpty && other.isEmpty {
return ShapeRegion()
}
if self.isEmpty && !other.isEmpty {
return other
}
if !self.isEmpty && other.isEmpty {
return self
}
if !self.boundary.isIntersect(other.boundary) {
return ShapeRegion(solids: chain(self.solids, other.solids))
}
var result1 = self.solids
var result2: [ShapeRegion.Solid] = []
var remain = other.solids
outer: while let rhs = remain.popLast() {
for idx in result1.indices {
if let union = result1[idx].union(rhs, reference: reference) {
result1.remove(at: idx)
remain.append(contentsOf: union)
continue outer
}
}
result2.append(rhs)
}
return ShapeRegion(solids: chain(result1, result2))
}
@usableFromInline
func intersection(_ other: ShapeRegion, reference: Double) -> ShapeRegion {
if self.isEmpty || other.isEmpty || !self.boundary.isIntersect(other.boundary) {
return ShapeRegion()
}
return ShapeRegion(solids: other.solids.flatMap { self.intersection($0, reference: reference) })
}
@usableFromInline
func subtracting(_ other: ShapeRegion, reference: Double) -> ShapeRegion {
if self.isEmpty {
return ShapeRegion()
}
if other.isEmpty || !self.boundary.isIntersect(other.boundary) {
return self
}
return other.solids.reduce(self) { ShapeRegion(solids: $0.subtracting($1, reference: reference)) }
}
@usableFromInline
func symmetricDifference(_ other: ShapeRegion, reference: Double) -> ShapeRegion {
if self.isEmpty && other.isEmpty {
return ShapeRegion()
}
if self.isEmpty && !other.isEmpty {
return other
}
if !self.isEmpty && other.isEmpty {
return self
}
if !self.boundary.isIntersect(other.boundary) {
return ShapeRegion(solids: chain(self.solids, other.solids))
}
let a = self.subtracting(other, reference: reference).solids
let b = other.subtracting(self, reference: reference).solids
return ShapeRegion(solids: chain(a, b))
}
}
| mit | 4e881fdadd99de6ad7844e894f993592 | 39.076577 | 131 | 0.622457 | 4.376291 | false | false | false | false |
AlexanderTar/LASwift | Sources/Vector.swift | 1 | 2849 | // Vector.swift
//
// Copyright (c) 2017 Alexander Taraymovich <[email protected]>
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
import Accelerate
/// Typealiasing of array of Doubles to Vector
/// to make functions more mathematical.
public typealias Vector = [Double]
// MARK: - One-line creators for vectors
/// Create a vector of zeros.
///
/// - Parameters:
/// - count: number of elements
/// - Returns: zeros vector of specified size
public func zeros(_ count: Int) -> Vector {
return Vector(repeating: 0.0, count: count)
}
/// Create a vector of ones.
///
/// - Parameters:
/// - count: number of elements
/// - Returns: ones vector of specified size
public func ones(_ count: Int) -> Vector {
return Vector(repeating: 1.0, count: count)
}
/// Create a vector of uniformly distributed on [0, 1) interval random values.
///
/// - Parameters:
/// - count: number of elements
/// - Returns: random values vector of specified size
public func rand(_ count: Int) -> Vector {
var iDist = __CLPK_integer(1)
var iSeed = (0..<4).map { _ in __CLPK_integer(Random.within(0.0...4095.0)) }
var n = __CLPK_integer(count)
var x = Vector(repeating: 0.0, count: count)
dlarnv_(&iDist, &iSeed, &n, &x)
return x
}
/// Create a vector of normally distributed random values.
///
/// - Parameters:
/// - count: number of elements
/// - Returns: random values vector of specified size
public func randn(_ count: Int) -> Vector {
var iDist = __CLPK_integer(3)
var iSeed = (0..<4).map { _ in __CLPK_integer(Random.within(0.0...4095.0)) }
var n = __CLPK_integer(count)
var x = Vector(repeating: 0.0, count: count)
dlarnv_(&iDist, &iSeed, &n, &x)
return x
}
// MARK: - Vector comparison
/// Check if two vectors are equal using Double value approximate comparison
public func == (lhs: Vector, rhs: Vector) -> Bool {
return lhs ==~ rhs
}
/// Check if two vectors are not equal using Double value approximate comparison
public func != (lhs: Vector, rhs: Vector) -> Bool {
return lhs !=~ rhs
}
/// Check if one vector is greater than another using Double value approximate comparison
public func > (lhs: Vector, rhs: Vector) -> Bool {
return lhs >~ rhs
}
/// Check if one vector is less than another using Double value approximate comparison
public func < (lhs: Vector, rhs: Vector) -> Bool {
return lhs <~ rhs
}
/// Check if one vector is greater than or equal to another using Double value approximate comparison
public func >= (lhs: Vector, rhs: Vector) -> Bool {
return lhs >=~ rhs
}
/// Check if one vector is less than or equal to another using Double value approximate comparison
public func <= (lhs: Vector, rhs: Vector) -> Bool {
return lhs <=~ rhs
}
| bsd-3-clause | fcab515cdeaccd84f2050e88fb6208b9 | 29.634409 | 101 | 0.667252 | 3.643223 | false | false | false | false |
haijianhuo/TopStore | Pods/DynamicBlurView/DynamicBlurView/UIImage+Blur.swift | 3 | 802 | //
// UIImage+Blur.swift
// DynamicBlurView
//
// Created by Kyohei Ito on 2017/08/11.
// Copyright © 2017年 kyohei_ito. All rights reserved.
//
public extension UIImage {
func blurred(radius: CGFloat, iterations: Int, ratio: CGFloat, blendColor color: UIColor?, blendMode mode: CGBlendMode) -> UIImage? {
guard let cgImage = cgImage else {
return nil
}
if cgImage.area <= 0 || radius <= 0 {
return self
}
var boxSize = UInt32(radius * scale * ratio)
if boxSize % 2 == 0 {
boxSize += 1
}
return cgImage.blurred(with: boxSize, iterations: iterations, blendColor: color, blendMode: mode).map {
UIImage(cgImage: $0, scale: scale, orientation: imageOrientation)
}
}
}
| mit | 6f0ab63fb992144ce362aa25346105c4 | 27.535714 | 137 | 0.593242 | 4.227513 | false | false | false | false |
tapptitude/TTSegmentedControl | TTSegmentedControl.playground/Contents.swift | 1 | 2995 | //: Playground - noun: a place where people can play
import UIKit
import Foundation
import PlaygroundSupport
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 350, height: 667))
mainView.backgroundColor = UIColor.white
var segmentedC4: TTSegmentedControl = TTSegmentedControl()
var segmentedC3: TTSegmentedControl = TTSegmentedControl()
var segmentedC2: TTSegmentedControl = TTSegmentedControl()
var segmentedC1: TTSegmentedControl = TTSegmentedControl()
segmentedC1.frame = CGRect(x: 14, y: 73, width: 322, height: 76)
segmentedC2.frame = CGRect(x: 14, y: 186, width: 322, height: 47)
segmentedC3.frame = CGRect(x: 14, y: 299, width: 322, height: 47)
segmentedC4.frame = CGRect(x: 14, y: 417, width: 133, height: 35)
//SegmentedControl 1
segmentedC1.itemTitles = ["men","women","kids"]
segmentedC1.allowChangeThumbWidth = false
segmentedC1.selectedTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.3))
segmentedC1.defaultTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.01))
segmentedC1.cornerRadius = 5
segmentedC1.useGradient = false
segmentedC1.useShadow = false
segmentedC1.thumbColor = TTSegmentedControl.UIColorFromRGB(0xD9D72B)
//SegmentedControl 2
segmentedC2.itemTitles = ["gas","diesel","electric"]
segmentedC2.allowChangeThumbWidth = false
segmentedC2.selectedTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.3))
segmentedC2.defaultTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.01))
segmentedC2.cornerRadius = 0
segmentedC2.useShadow = false
segmentedC2.useGradient = true
segmentedC2.thumbGradientColors = [ TTSegmentedControl.UIColorFromRGB(0xFE2C5A), TTSegmentedControl.UIColorFromRGB(0xF10EAE)]
//SegmentedControl 3
segmentedC3.itemTitles = ["XS","S","M","L","XL"]
segmentedC3.allowChangeThumbWidth = false
segmentedC3.selectedTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.3))
segmentedC3.defaultTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.01))
segmentedC3.useGradient = true
segmentedC3.useShadow = true
segmentedC3.thumbShadowColor = TTSegmentedControl.UIColorFromRGB(0x22C6E7)
segmentedC3.thumbGradientColors = [ TTSegmentedControl.UIColorFromRGB(0x25D0EC), TTSegmentedControl.UIColorFromRGB(0x1EA3D8)]
segmentedC3.didSelectItemWith = { index, title in
print(index)
}
//SegmentedControl 4
segmentedC4.itemTitles = ["OFF","ON"]
segmentedC4.selectedTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.3))
segmentedC4.defaultTextFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(0.01))
segmentedC4.useGradient = false
segmentedC4.thumbColor = TTSegmentedControl.UIColorFromRGB(0x1FDB58)
segmentedC4.useShadow = true
segmentedC4.thumbShadowColor = TTSegmentedControl.UIColorFromRGB(0x56D37C)
segmentedC4.allowChangeThumbWidth = false
mainView.addSubview(segmentedC1)
mainView.addSubview(segmentedC2)
mainView.addSubview(segmentedC3)
mainView.addSubview(segmentedC4)
PlaygroundPage.current.liveView = mainView
| mit | aaa865d03ce4a6e65af39a3df6a7cf1c | 31.554348 | 125 | 0.798331 | 3.540189 | false | false | false | false |
zirinisp/SlackKit | SlackKit/Sources/Item.swift | 1 | 2446 | //
// Item.swift
//
// Copyright © 2016 Peter Zignego. 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.
public struct Item: Equatable {
public let type: String?
public let ts: String?
public let channel: String?
public let message: Message?
public let file: File?
public let comment: Comment?
public let fileCommentID: String?
internal init(item:[String: Any]?) {
type = item?["type"] as? String
ts = item?["ts"] as? String
channel = item?["channel"] as? String
message = Message(dictionary: item?["message"] as? [String: Any])
// Comment and File can come across as Strings or Dictionaries
if let commentDictionary = item?["comment"] as? [String: Any] {
comment = Comment(comment: commentDictionary)
} else {
comment = Comment(id: item?["comment"] as? String)
}
if let fileDictionary = item?["file"] as? [String: Any] {
file = File(file: fileDictionary)
} else {
file = File(id: item?["file"] as? String)
}
fileCommentID = item?["file_comment"] as? String
}
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.type == rhs.type && lhs.channel == rhs.channel && lhs.file == rhs.file && lhs.comment == rhs.comment && lhs.message == rhs.message
}
}
| mit | fb9f2dd047accbf566319c93d522d00d | 40.440678 | 149 | 0.659714 | 4.421338 | false | false | false | false |
BMWB/RRArt-Swift-Test | RRArt-Swift/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView.swift | 2 | 12879 | //
// NVActivityIndicatorView.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/21/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
/**
Enum of animation types used for activity indicator view.
- Blank: Blank animation.
- BallPulse: BallPulse animation.
- BallGridPulse: BallGridPulse animation.
- BallClipRotate: BallClipRotate animation.
- SquareSpin: SquareSpin animation.
- BallClipRotatePulse: BallClipRotatePulse animation.
- BallClipRotateMultiple: BallClipRotateMultiple animation.
- BallPulseRise: BallPulseRise animation.
- BallRotate: BallRotate animation.
- CubeTransition: CubeTransition animation.
- BallZigZag: BallZigZag animation.
- BallZigZagDeflect: BallZigZagDeflect animation.
- BallTrianglePath: BallTrianglePath animation.
- BallScale: BallScale animation.
- LineScale: LineScale animation.
- LineScaleParty: LineScaleParty animation.
- BallScaleMultiple: BallScaleMultiple animation.
- BallPulseSync: BallPulseSync animation.
- BallBeat: BallBeat animation.
- LineScalePulseOut: LineScalePulseOut animation.
- LineScalePulseOutRapid: LineScalePulseOutRapid animation.
- BallScaleRipple: BallScaleRipple animation.
- BallScaleRippleMultiple: BallScaleRippleMultiple animation.
- BallSpinFadeLoader: BallSpinFadeLoader animation.
- LineSpinFadeLoader: LineSpinFadeLoader animation.
- TriangleSkewSpin: TriangleSkewSpin animation.
- Pacman: Pacman animation.
- BallGridBeat: BallGridBeat animation.
- SemiCircleSpin: SemiCircleSpin animation.
- BallRotateChase: BallRotateChase animation.
*/
public enum NVActivityIndicatorType: Int {
/**
Blank.
- returns: Instance of NVActivityIndicatorAnimationBlank.
*/
case Blank
/**
BallPulse.
- returns: Instance of NVActivityIndicatorAnimationBallPulse.
*/
case BallPulse
/**
BallGridPulse.
- returns: Instance of NVActivityIndicatorAnimationBallGridPulse.
*/
case BallGridPulse
/**
BallClipRotate.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotate.
*/
case BallClipRotate
/**
SquareSpin.
- returns: Instance of NVActivityIndicatorAnimationSquareSpin.
*/
case SquareSpin
/**
BallClipRotatePulse.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotatePulse.
*/
case BallClipRotatePulse
/**
BallClipRotateMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotateMultiple.
*/
case BallClipRotateMultiple
/**
BallPulseRise.
- returns: Instance of NVActivityIndicatorAnimationBallPulseRise.
*/
case BallPulseRise
/**
BallRotate.
- returns: Instance of NVActivityIndicatorAnimationBallRotate.
*/
case BallRotate
/**
CubeTransition.
- returns: Instance of NVActivityIndicatorAnimationCubeTransition.
*/
case CubeTransition
/**
BallZigZag.
- returns: Instance of NVActivityIndicatorAnimationBallZigZag.
*/
case BallZigZag
/**
BallZigZagDeflect
- returns: Instance of NVActivityIndicatorAnimationBallZigZagDeflect
*/
case BallZigZagDeflect
/**
BallTrianglePath.
- returns: Instance of NVActivityIndicatorAnimationBallTrianglePath.
*/
case BallTrianglePath
/**
BallScale.
- returns: Instance of NVActivityIndicatorAnimationBallScale.
*/
case BallScale
/**
LineScale.
- returns: Instance of NVActivityIndicatorAnimationLineScale.
*/
case LineScale
/**
LineScaleParty.
- returns: Instance of NVActivityIndicatorAnimationLineScaleParty.
*/
case LineScaleParty
/**
BallScaleMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleMultiple.
*/
case BallScaleMultiple
/**
BallPulseSync.
- returns: Instance of NVActivityIndicatorAnimationBallPulseSync.
*/
case BallPulseSync
/**
BallBeat.
- returns: Instance of NVActivityIndicatorAnimationBallBeat.
*/
case BallBeat
/**
LineScalePulseOut.
- returns: Instance of NVActivityIndicatorAnimationLineScalePulseOut.
*/
case LineScalePulseOut
/**
LineScalePulseOutRapid.
- returns: Instance of NVActivityIndicatorAnimationLineScalePulseOutRapid.
*/
case LineScalePulseOutRapid
/**
BallScaleRipple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleRipple.
*/
case BallScaleRipple
/**
BallScaleRippleMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleRippleMultiple.
*/
case BallScaleRippleMultiple
/**
BallSpinFadeLoader.
- returns: Instance of NVActivityIndicatorAnimationBallSpinFadeLoader.
*/
case BallSpinFadeLoader
/**
LineSpinFadeLoader.
- returns: Instance of NVActivityIndicatorAnimationLineSpinFadeLoader.
*/
case LineSpinFadeLoader
/**
TriangleSkewSpin.
- returns: Instance of NVActivityIndicatorAnimationTriangleSkewSpin.
*/
case TriangleSkewSpin
/**
Pacman.
- returns: Instance of NVActivityIndicatorAnimationPacman.
*/
case Pacman
/**
BallGridBeat.
- returns: Instance of NVActivityIndicatorAnimationBallGridBeat.
*/
case BallGridBeat
/**
SemiCircleSpin.
- returns: Instance of NVActivityIndicatorAnimationSemiCircleSpin.
*/
case SemiCircleSpin
/**
BallRotateChase.
- returns: Instance of NVActivityIndicatorAnimationBallRotateChase.
*/
case BallRotateChase
private static let allTypes = (Blank.rawValue ... BallRotateChase.rawValue).map{ NVActivityIndicatorType(rawValue: $0)! }
private func animation() -> NVActivityIndicatorAnimationDelegate {
switch self {
case .Blank:
return NVActivityIndicatorAnimationBlank()
case .BallPulse:
return NVActivityIndicatorAnimationBallPulse()
case .BallGridPulse:
return NVActivityIndicatorAnimationBallGridPulse()
case .BallClipRotate:
return NVActivityIndicatorAnimationBallClipRotate()
case .SquareSpin:
return NVActivityIndicatorAnimationSquareSpin()
case .BallClipRotatePulse:
return NVActivityIndicatorAnimationBallClipRotatePulse()
case .BallClipRotateMultiple:
return NVActivityIndicatorAnimationBallClipRotateMultiple()
case .BallPulseRise:
return NVActivityIndicatorAnimationBallPulseRise()
case .BallRotate:
return NVActivityIndicatorAnimationBallRotate()
case .CubeTransition:
return NVActivityIndicatorAnimationCubeTransition()
case .BallZigZag:
return NVActivityIndicatorAnimationBallZigZag()
case .BallZigZagDeflect:
return NVActivityIndicatorAnimationBallZigZagDeflect()
case .BallTrianglePath:
return NVActivityIndicatorAnimationBallTrianglePath()
case .BallScale:
return NVActivityIndicatorAnimationBallScale()
case .LineScale:
return NVActivityIndicatorAnimationLineScale()
case .LineScaleParty:
return NVActivityIndicatorAnimationLineScaleParty()
case .BallScaleMultiple:
return NVActivityIndicatorAnimationBallScaleMultiple()
case .BallPulseSync:
return NVActivityIndicatorAnimationBallPulseSync()
case .BallBeat:
return NVActivityIndicatorAnimationBallBeat()
case .LineScalePulseOut:
return NVActivityIndicatorAnimationLineScalePulseOut()
case .LineScalePulseOutRapid:
return NVActivityIndicatorAnimationLineScalePulseOutRapid()
case .BallScaleRipple:
return NVActivityIndicatorAnimationBallScaleRipple()
case .BallScaleRippleMultiple:
return NVActivityIndicatorAnimationBallScaleRippleMultiple()
case .BallSpinFadeLoader:
return NVActivityIndicatorAnimationBallSpinFadeLoader()
case .LineSpinFadeLoader:
return NVActivityIndicatorAnimationLineSpinFadeLoader()
case .TriangleSkewSpin:
return NVActivityIndicatorAnimationTriangleSkewSpin()
case .Pacman:
return NVActivityIndicatorAnimationPacman()
case .BallGridBeat:
return NVActivityIndicatorAnimationBallGridBeat()
case .SemiCircleSpin:
return NVActivityIndicatorAnimationSemiCircleSpin()
case .BallRotateChase:
return NVActivityIndicatorAnimationBallRotateChase()
}
}
}
/// Activity indicator view with nice animations
public class NVActivityIndicatorView: UIView {
private static let DEFAULT_TYPE: NVActivityIndicatorType = .Pacman
private static let DEFAULT_COLOR = UIColor.whiteColor()
private static let DEFAULT_PADDING: CGFloat = 0
/// Animation type, value of NVActivityIndicatorType enum.
public var type: NVActivityIndicatorType = NVActivityIndicatorView.DEFAULT_TYPE
@available(*, unavailable, message="This property is reserved for Interface Builder. Use 'type' instead.")
@IBInspectable var typeName: String {
get {
return String(self.type)
}
set (typeString) {
for item in NVActivityIndicatorType.allTypes {
if String(item).caseInsensitiveCompare(typeString) == NSComparisonResult.OrderedSame {
self.type = item
break
}
}
}
}
/// Color of activity indicator view.
@IBInspectable public var color: UIColor = NVActivityIndicatorView.DEFAULT_COLOR
/// Padding of activity indicator view.
@IBInspectable public var padding: CGFloat = NVActivityIndicatorView.DEFAULT_PADDING
/// Current status of animation, this is not used to start or stop animation.
public var animating: Bool = false
/// Specify whether activity indicator view should hide once stopped.
@IBInspectable public var hidesWhenStopped: Bool = true
/**
Create a activity indicator view with default type, color and padding.
This is used by storyboard to initiate the view.
- Default type is pacman.
- Default color is white.
- Default padding is 0.
- parameter decoder:
- returns: The activity indicator view.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clearColor()
}
/**
Create a activity indicator view with specified frame, type, color and padding.
- parameter frame: view's frame.
- parameter type: animation type, value of NVActivityIndicatorType enum. Default type is pacman.
- parameter color: color of activity indicator view. Default color is white.
- parameter padding: view's padding. Default padding is 0.
- returns: The activity indicator view.
*/
public init(frame: CGRect, type: NVActivityIndicatorType = DEFAULT_TYPE, color: UIColor = DEFAULT_COLOR, padding: CGFloat = DEFAULT_PADDING) {
self.type = type
self.color = color
self.padding = padding
super.init(frame: frame)
}
/**
Start animation.
*/
public func startAnimation() {
if hidesWhenStopped && hidden {
hidden = false
}
if (self.layer.sublayers == nil) {
setUpAnimation()
}
self.layer.speed = 1
self.animating = true
}
/**
Stop animation.
*/
public func stopAnimation() {
self.layer.sublayers = nil
self.animating = false
if hidesWhenStopped && !hidden {
hidden = true
}
}
// MARK: Privates
private func setUpAnimation() {
let animation: protocol<NVActivityIndicatorAnimationDelegate> = self.type.animation()
var animationRect = UIEdgeInsetsInsetRect(self.frame, UIEdgeInsetsMake(padding, padding, padding, padding))
let minEdge = min(animationRect.width, animationRect.height)
self.layer.sublayers = nil
animationRect.size = CGSizeMake(minEdge, minEdge)
animation.setUpAnimationInLayer(self.layer, size: animationRect.size, color: self.color)
}
}
| apache-2.0 | a726de60c2f677130c9729f2f164493e | 31.117207 | 146 | 0.667133 | 5.843466 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/AlertView/Rx/Rx+BottomAlertSheet.swift | 1 | 2997 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxSwift
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Never {
/// Show the alert and returns `Element`
public func showSheetAfterCompletion(bottomAlertSheet: BottomAlertSheet) -> Completable {
self.do(afterCompleted: {
bottomAlertSheet.show()
})
}
/// Hides the alert and returns `Element`
public func hideBottomSheetOnCompletionOrError(bottomAlertSheet: BottomAlertSheet) -> Completable {
self.do(onError: { _ in
bottomAlertSheet.hide()
}, onCompleted: {
bottomAlertSheet.hide()
})
}
/// Show the alert and returns `Element`
public func showSheetAfterFailure(bottomAlertSheet: BottomAlertSheet) -> Completable {
self.do(afterError: { _ in
bottomAlertSheet.show()
})
}
/// Show the alert and returns `Element`
public func showSheetOnSubscription(bottomAlertSheet: BottomAlertSheet) -> Completable {
self.do(onSubscribe: {
bottomAlertSheet.show()
})
}
}
extension PrimitiveSequence where Trait == SingleTrait {
/// Show the alert and returns `Element`
public func showSheetAfterSuccess(bottomAlertSheet: BottomAlertSheet) -> Single<Element> {
self.do(afterSuccess: { _ in
bottomAlertSheet.show()
})
}
/// Show the alert and returns `Element`
public func showSheetAfterFailure(bottomAlertSheet: BottomAlertSheet) -> Single<Element> {
self.do(afterError: { _ in
bottomAlertSheet.show()
})
}
/// Show the alert and returns `Element`
public func showSheetOnSubscription(bottomAlertSheet: BottomAlertSheet) -> Single<Element> {
self.do(onSubscribe: {
bottomAlertSheet.show()
})
}
/// Hides the alert and returns `Element`
public func hideBottomSheetOnDisposal(bottomAlertSheet: BottomAlertSheet) -> Single<Element> {
self.do(onDispose: {
bottomAlertSheet.hide()
})
}
/// Hides the alert and returns `Element`
public func hideBottomSheetOnSuccessOrError(bottomAlertSheet: BottomAlertSheet) -> Single<Element> {
self.do(onSuccess: { _ in
bottomAlertSheet.hide()
}, onError: { _ in
bottomAlertSheet.hide()
})
}
}
/// Extension for `ObservableType` that enables the loader to take part in a chain of observables
extension ObservableType {
/// Shows the alert upon subscription
public func showSheetOnSubscription(bottomAlertSheet: BottomAlertSheet) -> Observable<Element> {
self.do(onSubscribe: {
bottomAlertSheet.show()
})
}
/// Hides the alert upon disposal
public func hideBottomSheetOnDisposal(bottomAlertSheet: BottomAlertSheet) -> Observable<Element> {
self.do(onDispose: {
bottomAlertSheet.hide()
})
}
}
| lgpl-3.0 | 72e36622e22cb787006e5e725bf180d2 | 30.87234 | 104 | 0.647196 | 4.602151 | false | false | false | false |
yscode001/YSExtension | YSExtension/YSExtension/YSExtension/UIKit/UILabel+ysExtension.swift | 1 | 1183 | import UIKit
extension UILabel{
public convenience init(textColor:UIColor, fontSize:CGFloat, text:String?, textAlignment:NSTextAlignment? = nil, numberOfLines:Int? = nil,target:Any? = nil,action:Selector? = nil){
self.init()
self.textColor = textColor
self.font = UIFont.systemFont(ofSize: fontSize)
self.text = text
self.numberOfLines = numberOfLines ?? 0
if let ta = textAlignment{
self.textAlignment = ta
}
if let t = target,let a = action{
addGestureRecognizer(UITapGestureRecognizer(target: t, action: a))
}
}
public convenience init(textColor:UIColor, font:UIFont, text:String?, textAlignment:NSTextAlignment? = nil, numberOfLines:Int? = nil,target:Any? = nil,action:Selector? = nil){
self.init()
self.textColor = textColor
self.font = font
self.text = text
self.numberOfLines = numberOfLines ?? 0
if let ta = textAlignment{
self.textAlignment = ta
}
if let t = target,let a = action{
addGestureRecognizer(UITapGestureRecognizer(target: t, action: a))
}
}
}
| mit | 034b2d2e772183c11653b079d878df85 | 35.96875 | 184 | 0.620456 | 4.603113 | false | false | false | false |
acrookston/SQLite.swift | SQLiteTests/SchemaTests.swift | 1 | 41932 | import XCTest
import SQLite
class SchemaTests : XCTestCase {
func test_drop_compilesDropTableExpression() {
XCTAssertEqual("DROP TABLE \"table\"", table.drop())
XCTAssertEqual("DROP TABLE IF EXISTS \"table\"", table.drop(ifExists: true))
}
func test_drop_compilesDropVirtualTableExpression() {
XCTAssertEqual("DROP TABLE \"virtual_table\"", virtualTable.drop())
XCTAssertEqual("DROP TABLE IF EXISTS \"virtual_table\"", virtualTable.drop(ifExists: true))
}
func test_drop_compilesDropViewExpression() {
XCTAssertEqual("DROP VIEW \"view\"", _view.drop())
XCTAssertEqual("DROP VIEW IF EXISTS \"view\"", _view.drop(ifExists: true))
}
func test_create_withBuilder_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (" +
"\"blob\" BLOB NOT NULL, " +
"\"blobOptional\" BLOB, " +
"\"double\" REAL NOT NULL, " +
"\"doubleOptional\" REAL, " +
"\"int64\" INTEGER NOT NULL, " +
"\"int64Optional\" INTEGER, " +
"\"string\" TEXT NOT NULL, " +
"\"stringOptional\" TEXT" +
")",
table.create { t in
t.column(data)
t.column(dataOptional)
t.column(double)
t.column(doubleOptional)
t.column(int64)
t.column(int64Optional)
t.column(string)
t.column(stringOptional)
}
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(ifNotExists: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true, ifNotExists: true) { $0.column(int64) }
)
}
func test_create_withQuery_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" AS SELECT \"int64\" FROM \"view\"",
table.create(_view.select(int64))
)
}
// thoroughness test for ambiguity
func test_column_compilesColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create { t in t.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE)",
table.create { t in t.column(int64, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (0))",
table.create { t in t.column(int64, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (0))",
table.create { t in t.column(int64, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER)",
table.create { t in t.column(int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE)",
table.create { t in t.column(int64Optional, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (0))",
table.create { t in t.column(int64Optional, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: 0) }
)
}
func test_column_withIntegerExpression_compilesPrimaryKeyAutoincrementColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",
table.create { t in t.column(int64, primaryKey: .Autoincrement) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64Optional > 0) }
)
}
func test_column_withIntegerExpression_compilesReferentialColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, references: table, int64) }
)
}
func test_column_withStringExpression_compilesCollatedColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
}
func test_primaryKey_compilesPrimaryKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\"))",
table.create { t in t.primaryKey(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\"))",
table.create { t in t.primaryKey(int64, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\", \"double\"))",
table.create { t in t.primaryKey(int64, string, double) }
)
}
func test_unique_compilesUniqueExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (UNIQUE (\"int64\"))",
table.create { t in t.unique(int64) }
)
}
func test_check_compilesCheckExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64\" > 0)))",
table.create { t in t.check(int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64Optional\" > 0)))",
table.create { t in t.check(int64Optional > 0) }
)
}
func test_foreignKey_compilesForeignKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(string, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"stringOptional\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(stringOptional, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\") ON UPDATE CASCADE ON DELETE SET NULL)",
table.create { t in t.foreignKey(string, references: table, string, update: .Cascade, delete: .SetNull) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\"))",
table.create { t in t.foreignKey((string, string), references: table, (string, string)) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\", \"string\"))",
table.create { t in t.foreignKey((string, string, string), references: table, (string, string, string)) }
)
}
func test_addColumn_compilesAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL DEFAULT (1)",
table.addColumn(int64, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64Optional > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER",
table.addColumn(int64Optional)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0)",
table.addColumn(int64Optional, check: int64 > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0)",
table.addColumn(int64Optional, check: int64Optional > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER DEFAULT (1)",
table.addColumn(int64Optional, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64Optional > 0, defaultValue: 1)
)
}
func test_addColumn_withIntegerExpression_compilesReferentialAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64Optional > 0, references: table, int64)
)
}
func test_addColumn_withStringExpression_compilesCollatedAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT COLLATE RTRIM",
table.addColumn(stringOptional, collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
}
func test_rename_compilesAlterTableRenameToExpression() {
XCTAssertEqual("ALTER TABLE \"old\" RENAME TO \"table\"", Table("old").rename(table))
}
func test_createIndex_compilesCreateIndexExpression() {
XCTAssertEqual("CREATE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex(int64))
XCTAssertEqual(
"CREATE UNIQUE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true)
)
XCTAssertEqual(
"CREATE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], ifNotExists: true)
)
XCTAssertEqual(
"CREATE UNIQUE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true, ifNotExists: true)
)
}
func test_dropIndex_compilesCreateIndexExpression() {
XCTAssertEqual("DROP INDEX \"index_table_on_int64\"", table.dropIndex(int64))
XCTAssertEqual("DROP INDEX IF EXISTS \"index_table_on_int64\"", table.dropIndex([int64], ifExists: true))
}
func test_create_onView_compilesCreateViewExpression() {
XCTAssertEqual(
"CREATE VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64))
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true)
)
XCTAssertEqual(
"CREATE VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), ifNotExists: true)
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true, ifNotExists: true)
)
}
func test_create_onVirtualTable_compilesCreateVirtualTableExpression() {
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING \"custom\"('foo', 'bar')",
virtualTable.create(Module("custom", ["foo", "bar"]))
)
}
func test_rename_onVirtualTable_compilesAlterTableRenameToExpression() {
XCTAssertEqual(
"ALTER TABLE \"old\" RENAME TO \"virtual_table\"",
VirtualTable("old").rename(virtualTable)
)
}
}
| mit | 1af07b70e3ac254c6656db8b729fa9c9 | 53.670143 | 155 | 0.582681 | 4.343935 | false | false | false | false |
norio-nomura/RxSwift | RxSwift/Linq/Just.swift | 1 | 3761 | //
// Just.swift
// RxSwift
//
// Created by 野村 憲男 on 4/2/15.
// Copyright (c) 2015 Norio Nomura. All rights reserved.
//
import Foundation
// MARK: public
public extension Observable {
/**
Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
:param: value Single element in the resulting observable sequence.
:returns: An observable sequence containing the single specified element.
*/
public static func just(value: Output) -> Observable {
return _just(value)
}
public static func returnValue(value: Output) -> Observable {
return _just(value)
}
/**
Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
:param: value value Single element in the resulting observable sequence.
:param: scheduler scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
:returns: An observable sequence containing the single specified element.
*/
public static func just(value: Output, scheduler: IScheduler) -> Observable {
return _just(value, scheduler: scheduler)
}
public static func returnValue(value: Output, scheduler: IScheduler) -> Observable {
return _just(value, scheduler: scheduler)
}
}
/**
Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
:param: value Single element in the resulting observable sequence.
:returns: An observable sequence containing the single specified element.
*/
public func just<T>(value: T) -> Observable<T> {
return _just(value)
}
public func returnValue<T>(value: T) -> Observable<T> {
return _just(value)
}
/**
Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
:param: value value Single element in the resulting observable sequence.
:param: scheduler scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
:returns: An observable sequence containing the single specified element.
*/
public func just<T>(value: T, scheduler: IScheduler) -> Observable<T> {
return _just(value, scheduler: scheduler)
}
public func returnValue<T>(value: T, scheduler: IScheduler) -> Observable<T> {
return _just(value, scheduler: scheduler)
}
// MARK: private
private func _just<T>(value: T, scheduler: IScheduler = Scheduler.immediate) -> Observable<T> {
return Just(value, scheduler)
}
private final class Just<TResult>: Producer<TResult> {
let value: TResult
let scheduler: IScheduler
init(_ value: TResult, _ scheduler: IScheduler) {
self.value = value
self.scheduler = scheduler
}
override func run<TObserver: IObserver where TObserver.Input == Output>(observer: TObserver, cancel: IDisposable?, setSink: IDisposable? -> ()) -> IDisposable? {
var sink = JustSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
}
private final class JustSink<TResult>: Sink<TResult> {
let parent: Just<TResult>
init<TObserver : IObserver where TObserver.Input == TResult>(parent: Just<TResult>, observer: TObserver, cancel: IDisposable?) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> IDisposable? {
return parent.scheduler.schedule(action: invoke)
}
func invoke() {
super.observer?.onNext(parent.value)
super.observer?.onCompleted()
super.dispose()
}
}
| mit | f4db5df9e997bd8762cc552c8c92d5ae | 31.353448 | 165 | 0.695444 | 4.363953 | false | false | false | false |
psharanda/adocgen | Carthage/Checkouts/GRMustache.swift/Sources/Foundation.swift | 1 | 12624 | // The MIT License
//
// Copyright (c) 2016 Gwendal Roué
//
// 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
/// GRMustache provides built-in support for rendering `NSObject`.
extension NSObject : MustacheBoxable {
/// `NSObject` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// You should not directly call the `mustacheBox` property.
///
///
/// NSObject's default implementation handles two general cases:
///
/// - Enumerable objects that conform to the `NSFastEnumeration` protocol,
/// such as `NSArray` and `NSOrderedSet`.
/// - All other objects
///
/// GRMustache ships with a few specific classes that escape the general
/// cases and provide their own rendering behavior: `NSDictionary`,
/// `NSFormatter`, `NSNull`, `NSNumber`, `NSString`, and `NSSet` (see the
/// documentation for those classes).
///
/// Your own subclasses of NSObject can also override the `mustacheBox`
/// method and provide their own custom behavior.
///
///
/// ## Arrays
///
/// An object is treated as an array if it conforms to `NSFastEnumeration`.
/// This is the case of `NSArray` and `NSOrderedSet`, for example.
/// `NSDictionary` and `NSSet` have their own custom Mustache rendering: see
/// their documentation for more information.
///
///
/// ### Rendering
///
/// - `{{array}}` renders the concatenation of the renderings of the
/// array items.
///
/// - `{{#array}}...{{/array}}` renders as many times as there are items in
/// `array`, pushing each item on its turn on the top of the
/// context stack.
///
/// - `{{^array}}...{{/array}}` renders if and only if `array` is empty.
///
///
/// ### Keys exposed to templates
///
/// An array can be queried for the following keys:
///
/// - `count`: number of elements in the array
/// - `first`: the first object in the array
/// - `last`: the last object in the array
///
/// Because 0 (zero) is falsey, `{{#array.count}}...{{/array.count}}`
/// renders once, if and only if `array` is not empty.
///
///
/// ## Other objects
///
/// Other objects fall in the general case.
///
/// Their keys are extracted with the `valueForKey:` method, as long as the
/// key is a property name, a custom property getter, or the name of a
/// `NSManagedObject` attribute.
///
///
/// ### Rendering
///
/// - `{{object}}` renders the result of the `description` method,
/// HTML-escaped.
///
/// - `{{{object}}}` renders the result of the `description` method, *not*
/// HTML-escaped.
///
/// - `{{#object}}...{{/object}}` renders once, pushing `object` on the top
/// of the context stack.
///
/// - `{{^object}}...{{/object}}` does not render.
@objc open var mustacheBox: MustacheBox {
if let enumerable = self as? NSFastEnumeration {
// Enumerable
// Turn enumerable into a Swift array that we know how to box
return Box(Array(IteratorSequence(NSFastEnumerationIterator(enumerable))))
} else {
// Generic NSObject
#if OBJC
return MustacheBox(
value: self,
keyedSubscript: { (key: String) in
if GRMustacheKeyAccess.isSafeMustacheKey(key, for: self) {
// Use valueForKey: for safe keys
return self.value(forKey: key)
} else {
// Missing key
return nil
}
})
#else
return MustacheBox(value: self)
#endif
}
}
}
/// GRMustache provides built-in support for rendering `NSNull`.
extension NSNull {
/// `NSNull` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// You should not directly call the `mustacheBox` property. Always use the
/// `Box()` function instead:
///
/// NSNull().mustacheBox // Valid, but discouraged
/// Box(NSNull()) // Preferred
///
///
/// ### Rendering
///
/// - `{{null}}` does not render.
///
/// - `{{#null}}...{{/null}}` does not render (NSNull is falsey).
///
/// - `{{^null}}...{{/null}}` does render (NSNull is falsey).
open override var mustacheBox: MustacheBox {
return MustacheBox(
value: self,
boolValue: false,
render: { (info: RenderingInfo) in return Rendering("") })
}
}
/// GRMustache provides built-in support for rendering `NSNumber`.
extension NSNumber {
/// `NSNumber` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// You should not directly call the `mustacheBox` property.
///
///
/// ### Rendering
///
/// NSNumber renders exactly like Swift numbers: depending on its internal
/// objCType, an NSNumber is rendered as a Swift Bool, Int, UInt, Int64,
/// UInt64, or Double.
///
/// - `{{number}}` is rendered with built-in Swift String Interpolation.
/// Custom formatting can be explicitly required with NumberFormatter,
/// as in `{{format(a)}}` (see `Formatter`).
///
/// - `{{#number}}...{{/number}}` renders if and only if `number` is
/// not 0 (zero).
///
/// - `{{^number}}...{{/number}}` renders if and only if `number` is 0 (zero).
///
open override var mustacheBox: MustacheBox {
let objCType = String(cString: self.objCType)
switch objCType {
case "c":
return Box(Int(int8Value))
case "C":
return Box(UInt(uint8Value))
case "s":
return Box(Int(int16Value))
case "S":
return Box(UInt(uint16Value))
case "i":
return Box(Int(int32Value))
case "I":
return Box(UInt(uint32Value))
case "l":
return Box(intValue)
case "L":
return Box(uintValue)
case "q":
return Box(int64Value)
case "Q":
return Box(uint64Value)
case "f":
return Box(floatValue)
case "d":
return Box(doubleValue)
case "B":
return Box(boolValue)
default:
return Box(self)
}
}
}
/// GRMustache provides built-in support for rendering `NSString`.
extension NSString {
/// `NSString` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// You should not directly call the `mustacheBox` property.
///
///
/// ### Rendering
///
/// - `{{string}}` renders the string, HTML-escaped.
///
/// - `{{{string}}}` renders the string, *not* HTML-escaped.
///
/// - `{{#string}}...{{/string}}` renders if and only if `string` is
/// not empty.
///
/// - `{{^string}}...{{/string}}` renders if and only if `string` is empty.
///
/// HTML-escaping of `{{string}}` tags is disabled for Text templates: see
/// `Configuration.contentType` for a full discussion of the content type of
/// templates.
///
///
/// ### Keys exposed to templates
///
/// A string can be queried for the following keys:
///
/// - `length`: the number of characters in the string (using Swift method).
open override var mustacheBox: MustacheBox {
return Box(self as String)
}
}
/// GRMustache provides built-in support for rendering `NSSet`.
extension NSSet {
/// `NSSet` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// let set: NSSet = [1,2,3]
///
/// // Renders "213"
/// let template = try! Template(string: "{{#set}}{{.}}{{/set}}")
/// try! template.render(Box(["set": Box(set)]))
///
///
/// You should not directly call the `mustacheBox` property.
///
/// ### Rendering
///
/// - `{{set}}` renders the concatenation of the renderings of the set
/// items, in any order.
///
/// - `{{#set}}...{{/set}}` renders as many times as there are items in
/// `set`, pushing each item on its turn on the top of the context stack.
///
/// - `{{^set}}...{{/set}}` renders if and only if `set` is empty.
///
///
/// ### Keys exposed to templates
///
/// A set can be queried for the following keys:
///
/// - `count`: number of elements in the set
/// - `first`: the first object in the set
///
/// Because 0 (zero) is falsey, `{{#set.count}}...{{/set.count}}` renders
/// once, if and only if `set` is not empty.
open override var mustacheBox: MustacheBox {
return Box(Set(IteratorSequence(NSFastEnumerationIterator(self)).compactMap { $0 as? AnyHashable }))
}
}
/// GRMustache provides built-in support for rendering `NSDictionary`.
extension NSDictionary {
/// `NSDictionary` adopts the `MustacheBoxable` protocol so that it can feed
/// Mustache templates.
///
/// // Renders "Freddy Mercury"
/// let dictionary: NSDictionary = [
/// "firstName": "Freddy",
/// "lastName": "Mercury"]
/// let template = try! Template(string: "{{firstName}} {{lastName}}")
/// let rendering = try! template.render(Box(dictionary))
///
///
/// You should not directly call the `mustacheBox` property.
///
///
/// ### Rendering
///
/// - `{{dictionary}}` renders the result of the `description` method,
/// HTML-escaped.
///
/// - `{{{dictionary}}}` renders the result of the `description` method,
/// *not* HTML-escaped.
///
/// - `{{#dictionary}}...{{/dictionary}}` renders once, pushing `dictionary`
/// on the top of the context stack.
///
/// - `{{^dictionary}}...{{/dictionary}}` does not render.
///
///
/// In order to iterate over the key/value pairs of a dictionary, use the
/// `each` filter from the Standard Library:
///
/// // Attach StandardLibrary.each to the key "each":
/// let template = try! Template(string: "<{{# each(dictionary) }}{{@key}}:{{.}}, {{/}}>")
/// template.register(StandardLibrary.each, forKey: "each")
///
/// // Renders "<name:Arthur, age:36, >"
/// let dictionary = ["name": "Arthur", "age": 36] as NSDictionary
/// let rendering = try! template.render(["dictionary": dictionary])
open override var mustacheBox: MustacheBox {
return Box(self as? [AnyHashable: Any])
}
}
/// Support for Mustache rendering of ReferenceConvertible types.
extension ReferenceConvertible where Self: MustacheBoxable {
/// Returns a MustacheBox that behaves like the equivalent NSObject.
///
/// See NSObject.mustacheBox
public var mustacheBox: MustacheBox {
return (self as! ReferenceType).mustacheBox
}
}
/// Data can feed Mustache templates.
extension Data : MustacheBoxable { }
/// Date can feed Mustache templates.
extension Date : MustacheBoxable { }
/// URL can feed Mustache templates.
extension URL : MustacheBoxable { }
/// UUID can feed Mustache templates.
extension UUID : MustacheBoxable { }
| mit | 4e13a6326666a12fca4855dea7e2d294 | 33.489071 | 108 | 0.577517 | 4.571894 | false | false | false | false |
duliodenis/v | V/V/AppDelegate.swift | 1 | 5746 | //
// AppDelegate.swift
// V
//
// Created by Dulio Denis on 4/11/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// private optional contact importer
private var contactImporter: ContactImporter?
// private optional context sync manager for Contact syncing
private var contactsSyncer: ContextSyncManager?
// private optional context sync manager for remote Contact syncing
private var contactsUploadSyncer: ContextSyncManager?
// private optional context sync manager for Firebase syncing
private var firebaseSyncer: ContextSyncManager?
// private optional for our Remote Firebase Store
private var firebaseStore: FirebaseStore?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// setup the main App context with the Main Queue Concurrency Type
let mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
// setup the coordinator using our CoreDataStack Singleton
mainContext.persistentStoreCoordinator = CoreDataStack.sharedInstance.coordinator
// setup a Private Dispatch Queue Context for the Contacts to work in its own thread
let contactsContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
// setup the persistent store coordinator for the contacts context
contactsContext.persistentStoreCoordinator = CoreDataStack.sharedInstance.coordinator
// setup a Private Dispatch Queue Context for the Firebase Context to work in its own thread
let firebaseContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
// setup the persistent store coordinator for the Firebase context
firebaseContext.persistentStoreCoordinator = CoreDataStack.sharedInstance.coordinator
// initialize the Firebase Store
let firebaseStore = FirebaseStore(context: firebaseContext)
self.firebaseStore = firebaseStore
// initialize contacts remote upload syncer with Contacts context and firebase context
contactsUploadSyncer = ContextSyncManager(mainContext: contactsContext, backgroundContext: firebaseContext)
contactsUploadSyncer?.remoteStore = firebaseStore
// initialize firebase remote syncer with main context and firebase context
firebaseSyncer = ContextSyncManager(mainContext: mainContext, backgroundContext: firebaseContext)
firebaseSyncer?.remoteStore = firebaseStore
// initialize contacts syncer with main context and contacts context
contactsSyncer = ContextSyncManager(mainContext: mainContext, backgroundContext: contactsContext)
// initialize contact importer
contactImporter = ContactImporter(context: contactsContext)
// call the import contacts with this private queue context (pre-Firebase)
// importContacts(contactsContext)
// generate an instance of a tab bar controller
let tabController = UITabBarController()
// set-up an array of tuple instances of view controller data
let vcData: [(UIViewController, UIImage, String)] = [
(FavoritesViewController(), UIImage(named: "favorites_icon")!, "Favorites"),
(ContactsViewController(), UIImage(named: "contact_icon")!, "Contacts"),
(AllChatsViewController(), UIImage(named: "chat_icon")!, "Chats")
]
// use map closure method to create an array of UINavigationController instances
let viewControllers = vcData.map {
(vc: UIViewController, image: UIImage, title: String) -> UINavigationController in
// set-up the context of each ViewController using the ContextVC Protocol
if var vc = vc as? ContextViewController {
vc.context = mainContext
}
// for each nav controller we set its root VC
let nav = UINavigationController(rootViewController: vc)
// its image
nav.tabBarItem.image = image
// and its title
nav.title = title
// and return the NavController
return nav
}
tabController.viewControllers = viewControllers
if firebaseStore.hasAuth() {
firebaseStore.startSyncing()
// listen for changes
contactImporter?.listenForChanges()
window?.rootViewController = tabController
} else {
let vc = SignUpViewController()
vc.remoteStore = firebaseStore
vc.rootViewController = tabController
vc.contactImporter = contactImporter
window?.rootViewController = vc
}
return true
}
// MARK: Import Contacts into Core Data
func importContacts(context: NSManagedObjectContext) {
// check to see if we have a DataSeeded key in user defaults
let dataSeeded = NSUserDefaults.standardUserDefaults().boolForKey("DataSeeded")
// if we've already seeded data fall through and do not seed again
guard !dataSeeded else { return }
// fetch the user's contacts
contactImporter?.fetch()
// update user defaults with a true value for seeded data key
NSUserDefaults.standardUserDefaults().setObject(true, forKey: "DataSeeded")
}
} | mit | 1959dec9e02492366c94dc4acc9a0d38 | 41.562963 | 128 | 0.673803 | 6.170784 | false | false | false | false |
ilyapuchka/ViewControllerThinning | ViewControllerThinning/Views/Animations/ShakeAnimation.swift | 1 | 1302 | //
// ShakeAnimation.swift
// ViewControllerThinning
//
// Created by Ilya Puchka on 09.10.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import UIKit
@objc
protocol Animation {
var duration: Double {get}
var view: UIView? {get}
}
extension Animation {
func play() {
fatalError("Concrete instances of Animation protocol should provide implementation of this method.")
}
}
@objc
protocol ShakeAnimation: Animation {
var maxOffset: Double {get set}
var keyPath: String {get set}
}
extension ShakeAnimation {
func play() {
guard let view = view else { return }
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.values = [0, maxOffset, -0.8 * maxOffset, 0.4 * maxOffset, 0]
animation.keyTimes = [ 0, (1 / 6.0), (3 / 6.0), (5 / 6.0), 1 ]
animation.duration = duration ?? view.implicitAnimationDuration
animation.additive = true
view.layer.addAnimation(animation, forKey: "shake")
}
}
class ShakeAnimationImp: NSObject, ShakeAnimation {
@IBInspectable
var duration: Double = 0.2
@IBInspectable
var maxOffset: Double = 10
@IBInspectable
var keyPath: String = "position.x"
@IBOutlet
weak var view: UIView?
}
| mit | ac6f8a354c46eede0c6c9a2f7fff00ed | 21.824561 | 108 | 0.641045 | 4.015432 | false | false | false | false |
ryanbaldwin/RealmSwiftFHIR | firekit/fhir-parser-resources/fhir-1.6.0/swift-3.1/RealmTypes.swift | 1 | 4319 | //
// RealmTypes.swift
// SwiftFHIR
//
// Updated for Realm support by Ryan Baldwin on 2017-08-09
// Copyright @ 2017 Bunnyhug. All rights fall under Apache 2
//
import Foundation
import RealmSwift
public class RealmString: Object {
public dynamic var value: String = ""
public convenience init(val: String) {
self.init()
self.value = val
}
}
public class RealmInt: Object {
public dynamic var value: Int = 0
public convenience init(val: Int) {
self.init()
self.value = val
}
}
public class RealmDecimal: Object {
private dynamic var _value = "0"
public var value: Decimal {
get { return Decimal(string: _value)! }
set { _value = String(describing: newValue) }
}
public convenience init(string val: String) {
self.init()
self._value = val
}
public override class func ignoredProperties() -> [String] {
return ["value"]
}
public static func ==(lhs: RealmDecimal, rhs: RealmDecimal) -> Bool {
return lhs.value.isEqual(to: rhs.value)
}
public static func ==(lhs: RealmDecimal?, rhs: RealmDecimal) -> Bool {
if let lhs = lhs {
return lhs == rhs
}
return false
}
public static func ==(lhs: RealmDecimal, rhs: RealmDecimal?) -> Bool {
if let rhs = rhs {
return lhs == rhs
}
return false
}
}
public class RealmURL: Object {
private dynamic var _value: String?
private var _url: URL? = nil
public var value: URL? {
get {
if _url == nil {
_url = URL(string: _value ?? "")
}
return _url
}
set {
_url = newValue
_value = newValue?.absoluteString ?? ""
}
}
public override class func ignoredProperties() -> [String] {
return ["value", "_url"]
}
}
/// Realm is limited in its polymorphism and can't contain a List of different
/// classes. As a result, for example, deserializing from JSON into a DomainResource
/// will fail if that resource has any contained resources.
///
/// In normal SwiftFHIR the `DomainResource.contained` works fine, but because of
/// Swift's limitations it fails. `DomainResource.contained: RealmSwift<Resource>`
/// will blow up at runtime. The workaround is to create a `ContainedResource: Resource`
/// Which will store the same information as `Resource`, but will also provide functionality
/// to store the original JSON and inflate it on demand into the proper type.
public class ContainedResource: Resource {
public dynamic var resourceType: String?
private dynamic var json: Data?
private var _resource: FHIRAbstractBase? = nil
public var resource: FHIRAbstractBase? {
guard let resourceType = resourceType,
let json = json else {
return nil
}
if _resource == nil {
let js = NSKeyedUnarchiver.unarchiveObject(with: json) as! FHIRJSON
_resource = FHIRAbstractBase.factory(resourceType, json: js, owner: nil)
}
return _resource
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["resourceType"] {
presentKeys.insert("resourceType")
if let val = exist as? String {
self.resourceType = val
}
else {
errors.append(FHIRJSONError(key: "resourceType", wants: String.self, has: type(of: exist)))
}
}
self.json = NSKeyedArchiver.archivedData(withRootObject: js)
}
return errors.isEmpty ? nil : errors
}
public override func asJSON() -> FHIRJSON {
guard let resource = resource else {
return ["fhir_comments": "Failed to serialize ContainedResource (\(String(describing: self.resourceType))) because the resource was not set."]
}
return resource.asJSON()
}
}
| apache-2.0 | c9c26534aaabb4d78f91c7525081f4c4 | 28.582192 | 154 | 0.584395 | 4.669189 | false | false | false | false |
cygy/swift-ovh | Examples/OVHAPIWrapper-Example-watchOS/OVHAPIWrapper-Example-watchOS/ProductsViewController.swift | 2 | 14131 | //
// ProductsViewController.swift
//
// Copyright (c) 2016, OVH SAS.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of OVH SAS nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY OVH SAS 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 OVH SAS AND 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 UIKit
import CoreData
import OVHAPIWrapper
class ProductsViewController: UICollectionViewController, NSFetchedResultsControllerDelegate {
// MARK: - Properties
lazy fileprivate var fetchedResultsController: NSFetchedResultsController<OVHVPS> = { () -> NSFetchedResultsController<OVHVPS> in
let fetchRequest: NSFetchRequest<OVHVPS> = OVHVPS.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "displayName", ascending: true)]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.sharedManager.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
typealias changes = () -> ()
fileprivate var sectionsChanges = [changes]()
fileprivate var objectChanges = [changes]()
// MARK: - UI elements
@IBOutlet weak var authenticateButton: UIBarButtonItem!
fileprivate var refreshControl: UIRefreshControl?
// MARK: - Actions
@IBAction func authenticate(_ sender: UIBarButtonItem) {
sender.isEnabled = false;
OVHVPSController.sharedController.OVHAPI.requestCredentials(withAccessRules: [OVHAPIAccessRule(method: .get, path: "/vps*"), OVHAPIAccessRule(method: .post, path: "/vps*")], redirection: "https://www.ovh.com/fr/") { (viewController, error) -> Void in
guard error == nil else {
self.presentError(error)
sender.isEnabled = true
return
}
if let viewController = viewController {
viewController.completion = { consumerKeyIsValidated in
sender.isEnabled = true
if consumerKeyIsValidated {
self.refreshControl?.beginRefreshing()
self.collectionView?.contentOffset = CGPoint(x: 0, y: -self.refreshControl!.frame.size.height);
self.refreshVPS(self.refreshControl!)
// Send to the watch the updated credentials.
WatchSessionManager.sharedManager.updateAPICredentials()
}
}
self.present(viewController, animated: true, completion: nil)
}
}
}
@IBAction func refreshVPS(_ sender: UIRefreshControl) {
OVHVPSController.sharedController.loadVPS(withBlock: { error in
self.presentError(error)
self.refreshControl?.endRefreshing()
})
}
// MARK: - UICollectionViewController delegate methods
override func numberOfSections(in collectionView: UICollectionView) -> Int {
if let count = fetchedResultsController.sections?.count {
return count
}
return 0
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let sectionInfo = fetchedResultsController.sections?[section] {
return sectionInfo.numberOfObjects
}
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VPSCell", for: indexPath)
let VPS = fetchedResultsController.object(at: indexPath)
configureCell(cell, withVPS: VPS)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let VPS = fetchedResultsController.object(at: indexPath)
// No action on the busy VPS.
guard !VPS.isBusy() && !VPS.isStateUnknown() else {
return
}
let VPSName = VPS.name!
// Create the alert controller to present to the user.
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// Add the 'start' action.
if VPS.isStopped() {
let startAction = UIAlertAction(title: "Start", style: .default, handler: { action -> Void in
OVHVPSController.sharedController.startVPS(withName: VPSName, andCompletionBlock: { (task, error) in
self.presentError(error)
})
})
alertController.addAction(startAction)
}
if VPS.isRunning() {
// Add the 'reboot' action.
let rebootAction = UIAlertAction(title: "Reboot", style: .default, handler: { action -> Void in
OVHVPSController.sharedController.rebootVPS(withName: VPSName, andCompletionBlock: { (task, error) in
self.presentError(error)
})
})
alertController.addAction(rebootAction)
// Add the 'stop' action.
let stopAction = UIAlertAction(title: "Stop", style: .destructive, handler: { action -> Void in
OVHVPSController.sharedController.stopVPS(withName: VPSName, andCompletionBlock: { (task, error) in
self.presentError(error)
})
})
alertController.addAction(stopAction)
}
// Add the 'cancel' action.
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { action -> Void in
alertController.dismiss(animated: true, completion: nil)
})
alertController.addAction(cancelAction)
// A popover is created on the devices supporting this feature (iPad).
if let popoverPresentationController = alertController.popoverPresentationController {
alertController.modalPresentationStyle = .popover
if let cell = collectionView.cellForItem(at: indexPath) {
popoverPresentationController.sourceView = cell
popoverPresentationController.sourceRect = cell.bounds
}
}
// Present the alert controller to the user.
present(alertController, animated: true, completion: nil)
}
// MARK: - FetchedController delegate methods
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
sectionsChanges.removeAll()
objectChanges.removeAll()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
collectionView?.performBatchUpdates({ () -> Void in
for block in self.sectionsChanges {
block()
}
for block in self.objectChanges {
block()
}
}, completion: { (Bool) -> Void in
self.sectionsChanges.removeAll()
self.objectChanges.removeAll()
})
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let sections = IndexSet(integer: sectionIndex)
switch (type) {
case .insert:
sectionsChanges.append({ () -> () in
self.collectionView?.insertSections(sections)
})
case .delete:
sectionsChanges.append({ () -> () in
self.collectionView?.deleteSections(sections)
})
case .update:
sectionsChanges.append({ () -> () in
self.collectionView?.reloadSections(sections)
})
case .move:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let newIndexPath = newIndexPath {
objectChanges.append({ () -> () in
self.collectionView?.insertItems(at: [newIndexPath])
})
}
case .delete:
if let indexPath = indexPath {
objectChanges.append({ () -> () in
self.collectionView?.deleteItems(at: [indexPath])
})
}
case .update:
if let indexPath = indexPath {
objectChanges.append({ () -> () in
self.collectionView?.reloadItems(at: [indexPath])
})
}
case .move:
if let indexPath = indexPath, let newIndexPath = newIndexPath {
objectChanges.append({ () -> () in
// A cell must change its position means that this cell must be updated with the corresponding VPS.
if let cell = self.collectionView?.cellForItem(at: indexPath) {
let VPS = self.fetchedResultsController.object(at: newIndexPath)
self.configureCell(cell, withVPS: VPS)
}
self.collectionView?.moveItem(at: indexPath, to: newIndexPath)
})
}
}
}
// MARK: - Private methods
fileprivate func configureCell(_ cell: UICollectionViewCell, withVPS VPS: OVHVPS) {
let nameLabel = cell.viewWithTag(1) as! UILabel
let imageView = cell.viewWithTag(2) as! UIImageView
let loadingView = cell.viewWithTag(3) as! UIActivityIndicatorView
nameLabel.text = VPS.displayName
if VPS.isBusy() {
imageView.alpha = 0.25
nameLabel.alpha = 0.25
loadingView.startAnimating()
} else {
imageView.alpha = 1.0
nameLabel.alpha = 1.0
loadingView.stopAnimating()
}
var color = UIColor.gray
if VPS.isRunning() {
color = UIColor(red: 0.0, green: 0.8, blue: 0.2, alpha: 1.0)
} else if VPS.isStopped() {
color = UIColor.black
}
imageView.tintColor = color
}
fileprivate func presentError(_ error: Error?) {
guard error != nil else {
return
}
var title: String? = error.debugDescription
var message: String? = nil
if let error = error as? OVHAPIError {
title = error.description
switch error {
case OVHAPIError.missingApplicationKey: message = "Please fix the Credentials.plist file."
case OVHAPIError.missingApplicationSecret: message = "Please fix the Credentials.plist file."
case OVHAPIError.missingConsumerKey: message = "Please authenticate first."
case OVHAPIError.httpError(let code): message = "code \(code)"
case OVHAPIError.requestError(_, let httpCode?, let errorCode?, _): message = "Error \(httpCode): \(errorCode)"
default: break
}
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Close", style: .cancel) { action in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(ProductsViewController.refreshVPS(_:)), for: .valueChanged)
if let refreshControl = refreshControl {
collectionView?.addSubview(refreshControl)
collectionView?.alwaysBounceVertical = true
}
do {
try fetchedResultsController.performFetch()
} catch let error {
print("Failed to fetch VPS: \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| bsd-3-clause | c50c711b859999cf01bbf32915d030ff | 38.918079 | 258 | 0.607034 | 5.487767 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/ViewControllers/PollingViewController.swift | 1 | 12520 | //
// PollingViewController.swift
// StripePaymentSheet
//
// Created by Nick Porter on 9/2/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
/// For internal SDK use only
@objc(STP_Internal_PollingViewController)
class PollingViewController: UIViewController {
private enum PollingState {
case polling
case error
}
// MARK: State
private let deadline = Date().addingTimeInterval(60 * 5) // in 5 minutes
private var oneSecondTimer: Timer?
private let currentAction: STPPaymentHandlerActionParams
private let appearance: PaymentSheet.Appearance
private lazy var intentPoller: IntentStatusPoller = {
guard let currentAction = currentAction as? STPPaymentHandlerPaymentIntentActionParams,
let clientSecret = currentAction.paymentIntent?.clientSecret else { fatalError() }
let intentPoller = IntentStatusPoller(apiClient: currentAction.apiClient,
clientSecret: clientSecret,
maxRetries: 12)
intentPoller.delegate = self
return intentPoller
}()
private var timeRemaining: TimeInterval {
return Date().compatibleDistance(to: deadline)
}
private var dateFormatter: DateComponentsFormatter {
let formatter = DateComponentsFormatter()
if timeRemaining > 60 {
formatter.zeroFormattingBehavior = .dropLeading
} else {
formatter.zeroFormattingBehavior = .pad
}
formatter.allowedUnits = [.minute, .second]
return formatter
}
private var instructionLabelAttributedText: NSAttributedString {
let timeRemaining = dateFormatter.string(from: timeRemaining) ?? ""
let attrText = NSMutableAttributedString(string: String(
format: .Localized.open_upi_app,
timeRemaining
))
attrText.addAttributes([.foregroundColor: appearance.colors.primary],
range: NSString(string: attrText.string).range(of: timeRemaining))
return attrText
}
private var pollingState: PollingState = .polling {
didSet {
if oldValue != pollingState && pollingState == .error {
moveToErrorState()
}
}
}
private lazy var setErrorStateWorkItem: DispatchWorkItem = {
let workItem = DispatchWorkItem { [weak self] in
self?.pollingState = .error
}
return workItem
}()
// MARK: Views
lazy var formStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [errorImageView,
actvityIndicator,
titleLabel,
instructionLabel,
cancelButton])
stackView.directionalLayoutMargins = PaymentSheetUI.defaultMargins
stackView.isLayoutMarginsRelativeArrangement = true
stackView.axis = .vertical
// hard coded spacing values from figma
stackView.spacing = 18
stackView.setCustomSpacing(14, after: errorImageView)
stackView.setCustomSpacing(8, after: titleLabel)
stackView.setCustomSpacing(12, after: instructionLabel)
return stackView
}()
private lazy var actvityIndicator: ActivityIndicator = {
let indicator = ActivityIndicator(size: .large)
indicator.tintColor = appearance.colors.icon
indicator.startAnimating()
return indicator
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.text = .Localized.approve_payment
label.textColor = appearance.colors.text
label.font = appearance.scaledFont(for: appearance.font.base.medium, style: .body, maximumPointSize: 25)
label.sizeToFit()
return label
}()
private lazy var instructionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.font = appearance.scaledFont(for: appearance.font.base.regular, style: .subheadline, maximumPointSize: 22)
label.textColor = appearance.colors.textSecondary
label.attributedText = instructionLabelAttributedText
label.sizeToFit()
return label
}()
private lazy var cancelButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(.Localized.cancel_pay_another_way, for: .normal)
button.titleLabel?.font = appearance.scaledFont(for: appearance.font.base.regular, style: .footnote, maximumPointSize: 22)
button.addTarget(self, action: #selector(didTapCancel), for: .touchUpInside)
button.tintColor = appearance.colors.primary
return button
}()
// MARK: Error state views
private lazy var errorImageView: UIImageView = {
let imageView = UIImageView(image: Image.polling_error.makeImage(template: true))
imageView.tintColor = appearance.colors.danger
imageView.contentMode = .scaleAspectFit
imageView.isHidden = true
return imageView
}()
// MARK: Navigation bar
internal lazy var navigationBar: SheetNavigationBar = {
let navBar = SheetNavigationBar(isTestMode: false,
appearance: appearance)
navBar.delegate = self
navBar.setStyle(.none)
return navBar
}()
// MARK: Overrides
init(currentAction: STPPaymentHandlerActionParams, appearance: PaymentSheet.Appearance) {
self.currentAction = currentAction
self.appearance = appearance
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// disable swipe to dismiss
isModalInPresentation = true
// Height of the polling view controller is either the height of the parent, or the height of the screen (flow controller use case)
let height = parent?.view.frame.size.height ?? UIScreen.main.bounds.height
let stackView = UIStackView(arrangedSubviews: [formStackView])
stackView.spacing = PaymentSheetUI.defaultPadding
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.backgroundColor = appearance.colors.background
view.backgroundColor = appearance.colors.background
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
view.heightAnchor.constraint(equalToConstant: height - SheetNavigationBar.height),
])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if oneSecondTimer == nil {
oneSecondTimer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: (#selector(updateTimer)),
userInfo: nil,
repeats: true)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.intentPoller.beginPolling()
}
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
intentPoller.suspendPolling()
NotificationCenter.default.removeObserver(self)
}
// MARK: Handlers
@objc func didTapCancel() {
currentAction.complete(with: .canceled, error: nil)
dismiss()
}
private func dismiss() {
if let authContext = currentAction.authenticationContext as? PaymentSheetAuthenticationContext {
authContext.authenticationContextWillDismiss?(self)
authContext.dismiss(self)
}
oneSecondTimer?.invalidate()
}
// MARK: App lifecycle observers
@objc func didBecomeActive(_ notification: Notification) {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.intentPoller.beginPolling()
}
}
@objc func didEnterBackground(_ notification: Notification) {
intentPoller.suspendPolling()
}
// MARK: Timer handler
@objc func updateTimer() {
guard timeRemaining > 0 else {
oneSecondTimer?.invalidate()
finishPolling()
return
}
instructionLabel.attributedText = instructionLabelAttributedText
}
// MARK: Private helpers
private func moveToErrorState() {
DispatchQueue.main.async {
self.errorImageView.isHidden = false
self.actvityIndicator.isHidden = true
self.cancelButton.isHidden = true
self.titleLabel.text = .Localized.payment_failed
self.instructionLabel.text = .Localized.please_go_back
self.navigationBar.setStyle(.back)
self.intentPoller.suspendPolling()
self.oneSecondTimer?.invalidate()
self.currentAction.complete(with: .canceled, error: nil)
}
}
// Called after the 5 minute timer expires to wrap up polling
private func finishPolling() {
// Do one last force poll after 5 min
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
guard let self = self else { return }
self.intentPoller.forcePoll()
// If we don't get a terminal status back after 20 seconds from the previous force poll, set error state to suspend polling.
// This could occur if network connections are unreliable
DispatchQueue.main.asyncAfter(deadline: .now() + 20, execute: self.setErrorStateWorkItem)
}
}
}
// MARK: BottomSheetContentViewController
extension PollingViewController: BottomSheetContentViewController {
var allowsDragToDismiss: Bool {
return false
}
func didTapOrSwipeToDismiss() {
// no-op
}
var requiresFullScreen: Bool {
return false
}
}
// MARK: SheetNavigationBarDelegate
extension PollingViewController: SheetNavigationBarDelegate {
func sheetNavigationBarDidClose(_ sheetNavigationBar: SheetNavigationBar) {
dismiss()
}
func sheetNavigationBarDidBack(_ sheetNavigationBar: SheetNavigationBar) {
dismiss()
}
}
// MARK: IntentStatusPollerDelegate
extension PollingViewController: IntentStatusPollerDelegate {
func didUpdate(paymentIntent: STPPaymentIntent) {
guard let currentAction = currentAction as? STPPaymentHandlerPaymentIntentActionParams else { return }
if paymentIntent.status == .succeeded {
setErrorStateWorkItem.cancel() // cancel the error work item incase it was scheduled
currentAction.paymentIntent = paymentIntent // update the local copy of the intent with the latest from the server
currentAction.complete(with: .succeeded, error: nil)
dismiss()
} else if paymentIntent.status != .requiresAction {
// an error occured to take the intent out of requires action
// update polling state to indicate that we have encountered an error
pollingState = .error
}
}
}
| mit | 082c6df28623d87d4246236c031a0b8e | 35.286957 | 158 | 0.634396 | 5.541833 | false | false | false | false |
presence-insights/pi-sample-ios-BeaconConfig | pi-sample-ios-BeaconConfig/BeaconTableViewController.swift | 1 | 16262 | //
//© Copyright 2015 IBM Corp.
//
//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 CoreData
import CoreLocation
import PresenceInsightsSDK
class BeaconTableViewController: UITableViewController, CLLocationManagerDelegate {
var beacons : AnyObject = []
let locationManager = CLLocationManager()
var results : NSArray = []
var piAdapter : PIAdapter!
private var _authorization: String!
private let _httpContentTypeHeader = "Content-Type"
private let _httpAuthorizationHeader = "Authorization"
private let _contentTypeJSON = "application/json"
override func viewDidLoad() {
super.viewDidLoad()
//locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse)
{
locationManager.requestWhenInUseAuthorization()
}
results = retrieveAllDC("Beacon")
if(results.count > 0){
for res in results {
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "\(res.value! as String)")!, identifier: "Estimotes")
locationManager.startRangingBeaconsInRegion(region)
}
}
else{
alert("Error", messageInput: "Please go to settings and add beacon information!")
}
// //B9407F30-F5F8-466E-AFF9-25556B57FE6D
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return beacons.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//myData.removeAll()
let CellID: String = "Cell"
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID)! as UITableViewCell
let bea = beacons[indexPath.row]
let rssi = beacons[indexPath.row].rssi
//let major = bea.major!
let majorString = bea.major!!.stringValue
// let minor = bea.minor!
let minorString = bea.minor!!.stringValue
let proximity = bea.proximity
var proximityString = String()
switch proximity!
{
case .Near:
proximityString = "Near"
case .Immediate:
proximityString = "Immediate"
case .Far:
proximityString = "Far"
case .Unknown:
proximityString = "Unknown"
}
cell.textLabel?.numberOfLines = 2;
cell.textLabel?.text = "Proximity: \(proximityString) RSSI: \(rssi) \n Major: \(majorString) Minor: \(minorString)"
//myData.append(bea)
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Beacons in range"
}
// Override to support conditional editing of the table view.]
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let tenantID = retrieveSpecificDC("BM", key: "TenantID")
let orgID = retrieveSpecificDC("BM", key: "OrgID")
let username = retrieveSpecificDC("BM", key: "Username")
let passwd = retrieveSpecificDC("BM", key: "Password")
let siteID = retrieveSpecificDC("BM", key: "SiteID")
let floorID = retrieveSpecificDC("BM", key: "FloorID")
var inputTextField: UITextField?
if (tenantID.isEmpty || orgID.isEmpty || username.isEmpty || passwd.isEmpty || siteID.isEmpty || floorID.isEmpty){
alert("Error", messageInput: "Please make sure all the Presence Insights Information have been entered.")
}
else{
let uuid : NSUUID = beacons[indexPath.row].proximityUUID
_authorization = "Bearer " + retrieveSpecificDC("BM", key: "token")
let url: String = "https://presenceinsights.ng.bluemix.net:443/pi-config/v1/tenants/\(tenantID)/orgs/\(orgID)/sites/\(siteID)/floors/\(floorID)/beacons"
let Prompt = UIAlertController(title: "Confirm", message: "You have selected this beacon: \n UUID: \(uuid.UUIDString) \n Major: \(beacons[indexPath.row].major!!.stringValue) \n Minor: \(beacons[indexPath.row].minor!!.stringValue) \n Select Ok to continue.", preferredStyle: UIAlertControllerStyle.Alert)
Prompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
Prompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
//Now do whatever you want with inputTextField (remember to unwrap the optional)
//need to store to DB
let body : [String: AnyObject] = [
"name": "\(inputTextField!.text!)",
"proximityUUID": "\(uuid.UUIDString)",
"major": self.beacons[indexPath.row].major!!.stringValue,
"minor": self.beacons[indexPath.row].minor!!.stringValue,
"description": "Added by using Beacon App",
"x": 1,
"y": 1,
"threshold": 10
]
self.sendBeaconRegistration(url, body: body)
}))
Prompt.addTextFieldWithConfigurationHandler({(textField: UITextField) in
textField.placeholder = "Beacon name"
textField.secureTextEntry = false
inputTextField = textField
})
presentViewController(Prompt, animated: true, completion: nil)
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func alert(titleInput : String , messageInput : String){
let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)
{
self.beacons = beacons
refresh()
}
func refresh(){
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
func saveDC( entityName : String, key: String, value: String ) {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
//var request = NSFetchRequest(entityName: entityName)
//create newkey object
let newStore = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context)
//set value (value, key)
//print(key)
//print(value)
newStore.setValue(key , forKey: "key")
newStore.setValue(value, forKey: "value")
do {
try context.save()
} catch _ {
}
}
func retrieveAllDC (entityName : String ) -> NSArray {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: entityName)
request.returnsObjectsAsFaults = false;
let results : NSArray = try! context.executeFetchRequest(request)
return results
}
func retrieveSpecificDC ( entityName : String , key:String) -> String {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: entityName)
request.returnsObjectsAsFaults = false;
request.predicate = NSPredicate(format: "key = %@", key)
let results : NSArray = try! context.executeFetchRequest(request)
if (results.count > 0){
let res = results[0] as! NSManagedObject
return res.valueForKey("value") as! String
}
else{
print("Potential error or no results!")
return ""
}
}
func updateDC ( entityName: String, key: String, value: String){
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: entityName)
request.predicate = NSPredicate(format: "key = %@", key)
if let fetchResults = (try? appDel.managedObjectContext!.executeFetchRequest(request)) as? [NSManagedObject] {
if fetchResults.count != 0{
let managedObject = fetchResults[0]
managedObject.setValue(value, forKey: "value")
do {
try context.save()
} catch _ {
}
}
}
}
/**
Public function to send a payload of all beacons ranged by the device back to PI.
- parameter beaconData: Array containing all ranged beacons and the time they were detected.
*/
func sendBeaconRegistration(url: String, body: NSDictionary) {
let endpoint = url
let PostMessage = body
let Data = dictionaryToJSON(PostMessage as! [String : AnyObject])
//print("Sending Beacon Registration Payload: \(PostMessage)")
let request = buildRequest(endpoint, method: "POST", body: Data)
performRequest(request, callback: {response, error in
guard error == nil else {
print("Could not send beacon payload: \(error)")
return
}
print("Sent Beacon Payload Response: \(response)")
})
}
/**
Private function to convert a dictionary to a JSON object.
- parameter dictionary: The dictionary to convert.
- returns: An NSData object containing the raw JSON of the dictionary.
*/
private func dictionaryToJSON(dictionary: [String: AnyObject]) -> NSData {
do {
let deviceJSON = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions())
return deviceJSON
} catch let error as NSError {
print("Could not convert dictionary object to JSON. \(error)")
} catch {
print("IDK")
}
return NSData()
}
/**
Private function to perform a URL request.
Will always massage response data into a dictionary.
- parameter request: The NSURLRequest to perform.
- parameter callback: Returns an Dictionary of the response on task completion.
*/
private func performRequest(request:NSURLRequest, callback:([String: AnyObject]!, NSError!)->()) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error in
guard error == nil else {
print(error, terminator: "")
callback(nil, error)
return
}
//
// if let data = data {
// do {
// if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves) as? [String: AnyObject] {
//
// if let _ = json["code"] as? String, message = json["message"] as? String {
// let errorDetails = [NSLocalizedFailureReasonErrorKey: message]
// let error = NSError(domain: "PresenceInsightsSDK", code: 1, userInfo: errorDetails)
// callback( nil, error)
// return
// }
// callback(json, nil)
// return
// } else if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves) as? [AnyObject] {
// let returnVal = [ "dataArray" : json]
// callback(returnVal, nil)
// return
// }
// } catch let error {
// let returnVal = [ "rawData": data, "error": error as! NSError]
// callback(returnVal, nil)
// }
//
// } else {
// print("No response data.")
// }
})
task.resume()
}
/**
Private function to build an http/s request
- parameter endpoint: The URL to connect to.
- parameter method: The http method to use for the request.
- parameter body: (Optional) The body of the request.
- returns: A built NSURLRequest to execute.
*/
private func buildRequest(endpoint:String, method:String, body: NSData?) -> NSURLRequest {
if let url = NSURL(string: endpoint) {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method
request.addValue(_authorization, forHTTPHeaderField: _httpAuthorizationHeader)
request.addValue(_contentTypeJSON, forHTTPHeaderField: _httpContentTypeHeader)
if let bodyData = body {
request.HTTPBody = bodyData
}
return request
} else {
print("Invalid URL: \(endpoint)")
}
return NSURLRequest()
}
}
| apache-2.0 | e0b3e87478d34492e9ce5b8009a0fec5 | 36.125571 | 315 | 0.59572 | 5.380874 | false | false | false | false |
darina/omim | iphone/Maps/UI/Welcome/WelcomePageController.swift | 4 | 6784 | @objc(MWMWelcomePageControllerProtocol)
protocol WelcomePageControllerProtocol {
var view: UIView! { get set }
func addChildViewController(_ childController: UIViewController)
func closePageController(_ pageController: WelcomePageController)
}
@objc(MWMWelcomePageController)
final class WelcomePageController: UIPageViewController {
fileprivate var controllers: [UIViewController] = []
private var parentController: WelcomePageControllerProtocol!
private var iPadBackgroundView: SolidTouchView?
private var isAnimatingTransition = true
fileprivate var currentController: UIViewController! {
get {
return viewControllers?.first
}
set {
guard let controller = newValue, let parentView = parentController.view else { return }
let animated = !isAnimatingTransition
parentView.isUserInteractionEnabled = isAnimatingTransition
setViewControllers([controller], direction: .forward, animated: animated) { [weak self] _ in
guard let s = self else { return }
s.isAnimatingTransition = false
parentView.isUserInteractionEnabled = true
}
isAnimatingTransition = animated
}
}
static func shouldShowWelcome() -> Bool {
return WelcomeStorage.shouldShowTerms ||
Alohalytics.isFirstSession() ||
(WelcomeStorage.shouldShowWhatsNew && !DeepLinkHandler.shared.isLaunchedByDeeplink)
}
@objc static func controller(parent: WelcomePageControllerProtocol) -> WelcomePageController? {
guard WelcomePageController.shouldShowWelcome() else {
return nil
}
let vc = WelcomePageController(transitionStyle: .scroll ,
navigationOrientation: .horizontal,
options: convertToOptionalUIPageViewControllerOptionsKeyDictionary([:]))
vc.parentController = parent
var controllersToShow: [UIViewController] = []
if WelcomeStorage.shouldShowTerms {
controllersToShow.append(TermsOfUseBuilder.build(delegate: vc))
controllersToShow.append(contentsOf: FirstLaunchBuilder.build(delegate: vc))
} else {
if Alohalytics.isFirstSession() {
WelcomeStorage.shouldShowTerms = true
controllersToShow.append(TermsOfUseBuilder.build(delegate: vc))
controllersToShow.append(contentsOf: FirstLaunchBuilder.build(delegate: vc))
} else {
NSLog("deeplinking: whats new check")
if (WelcomeStorage.shouldShowWhatsNew && !DeepLinkHandler.shared.isLaunchedByDeeplink) {
controllersToShow.append(contentsOf: WhatsNewBuilder.build(delegate: vc))
}
}
}
WelcomeStorage.shouldShowWhatsNew = false
vc.controllers = controllersToShow
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
view.styleName = "Background"
iPadSpecific {
let parentView = parentController.view!
iPadBackgroundView = SolidTouchView(frame: parentView.bounds)
iPadBackgroundView!.styleName = "FadeBackground"
iPadBackgroundView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
parentView.addSubview(iPadBackgroundView!)
view.layer.cornerRadius = 5
view.clipsToBounds = true
}
currentController = controllers.first
}
func nextPage() {
currentController = pageViewController(self, viewControllerAfter: currentController)
}
func close() {
iPadBackgroundView?.removeFromSuperview()
view.removeFromSuperview()
removeFromParent()
parentController.closePageController(self)
FrameworkHelper.processFirstLaunch(LocationManager.lastLocation() != nil)
}
@objc func show() {
parentController.addChildViewController(self)
parentController.view.addSubview(view)
updateFrame()
}
private func updateFrame() {
let parentView = parentController.view!
let size = WelcomeViewController.presentationSize
view.frame = alternative(iPhone: CGRect(origin: CGPoint(), size: parentView.size),
iPad: CGRect(x: parentView.center.x - size.width/2,
y: parentView.center.y - size.height/2,
width: size.width,
height: size.height))
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [weak self] _ in self?.updateFrame() }, completion: nil)
}
}
extension WelcomePageController: UIPageViewControllerDataSource {
func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard viewController != controllers.first else { return nil }
let index = controllers.index(before: controllers.firstIndex(of: viewController)!)
return controllers[index]
}
func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard viewController != controllers.last else { return nil }
let index = controllers.index(after: controllers.firstIndex(of: viewController)!)
return controllers[index]
}
func presentationCount(for _: UIPageViewController) -> Int {
return controllers.count
}
func presentationIndex(for _: UIPageViewController) -> Int {
guard let vc = currentController else { return 0 }
return controllers.firstIndex(of: vc)!
}
}
extension WelcomePageController: WelcomeViewDelegate {
func welcomeDidPressNext(_ viewContoller: UIViewController) {
guard let index = controllers.firstIndex(of: viewContoller) else {
close()
return
}
if index + 1 < controllers.count {
nextPage()
} else {
if DeepLinkHandler.shared.needExtraWelcomeScreen {
let vc = DeepLinkInfoBuilder.build(delegate: self)
controllers.append(vc)
nextPage()
} else {
close()
DeepLinkHandler.shared.handleDeeplink()
}
}
}
func welcomeDidPressClose(_ viewContoller: UIViewController) {
close()
}
}
extension WelcomePageController: DeeplinkInfoViewControllerDelegate {
func deeplinkInfoViewControllerDidFinish(_ viewController: UIViewController, deeplink: URL?) {
close()
guard let dl = deeplink else { return }
DeepLinkHandler.shared.handleDeeplink(dl)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalUIPageViewControllerOptionsKeyDictionary(_ input: [String: Any]?) -> [UIPageViewController.OptionsKey: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIPageViewController.OptionsKey(rawValue: key), value)})
}
| apache-2.0 | 37bc028d2582cd9d2476a461f83e2b84 | 36.274725 | 144 | 0.713149 | 5.362846 | false | false | false | false |
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/ReusableComponentsSpec.swift | 7 | 1029 | import Quick
import Nimble
import Result
import ReactiveSwift
import ReactiveCocoa
import AppKit
class ReusableComponentsSpec: QuickSpec {
override func spec() {
describe("NSTableCellView") {
it("should send a `value` event when `prepareForReuse` is triggered") {
let cell = NSTableCellView()
var isTriggered = false
cell.reactive.prepareForReuse.observeValues {
isTriggered = true
}
expect(isTriggered) == false
cell.prepareForReuse()
expect(isTriggered) == true
}
}
if #available(macOS 10.11, *) {
describe("NSCollectionViewItem") {
it("should send a `value` event when `prepareForReuse` is triggered") {
let item = TestViewItem()
var isTriggered = false
item.reactive.prepareForReuse.observeValues {
isTriggered = true
}
expect(isTriggered) == false
item.prepareForReuse()
expect(isTriggered) == true
}
}
}
}
}
private class TestViewItem: NSCollectionViewItem {
override func loadView() {
view = NSView()
}
}
| gpl-3.0 | 206c6dd0606372e7ee03bd4a68baa5c1 | 19.58 | 75 | 0.681244 | 4.035294 | false | false | false | false |
luizlopezm/ios-Luis-Trucking | Pods/SwiftForms/SwiftForms/cells/FormTextFieldCell.swift | 1 | 5895 | //
// FormTextFieldCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormTextFieldCell: FormBaseCell {
// MARK: Cell views
public let titleLabel = UILabel()
public let textField = UITextField()
// MARK: Properties
private var customConstraints: [AnyObject]!
// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
titleLabel.translatesAutoresizingMaskIntoConstraints = false
textField.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
contentView.addSubview(titleLabel)
contentView.addSubview(textField)
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
titleLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
textField.addTarget(self, action: #selector(FormTextFieldCell.editingChanged(_:)), forControlEvents: .EditingChanged)
}
public override func update() {
super.update()
if let showsInputToolbar = rowDescriptor.configuration[FormRowDescriptor.Configuration.ShowsInputToolbar] as? Bool {
if showsInputToolbar && textField.inputAccessoryView == nil {
textField.inputAccessoryView = inputAccesoryView()
}
}
titleLabel.text = rowDescriptor.title
textField.text = rowDescriptor.value as? String
textField.placeholder = rowDescriptor.configuration[FormRowDescriptor.Configuration.Placeholder] as? String
textField.secureTextEntry = false
textField.clearButtonMode = .WhileEditing
switch rowDescriptor.rowType {
case .Text:
textField.autocorrectionType = .Default
textField.autocapitalizationType = .Sentences
textField.keyboardType = .Default
case .Number:
textField.keyboardType = .NumberPad
case .NumbersAndPunctuation:
textField.keyboardType = .NumbersAndPunctuation
case .Decimal:
textField.keyboardType = .DecimalPad
case .Name:
textField.autocorrectionType = .No
textField.autocapitalizationType = .Words
textField.keyboardType = .Default
case .Phone:
textField.keyboardType = .PhonePad
case .NamePhone:
textField.autocorrectionType = .No
textField.autocapitalizationType = .Words
textField.keyboardType = .NamePhonePad
case .URL:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .URL
case .Twitter:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .Twitter
case .Email:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .EmailAddress
case .ASCIICapable:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .ASCIICapable
case .Password:
textField.secureTextEntry = true
textField.clearsOnBeginEditing = false
default:
break
}
}
public override func constraintsViews() -> [String : UIView] {
var views = ["titleLabel" : titleLabel, "textField" : textField]
if self.imageView!.image != nil {
views["imageView"] = imageView
}
return views
}
public override func defaultVisualConstraints() -> [String] {
if self.imageView!.image != nil {
if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 {
return ["H:[imageView]-[titleLabel]-[textField]-16-|"]
}
else {
return ["H:[imageView]-[textField]-16-|"]
}
}
else {
if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 {
return ["H:|-16-[titleLabel]-[textField]-16-|"]
}
else {
return ["H:|-16-[textField]-16-|"]
}
}
}
public override func firstResponderElement() -> UIResponder? {
return textField
}
public override class func formRowCanBecomeFirstResponder() -> Bool {
return true
}
// MARK: Actions
internal func editingChanged(sender: UITextField) {
let trimmedText = sender.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
rowDescriptor.value = trimmedText.characters.count > 0 ? trimmedText : nil
}
}
| mit | 7d10cd99d075b75d681187d9c258f924 | 37.503268 | 185 | 0.633339 | 5.686293 | false | false | false | false |
CD1212/Doughnut | Pods/GRDB.swift/GRDB/Record/Record.swift | 1 | 13603 | // MARK: - Record
/// Record is a class that wraps a table row, or the result of any query. It is
/// designed to be subclassed.
open class Record : RowConvertible, TableMapping, Persistable {
// MARK: - Initializers
/// Creates a Record.
public init() {
}
/// Creates a Record from a row.
required public init(row: Row) {
if row.isFetched {
// Take care of the hasPersistentChangedValues flag.
//
// Row may be a reused row which will turn invalid as soon as the
// SQLite statement is iterated. We need to store an
// immutable copy.
referenceRow = row.copy()
}
}
// MARK: - Core methods
/// The name of a database table.
///
/// This table name is required by the insert, update, save, delete,
/// and exists methods.
///
/// class Player : Record {
/// override class var databaseTableName: String {
/// return "players"
/// }
/// }
///
/// The implementation of the base class Record raises a fatal error.
///
/// - returns: The name of a database table.
open class var databaseTableName: String {
// Programmer error
fatalError("subclass must override")
}
/// The policy that handles SQLite conflicts when records are inserted
/// or updated.
///
/// This property is optional: its default value uses the ABORT policy
/// for both insertions and updates, and has GRDB generate regular
/// INSERT and UPDATE queries.
///
/// If insertions are resolved with .ignore policy, the
/// `didInsert(with:for:)` method is not called upon successful insertion,
/// even if a row was actually inserted without any conflict.
///
/// See https://www.sqlite.org/lang_conflict.html
open class var persistenceConflictPolicy: PersistenceConflictPolicy {
return PersistenceConflictPolicy(insert: .abort, update: .abort)
}
/// The default request selection.
///
/// Unless this method is overriden, requests select all columns:
///
/// // SELECT * FROM players
/// try Player.fetchAll(db)
///
/// You can override this property and provide an explicit list
/// of columns:
///
/// class RestrictedPlayer : Record {
/// override static var databaseSelection: [SQLSelectable] {
/// return [Column("id"), Column("name")]
/// }
/// }
///
/// // SELECT id, name FROM players
/// try RestrictedPlayer.fetchAll(db)
///
/// You can also add extra columns such as the `rowid` column:
///
/// class ExtendedPlayer : Player {
/// override static var databaseSelection: [SQLSelectable] {
/// return [AllColumns(), Column.rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM players
/// try ExtendedPlayer.fetchAll(db)
open class var databaseSelection: [SQLSelectable] {
return [AllColumns()]
}
/// Defines the values persisted in the database.
///
/// Store in the *container* argument all values that should be stored in
/// the columns of the database table (see Record.databaseTableName()).
///
/// Primary key columns, if any, must be included.
///
/// class Player : Record {
/// var id: Int64?
/// var name: String?
///
/// override func encode(to container: inout PersistenceContainer) {
/// container["id"] = id
/// container["name"] = name
/// }
/// }
///
/// The implementation of the base class Record does not store any value in
/// the container.
open func encode(to container: inout PersistenceContainer) {
}
/// Notifies the record that it was succesfully inserted.
///
/// Do not call this method directly: it is called for you, in a protected
/// dispatch queue, with the inserted RowID and the eventual
/// INTEGER PRIMARY KEY column name.
///
/// The implementation of the base Record class does nothing.
///
/// class Player : Record {
/// var id: Int64?
/// var name: String?
///
/// func didInsert(with rowID: Int64, for column: String?) {
/// id = rowID
/// }
/// }
///
/// - parameters:
/// - rowID: The inserted rowID.
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
open func didInsert(with rowID: Int64, for column: String?) {
}
// MARK: - Copy
/// Returns a copy of `self`, initialized from all values encoded in the
/// `encode(to:)` method.
///
/// The eventual primary key is copied, as well as the
/// `hasPersistentChangedValues` flag.
///
/// - returns: A copy of self.
open func copy() -> Self {
let row: Row
#if swift(>=3.1)
row = Row(self)
#else
// workaround weird Swift 3.0 glitch
row = Row(self as! MutablePersistable)
#endif
let copy = type(of: self).init(row: row)
copy.referenceRow = referenceRow
return copy
}
// MARK: - Changes Tracking
/// A boolean that indicates whether the record has changes that have not
/// been saved.
///
/// This flag is purely informative, and does not prevent insert(),
/// update(), and save() from performing their database queries.
///
/// A record is *edited* if has been changed since last database
/// synchronization (fetch, update, insert). Comparison
/// is performed between *values* (values stored in the `encode(to:)`
/// method, and values loaded from the database). Property setters do not
/// trigger this flag.
///
/// You can rely on the Record base class to compute this flag for you, or
/// you may set it to true or false when you know better. Setting it to
/// false does not prevent it from turning true on subsequent modifications
/// of the record.
public var hasPersistentChangedValues: Bool {
get { return makePersistentChangedValuesIterator().next() != nil }
set { referenceRow = newValue ? nil : Row(self) }
}
/// A dictionary of changes that have not been saved.
///
/// Its keys are column names, and values the old values that have been
/// changed since last fetching or saving of the record.
///
/// Unless the record has actually been fetched or saved, the old values
/// are nil.
///
/// See `hasPersistentChangedValues` for more information.
public var persistentChangedValues: [String: DatabaseValue?] {
var persistentChangedValues: [String: DatabaseValue?] = [:]
for (key, value) in makePersistentChangedValuesIterator() {
persistentChangedValues[key] = value
}
return persistentChangedValues
}
// A change iterator that is used by both hasPersistentChangedValues and
// persistentChangedValues properties.
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
let oldRow = referenceRow
var newValueIterator = PersistenceContainer(self).makeIterator()
return AnyIterator {
// Loop until we find a change, or exhaust columns:
while let (column, newValue) = newValueIterator.next() {
let new = newValue?.databaseValue ?? .null
guard let oldRow = oldRow, let old: DatabaseValue = oldRow[column] else {
return (column: column, old: nil)
}
if new != old {
return (column: column, old: old)
}
}
return nil
}
}
/// Reference row for the *hasPersistentChangedValues* property.
var referenceRow: Row?
// MARK: - CRUD
/// Executes an INSERT statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have inserted a row in the database if it
/// returns without error.
///
/// Records whose primary key is declared as "INTEGER PRIMARY KEY" have
/// their id automatically set after successful insertion, if it was nil
/// before the insertion.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs.
open func insert(_ db: Database) throws {
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
let dao = try DAO(db, self)
var persistenceContainer = dao.persistenceContainer
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
if !conflictResolutionForInsert.invalidatesLastInsertedRowID {
let rowID = db.lastInsertedRowID
let rowIDColumn = dao.primaryKey.rowIDColumn
didInsert(with: rowID, for: rowIDColumn)
// Update persistenceContainer with inserted id, so that we can
// set hasPersistentChangedValues to false:
if let rowIDColumn = rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowID
}
}
// Set hasPersistentChangedValues to false
referenceRow = Row(persistenceContainer)
}
/// Executes an UPDATE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have updated a row in the database if it
/// returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
open func update(_ db: Database, columns: Set<String>) throws {
// The simplest code would be:
//
// try performUpdate(db, columns: columns)
// hasPersistentChangedValues = false
//
// But this would trigger two calls to `encode(to:)`.
let dao = try DAO(db, self)
guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else {
// Nil primary key
throw PersistenceError.recordNotFound(self)
}
try statement.execute()
if db.changesCount == 0 {
throw PersistenceError.recordNotFound(self)
}
// Set hasPersistentChangedValues to false
referenceRow = Row(dao.persistenceContainer)
}
/// If the record has been changed, executes an UPDATE statement so that
/// those changes and only those changes are saved in the database.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have saved the eventual changes in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - parameter columns: The columns to update.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
/// PersistenceError.recordNotFound is thrown if the primary key does not
/// match any row in the database and record could not be updated.
final public func updateChanges(_ db: Database) throws {
let changedColumns = Set(persistentChangedValues.keys)
guard !changedColumns.isEmpty else {
return
}
try update(db, columns: changedColumns)
}
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
/// the database.
///
/// If the record has a non-nil primary key and a matching row in the
/// database, this method performs an update.
///
/// Otherwise, performs an insert.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to false.
///
/// This method is guaranteed to have inserted or updated a row in the
/// database if it returns without error.
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError whenever an SQLite error occurs, or errors
/// thrown by update().
final public func save(_ db: Database) throws {
try performSave(db)
}
/// Executes a DELETE statement.
///
/// On success, this method sets the *hasPersistentChangedValues* flag
/// to true.
///
/// - parameter db: A database connection.
/// - returns: Whether a database row was deleted.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
open func delete(_ db: Database) throws -> Bool {
defer {
// Future calls to update() will throw NotFound. Make the user
// a favor and make sure this error is thrown even if she checks the
// hasPersistentChangedValues flag:
hasPersistentChangedValues = true
}
return try performDelete(db)
}
}
| gpl-3.0 | c22c1f2a71159274975f8bd89e87e4b3 | 36.268493 | 160 | 0.604352 | 4.806714 | false | false | false | false |
nhatminh12369/LNSlideUpTransition | LNSlideUpTransition/LNSlideUpTransition/LNSlideUpDismissAnimatedTransitioning.swift | 1 | 3514 | /**
Copyright (c) 2016 Minh Nguyen <[email protected]>
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 LNSlideUpDismissAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
weak var transitionManager:LNSlideUpTransitionManager!
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
if transitionManager.bounceAnimation {
return transitionManager.DEFAULT_DURATION
} else if transitionManager.springAnimation {
return transitionManager.duration*0.6
} else {
return transitionManager.duration
}
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
let containerView = transitionContext.containerView(),
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
let finalFrameFromVC = CGRectMake(0, fromVC.view.frame.size.height, fromVC.view.frame.size.width, fromVC.view.frame.size.height)
toVC.view.transform = CGAffineTransformMakeScale(0.9, 0.9)
let snapshot = fromVC.view.snapshotViewAfterScreenUpdates(false)
let blackBG = UIView(frame: fromVC.view.frame)
let mask = UIView(frame: fromVC.view.frame)
blackBG.backgroundColor = UIColor.blackColor()
mask.backgroundColor = UIColor.blackColor()
containerView.addSubview(blackBG)
containerView.addSubview(toVC.view)
containerView.addSubview(mask)
containerView.addSubview(snapshot)
let duration = transitionDuration(transitionContext)
UIView.animateKeyframesWithDuration(
duration,
delay: 0,
options: .CalculationModePaced,
animations: {
snapshot.frame = finalFrameFromVC
toVC.view.transform = CGAffineTransformMakeScale(1.0, 1.0)
mask.alpha = 0.0
},
completion: { _ in
fromVC.view.hidden = false
snapshot.removeFromSuperview()
blackBG.removeFromSuperview()
mask.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
}
}
| mit | 9fe033eb6decd2208daf11ef39edf416 | 43.481013 | 136 | 0.698634 | 5.640449 | false | false | false | false |
andrew749/Sportify | Sportify/SportsOptionPicker.swift | 1 | 2368 | //
// SportsOptionPicker.swift
// Sportify
//
// Created by Andrew Codispoti on 2015-06-08.
// Copyright (c) 2015 Andrew Codispoti. All rights reserved.
//
import Foundation
import UIKit
class SportsOptionPicker:UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
@IBOutlet weak var nameLabel: UITextField!
var dataDelegate:DataSendingDelegate?
var imagePicker:UIImagePickerController?
var logo:UIImage?
var name:String?
@IBAction func createButtonClick(sender: AnyObject) {
if let teamName = nameLabel.text{
//TODO need to add logo selection method
dataDelegate?.sendData(teamName, teamLogo: logo)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
@IBAction func cancelClick(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.nameLabel.delegate=self
if let tempName = self.name{
self.nameLabel.text = tempName
}
if let tempImage = self.logo{
self.mainImageView.image = tempImage
self.addButton.setTitle("+", forState: UIControlState.Normal)
}
}
@IBOutlet weak var addButton: UIButton!
@IBAction func addButtonClick(sender: AnyObject) {
showPicker()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
nameLabel.endEditing(true)
return true;
}
func showPicker(){
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
imagePicker?.allowsEditing = true
imagePicker?.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker!, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imagePicker?.dismissViewControllerAnimated(true, completion: nil)
logo = image
mainImageView.image = logo
if (image != nil){
addButton.setTitle("Edit", forState: UIControlState.Normal)
}
}
@IBOutlet weak var mainImageView: UIImageView!
} | gpl-3.0 | d8efae0bcfebbd08b03e70cf5a98fbc8 | 30.586667 | 142 | 0.664696 | 5.431193 | false | false | false | false |
congncif/PagingDataController | PagingDataController/Core/PageDataSource.swift | 1 | 3773 | //
// PageDataSource.swift
// PagingDataController
//
// Created by Nguyen Chi Cong on 5/16/16.
// Copyright © 2016 Nguyen Chi Cong. All rights reserved.
//
import Foundation
public protocol PageDataSourceDelegate: class {
func pageDataSourceDidChange(hasNextPage: Bool, nextPageIndicatorShouldChange shouldChange: Bool)
}
open class PageData<T> {
open var pageIndex: Int
open var pageData: [T]
public init(index pageIndex: Int, data pageData: [T]) {
self.pageIndex = pageIndex
self.pageData = pageData
}
}
open class PageDataSource<T> {
private let delegateProxy = PageDataSourceDelegateProxy()
public var hasMore: Bool = false
public var pageSize: Int
public var allObjects: [T] {
return getAllObjects()
}
public var data: [PageData<T>] = []
public var currentPage: Int {
let page = data.last
guard page != nil else { return -1 }
return page!.pageIndex
}
// private(set) var pages: [T]
public init(pageSize: Int) {
self.pageSize = pageSize
}
public init() {
pageSize = 36
}
public var delegate: PageDataSourceDelegate? {
set {
if let value = newValue {
delegateProxy.removeAllObservers()
delegateProxy.addObserver(value)
} else {
delegateProxy.removeAllObservers()
}
}
get {
return delegateProxy
}
}
public func addDelegate(_ delegate: PageDataSourceDelegate?) {
delegateProxy.addObserver(delegate)
}
public func removeDelegate(_ delegate: PageDataSourceDelegate?) {
delegateProxy.removeObserver(delegate)
}
open func extendDataSource(_ page: PageData<T>) {
if !pageIsExists(page.pageIndex) {
data.append(page)
pageDataSourceDidExtend(pageData: page.pageData, at: page.pageIndex)
var shouldChange = false
if page.pageData.count < pageSize {
let newFlag = false
if hasMore != newFlag {
hasMore = newFlag
shouldChange = true
}
} else {
let newFlag = true
if hasMore != newFlag {
hasMore = newFlag
shouldChange = true
}
}
notifyToDelegate(nextPageIndicatorShouldChange: shouldChange)
} else {
print("Page \(page.pageIndex) is exists")
}
}
open func reset() {
data.removeAll()
pageDataSourceDidReset()
// let changed = (hasMore == false) // at last page
hasMore = false
notifyToDelegate(nextPageIndicatorShouldChange: true)
}
open func pageIsExists(_ index: Int) -> Bool {
let pages = data.filter { (pageData) -> Bool in
pageData.pageIndex == index
}
return !pages.isEmpty
}
open func pageDataSourceDidExtend(pageData: [T], at page: Int) {}
open func pageDataSourceDidReset() {}
}
extension PageDataSource {
private func notifyToDelegate(nextPageIndicatorShouldChange: Bool) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.pageDataSourceDidChange(hasNextPage: self.hasMore, nextPageIndicatorShouldChange: nextPageIndicatorShouldChange)
}
}
private func getAllObjects() -> [T] {
var source: [T] = [T]()
for page in data {
source += page.pageData
}
return source
}
}
| mit | febd25e54bb518cf1203cc2aa6e7751e | 26.333333 | 139 | 0.566543 | 4.963158 | false | false | false | false |
DragonCherry/AssetsPickerViewController | Common/SwiftAlert.swift | 2 | 6732 | //
// SwiftAlert.swift
// Pods
//
// Created by DragonCherry on 1/10/17.
//
//
import UIKit
@available(iOS 8.0, *)
@objcMembers public class SwiftAlert: NSObject {
fileprivate weak var parent: UIViewController?
fileprivate var alertController: UIAlertController?
fileprivate var forceDismiss: Bool = false
public var isShowing: Bool = false
fileprivate var dismissHandler: ((Int) -> Void)?
fileprivate var cancelHandler: (() -> Void)?
fileprivate var destructHandler: (() -> Void)?
fileprivate var promptHandler: ((Int, String?) -> Void)?
fileprivate var promptTextField: UITextField?
public required override init() {
super.init()
}
public func show(
_ parent: UIViewController,
style: UIAlertController.Style = .alert,
title: String? = nil,
message: String?,
dismissTitle: String) {
self.show(
parent,
style: style,
title: title,
message: message,
cancelTitle: nil,
cancel: nil,
otherTitles: [dismissTitle],
dismiss: nil)
}
public func show(
_ parent: UIViewController,
style: UIAlertController.Style = .alert,
title: String? = nil,
message: String?,
dismissTitle: String,
dismiss: (() -> Void)?) {
self.show(
parent,
style: style,
title: title,
message: message,
cancelTitle: dismissTitle,
cancel: { dismiss?() },
otherTitles: nil,
dismiss: nil)
}
public func show(
_ parent: UIViewController,
style: UIAlertController.Style = .alert,
title: String? = nil,
message: String? = nil,
cancelTitle: String? = nil,
cancel: (() -> Void)? = nil,
otherTitles: [String]? = nil,
dismiss: ((Int) -> Void)? = nil,
destructTitle: String? = nil,
destruct: (() -> Void)? = nil) {
close(false)
self.parent = parent
self.dismissHandler = dismiss
self.cancelHandler = cancel
self.destructHandler = destruct
self.alertController = UIAlertController(title: title, message: message, preferredStyle: style)
guard let alertController = self.alertController else {
return
}
if let otherTitles = otherTitles {
for (index, otherTitle) in otherTitles.enumerated() {
let dismissAction: UIAlertAction = UIAlertAction(title: otherTitle, style: .default, handler: { action in
self.dismissHandler?(index)
self.clear()
})
alertController.addAction(dismissAction)
}
}
if let cancelTitle = cancelTitle {
let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: { action in
self.cancelHandler?()
self.clear()
})
alertController.addAction(cancelAction)
}
if let destructTitle = destructTitle {
let destructAction: UIAlertAction = UIAlertAction(title: destructTitle, style: .destructive, handler: { action in
self.destructHandler?()
self.clear()
})
alertController.addAction(destructAction)
}
if let parent = self.parent {
parent.present(alertController, animated: true, completion: nil)
} else {
print("Cannot find parent while presenting alert.")
}
self.isShowing = true
}
public func prompt(
_ parent: UIViewController,
title: String? = nil,
message: String?,
placeholder: String? = nil,
defaultText: String? = nil,
isNumberOnly: Bool = false,
isSecure: Bool = true,
cancelTitle: String? = nil,
cancel: (() -> Void)? = nil,
otherTitles: [String]? = nil,
prompt: ((Int, String?) -> Void)? = nil) {
close(false)
self.parent = parent
self.promptHandler = prompt
self.cancelHandler = cancel
self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
guard let alertController = self.alertController else {
return
}
alertController.addTextField(configurationHandler: { textField in
if isNumberOnly {
textField.keyboardType = .numberPad
}
textField.text = defaultText
textField.isSecureTextEntry = isSecure
if let placeholder = placeholder {
textField.placeholder = placeholder
}
self.promptTextField = textField
})
if let otherTitles = otherTitles {
for (index, otherTitle) in otherTitles.enumerated() {
let dismissAction: UIAlertAction = UIAlertAction(title: otherTitle, style: .default, handler: { action in
self.promptTextField?.resignFirstResponder()
self.promptHandler?(index, self.promptTextField!.text)
self.clear()
})
alertController.addAction(dismissAction)
}
}
if let cancelTitle = cancelTitle {
let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: { action in
self.promptTextField?.resignFirstResponder()
self.cancelHandler?()
self.clear()
})
alertController.addAction(cancelAction)
}
if let parent = self.parent {
parent.present(alertController, animated: true, completion: nil)
} else {
print("Cannot find parent while presenting alert.")
}
isShowing = true
}
fileprivate func autoDismiss() {
close()
}
public func close(_ animated: Bool = true, completion: (() -> Void)? = nil) {
if isShowing {
alertController?.dismiss(animated: animated, completion: {
completion?()
})
}
clear()
isShowing = false
}
private func clear() {
self.parent = nil
self.alertController = nil
self.promptTextField = nil
self.cancelHandler = nil
self.dismissHandler = nil
self.destructHandler = nil
}
}
| mit | 890f6804d58c59952643c3b9346c2b99 | 30.311628 | 125 | 0.545455 | 5.407229 | false | false | false | false |
daniel-beard/SwiftLint | Source/SwiftLintFramework/Rules/NestingRule.swift | 1 | 3162 | //
// NestingRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct NestingRule: ASTRule, ConfigProviderRule {
public var config = SeverityConfig(.Warning)
public init() {}
public static let description = RuleDescription(
identifier: "nesting",
name: "Nesting",
description: "Types should be nested at most 1 level deep, " +
"and statements should be nested at most 5 levels deep.",
nonTriggeringExamples: ["class", "struct", "enum"].flatMap { kind in
["\(kind) Class0 { \(kind) Class1 {} }\n",
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\n}\n}\n}\n}\n}\n}\n"]
} + ["enum Enum0 { enum Enum1 { case Case } }"],
triggeringExamples: ["class", "struct", "enum"].map { kind in
"\(kind) A { \(kind) B { ↓\(kind) C {} } }\n"
} + [
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\n↓func func6() {\n}\n}\n}\n}\n}\n}\n}\n"
]
)
public func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return validateFile(file, kind: kind, dictionary: dictionary, level: 0)
}
func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable],
level: Int) -> [StyleViolation] {
var violations = [StyleViolation]()
let typeKinds: [SwiftDeclarationKind] = [.Class, .Struct, .Typealias, .Enum]
if let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) {
if level > 1 && typeKinds.contains(kind) {
violations.append(StyleViolation(ruleDescription: self.dynamicType.description,
severity: config.severity,
location: Location(file: file, byteOffset: offset),
reason: "Types should be nested at most 1 level deep"))
} else if level > 5 {
violations.append(StyleViolation(ruleDescription: self.dynamicType.description,
severity: config.severity,
location: Location(file: file, byteOffset: offset),
reason: "Statements should be nested at most 5 levels deep"))
}
}
let substructure = dictionary["key.substructure"] as? [SourceKitRepresentable] ?? []
violations.appendContentsOf(substructure.flatMap { subItem in
if let subDict = subItem as? [String: SourceKitRepresentable],
kind = (subDict["key.kind"] as? String).flatMap(SwiftDeclarationKind.init) {
return (kind, subDict)
}
return nil
}.flatMap { kind, subDict in
return self.validateFile(file, kind: kind, dictionary: subDict, level: level + 1)
})
return violations
}
}
| mit | 92010d13f3a99c0a3773761db09c98ed | 44.114286 | 99 | 0.572198 | 4.454161 | false | true | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Common/Extensions/UIColor+Helpers.swift | 1 | 766 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
extension UIColor {
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return adjust(by: abs(percentage))
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return adjust(by: -1 * abs(percentage))
}
func adjust(by percentage: CGFloat=30.0) -> UIColor? {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
return UIColor(red: min(r + percentage/100, 1.0),
green: min(g + percentage/100, 1.0),
blue: min(b + percentage/100, 1.0),
alpha: a)
} else {
return nil
}
}
}
| gpl-3.0 | aff9a174a3605897a5c423c1663f4076 | 26.321429 | 70 | 0.560784 | 3.493151 | false | false | false | false |
linbin00303/Dotadog | DotaDog/DotaDog/Classes/News/New/Controller/DDogNewViewController.swift | 1 | 3831 | //
// DDogNewViewController.swift
// DotaDog
//
// Created by 林彬 on 16/5/31.
// Copyright © 2016年 linbin. All rights reserved.
//
import UIKit
import MJRefresh
import SVProgressHUD
class DDogNewViewController: UITableViewController {
private let ID = "new"
let header = MJRefreshNormalHeader()
let footer = MJRefreshAutoNormalFooter()
var page = 1
private lazy var newsModelArr : NSMutableArray = {
let newsModelArr = NSMutableArray()
return newsModelArr
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
DDogNewsHttp.getNewData(1) { [weak self](resultMs) in
if resultMs == ["error"] {
// SVProgressHUD.setMinimumDismissTimeInterval(1)
// SVProgressHUD.showErrorWithStatus("Json数据出错,请刷新")
return
}
self?.newsModelArr = resultMs
self?.tableView.reloadData()
}
header.setRefreshingTarget(self, refreshingAction:#selector(DDogNewViewController.getNetData))
tableView.mj_header = header
footer.setRefreshingTarget(self, refreshingAction: #selector(DDogNewViewController.getMoreData))
footer.automaticallyHidden = true
tableView.mj_footer = footer
tableView.registerNib(UINib(nibName: "DDogNewsCell", bundle: nil), forCellReuseIdentifier: ID)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
DDogNewsHttp.getNewData(1) { [weak self](resultMs) in
if resultMs == ["error"] {
SVProgressHUD.setMinimumDismissTimeInterval(1)
SVProgressHUD.showErrorWithStatus("Json数据出错,请刷新")
return
}
self?.newsModelArr = resultMs
self?.tableView.reloadData()
}
}
func getNetData() {
DDogNewsHttp.getNewData(1) { [weak self](resultMs) in
self?.newsModelArr = resultMs
self?.tableView.reloadData()
self?.tableView.mj_header.endRefreshing()
}
}
func getMoreData() {
page = page + 1
DDogNewsHttp.getNewData(page) { [weak self](resultMs) in
if resultMs == [] {
self?.tableView.mj_footer.state = .NoMoreData
self?.tableView.mj_footer.endRefreshing()
return
}
for i in 0..<resultMs.count {
self?.newsModelArr.addObject(resultMs[i])
}
self?.tableView.reloadData()
self?.tableView.mj_footer.endRefreshing()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return newsModelArr.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! DDogNewsCell
cell.newsModel = newsModelArr[indexPath.row] as? DDogNewsModel
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let contentVC = DDogDetailsViewController()
contentVC.model = newsModelArr[indexPath.row] as? DDogNewsModel
self.navigationController?.pushViewController(contentVC, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
}
| mit | a25c973ec96d414e36115483da0d1951 | 30.371901 | 118 | 0.620653 | 5.384397 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCActionHandler.swift | 2 | 1292 | //
// NCActionHandler.swift
// Neocom
//
// Created by Artem Shimanski on 20.07.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
extension UIControlEvents: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
static func == (lhs: UIControlEvents, rhs: UIControlEvents) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
class NCActionHandler<Control: UIControl> {
private let handler: NCOpaqueHandler
private let control: Control
private let controlEvents: UIControlEvents
class NCOpaqueHandler: NSObject {
let handler: (Control) -> Void
init(_ handler: @escaping(Control) -> Void) {
self.handler = handler
}
@objc func handle(_ sender: UIControl) {
guard let control = sender as? Control else {return}
handler(control)
}
}
init(_ control: Control, for controlEvents: UIControlEvents, handler: @escaping(Control) -> Void) {
self.handler = NCOpaqueHandler(handler)
self.control = control
self.controlEvents = controlEvents
control.addTarget(self.handler, action: #selector(NCOpaqueHandler.handle(_:)), for: controlEvents)
}
deinit {
control.removeTarget(self.handler, action: #selector(NCOpaqueHandler.handle(_:)), for: controlEvents)
}
}
| lgpl-2.1 | d8bc159a7627400abdd7308cba10126e | 23.826923 | 103 | 0.707978 | 3.830861 | false | false | false | false |
3lvis/TextField | Native/HeaderCell.swift | 2 | 1030 | import UIKit
class HeaderCell: UITableViewCell {
static let Identifier = "HeaderCell"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor(red: 239 / 255, green: 239 / 255, blue: 244 / 255, alpha: 1)
selectionStyle = .none
guard let textLabel = self.textLabel else { return }
textLabel.textColor = UIColor(red: 109 / 255, green: 109 / 255, blue: 114 / 255, alpha: 1)
textLabel.font = UIFont.systemFont(ofSize: 14)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let textLabel = self.textLabel else { return }
var frame = textLabel.frame
frame.size.height = 30
frame.origin.x = 20
frame.origin.y = self.frame.height - frame.height
textLabel.frame = frame
}
}
| mit | 599850d984b43ffc8aa68b915720c58f | 32.225806 | 106 | 0.645631 | 4.458874 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/EclipseCenter/EclipseTimeGenerator.swift | 1 | 22746 | //
// EclipseTimeGenerator.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 6/23/17.
//
// Copyright © 2017 Arlindo Goncalves.
// 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/].
//
// For Contact email: [email protected]
//
// Translated into Swift from:
// Solar Eclipse Calculator for Google Maps (Xavier Jubier: http://xjubier.free.fr/)
// Some of the code is inspired by Chris O'Byrne (http://www.chris.obyrne.com/)
import UIKit
enum EclipseType {
case partial, full, none
}
struct EclipseEvent: Equatable {
var name : String = ""
var date : String = ""
var time : String = ""
var alt : String = ""
var azi : String = ""
init(name : String, date : String, time : String, alt : String, azi : String) {
self.name = name
self.date = date
self.time = time
self.alt = alt
self.azi = azi
}
func eventDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss.S"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
return dateFormatter.date(from: "\(date) \(time)")
}
static func == (lhs: EclipseEvent, rhs: EclipseEvent) -> Bool {
return lhs.name == rhs.name
}
}
class EclipseTimeGenerator {
var longitude: Double!
var latitude: Double!
var isEclipse = true
var isPartial = false
var R2D = 180.0 / Double.pi
var D2R = Double.pi / 180
var obsvconst = [Double](repeating: 0.0, count: 10)
var elements = [
2460409.262835,
18.0,
-4.0,
4.0,
70.6,
-0.31815711,
0.51171052,
0.00003265,
-0.00000852,
0.21974689,
0.27095860,
-0.00005943,
-0.00000467,
7.58619928,
0.01484434,
-0.00000168,
89.59121704,
15.00408363,
-0.00000130,
0.53581262,
0.00006179,
-0.00001275,
-0.01027351,
0.00006148,
-0.00001269,
0.00466826,
0.00464501,
]
var c1 = [Double](repeating: 0.0, count: 40)
var c2 = [Double](repeating: 0.0, count: 40)
var mid = [Double](repeating: 0.0, count: 40)
var c3 = [Double](repeating: 0.0, count: 40)
var c4 = [Double](repeating: 0.0, count: 40)
var latString: String {
return String(format: "%.3f\u{00B0} %@", abs(latitude), latitude > 0 ? "North": "South")
}
var lonString: String {
return String(format: "%.3f\u{00B0} %@", abs(longitude), longitude > 0 ? "East": "West")
}
var eclipseType: EclipseType = .full
var magnitude: String? {
if eclipseType == .none {
return nil
}
return String((mid[34] * 1000).rounded() / 1000)
}
var duration: String? {
if eclipseType == .full {
return getduration()
}
return nil
}
var coverage: String {
return getcoverage()
}
var contact1: EclipseEvent {
return EclipseEvent(name: localizedString(key: "Start of partial eclipse"), date: getdate(c1), time: gettime(c1), alt: getalt(c1), azi: getazi(c1))
}
var contact2: EclipseEvent {
return EclipseEvent(name: localizedString(key: "Start of total eclipse"), date: getdate(c2), time: gettime(c2), alt: getalt(c2), azi: getazi(c2))
}
var contactMid: EclipseEvent {
return EclipseEvent(name: localizedString(key: "Maximum eclipse"), date: getdate(mid), time: gettime(mid), alt: getalt(mid), azi: getazi(mid))
}
var contact3: EclipseEvent {
return EclipseEvent(name: localizedString(key: "End of total eclipse"), date: getdate(c3), time: gettime(c3), alt: getalt(c3), azi: getazi(c3))
}
var contact4: EclipseEvent {
return EclipseEvent(name: localizedString(key: "End of partial eclipse"), date: getdate(c4), time: gettime(c4), alt: getalt(c4), azi: getazi(c4))
}
init(latitude: Double, longitude: Double) {
self.longitude = longitude
self.latitude = latitude
loc_circ(latitude, longitude)
printTimes()
}
// Populate the circumstances array with the time-only dependent circumstances (x, y, d, m, ...)
func timedependent(_ circumstances : UnsafeMutablePointer<Double>) {
let t = circumstances[1]
var ans = elements[8] * t + elements[7]
ans = ans * t + elements[6]
ans = ans * t + elements[5]
circumstances[2] = ans
// dx
ans = 3.0 * elements[8] * t + 2.0 * elements[7]
ans = ans * t + elements[6]
circumstances[10] = ans
// y
ans = elements[12] * t + elements[11]
ans = ans * t + elements[10]
ans = ans * t + elements[9]
circumstances[3] = ans
// dy
ans = 3.0 * elements[12] * t + 2.0 * elements[11]
ans = ans * t + elements[10]
circumstances[11] = ans
// d
ans = elements[15] * t + elements[14]
ans = ans * t + elements[13]
ans *= D2R
circumstances[4] = ans
// sin d and cos d
circumstances[5] = sin(ans)
circumstances[6] = cos(ans)
// dd
ans = 2.0 * elements[15] * t + elements[14]
ans *= D2R
circumstances[12] = ans
// m
ans = elements[18] * t + elements[17]
ans = ans * t + elements[16]
if ans >= 360.0 {
ans -= 360.0
}
ans *= D2R
circumstances[7] = ans
// dm
ans = 2.0 * elements[18] * t + elements[17]
ans *= D2R
circumstances[13] = ans
// l1 and dl1
let type = circumstances[0]
if type == -2 || type == 0 || type == 2 {
ans = elements[21] * t + elements[20]
ans = ans * t + elements[19]
circumstances[8] = ans
circumstances[14] = 2.0 * elements[21] * t + elements[20]
}
// l2 and dl2
if type == -1 || type == 0 || type == 1 {
ans = elements[24] * t + elements[23]
ans = ans * t + elements[22]
circumstances[9] = ans
circumstances[15] = 2.0 * elements[24] * t + elements[23]
}
}
// Populate the circumstances array with the time and location dependent circumstances
func timelocaldependent(_ circumstances : UnsafeMutablePointer<Double>) {
timedependent(circumstances)
//h, sin h, cos h
circumstances[16] = circumstances[7] - obsvconst[1] - (elements[4] / 13713.44)
circumstances[17] = sin(circumstances[16])
circumstances[18] = cos(circumstances[16])
//xi
circumstances[19] = obsvconst[5] * circumstances[17]
//eta
circumstances[20] = obsvconst[4] * circumstances[6] - obsvconst[5] * circumstances[18] * circumstances[5]
//zeta
circumstances[21] = obsvconst[4] * circumstances[5] + obsvconst[5] * circumstances[18] * circumstances[6]
//dxi
circumstances[22] = circumstances[13] * obsvconst[5] * circumstances[18]
//deta
circumstances[23] = circumstances[13] * circumstances[19] * circumstances[5] - circumstances[21] * circumstances[12]
// u
circumstances[24] = circumstances[2] - circumstances[19]
// v
circumstances[25] = circumstances[3] - circumstances[20]
// a
circumstances[26] = circumstances[10] - circumstances[22]
// b
circumstances[27] = circumstances[11] - circumstances[23]
// l1'
let type = circumstances[0]
if type == -2 || type == 0 || type == 2 {
circumstances[28] = circumstances[8] - circumstances[21] * elements[25]
}
// l2'
if type == -1 || type == 0 || type == 1 {
circumstances[29] = circumstances[9] - circumstances[21] * elements[26]
}
// n^2
circumstances[30] = circumstances[26] * circumstances[26] + circumstances[27] * circumstances[27]
}
// Iterate on C1 or C4
func c1c4iterate(_ circumstances : UnsafeMutablePointer<Double>) {
var sign = 0.0
var n = 0.0
timelocaldependent(circumstances)
if circumstances[0] < 0 {
sign = -1.0
} else {
sign = 1.0
}
var tmp = 1.0
var iter = 0
while (tmp > 0.000001 || tmp < -0.000001) && iter < 50 {
n = sqrt(circumstances[30])
tmp = circumstances[26] * circumstances[25] - circumstances[24] * circumstances[27]
tmp = tmp / n / circumstances[28]
tmp = sign * sqrt(1.0 - tmp * tmp) * circumstances[28] / n
tmp = (circumstances[24] * circumstances[26] + circumstances[25] * circumstances[27]) / circumstances[30] - tmp
circumstances[1] = circumstances[1] - tmp
timelocaldependent(circumstances)
iter += 1
}
}
// Get C1 and C4 data
// Entry conditions -
// 1. The mid array must be populated
// 2. The magnitude at mid eclipse must be > 0.0
func getc1c4() {
let n = sqrt(mid[30])
var tmp = mid[26] * mid[25] - mid[24] * mid[27]
tmp = tmp / n / mid[28]
tmp = sqrt(1.0 - tmp * tmp) * mid[28] / n
c1[0] = -2
c4[0] = 2
c1[1] = mid[1] - tmp
c4[1] = mid[1] + tmp
c1c4iterate(&c1)
c1c4iterate(&c4)
}
// Iterate on C2 or C3
func c2c3iterate(_ circumstances : UnsafeMutablePointer<Double>) {
var sign = 0.0
var n = 0.0
timelocaldependent(circumstances)
if circumstances[0] < 0 {
sign = -1.0
} else {
sign = 1.0
}
if mid[29] < 0.0 {
sign = -sign
}
var tmp = 1.0
var iter = 0
while (tmp > 0.000001 || tmp < -0.000001) && iter < 50 {
n = sqrt(circumstances[30])
tmp = circumstances[26] * circumstances[25] - circumstances[24] * circumstances[27]
tmp = tmp / n / circumstances[29]
tmp = sign * sqrt(1.0 - tmp * tmp) * circumstances[29] / n
tmp = (circumstances[24] * circumstances[26] + circumstances[25] * circumstances[27]) / circumstances[30] - tmp
circumstances[1] = circumstances[1] - tmp
timelocaldependent(circumstances)
iter += 1
}
}
// Get C2 and C3 data
// Entry conditions -
// 1. The mid array must be populated
// 2. There must be either a total or annular eclipse at the location!
func getc2c3() {
let n = sqrt(mid[30])
var tmp = mid[26] * mid[25] - mid[24] * mid[27]
tmp = tmp / n / mid[29]
tmp = sqrt(1.0 - tmp * tmp) * mid[29] / n
c2[0] = -1
c3[0] = 1
if mid[29] < 0.0 {
c2[1] = mid[1] + tmp
c3[1] = mid[1] - tmp
} else {
c2[1] = mid[1] - tmp
c3[1] = mid[1] + tmp
}
c2c3iterate(&c2)
c2c3iterate(&c3)
}
// Get the observational circumstances
func observational(_ circumstances : UnsafeMutablePointer<Double>) {
// alt
let sinlat = sin(obsvconst[0])
let coslat = cos(obsvconst[0])
circumstances[31] = asin(circumstances[5] * sinlat + circumstances[6] * coslat * circumstances[18])
// azi
circumstances[32] = atan2(-1.0 * circumstances[17] * circumstances[6],
circumstances[5] * coslat - circumstances[18] * sinlat * circumstances[6])
}
// Calculate max eclipse
func getmid() {
mid[0] = 0
mid[1] = 0.0
var iter = 0
var tmp = 1.0
timelocaldependent(&mid)
while (tmp > 0.000001 || tmp < -0.000001) && iter < 50 {
tmp = (mid[24] * mid[26] + mid[25] * mid[27]) / mid[30]
mid[1] = mid[1] - tmp
iter += 1
timelocaldependent(&mid)
}
}
// Populate the c1, c2, mid, c3 and c4 arrays
func getall() {
getmid()
observational(&mid)
// m, magnitude and moon/sun ratio
mid[33] = sqrt(mid[24]*mid[24] + mid[25]*mid[25])
mid[34] = (mid[28] - mid[33]) / (mid[28] + mid[29])
mid[35] = (mid[28] - mid[29]) / (mid[28] + mid[29])
if mid[34] > 0.0 {
getc1c4()
if mid[33] < mid[29] || mid[33] < -mid[29] {
getc2c3()
if mid[29] < 0.0 {
mid[36] = 3 // Total solar eclipse
} else {
mid[36] = 2 // Annular solar eclipse
}
observational(&c2)
observational(&c3)
c2[33] = 999.9
c3[33] = 999.9
} else {
mid[36] = 1 // Partial eclipse
}
observational(&c1)
observational(&c4)
} else {
mid[36] = 0 // No eclipse
}
}
// Read the data, and populate the obsvconst array
func readdata(_ lat : Double, _ lon : Double) {
// Get the latitude
obsvconst[0] = lat
obsvconst[0] *= 1
obsvconst[0] *= D2R
// Get the longitude
obsvconst[1] = lon
obsvconst[1] *= -1
obsvconst[1] *= D2R
// Get the altitude (sea level by default)
obsvconst[2] = 0
// Get the time zone (UT by default)
obsvconst[3] = 0
// Get the observer's geocentric position
let tmp = atan(0.99664719 * tan(obsvconst[0]))
obsvconst[4] = 0.99664719 * sin(tmp) + (obsvconst[2] / 6378140.0) * sin(obsvconst[0])
obsvconst[5] = cos(tmp) + (obsvconst[2] / 6378140.0 * cos(obsvconst[0]))
}
// This is used in getday()
// Pads digits
func padDigits(_ n : Double, _ totalDigits : Int ) -> String {
let nString = String(format: "%.0f", n)
var pd = ""
if totalDigits > nString.count {
for _ in 0...(totalDigits - nString.count) {
pd.append("0")
}
}
return "\(pd)\(nString)"
}
// Get the local date
func getdate(_ circumstances : [Double]) -> String {
let jd = elements[0]
// Calculate the local time.
// Assumes JD > 0 (uses same algorithm as SKYCAL)
var t = circumstances[1] + elements[1] - obsvconst[3] - (elements[4] - 0.05) / 3600.0
if t < 0.0 {
t += 24.0 // and jd-- below
} else if t >= 24.0 {
t -= 24.0 // and jd++ below
}
var a = 0.0
var y = 0.0 // Year
var m = 0.0 // Month
var day = 0.0
let jdm = jd + 0.5
let z = floor(jdm)
let f = jdm - z
if z < 2299161 {
a = z
} else if z >= 2299161 {
let alpha = floor((z - 1867216.25) / 36524.25)
a = z + 1 + alpha - floor(alpha / 4)
}
let b = a + 1524
let c = floor((b - 122.1) / 365.25)
let d = floor(365.25 * c)
let e = floor((b - d) / 30.6001)
day = b - d - floor(30.6001 * e) + f
if e < 14 {
m = e - 1.0
} else if e == 14 || e == 15 {
m = e - 13.0
}
if m > 2 {
y = c - 4716.0
} else if m == 1 || m == 2 {
y = c - 4715.0
}
let timediff = t - 24 * (day - floor(day)) // present time minus UT at GE
if timediff < -12 {
day += 1
} else if timediff > 12 {
day -= 1
}
let date = String.init(format: "%.0f-%.0f-%.0f", floor(m), floor(day), floor(y))
return date
}
// Get the local time
func gettime(_ circumstances: [Double]) -> String {
var ans = ""
var t = circumstances[1] + elements[1] - obsvconst[3] - (elements[4] - 0.05) / 3600.0
if t < 0.0 {
t += 24.0
} else if t >= 24.0 {
t -= 24.0
}
if t < 10.0 {
ans.append("0")
}
let hour = String.init(format: "%.0f", floor(t))
ans.append(hour)
ans.append(":")
t = (t * 60.0) - 60.0 * floor(t)
if t < 10.0 {
ans.append("0")
}
let minute = String.init(format: "%.0f", floor(t))
ans.append(minute)
ans.append(":")
t = (t * 60.0) - 60.0 * floor(t)
if t < 10.0 {
ans.append("0")
}
let second = String.init(format: "%.0f", floor(t))
ans.append(second)
ans.append(".")
let milisecond = String.init(format: "%.0f", floor(10.0 * (t - floor(t))))
ans.append(milisecond)
return ans
}
// Display the information about 1st contact
func displayc1() -> String {
return "C1: \(getdate(c1)) \(gettime(c1)) alt: \(getalt(c1)) azi: \(getazi(c1))"
}
// Display the information about 2nd contact
func displayc2() -> String {
return "C2: \(getdate(c2)) \(gettime(c2)) alt: \(getalt(c2)) azi: \(getazi(c2))"
}
// Display the information about maximum eclipse
func displaymid() -> String {
return "MID: \(getdate(mid)) \(gettime(mid)) alt: \(getalt(mid))azi: \(getazi(mid))"
}
//
// Display the information about 3rd contact
func displayc3() -> String {
return "C3: \(getdate(c3)) \(gettime(c3)) alt: \(getalt(c3)) azi: \(getazi(c3))"
}
// Display the information about 4th contact
func displayc4() -> String {
return "C4: \(getdate(c4)) \(gettime(c4)) alt: \(getalt(c4)) azi: \(getazi(c4))"
}
// Get the altitude
func getalt(_ circumstances : [Double]) -> String {
var ans = ""
let t = circumstances[31] * R2D
ans.append(String.init(format: "%.1f\u{00B0}", abs(t)))
return ans
}
// Get the azimuth
func getazi(_ circumstances : [Double]) -> String {
var ans = ""
var t = circumstances[32] * R2D
if t < 0.0 {
t += 360.0
} else if t >= 360.0 {
t -= 360.0
}
ans.append(String.init(format: "%.1f\u{00B0}", t))
return ans
}
// Get the duration in 00m00.0s format
func getduration() -> String {
var tmp = c3[1] - c2[1]
if tmp < 0.0 {
tmp += 24.0
} else if tmp >= 24.0 {
tmp -= 24.0
}
tmp = (tmp * 60.0) - 60.0 * floor(tmp) + 0.05 / 60.0
let minutes = String(format: "%.0fm", floor(tmp))
var singleDigit : String?
tmp = (tmp * 60.0) - 60.0 * floor(tmp)
if tmp < 10.0 {
singleDigit = "0"
}
let seconds = String(format: "%.0f.%.0fs", floor(tmp), floor((tmp - floor(tmp)) * 10.0))
return "\(minutes)\(singleDigit ?? "")\(seconds)"
}
// Get the obscuration
func getcoverage() -> String {
var a = 0.0
var b = 0.0
var c = 0.0
if mid[34] <= 0.0 {
return "0.00%"
} else if mid[34] >= 1.0 {
return "100.00%"
}
if mid[36] == 2 {
c = mid[35] * mid[35]
} else {
c = acos((mid[28] * mid[28] + mid[29] * mid[29] - 2.0 * mid[33] * mid[33]) / (mid[28] * mid[28] - mid[29] * mid[29]))
b = acos((mid[28] * mid[29] + mid[33] * mid[33]) / mid[33] / (mid[28] + mid[29]))
a = Double.pi - b - c
c = ((mid[35] * mid[35] * a + b) - mid[35] * sin(c)) / Double.pi
}
return String.init(format: "%.2f%%", c * 100)
}
//
// Compute the local circumstances
func loc_circ(_ lat : Double, _ lon : Double) {
readdata(lat, lon)
getall()
}
func printTimes() {
isPartial = false
isEclipse = true
if mid[36] > 0 {
// There is an eclipse
if mid[36] > 1 {
// Total/annular eclipse
if c1[31] <= 0.0 && c4[31] <= 0.0 {
// Sun below the horizon for the entire duration of the event
isEclipse = false
} else {
// Sun above the horizon for at least some of the event
if c2[31] <= 0.0 && c3[31] <= 0.0 {
// Sun below the horizon for just the total/annular event
isPartial = true
} else {
// Sun above the horizon for at least some of the total/annular event
if c2[31] > 0.0 && c3[31] > 0.0 {
// Sun above the horizon for the entire annular/total event
if mid[36] == 2 {
// Annular Solar Eclipse
} else {
// Total Solar Eclipse
}
} else {
// Sun below the horizon for at least some of the annular/total event
}
}
}
} else {
// Partial eclipse
if c1[31] <= 0.0 && c4[31] <= 0.0 {
// Sun below the horizon
isEclipse = false
} else {
isPartial = true
}
}
} else {
// No eclipse
isEclipse = false
}
if isEclipse {
if isPartial {
eclipseType = .partial
} else {
eclipseType = .full
}
} else {
eclipseType = .none
}
}
}
| gpl-3.0 | a241e4f9ded3786d85b27d08cb5475e1 | 31.308239 | 155 | 0.490086 | 3.602312 | false | false | false | false |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/KeyPadButton.swift | 1 | 753 | //
// KeyPadButton.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 1/23/17.
// Copyright © 2017 Zakk Hoyt. All rights reserved.
//
import UIKit
public class KeyPadButton: UIButton {
public override func layoutSubviews() {
super.layoutSubviews()
self.setTitleColor(.black, for: .normal)
self.setTitleColor(.lightGray, for: .highlighted)
self.backgroundColor = UIColor.white
self.layer.masksToBounds = false
self.layer.cornerRadius = 4.0
self.layer.shadowRadius = 1.0
self.layer.shadowColor = UIColor.darkGray.withAlphaComponent(0.5).cgColor
self.layer.shadowOpacity = 1.0
self.layer.shadowOffset = CGSize(width: 0, height: 2)
}
}
| mit | c2549057be4f5a8cec4f541694bb6080 | 26.851852 | 81 | 0.652926 | 4.154696 | false | false | false | false |
mattjgalloway/emoncms-ios | EmonCMSiOS/Controllers/LoginController.swift | 1 | 2490 | //
// LoginController.swift
// EmonCMSiOS
//
// Created by Matt Galloway on 13/09/2016.
// Copyright © 2016 Matt Galloway. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Locksmith
final class LoginController {
enum LoginControllerError: Error {
case Generic
case KeychainFailed
}
private var _account = Variable<Account?>(nil)
let account: Observable<Account?>
init() {
self.account = _account.asObservable().shareReplay(1)
self.loadAccount()
}
private func loadAccount() {
guard
let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue),
let accountUUIDString = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue),
let accountUUID = UUID(uuidString: accountUUIDString)
else { return }
guard
let data = Locksmith.loadDataForUserAccount(userAccount: accountUUIDString),
let apikey = data["apikey"] as? String
else { return }
let account = Account(uuid: accountUUID, url: accountURL, apikey: apikey)
self._account.value = account
}
func login(withAccount account: Account) throws {
do {
if let currentAccount = _account.value {
if currentAccount == account {
return
}
}
let data = ["apikey": account.apikey]
do {
try Locksmith.saveData(data: data, forUserAccount: account.uuid.uuidString)
} catch LocksmithError.duplicate {
// We already have it, let's try updating it
try Locksmith.updateData(data: data, forUserAccount: account.uuid.uuidString)
}
UserDefaults.standard.set(account.url, forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue)
UserDefaults.standard.set(account.uuid.uuidString, forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue)
self._account.value = account
} catch {
throw LoginControllerError.KeychainFailed
}
}
func logout() throws {
guard let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue) else {
throw LoginControllerError.Generic
}
do {
try Locksmith.deleteDataForUserAccount(userAccount: accountURL)
UserDefaults.standard.removeObject(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue)
self._account.value = nil
} catch {
throw LoginControllerError.KeychainFailed
}
}
}
| mit | 2c74364d5816368ed266f6ff35f4982e | 29.353659 | 125 | 0.709522 | 4.566972 | false | false | false | false |
mr-v/SimpleServices | Services/WebService.swift | 1 | 5021 | //
// WebServices.swift
// ServicesTest
//
// Created by Witold Skibniewski on 13/12/14.
// Copyright (c) 2014 Witold Skibniewski. All rights reserved.
//
import UIKit
// created global factory methods to avoid calling it like: WebService<UIImage>.makeImageWebService() // where UIImage generic type would be ignored anyway
public func makeImageWebService() -> WebService<UIImage> {
return WebService<UIImage>(baseURLString: "", defaultParameters: [String : Any](), deserializer: ImageDeserializer()) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let imageCache = NSURLCache(memoryCapacity:40 * 1024 * 1024, diskCapacity:50 * 1024 * 1024, diskPath:nil)
configuration.URLCache = imageCache
configuration.requestCachePolicy = .ReturnCacheDataElseLoad
return NSURLSession(configuration: configuration)
}
}
public func makeJSONWebService(#baseURLString: String, #defaultParameters: [String: Any]) -> WebService<NSDictionary> {
return WebService<NSDictionary>(baseURLString: baseURLString,
defaultParameters: defaultParameters,
deserializer: JSONDeserializer(errorPointer: nil),
makeSessionClosure: {
let defaultConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
// defaultConfiguration.requestCachePolicy = .ReturnCacheDataElseLoad
return NSURLSession(configuration: defaultConfiguration)
})
}
public class WebService<T>: ServiceType {
private var dataValidator: Any!
private let deserializer: DeserializerType
private let session: NSURLSession!
private let baseURLString: String
private let defaultParameters = [String: Any]()
private init(baseURLString: String, defaultParameters: [String: Any], deserializer: DeserializerType, makeSessionClosure: () -> NSURLSession) {
self.baseURLString = baseURLString
self.defaultParameters = defaultParameters
self.deserializer = deserializer
session = makeSessionClosure()
}
public func fetch(URLString: String, completionHandler: Result<T> -> ()) {
if let URL = NSURL(string: URLString) {
fetch(URL, completionHandler: completionHandler)
} else {
dispatch_async(dispatch_get_main_queue()) { completionHandler(.Error) }
}
}
public func fetch(URL: NSURL, completionHandler: Result<T> -> ()) {
let request = NSURLRequest(URL: URL)
startTaskWithRequest(request, completionHandler: completionHandler)
}
public func fetch(parameters: [String: Any], completionHandler: Result<T> -> ()) { //-> Cancelable {
let request = urlRequestWithParameters(parameters)
startTaskWithRequest(request, completionHandler: completionHandler)
}
private func startTaskWithRequest(request: NSURLRequest, completionHandler: Result<T> -> ()) {
let task = session.dataTaskWithRequest(request, completionHandler: {
[weak self] data, urlResponse, error in
func dispatchError() {
dispatch_async(dispatch_get_main_queue()) { completionHandler(.Error) }
}
if let taskError = error {
if taskError.code != NSUserCancelledError {
dispatchError()
}
return
}
if let httpResponse = urlResponse as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
dispatchError()
return
}
}
if let deserialized = self?.deserializer.deserialize(data) as? T {
// if !validate(deserialized)? {
// dispatchError()
// return
// }
let result: Result = .OK(deserialized) // forced casting
dispatch_async(dispatch_get_main_queue()) { completionHandler(result) }
} else {
dispatchError()
return
}
})
task.resume()
}
private func urlRequestWithParameters(parameters: [String: Any]) -> NSURLRequest {
let components = NSURLComponents(string: baseURLString)!
let mergedParameters = defaultParameters + parameters
if !mergedParameters.isEmpty {
components.queryItems = queryItemsWithParameters(mergedParameters)
}
let request = NSURLRequest(URL: components.URL!)
return request
}
private func queryItemsWithParameters(parameters: [String: Any]) -> [NSURLQueryItem] {
let keys = parameters.keys.array
return keys.map { key in NSURLQueryItem(name: key, value: "\(parameters[key]!)") }
}
}
// TODO: move it
private func + <K, V> (left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> {
var result = left
for (k, v) in right {
result.updateValue(v, forKey: k)
}
return result
}
| mit | da731c15edf70ad5f67f1b82c2a50163 | 38.849206 | 155 | 0.638917 | 5.27416 | false | true | false | false |
Snail93/iOSDemos | SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/RxCocoaViewController.swift | 2 | 1891 | //
// RxCocoaViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2017/1/3.
// Copyright © 2017年 Snail. All rights reserved.
//
import UIKit
class RxCocoaViewController: CustomViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var aTableView: UITableView!
var cellNames = ["NumberPlus","SimpleValidation","UITextView","UITextField","UIScrollView","AlertController"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
leftBtn.isHidden = false
navTitleLabel.text = "RxCocoa"
aTableView.register(UITableViewCell.self, forCellReuseIdentifier: "RxCocoaCell")
}
//MARK: - UITableViewDelegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RxCocoaCell", for: indexPath)
cell.textLabel?.text = cellNames[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: cellNames[indexPath.row], sender: nil)
}
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.
}
*/
}
| apache-2.0 | dd876c704f51ffbfba586643f45025e8 | 32.714286 | 113 | 0.690678 | 5.229917 | false | false | false | false |
xsunsmile/zentivity | zentivity/SearchFilterView.swift | 1 | 1188 | //
// SearchFilterView.swift
// zentivity
//
// Created by Hao Sun on 3/22/15.
// Copyright (c) 2015 Zendesk. All rights reserved.
//
import UIKit
protocol SearchFilterViewDelegate: class {
func onSearchFilterPress()
}
class SearchFilterView: UIView {
var contentView: UIView!
@IBOutlet weak var filterView: UIView!
@IBOutlet weak var searchBar: UISearchBar!
var delegate: SearchFilterViewDelegate?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubViews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initSubViews()
}
func initSubViews() {
let nib = UINib(nibName: "SearchFilterView", bundle: nil)
let objects = nib.instantiateWithOwner(self, options: nil)
contentView = objects[0] as! UIView
contentView.frame = bounds
searchBar.barTintColor = UIColor.clearColor()
searchBar.backgroundImage = UIImage()
filterView.hidden = true
addSubview(contentView)
}
@IBAction func onFilterPress(sender: AnyObject) {
delegate?.onSearchFilterPress()
}
}
| apache-2.0 | 30ccb34c56923ed717b999d7f2110acc | 23.244898 | 66 | 0.640572 | 4.483019 | false | false | false | false |
slavapestov/swift | test/SILGen/optional_lvalue.swift | 2 | 3083 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
// CHECK-LABEL: sil hidden @_TF15optional_lvalue22assign_optional_lvalueFTRGSqSi_Si_T_
// CHECK: [[SHADOW:%.*]] = alloc_box $Optional<Int>
// CHECK: [[PB:%.*]] = project_box [[SHADOW]]
// CHECK: [[PRECOND:%.*]] = function_ref @_TFs30_diagnoseUnexpectedNilOptionalFT_T_
// CHECK: apply [[PRECOND]]()
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[PB]] : $*Optional<Int>, #Optional.Some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_optional_lvalue(inout x: Int?, _ y: Int) {
x! = y
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue17assign_iuo_lvalueFTRGSQSi_Si_T_
// CHECK: [[SHADOW:%.*]] = alloc_box $ImplicitlyUnwrappedOptional<Int>
// CHECK: [[PB:%.*]] = project_box [[SHADOW]]
// CHECK: [[PRECOND:%.*]] = function_ref @_TFs30_diagnoseUnexpectedNilOptionalFT_T_
// CHECK: apply [[PRECOND]]()
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[PB]] : $*ImplicitlyUnwrappedOptional<Int>, #ImplicitlyUnwrappedOptional.Some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_iuo_lvalue(inout x: Int!, _ y: Int) {
x! = y
}
struct S {
var x: Int
var computed: Int {
get {}
set {}
}
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue26assign_iuo_lvalue_implicitFTRGSQVS_1S_Si_T_
// CHECK: [[SHADOW:%.*]] = alloc_box
// CHECK: [[PB:%.*]] = project_box [[SHADOW]]
// CHECK: [[SOME:%.*]] = unchecked_take_enum_data_addr [[PB]]
// CHECK: [[X:%.*]] = struct_element_addr [[SOME]]
func assign_iuo_lvalue_implicit(inout s: S!, _ y: Int) {
s.x = y
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue35assign_optional_lvalue_reabstractedFTRGSqFSiSi_FSiSi_T_
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK: [[REABSTRACTED:%.*]] = partial_apply [[REABSTRACT]]
// CHECK: assign [[REABSTRACTED]] to {{%.*}} : $*@callee_owned (@out Int, @in Int) -> ()
func assign_optional_lvalue_reabstracted(inout x: (Int -> Int)?,
_ y: Int -> Int) {
x! = y
}
// CHECK-LABEL: sil hidden @_TF15optional_lvalue31assign_optional_lvalue_computedFTRGSqVS_1S_Si_Si
// CHECK: function_ref @_TFV15optional_lvalue1Ss8computedSi
// CHECK: function_ref @_TFV15optional_lvalue1Sg8computedSi
func assign_optional_lvalue_computed(inout x: S?, _ y: Int) -> Int {
x!.computed = y
return x!.computed
}
func generate_int() -> Int { return 0 }
// CHECK-LABEL: sil hidden @_TF15optional_lvalue28assign_bound_optional_lvalueFRGSqSi_T_
// CHECK: select_enum_addr
// CHECK: cond_br {{%.*}}, [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]]
// CHECK: [[SOME]]:
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr
// CHECK: [[FN:%.*]] = function_ref
// CHECK: [[T0:%.*]] = apply [[FN]]()
// CHECK: assign [[T0]] to [[PAYLOAD]]
func assign_bound_optional_lvalue(inout x: Int?) {
x? = generate_int()
}
| apache-2.0 | bbec567dfb6aa017d0fd83f4f958a50e | 41.819444 | 154 | 0.591632 | 3.365721 | false | false | false | false |
Sephiroth87/C-swifty4 | C-swifty4 Remote/ViewController.swift | 1 | 3148 | //
// ViewController.swift
// C-swifty4 Remote
//
// Created by Fabio on 22/11/2017.
// Copyright © 2017 orange in a day. All rights reserved.
//
import UIKit
import MultipeerConnectivity
class ViewController: UIViewController {
let peerId = MCPeerID(displayName: UIDevice.current.name)
lazy var session: MCSession = {
return MCSession(peer: peerId, securityIdentity: nil, encryptionPreference: .none)
}()
lazy var browser: MCNearbyServiceBrowser = {
MCNearbyServiceBrowser(peer: peerId, serviceType: "c-swifty4")
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
browser.delegate = self
browser.startBrowsingForPeers()
becomeFirstResponder()
}
override var canBecomeFirstResponder: Bool {
return true
}
@IBAction func onBrowserButton() {
let picker = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .open)
picker.delegate = self
present(picker, animated: true, completion: nil)
}
}
extension ViewController: UIKeyInput {
var autocorrectionType: UITextAutocorrectionType {
get { return .no }
set {}
}
var keyboardAppearance: UIKeyboardAppearance {
get { return .dark }
set {}
}
var hasText: Bool {
return true
}
func insertText(_ text: String) {
if text == "\n" {
try? session.send(Data([0x00, 0x01]), toPeers: session.connectedPeers, with: .reliable)
} else {
let char = text.utf8[text.utf8.startIndex]
try? session.send(Data([char]), toPeers: session.connectedPeers, with: .reliable)
}
}
func deleteBackward() {
try? session.send(Data([0x00, 0x00]), toPeers: session.connectedPeers, with: .reliable)
}
}
extension ViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
guard let peer = session.connectedPeers.first else { return }
_ = url.startAccessingSecurityScopedResource()
let coordinator = NSFileCoordinator()
coordinator.coordinate(readingItemAt: url, options: .forUploading, error: nil) { newUrl in
let tmp = URL(fileURLWithPath: NSTemporaryDirectory() + newUrl.lastPathComponent)
try? FileManager.default.copyItem(at: newUrl, to: tmp)
session.sendResource(at: tmp, withName: tmp.lastPathComponent, toPeer: peer) { error in
error.map { print($0) }
try? FileManager.default.removeItem(at: tmp)
url.stopAccessingSecurityScopedResource()
}
}
}
}
extension ViewController: MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 30)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
}
}
| mit | 6a867ba574e7f54637c0f2ade598528c | 29.553398 | 125 | 0.644741 | 4.894246 | false | false | false | false |
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/Style/Stylers/PlaceholderStyler.swift | 1 | 1431 | //
// PlaceholderTextStylePropertySet.swift
// Pods-SwiftStylableExample
//
// Created by Bob De Kort-Goossens on 19/07/2018.
//
import Foundation
class PlaceholderTextStyler: Styler {
private weak var _view: PlaceholderStylable?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Initializers
//
// -----------------------------------------------------------------------------------------------------------------------
init(_ view: PlaceholderStylable) {
self._view = view
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Public methods
//
// -----------------------------------------------------------------------------------------------------------------------
open func applyStyle(_ style: Style) {
guard let view = self._view else {
return
}
if let fullUppercasePlaceholder = style.placeholderStyle.fullUppercasePlaceholder {
view.fullUppercasePlaceholder = fullUppercasePlaceholder
}
if let styledPlaceholderAttributes = style.placeholderStyle.styledPlaceholderAttributes {
view.styledPlaceholderAttributes = styledPlaceholderAttributes
}
}
}
| mit | a12ec8eddcf17429772eda19cabe1323 | 30.8 | 126 | 0.401817 | 7.227273 | false | false | false | false |
kArTeL/News-YC---iPhone | HN/CustomViews/Cells/Comments/HNCommentCell.swift | 5 | 6791 | //
// HNCommentCell.swift
// HN
//
// Created by Ben Gordon on 9/19/14.
// Copyright (c) 2014 bennyguitar. All rights reserved.
//
import UIKit
let horizCommentSpaceStart = 8.0
let commentLevelSpace = 15.0
protocol HNCommentsCellDelegate {
func didSelectHideNested(index: Int, level: Int)
}
enum HNCommentCellVisibility: Int {
case Visible, Closed, Hidden
}
class HNCommentCell: UITableViewCell, TTTAttributedLabelDelegate {
@IBOutlet weak var topBar: UIView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var commentLabel: TTTAttributedLabel!
@IBOutlet weak var topBarLeftSpaceConstraint: NSLayoutConstraint!
@IBOutlet weak var commentLabelLeftSpaceConstraint: NSLayoutConstraint!
@IBOutlet weak var commentViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var topBarHeightConstraint: NSLayoutConstraint!
var commentLevel = 0
var index = 0
var del: HNCommentsCellDelegate? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(false, animated: false)
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(false, animated: false)
}
func setContentWithComment(comment: HNComment, indexPath: NSIndexPath, delegate: HNCommentsCellDelegate, visibility: HNCommentCellVisibility) {
// Data
usernameLabel.text = comment.Username
timeLabel.text = comment.TimeCreatedString
commentLevel = Int(comment.Level)
index = indexPath.row
del = delegate
// Visibility
if (visibility == HNCommentCellVisibility.Closed) {
setContentViewForVisibility(HNCommentCellVisibility.Closed)
topBar.backgroundColor = HNOrangeColor
return
}
else if (visibility == HNCommentCellVisibility.Hidden) {
setContentViewForVisibility(HNCommentCellVisibility.Hidden)
topBar.backgroundColor = UIColor.redColor()
return
}
setContentViewForVisibility(HNCommentCellVisibility.Visible)
// Links
commentLabel.delegate = self
commentLabel.linkAttributes = [kCTForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.CommentLinkColor), kCTUnderlineStyleAttributeName:NSUnderlineStyle.StyleNone.rawValue]
commentLabel.activeLinkAttributes = [kCTForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.CommentLinkColor), kCTUnderlineStyleAttributeName:NSUnderlineStyle.StyleNone.rawValue, kCTFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]
commentLabel.setText(comment.Text, afterInheritingLabelAttributesAndConfiguringWithBlock: { (aString) -> NSMutableAttributedString! in
aString.addAttributes([kCTForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.MainFont), kCTFontAttributeName:UIFont.systemFontOfSize(14.0), NSBackgroundColorAttributeName: HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.BackgroundColor)], range: NSMakeRange(0, NSString(string: comment.Text).length))
return aString
})
for link in comment.Links {
commentLabel.addLinkToURL(link.Url, withRange: link.UrlRange)
}
// UI
var bgColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.BackgroundColor)
var barColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.Bar)
if (comment.Type == HNCommentType.AskHN) {
bgColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBackground)
barColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBar)
}
else if (comment.Type == HNCommentType.Jobs) {
bgColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBackground)
barColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBar)
}
backgroundColor = bgColor
topBar.backgroundColor = barColor
usernameLabel.backgroundColor = barColor
timeLabel.backgroundColor = barColor
usernameLabel.textColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.SubFont)
timeLabel.textColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.SubFont)
// Constraints
commentLabelLeftSpaceConstraint.constant = CGFloat(comment.Level) * CGFloat(commentLevelSpace) + CGFloat(horizCommentSpaceStart)
topBarLeftSpaceConstraint.constant = CGFloat(comment.Level) * CGFloat(commentLevelSpace)
}
override func drawRect(rect: CGRect) {
// Create comment level lines
for (var xx = 0; xx < commentLevel + 1; xx++) {
if (xx != 0) {
var path = UIBezierPath()
HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.Bar).setStroke()
path.moveToPoint(CGPoint(x: 15*xx, y: 0))
path.addLineToPoint(CGPoint(x: Double(15)*Double(xx), y: Double(rect.size.height)))
path.stroke()
}
}
}
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
HNNavigationBrain.navigateToWebViewController(url.absoluteString!)
}
@IBAction func didSelectCommentsBar(sender: AnyObject) {
del?.didSelectHideNested(index, level: commentLevel)
}
func setNested() {
setContentViewForVisibility(HNCommentCellVisibility.Closed)
}
func setHidden() {
setContentViewForVisibility(HNCommentCellVisibility.Hidden)
}
func setContentViewForVisibility(visibility: HNCommentCellVisibility) {
/*
switch (visibility) {
case .Closed:
topBarHeightConstraint.constant = 0.0
topBarHeightConstraint.priority = 1000
commentViewHeightConstraint.constant = 0.0
commentViewHeightConstraint.priority = 1000
case .Hidden:
topBarHeightConstraint.constant = 18.0
topBarHeightConstraint.priority = 1000
commentViewHeightConstraint.constant = 0.0
commentViewHeightConstraint.priority = 1000
case .Visible:
topBarHeightConstraint.constant = 18.0
topBarHeightConstraint.priority = 100
commentViewHeightConstraint.constant = 47.5
commentViewHeightConstraint.priority = 100
}
*/
}
}
| mit | 2d3382c4c9707754a01d22aec8924a07 | 42.532051 | 370 | 0.700044 | 5.098348 | false | false | false | false |
benzguo/SVGPath | SVGPath/SVGPath.swift | 1 | 8672 | //
// SVGPath.swift
// SVGPath
//
// Created by Tim Wood on 1/21/15.
// Copyright (c) 2015 Tim Wood. All rights reserved.
//
import Foundation
import CoreGraphics
// MARK: UIBezierPath
public extension UIBezierPath {
convenience init (svgPath: String) {
self.init()
applyCommands(svgPath, path: self)
}
}
private func applyCommands (svgPath: String, path: UIBezierPath) {
for command in SVGPath(svgPath).commands {
switch command.type {
case .Move: path.moveToPoint(command.point)
case .Line: path.addLineToPoint(command.point)
case .QuadCurve: path.addQuadCurveToPoint(command.point, controlPoint: command.control1)
case .CubeCurve: path.addCurveToPoint(command.point, controlPoint1: command.control1, controlPoint2: command.control2)
case .Close: path.closePath()
}
}
}
// MARK: Enums
private enum Coordinates {
case Absolute
case Relative
}
// MARK: Class
public class SVGPath {
public var commands: [SVGCommand] = []
private var builder: SVGCommandBuilder = moveTo
private var coords: Coordinates = .Absolute
private var stride: Int = 2
private var numbers = ""
public init (_ string: String) {
for char in string.characters {
switch char {
case "M": use(.Absolute, 2, moveTo)
case "m": use(.Relative, 2, moveTo)
case "L": use(.Absolute, 2, lineTo)
case "l": use(.Relative, 2, lineTo)
case "V": use(.Absolute, 1, lineToVertical)
case "v": use(.Relative, 1, lineToVertical)
case "H": use(.Absolute, 1, lineToHorizontal)
case "h": use(.Relative, 1, lineToHorizontal)
case "Q": use(.Absolute, 4, quadBroken)
case "q": use(.Relative, 4, quadBroken)
case "T": use(.Absolute, 2, quadSmooth)
case "t": use(.Relative, 2, quadSmooth)
case "C": use(.Absolute, 6, cubeBroken)
case "c": use(.Relative, 6, cubeBroken)
case "S": use(.Absolute, 4, cubeSmooth)
case "s": use(.Relative, 4, cubeSmooth)
case "Z": use(.Absolute, 1, close)
case "z": use(.Absolute, 1, close)
default: numbers.append(char)
}
}
finishLastCommand()
}
private func use (coords: Coordinates, _ stride: Int, _ builder: SVGCommandBuilder) {
finishLastCommand()
self.builder = builder
self.coords = coords
self.stride = stride
}
private func finishLastCommand () {
for command in take(SVGPath.parseNumbers(numbers), stride: stride, coords: coords, last: commands.last, callback: builder) {
commands.append(coords == .Relative ? command.relativeTo(commands.last) : command)
}
numbers = ""
}
}
// MARK: Numbers
private let numberSet = NSCharacterSet(charactersInString: "-.0123456789eE")
private let locale = NSLocale(localeIdentifier: "en_US")
public extension SVGPath {
class func parseNumbers (numbers: String) -> [CGFloat] {
var all:[String] = []
var curr = ""
var last = ""
for char in numbers.unicodeScalars {
let next = String(char)
if next == "-" && last != "" && last != "E" && last != "e" {
if curr.utf16.count > 0 {
all.append(curr)
}
curr = next
} else if numberSet.longCharacterIsMember(char.value) {
curr += next
} else if curr.utf16.count > 0 {
all.append(curr)
curr = ""
}
last = next
}
all.append(curr)
return all.map { CGFloat(NSDecimalNumber(string: $0, locale: locale)) }
}
}
// MARK: Commands
public struct SVGCommand {
public var point:CGPoint
public var control1:CGPoint
public var control2:CGPoint
public var type:Kind
public enum Kind {
case Move
case Line
case CubeCurve
case QuadCurve
case Close
}
public init () {
let point = CGPoint()
self.init(point, point, point, type: .Close)
}
public init (_ x: CGFloat, _ y: CGFloat, type: Kind) {
let point = CGPoint(x: x, y: y)
self.init(point, point, point, type: type)
}
public init (_ cx: CGFloat, _ cy: CGFloat, _ x: CGFloat, _ y: CGFloat) {
let control = CGPoint(x: cx, y: cy)
self.init(control, control, CGPoint(x: x, y: y), type: .QuadCurve)
}
public init (_ cx1: CGFloat, _ cy1: CGFloat, _ cx2: CGFloat, _ cy2: CGFloat, _ x: CGFloat, _ y: CGFloat) {
self.init(CGPoint(x: cx1, y: cy1), CGPoint(x: cx2, y: cy2), CGPoint(x: x, y: y), type: .CubeCurve)
}
public init (_ control1: CGPoint, _ control2: CGPoint, _ point: CGPoint, type: Kind) {
self.point = point
self.control1 = control1
self.control2 = control2
self.type = type
}
private func relativeTo (other:SVGCommand?) -> SVGCommand {
if let otherPoint = other?.point {
return SVGCommand(control1 + otherPoint, control2 + otherPoint, point + otherPoint, type: type)
}
return self
}
}
// MARK: CGPoint helpers
private func +(a:CGPoint, b:CGPoint) -> CGPoint {
return CGPoint(x: a.x + b.x, y: a.y + b.y)
}
private func -(a:CGPoint, b:CGPoint) -> CGPoint {
return CGPoint(x: a.x - b.x, y: a.y - b.y)
}
// MARK: Command Builders
private typealias SVGCommandBuilder = ([CGFloat], SVGCommand?, Coordinates) -> SVGCommand
private func take (numbers: [CGFloat], stride: Int, coords: Coordinates, last: SVGCommand?, callback: SVGCommandBuilder) -> [SVGCommand] {
var out: [SVGCommand] = []
var lastCommand:SVGCommand? = last
let count = (numbers.count / stride) * stride
var nums:[CGFloat] = [0, 0, 0, 0, 0, 0];
for i in 0.stride(to: count, by: stride) {
for j in 0 ..< stride {
nums[j] = numbers[i + j]
}
lastCommand = callback(nums, lastCommand, coords)
out.append(lastCommand!)
}
return out
}
// MARK: Mm - Move
private func moveTo (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], type: .Move)
}
// MARK: Ll - Line
private func lineTo (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], type: .Line)
}
// MARK: Vv - Vertical Line
private func lineToVertical (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(coords == .Absolute ? last?.point.x ?? 0 : 0, numbers[0], type: .Line)
}
// MARK: Hh - Horizontal Line
private func lineToHorizontal (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], coords == .Absolute ? last?.point.y ?? 0 : 0, type: .Line)
}
// MARK: Qq - Quadratic Curve To
private func quadBroken (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3])
}
// MARK: Tt - Smooth Quadratic Curve To
private func quadSmooth (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
var lastControl = last?.control1 ?? CGPoint()
let lastPoint = last?.point ?? CGPoint()
if (last?.type ?? .Line) != .QuadCurve {
lastControl = lastPoint
}
var control = lastPoint - lastControl
if coords == .Absolute {
control = control + lastPoint
}
return SVGCommand(control.x, control.y, numbers[0], numbers[1])
}
// MARK: Cc - Cubic Curve To
private func cubeBroken (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5])
}
// MARK: Ss - Smooth Cubic Curve To
private func cubeSmooth (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
var lastControl = last?.control2 ?? CGPoint()
let lastPoint = last?.point ?? CGPoint()
if (last?.type ?? .Line) != .CubeCurve {
lastControl = lastPoint
}
var control = lastPoint - lastControl
if coords == .Absolute {
control = control + lastPoint
}
return SVGCommand(control.x, control.y, numbers[0], numbers[1], numbers[2], numbers[3])
}
// MARK: Zz - Close Path
private func close (numbers: [CGFloat], last: SVGCommand?, coords: Coordinates) -> SVGCommand {
return SVGCommand()
}
| mit | 44bc4bdb855e0c281f0ea5e08aa8159d | 30.306859 | 138 | 0.602053 | 3.888789 | false | false | false | false |
chronotruck/CTKFlagPhoneNumber | Sources/FPNCountryRepository.swift | 1 | 2525 | //
// FPNCountryRepository.swift
// FlagPhoneNumber
//
// Created by Aurelien on 21/11/2019.
//
import Foundation
open class FPNCountryRepository {
open var locale: Locale
open var countries: [FPNCountry] = []
public init(locale: Locale = Locale.current) {
self.locale = locale
countries = getAllCountries()
}
// Populates the metadata from the included json file resource
private func getAllCountries() -> [FPNCountry] {
let bundle: Bundle = Bundle.FlagPhoneNumber()
let resource: String = "countryCodes"
let jsonPath = bundle.path(forResource: resource, ofType: "json")
assert(jsonPath != nil, "Resource file is not found in the Bundle")
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath!))
assert(jsonPath != nil, "Resource file is not found")
var countries = [FPNCountry]()
do {
if let jsonObjects = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSArray {
for jsonObject in jsonObjects {
guard let countryObj = jsonObject as? NSDictionary else { return countries }
guard let code = countryObj["code"] as? String, let phoneCode = countryObj["dial_code"] as? String, let name = countryObj["name"] as? String else { return countries }
let country = FPNCountry(code: code, name: locale.localizedString(forRegionCode: code) ?? name, phoneCode: phoneCode)
countries.append(country)
}
}
} catch let error {
assertionFailure(error.localizedDescription)
}
return countries.sorted(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == ComparisonResult.orderedAscending })
}
private func getAllCountries(excluding countryCodes: [FPNCountryCode]) -> [FPNCountry] {
var allCountries = getAllCountries()
for countryCode in countryCodes {
allCountries.removeAll(where: { (country: FPNCountry) -> Bool in
return country.code == countryCode
})
}
return allCountries
}
private func getAllCountries(equalTo countryCodes: [FPNCountryCode]) -> [FPNCountry] {
let allCountries = getAllCountries()
var countries = [FPNCountry]()
for countryCode in countryCodes {
for country in allCountries {
if country.code == countryCode {
countries.append(country)
}
}
}
return countries
}
open func setup(with countryCodes: [FPNCountryCode]) {
countries = getAllCountries(equalTo: countryCodes)
}
open func setup(without countryCodes: [FPNCountryCode]) {
countries = getAllCountries(excluding: countryCodes)
}
}
| apache-2.0 | b5bcae66bec82421d52af464fb019390 | 27.693182 | 171 | 0.723168 | 3.896605 | false | false | false | false |
hamzamuhammad/bluchat | bluchat/bluchat/MPCManager.swift | 1 | 4281 | //
// MPCManager.swift
// bluchat
//
// Created by Hamza Muhammad on 8/3/16.
// Copyright © 2016 Hamza Muhammad. All rights reserved.
//
import UIKit
import MultipeerConnectivity
import JSQMessagesViewController
protocol MPCManagerDelegate {
func foundPeer()
func lostPeer()
func invitationWasReceived(fromPeer: String)
func connectedWithPeer(peerID: MCPeerID)
}
class MPCManager: NSObject, MCSessionDelegate, MCNearbyServiceBrowserDelegate, MCNearbyServiceAdvertiserDelegate {
var session: MCSession!
var peer: MCPeerID!
var browser: MCNearbyServiceBrowser!
var advertiser: MCNearbyServiceAdvertiser!
var foundPeers = [MCPeerID]()
var invitationHandler: ((Bool, MCSession)->Void)?
var delegate: MPCManagerDelegate?
override init() {
super.init()
peer = MCPeerID(displayName: UIDevice.currentDevice().name)
session = MCSession(peer: peer)
session.delegate = self
browser = MCNearbyServiceBrowser(peer: peer, serviceType: "bluchat-mpc")
browser.delegate = self
advertiser = MCNearbyServiceAdvertiser(peer: peer, discoveryInfo: nil, serviceType: "bluchat-mpc")
advertiser.delegate = self
}
func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
foundPeers.append(peerID)
delegate?.foundPeer()
}
func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
for (index, aPeer) in foundPeers.enumerate() {
if aPeer == peerID {
foundPeers.removeAtIndex(index)
break
}
}
delegate?.lostPeer()
}
func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError) {
print(error.localizedDescription)
}
func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {
let receivedMessage = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! JSQMessage
NSNotificationCenter.defaultCenter().postNotificationName("receivedMPCDataNotification", object: receivedMessage)
}
func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
}
func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
}
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
switch state {
case MCSessionState.Connected:
print("Connected to session: \(session)")
delegate?.connectedWithPeer(peerID)
case MCSessionState.Connecting:
print("Connecting to session: \(session)")
default:
print("Did not connect to session: \(session)")
}
}
func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool,
MCSession) -> Void) {
self.invitationHandler = invitationHandler
delegate?.invitationWasReceived(peerID.displayName)
}
func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) {
print(error.localizedDescription)
}
// may have to fix this method
func sendData(messageToSend sentMsg: JSQMessage, toPeer targetPeer: MCPeerID) -> Bool {
let dataToSend = NSKeyedArchiver.archivedDataWithRootObject(sentMsg)
let peersArray = NSArray(object: targetPeer)
do {
try session.sendData(dataToSend, toPeers: peersArray as! [MCPeerID], withMode: MCSessionSendDataMode.Reliable)
}
catch {
print("Error while sending data")
}
return true
}
}
| apache-2.0 | c6e02d206af37244f25daa14535c5794 | 32.700787 | 172 | 0.666121 | 5.536869 | false | false | false | false |
devinross/curry | Examples/Examples/CustomKeyboardViewController.swift | 1 | 1774 | //
// CustomKeyboardViewController.swift
// Created by Devin Ross on 9/12/16.
//
/*
curry || https://github.com/devinross/curry
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 CustomKeyboardViewController: UIViewController {
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.white
self.edgesForExtendedLayout = .bottom
let textField = UITextField(frame: CGRectMakeInset(0, 0, self.view.width, 100, 30, 20))
textField.autoresizingMask = [.flexibleWidth]
textField.backgroundColor = UIColor(white: 0.95, alpha: 1)
self.view.addSubview(textField)
let input = TKNumberInputView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 216))
input.textField = textField
textField.inputView = input
}
}
| mit | 8c2b7d4255e57d63286b7e9afc97a3e7 | 30.122807 | 95 | 0.769448 | 4.14486 | false | false | false | false |
ayvazj/BrundleflyiOS | Pod/Classes/BtfyAnimationView.swift | 1 | 15203 | /*
* Copyright (c) 2015 James Ayvaz
*
* 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 AVFoundation
public class BtfyAnimationView: UIView {
let kDebug = false // draw bounding boxes and green screens
var btfyStage : BtfyStage?
var viewMap : [String:UIView] = [:]
let stageView : UIView
// drawRect lays out a grid to help verify placement
// override public func drawRect(rect: CGRect) {
// let context = UIGraphicsGetCurrentContext()
//
// CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
// CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
// for var i = 0; i < 200; i++ {
// if i % 10 == 0 {
// CGContextSetLineWidth(context,2.0)
// CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
// }
// else {
// CGContextSetLineWidth(context,0.5)
// CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
//
// }
//
// CGContextMoveToPoint(context, CGFloat(i * 10), 0)
// CGContextAddLineToPoint(context, CGFloat(i * 10), 1000)
//
// CGContextMoveToPoint(context, 0, CGFloat(i * 10))
// CGContextAddLineToPoint(context, 1000, CGFloat(i * 10))
//
// CGContextStrokePath(context)
// }
// }
override init(frame: CGRect) {
self.stageView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
self.stageView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
super.init(coder: aDecoder)
setup()
}
private func setup() -> Void {
self.autoresizesSubviews = false
self.autoresizingMask = UIViewAutoresizing.None
}
public func load(filename: String, ofType: String, inDirectory: String, complete: () -> Void) -> Void {
if (!filename.isEmpty) {
do {
let stage = try BtfyLoader.bundleFileAsStage(filename, ofType: ofType, inDirectory: inDirectory)
initStage(stage!, complete: complete)
}
catch BtfyError.ParseError(let msg) {
print(msg)
}
catch let error as NSError {
print(error.localizedDescription)
}
catch _ {
}
}
if kDebug {
self.backgroundColor = UIColor.greenColor()
}
}
private func initStage(stage: BtfyStage, complete: () -> Void ) -> Void {
for subview in self.subviews {
subview.removeFromSuperview()
}
self.btfyStage = stage
self.viewMap = [:]
self.updateBounds()
for var i = 0; i < stage.animationGroups.count; ++i {
let animationGroup = stage.animationGroups[i]
var view : UIView?
if let text = animationGroup.text {
view = UILabel()
(view as? UILabel)?.text = text
} else {
if let backgroundImage = animationGroup.backgroundImage {
if backgroundImage.hasSuffix(".mp4") {
if let videoUrl = NSBundle.mainBundle().URLForResource("btfy/\(backgroundImage)", withExtension: "") {
view = BtfyVideoView()
(view as! BtfyVideoView).url = videoUrl
}
}
else {
if let imagePath = NSBundle.mainBundle().pathForResource("btfy/\(backgroundImage)") {
if (NSFileManager.defaultManager().fileExistsAtPath(imagePath)) {
let img = UIImage(data: UIImagePNGRepresentation(UIImage(contentsOfFile: imagePath)!)!)
view = UIImageView(image: img)
view!.contentMode = .ScaleToFill
}
}
}
} else if let shape = animationGroup.shape {
if shape.name == BtfyShape.Name.ellipse {
view = BtfyEllipseView()
}
else {
view = BtfyRectangleView()
}
} else {
view = BtfyRectangleView()
}
}
view!.animationGroup = animationGroup
if (kDebug) {
//view!.layer.masksToBounds = false
view!.layer.borderColor = UIColor.redColor().CGColor
view!.layer.borderWidth = 1
}
initView(view!, animationGroup: animationGroup)
}
complete()
}
private func animateView(view : UIView) {
if let animationGroup = view.animationGroup {
playAnimation(view, animationGroup: animationGroup)
}
for sv in view.subviews {
animateView(sv)
}
}
public func playAnimation() {
for subview in self.stageView.subviews {
animateView(subview)
}
}
private func playAnimation(subview : UIView, animationGroup: BtfyAnimationGroup) -> Void {
guard animationGroup.duration > 0 else {
return;
}
var animations :[CAAnimation] = []
for ani in animationGroup.animations {
switch ani.property {
case .Opacity:
var values : [Double] = []
var keys : [CGFloat] = []
var timings : [CAMediaTimingFunction] = []
for keyframe in ani.keyframes {
let val = keyframe.val as! Double
values.append(val)
keys.append(CGFloat(keyframe.index))
timings.append(keyframe.timingFunction)
} // for keyframe in ani.keyframes {
let opacityAnim = createKeyFrame(
"opacity",
values: values,
keyTimes: keys,
timings: timings,
ani: ani)
animations.append(opacityAnim)
break
case .Position:
var values : [NSValue] = []
var keys : [CGFloat] = []
var timings : [CAMediaTimingFunction] = []
for keyframe in ani.keyframes {
let val = keyframe.val as! BtfyPoint
values.append(NSValue(CGPoint: CGPoint(x: xRel(val.x), y: yRel(val.y))))
keys.append(CGFloat(keyframe.index))
timings.append(keyframe.timingFunction)
} // for keyframe in ani.keyframes {
let posAnim = createKeyFrame(
"position",
values: values,
keyTimes: keys,
timings: timings,
ani: ani)
animations.append(posAnim)
break
case .Scale:
var values : [NSValue] = []
var keys : [CGFloat] = []
var timings : [CAMediaTimingFunction] = []
for keyframe in ani.keyframes {
let val = keyframe.val as! BtfyPoint
values.append(NSValue(CGPoint: CGPoint(x: val.x, y: val.y)))
keys.append(CGFloat(keyframe.index))
timings.append(keyframe.timingFunction)
} // for keyframe in ani.keyframes {
let scaleAnim = createKeyFrame(
"transform.scale",
values: values,
keyTimes: keys,
timings: timings,
ani: ani)
animations.append(scaleAnim)
break
case .Rotation:
var values : [Double] = []
var keys : [CGFloat] = []
var timings : [CAMediaTimingFunction] = []
for keyframe in ani.keyframes {
let val = (keyframe.val as! Double).degreesToRadians
values.append(val)
keys.append(CGFloat(keyframe.index))
timings.append(keyframe.timingFunction)
} // for keyframe in ani.keyframes {
let rotationAnim = createKeyFrame(
"transform.rotation",
values: values,
keyTimes: keys,
timings: timings,
ani: ani)
animations.append(rotationAnim)
break
}
let animGroup = CAAnimationGroup()
animGroup.duration = NSTimeInterval(animationGroup.duration)
animGroup.repeatCount = 1
animGroup.animations = animations
animGroup.fillMode = kCAFillModeForwards
animGroup.removedOnCompletion = false
subview.layer.addAnimation(animGroup, forKey: animationGroup.id)
}
}
private func createKeyFrame(
keyPath: String,
values: [AnyObject],
keyTimes: [CGFloat],
timings: [CAMediaTimingFunction],
ani: BtfyAnimation) -> CAKeyframeAnimation {
let anim = CAKeyframeAnimation(keyPath: keyPath)
anim.beginTime = ani.delay
anim.values = values
anim.keyTimes = keyTimes
anim.duration = NSTimeInterval(ani.duration)
anim.additive = false
anim.timingFunctions = timings
anim.fillMode = kCAFillModeForwards
anim.removedOnCompletion = false
return anim
}
private func updateBounds() {
if let stage = self.btfyStage {
let size = stage.size;
self.addSubview(self.stageView)
self.setNeedsLayout()
self.layoutIfNeeded()
var resolveSizeWidth = Double(self.bounds.width)
var resolveSizeHeight = Double(self.bounds.height)
let resolvedRatio = resolveSizeWidth / resolveSizeHeight
let sizeRatio = size.width / size.height
if resolvedRatio > sizeRatio {
resolveSizeWidth = round( resolveSizeHeight * sizeRatio)
} else if (resolvedRatio < sizeRatio) {
resolveSizeHeight = round( resolveSizeWidth / sizeRatio)
}
self.stageView.transform = CGAffineTransformIdentity
if kDebug {
self.stageView.backgroundColor = UIColor.orangeColor()
}
self.stageView.bounds = CGRect(x: 0, y: 0, width: resolveSizeWidth, height: resolveSizeHeight)
self.stageView.center = self.convertPoint(self.center, fromCoordinateSpace: self.superview!)
self.stageView.clipsToBounds = true
self.stageView.setNeedsLayout()
self.stageView.layoutIfNeeded()
}
}
private func initView(view: UIView, animationGroup : BtfyAnimationGroup) {
let iv = animationGroup.initialValues
self.viewMap[animationGroup.id] = view
if let parentId = animationGroup.parentId, parentView = self.viewMap[parentId] {
parentView.addSubview(view)
}
else {
self.stageView.addSubview(view)
}
view.clipsToBounds = false
view.autoresizingMask = UIViewAutoresizing.None
view.autoresizesSubviews = false
view.backgroundColor = UIColor(btfyColor: iv.backgroundColor)
view.bounds = CGRect(x:0, y: 0, width: relWidth(iv.size.width), height: relHeight(iv.size.height))
view.center = CGPoint(x: xRel(iv.position.x), y: yRel(iv.position.y))
view.layer.anchorPoint = CGPoint(x: iv.anchorPoint.x, y: iv.anchorPoint.y)
view.alpha = CGFloat(iv.opacity)
var tMatrix = CGAffineTransformIdentity
// tMatrix = CGAffineTransformTranslate(tMatrix, CGFloat(xRel(iv.position.x)), CGFloat(yRel(iv.position.y)))
tMatrix = CGAffineTransformRotate(tMatrix, (CGFloat(iv.rotation.degreesToRadians)))
tMatrix = CGAffineTransformScale(tMatrix, CGFloat(iv.scale.x), CGFloat(iv.scale.y))
view.transform = tMatrix
if let labelview = view as? UILabel {
labelview.textColor = UIColor(btfyColor: iv.textColor)
labelview.font = UIFont(name: BtfyJson.parseTypeface(iv.textStyle), size: CGFloat(relWidth(iv.fontSize!)))
labelview.textAlignment = iv.textAlign
labelview.numberOfLines = 0
labelview.lineBreakMode = .ByWordWrapping
}
}
private func relWidth(width: Double) -> Double {
return (width * Double(self.stageView.bounds.width))
}
private func relHeight(height: Double) -> Double {
return (height * Double(self.stageView.bounds.height))
}
private func xRel(x: Double) -> Double {
return (x * Double(self.stageView.bounds.width ))
}
private func yRel(y: Double) -> Double {
return (y * Double(self.stageView.bounds.height))
}
func deviceOrientationDidChange() -> Void {
setNeedsLayout()
}
}
| mit | e9b7bca6dd45f10829d30b61d3bb217a | 36.818408 | 126 | 0.527988 | 5.393047 | false | false | false | false |
ObjectAlchemist/OOUIKit | Sources/_UIKitDelegate/UITableViewDataSource/ConfiguringAnIndex/UITableViewDataSourceIndex.swift | 1 | 2322 | //
// UITableViewDataSourceIndex.swift
// OOUIKit
//
// Created by Karsten Litsche on 04.11.17.
//
import UIKit
import OOBase
public final class UITableViewDataSourceIndex: NSObject, UITableViewDataSource {
// MARK: - init
fileprivate init(
sectionIndexTitles: @escaping (UITableView) -> [OOString]? = { _ in nil },
sectionForSectionIndexTitle: @escaping (UITableView, String, Int) -> OOInt = { _,_,_ in IntConst(0) }
) {
self.sectionIndexTitles = sectionIndexTitles
self.sectionForSectionIndexTitle = sectionForSectionIndexTitle
super.init()
}
// MARK: - protocol: UITableViewDataSource
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("This object do not provide configuration informations!")
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fatalError("This object do not provide configuration informations!")
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sectionIndexTitles(tableView)?.map { $0.value }
}
public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return sectionForSectionIndexTitle(tableView, title, index).value
}
// MARK: - private
private let sectionIndexTitles: (UITableView) -> [OOString]?
private let sectionForSectionIndexTitle: (UITableView, String, Int) -> OOInt
}
public extension UITableViewDataSourceIndex {
convenience init(
sectionIndexTitles: @escaping (UITableView) -> [OOString],
sectionForSectionIndexTitle: @escaping (UITableView, String, Int) -> OOInt = { _,_,_ in IntConst(0) }
) {
let sectionIndexTitles: (UITableView) -> [OOString]? = sectionIndexTitles
self.init(sectionIndexTitles: sectionIndexTitles, sectionForSectionIndexTitle: sectionForSectionIndexTitle)
}
convenience init(
sectionForSectionIndexTitle: @escaping (UITableView, String, Int) -> OOInt = { _,_,_ in IntConst(0) }
) {
self.init(sectionIndexTitles: { _ in nil }, sectionForSectionIndexTitle: sectionForSectionIndexTitle)
}
}
| mit | 2f77a9690887cb23400b5e43bc536ae8 | 34.723077 | 118 | 0.68174 | 5.325688 | false | false | false | false |
TouchInstinct/LeadKit | TINetworking/Sources/Request/EndpointRequest+Serialization.swift | 1 | 3062 | //
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
public extension EndpointRequest {
func serialize<Serializer: BodySerializer>(using serializer: Serializer,
defaultServer: Server) throws -> SerializedRequest where Serializer.Body == Body {
let baseUrl = try (server ?? defaultServer).url(using: customServerVariables)
let path = PathParameterEncoding(templateUrl: templatePath).encode(parameters: pathParameters)
let (contentType, bodyData) = try serializer.serialize(body: body)
let serializedQueryParameters = QueryStringParameterEncoding().encode(parameters: queryParameters)
var serializedHeaderParameters: [String: String]
if let customHeaderParameters = headerParameters {
serializedHeaderParameters = HeaderParameterEncoding().encode(parameters: customHeaderParameters)
} else {
serializedHeaderParameters = [:]
}
serializedHeaderParameters[HTTPHeader.contentType(contentType).name] = contentType
let cookies: [HTTPCookie]
if let domain = baseUrl.host {
cookies = cookieParameters.compactMap { key, value in
HTTPCookie(properties: [
.name : key,
.value: value,
.domain: domain,
.path: path
])
}
} else {
cookies = []
}
return SerializedRequest(baseURL: baseUrl,
path: path,
method: method,
bodyData: bodyData,
queryParameters: serializedQueryParameters,
headers: serializedHeaderParameters,
cookies: cookies,
acceptableStatusCodes: acceptableStatusCodes)
}
}
| apache-2.0 | 45944874aaee2bb3086bbdf79ac34312 | 42.742857 | 129 | 0.637165 | 5.537071 | false | false | false | false |
nyjsl/Hank | DateUtils.swift | 1 | 2165 | //
// DateUtils.swift
// Gank
//
// Created by 魏星 on 16/7/17.
// Copyright © 2016年 wx. All rights reserved.
//
import Foundation
public class DateUtils{
static let DATE_FORMATTER = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
public static func stringToNSDate(dateString: String,formatter: String = DATE_FORMATTER) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = formatter
return dateFormatter.dateFromString( dateString )!
}
public static func nsDateToString(date: NSDate,formatter: String = "yyyy-MM-dd HH:mm:ss" ) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = formatter
return dateFormatter.stringFromDate(date)
}
public static func areDatesSameDay(dateOne:NSDate,dateTwo:NSDate) -> Bool {
let calender = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [.Day, .Month, .Year]
let compOne: NSDateComponents = calender.components(flags, fromDate: dateOne)
let compTwo: NSDateComponents = calender.components(flags, fromDate: dateTwo);
return (compOne.day == compTwo.day && compOne.month == compTwo.month && compOne.year == compTwo.year);
}
public static func getYMDTupleArray() ->[(String,String,String)]{
var date = NSDate()
var ymdTuples:[(String,String,String)] = []
for _ in 0...4{
date = getDateYesterday(date)
ymdTuples += [getYMDTypleFromDate(date)]
}
return ymdTuples
}
private static func getDateYesterday(date: NSDate) -> NSDate{
let calender = NSCalendar.currentCalendar()
return calender.dateByAddingUnit(.Day, value: -1, toDate: date, options: .MatchStrictly)!
}
private static func getYMDTypleFromDate(date: NSDate) -> (String,String,String){
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
let datesStr = formatter.stringFromDate(date)
let dates = datesStr.componentsSeparatedByString("/")
return (dates[0],dates[1],dates[2])
}
}
| mit | 53516ff2ea56c1437633449049b5a8e3 | 34.377049 | 110 | 0.642261 | 4.359596 | false | false | false | false |
cp3hnu/CPImageViewer | Classes/CPImageViewerAnimator.swift | 1 | 3033 | //
// BaseViewController.swift
// CPImageViewer
//
// Created by ZhaoWei on 16/2/27.
// Copyright © 2016年 cp3hnu. All rights reserved.
//
import UIKit
public final class CPImageViewerAnimator: NSObject, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate {
private let animator = CPImageViewerAnimationTransition()
private let interativeAnimator = CPImageViewerInteractiveTransition()
// MARK: - UIViewControllerTransitioningDelegate
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let sourceViewer = source as? CPImageViewerProtocol,
let _ = presenting as? CPImageViewerProtocol,
let imageViewer = presented as? CPImageViewer {
if let navi = presenting as? UINavigationController {
navi.animationImageView = sourceViewer.animationImageView
} else if let tabBarVC = presenting as? UITabBarController {
tabBarVC.animationImageView = sourceViewer.animationImageView
}
interativeAnimator.wireToImageViewer(imageViewer)
interativeAnimator.isPresented = true
animator.isBack = false
return animator
}
return nil
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed is CPImageViewer {
animator.isBack = true
return animator
}
return nil
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interativeAnimator.interactionInProgress ? interativeAnimator : nil
}
// MARK: - UINavigationDelegate
public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .push,
fromVC is CPImageViewerProtocol,
let imageViewer = toVC as? CPImageViewer {
interativeAnimator.wireToImageViewer(imageViewer)
interativeAnimator.isPresented = false
animator.isBack = false
return animator
} else if operation == .pop,
toVC is CPImageViewerProtocol,
fromVC is CPImageViewer {
animator.isBack = true
return animator
}
return nil
}
public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interativeAnimator.interactionInProgress ? interativeAnimator : nil
}
}
| mit | 1be99aa3fb7f4b51384aab7dc60bb464 | 40.506849 | 254 | 0.70264 | 6.530172 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/Scenes/Deal/CustomView/DealSingleRowCell.swift | 4 | 1773 | //
// DealSingleRowCell.swift
// iOSStar
//
// Created by J-bb on 17/5/23.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class DealSingleRowCell: UITableViewCell {
var dealType:[Int:String] = [-1:"转让",1:"求购"]
var dealStatus:[Int32:String] = [-2:"委托失败",0:"委托中", 1:"委托中", 2:"委托成功"]
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var codeLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var thirdLabel: UILabel!
@IBOutlet weak var lastLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func setData(model:EntrustListModel) {
StartModel.getStartName(startCode: model.symbol) { (response) in
if let star = response as? StartModel {
self.nameLabel.text = star.name
} else {
self.nameLabel.text = ""
}
}
codeLabel.text = model.symbol
// secondLabel.text = "\(model.amount)/\(model.rtAmount)"
secondLabel.text = "\(model.amount)"
thirdLabel.text = String(format: "%.2f", model.openPrice)
// if model.handle == 0 {
// lastLabel.text = dealType[model.buySell]
// } else {
// lastLabel.text = dealStatus[model.handle]
// }
lastLabel.numberOfLines = 0
lastLabel.text = "\(dealType[model.buySell]!)\n\(dealStatus[model.handle]!)"
lastLabel.textColor = UIColor(hexString: "666666")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | 75e5027f91f6a7ac676d5f7e5b268564 | 27.9 | 84 | 0.585928 | 4.06089 | false | false | false | false |
zisko/swift | stdlib/public/core/CollectionOfOne.swift | 1 | 4573 | //===--- CollectionOfOne.swift - A Collection with one element ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// An iterator that produces one or fewer instances of `Element`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct IteratorOverOne<Element> {
@_versioned // FIXME(sil-serialize-all)
internal var _elements: Element?
/// Construct an instance that generates `_element!`, or an empty
/// sequence if `_element == nil`.
@_inlineable // FIXME(sil-serialize-all)
public // @testable
init(_elements: Element?) {
self._elements = _elements
}
}
extension IteratorOverOne: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
let result = _elements
_elements = nil
return result
}
}
/// A collection containing a single element of type `Element`.
@_fixed_layout // FIXME(sil-serialize-all)
public struct CollectionOfOne<Element> {
@_versioned // FIXME(sil-serialize-all)
internal var _element: Element
/// Creates an instance containing just `element`.
@_inlineable // FIXME(sil-serialize-all)
public init(_ element: Element) {
self._element = element
}
}
extension CollectionOfOne: RandomAccessCollection, MutableCollection {
public typealias Index = Int
public typealias Indices = Range<Int>
/// The position of the first element.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Int {
return 0
}
/// The "past the end" position---that is, the position one greater than the
/// last valid subscript argument.
///
/// In a `CollectionOfOne` instance, `endIndex` is always identical to
/// `index(after: startIndex)`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Int {
return 1
}
/// Always returns `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Int) -> Int {
_precondition(i == startIndex)
return endIndex
}
/// Always returns `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Int) -> Int {
_precondition(i == endIndex)
return startIndex
}
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable // FIXME(sil-serialize-all)
public func makeIterator() -> IteratorOverOne<Element> {
return IteratorOverOne(_elements: _element)
}
/// Accesses the element at `position`.
///
/// - Precondition: `position == 0`.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Int) -> Element {
get {
_precondition(position == 0, "Index out of range")
return _element
}
set {
_precondition(position == 0, "Index out of range")
_element = newValue
}
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Int>)
-> Slice<CollectionOfOne<Element>> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
set {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
_precondition(bounds.count == newValue.count,
"CollectionOfOne can't be resized")
if let newElement = newValue.first {
_element = newElement
}
}
}
/// The number of elements (always one).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return 1
}
}
extension CollectionOfOne : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
@_inlineable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "CollectionOfOne(\(String(reflecting: _element)))"
}
}
extension CollectionOfOne : CustomReflectable {
@_inlineable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(self, children: ["element": _element])
}
}
| apache-2.0 | bdbdfac9ffbcb6db41835be20c513203 | 29.085526 | 80 | 0.659961 | 4.269841 | false | false | false | false |
SuPair/firefox-ios | Storage/DiskImageStore.swift | 7 | 3885 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import UIKit
import Deferred
import XCGLogger
private var log = XCGLogger.default
private class DiskImageStoreErrorType: MaybeErrorType {
let description: String
init(description: String) {
self.description = description
}
}
/**
* Disk-backed key-value image store.
*/
open class DiskImageStore {
fileprivate let files: FileAccessor
fileprivate let filesDir: String
fileprivate let queue = DispatchQueue(label: "DiskImageStore")
fileprivate let quality: CGFloat
fileprivate var keys: Set<String>
required public init(files: FileAccessor, namespace: String, quality: Float) {
self.files = files
self.filesDir = try! files.getAndEnsureDirectory(namespace)
self.quality = CGFloat(quality)
// Build an in-memory set of keys from the existing images on disk.
var keys = [String]()
if let fileEnumerator = FileManager.default.enumerator(atPath: filesDir) {
for file in fileEnumerator {
keys.append(file as! String)
}
}
self.keys = Set(keys)
}
/// Gets an image for the given key if it is in the store.
open func get(_ key: String) -> Deferred<Maybe<UIImage>> {
return deferDispatchAsync(queue) { () -> Deferred<Maybe<UIImage>> in
if !self.keys.contains(key) {
return deferMaybe(DiskImageStoreErrorType(description: "Image key not found"))
}
let imagePath = URL(fileURLWithPath: self.filesDir).appendingPathComponent(key)
if let data = try? Data(contentsOf: imagePath),
let image = UIImage.imageFromDataThreadSafe(data) {
return deferMaybe(image)
}
return deferMaybe(DiskImageStoreErrorType(description: "Invalid image data"))
}
}
/// Adds an image for the given key.
/// This put is asynchronous; the image is not recorded in the cache until the write completes.
/// Does nothing if this key already exists in the store.
@discardableResult open func put(_ key: String, image: UIImage) -> Success {
return deferDispatchAsync(queue) { () -> Success in
if self.keys.contains(key) {
return deferMaybe(DiskImageStoreErrorType(description: "Key already in store"))
}
let imageURL = URL(fileURLWithPath: self.filesDir).appendingPathComponent(key)
if let data = UIImageJPEGRepresentation(image, self.quality) {
do {
try data.write(to: imageURL, options: .noFileProtection)
self.keys.insert(key)
return succeed()
} catch {
log.error("Unable to write image to disk: \(error)")
}
}
return deferMaybe(DiskImageStoreErrorType(description: "Could not write image to file"))
}
}
/// Clears all images from the cache, excluding the given set of keys.
open func clearExcluding(_ keys: Set<String>) -> Success {
return deferDispatchAsync(queue) { () -> Success in
let keysToDelete = self.keys.subtracting(keys)
for key in keysToDelete {
let url = URL(fileURLWithPath: self.filesDir).appendingPathComponent(key)
do {
try FileManager.default.removeItem(at: url)
} catch {
log.warning("Failed to remove DiskImageStore item at \(url.absoluteString): \(error)")
}
}
self.keys = self.keys.intersection(keys)
return succeed()
}
}
}
| mpl-2.0 | 82bde562f9923fb5f5f36202007b761e | 36.355769 | 106 | 0.613385 | 4.838107 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/General/BaseCollectionViewController.swift | 1 | 927 | //
// BaseCollectionViewController.swift
// Habitica
//
// Created by Phillip Thelen on 06.05.19.
// Copyright © 2019 HabitRPG Inc. All rights reserved.
//
import Foundation
class BaseCollectionViewController: HRPGBaseCollectionViewController, Themeable {
override func viewDidLoad() {
super.viewDidLoad()
ThemeService.shared.addThemeable(themable: self)
}
func applyTheme(theme: Theme) {
if #available(iOS 13.0, *) {
if ThemeService.shared.themeMode == "dark" {
self.overrideUserInterfaceStyle = .dark
} else if ThemeService.shared.themeMode == "light" {
self.overrideUserInterfaceStyle = .light
} else {
self.overrideUserInterfaceStyle = .unspecified
}
}
collectionView.backgroundColor = theme.windowBackgroundColor
collectionView.reloadData()
}
}
| gpl-3.0 | e6491707525995efc8a259b0446a6adf | 28.870968 | 81 | 0.634989 | 5.173184 | false | false | false | false |
sheepy1/SelectionOfZhihu | SelectionOfZhihu/TopUserCell.swift | 1 | 1161 | //
// TopUserCell.swift
// SelectionOfZhihu
//
// Created by 杨洋 on 16/1/13.
// Copyright © 2016年 Sheepy. All rights reserved.
//
import UIKit
class TopUserCell: UITableViewCell, ViewModelType {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var signatureLabel: UILabel!
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
typealias ModelType = (user: TopUserModel, index: Int)
func bindModel(model: ModelType) {
let user = model.user
let index = model.index
avatarImageView.setImageWithId(index, imagePath: user.avatar)
nameLabel.text = user.name
signatureLabel.text = user.signature
if user.agree > 0 {
numberLabel.text = "\(user.agree)"
itemLabel.text = SortOrderItem.Agree.associatedValue.desc
} else if user.follower > 0 {
numberLabel.text = "\(user.follower)"
itemLabel.text = SortOrderItem.Follower.associatedValue.desc
}
}
}
| mit | f3936523e50b052ef2030b49363c81d1 | 24.644444 | 72 | 0.612652 | 4.691057 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/SignUpFlow/CountryPickerView.swift | 1 | 2301 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import Foundation
import Localization
import SwiftUI
import UIComponentsKit
public struct CountryPickerView: View {
private typealias LocalizedStrings = LocalizationConstants.Authentication.CountryAndStatePickers
static let restrictedCountryIdentifiers: Set<String> = ["CU", "IR", "KP", "SY"]
public static let countries: [SearchableItem<String>] = Locale.isoRegionCodes
.filter { !restrictedCountryIdentifiers.contains($0) }
.compactMap { code -> SearchableItem? in
guard let countryName = Locale.current.localizedString(forRegionCode: code) else {
return nil
}
return SearchableItem(
id: code,
title: countryName
)
}
.sorted {
$0.title.localizedCompare($1.title) == .orderedAscending
}
@Binding private var selectedItem: SearchableItem<String>?
private var sections: [SearchableItemPicker<String>.SearchableSection] {
var sections: [SearchableItemPicker<String>.SearchableSection] = []
if let currentRegionCode = Locale.current.regionCode,
!Self.restrictedCountryIdentifiers.contains(currentRegionCode),
let currentRegionName = Locale.current.localizedString(forRegionCode: currentRegionCode)
{
sections.append(
.init(
title: LocalizedStrings.suggestedSelectionTitle,
items: [SearchableItem(id: currentRegionCode, title: currentRegionName)]
)
)
}
sections.append(
.init(
title: LocalizedStrings.countriesSectionTitle,
items: CountryPickerView.countries
)
)
return sections
}
public init(selectedItem: Binding<SearchableItem<String>?>) {
_selectedItem = selectedItem
}
public var body: some View {
SearchableItemPicker(
sections: sections,
selectedItem: $selectedItem,
cancelButtonTitle: LocalizationConstants.searchCancelButtonTitle,
searchPlaceholder: LocalizationConstants.searchPlaceholder
)
}
}
| lgpl-3.0 | d6bb42bc81153cf7235b5175c6690c72 | 32.333333 | 100 | 0.639565 | 5.665025 | false | false | false | false |
eBay/NMessenger | nMessenger/Source/MessageNodes/MessageCell/MessageNode.swift | 2 | 11050 | //
// Copyright (c) 2016 eBay Software Foundation
//
// 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 AsyncDisplayKit
//MARK: MessageNode
/**
Base message class for N Messenger. Extends GeneralMessengerCell. Holds one message
*/
open class MessageNode: GeneralMessengerCell {
// MARK: Public Variables
open weak var delegate: MessageCellProtocol?
/** ASDisplayNode as the content of the cell*/
open var contentNode: ContentNode? {
didSet {
self.setNeedsLayout()
}
}
/** ASDisplayNode as the avatar of the cell*/
open var avatarNode: ASDisplayNode? {
didSet {
self.setNeedsLayout()
}
}
/** ASDisplayNode as the header of the cell*/
open var headerNode: ASDisplayNode? {
didSet {
self.setNeedsLayout()
}
}
/** ASDisplayNode as the footer of the cell*/
open var footerNode: ASDisplayNode? {
didSet {
self.setNeedsLayout()
}
}
/**
Spacing around the avatar. Defaults to UIEdgeInsetsMake(0, 0, 0, 10)
*/
open var avatarInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10) {
didSet {
self.setNeedsLayout()
}
}
/** Message offset from edge (edge->offset->message content). Defaults to 10*/
open var messageOffset: CGFloat = 10 {
didSet {
self.setNeedsLayout()
}
}
/** Spacing under the header. Defaults to 10*/
open var headerSpacing: CGFloat = 10 {
didSet {
self.setNeedsLayout()
}
}
/** Spacing above the footer. Defaults to 10*/
open var footerSpacing: CGFloat = 10 {
didSet {
self.setNeedsLayout()
}
}
/** Message width in relation to the NMessenger container size. **Warning:** Raises a fatal error if this value is not within the range. Defaults to 2/3*/
open var maxWidthRatio: CGFloat = 2/3 {
didSet {
if self.maxWidthRatio > 1 || self.maxWidthRatio < 0 {fatalError("maxWidthRatio expects a value between 0 and 1!")}
self.setNeedsLayout()
}
}
/** Max message height. Defaults to 100000.0 */
open var maxHeight: CGFloat = 10000.0 {
didSet {
self.setNeedsLayout()
}
}
/** Bool if the cell is an incoming or out going message cell*/
open override var isIncomingMessage:Bool {
didSet {
self.contentNode?.isIncomingMessage = isIncomingMessage
}
}
// MARK: Private Variables
/** Button node to handle avatar click*/
fileprivate var avatarButtonNode: ASControlNode = ASControlNode()
// MARK: Initializers
/**
Initialiser for the cell
*/
public init(content: ContentNode) {
super.init()
self.setupMessageNode(withContent: content)
}
// MARK: Initializer helper method
/**
Creates background node and avatar node if they do not exist
*/
fileprivate func setupMessageNode(withContent content: ContentNode)
{
self.avatarButtonNode.addTarget(self, action: #selector(MessageNode.avatarClicked), forControlEvents: .touchUpInside)
self.avatarButtonNode.isExclusiveTouch = true
self.contentNode = content
self.automaticallyManagesSubnodes = true
}
// MARK: Override AsycDisaplyKit Methods
func createSpacer() -> ASLayoutSpec{
let spacer = ASLayoutSpec()
spacer.style.flexGrow = 0
spacer.style.flexShrink = 0
spacer.style.minHeight = ASDimension(unit: .points, value: 0)
return spacer
}
/**
Overriding layoutSpecThatFits to specifiy relatiohsips between elements in the cell
*/
override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
var layoutSpecs: ASLayoutSpec!
//location dependent on sender
let justifyLocation = isIncomingMessage ? ASStackLayoutJustifyContent.start : ASStackLayoutJustifyContent.end
if let tmpAvatar = self.avatarNode {
let tmpSizeMeasure = tmpAvatar.layoutThatFits(ASSizeRange(min: CGSize.zero, max: constrainedSize.max))
let avatarSizeLayout = ASAbsoluteLayoutSpec()
avatarSizeLayout.sizing = .sizeToFit
avatarSizeLayout.children = [tmpAvatar]
self.avatarButtonNode.style.width = ASDimension(unit: .points, value: tmpSizeMeasure.size.width)
self.avatarButtonNode.style.height = ASDimension(unit: .points, value: tmpSizeMeasure.size.height)
let avatarButtonSizeLayout = ASAbsoluteLayoutSpec()
avatarButtonSizeLayout.sizing = .sizeToFit
avatarButtonSizeLayout.children = [self.avatarButtonNode]
let avatarBackStack = ASBackgroundLayoutSpec(child: avatarButtonSizeLayout, background: avatarSizeLayout)
let width = constrainedSize.max.width - tmpSizeMeasure.size.width - self.cellPadding.left - self.cellPadding.right - avatarInsets.left - avatarInsets.right - self.messageOffset
contentNode?.style.maxWidth = ASDimension(unit: .points, value: width * self.maxWidthRatio)
contentNode?.style.maxHeight = ASDimension(unit: .points, value: self.maxHeight)
let contentSizeLayout = ASAbsoluteLayoutSpec()
contentSizeLayout.sizing = .sizeToFit
contentSizeLayout.children = [self.contentNode!]
let ins = ASInsetLayoutSpec(insets: self.avatarInsets, child: avatarBackStack)
let cellOrientation = isIncomingMessage ? [ins, contentSizeLayout] : [contentSizeLayout,ins]
layoutSpecs = ASStackLayoutSpec(direction: .horizontal, spacing: 0, justifyContent: justifyLocation, alignItems: .end, children: cellOrientation)
contentSizeLayout.style.flexShrink = 1
} else {
let width = constrainedSize.max.width - self.cellPadding.left - self.cellPadding.right - self.messageOffset
contentNode?.style.maxWidth = ASDimension(unit: .points, value: width * self.maxWidthRatio)
contentNode?.style.maxHeight = ASDimension(unit: .points, value: self.maxHeight)
contentNode?.style.flexGrow = 1
let contentSizeLayout = ASAbsoluteLayoutSpec()
contentSizeLayout.sizing = .sizeToFit
contentSizeLayout.children = [self.contentNode!]
layoutSpecs = ASStackLayoutSpec(direction: .horizontal, spacing: 0, justifyContent: justifyLocation, alignItems: .end, children: [createSpacer(), contentSizeLayout])
contentSizeLayout.style.flexShrink = 1
}
if let headerNode = self.headerNode
{
layoutSpecs = ASStackLayoutSpec(direction: .vertical, spacing: self.headerSpacing, justifyContent: .start, alignItems: isIncomingMessage ? .start : .end, children: [headerNode, layoutSpecs])
}
if let footerNode = self.footerNode {
layoutSpecs = ASStackLayoutSpec(direction: .vertical, spacing: self.footerSpacing, justifyContent: .start, alignItems: isIncomingMessage ? .start : .end, children: [layoutSpecs, footerNode])
}
let cellOrientation = isIncomingMessage ? [createSpacer(), layoutSpecs!] : [layoutSpecs!, createSpacer()]
let layoutSpecs2 = ASStackLayoutSpec(direction: .horizontal, spacing: self.messageOffset, justifyContent: justifyLocation, alignItems: .end, children: cellOrientation)
return ASInsetLayoutSpec(insets: self.cellPadding, child: layoutSpecs2)
}
// MARK: UILongPressGestureRecognizer Override Methods
/**
Overriding didLoad to add UILongPressGestureRecognizer to view
*/
override open func didLoad() {
super.didLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(messageNodeLongPressSelector(_:)))
view.addGestureRecognizer(longPressRecognizer)
}
/**
Overriding canBecomeFirstResponder to make cell first responder
*/
override open func canBecomeFirstResponder() -> Bool {
return true
}
/**
Overriding touchesBegan to make to close UIMenuController
*/
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if UIMenuController.shared.isMenuVisible == true {
UIMenuController.shared.setMenuVisible(false, animated: true)
}
}
/**
Overriding touchesEnded to make to handle events with UIMenuController
*/
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if UIMenuController.shared.isMenuVisible == false {
}
}
/**
Overriding touchesCancelled to make to handle events with UIMenuController
*/
override open func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
if UIMenuController.shared.isMenuVisible == false {
}
}
// MARK: UILongPressGestureRecognizer Selector Methods
/**
UILongPressGestureRecognizer selector
- parameter recognizer: Must be an UITapGestureRecognizer.
Can be be overritten when subclassed
*/
open func messageNodeLongPressSelector(_ recognizer: UITapGestureRecognizer) {
contentNode?.messageNodeLongPressSelector(recognizer)
}
}
/** Delegate functions extension */
extension MessageNode {
/**
Notifies the delegate that the avatar was clicked
*/
public func avatarClicked()
{
self.delegate?.avatarClicked?(self)
}
}
| mit | 584ae79c88d57e56541a7ce99a060a05 | 37.908451 | 463 | 0.657285 | 5.180497 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Utility/ReachabilityUtils+OnlineActions.swift | 2 | 2502 | import Foundation
import WordPressFlux
extension ReachabilityUtils {
private enum DefaultNoConnectionMessage {
static let title = NSLocalizedString("No Connection",
comment: "Title of error prompt when no internet connection is available.")
static let message = noConnectionMessage()
static let tag: Notice.Tag = "ReachabilityUtils.NoConnection"
}
/// Performs the action when an internet connection is available
/// If no internet connection is available an error message is displayed
///
@objc class func onAvailableInternetConnectionDo(_ action: () -> Void) {
guard ReachabilityUtils.isInternetReachable() else {
WPError.showAlert(withTitle: DefaultNoConnectionMessage.title, message: DefaultNoConnectionMessage.message)
return
}
action()
}
/// Performs the action once when internet becomes reachable.
///
/// This returns an opaque value similar to what
/// NotificationCenter.addObserver(forName:object:queue:using:) returns.
/// You can keep a reference to this if you want to cancel the observer by
/// calling NotificationCenter.removeObserver(_:)
///
@discardableResult
@objc class func observeOnceInternetAvailable(action: @escaping () -> Void) -> NSObjectProtocol {
return NotificationCenter.default.observeOnce(
forName: .reachabilityChanged,
object: nil,
queue: .main,
using: { _ in action() },
filter: { (notification) in
return notification.userInfo?[Foundation.Notification.reachabilityKey] as? Bool == true
})
}
/// Shows a generic non-blocking "No Connection" error message to the user.
///
/// We use a Snackbar instead of a literal Alert because, for internet connection errors,
/// Alerts can be disruptive.
@objc static func showNoInternetConnectionNotice(message: String = noConnectionMessage()) {
// An empty title is intentional to only show a single regular font message.
let notice = Notice(title: "", message: message, tag: DefaultNoConnectionMessage.tag)
ActionDispatcher.dispatch(NoticeAction.post(notice))
}
/// Dismiss the currently shown Notice if it was created using showNoInternetConnectionNotice()
@objc static func dismissNoInternetConnectionNotice() {
ActionDispatcher.dispatch(NoticeAction.clearWithTag(DefaultNoConnectionMessage.tag))
}
}
| gpl-2.0 | 33cdd019e0479f1beb0106c65a414d0d | 43.678571 | 119 | 0.689848 | 5.403888 | false | false | false | false |
snowpunch/AppLove | App Love/Custom/Theme.swift | 1 | 1473 | //
// Theme.swift
// App Love
//
// Created by Woodie Dovich on 2016-02-27.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Theme colors for the app.
//
// cleaned
import UIKit
internal struct Theme {
// dark pastel blue
static let defaultColor = UIColor(red: 43/255, green: 85/255, blue: 127/255, alpha: 1.0)
static let lighterDefaultColor = UIColor(red: 73/255, green: 115/255, blue: 157/255, alpha: 1.0)
static let lightestDefaultColor = UIColor(red: 103/255, green: 145/255, blue: 197/255, alpha: 1.0)
static func navigationBar() {
let bar = UINavigationBar.appearance()
bar.tintColor = .whiteColor()
bar.barTintColor = Theme.defaultColor
bar.translucent = false
bar.barStyle = .Black
}
static func mailBar(bar:UINavigationBar) {
bar.tintColor = .whiteColor()
bar.barTintColor = Theme.defaultColor
bar.translucent = false
bar.barStyle = .Black
}
static func toolBar(item:UIToolbar) {
item.tintColor = .whiteColor()
item.barTintColor = Theme.defaultColor
item.translucent = false
}
static func alertController(item:UIAlertController) {
item.view.tintColor = Theme.lighterDefaultColor
}
static func searchBar(item:UISearchBar) {
item.barTintColor = Theme.defaultColor
item.backgroundImage = UIImage()
item.backgroundColor = Theme.defaultColor
}
} | mit | 6bd3c7f6d3e81dd90b3e98657b143417 | 27.882353 | 102 | 0.648098 | 4.169972 | false | false | false | false |
abunur/quran-ios | Quran/SearchService.swift | 1 | 4117 | //
// SearchService.swift
// Quran
//
// Created by Mohamed Afifi on 5/17/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import RxSwift
protocol SearchService {
func search(for term: String) -> Observable<SearchResults>
}
protocol SearchAutocompletionService {
func autocomplete(term: String) -> Observable<[SearchAutocompletion]>
}
class SQLiteSearchService: SearchAutocompletionService, SearchService {
private let localTranslationInteractor: AnyGetInteractor<[TranslationFull]>
private let arabicPersistence: AyahTextPersistence
private let translationPersistenceCreator: AnyCreator<String, AyahTextPersistence>
init(
localTranslationInteractor: AnyGetInteractor<[TranslationFull]>,
simplePersistence: SimplePersistence,
arabicPersistence: AyahTextPersistence,
translationPersistenceCreator: AnyCreator<String, AyahTextPersistence>) {
self.localTranslationInteractor = localTranslationInteractor
self.arabicPersistence = arabicPersistence
self.translationPersistenceCreator = translationPersistenceCreator
}
func autocomplete(term: String) -> Observable<[SearchAutocompletion]> {
let translationCreator = self.translationPersistenceCreator
let arabicPersistence = self.arabicPersistence
return prepare()
.map { translations -> [SearchAutocompletion] in
let arabicResults = try arabicPersistence.autocomplete(term: term)
guard arabicResults.isEmpty else {
return arabicResults
}
for translation in translations {
let fileURL = Files.translationsURL.appendingPathComponent(translation.fileName)
let persistence = translationCreator.create(fileURL.absoluteString)
let results = try persistence.autocomplete(term: term)
if !results.isEmpty {
return results
}
}
return []
}
}
func search(for term: String) -> Observable<SearchResults> {
let translationCreator = self.translationPersistenceCreator
let arabicPersistence = self.arabicPersistence
return prepare()
.map { translations -> SearchResults in
let arabicResults = try arabicPersistence.search(for: term)
guard arabicResults.isEmpty else {
return SearchResults(source: .quran, items: arabicResults)
}
for translation in translations {
let fileURL = Files.translationsURL.appendingPathComponent(translation.fileName)
let persistence = translationCreator.create(fileURL.absoluteString)
let results = try persistence.search(for: term)
if !results.isEmpty {
return SearchResults(source: .translation(translation), items: results)
}
}
return SearchResults(source: .none, items: [])
}
}
private func prepare() -> Observable<[Translation]> {
return localTranslationInteractor
.get()
.asObservable()
.observeOn(ConcurrentDispatchQueueScheduler(qos: .default))
.map { allTranslations -> [Translation] in
return allTranslations
.filter { $0.isDownloaded }
.map { $0.translation }
}
}
}
| gpl-3.0 | 7d59c09cf7c3291fa5caf195233e1235 | 40.17 | 100 | 0.643915 | 5.482024 | false | false | false | false |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Core/Classes/RSAFKeychainStateManager.swift | 1 | 2129 | //
// RSAFKeychainStateManager.swift
// Pods
//
// Created by James Kizer on 3/25/17.
//
//
import UIKit
import ResearchKit
open class RSAFKeychainStateManager: RSAFStateManager {
static private let keychainQueue = DispatchQueue(label: "keychainQueue")
static func setKeychainObject(_ object: NSSecureCoding, forKey key: String) {
do {
try keychainQueue.sync {
try ORKKeychainWrapper.setObject(object, forKey: key)
}
} catch let error {
assertionFailure("Got error \(error) when setting \(key)")
}
}
static func removeKeychainObject(forKey key: String) {
do {
try keychainQueue.sync {
try ORKKeychainWrapper.removeObject(forKey: key)
}
} catch let error {
assertionFailure("Got error \(error) when setting \(key)")
}
}
static public func clearKeychain() {
do {
try keychainQueue.sync {
try ORKKeychainWrapper.resetKeychain()
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
static func getKeychainObject(_ key: String) -> NSSecureCoding? {
return keychainQueue.sync {
var error: NSError?
let o = ORKKeychainWrapper.object(forKey: key, error: &error)
if error == nil {
return o
}
else {
print("Got error \(error) when getting \(key). This may just be the key has not yet been set!!")
return nil
}
}
}
static public func setValueInState(value: NSSecureCoding?, forKey: String) {
if let val = value {
RSAFKeychainStateManager.setKeychainObject(val, forKey: forKey)
}
else {
RSAFKeychainStateManager.removeKeychainObject(forKey: forKey)
}
}
static public func valueInState(forKey: String) -> NSSecureCoding? {
return RSAFKeychainStateManager.getKeychainObject(forKey)
}
}
| apache-2.0 | 0bb8f512508819d91e9c5a710331a0b8 | 27.386667 | 112 | 0.569751 | 5.033097 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/SimpleData.swift | 1 | 1754 | //
// SimpleData.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML SimpleData
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="SimpleData" type="kml:SimpleDataType"/>
public class SimpleData :SPXMLElement, HasXMLElementValue {
public static var elementName: String = "SimpleData"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as SchemaData: v.value.simpleData.append(self)
default: break
}
}
}
}
public var value : SimpleDataType
public required init(attributes:[String:String]){
self.value = SimpleDataType(attributes: attributes)
super.init(attributes: attributes)
}
}
/// KML SimpleDataType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="SimpleDataType" final="#all">
/// <simpleContent>
/// <extension base="string">
/// <attribute name="name" type="string" use="required"/>
/// </extension>
/// </simpleContent>
/// </complexType>
public class SimpleDataType {
public struct Name: XMLAttributed {
public static var attributeName:String = "name"
public var value: String = ""
}
public var name : Name = Name()
init(attributes:[String:String]){
self.name = Name(value: attributes[Name.attributeName]!)
}
}
| mit | fb4faa0a254805c893da30a62f25d40d | 29.303571 | 73 | 0.614025 | 3.804933 | false | false | false | false |
junpluse/Tuka | Sources/MultipeerConnectivity/Session+Resource.swift | 1 | 4637 | //
// Session+Resource.swift
// Tuka
//
// Created by Jun Tanaka on 2016/11/18.
// Copyright © 2016 Jun Tanaka. All rights reserved.
//
import MultipeerConnectivity
import ReactiveSwift
import Result
extension Session {
public enum ResourceTransferEvent {
case started(name: String, peer: Peer, progress: Progress?)
case completed(name: String, peer: Peer, localURL: URL)
case failed(name: String, peer: Peer, error: Error)
}
public func sendResource(at url: URL, withName name: String, to peer: Peer) -> SignalProducer<ResourceTransferEvent, AnyError> {
return SignalProducer<ResourceTransferEvent, AnyError> { [mcSession] observer, lifetime in
let progress = mcSession.sendResource(at: url, withName: name, toPeer: peer) { error in
if let error = error {
observer.send(value: .failed(name: name, peer: peer, error: error))
observer.send(error: AnyError(error))
} else {
observer.send(value: .completed(name: name, peer: peer, localURL: url))
observer.sendCompleted()
}
}
if let progress = progress {
progress.cancellationHandler = {
if lifetime.hasEnded == false {
observer.sendInterrupted()
}
}
lifetime.observeEnded {
if progress.isCancelled == false {
progress.cancel()
}
}
}
observer.send(value: .started(name: name, peer: peer, progress: progress))
}
}
public func sendResource(at url: URL, withName name: String, to peers: Set<Peer>, concurrently: Bool = false) -> SignalProducer<ResourceTransferEvent, AnyError> {
let childProducers = peers.map { peer in
return sendResource(at: url, withName: name, to: peer)
}
return SignalProducer { observer, lifetime in
lifetime += childProducers
.map { childProducer in
return childProducer.on(value: { event in observer.send(value: event) })
}
.reduce(SignalProducer<ResourceTransferEvent, AnyError>.empty) { previous, current in
if concurrently {
return previous.concat(current)
} else {
return previous.then(current)
}
}
.filter { _ in false }
.start(observer)
}
}
public func incomingResourceEvents(forName resourceName: String? = nil, from peers: Set<Peer>? = nil) -> Signal<ResourceTransferEvent, NoError> {
return Signal.merge([
startReceivingResourceEvents.filterMap { name, peer, progress -> ResourceTransferEvent? in
guard (resourceName == nil || resourceName == name) && (peers == nil || peers?.contains(peer) == true) else {
return nil
}
return .started(name: name, peer: peer, progress: progress)
},
finishReceivingResourceEvents.filterMap { name, peer, url, error -> ResourceTransferEvent? in
guard (resourceName == nil || resourceName == name) && (peers == nil || peers?.contains(peer) == true) else {
return nil
}
if let error = error {
return .failed(name: name, peer: peer, error: error)
} else if let url = url {
return .completed(name: name, peer: peer, localURL: url)
} else {
fatalError("Received `FinishReceivingResourceEvent` without both `error` and `url`")
}
}
])
}
public func incomingResources(forName resourceName: String? = nil, from peers: Set<Peer>? = nil) -> Signal<(String, URL, Peer), AnyError> {
return finishReceivingResourceEvents
.filter { name, peer, _, _ in
return (resourceName == nil || resourceName == name) && (peers == nil || peers?.contains(peer) == true)
}
.attemptMap { name, peer, url, error in
if let error = error {
throw error
} else if let url = url {
return (name, url, peer)
} else {
fatalError("Received `FinishReceivingResourceEvent` without both `error` and `url`")
}
}
}
}
| mit | 13adfa555a4fd1a55964a6bc35164247 | 42.327103 | 166 | 0.536022 | 5.044614 | false | false | false | false |
kenwilcox/NamesToFaces | NamesToFaces/ViewController.swift | 1 | 4673 | //
// ViewController.swift
// NamesToFaces
//
// Created by Kenneth Wilcox on 11/26/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
var people = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewPerson")
let defaults = NSUserDefaults.standardUserDefaults()
if let savedPeople = defaults.objectForKey("people") as? NSData {
people = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! [Person]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addNewPerson() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
func save() {
let savedData = NSKeyedArchiver.archivedDataWithRootObject(people)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(savedData, forKey: "people")
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return people.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Person", forIndexPath: indexPath) as! PersonCell
let person = people[indexPath.item]
cell.name.text = person.name
let path = getDocumentsDirectory().stringByAppendingPathComponent(person.image)
cell.imageView.image = UIImage(contentsOfFile: path)
cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor
cell.imageView.layer.borderWidth = 2
cell.imageView.layer.cornerRadius = 3
cell.layer.cornerRadius = 7
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let person = people[indexPath.item]
let ac = UIAlertController(title: "Rename person", message: person.name, preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
let newName = ac.textFields![0]
person.name = newName.text!
self.collectionView.reloadItemsAtIndexPaths([indexPath])
self.save()
})
presentViewController(ac, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
var newImage: UIImage
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
} else {
return
}
let imageName = NSUUID().UUIDString
let imagePath = getDocumentsDirectory().stringByAppendingPathComponent(imageName)
if let jpegData = UIImageJPEGRepresentation(newImage, 80) {
jpegData.writeToFile(imagePath, atomically: true)
}
let person = Person(name: "Unknown", image: imageName)
people.append(person)
collectionView.reloadData()
save()
dismissViewControllerAnimated(true, completion: nil)
}
func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
} | mit | 76aa22c9c0b6445e9b26910bae4875d8 | 36.685484 | 130 | 0.671233 | 5.796526 | false | false | false | false |
xedin/swift | test/SILGen/nested_types_referencing_nested_functions.swift | 10 | 1064 |
// RUN: %target-swift-emit-silgen -module-name nested_types_referencing_nested_functions %s | %FileCheck %s
do {
func foo() { bar(2) }
func bar<T>(_: T) { foo() }
class Foo {
// CHECK-LABEL: sil private [ossa] @$s025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo {
init() {
foo()
}
// CHECK-LABEL: sil private [ossa] @$s025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> ()
func zim() {
foo()
}
// CHECK-LABEL: sil private [ossa] @$s025nested_types_referencing_A10_functions3FooL_C4zangyyxlF : $@convention(method) <T> (@in_guaranteed T, @guaranteed Foo) -> ()
func zang<T>(_ x: T) {
bar(x)
}
// CHECK-LABEL: sil private [ossa] @$s025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> ()
deinit {
foo()
}
}
let x = Foo()
x.zim()
x.zang(1)
_ = Foo.zim
_ = Foo.zang as (Foo) -> (Int) -> ()
_ = x.zim
_ = x.zang as (Int) -> ()
}
| apache-2.0 | 21623046165f663ad24b9cb3959d07d6 | 30.294118 | 169 | 0.594925 | 3.022727 | false | false | false | false |
yossan4343434/TK_15 | src/app/Visy/Pods/Spring/Spring/DesignableTextField.swift | 33 | 3665 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// 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
@IBDesignable public class DesignableTextField: SpringTextField {
@IBInspectable public var placeholderColor: UIColor = UIColor.clearColor() {
didSet {
attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: placeholderColor])
layoutSubviews()
}
}
@IBInspectable public var sidePadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRectMake(0, 0, sidePadding, sidePadding))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var leftPadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable public var rightPadding: CGFloat = 0 {
didSet {
let padding = UIView(frame: CGRectMake(0, 0, rightPadding, 0))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
let font = UIFont(name: self.font!.fontName, size: self.font!.pointSize)
let text = self.text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
let attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | 1d2f5b2756b355192efbbcb3faf5836b | 36.020202 | 143 | 0.648568 | 5.544629 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/View/EntryHeaderTableViewCell.swift | 1 | 1332 | //
// EntryHeaderTableViewCell.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/04.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class EntryHeaderTableViewCell: UITableViewCell {
let requireIcon = UIImageView(image: UIImage(named: "ico_require"))
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.contentView.addSubview(requireIcon)
require = false
}
var _require: Bool = false
var require: Bool {
set {
_require = newValue
requireIcon.hidden = !_require
}
get {
return _require
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel!.sizeToFit()
var rect = textLabel!.frame
rect.size.height = self.contentView.frame.height
textLabel!.frame = rect
rect = requireIcon.frame
rect.origin.x = self.textLabel!.frame.origin.x + self.textLabel!.frame.width + 8.0
rect.origin.y = 8.0
requireIcon.frame = rect
}
}
| mit | b32c8a1f2bcb6ba08e09ac7dab9b68d3 | 24.09434 | 90 | 0.590977 | 4.586207 | false | false | false | false |
renyufei8023/WeiBo | Pods/BSGridCollectionViewLayout/Pod/Classes/GridCollectionViewLayout.swift | 2 | 9597 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
/**
Provides a grid collection view layout
*/
@objc(BSGridCollectionViewLayout)
public final class GridCollectionViewLayout: UICollectionViewLayout {
/**
Spacing between items (horizontal and vertical)
*/
public var itemSpacing: CGFloat = 0 {
didSet {
_itemSize = estimatedItemSize()
}
}
/**
Number of items per row
*/
public var itemsPerRow = 3 {
didSet {
_itemSize = estimatedItemSize()
}
}
/**
Item height ratio relative to it's width
*/
public var itemHeightRatio: CGFloat = 1 {
didSet {
_itemSize = estimatedItemSize()
}
}
/**
Size for each item
*/
public var itemSize: CGSize {
get {
return _itemSize
}
}
var items = 0
var rows = 0
var _itemSize = CGSizeZero
public override func prepareLayout() {
// Set total number of items and rows
items = estimatedNumberOfItems()
rows = items / itemsPerRow + ((items % itemsPerRow > 0) ? 1 : 0)
// Set item size
_itemSize = estimatedItemSize()
}
/**
See UICollectionViewLayout documentation
*/
public override func collectionViewContentSize() -> CGSize {
guard let collectionView = collectionView where rows > 0 else {
return CGSizeZero
}
let height = estimatedRowHeight() * CGFloat(rows)
return CGSize(width: collectionView.bounds.width, height: height)
}
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return indexPathsInRect(rect).map { (indexPath) -> UICollectionViewLayoutAttributes in
return self.layoutAttributesForItemAtIndexPath(indexPath)! // TODO: Fix forcefull unwrap
}
}
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let itemIndex = flatIndex(indexPath) // index among total number of items
let rowIndex = itemIndex % itemsPerRow // index within it's row
let row = itemIndex / itemsPerRow // which row for that item
let x = (CGFloat(rowIndex) * itemSpacing) + (CGFloat(rowIndex) * itemSize.width)
let y = (CGFloat(row) * itemSpacing) + (CGFloat(row) * itemSize.height)
let width = _itemSize.width
let height = _itemSize.height
let attribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attribute.frame = CGRect(x: x, y: y, width: width, height: height)
return attribute
}
/**
See UICollectionViewLayout documentation
*/
public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
// No decoration or supplementary views
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return nil }
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { return nil }
}
extension GridCollectionViewLayout {
/**
Calculates which index paths are within a given rect
- parameter rect: The rect which we want index paths for
- returns: An array of indexPaths for that rect
*/
func indexPathsInRect(rect: CGRect) -> [NSIndexPath] {
// Make sure we have items/rows
guard items > 0 && rows > 0 else { return [] }
let rowHeight = estimatedRowHeight()
let startRow = GridCollectionViewLayout.firstRowInRect(rect, withRowHeight: rowHeight)
let endRow = GridCollectionViewLayout.lastRowInRect(rect, withRowHeight: rowHeight, max: rows)
let startIndex = GridCollectionViewLayout.firstIndexInRow(startRow, withItemsPerRow: itemsPerRow)
let endIndex = GridCollectionViewLayout.lastIndexInRow(endRow, withItemsPerRow: itemsPerRow, numberOfItems: items)
let indexPaths = (startIndex...endIndex).map { indexPathFromFlatIndex($0) }
return indexPaths
}
/**
Calculates which row index would be first for a given rect.
- parameter rect: The rect to check
- parameter rowHeight: Height for a row
- returns: First row index
*/
static func firstRowInRect(rect: CGRect, withRowHeight rowHeight: CGFloat) -> Int {
if rect.origin.y / rowHeight < 0 {
return 0
} else {
return Int(rect.origin.y / rowHeight)
}
}
/**
Calculates which row index would be last for a given rect.
- parameter rect: The rect to check
- parameter rowHeight: Height for a row
- returns: Last row index
*/
static func lastRowInRect(rect: CGRect, withRowHeight rowHeight: CGFloat, max: Int) -> Int {
guard rect.size.height >= rowHeight else { return 0 }
if (rect.origin.y + rect.height) / rowHeight > CGFloat(max) {
return max - 1
} else {
return Int(ceil((rect.origin.y + rect.height) / rowHeight)) - 1
}
}
/**
Calculates which index would be the first for a given row.
- parameter row: Row index
- parameter itemsPerRow: How many items there can be in a row
- returns: First index
*/
static func firstIndexInRow(row: Int, withItemsPerRow itemsPerRow: Int) -> Int {
return row * itemsPerRow
}
/**
Calculates which index would be the last for a given row.
- parameter row: Row index
- parameter itemsPerRow: How many items there can be in a row
- parameter numberOfItems: The total number of items.
- returns: Last index
*/
static func lastIndexInRow(row: Int, withItemsPerRow itemsPerRow: Int, numberOfItems: Int) -> Int {
let maxIndex = (row + 1) * itemsPerRow - 1
let bounds = numberOfItems - 1
if maxIndex > bounds {
return bounds
} else {
return maxIndex
}
}
/**
Takes an index path (which are 2 dimensional) and turns it into a 1 dimensional index
- parameter indexPath: The index path we want to flatten
- returns: A flat index
*/
func flatIndex(indexPath: NSIndexPath) -> Int {
guard let collectionView = collectionView else {
return 0
}
return (0..<indexPath.section).reduce(indexPath.row) { $0 + collectionView.numberOfItemsInSection($1)}
}
/**
Converts a flat index into an index path
- parameter index: The flat index
- returns: An index path
*/
func indexPathFromFlatIndex(index: Int) -> NSIndexPath {
guard let collectionView = collectionView else {
return NSIndexPath(forItem: 0, inSection: 0)
}
var item = index
var section = 0
while(item >= collectionView.numberOfItemsInSection(section)) {
item -= collectionView.numberOfItemsInSection(section)
section += 1
}
return NSIndexPath(forItem: item, inSection: section)
}
/**
Estimated the size of the items
- returns: Estimated item size
*/
func estimatedItemSize() -> CGSize {
guard let collectionView = collectionView else {
return CGSizeZero
}
let itemWidth = (collectionView.bounds.width - CGFloat(itemsPerRow - 1) * itemSpacing) / CGFloat(itemsPerRow)
return CGSize(width: itemWidth, height: itemWidth * itemHeightRatio)
}
/**
Estimated total number of items
- returns: Total number of items
*/
func estimatedNumberOfItems() -> Int {
guard let collectionView = collectionView else {
return 0
}
return (0..<collectionView.numberOfSections()).reduce(0, combine: {$0 + collectionView.numberOfItemsInSection($1)})
}
/**
Height for each row
- returns: Row height
*/
func estimatedRowHeight() -> CGFloat {
return _itemSize.height+itemSpacing
}
}
| mit | fde05b16922abcc2beeefa0795bf7484 | 32.788732 | 176 | 0.650271 | 5.131551 | false | false | false | false |
thiagolioy/Notes | old/Example/Tests/ScaleSpec.swift | 1 | 14540 | //
// ScaleSpec.swift
// notes
//
// Created by Thiago Lioy on 2/12/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import notes
extension ScaleSpec{
func compareScaleNotes(expected:[Note],actual:[Note]){
for (i,n) in actual.enumerate(){
let other = expected[i]
let areTheSame = n.equalOrEqvl(toNote: other)
if(!areTheSame){
print("Scale Note: \(n.fullname()) is not equal to : \(other.fullname())")
}
expect(areTheSame).to(beTruthy())
}
}
func compareChordTones(expected:[Note],actual:[Note]){
for (i,n) in actual.enumerate(){
let other = expected[i]
let areTheSame = n.equalOrEqvl(toNote: other)
if(!areTheSame){
print("Chord Tone Note: \(n.fullname()) is not equal to : \(other.fullname())")
}
expect(areTheSame).to(beTruthy())
}
}
}
class ScaleSpec: QuickSpec {
override func spec() {
describe("default init"){
let scale = Scale()
it("should have default key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have default scale kind ") {
expect(scale.kind) == ScaleKind.Ionian
}
}
describe("Ionian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Natural),
Note(name: .B, intonation: .Natural),
Note(name: .C, intonation: .Natural)
]
let ionianScale = Scale(kind: .Ionian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(ionianScale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(ionianScale.kind) == ScaleKind.Ionian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: ionianScale.notes())
}
describe("chordTones") {
it("should be of kind") {
expect(ionianScale.chordKind()) == ChordKind.Major7
}
it("should have expected chordTones") {
expect(ionianScale.chordTones()) == [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Natural)
]
}
}
}
describe("Dorian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Natural),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Dorian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Dorian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Flat)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.Minor7
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("Phrygian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Flat),
Note(name: .E, intonation: .Flat),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Flat),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Phrygian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Phrygian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Flat)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.Minor7
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("Lydian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .F, intonation: .Sharp),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Natural),
Note(name: .B, intonation: .Natural),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Lydian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Lydian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Natural)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.Major7
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("Mixolydian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Natural),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Mixolydian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Mixolydian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Flat)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.dom7
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("Aeolian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Flat),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Aeolian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Aeolian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Flat)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.Minor7
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("Locrian Mode") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Flat),
Note(name: .E, intonation: .Flat),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Flat),
Note(name: .A, intonation: .Flat),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale(kind: .Locrian, key: expectedNotes.first!)
it("should have access to scale key ") {
expect(scale.key) == Note(name: .C, intonation: .Natural)
}
it("should have access to scale kind ") {
expect(scale.kind) == ScaleKind.Locrian
}
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.notes())
}
describe("chordTones") {
let expectedChordTones = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .G, intonation: .Flat),
Note(name: .B, intonation: .Flat)
]
it("should be of kind") {
expect(scale.chordKind()) == ChordKind.Minor7b5
}
it("should have expected chordTones") {
self.compareChordTones(expectedChordTones, actual: scale.chordTones())
}
}
}
describe("minorPentatonic") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .E, intonation: .Flat),
Note(name: .F, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .B, intonation: .Flat),
Note(name: .C, intonation: .Natural)
]
let scale = Scale()
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.minorPentatonic())
}
}
describe("majorPentatonic") {
let expectedNotes = [
Note(name: .C, intonation: .Natural),
Note(name: .D, intonation: .Natural),
Note(name: .E, intonation: .Natural),
Note(name: .G, intonation: .Natural),
Note(name: .A, intonation: .Natural),
Note(name: .C, intonation: .Natural)
]
let scale = Scale()
it("should have expected notes") {
self.compareScaleNotes(expectedNotes, actual: scale.majorPentatonic())
}
}
}
}
| mit | cb8db56808adbe410173f4a1d2a664df | 37.361478 | 95 | 0.457115 | 4.75286 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Controller/Listing/ListingViewController.swift | 1 | 53871 | //
// ListingViewController.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 19/09/16.
// Copyright © 2016 Mihai Cristescu. All rights reserved.
//
import UIKit
class ListingViewController: UITableViewController {
// MARK: - Internal Properties
var onFinish: (() -> Void)?
// MARK: - Internal Properties
// Type of action made by controller
private let action: ActionType
// The current location in normal listing mode
private var rootLocation: Location
// The current node in normal listing mode
private var rootNode: Node?
// The content of the rootnode
private var nodes: [Node] = []
// When coping or moving files/folders, this property will hold the source location which is passed between
// controllers on navigation stack.
private var sourceLocations: [Location]?
private var needRefresh: Bool = true
private let searchResult: String?
private var isUpdating: Bool = false
private var isActionConfirmed: Bool = false
private var searchController: UISearchController!
private let dispatchGroup = DispatchGroup()
private var didReceivedNetworkError = false
private var didReceivedStatus400 = false
private var didReceivedStatus404 = false
private var didSucceedCopyOrMove = false
private var errorMessage = ""
private var searchResultWasHighlighted = false
private let flexibleBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.YYY・HH:mm"
return formatter
}()
private let byteFormatter: ByteCountFormatter = {
let formatter = ByteCountFormatter()
formatter.countStyle = .binary
formatter.allowsNonnumericFormatting = false
return formatter
}()
private let busyIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
return activityIndicator
}()
private let emptyFolderLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.lightGray
label.textAlignment = .center
return label
}()
private lazy var messageStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 10
stackView.alignment = .center
stackView.addArrangedSubview(self.busyIndicator)
stackView.addArrangedSubview(self.emptyFolderLabel)
return stackView
}()
private lazy var createFolderBarButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Create Folder", comment: ""), style: .done, target: self, action: #selector(handleShowCreateFolderViewController))
return button
}()
private lazy var copyInEditModeButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Copy", comment: ""), style: .done, target: self, action: #selector(handleExecuteActionsInEditMode(_:)))
button.tag = ActionType.copy.rawValue
return button
}()
private lazy var moveInEditModeButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Move", comment: ""), style: .done, target: self, action: #selector(handleExecuteActionsInEditMode(_:)))
button.tag = ActionType.move.rawValue
return button
}()
private lazy var bookmarksBarButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(handleShowBookmarksViewController(_:)))
button.tag = 3
return button
}()
private lazy var deleteInEditModeButton: UIBarButtonItem = {
let buttonView = UIButton(type: UIButtonType.system)
buttonView.setTitle(NSLocalizedString("Delete", comment: ""), for: .normal)
buttonView.addTarget(self, action: #selector(handleExecuteActionsInEditMode(_:)), for: .touchUpInside)
buttonView.setTitleColor(UIColor(white: 0.8, alpha: 1), for: .disabled)
buttonView.setTitleColor(.red, for: .normal)
buttonView.titleLabel?.font = UIFont.systemFont(ofSize: 18)
buttonView.sizeToFit()
buttonView.tag = ActionType.delete.rawValue
let button = UIBarButtonItem(customView: buttonView)
return button
}()
private lazy var cancelInEditModeButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: ""), style: .done, target: self, action: #selector(handleCancelEditMode))
return button
}()
// MARK: - Initializers and Deinitializers
init(location: Location, action: ActionType, searchResult: String? = nil, sourceLocations: [Location]? = nil) {
self.rootLocation = location
self.action = action
self.searchResult = searchResult
self.sourceLocations = sourceLocations
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UIViewController Methods
extension ListingViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupSearchController()
updateNavigationBarItems()
setupToolBarButtonItems()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if [ActionType.noAction, ActionType.showSearchResult].contains(self.action) {
updateNavigationBarRightButtonItems()
}
if needRefresh {
nodes.removeAll()
busyIndicator.startAnimating()
emptyFolderLabel.text = NSLocalizedString("Loading ...", comment: "")
tableView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if needRefresh {
self.getContent()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
#if DEBUG
UIApplication.shared.isNetworkActivityIndicatorVisible = false
#endif
if tableView.isEditing {
handleCancelEditMode()
}
}
}
// MARK: - UITableView Delegate Conformance
extension ListingViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodes.isEmpty ? 2 : nodes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if nodes.isEmpty {
let cell = UITableViewCell()
cell.isUserInteractionEnabled = false
if indexPath.row == 1 {
cell.contentView.addSubview(messageStackView)
NSLayoutConstraint.activate([
messageStackView.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor),
messageStackView.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor)])
}
return cell
}
let item = nodes[indexPath.row]
let itemDate = Date(timeIntervalSince1970: item.modified / 1000)
let modifiedDateString = itemDate.timeAgoSyle
if item.type == "dir" {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: FolderCell.self),
for: indexPath) as? FolderCell else {
return UITableViewCell()
}
// In copy or move mode you cannot copy or move a folder into itself.
if self.action == .copy || self.action == .move {
if let sourceLocations = sourceLocations {
if sourceLocations.contains(item.location(in: self.rootLocation)) {
cell.isUserInteractionEnabled = false
cell.nodeNameLabel.isEnabled = false
cell.detailsLabel.isEnabled = false
} else {
cell.isUserInteractionEnabled = true
cell.nodeNameLabel.isEnabled = true
cell.detailsLabel.isEnabled = true
}
}
}
cell.actionsButton.addTarget(self, action: #selector(handleShowNodeActionsController(_:)), for: .touchUpInside)
cell.actionsButton.tag = indexPath.row
cell.nodeNameLabel.text = item.name
cell.hasButton = [ActionType.noAction, ActionType.showSearchResult].contains(self.action)
// CHECK THIS!
cell.isShared = item.mount != nil
cell.hasLink = item.link != nil
cell.hasReceiver = item.receiver != nil
cell.isBookmarked = item.bookmark != nil
let detailAttributtedString = NSMutableAttributedString(string: modifiedDateString)
if cell.hasLink {
// http://fontawesome.io/icon/cloud-upload/
let attributedString = NSAttributedString(string: " \u{f0aa}",
attributes: [NSAttributedStringKey.font: UIFont.fontAwesome(size: 12)])
detailAttributtedString.append(attributedString)
}
if cell.hasReceiver {
// http://fontawesome.io/icon/cloud-download/
let attributedString = NSAttributedString(string: " \u{f0ab}",
attributes: [NSAttributedStringKey.font: UIFont.fontAwesome(size: 12)])
detailAttributtedString.append(attributedString)
}
cell.detailsLabel.attributedText = detailAttributtedString
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: FileCell.self),
for: indexPath) as? FileCell else {
return UITableViewCell()
}
cell.actionsButton.addTarget(self, action: #selector(handleShowNodeActionsController(_:)), for: .touchUpInside)
cell.actionsButton.tag = indexPath.row
cell.hasButton = [ActionType.noAction, ActionType.showSearchResult].contains(self.action)
// In copy or move mode you cannot copy or move into a file.
if self.action == .copy || self.action == .move {
cell.isUserInteractionEnabled = false
cell.nodeNameLabel.isEnabled = false
cell.detailsLabel.isEnabled = false
}
cell.hasLink = item.link != nil
cell.nodeNameLabel.text = item.name
let sizeString = byteFormatter.string(fromByteCount: item.size)
let detailAttributtedString = NSMutableAttributedString(string: sizeString + "・" + modifiedDateString)
if cell.hasLink {
// http://fontawesome.io/icon/cloud-upload/
let attributedString = NSAttributedString(string: " \u{f0aa}",
attributes: [NSAttributedStringKey.font: UIFont.fontAwesome(size: 12)])
detailAttributtedString.append(attributedString)
}
cell.detailsLabel.attributedText = detailAttributtedString
return cell
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if tableView.isEditing {
updateToolBarButtonItemsToMatchTableState()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.isEditing {
updateToolBarButtonItemsToMatchTableState()
return
}
tableView.deselectRow(at: indexPath, animated: false)
refreshControl?.endRefreshing()
let selectedNode = nodes[indexPath.row]
let newLocation = self.rootLocation.appendingPathComponentFrom(node: selectedNode)
if selectedNode.type == "dir" {
// This is a Folder
let controller = ListingViewController(location: newLocation, action: self.action, sourceLocations: self.sourceLocations)
if self.action != .noAction {
// It makes sens only if this is a copy or move controller
controller.onFinish = { [weak self] in
self?.onFinish?()
}
}
navigationController?.pushViewController(controller, animated: true)
} else {
// This is a file
if [ActionType.noAction, ActionType.showSearchResult].contains(self.action) {
let controller = ContentViewController(location: newLocation)
controller.node = selectedNode
navigationController?.pushViewController(controller, animated: true)
}
}
}
}
// MARK: - UIScrollView delegate Conformance
extension ListingViewController {
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if refreshControl?.isRefreshing == true {
if self.isUpdating {
return
}
endRefreshAndReloadTable()
}
}
}
// MARK: - Target-Action Methods
private extension ListingViewController {
@objc func handleShowNodeActionsController(_ sender: UIButton) {
self.animateActionButton(sender)
let nodeIndex = sender.tag
let node = self.nodes[nodeIndex]
let nodeLocation = node.location(in: self.rootLocation)
let controller = NodeActionsViewController(location: nodeLocation, node: node)
controller.onSelect = { [unowned self] action in
switch action {
case .bookmark:
self.executeToogleBookmark(location: nodeLocation, node: node, index: nodeIndex)
case .copy, .move:
self.showCopyOrMoveViewController(action: action, sourceLocations: [nodeLocation])
case .delete:
self.showDeleteViewController(location: nodeLocation, sourceView: sender, index: nodeIndex)
case .folderInfo:
self.showFolderInfoViewController(location: nodeLocation, index: nodeIndex)
case .rename:
self.showRenameViewController(nodeLocation: nodeLocation, node: node, index: nodeIndex)
case .sendDownloadLink:
self.showLinkViewController(location: nodeLocation, sharedNode: node, linkType: .download)
case .sendUploadLink:
self.showLinkViewController(location: nodeLocation, sharedNode: node, linkType: .upload)
case .makeShare, .manageShare:
self.showShareMountViewController(location: nodeLocation, sharedNode: node)
default:
break
}
}
presentController(controller, sender: sender)
}
@objc func handleCancelEditMode() {
tableView.setEditing(false, animated: true)
navigationController?.setToolbarHidden(true, animated: true)
updateNavigationBarRightButtonItems()
}
@objc func handleExecuteActionsInEditMode(_ sender: UIBarButtonItem) {
guard let chosenAction = ActionType(rawValue: sender.tag) else { return }
guard let selectedItemsIndexPaths = tableView.indexPathsForSelectedRows else { return }
let sourceLocations = selectedItemsIndexPaths.map { nodes[$0.row].location(in: self.rootLocation) }
switch chosenAction {
case .delete:
self.executeDeletionInSelectionMode(locations: sourceLocations)
case .copy, .move:
self.showCopyOrMoveViewController(action: chosenAction, sourceLocations: sourceLocations)
default:
break
}
}
@objc func handleCopyOrMoveAction() {
setBusyIndicatorView(true)
guard self.sourceLocations != nil else {
return
}
didSucceedCopyOrMove = false
didReceivedNetworkError = false
didReceivedStatus400 = false
didReceivedStatus404 = false
for sourceLocation in self.sourceLocations! {
self.executeCopyOrMove(sourceLocation: sourceLocation)
}
dispatchGroup.notify(queue: .main) {
self.setBusyIndicatorView(false)
if self.didReceivedNetworkError {
let title = NSLocalizedString("Error", comment: "")
let message = NSLocalizedString("An error has occured while processing the request.", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
} else {
if self.didReceivedStatus400 {
let message = NSLocalizedString("An error has occured. Some elements already exists at the destination or the destination location no longer exists.", comment: "")
let title = NSLocalizedString("Error", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
} else {
if self.didReceivedStatus404 {
let message = NSLocalizedString("An error has occured. Some elements no longer exists.", comment: "")
let title = NSLocalizedString("Error", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: { _ in
self.onFinish?()
}))
self.present(alertController, animated: true, completion: nil)
return
}
}
}
// Finish multiple edits without issues
self.dismiss(animated: true) {
self.onFinish?()
}
}
}
@objc func handleCancelCopyOrMoveAction() {
dismiss(animated: true, completion: nil)
}
@objc func handleUpdateContentOnPullToRefreshGesture() {
if self.isUpdating {
self.refreshControl?.endRefreshing()
return
}
self.getContent()
}
@objc func handleShowBookmarksViewController(_ sender: UIBarButtonItem) {
guard let buttonView = sender.value(forKey: "view") as? UIView, sender.tag == 3 else {
return
}
let controller = ManageBookmarksViewController()
let controllerAction = self.action
let controllerSourceLocations = self.sourceLocations
controller.onFinish = { [weak self] in
self?.getContent()
}
controller.onUpdateNeeded = { [weak self] in
self?.getContent()
}
controller.onSelect = { [weak self] location in
let controller = ListingViewController(location: location, action: controllerAction, sourceLocations: controllerSourceLocations)
if self?.action != .noAction {
// It makes sens only if this is a copy or move controller
controller.onFinish = { [weak self] in
self?.onFinish?()
}
}
self?.navigationController?.pushViewController(controller, animated: true)
}
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .popover
navController.popoverPresentationController?.sourceView = buttonView
navController.popoverPresentationController?.sourceRect = buttonView.bounds
present(navController, animated: true, completion: nil)
}
@objc func handleShowSortingSelectionViewController(_ sender: UIBarButtonItem) {
guard let buttonView = sender.value(forKey: "view") as? UIView, sender.tag == 1 else {
return
}
let controller = SortFolderViewController()
controller.onSelection = { [weak self] in
self?.sortContent()
self?.tableView.reloadData()
}
presentController(controller, sender: buttonView)
}
@objc func handleShowMoreActionsViewController(_ sender: UIBarButtonItem) {
guard let rootNode = self.rootNode else {
print("No valid root node fetched in updateContent.")
return
}
guard let buttonView = sender.value(forKey: "view") as? UIView, sender.tag == 0 else {
return
}
let controller = MoreActionsViewController(rootNode: rootNode, childs: self.nodes.count)
controller.onSelect = { [unowned self] selection in
switch selection {
case .bookmark:
self.setNeedsRefreshInPrevious()
self.executeToogleBookmark(location: self.rootLocation, node: rootNode)
case .createFolder:
self.handleShowCreateFolderViewController()
case .selectionMode:
if self.nodes.isEmpty { return }
self.activateEditMode()
case .manageShare, .makeShare, .shareInfo:
self.showShareMountViewController(location: self.rootLocation, sharedNode: rootNode)
case .sendDownloadLink:
self.showLinkViewController(location: self.rootLocation, sharedNode: rootNode, linkType: .download)
case .sendUploadLink:
self.showLinkViewController(location: self.rootLocation, sharedNode: rootNode, linkType: .upload)
default:
break
}
}
presentController(controller, sender: buttonView)
}
@objc func handleShowSearchViewController(_ sender: UIBarButtonItem) {
guard let nav = self.navigationController as? MainNavigationController else {
print("Could not get the MainNavigationController")
return
}
// If index of the search controller is set, and it is different than the current index on
// navigation stack, then we pop to the saved index, otherwise we show the search controller.
if let index = nav.searchResultsControllerIndex, index != nav.viewControllers.count - 1 {
let searchResultsController = nav.viewControllers[index]
_ = self.navigationController?.popToViewController(searchResultsController, animated: true)
} else {
nav.searchResultsControllerIndex = nav.viewControllers.count - 1
}
}
@objc func handleShowCreateFolderViewController() {
let controller = CreateFolderViewController(parentLocation: self.rootLocation)
controller.onFinish = { [unowned self] (folderName) in
// Set needRefresh in this list
self.needRefresh = true
// Set needRefresh in the main List
if let nav = self.presentingViewController as? UINavigationController {
if let cont = nav.topViewController as? ListingViewController {
cont.needRefresh = true
}
}
let newLocation = self.rootLocation.appendingPathComponent(folderName, isFolder: true)
let controller = ListingViewController(location: newLocation, action: self.action, sourceLocations: self.sourceLocations)
controller.onFinish = { [weak self] in
self?.onFinish?()
}
self.navigationController?.pushViewController(controller, animated: true)
}
let navigationController = UINavigationController(rootViewController: controller)
navigationController.modalPresentationStyle = .formSheet
present(navigationController, animated: true, completion: nil)
}
}
// MARK: - Private Methods
private extension ListingViewController {
func setupTableView() {
definesPresentationContext = true
tableView.allowsMultipleSelectionDuringEditing = true
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(handleUpdateContentOnPullToRefreshGesture), for: UIControlEvents.valueChanged)
tableView.register(FileCell.self, forCellReuseIdentifier: String(describing: FileCell.self))
tableView.register(FolderCell.self, forCellReuseIdentifier: String(describing: FolderCell.self))
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.rowHeight = AppSettings.tableViewRowHeight
}
func updateNavigationBarItems() {
if self.rootLocation.path == "/" {
self.title = rootLocation.mount.name
} else {
self.title = (rootLocation.path as NSString).lastPathComponent
}
switch self.action {
case .copy, .move:
self.navigationItem.prompt = NSLocalizedString("Choose a destination", comment: "")
let cancelButton = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: ""), style: .done, target: self, action: #selector(handleCancelCopyOrMoveAction))
navigationItem.rightBarButtonItem = cancelButton
default:
break
}
}
func setupToolBarButtonItems() {
switch self.action {
case .copy, .move:
navigationController?.isToolbarHidden = false
let buttonTitle = self.action == .copy ?
NSLocalizedString("Save copy", comment: "") :
NSLocalizedString("Move", comment: "")
let copyMoveButton = UIBarButtonItem(title: buttonTitle, style: .done, target: self, action: #selector(handleCopyOrMoveAction))
copyMoveButton.isEnabled = true
self.toolbarItems = [createFolderBarButton, flexibleBarButton, bookmarksBarButton, flexibleBarButton, copyMoveButton]
default:
self.toolbarItems = [deleteInEditModeButton, flexibleBarButton, copyInEditModeButton, flexibleBarButton, moveInEditModeButton]
}
}
func setupSearchController() {
// Pass the location of the current folder
let src = SearchResultController(location: self.rootLocation)
searchController = UISearchController(searchResultsController: src)
searchController.searchResultsUpdater = src
searchController.searchBar.delegate = src
searchController.searchBar.autocorrectionType = .no
searchController.searchBar.autocapitalizationType = .none
searchController.searchBar.placeholder = NSLocalizedString("Search for files or folders", comment: "")
searchController.searchBar.scopeButtonTitles = [NSLocalizedString("This folder", comment: ""),
NSLocalizedString("Everywhere", comment: "")]
searchController.searchBar.setValue(NSLocalizedString("Cancel", comment: ""), forKey: "cancelButtonText")
switch self.action {
case .copy, .move: break
default:
navigationItem.searchController = searchController
}
}
func presentError(message: String) {
let title = NSLocalizedString("Error", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
func getContent() {
needRefresh = false
isUpdating = true
didReceivedNetworkError = false
DigiClient.shared.getBundle(for: self.rootLocation) { nodesResult, rootNodeResult, error in
self.isUpdating = false
guard error == nil else {
self.didReceivedNetworkError = true
switch error! {
case NetworkingError.internetOffline(let msg):
self.errorMessage = msg
case NetworkingError.requestTimedOut(let msg):
self.errorMessage = msg
default:
self.errorMessage = NSLocalizedString("There was an error while refreshing the locations.", comment: "")
}
if self.tableView.isDragging {
return
}
self.busyIndicator.stopAnimating()
self.emptyFolderLabel.text = NSLocalizedString("The location is not available.", comment: "")
self.nodes.removeAll()
self.tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.presentError(message: self.errorMessage)
}
return
}
guard nodesResult != nil, rootNodeResult != nil else {
print("Error at receiving content.")
return
}
let nodes: [Node] = nodesResult!
self.rootNode = rootNodeResult!
if self.action == .copy || self.action == .move {
// While copy and move, we sort by name with folders shown first
self.nodes = nodes.sorted {
return $0.type == $1.type ? ($0.name.lowercased() < $1.name.lowercased()) : ($0.type < $1.type)
}
} else {
// In normal case (.noAction) we just sort the content with the method saved by the user.
self.nodes = nodes
self.sortContent()
}
// In case the user pulled the table to refresh, reload table only if the user has finished dragging.
if self.refreshControl?.isRefreshing == true {
if self.tableView.isDragging {
return
} else {
self.updateLocationContentMessage()
self.endRefreshAndReloadTable()
}
} else {
self.updateLocationContentMessage()
// The content update is made while normal navigating through folders, in this case simply reload the table.
self.tableView.reloadData()
self.highlightSearchResultIfNeeded()
}
}
}
func highlightSearchResultIfNeeded() {
if let nameToHighlight = self.searchResult?.lowercased() {
if !searchResultWasHighlighted {
var indexFound = -1
for nodeItem in self.nodes.enumerated() {
if nodeItem.element.name.lowercased() == nameToHighlight {
indexFound = nodeItem.offset
break
}
}
if indexFound != -1 {
let indexPath = IndexPath(row: indexFound, section: 0)
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
}
}
}
}
func updateLocationContentMessage() {
busyIndicator.stopAnimating()
emptyFolderLabel.text = NSLocalizedString("Folder is Empty", comment: "")
}
func endRefreshAndReloadTable() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
self.refreshControl?.endRefreshing()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
if self.didReceivedNetworkError {
self.presentError(message: self.errorMessage)
} else {
self.updateLocationContentMessage()
self.tableView.reloadData()
}
}
}
}
func sortContent() {
switch AppSettings.sortMethod {
case .byName: sortByName()
case .byDate: sortByDate()
case .bySize: sortBySize()
case .byContentType: sortByContentType()
}
}
func animateActionButton(_ button: UIButton) {
var transform: CGAffineTransform
if button.transform == .identity {
transform = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi))
} else {
transform = CGAffineTransform.identity
}
UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1,
options: UIViewAnimationOptions.curveEaseOut,
animations: { button.transform = transform },
completion: nil)
}
func updateNavigationBarRightButtonItems() {
var rightBarButtonItems: [UIBarButtonItem] = []
if tableView.isEditing {
rightBarButtonItems.append(cancelInEditModeButton)
} else {
let moreActionsBarButton = UIBarButtonItem(image: #imageLiteral(resourceName: "more_icon"), style: .done, target: self, action: #selector(handleShowMoreActionsViewController(_:)))
moreActionsBarButton.tag = 0
let sortBarButton = UIBarButtonItem(image: #imageLiteral(resourceName: "sort_icon"), style: .done, target: self, action: #selector(handleShowSortingSelectionViewController(_:)))
sortBarButton.tag = 1
let searchBarButton = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(handleShowSearchViewController(_:)))
searchBarButton.tag = 2
rightBarButtonItems.append(moreActionsBarButton)
rightBarButtonItems.append(contentsOf: [sortBarButton, bookmarksBarButton])
}
navigationItem.setRightBarButtonItems(rightBarButtonItems, animated: false)
}
func updateToolBarButtonItemsToMatchTableState() {
if tableView.indexPathsForSelectedRows != nil, toolbarItems != nil {
if rootLocation.mount.canWrite {
moveInEditModeButton.isEnabled = true
deleteInEditModeButton.isEnabled = true
}
copyInEditModeButton.isEnabled = true
} else {
self.toolbarItems!.forEach { $0.isEnabled = false }
}
}
func updateTableState() {
// Clear source locations
self.sourceLocations = nil
if self.needRefresh {
if self.tableView.isEditing {
self.handleCancelEditMode()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.getContent()
}
} else {
self.getContent()
}
}
}
func activateEditMode() {
tableView.setEditing(true, animated: true)
navigationController?.setToolbarHidden(false, animated: true)
updateNavigationBarRightButtonItems()
updateToolBarButtonItemsToMatchTableState()
}
func sortByName() {
if AppSettings.showsFoldersFirst {
if AppSettings.sortAscending {
self.nodes.sort { return $0.type == $1.type ? ($0.name.lowercased() < $1.name.lowercased()) : ($0.type < $1.type) }
} else {
self.nodes.sort { return $0.type == $1.type ? ($0.name.lowercased() > $1.name.lowercased()) : ($0.type < $1.type) }
}
} else {
if AppSettings.sortAscending {
self.nodes.sort { return $0.name.lowercased() < $1.name.lowercased() }
} else {
self.nodes.sort { return $0.name.lowercased() > $1.name.lowercased() }
}
}
}
func sortByDate() {
if AppSettings.showsFoldersFirst {
if AppSettings.sortAscending {
self.nodes.sort { return $0.type == $1.type ? ($0.modified < $1.modified) : ($0.type < $1.type) }
} else {
self.nodes.sort { return $0.type == $1.type ? ($0.modified > $1.modified) : ($0.type < $1.type) }
}
} else {
if AppSettings.sortAscending {
self.nodes.sort { return $0.modified < $1.modified }
} else {
self.nodes.sort { return $0.modified > $1.modified }
}
}
}
func sortBySize() {
if AppSettings.sortAscending {
self.nodes.sort { return $0.type == $1.type ? ($0.size < $1.size) : ($0.type < $1.type) }
} else {
self.nodes.sort { return $0.type == $1.type ? ($0.size > $1.size) : ($0.type < $1.type) }
}
}
func sortByContentType() {
if AppSettings.sortAscending {
self.nodes.sort { return $0.type == $1.type ? ($0.ext < $1.ext) : ($0.type < $1.type) }
} else {
self.nodes.sort { return $0.type == $1.type ? ($0.ext > $1.ext) : ($0.type < $1.type) }
}
}
func setBusyIndicatorView(_ visible: Bool) {
guard let navControllerView = navigationController?.view else {
return
}
if visible {
let screenSize = navControllerView.bounds.size
let origin = CGPoint(x: (screenSize.width / 2) - 45, y: (screenSize.height / 2) - 45)
let frame = CGRect(origin: origin, size: CGSize(width: 90, height: 90))
let overlayView = UIView(frame: frame)
overlayView.layer.cornerRadius = 8
overlayView.backgroundColor = UIColor.init(white: 0.75, alpha: 1.0)
overlayView.tag = 9999
navControllerView.addSubview(overlayView)
let activityIndicator = UIActivityIndicatorView()
activityIndicator.startAnimating()
activityIndicator.activityIndicatorViewStyle = .white
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
navControllerView.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: navControllerView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: navControllerView.centerYAnchor)
])
} else {
if let overlayView = navControllerView.viewWithTag(9999) {
UIView.animate(withDuration: 0.4, animations: {
overlayView.alpha = 0
}, completion: { _ in
overlayView.removeFromSuperview()
})
}
}
}
func setNeedsRefreshInMain() {
// Set needRefresh true in the main Listing controller
if let nav = self.presentingViewController as? UINavigationController {
for controller in nav.viewControllers {
if let controller = controller as? ListingViewController {
controller.needRefresh = true
}
}
}
}
func setNeedsRefreshInPrevious() {
if let viewControllers = self.navigationController?.viewControllers {
if let previousVC = viewControllers[viewControllers.count-2] as? ListingViewController {
previousVC.needRefresh = true
}
}
}
func presentController(_ controller: UIViewController, sender: UIView) {
if traitCollection.horizontalSizeClass == .regular {
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.sourceView = sender
controller.popoverPresentationController?.sourceRect = sender.bounds
present(controller, animated: true, completion: nil)
} else {
let navigationController = UINavigationController(rootViewController: controller)
present(navigationController, animated: true, completion: nil)
}
}
func executeToogleBookmark(location: Location, node: Node, index: Int? = nil) {
func updateBookmarkIcon(bookmark: Bookmark?) {
if let index = index {
let indexPath = IndexPath(row: index, section: 0)
self.nodes[indexPath.row].bookmark = bookmark
self.tableView.reloadRows(at: [indexPath], with: .none)
} else {
self.rootNode?.bookmark = bookmark
}
}
if var bookmark = node.bookmark {
bookmark.mountId = location.mount.identifier
DigiClient.shared.removeBookmark(bookmark: bookmark) { error in
guard error == nil else {
print(error!.localizedDescription)
return
}
updateBookmarkIcon(bookmark: nil)
}
} else {
let bookmark = Bookmark(name: node.name, mountId: location.mount.identifier, path: location.path)
DigiClient.shared.addBookmark(bookmark: bookmark) { error in
guard error == nil else {
print(error!.localizedDescription)
return
}
updateBookmarkIcon(bookmark: bookmark)
}
}
}
func executeDeletion(at location: Location, index: Int) {
DigiClient.shared.deleteNode(at: location) { (statusCode, error) in
guard error == nil else {
print(error!.localizedDescription)
return
}
if let code = statusCode {
switch code {
case 200:
self.nodes.remove(at: index)
if self.nodes.isEmpty {
self.updateLocationContentMessage()
} else {
self.tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left)
}
// MUST: for reordering the buttons tags!
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.tableView.reloadData()
}
case 400:
// TODO: Alert Bad Request
break
case 404:
// File not found, folder will be refreshed
break
default :
// TODO: Alert Status Code server
break
}
}
}
}
func executeCopyOrMove(sourceLocation: Location) {
let sourceName = (sourceLocation.path as NSString).lastPathComponent
let isFolder = sourceName.last == "/"
let index = sourceName.getIndexBeforeExtension()
// Start with initial destination location.
var destinationLocation = self.rootLocation.appendingPathComponent(sourceName, isFolder: isFolder)
if self.action == .copy {
var destinationName = sourceName
var copyCount: Int = 0
var wasRenamed = false
var wasFound = false
repeat {
// reset before check of all nodes
wasFound = false
// check all nodes for the initial name or new name incremented
for node in self.nodes where node.name == destinationName {
// set the flags
wasFound = true
// increment counter in the new file name
copyCount += 1
// reset name to original
destinationName = sourceName
// Pad number (using Foundation Method)
let countString = String(format: " (%d)", copyCount)
// If name has an extension, we introduce the count number
if index != nil {
destinationName.insert(contentsOf: countString, at: index!)
} else {
destinationName = sourceName + countString
}
wasRenamed = true
}
} while (wasRenamed && wasFound)
// change the file/folder name with incremented one
destinationLocation = self.rootLocation.appendingPathComponent(destinationName, isFolder: isFolder)
}
dispatchGroup.enter()
DigiClient.shared.copyOrMove(from: sourceLocation, to: destinationLocation, action: self.action) { statusCode, error in
self.dispatchGroup.leave()
guard error == nil else {
self.didReceivedNetworkError = true
DLog(object: error!.localizedDescription)
return
}
if let code = statusCode {
switch code {
case 200:
// Operation successfully completed
self.setNeedsRefreshInMain()
self.didSucceedCopyOrMove = true
case 400:
// Bad request ( Folder already exists, invalid file name?)
self.didReceivedStatus400 = true
case 404:
// Not Found (Folder do not exists anymore), folder will refresh
self.setNeedsRefreshInMain()
self.didReceivedStatus404 = true
default :
print("Server replied with Status Code: ", code)
}
}
}
}
func executeDeletionInSelectionMode(locations: [Location]) {
guard isActionConfirmed else {
let string: String
if locations.count == 1 {
if locations.first!.path.last == "/" {
string = NSLocalizedString("Are you sure you want to delete this folder?", comment: "")
} else {
string = NSLocalizedString("Are you sure you want to delete this file?", comment: "")
}
} else {
string = NSLocalizedString("Are you sure you want to delete %d items?", comment: "")
}
let title = String.localizedStringWithFormat(string, locations.count)
let message = NSLocalizedString("This action is not reversible.", comment: "")
let confirmationController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let deleteAction = UIAlertAction(title: NSLocalizedString("Yes", comment: ""), style: .destructive, handler: { _ in
self.isActionConfirmed = true
self.executeDeletionInSelectionMode(locations: locations)
})
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
confirmationController.addAction(deleteAction)
confirmationController.addAction(cancelAction)
present(confirmationController, animated: true, completion: nil)
return
}
self.isActionConfirmed = false
self.setBusyIndicatorView(true)
didSucceedCopyOrMove = false
didReceivedNetworkError = false
didReceivedStatus400 = false
didReceivedStatus404 = false
self.handleCancelEditMode()
for location in locations {
self.dispatchGroup.enter()
DigiClient.shared.deleteNode(at: location) { statusCode, error in
self.dispatchGroup.leave()
guard error == nil, statusCode != nil else {
print(error!.localizedDescription)
return
}
if statusCode! != 200 {
print("Could not delete an item.")
}
}
}
// After all deletions have finished...
dispatchGroup.notify(queue: .main) {
self.setBusyIndicatorView(false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.getContent()
}
}
}
func showRenameViewController(nodeLocation: Location, node: Node, index: Int) {
let controller = RenameViewController(nodeLocation: nodeLocation, node: node)
controller.onRename = { [weak self] name in
self?.nodes[index].name = name
self?.tableView.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: .middle)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
self?.getContent()
}
}
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .formSheet
self.present(navController, animated: true, completion: nil)
}
func showFolderInfoViewController(location: Location, index: Int) {
let controller = FolderInfoViewController(location: location)
controller.onFinish = { [weak self] in
self?.executeDeletion(at: location, index: index)
}
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .formSheet
self.present(navController, animated: true, completion: nil)
}
func showDeleteViewController(location: Location, sourceView: UIView, index: Int) {
let controller = DeleteViewController(isFolder: false)
controller.onSelection = { [weak self] in
self?.executeDeletion(at: location, index: index)
}
presentController(controller, sender: sourceView)
}
func showCopyOrMoveViewController(action: ActionType, sourceLocations: [Location]) {
guard let stackControllers = self.navigationController?.viewControllers else {
print("Couldn't get the previous navigation controllers!")
return
}
var controllers: [UIViewController] = []
for controller in stackControllers {
if controller is LocationsViewController {
let locationController = LocationsViewController(action: action, sourceLocations: sourceLocations)
locationController.title = NSLocalizedString("Locations", comment: "")
locationController.onFinish = { [weak self] in
self?.updateTableState()
}
controllers.append(locationController)
continue
} else {
guard let rootLocation = (controller as? ListingViewController)?.rootLocation else {
continue
}
let listingViewController = ListingViewController(location: rootLocation, action: action, sourceLocations: sourceLocations)
listingViewController.title = controller.title
listingViewController.onFinish = { [weak self] in
self?.updateTableState()
}
controllers.append(listingViewController)
}
}
let navController = UINavigationController(navigationBarClass: CustomNavBar.self, toolbarClass: nil)
navController.setViewControllers(controllers, animated: false)
navController.modalPresentationStyle = .formSheet
self.present(navController, animated: true, completion: nil)
}
func showLinkViewController(location: Location, sharedNode: Node, linkType: LinkType) {
let onFinish = { [weak self] (shouldExitMount: Bool) in
if let navController = self?.navigationController as? MainNavigationController {
self?.getContent()
for controller in navController.viewControllers {
(controller as? ListingViewController)?.needRefresh = true
}
}
}
let controller = ShareLinkViewController(location: location, linkType: linkType, onFinish: onFinish)
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .formSheet
self.present(navController, animated: true, completion: nil)
}
func showShareMountViewController(location: Location, sharedNode: Node) {
let onFinish = { [weak self] (shouldExitMount: Bool) in
if let navController = self?.navigationController as? MainNavigationController {
if shouldExitMount {
navController.popToRootViewController(animated: true)
} else {
self?.getContent()
for controller in navController.viewControllers {
(controller as? ListingViewController)?.needRefresh = true
}
}
}
}
let controller = ShareMountViewController(location: location, sharedNode: sharedNode, onFinish: onFinish)
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .formSheet
self.present(navController, animated: true, completion: nil)
}
}
| mit | 7925943b6a4887486a2f5975f0460a83 | 36.85383 | 191 | 0.603962 | 5.561222 | false | false | false | false |
socialradar/Vacation-Tracker-Swift | Vacation-Tracker-Swift/VTTrip.swift | 2 | 1274 | //
// VTTrip.swift
// Vacation-Tracker
//
// Created by Spencer Atkin on 7/29/15.
// Copyright (c) 2015 SocialRadar. All rights reserved.
//
import Foundation
class VTTrip: NSObject, NSCoding {
var tripName: NSString = NSString()
var visitHandler: VTVisitHandler = VTVisitHandler()
init(name: NSString?) {
if name == nil {
self.tripName = "Unknown Location"
}
else {
self.tripName = name!.capitalizedStringWithLocale(NSLocale.currentLocale())
}
}
func addVisit(visit: VTVisit) -> Void {
NSLog("Adding visit. address %@", visit.place.address)
visitHandler.addVisit(visit)
}
override init() {
super.init()
self.tripName = NSString()
self.visitHandler = VTVisitHandler()
}
required init(coder aDecoder: NSCoder) {
super.init()
self.tripName = aDecoder.decodeObjectForKey("self.tripName") as! NSString
self.visitHandler = aDecoder.decodeObjectForKey("self.visitHandler") as! VTVisitHandler
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.tripName, forKey: "self.tripName")
aCoder.encodeObject(self.visitHandler, forKey: "self.visitHandler")
}
} | mit | 2192e979090f81c453799e1a7f496e88 | 27.333333 | 95 | 0.631083 | 4.149837 | false | false | false | false |
onmyway133/FTGParamount | Sources/Manager.swift | 1 | 769 | //
// Manager.swift
// Paramount
//
// Created by Khoa Pham on 26/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import UIKit
public typealias Action = () -> Void
public class Manager {
public static var action: Action?
public static var window: UIWindow = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = viewController
return window
}()
public static var viewController: ViewController = {
let viewController = ViewController()
viewController.close = {
Manager.hide()
}
viewController.action = action
return viewController
}()
public static func show() {
window.hidden = false
}
public static func hide() {
window.hidden = true
}
}
| mit | 1059927cf13f9a16dc0209cd5de76ec9 | 17.285714 | 62 | 0.669271 | 4.388571 | false | false | false | false |
collinhundley/MySQL | Sources/MySQL/ResultFetcher.swift | 1 | 10023 | //
// ResultFetcher.swift
// MySQL
//
// Created by Collin Hundley on 6/24/17.
//
import Foundation
#if os(Linux)
import CMySQLLinux
#else
import CMySQLMac
#endif
/// An implementation of query result fetcher.
public class ResultFetcher {
enum Error: Swift.Error, LocalizedError {
case database(String)
var errorDescription: String? {
switch self {
case .database(let msg):
return msg
}
}
}
private var preparedStatement: PreparedStatement
private var bindPtr: UnsafeMutablePointer<MYSQL_BIND>?
private let binds: [MYSQL_BIND]
private let fieldNames: [String]
private var hasMoreRows = true
init(preparedStatement: PreparedStatement, resultMetadata: UnsafeMutablePointer<MYSQL_RES>) throws {
guard let fields = mysql_fetch_fields(resultMetadata) else {
throw ResultFetcher.initError(preparedStatement)
}
let numFields = Int(mysql_num_fields(resultMetadata))
var binds = [MYSQL_BIND]()
var fieldNames = [String]()
for i in 0 ..< numFields {
let field = fields[i]
binds.append(ResultFetcher.getOutputBind(field))
fieldNames.append(String(cString: field.name))
}
let bindPtr = UnsafeMutablePointer<MYSQL_BIND>.allocate(capacity: binds.count)
for i in 0 ..< binds.count {
bindPtr[i] = binds[i]
}
guard mysql_stmt_bind_result(preparedStatement.statement, bindPtr) == 0 else {
throw ResultFetcher.initError(preparedStatement, bindPtr: bindPtr, binds: binds)
}
guard mysql_stmt_execute(preparedStatement.statement) == 0 else {
throw ResultFetcher.initError(preparedStatement, bindPtr: bindPtr, binds: binds)
}
self.preparedStatement = preparedStatement
self.bindPtr = bindPtr
self.binds = binds
self.fieldNames = fieldNames
}
deinit {
close()
}
private static func initError(_ preparedStatement: PreparedStatement, bindPtr: UnsafeMutablePointer<MYSQL_BIND>? = nil, binds: [MYSQL_BIND]? = nil) -> Error {
defer {
preparedStatement.release()
}
if let binds = binds {
for bind in binds {
bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1)
bind.length.deallocate(capacity: 1)
bind.is_null.deallocate(capacity: 1)
bind.error.deallocate(capacity: 1)
}
if let bindPtr = bindPtr {
bindPtr.deallocate(capacity: binds.count)
}
}
return Error.database(Connection.getError(from: preparedStatement.statement!))
}
/// All results of an execution, as an array of dictionaries.
///
/// - Returns: An array `[[String : Any]]` of rows returned by the database.
func rows() -> MySQL.Result {
var rows = [[String : Any?]]()
while true {
if let result = fetchNext() {
var row = [String : Any?]()
guard result.count == fieldNames.count else {
print("ERROR: Fetched row contains \(result.count) fields, but we only have \(fieldNames.count) field names.")
continue
}
for pair in zip(fieldNames, result) {
row[pair.0] = pair.1
}
rows.append(row)
} else {
break
}
}
return rows
}
/// Fetch the next row of the query result. This function is blocking.
///
/// - Returns: An array of values of type Any? representing the next row from the query result.
private func fetchNext() -> [Any?]? {
guard hasMoreRows else {
return nil
}
if let row = buildRow() {
return row
} else {
hasMoreRows = false
close()
return nil
}
}
private static func getOutputBind(_ field: MYSQL_FIELD) -> MYSQL_BIND {
let size = getSize(field: field)
var bind = MYSQL_BIND()
bind.buffer_type = field.type
bind.buffer_length = UInt(size)
bind.is_unsigned = 0
bind.buffer = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: 1)
bind.length = UnsafeMutablePointer<UInt>.allocate(capacity: 1)
bind.is_null = UnsafeMutablePointer<my_bool>.allocate(capacity: 1)
bind.error = UnsafeMutablePointer<my_bool>.allocate(capacity: 1)
return bind
}
private static func getSize(field: MYSQL_FIELD) -> Int {
switch field.type {
case MYSQL_TYPE_TINY:
return MemoryLayout<Int8>.size
case MYSQL_TYPE_SHORT:
return MemoryLayout<Int16>.size
case MYSQL_TYPE_INT24,
MYSQL_TYPE_LONG:
return MemoryLayout<Int32>.size
case MYSQL_TYPE_LONGLONG:
return MemoryLayout<Int64>.size
case MYSQL_TYPE_FLOAT:
return MemoryLayout<Float>.size
case MYSQL_TYPE_DOUBLE:
return MemoryLayout<Double>.size
case MYSQL_TYPE_TIME,
MYSQL_TYPE_DATE,
MYSQL_TYPE_DATETIME,
MYSQL_TYPE_TIMESTAMP:
return MemoryLayout<MYSQL_TIME>.size
default:
return Int(field.length)
}
}
private func buildRow() -> [Any?]? {
let fetchStatus = mysql_stmt_fetch(preparedStatement.statement)
if fetchStatus == MYSQL_NO_DATA {
return nil
}
if fetchStatus == 1 {
print("Error fetching row: \(Connection.getError(from: preparedStatement.statement!))")
return nil
}
var row = [Any?]()
for bind in binds {
guard let buffer = bind.buffer else {
// Note: This is an error, but we append nil and continue
print("Error reading data: bind buffer not set.")
row.append(nil)
continue
}
guard bind.is_null.pointee == 0 else {
row.append(nil)
continue
}
let type = bind.buffer_type
switch type {
// Note: Here we convert all integer types to Swift Int
case MYSQL_TYPE_TINY:
row.append(Int(buffer.load(as: Int8.self)))
case MYSQL_TYPE_SHORT:
row.append(Int(buffer.load(as: Int16.self)))
case MYSQL_TYPE_INT24,
MYSQL_TYPE_LONG:
row.append(Int(buffer.load(as: Int32.self)))
case MYSQL_TYPE_LONGLONG:
row.append(Int(buffer.load(as: Int64.self)))
case MYSQL_TYPE_FLOAT:
row.append(buffer.load(as: Float.self))
case MYSQL_TYPE_DOUBLE:
row.append(buffer.load(as: Double.self))
case MYSQL_TYPE_NEWDECIMAL,
MYSQL_TYPE_STRING,
MYSQL_TYPE_VAR_STRING:
row.append(String(bytesNoCopy: buffer, length: getLength(bind), encoding: .utf8, freeWhenDone: false))
case MYSQL_TYPE_TINY_BLOB,
MYSQL_TYPE_BLOB,
MYSQL_TYPE_MEDIUM_BLOB,
MYSQL_TYPE_LONG_BLOB,
MYSQL_TYPE_BIT:
// Note: MySQL returns all TEXT types as BLOBs.
// So, here we check if the data can be interpreted as a String and return it if so.
// Otherwise, we return the raw data.
let data = Data(bytes: buffer, count: getLength(bind))
if let str = String(data: data, encoding: .utf8) {
row.append(str)
} else {
row.append(data)
}
case MYSQL_TYPE_TIME:
let time = buffer.load(as: MYSQL_TIME.self)
row.append("\(pad(time.hour)):\(pad(time.minute)):\(pad(time.second))")
case MYSQL_TYPE_DATE:
let time = buffer.load(as: MYSQL_TIME.self)
row.append("\(time.year)-\(pad(time.month))-\(pad(time.day))")
case MYSQL_TYPE_DATETIME,
MYSQL_TYPE_TIMESTAMP:
let time = buffer.load(as: MYSQL_TIME.self)
let formattedDate = "\(time.year)-\(time.month)-\(time.day) \(time.hour):\(time.minute):\(time.second)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
row.append(dateFormatter.date(from: formattedDate))
default:
print("Using string for unhandled enum_field_type: \(type.rawValue)")
row.append(String(bytesNoCopy: buffer, length: getLength(bind), encoding: .utf8, freeWhenDone: false))
}
}
return row
}
private func close() {
if let bindPtr = bindPtr {
self.bindPtr = nil
for bind in binds {
bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1)
bind.length.deallocate(capacity: 1)
bind.is_null.deallocate(capacity: 1)
bind.error.deallocate(capacity: 1)
}
bindPtr.deallocate(capacity: binds.count)
preparedStatement.release()
}
}
private func getLength(_ bind: MYSQL_BIND) -> Int {
return Int(bind.length.pointee > bind.buffer_length ? bind.buffer_length : bind.length.pointee)
}
private func pad(_ uInt: UInt32) -> String {
return String(format: "%02u", uInt)
}
}
| mit | a14598d0e10fe4857a90661965e192f7 | 33.091837 | 162 | 0.539958 | 4.496635 | false | false | false | false |
tscholze/nomster-ios | Nomster/AppDelegate.swift | 1 | 3365 | //
// AppDelegate.swift
// Nomster
//
// Created by Tobias Scholze on 24.02.15.
// Copyright (c) 2015 Tobias Scholze. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// Debug flag. If true, the application will go into maintancene mode with local data provider.
let IsDebug: Bool = true
var window: UIWindow?
var suggestions: NSMutableArray = []
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
setSuggestionsByRemoteDataSource()
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:.
}
// MARK: - Helper
func setSuggestionsByRemoteDataSource() -> Void {
var results: NSMutableArray = []
suggestions = []
if IsDebug {
let path = NSBundle.mainBundle().pathForResource("data", ofType: "json")
let data = NSData(contentsOfFile: path!)
results = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSMutableArray
} else {
let loader: RESTLoader = RESTLoader()
results = loader.get("suggestions") as! NSMutableArray
}
// Map to real objects
for result in results {
suggestions.addObject(Suggestion.suggestionFromDictionary(result as! NSDictionary))
}
// Sort array (date asc)
suggestions.sortUsingComparator {
(lhs, rhs) -> NSComparisonResult in
let o1 = lhs as! Suggestion
let o2 = rhs as! Suggestion
return o1.date.compare(o2.date)
}
}
}
| mit | 9d371bd1deda7779e513639ab5371fae | 43.276316 | 285 | 0.695097 | 5.392628 | false | false | false | false |
NikitaAsabin/pdpDecember | DayPhoto/AppDelegate.swift | 1 | 5759 | //
// AppDelegate.swift
// DayPhoto
//
// Created by Kruperfone on 02.10.14.
// Copyright (c) 2014 Flatstack. All rights reserved.
//
import UIKit
import CoreData
import SDWebImage
import MagicalRecord
import FBSDKCoreKit
import Fabric
import TwitterKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
#if TEST
switch TestingMode() {
case .Unit:
print("Unit Tests")
self.window?.rootViewController = UIViewController()
return true
case .UI:
print("UI Tests")
}
#endif
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
Fabric.with([Twitter.self])
//setting AFNetwork
/*
AFNetworkReachabilityManager.sharedManager().startMonitoring()
AFNetworkActivityIndicatorManager.sharedManager().enabled = true
*/
//setting SDWebImage
let imageCache:SDImageCache = SDImageCache.sharedImageCache()
imageCache.maxCacheSize = 1024*1024*100 // 100mb on disk
imageCache.maxMemoryCost = 1024*1024*10 // 10mb in memory
let imageDownloader:SDWebImageDownloader = SDWebImageDownloader.sharedDownloader()
imageDownloader.downloadTimeout = 60.0
MagicalRecord.setupCoreDataStackWithStoreNamed("DayPhoto")
//setting Crashlytics
/*
if DEBUG == 1
{
println("Crashlytics is disabled in DEBUG")
}
else
{
Crashlytics.startWithAPIKey(kAPIKeyCrashlitycs)
}
*/
return true
}
func applicationWillResignActive(application: UIApplication)
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication)
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication)
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication)
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication:sourceApplication, annotation: annotation)
VKSdk.processOpenURL(url, fromApplication: sourceApplication)
return true
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
VKSdk.processOpenURL(url, fromApplication: options.fs_objectForKey(UIApplicationOpenURLOptionsSourceApplicationKey, orDefault: "") as! String)
return true
}
//MARK: - Remote Notifications
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
let formatString = "%02.2hhx"
tokenString += String(format: formatString, arguments: [tokenChars[i]])
}
NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: SBKeyUserDefaultsDeviceTokenData)
NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: SBKeyUserDefaultsDeviceTokenString)
NSUserDefaults.standardUserDefaults().synchronize()
}
func requestForRemoteNotifications () {
if #available(iOS 8.0, *) {
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Sound, UIUserNotificationType.Badge], categories: nil))
UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
UIApplication.sharedApplication().registerForRemoteNotificationTypes([UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound, UIRemoteNotificationType.Badge])
}
}
}
| mit | 41e3908efac42d0cd88392ddfe6c50f6 | 41.345588 | 285 | 0.695954 | 5.876531 | false | false | false | false |
ivygulch/IVGFoundation | IVGFoundation/source/extensions/NSAttributedString+IVGFoundation.swift | 1 | 2947 | //
// NSAttributedString+IVGFoundation.swift
// IVGFoundation
//
// Created by Douglas Sjoquist on 2/4/17.
// Copyright © 2017 Ivy Gulch. All rights reserved.
//
import Foundation
public extension NSAttributedString {
public static func concatenated(fromValues values: [(String, [NSAttributedString.Key: Any]?)]) -> NSAttributedString {
let result = NSMutableAttributedString()
for (string, attributes) in values {
if let attributes = attributes {
result.append(NSAttributedString(string: string, attributes: attributes))
} else {
result.append(NSAttributedString(string: string))
}
}
return NSAttributedString(attributedString: result)
}
public func withReplacements(_ replacements: [NSAttributedString.Key: Any?]) -> NSAttributedString {
let range = NSRange(location: 0, length: length)
let result = NSMutableAttributedString()
let replacementKeys = Set(replacements.keys)
enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired, using: { (attributes, range, _) in
var updatedAttributes: [NSAttributedString.Key: Any] = [:]
for attributeName in attributes.keys {
if replacementKeys.contains(attributeName) {
if let replacementValue = replacements[attributeName] {
updatedAttributes[attributeName] = replacementValue
}
} else {
updatedAttributes[attributeName] = attributes[attributeName]
}
}
result.append(NSAttributedString(string: attributedSubstring(from: range).string, attributes: updatedAttributes))
})
return NSAttributedString(attributedString: result)
}
public func replacing(attribute attributeName: NSAttributedString.Key, withValue value: Any?) -> NSAttributedString {
return withReplacements([attributeName: value])
}
public func wrapping(withAttributes wrappingAttributes: [NSAttributedString.Key: Any?]) -> NSAttributedString {
let range = NSRange(location: 0, length: length)
var replacements: [NSAttributedString.Key: Any?] = [:]
var newAttributes: [NSAttributedString.Key: Any] = [:]
for key in wrappingAttributes.keys {
replacements[key] = nil
if let newValue = wrappingAttributes[key] {
newAttributes[key] = newValue
}
}
let result = NSMutableAttributedString(attributedString: withReplacements(replacements))
result.addAttributes(newAttributes, range: range)
return NSAttributedString(attributedString: result)
}
public func wrapping(withAttribute attributeName: NSAttributedString.Key, value: Any?) -> NSAttributedString {
return wrapping(withAttributes: [attributeName: value])
}
}
| mit | 529f74664749d64190477914ff9b7fc4 | 41.695652 | 125 | 0.655465 | 5.548023 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.