repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iCodeForever/ifanr | ifanr/ifanr/Models/MindStoreModel/MindStoreVoteModel.swift | 1 | 1869 | //
// MindStoreVoteModel.swift
// ifanr
//
// Created by 梁亦明 on 16/8/8.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import UIKit
struct VotedUser {
var avatar_url: String!
var company: String!
var email: String!
var id: Int64!
var lime_home_url: String!
var position: String!
init(dict: NSDictionary) {
self.avatar_url = dict["avatar_url"] as? String ?? ""
self.company = dict["company"] as? String ?? ""
self.email = dict["email"] as? String ?? ""
self.id = dict["id"] as? Int64 ?? 0
self.lime_home_url = dict["lime_home_url"] as? String ?? ""
self.position = dict["position"] as? String ?? ""
}
}
struct MindStoreVoteModel: Initable {
var id: Int64!
var resource_uri: String!
var share_count: Int64!
var voted: Bool!
var votedUserArray = Array<VotedUser>()
init(dict: NSDictionary) {
self.id = dict["id"] as? Int64 ?? 0
self.resource_uri = dict["resource_uri"] as? String ?? ""
self.share_count = dict["share_count"] as? Int64 ?? 0
self.voted = dict["voted"] as? Bool ?? false
if let votedUserArray = dict["voted_user"] as? Array<NSDictionary> {
self.votedUserArray = votedUserArray.map { (dict) -> VotedUser in
return VotedUser(dict: dict)
}
}
}
}
/*
"id": 11149,
"resource_uri": "/api/v1.2/mind/vote/11149/",
"share_count": 44,
"vote_count": 311,
"voted": false,
"voted_user": [
{
"avatar_url": "http://media.ifanrusercontent.com/media/tavatar/f0/e0/f0e0018ac7f46e9b92919cd32dbb49bc06d58051.jpg",
"company": "",
"email": "[email protected]",
"id": 24336494,
"lime_home_url": "/lime/user/home/24336494/",
"nickname": "西瓜欣030E-CREW",
"position": "",
"userprofile": {
"weibo_uid": null
},
"wechat_screenname": null
*/ | mit | 45c7e02358e9dd906c920d579a7ce6f0 | 25.5 | 115 | 0.598166 | 3.100334 | false | false | false | false |
safx/TypetalkApp | TypetalkApp/iOS/ViewModels/TopicListViewModel.swift | 1 | 1740 | //
// TopicListViewModel.swift
// TypetalkApp
//
// Created by Safx Developer on 2014/11/09.
// Copyright (c) 2014年 Safx Developers. All rights reserved.
//
import UIKit
import TypetalkKit
import RxSwift
class TopicListViewModel: NSObject, UITableViewDataSource {
var model = TopicsDataSource()
func fetch(observe: Bool) -> TopicsDataSource.Event {
return model.fetch(observe)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.topics.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TopicCell", forIndexPath: indexPath) as! TopicCell
cell.model = model.topics[indexPath.row]
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// TODO
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - ViewModel Actions
func createTopicAction(topicName: String) -> Observable<CreateTopic.Response> {
return model.createTopic(topicName)
}
}
| mit | 998d4d5f55d67c51184269b3131373e9 | 30.6 | 148 | 0.693326 | 4.994253 | false | false | false | false |
dangnguyenhuu/JSQMessagesSwift | Sources/Categories/DateHelper.swift | 1 | 1434 | //
// DateHelper.swift
// JSQMessagesSwift
//
// Created by NGUYEN HUU DANG on 2017/03/19.
//
//
import Foundation
public class DateHelper {
var jsq_YyyymmddFormat: DateFormatter!
var jsq_MmddFormat: DateFormatter!
var jsq_HHmmFormat: DateFormatter!
var jsq_WeekDayFormat: DateFormatter!
static let shared: DateHelper = {
let instance = DateHelper()
if instance.jsq_YyyymmddFormat == nil {
instance.jsq_YyyymmddFormat = DateFormatter()
instance.jsq_YyyymmddFormat.locale = Locale(identifier: "en_US_POSIX")
instance.jsq_YyyymmddFormat.dateFormat = "yyyy/MM/dd"
}
if instance.jsq_MmddFormat == nil {
instance.jsq_MmddFormat = DateFormatter()
instance.jsq_MmddFormat.locale = Locale(identifier: "en_US_POSIX")
instance.jsq_MmddFormat.dateFormat = "M/d"
}
if instance.jsq_HHmmFormat == nil {
instance.jsq_HHmmFormat = DateFormatter()
instance.jsq_HHmmFormat.locale = Locale(identifier: "en_US_POSIX")
instance.jsq_HHmmFormat.dateFormat = "HH:mm"
}
if instance.jsq_WeekDayFormat == nil {
instance.jsq_WeekDayFormat = DateFormatter()
instance.jsq_WeekDayFormat.locale = Locale(identifier: "ja")
}
return instance
}()
}
| apache-2.0 | 249792ebb34a8ccca4c7c7f8c07349d1 | 27.68 | 82 | 0.596932 | 4.12069 | false | false | false | false |
weipin/Cycles | source/Service.swift | 1 | 13867 | //
// Service.swift
//
// Copyright (c) 2014 Weipin Xia
//
// 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
enum ServiceKey: String {
case BaseURL = "BaseURL"
case Resources = "Resources"
case Name = "Name"
case URITemplate = "URITemplate"
case Method = "Method"
}
public enum CycleForResourceOption {
case Reuse /* If there is a Cycle with the specified identifier, the Service will reuse it. */
case Replace /* If there is a Cycle with the specified identifier, the Service will cancel it, create a new Cycle and replace the existing one. */
}
/*!
* @discussion
* This class is an abstract class you use to represent a "service".
* Because it is abstract, you do not use this class directly but instead
* subclass.
*/
public class Service: NSObject {
var _baseURLString: String?
/*!
* The string represents the first part of all URLs the Serivce will produce.
*/
var baseURLString: String {
get {
if (_baseURLString != nil) {
return _baseURLString!
}
var value: AnyObject? = self.profile[ServiceKey.BaseURL.rawValue]
if let str = value as? String {
return str
}
return ""
}
set {
self._baseURLString = newValue
}
}
/*!
* A Dictionary describes the resources of a service.
*/
public var profile: Dictionary<String, AnyObject>!
var session: Session!
/*!
* MUST be overridden
*/
public class func className() -> String {
//TODO: Find a way to obtain class name
assert(false)
return "Service"
}
class func filenameOfDefaultProfile() -> String {
var className = self.className()
var filename = className + ".plist"
return filename
}
/*!
* Override this method to customize the Session
*/
public func defaultSession() -> Session {
return Session()
}
/*!
* Override this method to customize the specific Cycles.
*/
public func cycleDidCreateWithResourceName(cycle: Cycle, name: String) {
}
/*!
* Find and read a service profile in the bundle with specified filename.
*/
class func profileForFilename(filename: String) -> Dictionary<String, AnyObject>? {
var theClass: AnyClass! = self.classForCoder()
var bundle = NSBundle(forClass: theClass)
var URL = bundle.URLForResource(filename, withExtension: nil)
if URL == nil {
println("file not found for: \(filename)");
return nil
}
var error: NSError?
var data = NSData(contentsOfURL:URL!, options: NSDataReadingOptions(0), error: &error)
if data == nil {
println("\(error?.description)");
return nil
}
return self.profileForData(data!)
}
class func profileForData(data: NSData) -> Dictionary<String, AnyObject>? {
var error: NSError?
var profile = NSPropertyListSerialization.propertyListWithData(data,
options: 0, format: nil, error: &error) as Dictionary<String, AnyObject>?
return profile
}
public class func URLStringByJoiningComponents(part1: String, part2: String) -> String {
if part1.isEmpty {
return part2
}
if part2.isEmpty {
return part1
}
var p1 = part1
var p2 = part2
if !part1.isEmpty && part1.hasSuffix("/") {
p1 = part1[part1.startIndex ..< advance(part1.endIndex, -1)]
}
if !part2.isEmpty && part2.hasPrefix("/") {
p2 = part2[advance(part2.startIndex, 1) ..< part2.endIndex]
}
var result = p1 + "/" + p2
return result
}
/*!
* @abstract
* Initialize a Session object
*
* @param profile
* A dictionary for profile. If nil, the bundled default file will be read to create
* the dictionary.
*/
public init(profile: Dictionary<String, AnyObject>? = nil) {
super.init()
self.session = self.defaultSession()
if profile != nil {
self.profile = profile
} else {
self.updateProfileFromLocalFile()
}
}
public func updateProfileFromLocalFile(URL: NSURL? = nil) -> Bool {
var objectClass: AnyClass! = self.classForCoder
if URL == nil {
var filename = self.dynamicType.filenameOfDefaultProfile()
if let profile = self.dynamicType.profileForFilename(filename) {
self.profile = profile
return true
}
return false
}
var error: NSError?
var data = NSData(contentsOfURL: URL!, options: NSDataReadingOptions(0), error: &error)
if data == nil {
println("\(error?.description)");
return false
}
if let profile = objectClass.profileForData(data!) {
self.profile = profile
return true
}
return false
}
/*!
* @abstract
* Check if specified profile is valid
*
* @param profile
* A dictionary as profile.
*
* @result
* true if valid, or false if an error occurs.
*/
public func verifyProfile(profile: Dictionary<String, AnyObject>) -> Bool {
var names = NSMutableSet()
if let value: AnyObject = profile[ServiceKey.Resources.rawValue] {
if let resources = value as? [Dictionary<String, String>] {
for (index, resource) in enumerate(resources) {
if let name = resource[ServiceKey.Name.rawValue] {
if names.containsObject(name) {
println("Error: Malformed Resources (duplicate name) in Service profile (resource index: \(index))!");
return false
}
names.addObject(name)
} else {
println("Error: Malformed Resources (name not found) in Service profile (resource index: \(index))!");
return false
}
if resource[ServiceKey.URITemplate.rawValue] == nil {
println("Error: Malformed Resources (URL Template not found) in Service profile (resource index: \(index))!");
return false
}
}
} else {
println("Error: Malformed Resources in Service profile (type does not match)!");
return false
}
} else {
println("Warning: no resources found in Service profile!");
return false
}
return true
}
public func resourceProfileForName(name: String) -> Dictionary<String, String>? {
assert(self.profile != nil)
if let value: AnyObject = profile![ServiceKey.Resources.rawValue] {
if let resources = value as? [Dictionary<String, String>] {
for resource in resources {
if let n = resource[ServiceKey.Name.rawValue] {
if n == name {
return resource
}
}
}
}
}
return nil
}
public func cycleForIdentifer(identifier: String) -> Cycle? {
return self.session.cycleForIdentifer(identifier)
}
/*!
* @abstract
* Create a Cycle object based on the specified resource profile and parameters
*
* @param name
* The name of the resouce, MUST present in the profile. The name is case sensitive.
*
* @param identifer
* If present, the identifer will be used to locate an existing cycle.
*
* @param option
* Decide the Cycle creation logic if a Cycle with the specified identifer already exists.
*
* @param URIValues
* The object to provide values for the URI Template expanding.
*
* @param requestObject
* The property object of the Request for the Cycle.
*
* @param solicited
* The same property of Cycle.
*
* @result
* A new or existing Cycle.
*/
public func cycleForResourceWithIdentifer(name: String, identifier: String? = nil,
option: CycleForResourceOption = .Replace, URIValues: AnyObject? = nil,
requestObject: AnyObject? = nil,
solicited: Bool = false) -> Cycle {
var cycle: Cycle!
if identifier != nil {
cycle = self.cycleForIdentifer(identifier!)
if cycle != nil {
if option == .Reuse {
} else if option == .Replace {
cycle.cancel(true)
cycle = nil
} else {
assert(false)
}
}
} // if identifier
if cycle != nil {
return cycle
}
if let resourceProfile = self.resourceProfileForName(name) {
var URITemplate = resourceProfile[ServiceKey.URITemplate.rawValue]
var part2 = ExpandURITemplate(URITemplate!, values: URIValues)
var URLString = Service.URLStringByJoiningComponents(self.baseURLString, part2: part2)
var URL = NSURL(string: URLString)
assert(URL != nil)
var method = resourceProfile[ServiceKey.Method.rawValue]
if method == nil {
method = "GET"
}
cycle = Cycle(requestURL: URL!, taskType: .Data, session: self.session,
requestMethod: method!, requestObject: requestObject)
cycle.solicited = solicited
if identifier != nil {
cycle.identifier = identifier!
self.session.addCycleToCycleWithIdentifiers(cycle)
}
self.cycleDidCreateWithResourceName(cycle, name: name)
} else {
assert(false)
}
return cycle!
}
/*!
* @abstract
* Create a Cycle object based on the specified resource profile and parameters
*
* @param name
* The name of the resouce, MUST present in the profile. The name is case sensitive.
*
* @param URIValues
* The object to provide values for the URI Template expanding.
*
* @param requestObject
* The property object of the Request for the Cycle.
*
* @param solicited
* The same property of Cycle.
*
* @result
* A new Cycle.
*/
public func cycleForResource(name: String, URIValues: AnyObject? = nil,
requestObject: AnyObject? = nil, solicited: Bool = false) -> Cycle {
var cycle = self.cycleForResourceWithIdentifer(name,
URIValues: URIValues, requestObject: requestObject, solicited: solicited)
return cycle
}
/*!
* @abstract
* Create a Cycle object based on the specified resource profile and parameters,
* and start the Cycle.
*
* @param name
* The name of the resouce, MUST present in the profile. The name is case sensitive.
*
* @param identifer
* If present, the identifer will be used to locate an existing cycle.
*
* @param URIValues
* The object to provide values for the URI Template expanding.
*
* @param requestObject
* The property object of the Request for the Cycle.
*
* @param solicited
* The same property of Cycle.
*
* @param completionHandler
* Called when the content of the given resource is retrieved
* or an error occurred.
*
* @result
* A new Cycle.
*/
public func requestResourceWithIdentifer(name: String, identifier: String,
URIValues: AnyObject? = nil, requestObject: AnyObject? = nil,
solicited: Bool = false, completionHandler: CycleCompletionHandler) -> Cycle {
var cycle = self.cycleForResourceWithIdentifer(name, identifier: identifier,
URIValues: URIValues, requestObject: requestObject, solicited: solicited)
cycle.start(completionHandler: completionHandler)
return cycle
}
/*!
* @abstract
* Create a Cycle object based on the specified resource profile and parameters,
* and start the Cycle.
*
* @param name
* The name of the resouce, MUST present in the profile. The name is case sensitive.
*
* @param URIValues
* The object to provide values for the URI Template expanding.
*
* @param requestObject
* The property object of the Request for the Cycle.
*
* @param solicited
* The same property of Cycle.
*
* @param completionHandler
* Called when the content of the given resource is retrieved
* or an error occurred.
*
* @result
* A new Cycle.
*/
public func requestResource(name: String, URIValues: AnyObject? = nil,
requestObject: AnyObject? = nil, solicited: Bool = false,
completionHandler: CycleCompletionHandler) -> Cycle {
var cycle = self.cycleForResourceWithIdentifer(name, identifier: nil,
URIValues: URIValues, requestObject: requestObject, solicited: solicited)
cycle.start(completionHandler: completionHandler)
return cycle
}
} // class Service
| mit | 5a6a84237d53e013bacf7c2a3d209e34 | 30.805046 | 150 | 0.619456 | 4.608508 | false | false | false | false |
boytpcm123/ImageDownloader | ImageDownloader/ImageDownloader/Const.swift | 1 | 935 | //
// Const.swift
// ImageDownloader
//
// Created by ninjaKID on 2/27/17.
// Copyright © 2017 ninjaKID. All rights reserved.
//
import Foundation
class Const {
static let urlFileZip = "https://dl.dropboxusercontent.com/u/4529715/JSON%20files%20updated.zip";
static let fileUrl = URL(string: urlFileZip)
static let fileName = fileUrl?.lastPathComponent
static let folderName = fileUrl?.deletingPathExtension().lastPathComponent;
// create your document folder url
static let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
static let pathZipFile = documentsUrl.appendingPathComponent(fileName!)
static let pathFolderName = documentsUrl.appendingPathComponent(folderName!)
// Define identifier
static let notificationDownloadedZip = Notification.Name(rawValue: "NotificationDownloadedZip")
}
| apache-2.0 | b142ab61dfcb733fcf012b7b3262441a | 34.923077 | 139 | 0.743041 | 4.490385 | false | false | false | false |
zl00/CocoaMQTT | Example/Example/ViewController.swift | 2 | 7021 | //
// ViewController.swift
// Example
//
// Created by CrazyWisdom on 15/12/14.
// Copyright © 2015年 emqtt.io. All rights reserved.
//
import UIKit
import CocoaMQTT
class ViewController: UIViewController {
var mqtt: CocoaMQTT?
var animal: String?
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var animalsImageView: UIImageView! {
didSet {
animalsImageView.clipsToBounds = true
animalsImageView.layer.borderWidth = 1.0
animalsImageView.layer.cornerRadius = animalsImageView.frame.width / 2.0
}
}
@IBAction func connectToServer() {
mqtt!.connect()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
tabBarController?.delegate = self
animal = tabBarController?.selectedViewController?.tabBarItem.title
mqttSetting()
// selfSignedSSLSetting()
// simpleSSLSetting()
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = false
}
func mqttSetting() {
let clientID = "CocoaMQTT-\(animal!)-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 1883)
mqtt!.username = ""
mqtt!.password = ""
mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt!.keepAlive = 60
mqtt!.delegate = self
}
func simpleSSLSetting() {
let clientID = "CocoaMQTT-\(animal!)-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 8883)
mqtt!.username = ""
mqtt!.password = ""
mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt!.keepAlive = 60
mqtt!.delegate = self
mqtt!.enableSSL = true
}
func selfSignedSSLSetting() {
let clientID = "CocoaMQTT-\(animal!)-" + String(ProcessInfo().processIdentifier)
mqtt = CocoaMQTT(clientID: clientID, host: "127.0.0.1", port: 8883)
mqtt!.username = ""
mqtt!.password = ""
mqtt!.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
mqtt!.keepAlive = 60
mqtt!.delegate = self
mqtt!.enableSSL = true
let clientCertArray = getClientCertFromP12File(certName: "client-keycert", certPassword: "MySecretPassword")
var sslSettings: [String: NSObject] = [:]
sslSettings[kCFStreamSSLCertificates as String] = clientCertArray
mqtt!.sslSettings = sslSettings
}
func getClientCertFromP12File(certName: String, certPassword: String) -> CFArray? {
// get p12 file path
let resourcePath = Bundle.main.path(forResource: certName, ofType: "p12")
guard let filePath = resourcePath, let p12Data = NSData(contentsOfFile: filePath) else {
print("Failed to open the certificate file: \(certName).p12")
return nil
}
// create key dictionary for reading p12 file
let key = kSecImportExportPassphrase as String
let options : NSDictionary = [key: certPassword]
var items : CFArray?
let securityError = SecPKCS12Import(p12Data, options, &items)
guard securityError == errSecSuccess else {
if securityError == errSecAuthFailed {
print("ERROR: SecPKCS12Import returned errSecAuthFailed. Incorrect password?")
} else {
print("Failed to open the certificate file: \(certName).p12")
}
return nil
}
guard let theArray = items, CFArrayGetCount(theArray) > 0 else {
return nil
}
let dictionary = (theArray as NSArray).object(at: 0)
guard let identity = (dictionary as AnyObject).value(forKey: kSecImportItemIdentity as String) else {
return nil
}
let certArray = [identity] as CFArray
return certArray
}
}
extension ViewController: CocoaMQTTDelegate {
func mqtt(_ mqtt: CocoaMQTT, didConnect host: String, port: Int) {
print("didConnect \(host):\(port)")
}
// Optional ssl CocoaMQTTDelegate
func mqtt(_ mqtt: CocoaMQTT, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
/// Validate the server certificate
///
/// Some custom validation...
///
/// if validatePassed {
/// completionHandler(true)
/// } else {
/// completionHandler(false)
/// }
completionHandler(true)
}
func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
print("didConnectAck: \(ack),rawValue: \(ack.rawValue)")
if ack == .accept {
mqtt.subscribe("chat/room/animals/client/+", qos: CocoaMQTTQOS.qos1)
let chatViewController = storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as? ChatViewController
chatViewController?.mqtt = mqtt
navigationController!.pushViewController(chatViewController!, animated: true)
}
}
func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
print("didPublishMessage with message: \(message.string)")
}
func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
print("didPublishAck with id: \(id)")
}
func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
print("didReceivedMessage: \(message.string) with id \(id)")
let name = NSNotification.Name(rawValue: "MQTTMessageNotification" + animal!)
NotificationCenter.default.post(name: name, object: self, userInfo: ["message": message.string!, "topic": message.topic])
}
func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopic topic: String) {
print("didSubscribeTopic to \(topic)")
}
func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopic topic: String) {
print("didUnsubscribeTopic to \(topic)")
}
func mqttDidPing(_ mqtt: CocoaMQTT) {
print("didPing")
}
func mqttDidReceivePong(_ mqtt: CocoaMQTT) {
_console("didReceivePong")
}
func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
_console("mqttDidDisconnect")
}
func _console(_ info: String) {
print("Delegate: \(info)")
}
}
extension ViewController: UITabBarControllerDelegate {
// Prevent automatic popToRootViewController on double-tap of UITabBarController
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return viewController != tabBarController.selectedViewController
}
}
| mit | b25c117c7d7f9a018ac3343266ce85e4 | 34.256281 | 135 | 0.620724 | 4.795625 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/ReviewsVC.swift | 1 | 6043 | import UIKit
protocol ReviewsVCDelegate: class {
func reviewLogoClicked(review: HDKReview, fromViewController viewController: UIViewController)
}
class ReviewsVC: HLCommonVC, UITableViewDataSource, UITableViewDelegate, ReviewCellDelegate, PeekVCProtocol {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var filterContainerView: UIView!
@IBOutlet weak var agencyButton: UIButton!
var commitBlock: (() -> Void)?
weak var delegate: ReviewsVCDelegate?
var sections: [TableSection] = []
let gates: [HDKGate]
let reviews: [HDKReview]
let variant: HLResultVariant
var selectedGate: HDKGate?
init(reviews: [HDKReview], variant: HLResultVariant) {
self.reviews = reviews
self.variant = variant
gates = ReviewsVC.reviewGates(reviews: reviews)
super.init(nibName: "ReviewsVC", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createSections() -> [TableSection] {
let filteredReviews = selectedGate == nil
? reviews
: reviews.filter { $0.gate.gateId == selectedGate!.gateId }
let items = filteredReviews.map { ReviewItem(model: $0, delegate: self) }
TableItem.setFirstAndLast(items: items)
var sections = [TableSection(name: nil, items: items)]
sections = addPoweredByBookingSectionIfNeeded(to: sections)
return sections
}
private func addPoweredByBookingSectionIfNeeded(to sections: [TableSection]) -> [TableSection] {
guard HDKGate.isBooking(gateId: selectedGate?.gateId ?? "") else {
return sections
}
var result = sections
result.insert(createPoweredByBookingSection(), at: 0)
return result
}
private func createPoweredByBookingSection() -> TableSection {
return TableSection(name: nil, items: [PoweredByBookingItem()])
}
private static func reviewGates(reviews: [HDKReview]) -> [HDKGate] {
return reviews.reduce([], { (result, review) -> [HDKGate] in
let gateId = review.gate.gateId
if !result.contains(where: { $0.gateId == gateId }) {
return result + [review.gate]
}
return result
})
}
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
sections = createSections()
agencyButton.setTitleColor(JRColorScheme.actionColor(), for: .normal)
agencyButton.setTitle(NSLS("HL_REVIEWS_ALL_AGENCIES_FILTER_TITLE"), for: .normal)
}
private func setupTableView() {
tableView.separatorStyle = .none
tableView.allowsSelection = false
tableView.register(ReviewCell.self, forCellReuseIdentifier: ReviewCell.hl_reuseIdentifier())
tableView.register(PoweredByBookingCell.self, forCellReuseIdentifier: PoweredByBookingCell.hl_reuseIdentifier())
tableView.estimatedRowHeight = 200
var inset = tableView.contentInset
inset.bottom += kNavBarHeight + 20
tableView.contentInset = inset
}
private func titleForGate(gate: HDKGate?) -> String {
if gate == nil {
return NSLS("HL_REVIEWS_ALL_AGENCIES_FILTER_TITLE")
} else {
return gate?.name?.hl_firstLetterCapitalized() ?? ""
}
}
@IBAction func changeAgencyClicked(_ sender: Any) {
let allGatesPopoverItem = PopoverItem(title: titleForGate(gate: nil), selected: selectedGate == nil, action: {
self.applyFilter(gate: nil)
})
let gatesPopoverItems: [PopoverItem] = gates.compactMap { gate -> PopoverItem? in
guard gate.name != nil else { return nil }
return PopoverItem(title: titleForGate(gate: gate), selected: gate == selectedGate, action: {
self.applyFilter(gate: gate)
})
}
let popoverItems = [allGatesPopoverItem] + gatesPopoverItems
let pickerVC = PopoverItemPickerVC(items: popoverItems)
let contentSize = PopoverItemPickerVC.prefferedSizeForPopoverPresentation(itemsCount: popoverItems.count)
presentPopover(pickerVC,
under: agencyButton,
contentSize: contentSize)
}
private func applyFilter(gate: HDKGate?) {
if selectedGate != gate {
selectedGate = gate
agencyButton.setTitle(titleForGate(gate: selectedGate), for: .normal)
sections = createSections()
tableView.reloadData()
if sections.count > 0 && sections[0].items.count > 0 {
tableView.scrollToRow(at: IndexPath(item: 0, section: 0), at: .top, animated: false)
}
}
}
func gateLogoClicked(review: HDKReview) {
delegate?.reviewLogoClicked(review: review, fromViewController: self)
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return sections[indexPath.section].items[indexPath.row].cell(tableView: tableView, indexPath: indexPath)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return sections[indexPath.section].items[indexPath.row].cellHeight(tableWidth: tableView.bounds.width)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return sections[section].headerView()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sections[section].headerHeight()
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat(ZERO_HEADER_HEIGHT)
}
}
| mit | ec4e7122c9f0d950f6b15f18a6dceddc | 35.624242 | 120 | 0.656297 | 4.684496 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift | 14 | 8103 | //
// RetryWhen.swift
// RxSwift
//
// Created by Junior B. on 06/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> Observable<Element> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> Observable<Element> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
}
final private class RetryTriggerSink<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = TriggerObservable.Element
typealias Parent = RetryWhenSequenceSinkIter<Sequence, Observer, TriggerObservable, Error>
fileprivate let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self._parent._parent._lastError = nil
self._parent._parent.schedule(.moveNext)
case .error(let e):
self._parent._parent.forwardOn(.error(e))
self._parent._parent.dispose()
case .completed:
self._parent._parent.forwardOn(.completed)
self._parent._parent.dispose()
}
}
}
final private class RetryWhenSequenceSinkIter<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType
, Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>
fileprivate let _parent: Parent
fileprivate let _errorHandlerSubscription = SingleAssignmentDisposable()
fileprivate let _subscription: Disposable
init(parent: Parent, subscription: Disposable) {
self._parent = parent
self._subscription = subscription
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self._parent.forwardOn(event)
case .error(let error):
self._parent._lastError = error
if let failedWith = error as? Error {
// dispose current subscription
self._subscription.dispose()
let errorHandlerSubscription = self._parent._notifier.subscribe(RetryTriggerSink(parent: self))
self._errorHandlerSubscription.setDisposable(errorHandlerSubscription)
self._parent._errorSubject.on(.next(failedWith))
}
else {
self._parent.forwardOn(.error(error))
self._parent.dispose()
}
case .completed:
self._parent.forwardOn(event)
self._parent.dispose()
}
}
final func dispose() {
self._subscription.dispose()
self._errorHandlerSubscription.dispose()
}
}
final private class RetryWhenSequenceSink<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: TailRecursiveSink<Sequence, Observer> where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequence<Sequence, TriggerObservable, Error>
let _lock = RecursiveLock()
fileprivate let _parent: Parent
fileprivate var _lastError: Swift.Error?
fileprivate let _errorSubject = PublishSubject<Error>()
fileprivate let _handler: Observable<TriggerObservable.Element>
fileprivate let _notifier = PublishSubject<TriggerObservable.Element>()
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._handler = parent._notificationHandler(self._errorSubject).asObservable()
super.init(observer: observer, cancel: cancel)
}
override func done() {
if let lastError = self._lastError {
self.forwardOn(.error(lastError))
self._lastError = nil
}
else {
self.forwardOn(.completed)
}
self.dispose()
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
// It is important to always return `nil` here because there are sideffects in the `run` method
// that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this
// case.
return nil
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
let subscription = SingleAssignmentDisposable()
let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription)
subscription.setDisposable(source.subscribe(iter))
return iter
}
override func run(_ sources: SequenceGenerator) -> Disposable {
let triggerSubscription = self._handler.subscribe(self._notifier.asObserver())
let superSubscription = super.run(sources)
return Disposables.create(superSubscription, triggerSubscription)
}
}
final private class RetryWhenSequence<Sequence: Swift.Sequence, TriggerObservable: ObservableType, Error>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableType {
typealias Element = Sequence.Element.Element
fileprivate let _sources: Sequence
fileprivate let _notificationHandler: (Observable<Error>) -> TriggerObservable
init(sources: Sequence, notificationHandler: @escaping (Observable<Error>) -> TriggerObservable) {
self._sources = sources
self._notificationHandler = notificationHandler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run((self._sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
| mit | b61aca98ac6df92a3c7b61c4cb5de059 | 43.516484 | 254 | 0.700568 | 5.190263 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals WatchKit Extension/WatchActionSender.swift | 1 | 1030 | //
// WatchActionSender.swift
// YourGoals WatchKit Extension
//
// Created by André Claaßen on 24.05.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
import WatchKit
import WatchConnectivity
class WatchActionSender {
let session:WCSession
init(session:WCSession) {
self.session = session
}
/// send an action (command) to the iOS App
///
/// - Parameters:
/// - action: action
/// - uri: a task uri for task orientated actions
/// - description: a task description
func send(action: WatchAction, taskUri uri:String? = nil, taskDescription description:String? = nil) {
var userInfo = [String:Any]()
userInfo["action"] = action.rawValue
if uri != nil {
userInfo["taskUri"] = uri
}
if description != nil {
userInfo["description"] = description
}
session.sendMessage(userInfo, replyHandler: nil, errorHandler: nil)
}
}
| lgpl-3.0 | 2c7d62eb2616a0499317c39dfcc92b85 | 24.625 | 106 | 0.604878 | 4.475983 | false | false | false | false |
AlexMoffat/timecalc | TimeCalc/Parser.swift | 1 | 11820 | /*
* Copyright (c) 2017 Alex Moffat
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of mosquitto 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
protocol ExprNode: CustomStringConvertible {
}
struct NumberNode: ExprNode {
let value: Int
var description: String {
return "NumberNode(\(value))"
}
}
struct IdentifierNode: ExprNode {
let value: String
var description: String {
return "IdentifierNode(\(value))"
}
}
struct StringNode: ExprNode {
let value: String
var description: String {
return "StringNode(\(value))"
}
}
struct CommentNode: ExprNode {
let value: String
var description: String {
return "CommentNode(\(value))"
}
}
struct DateTimeNode: ExprNode {
let value: Date
let timezoneSpecified: Bool
var description: String {
return "DateTimeNode(\(value), \(timezoneSpecified))"
}
}
struct DurationNode: ExprNode {
let value: Int
var description: String {
return "DurationNode(\(value))"
}
}
struct AssignmentNode: ExprNode {
let variable: IdentifierNode
let value: ExprNode
var description: String {
return "AssignmentNode(variable: \(variable), value: \(value))"
}
}
struct BinaryOpNode: ExprNode {
let op: String
let lhs: ExprNode
let rhs: ExprNode
var description: String {
return "BinaryOpNode(op: \(op), lhs: \(lhs), rhs: \(rhs))"
}
}
struct LineNode: ExprNode {
let lineNumber: Int
let value: ExprNode?
let error: ParseError?
var description: String {
return "LineNode(lineNumber: \(lineNumber), value: \(String(describing: value)), error: \(String(describing: error)))"
}
}
enum ParseError: Error, CustomStringConvertible {
case ExpectedCharacter(Character)
case ExpectedComment
case ExpectedDateTime
case ExpectedDuration
case ExpectedExpression(Token)
case ExpectedIdentifier
case ExpectedNewline
case ExpectedNumber
case ExpectedOperator
case ExpectedString(String)
case ExpectedStringValue
case ExpectedToken
case UndefinedOperator(String)
var description: String {
switch self {
case let .ExpectedCharacter(c):
return "Parser Expected character \(c)."
case .ExpectedComment:
return "Parser Expected a comment."
case .ExpectedDateTime:
return "Parser Expected a date time value."
case .ExpectedDuration:
return "Parser Expected a duration value."
case let .ExpectedExpression(t):
return "Parser Expected an expression but found \(t)."
case .ExpectedIdentifier:
return "Parser Expected an identifier."
case .ExpectedNewline:
return "Parser Expected a newline."
case .ExpectedNumber:
return "Parser Expected a number."
case .ExpectedOperator:
return "Parser Expected an operator, one of + - * / @ ."
case let .ExpectedString(s):
return "Parser Expected the value \(s)."
case .ExpectedStringValue:
return "Parser Expected a string."
case .ExpectedToken:
return "Parser Expected to find a token."
case let .UndefinedOperator(s):
return "Parser Expected an operator, one of + - * / @ . but got \(s)."
}
}
}
// The higher the precedence the more tightly the operator binds. So 'now @ UTC as yyyy' is
// interpreted as '(now @ UTC) as yyyy'.
let opPrecedence: [String: Int] = [
"as": 10,
"@": 20,
"+": 30,
"-": 30,
"*": 40,
"/": 40
]
class Parser {
let tokens: [Token]
var index = 0
var lineNumber = 1
init(tokens: [Token]) {
self.tokens = tokens
}
var tokensAvailable: Bool {
return index < tokens.count
}
func peekCurrentToken() throws -> Token {
if !tokensAvailable {
throw ParseError.ExpectedToken
}
return tokens[index]
}
func popCurrentToken() throws -> Token {
let nextToken = try peekCurrentToken()
index += 1
return nextToken
}
func getCurrentTokenPrecedence() throws -> Int {
guard tokensAvailable else {
return -1
}
guard case let Token.Operator(op) = try peekCurrentToken() else {
return -1
}
guard let precedence = opPrecedence[op] else {
throw ParseError.UndefinedOperator(op)
}
return precedence
}
func parseNumber() throws -> NumberNode {
guard case let Token.Int(value) = try popCurrentToken() else {
throw ParseError.ExpectedNumber
}
return NumberNode(value: value)
}
func parseVariable() throws -> IdentifierNode {
guard case let Token.Identifier(value) = try popCurrentToken() else {
throw ParseError.ExpectedIdentifier
}
return IdentifierNode(value: value)
}
func parseString() throws -> StringNode {
guard case let Token.String(value) = try popCurrentToken() else {
throw ParseError.ExpectedStringValue
}
return StringNode(value: value)
}
func parseDateTime() throws -> DateTimeNode {
guard case let Token.DateTime(date, timezoneSpecified) = try popCurrentToken() else {
throw ParseError.ExpectedDateTime
}
return DateTimeNode(value: date, timezoneSpecified: timezoneSpecified)
}
func parseDurations() throws -> DurationNode {
guard case let Token.MillisDuration(value) = try popCurrentToken() else {
throw ParseError.ExpectedDuration
}
var totalDuration = value
while tokensAvailable, case let Token.MillisDuration(value) = try peekCurrentToken() {
totalDuration += value
_ = try popCurrentToken()
}
return DurationNode(value: totalDuration)
}
func parseParens() throws -> ExprNode {
guard case Token.OpenParen = try popCurrentToken() else {
throw ParseError.ExpectedCharacter("(")
}
let exp = try parseExpression()
guard case Token.CloseParen = try popCurrentToken() else {
throw ParseError.ExpectedCharacter(")")
}
return exp
}
func parsePrimary() throws -> ExprNode {
switch (try peekCurrentToken()) {
case .Int:
return try parseNumber()
case .String:
return try parseString()
case .Identifier:
return try parseVariable()
case .DateTime:
return try parseDateTime()
case .MillisDuration:
return try parseDurations()
case .OpenParen:
return try parseParens()
default:
throw ParseError.ExpectedExpression(try peekCurrentToken())
}
}
func parseBinaryOp(node: ExprNode, exprPrecedence: Int = 0) throws -> ExprNode {
var lhs = node
while true {
let tokenPrecedence = try getCurrentTokenPrecedence()
if tokenPrecedence < exprPrecedence {
return lhs
}
guard case let Token.Operator(op) = try popCurrentToken() else {
throw ParseError.ExpectedOperator
}
var rhs = try parsePrimary()
let nextPrecedence = try getCurrentTokenPrecedence()
if tokenPrecedence < nextPrecedence {
rhs = try parseBinaryOp(node: rhs, exprPrecedence: tokenPrecedence + 1)
}
lhs = BinaryOpNode(op: op, lhs: lhs, rhs: rhs)
}
}
func parseExpression() throws -> ExprNode {
let node = try parsePrimary()
return try parseBinaryOp(node: node)
}
func parseAssignment() throws -> ExprNode {
guard case Token.Let = try popCurrentToken() else {
throw ParseError.ExpectedString("let")
}
let variable = try parseVariable()
guard case Token.Assign = try popCurrentToken() else {
throw ParseError.ExpectedCharacter("=")
}
let value = try parseExpression()
return AssignmentNode(variable: variable, value: value)
}
func parseNewline(value: ExprNode? = nil) throws -> LineNode {
guard case Token.Newline = try popCurrentToken() else {
throw ParseError.ExpectedNewline
}
let currentLineNumber = lineNumber
lineNumber += 1
return LineNode(lineNumber: currentLineNumber, value: value, error: nil)
}
func parseComment() throws -> CommentNode {
guard case let Token.Comment(value) = try popCurrentToken() else {
throw ParseError.ExpectedComment
}
return CommentNode(value: value)
}
func parseLine() throws -> LineNode {
let value: ExprNode
switch (try peekCurrentToken()) {
case .Newline:
return try parseNewline()
case .Comment:
value = try parseComment()
case .Let:
value = try parseAssignment()
default:
value = try parseExpression()
}
if tokensAvailable {
return try parseNewline(value: value)
} else {
return LineNode(lineNumber: lineNumber, value: value, error: nil)
}
}
func skipToEndOfLine(error: ParseError) throws -> LineNode {
while (tokensAvailable) {
let token = try popCurrentToken()
if token == Token.Newline {
let currentLineNumber = lineNumber
lineNumber += 1
return LineNode(lineNumber: currentLineNumber, value: nil, error: error)
}
}
return LineNode(lineNumber: lineNumber, value: nil, error: error)
}
// Main entry point.
func parseDocument() throws -> [LineNode] {
var lines = [LineNode]()
while (tokensAvailable) {
do {
lines.append(try parseLine())
} catch let error as ParseError {
lines.append(try skipToEndOfLine(error: error))
}
}
return lines
}
}
| bsd-3-clause | 6e78b0e0f460f13f8186e06a1df70db4 | 30.352785 | 126 | 0.612775 | 4.8582 | false | false | false | false |
msdgwzhy6/Sleipnir | Sleipnir/Spec/Matchers/ExpectFailureWithMessage.swift | 1 | 1454 | //
// ExpectFailureWithMessage.swift
// Sleipnir
//
// Created by Artur Termenji on 7/11/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
func expectFailureWithMessage(message: String, block: SleipnirBlock,
file: String = __FILE__, line: Int = __LINE__) {
let currentExample = Runner.currentExample
let fakeExample = Example("I am fake", {})
Runner.currentExample = fakeExample
func updateCurrentExample(state: ExampleState, specFailure: SpecFailure? = nil) {
if specFailure != nil {
currentExample!.specFailure = specFailure
}
currentExample!.setState(state)
Runner.currentExample = currentExample
}
block()
if fakeExample.failed() {
if !(message == fakeExample.message()) {
let reason =
"Expected failure message: \(message) but received failure message \(fakeExample.message())"
let specFailure = SpecFailure(reasonRaw: reason, fileName: file, lineNumber: line)
updateCurrentExample(ExampleState.Failed, specFailure: specFailure)
} else {
updateCurrentExample(ExampleState.Passed)
}
} else {
let reason = "Expectation should have failed"
let specFailure = SpecFailure(reasonRaw: reason, fileName: file, lineNumber: line)
updateCurrentExample(ExampleState.Failed, specFailure: specFailure)
}
} | mit | 2fb69007f9ab29ee1ce079f6bdda4779 | 34.487805 | 108 | 0.651307 | 4.751634 | false | false | false | false |
sschiau/swift-package-manager | Sources/Basic/FileSystem.swift | 1 | 30447 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import POSIX
import SPMLibc
import Foundation
public enum FileSystemError: Swift.Error {
/// Access to the path is denied.
///
/// This is used when an operation cannot be completed because a component of
/// the path cannot be accessed.
///
/// Used in situations that correspond to the POSIX EACCES error code.
case invalidAccess
/// Invalid encoding
///
/// This is used when an operation cannot be completed because a path could
/// not be decoded correctly.
case invalidEncoding
/// IO Error encoding
///
/// This is used when an operation cannot be completed due to an otherwise
/// unspecified IO error.
case ioError
/// Is a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a file was not.
///
/// Used in situations that correspond to the POSIX EISDIR error code.
case isDirectory
/// No such path exists.
///
/// This is used when a path specified does not exist, but it was expected
/// to.
///
/// Used in situations that correspond to the POSIX ENOENT error code.
case noEntry
/// Not a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a directory was not.
///
/// Used in situations that correspond to the POSIX ENOTDIR error code.
case notDirectory
/// Unsupported operation
///
/// This is used when an operation is not supported by the concrete file
/// system implementation.
case unsupported
/// An unspecific operating system error.
case unknownOSError
}
extension FileSystemError {
init(errno: Int32) {
switch errno {
case SPMLibc.EACCES:
self = .invalidAccess
case SPMLibc.EISDIR:
self = .isDirectory
case SPMLibc.ENOENT:
self = .noEntry
case SPMLibc.ENOTDIR:
self = .notDirectory
default:
self = .unknownOSError
}
}
}
/// Defines the file modes.
public enum FileMode {
public enum Option: Int {
case recursive
case onlyFiles
}
case userUnWritable
case userWritable
case executable
public var cliArgument: String {
switch self {
case .userUnWritable:
return "u-w"
case .userWritable:
return "u+w"
case .executable:
return "+x"
}
}
}
// FIXME: Design an asynchronous story?
//
/// Abstracted access to file system operations.
///
/// This protocol is used to allow most of the codebase to interact with a
/// natural filesystem interface, while still allowing clients to transparently
/// substitute a virtual file system or redirect file system operations.
///
/// NOTE: All of these APIs are synchronous and can block.
public protocol FileSystem: class {
/// Check whether the given path exists and is accessible.
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool
/// Check whether the given path is accessible and a directory.
func isDirectory(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and a file.
func isFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is an accessible and executable file.
func isExecutableFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and is a symbolic link.
func isSymlink(_ path: AbsolutePath) -> Bool
// FIXME: Actual file system interfaces will allow more efficient access to
// more data than just the name here.
//
/// Get the contents of the given directory, in an undefined order.
func getDirectoryContents(_ path: AbsolutePath) throws -> [String]
/// Get the current working directory (similar to `getcwd(3)`), which can be
/// different for different (virtualized) implementations of a FileSystem.
/// The current working directory can be empty if e.g. the directory became
/// unavailable while the current process was still working in it.
/// This follows the POSIX `getcwd(3)` semantics.
var currentWorkingDirectory: AbsolutePath? { get }
/// Get the home directory of current user
var homeDirectory: AbsolutePath { get }
/// Create the given directory.
func createDirectory(_ path: AbsolutePath) throws
/// Create the given directory.
///
/// - recursive: If true, create missing parent directories if possible.
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Get the contents of a file.
///
/// - Returns: The file contents as bytes, or nil if missing.
func readFileContents(_ path: AbsolutePath) throws -> ByteString
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws
/// Recursively deletes the file system entity at `path`.
///
/// If there is no file system entity at `path`, this function does nothing (in particular, this is not considered
/// to be an error).
func removeFileTree(_ path: AbsolutePath) throws
/// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws
/// Returns the file info of the given path.
///
/// If `followSymlink` is true and the file system entity at `path` is a symbolic link, it is traversed;
/// otherwise it is not (any symbolic links in path components other than the last one are always traversed).
///
/// The method throws if the underlying stat call fails.
func getFileInfo(_ path: AbsolutePath, followSymlink: Bool) throws -> FileInfo
}
/// Convenience implementations (default arguments aren't permitted in protocol
/// methods).
public extension FileSystem {
/// exists override with default value.
func exists(_ path: AbsolutePath) -> Bool {
return exists(path, followSymlink: true)
}
/// Default implementation of createDirectory(_:)
func createDirectory(_ path: AbsolutePath) throws {
try createDirectory(path, recursive: false)
}
// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath) throws {
try chmod(mode, path: path, options: [])
}
// Unless the file system type provides an override for this method, throw
// if `atomically` is `true`, otherwise fall back to whatever implementation already exists.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
guard !atomically else {
throw FileSystemError.unsupported
}
try writeFileContents(path, bytes: bytes)
}
/// Write to a file from a stream producer.
func writeFileContents(_ path: AbsolutePath, body: (OutputByteStream) -> Void) throws {
let contents = BufferedOutputByteStream()
body(contents)
try createDirectory(path.parentDirectory, recursive: true)
try writeFileContents(path, bytes: contents.bytes)
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
return try getFileInfo(path, followSymlink: true)
}
func getFileInfo(_ path: AbsolutePath, followSymlink: Bool) throws -> FileInfo {
fatalError("This file system currently doesn't support this method")
}
}
/// Concrete FileSystem implementation which communicates with the local file system.
private class LocalFileSystem: FileSystem {
func isExecutableFile(_ path: AbsolutePath) -> Bool {
guard let filestat = try? POSIX.stat(path.asString) else {
return false
}
return filestat.st_mode & SPMLibc.S_IXUSR != 0 && filestat.st_mode & S_IFREG != 0
}
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return Basic.exists(path, followSymlink: followSymlink)
}
func isDirectory(_ path: AbsolutePath) -> Bool {
return Basic.isDirectory(path)
}
func isFile(_ path: AbsolutePath) -> Bool {
return Basic.isFile(path)
}
func isSymlink(_ path: AbsolutePath) -> Bool {
return Basic.isSymlink(path)
}
func getFileInfo(_ path: AbsolutePath, followSymlink: Bool = true) throws -> FileInfo {
let statBuf = try stat(path, followSymlink: followSymlink)
return FileInfo(statBuf)
}
var currentWorkingDirectory: AbsolutePath? {
let cwdStr = FileManager.default.currentDirectoryPath
return try? AbsolutePath(validating: cwdStr)
}
var homeDirectory: AbsolutePath {
#if os(macOS)
if #available(macOS 10.12, *) {
return AbsolutePath(FileManager.default.homeDirectoryForCurrentUser.path)
} else {
fatalError("Unsupported OS")
}
#else
return AbsolutePath(FileManager.default.homeDirectoryForCurrentUser.path)
#endif
}
func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
guard let dir = SPMLibc.opendir(path.asString) else {
throw FileSystemError(errno: errno)
}
defer { _ = SPMLibc.closedir(dir) }
var result: [String] = []
var entry = dirent()
while true {
var entryPtr: UnsafeMutablePointer<dirent>? = nil
let readdir_rErrno = readdir_r(dir, &entry, &entryPtr)
if readdir_rErrno != 0 {
throw FileSystemError(errno: readdir_rErrno)
}
// If the entry pointer is null, we reached the end of the directory.
if entryPtr == nil {
break
}
// Otherwise, the entry pointer should point at the storage we provided.
assert(entryPtr == &entry)
// Add the entry to the result.
guard let name = entry.name else {
throw FileSystemError.invalidEncoding
}
// Ignore the pseudo-entries.
if name == "." || name == ".." {
continue
}
result.append(name)
}
return result
}
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Try to create the directory.
let result = mkdir(path.asString, SPMLibc.S_IRWXU | SPMLibc.S_IRWXG)
// If it succeeded, we are done.
if result == 0 { return }
// If the failure was because the directory exists, everything is ok.
if errno == EEXIST && isDirectory(path) { return }
// If it failed due to ENOENT (e.g., a missing parent), and we are
// recursive, then attempt to create the parent and retry.
if errno == ENOENT && recursive &&
path != path.parentDirectory /* FIXME: Need Path.isRoot */ {
// Attempt to create the parent.
try createDirectory(path.parentDirectory, recursive: true)
// Re-attempt creation, non-recursively.
try createDirectory(path, recursive: false)
} else {
// Otherwise, we failed due to some other error. Report it.
throw FileSystemError(errno: errno)
}
}
func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Open the file.
let fp = fopen(path.asString, "rb")
if fp == nil {
throw FileSystemError(errno: errno)
}
defer { fclose(fp) }
// Read the data one block at a time.
let data = BufferedOutputByteStream()
var tmpBuffer = [UInt8](repeating: 0, count: 1 << 12)
while true {
let n = fread(&tmpBuffer, 1, tmpBuffer.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError.ioError
}
if n == 0 {
if ferror(fp) != 0 {
throw FileSystemError.ioError
}
break
}
data <<< tmpBuffer[0..<n]
}
return data.bytes
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// Open the file.
let fp = fopen(path.asString, "wb")
if fp == nil {
throw FileSystemError(errno: errno)
}
defer { fclose(fp) }
// Write the data in one chunk.
var contents = bytes.contents
while true {
let n = fwrite(&contents, 1, contents.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError.ioError
}
if n != contents.count {
throw FileSystemError.ioError
}
break
}
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// Perform non-atomic writes using the fast path.
if !atomically {
return try writeFileContents(path, bytes: bytes)
}
let temp = try TemporaryFile(dir: path.parentDirectory, deleteOnClose: false)
do {
try writeFileContents(temp.path, bytes: bytes)
try POSIX.rename(old: temp.path.asString, new: path.asString)
} catch {
// Write or rename failed, delete the temporary file.
// Rethrow the original error, however, as that's the
// root cause of the failure.
_ = try? self.removeFileTree(temp.path)
throw error
}
}
func removeFileTree(_ path: AbsolutePath) throws {
if self.exists(path, followSymlink: false) {
try FileManager.default.removeItem(atPath: path.asString)
}
}
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
#if os(macOS)
// Get the mode we need to set.
guard let setMode = setmode(mode.cliArgument) else {
throw FileSystemError(errno: errno)
}
defer { setMode.deallocate() }
let recursive = options.contains(.recursive)
// If we're in recursive mode, do physical walk otherwise logical.
let ftsOptions = recursive ? FTS_PHYSICAL : FTS_LOGICAL
// Get handle to the file hierarchy we want to traverse.
let paths = CStringArray([path.asString])
guard let ftsp = fts_open(paths.cArray, ftsOptions, nil) else {
throw FileSystemError(errno: errno)
}
defer { fts_close(ftsp) }
// Start traversing.
while let p = fts_read(ftsp) {
switch Int32(p.pointee.fts_info) {
// A directory being visited in pre-order.
case FTS_D:
// If we're not recursing, skip the contents of the directory.
if !recursive {
fts_set(ftsp, p, FTS_SKIP)
}
continue
// A directory couldn't be read.
case FTS_DNR:
// FIXME: We should warn here.
break
// There was an error.
case FTS_ERR:
fallthrough
// No stat(2) information was available.
case FTS_NS:
// FIXME: We should warn here.
continue
// A symbolic link.
case FTS_SL:
fallthrough
// A symbolic link with a non-existent target.
case FTS_SLNONE:
// The only symlinks that end up here are ones that don't point
// to anything and ones that we found doing a physical walk.
continue
default:
break
}
// Compute the new mode for this file.
let currentMode = mode_t(p.pointee.fts_statp.pointee.st_mode)
// Skip if only files should be changed.
if options.contains(.onlyFiles) && (currentMode & S_IFMT) == S_IFDIR {
continue
}
// Compute the new mode.
let newMode = getmode(setMode, currentMode)
if newMode == currentMode {
continue
}
// Update the mode.
//
// We ignore the errors for now but we should have a way to report back.
_ = SPMLibc.chmod(p.pointee.fts_accpath, newMode)
}
#endif
// FIXME: We only support macOS right now.
}
}
// FIXME: This class does not yet support concurrent mutation safely.
//
/// Concrete FileSystem implementation which simulates an empty disk.
public class InMemoryFileSystem: FileSystem {
private class Node {
/// The actual node data.
let contents: NodeContents
init(_ contents: NodeContents) {
self.contents = contents
}
/// Creates deep copy of the object.
func copy() -> Node {
return Node(contents.copy())
}
}
private enum NodeContents {
case file(ByteString)
case directory(DirectoryContents)
/// Creates deep copy of the object.
func copy() -> NodeContents {
switch self {
case .file(let bytes):
return .file(bytes)
case .directory(let contents):
return .directory(contents.copy())
}
}
}
private class DirectoryContents {
var entries: [String: Node]
init(entries: [String: Node] = [:]) {
self.entries = entries
}
/// Creates deep copy of the object.
func copy() -> DirectoryContents {
let contents = DirectoryContents()
for (key, node) in entries {
contents.entries[key] = node.copy()
}
return contents
}
}
/// The root filesytem.
private var root: Node
public init() {
root = Node(.directory(DirectoryContents()))
}
/// Creates deep copy of the object.
public func copy() -> InMemoryFileSystem {
let fs = InMemoryFileSystem()
fs.root = root.copy()
return fs
}
/// Get the node corresponding to the given path.
private func getNode(_ path: AbsolutePath) throws -> Node? {
func getNodeInternal(_ path: AbsolutePath) throws -> Node? {
// If this is the root node, return it.
if path.isRoot {
return root
}
// Otherwise, get the parent node.
guard let parent = try getNodeInternal(path.parentDirectory) else {
return nil
}
// If we didn't find a directory, this is an error.
guard case .directory(let contents) = parent.contents else {
throw FileSystemError.notDirectory
}
// Return the directory entry.
return contents.entries[path.basename]
}
// Get the node that corresponds to the path.
return try getNodeInternal(path)
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
do {
return try getNode(path) != nil
} catch {
return false
}
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
do {
if case .directory? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
public func isFile(_ path: AbsolutePath) -> Bool {
do {
if case .file? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
// FIXME: Always return false until in-memory implementation
// gets symbolic link semantics.
return false
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
// FIXME: Always return false until in-memory implementation
// gets permission semantics.
return false
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return AbsolutePath("/")
}
public var homeDirectory: AbsolutePath {
// FIXME: Maybe we should allow setting this when creating the fs.
return AbsolutePath("/home/user")
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
guard let node = try getNode(path) else {
throw FileSystemError.noEntry
}
guard case .directory(let contents) = node.contents else {
throw FileSystemError.notDirectory
}
// FIXME: Perhaps we should change the protocol to allow lazy behavior.
return [String](contents.entries.keys)
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Ignore if client passes root.
guard !path.isRoot else {
return
}
// Get the parent directory node.
let parentPath = path.parentDirectory
guard let parent = try getNode(parentPath) else {
// If the parent doesn't exist, and we are recursive, then attempt
// to create the parent and retry.
if recursive && path != parentPath {
// Attempt to create the parent.
try createDirectory(parentPath, recursive: true)
// Re-attempt creation, non-recursively.
return try createDirectory(path, recursive: false)
} else {
// Otherwise, we failed.
throw FileSystemError.noEntry
}
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// Check if the node already exists.
if let node = contents.entries[path.basename] {
// Verify it is a directory.
guard case .directory = node.contents else {
// The path itself isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// We are done.
return
}
// Otherwise, the node does not exist, create it.
contents.entries[path.basename] = Node(.directory(DirectoryContents()))
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Get the node.
guard let node = try getNode(path) else {
throw FileSystemError.noEntry
}
// Check that the node is a file.
guard case .file(let contents) = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError.isDirectory
}
// Return the file contents.
return contents
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// It is an error if this is the root node.
let parentPath = path.parentDirectory
guard path != parentPath else {
throw FileSystemError.isDirectory
}
// Get the parent node.
guard let parent = try getNode(parentPath) else {
throw FileSystemError.noEntry
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// Check if the node exists.
if let node = contents.entries[path.basename] {
// Verify it is a file.
guard case .file = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError.isDirectory
}
}
// Write the file.
contents.entries[path.basename] = Node(.file(bytes))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// In memory file system's writeFileContents is already atomic, so ignore the parameter here
// and just call the base implementation.
try writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
// Ignore root and get the parent node's content if its a directory.
guard !path.isRoot,
let parent = try? getNode(path.parentDirectory),
case .directory(let contents)? = parent?.contents else {
return
}
// Set it to nil to release the contents.
contents.entries[path.basename] = nil
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
// FIXME: We don't have these semantics in InMemoryFileSystem.
}
}
/// A rerooted view on an existing FileSystem.
///
/// This is a simple wrapper which creates a new FileSystem view into a subtree
/// of an existing filesystem. This is useful for passing to clients which only
/// need access to a subtree of the filesystem but should otherwise remain
/// oblivious to its concrete location.
///
/// NOTE: The rerooting done here is purely at the API level and does not
/// inherently prevent access outside the rerooted path (e.g., via symlinks). It
/// is designed for situations where a client is only interested in the contents
/// *visible* within a subpath and is agnostic to the actual location of those
/// contents.
public class RerootedFileSystemView: FileSystem {
/// The underlying file system.
private var underlyingFileSystem: FileSystem
/// The root path within the containing file system.
private let root: AbsolutePath
public init(_ underlyingFileSystem: FileSystem, rootedAt root: AbsolutePath) {
self.underlyingFileSystem = underlyingFileSystem
self.root = root
}
/// Adjust the input path for the underlying file system.
private func formUnderlyingPath(_ path: AbsolutePath) -> AbsolutePath {
if path == AbsolutePath.root {
return root
} else {
// FIXME: Optimize?
return root.appending(RelativePath(String(path.asString.dropFirst(1))))
}
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return underlyingFileSystem.exists(formUnderlyingPath(path), followSymlink: followSymlink)
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isDirectory(formUnderlyingPath(path))
}
public func isFile(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isFile(formUnderlyingPath(path))
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isSymlink(formUnderlyingPath(path))
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isExecutableFile(formUnderlyingPath(path))
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return AbsolutePath("/")
}
public var homeDirectory: AbsolutePath {
fatalError("homeDirectory on RerootedFileSystemView is not supported.")
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
return try underlyingFileSystem.getDirectoryContents(formUnderlyingPath(path))
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
let path = formUnderlyingPath(path)
return try underlyingFileSystem.createDirectory(path, recursive: recursive)
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try underlyingFileSystem.readFileContents(formUnderlyingPath(path))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
let path = formUnderlyingPath(path)
return try underlyingFileSystem.writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
try underlyingFileSystem.removeFileTree(path)
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
try underlyingFileSystem.chmod(mode, path: path, options: options)
}
}
/// Public access to the local FS proxy.
public var localFileSystem: FileSystem = LocalFileSystem()
extension FileSystem {
/// Print the filesystem tree of the given path.
///
/// For debugging only.
public func dumpTree(at path: AbsolutePath = .root) {
print(".")
do {
try recurse(fs: self, path: path)
} catch {
print("\(error)")
}
}
/// Helper method to recurse and print the tree.
private func recurse(fs: FileSystem, path: AbsolutePath, prefix: String = "") throws {
let contents = try fs.getDirectoryContents(path)
for (idx, entry) in contents.enumerated() {
let isLast = idx == contents.count - 1
let line = prefix + (isLast ? "└── " : "├── ") + entry
print(line)
let entryPath = path.appending(component: entry)
if fs.isDirectory(entryPath) {
let childPrefix = prefix + (isLast ? " " : "│ ")
try recurse(fs: fs, path: entryPath, prefix: String(childPrefix))
}
}
}
}
| apache-2.0 | 68362eb3e3886d498fb9238c2f7627bc | 32.627624 | 118 | 0.608057 | 4.875521 | false | false | false | false |
chicio/RangeUISlider | RangeUISliderDemo/GroupedFeaturesTableViewController.swift | 1 | 2792 | //
// GourpedFeaturesTableTableViewController.swift
// Demo
//
// Created by Fabrizio Duroni on 01/04/2017.
// 2017 Fabrizio Duroni.
//
import UIKit
struct GroupedFeaturesViewControllerData {
let description: String
let segueIdentifier: String
init(description aDescription: String, segueIdentifier aSegueIdentifier: String) {
description = aDescription
segueIdentifier = aSegueIdentifier
}
}
class GroupedFeaturesTableViewController: UITableViewController {
let data: [GroupedFeaturesViewControllerData] = [
GroupedFeaturesViewControllerData(description: "Only colors", segueIdentifier: "showOnlyColorsSegue"),
GroupedFeaturesViewControllerData(description: "Only images", segueIdentifier: "showOnlyImagesSegue"),
GroupedFeaturesViewControllerData(description: "Only gradients", segueIdentifier: "showOnlyGradientsSegue"),
GroupedFeaturesViewControllerData(
description: "Programmatic setup",
segueIdentifier: "showProgrammaticSetupSegue"
),
GroupedFeaturesViewControllerData(
description: "Inside UITableView",
segueIdentifier: "showTableViewSetupSegue"
),
GroupedFeaturesViewControllerData(
description: "Programmatic knob change",
segueIdentifier: "showChangeKnobProgrammaticSegue"),
GroupedFeaturesViewControllerData(
description: "Programmatic scale change",
segueIdentifier: "showChangeScaleProgrammaticSegue"
),
GroupedFeaturesViewControllerData(
description: "Programmatic default knob value change",
segueIdentifier: "showChangeDefaultKnobValueProgrammaticSegue"
),
GroupedFeaturesViewControllerData(description: "SwiftUI", segueIdentifier: "swiftUISegue")
]
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GroupedFeaturesCell", for: indexPath)
cell.accessibilityIdentifier = data[indexPath.row].description.replacingOccurrences(of: " ", with: "")
cell.textLabel?.accessibilityIdentifier = data[indexPath.row].description.trimmingCharacters(in: .whitespaces)
cell.textLabel?.text = data[indexPath.row].description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: data[indexPath.row].segueIdentifier, sender: self)
}
}
| mit | 0e3e15db48d0f6791f6fd21423f631b8 | 40.671642 | 118 | 0.72063 | 5.517787 | false | false | false | false |
slavapestov/swift | test/SourceKit/InterfaceGen/gen_stdlib.swift | 1 | 1828 |
var x: Int
// RUN: %sourcekitd-test -req=interface-gen -module Swift -check-interface-ascii > %t.response
// RUN: FileCheck -check-prefix=CHECK-STDLIB -input-file %t.response %s
// RUN: FileCheck -check-prefix=CHECK-MUTATING-ATTR -input-file %t.response %s
// RUN: FileCheck -check-prefix=CHECK-HIDE-ATTR -input-file %t.response %s
// Just check a small part, mainly to make sure we can print the interface of the stdlib.
// CHECK-STDLIB-NOT: extension _SwiftNSOperatingSystemVersion
// CHECK-STDLIB: struct Int : SignedIntegerType, Comparable, Equatable {
// CHECK-STDLIB: static var max: Int { get }
// CHECK-STDLIB: static var min: Int { get }
// CHECK-STDLIB: }
// Check that extensions of nested decls are showing up.
// CHECK-STDLIB-LABEL: extension String.UTF16View.Index {
// CHECK-STDLIB: func samePositionIn(utf8: String.UTF8View) -> String.UTF8View.Index?
// CHECK-STDLIB: func samePositionIn(unicodeScalars: String.UnicodeScalarView) -> UnicodeScalarIndex?
// CHECK-STDLIB: func samePositionIn(characters: String) -> Index?
// CHECK-STDLIB-NEXT: }
// CHECK-MUTATING-ATTR: mutating func
// CHECK-HIDE-ATTR-NOT: @effects
// CHECK-HIDE-ATTR-NOT: @semantics
// CHECK-HIDE-ATTR-NOT: @inline
// RUN: %sourcekitd-test -req=interface-gen-open -module Swift \
// RUN: == -req=cursor -pos=2:8 %s -- %s | FileCheck -check-prefix=CHECK1 %s
// CHECK1: source.lang.swift.ref.struct ()
// CHECK1-NEXT: Int
// CHECK1-NEXT: s:Si
// CHECK1-NEXT: Int.Type
// CHECK1-NEXT: Swift{{$}}
// CHECK1-NEXT: <Group>FixedPoint</Group>
// CHECK1-NEXT: /<interface-gen>{{$}}
// CHECK1-NEXT: SYSTEM
// CHECK1-NEXT: <Declaration>struct Int : <Type usr="s:Ps17SignedIntegerType">SignedIntegerType</Type>{{.*}}{{.*}}<Type usr="s:Ps10Comparable">Comparable</Type>{{.*}}<Type usr="s:Ps9Equatable">Equatable</Type>{{.*}}</Declaration>
| apache-2.0 | c8c6139859f0d17517788c1c52c21e6e | 44.7 | 229 | 0.712254 | 3.32969 | false | false | false | false |
aclissold/the-oakland-post | The Oakland Post/PushViewController.swift | 2 | 4483 | //
// PushViewController.swift
// TheOaklandPost
//
// Push functionality for authenticated users.
//
// Created by Andrew Clissold on 9/28/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
private enum AlertPurpose: Int {
case PushConfirmation = 0
case PasswordConfirmation = 1
}
class PushViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint!
override func viewDidLoad() {
let sendButton = UIBarButtonItem(title: "Send", style: .Done, target: self, action: "confirmPush")
sendButton.enabled = false
textView.editable = false
textView.selectable = false
navigationItem.rightBarButtonItem = sendButton
textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
registerForKeyboardNotifications()
confirmPassword("Please re-type your\npassword to continue.")
}
// MARK: Password Confirmation
func confirmPassword(message: String) {
let alertView = UIAlertView(title: "Confirm Password",
message: message, delegate: self,
cancelButtonTitle: "Cancel", otherButtonTitles: "Confirm")
alertView.alertViewStyle = .PlainTextInput
alertView.textFieldAtIndex(0)!.secureTextEntry = true
alertView.tag = AlertPurpose.PasswordConfirmation.rawValue
alertView.show()
}
func checkPassword(password: String) {
let currentUser = PFUser.currentUser()!
PFUser.logInWithUsernameInBackground(currentUser.username!, password: password) { (user, error) in
if error != nil {
self.confirmPassword("Confirmation failed. Please try again.")
} else {
self.navigationItem.rightBarButtonItem!.enabled = true
self.textView.editable = true
self.textView.selectable = true
}
}
}
// MARK: Push Confirmation
func confirmPush() {
let alertView = UIAlertView(title: "Are you sure?",
message: "\(textView.text)", delegate: self,
cancelButtonTitle: "Cancel", otherButtonTitles: "Send")
alertView.tag = AlertPurpose.PushConfirmation.rawValue
alertView.show()
}
func sendPush() {
self.navigationItem.rightBarButtonItem!.enabled = false
PFCloud.callFunctionInBackground("push", withParameters: ["message": textView.text]) { (result, error) in
if error != nil {
self.navigationItem.rightBarButtonItem!.enabled = true
showAlertForErrorCode(error!.code)
} else {
self.textView.resignFirstResponder()
self.navigationController!.popViewControllerAnimated(true)
}
}
}
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
let alertPurpose = AlertPurpose(rawValue: alertView.tag)!
switch alertPurpose {
case .PushConfirmation:
if buttonIndex == 1 {
sendPush()
}
case .PasswordConfirmation:
let passwordTextField = alertView.textFieldAtIndex(0)!
passwordTextField.resignFirstResponder()
if buttonIndex == 0 {
navigationController!.popViewControllerAnimated(true)
} else if buttonIndex == 1 {
checkPassword(passwordTextField.text ?? "")
}
}
}
// MARK: Keyboard Handling
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardDidShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardHeight = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size.height
let navBarHeight = navigationController?.navigationBar.frame.size.height ?? 44
self.bottomLayoutConstraint.constant += (keyboardHeight - navBarHeight)
}
func keyboardWillHide(notification: NSNotification) {
self.bottomLayoutConstraint.constant = 20
}
}
| bsd-3-clause | 50957bfaf164a235a0b9f83490370766 | 35.745902 | 113 | 0.654026 | 5.589776 | false | false | false | false |
pandyanandan/PitchPerfect | PitchPerfect/PitchPerfect/PlaySoundsViewController+Audio.swift | 1 | 6058 | //
// PlaySoundsViewController+Audio.swift
// PitchPerfect
//
// Copyright 2016 Udacity. All rights reserved.
//
import UIKit
import AVFoundation
// MARK: - PlaySoundsViewController: AVAudioPlayerDelegate
extension PlaySoundsViewController: AVAudioPlayerDelegate {
// MARK: Alerts
struct Alerts {
static let DismissAlert = "Dismiss"
static let RecordingDisabledTitle = "Recording Disabled"
static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Check Settings."
static let RecordingFailedTitle = "Recording Failed"
static let RecordingFailedMessage = "Something went wrong with your recording."
static let AudioRecorderError = "Audio Recorder Error"
static let AudioSessionError = "Audio Session Error"
static let AudioRecordingError = "Audio Recording Error"
static let AudioFileError = "Audio File Error"
static let AudioEngineError = "Audio Engine Error"
}
// MARK: PlayingState (raw values correspond to sender tags)
enum PlayingState { case playing, notPlaying }
// MARK: Audio Functions
func setupAudio() {
// initialize (recording) audio file
do {
audioFile = try AVAudioFile(forReading: recordedAudioURL as URL)
} catch {
showAlert(Alerts.AudioFileError, message: String(describing: error))
}
}
func playSound(rate: Float? = nil, pitch: Float? = nil, echo: Bool = false, reverb: Bool = false) {
// initialize audio engine components
audioEngine = AVAudioEngine()
// node for playing audio
audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
// node for adjusting rate/pitch
let changeRatePitchNode = AVAudioUnitTimePitch()
if let pitch = pitch {
changeRatePitchNode.pitch = pitch
}
if let rate = rate {
changeRatePitchNode.rate = rate
}
audioEngine.attach(changeRatePitchNode)
// node for echo
let echoNode = AVAudioUnitDistortion()
echoNode.loadFactoryPreset(.multiEcho1)
audioEngine.attach(echoNode)
// node for reverb
let reverbNode = AVAudioUnitReverb()
reverbNode.loadFactoryPreset(.cathedral)
reverbNode.wetDryMix = 50
audioEngine.attach(reverbNode)
// connect nodes
if echo == true && reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, reverbNode, audioEngine.outputNode)
} else if echo == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, audioEngine.outputNode)
} else if reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, reverbNode, audioEngine.outputNode)
} else {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, audioEngine.outputNode)
}
// schedule to play and start the engine!
audioPlayerNode.stop()
audioPlayerNode.scheduleFile(audioFile, at: nil) {
var delayInSeconds: Double = 0
if let lastRenderTime = self.audioPlayerNode.lastRenderTime, let playerTime = self.audioPlayerNode.playerTime(forNodeTime: lastRenderTime) {
if let rate = rate {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) / Double(rate)
} else {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate)
}
}
// schedule a stop timer for when audio finishes playing
self.stopTimer = Timer(timeInterval: delayInSeconds, target: self, selector: #selector(PlaySoundsViewController.stopAudio), userInfo: nil, repeats: false)
RunLoop.main.add(self.stopTimer!, forMode: RunLoopMode.defaultRunLoopMode)
}
do {
try audioEngine.start()
} catch {
showAlert(Alerts.AudioEngineError, message: String(describing: error))
return
}
// play the recording!
audioPlayerNode.play()
}
func stopAudio() {
if let audioPlayerNode = audioPlayerNode {
audioPlayerNode.stop()
}
if let stopTimer = stopTimer {
stopTimer.invalidate()
}
configureUI(.notPlaying)
if let audioEngine = audioEngine {
audioEngine.stop()
audioEngine.reset()
}
}
// MARK: Connect List of Audio Nodes
func connectAudioNodes(_ nodes: AVAudioNode...) {
for x in 0..<nodes.count-1 {
audioEngine.connect(nodes[x], to: nodes[x+1], format: audioFile.processingFormat)
}
}
// MARK: UI Functions
func configureUI(_ playState: PlayingState) {
switch(playState) {
case .playing:
setPlayButtonsEnabled(false)
stopButton.isEnabled = true
case .notPlaying:
setPlayButtonsEnabled(true)
stopButton.isEnabled = false
}
}
func setPlayButtonsEnabled(_ enabled: Bool) {
snailButton.isEnabled = enabled
highPitch.isEnabled = enabled
rabbitButton.isEnabled = enabled
lowPitch.isEnabled = enabled
echoButton.isEnabled = enabled
reverbButton.isEnabled = enabled
}
func showAlert(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| gpl-2.0 | 5cb1c0ad57421b8f050439c1856ac6c3 | 35.059524 | 166 | 0.621657 | 5.462579 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/file formats/DATModel.swift | 1 | 2487 | //
// DATModel.swift
// GoD Tool
//
// Created by Stars Momodu on 02/04/2021.
//
import Foundation
class DATModel: CustomStringConvertible, GoDTexturesContaining {
var data: XGMutableData?
var textureHeaderOffsets: [Int] {
return nodes?.textureHeaderOffsets.map { $0 + 32 } ?? []
}
var textureDataOffsets: [Int] {
return nodes?.textureDataOffsets.map { $0 + 32 } ?? []
}
var texturePaletteData: [(format: Int?, offset: Int?, numberOfEntries: Int)] {
return nodes?.texturePalettes.map {
return (format: $0.format, offset: $0.offset +? 32, numberOfEntries: $0.numberOfEntries)
} ?? []
}
var usesDATTextureHeaderFormat: Bool { return true }
var vertexColourProfile: XGImage {
return nodes?.vertexColourProfile ?? .dummy
}
var modelData: XGMutableData
var header: GoDStructData
var nodes: DATNodes?
var description: String {
return "File: \(modelData.file.path)"
+ header.description
+ "\nNodes:\n"
+ (nodes?.rootNode.description ?? "-")
}
convenience init?(file: XGFiles) {
guard let data = file.data else { return nil }
self.init(data: data)
}
private let datArchiveHeaderStruct = GoDStruct(name: "DAT Model Header", format: [
.word(name: "File Size", description: "", type: .uint),
.word(name: "Data Size", description: "", type: .uint),
.word(name: "Node Count", description: "", type: .uint),
.word(name: "Public Root Nodes Count", description: "", type: .uint),
.word(name: "External Root Nodes Count", description: "", type: .uint),
.array(name: "Padding", description: "", property:
.word(name: "Padding", description: "", type: .null), count: 3)
])
init(data: XGMutableData) {
self.data = data
header = GoDStructData(properties: datArchiveHeaderStruct, fileData: data, startOffset: 0)
let headerLength = datArchiveHeaderStruct.length
modelData = data.getSubDataFromOffset(headerLength, length: data.length - headerLength)
if let nodesSize: Int = header.get("Node Count") *? 4,
let publicCount: Int = header.get("Public Root Nodes Count"),
let externCount: Int = header.get("External Root Nodes Count"),
let dataSize: Int = header.get("Data Size")
{
let rootNodesOffset = dataSize + nodesSize
nodes = DATNodes(firstRootNodeOffset: rootNodesOffset, publicCount: publicCount, externCount: externCount, data: modelData)
}
}
func save() {
let headerLength = datArchiveHeaderStruct.length
data?.replaceData(data: modelData, atOffset: headerLength)
data?.save()
}
}
| gpl-2.0 | 778a9c722dfcb33757c779742ad42f6d | 30.884615 | 126 | 0.695215 | 3.360811 | false | false | false | false |
Vmlweb/Dingle-Swift | request.swift | 1 | 12682 | //
// <class>.swift
// <class>
//
// Created by Vmlweb on 27/05/2015.
// Copyright (c) 2015 Vmlweb. All rights reserved.
//
import Foundation
import AFNetworking
import SwiftyJSON
import CocoaAsyncSocket
class <class> : NSObject, GCDAsyncSocketDelegate, GCDAsyncUdpSocketDelegate{
//Hostnames
var hostnames = Dictionary<String, String>()
override init() {
//hostnames["_METHOD_"] = "_URL_"
<hostnames>
}
//Route Request
func sendRequest(name: String, methods: Array<String>, params: [String : AnyObject],
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Methods
let http = [ "POST", "OPTIONS", "GET", "HEAD", "PUT", "PATCH", "DELETE", "TRACE", "CONNECT" ]
for method in methods{
//Route
if method == "UDP" && hostnames["udp"] != nil{
return dingleUDP(name, params: params, callback: callback)
}else if method == "TCP" && hostnames["udp"] != nil{
return dingleTCP(name, params: params, callback: callback)
}else if contains(http, method) && (hostnames["https"] != nil || hostnames["http"] != nil){
return dingleHTTP(name, method: method, params: params, callback: callback, uploading: uploading, downloading: downloading, stream: stream)
}else{
return callback(success: false, message: "Could not find method to call", output: nil)
}
}
}
//Cancel
func cancelAll(){
httpManager.operationQueue.cancelAllOperations()
tcpClose()
udpClose()
}
//HTTP
var httpManager = AFURLSessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
func dingleHTTP(name: String, method: String, params: [String : AnyObject],
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Setup
var serializer = AFHTTPRequestSerializer()
var error: NSError? = nil
//Check Params
var files = [String : NSURL?]()
var strings = [String : String]()
for (key, value) in params{
//Check if file
if value is NSURL{
files[key] = value as? NSURL
}else{
strings[key] = "\(value)"
}
}
//Hostname
var hostname : String
if let connection = hostnames["https"]{
hostname = "https://\(connection)/"
}else if let connection = hostnames["http"]{
hostname = "http://\(connection)/"
}else{
callback(success: false, message: "Could not find HTTP or HTTPS hostname", output: nil)
return
}
//Make request
var url = hostname + name + "/"
var request : NSMutableURLRequest
if method == "POST"{
request = serializer.multipartFormRequestWithMethod(method, URLString: url, parameters: strings, constructingBodyWithBlock: { (form) -> Void in
//Add files
for (key, value) in files{
if let file = value{
form.appendPartWithFileURL(file, name: key, error: &error)
}
}
}, error: &error)
}else{
request = serializer.requestWithMethod(method, URLString: url, parameters: strings, error: &error)
}
//Error
if let error = error{
callback(success: false, message: error.localizedDescription, output: nil)
}
//Make Operation
var operation = AFHTTPRequestOperation(request: request)
operation.securityPolicy.allowInvalidCertificates = true
if let stream = stream{
operation.outputStream = stream
}
//Completed
operation.setCompletionBlockWithSuccess({ (request, object) -> Void in
if let type = request.response.allHeaderFields["Content-Disposition"] as? String{
//Download
if let stream = stream{
callback(success: true, message: "Response written to stream", output: ["stream":stream])
}else{
callback(success: false, message: "Stream required to download this file", output: nil)
}
}else{
//Stream
if let stream = stream{
callback(success: true, message: "Response written to stream", output: ["stream":stream])
}else{
//JSON?
if let data = object as? NSData{
//Read JSON
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
}
}
}
}, failure: { (request, error) -> Void in
if error.code == -1009{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else if error.code == -1004{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
}else{
callback(success: false, message: error.localizedDescription, output: nil)
}
})
//Downloading
operation.setDownloadProgressBlock { (read, total, expected) -> Void in
if let downloading = downloading{
var expected = Double(expected)
var total = Double(total)
downloading(size: expected, remaining: total, percentage: total / expected)
}
}
//Uploading
operation.setUploadProgressBlock { (read, total, expected) -> Void in
if let uploading = uploading{
var expected = Double(expected)
var total = Double(total)
uploading(size: expected, remaining: total, percentage: total / expected)
}
}
operation.start()
}
//TCP
var tcpSocket : GCDAsyncSocket!
var tcpCallback : ((success: Bool, message: String, output: JSON?)->())?
func dingleTCP(name: String, params: [String : AnyObject], callback: (success: Bool, message: String, output: JSON?)->()){
var error : NSError?
//Connection
var hostname : String
var port : UInt16
if let connection = hostnames["tcp"]{
//Hostname
if let hostname_check = find(connection, ":"){
hostname = connection.substringToIndex(hostname_check)
}else{
callback(success: false, message: "Could not find a TCP hostname", output: nil)
return
}
//Port
if let port_check = find(connection, ":"){
var port_string = connection.substringFromIndex(port_check)
port_string.removeAtIndex(port_string.startIndex)
port = UInt16(port_string.toInt()!)
}else{
callback(success: false, message: "Could not find a TCP port", output: nil)
return
}
}else{
callback(success: false, message: "Could not find TCP hostname", output: nil)
return
}
//Setup socket
tcpSocket = GCDAsyncSocket(delegate:self, delegateQueue: dispatch_get_main_queue())
tcpSocket.connectToHost(hostname, onPort: port, error: &error)
tcpCallback = callback
//Error
if let error = error {
callback(success: false, message: error.localizedDescription, output: nil)
return
}
//Send
var name = "/\(name)/"
var message = name.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
tcpSocket.writeData(message, withTimeout: -1, tag: 0)
tcpSocket.readDataWithTimeout(-1, tag: 0)
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("tcpTimeout"), userInfo: nil, repeats: false)
}
func tcpTimeout(){
if let callback = tcpCallback{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
tcpClose()
}
}
func tcpClose(){
if let socket = tcpSocket{
socket.disconnect()
}
tcpSocket = nil
tcpCallback = nil
}
func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
if let callback = tcpCallback{
if err.code == 8{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else if err.code == 61{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
}else{
callback(success: false, message: err.localizedDescription, output: nil)
}
tcpClose()
}
}
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
if let callback = tcpCallback{
//JSON?
if let data = data{
//Read JSON?
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
tcpClose()
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
tcpClose()
}
}
}
//UDP
var udpSocket : GCDAsyncUdpSocket!
var udpCallback : ((success: Bool, message: String, output: JSON?)->())?
func dingleUDP(name: String, params: [String : AnyObject], callback: (success: Bool, message: String, output: JSON?)->()){
var error : NSError?
//Connection
var hostname : String
var port : UInt16
if let connection = hostnames["udp"]{
//Hostname
if let hostname_check = find(connection, ":"){
hostname = connection.substringToIndex(hostname_check)
}else{
callback(success: false, message: "Could not find a UDP hostname", output: nil)
return
}
//Port
if let port_check = find(connection, ":"){
var port_string = connection.substringFromIndex(port_check)
port_string.removeAtIndex(port_string.startIndex)
port = UInt16(port_string.toInt()!)
}else{
callback(success: false, message: "Could not find a UDP port", output: nil)
return
}
}else{
callback(success: false, message: "Could not find UDP hostname", output: nil)
return
}
//Setup socket
udpSocket = GCDAsyncUdpSocket(delegate:self, delegateQueue: dispatch_get_main_queue())
udpSocket.bindToPort(0, error: &error)
udpSocket.connectToHost(hostname, onPort: port, error: &error)
udpSocket.beginReceiving(&error)
udpCallback = callback
//Error
if let error = error {
callback(success: false, message: error.localizedDescription, output: nil)
return
}
//Send
var message = "/\(name)/".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
udpSocket.sendData(message, withTimeout: -1, tag: 0)
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("udpTimeout"), userInfo: nil, repeats: false)
}
func udpTimeout(){
if let callback = udpCallback{
callback(success: false, message: "Could not connect to server, please contact administrator", output: nil)
udpClose()
}
}
func udpClose(){
if let socket = udpSocket{
socket.close()
}
udpSocket = nil
udpCallback = nil
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
if let callback = udpCallback{
if error.code == 8{
callback(success: false, message: "Could not find server, please check your internet connection", output: nil)
}else{
callback(success: false, message: error.localizedDescription, output: nil)
}
udpClose()
}
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
if let callback = udpCallback{
callback(success: false, message: error.localizedDescription, output: nil)
udpClose()
}
}
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
if let callback = udpCallback{
//JSON?
if let data = data{
//Read JSON?
let json = JSON(data: data)
let success = json["success"].boolValue
let message = json["message"].stringValue
callback(success: success, message: message, output: json["output"])
udpClose()
}else{
callback(success: false, message: "Invalid JSON response", output: nil)
udpClose()
}
}
}
//Request Functions
/*
func _NAME_(_PARAMS_, callback: (success: Bool, message: String, output: JSON?)->()){
_NAME_(_PARAMS_, callback: callback, uploading: nil, downloading: nil, stream: nil)
}
func _NAME_(_PARAMS_,
callback: (success: Bool, message: String, output: JSON?)->(),
uploading: ((size: Double, remaining: Double, percentage: Double)->Void)?,
downloading: ((size: Double, remaining: Double, percentage: Double)->Void)?, stream: NSOutputStream?){
//Parameters
var params = [String : AnyObject]()
if let value = _PARAM_{
if value is NSURL{
params["_PARAM_"] = value as? NSURL
}else{
params["_PARAM_"] = "\(value)"
}
}
//Execute
sendRequest("_NAME_", methods: [ "_METHODS_" ], params: params, callback: callback, uploading: uploading, downloading: downloading, stream: stream)
}
*/
<functions>
} | mit | 18ff64fb52b920a2625876fd28d05b86 | 30.471464 | 149 | 0.676234 | 3.711443 | false | false | false | false |
fcanas/Bayes | Sources/Bayes/BayesianClassifier.swift | 1 | 1829 | //
// BayesianClassifier.swift
// Bayes
//
// Created by Fabian Canas on 5/9/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import Darwin
private let nonZeroLog = 0.00000001
public struct BayesianClassifier<C :Hashable, F :Hashable> {
public typealias Feature = F
public typealias Category = C
/// Initializes a new BayesianClassifier with an empty EventSpace
public init(){ }
/// Initializes a new BayesianClassifier with an existing EventSpace
///
/// - Parameter eventSpace: an EventSpace of Features and Categories
public init(eventSpace: EventSpace<Category,Feature>){
self.eventSpace = eventSpace
}
public var eventSpace :EventSpace<Category,Feature> = EventSpace<Category,Feature>()
/// The most likely category given a sequence of Features
///
/// - Parameter features: A Sequence of observed Features
/// - Returns: the Category with the highest propbability given the features
public func classify <S :Sequence> (_ features :S) -> Category? where S.Iterator.Element == Feature {
return argmax(categoryProbabilities(features))
}
/// The probability of each known Category given a sequence of Features
///
/// - Parameter features: A sequence of features
/// - Returns: A dictionary mapping each known Category to a probability of
/// that Category given the features.
public func categoryProbabilities <S :Sequence> (_ features: S) -> [Category: Double] where S.Iterator.Element == Feature {
return eventSpace.categories.reduce([C:Double](), {(v: [C:Double], c: Category) in
var mv = v
mv[c] = log(self.eventSpace.P(c)) + sum(features.map { log(self.eventSpace.P($0, givenCategory: c) + nonZeroLog) } )
return mv
})
}
}
| mit | 1fc637e86164af0c144cc0d832a1cdb2 | 36.326531 | 128 | 0.671405 | 4.303529 | false | false | false | false |
Alamofire/Alamofire | Source/ServerTrustEvaluation.swift | 2 | 37680 | //
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts.
open class ServerTrustManager {
/// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default.
public let allHostsMustBeEvaluated: Bool
/// The dictionary of policies mapped to a particular host.
public let evaluators: [String: ServerTrustEvaluating]
/// Initializes the `ServerTrustManager` instance with the given evaluators.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - Parameters:
/// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true`
/// by default.
/// - evaluators: A dictionary of evaluators mapped to hosts.
public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) {
self.allHostsMustBeEvaluated = allHostsMustBeEvaluated
self.evaluators = evaluators
}
#if !(os(Linux) || os(Windows))
/// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - Parameter host: The host to use when searching for a matching policy.
///
/// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
/// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching
/// evaluators are found.
open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
guard let evaluator = evaluators[host] else {
if allHostsMustBeEvaluated {
throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host))
}
return nil
}
return evaluator
}
#endif
}
/// A protocol describing the API used to evaluate server trusts.
public protocol ServerTrustEvaluating {
#if os(Linux) || os(Windows)
// Implement this once Linux/Windows has API for evaluating server trusts.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
///
/// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
func evaluate(_ trust: SecTrust, forHost host: String) throws
#endif
}
// MARK: - Server Trust Evaluators
#if !(os(Linux) || os(Windows))
/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
/// host provided by the challenge. Applications are encouraged to always validate the host in production environments
/// to guarantee the validity of the server's certificate chain.
public final class DefaultTrustEvaluator: ServerTrustEvaluating {
private let validateHost: Bool
/// Creates a `DefaultTrustEvaluator`.
///
/// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default.
public init(validateHost: Bool = true) {
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if validateHost {
try trust.af.performValidation(forHost: host)
}
try trust.af.performDefaultValidation(forHost: host)
}
}
/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
/// environments to guarantee the validity of the server's certificate chain.
public final class RevocationTrustEvaluator: ServerTrustEvaluating {
/// Represents the options to be use when evaluating the status of a certificate.
/// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants).
public struct Options: OptionSet {
/// Perform revocation checking using the CRL (Certification Revocation List) method.
public static let crl = Options(rawValue: kSecRevocationCRLMethod)
/// Consult only locally cached replies; do not use network access.
public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
/// Perform revocation checking using OCSP (Online Certificate Status Protocol).
public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
/// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
/// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
/// "best attempt" basis, where failure to reach the server is not considered fatal.
public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
/// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
/// certificate and the value of `preferCRL`.
public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
/// The raw value of the option.
public let rawValue: CFOptionFlags
/// Creates an `Options` value with the given `CFOptionFlags`.
///
/// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
public init(rawValue: CFOptionFlags) {
self.rawValue = rawValue
}
}
private let performDefaultValidation: Bool
private let validateHost: Bool
private let options: Options
/// Creates a `RevocationTrustEvaluator` using the provided parameters.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
/// performing the default evaluation, even if `performDefaultValidation` is `false`.
/// `true` by default.
/// - options: The `Options` to use to check the revocation status of the certificate. `.any` by
/// default.
public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) {
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
self.options = options
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options))
} else {
try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in
AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options))
}
}
}
}
#if swift(>=5.5)
extension ServerTrustEvaluating where Self == RevocationTrustEvaluator {
/// Provides a default `RevocationTrustEvaluator` instance.
public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() }
/// Creates a `RevocationTrustEvaluator` using the provided parameters.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. `true` by default.
/// - options: The `Options` to use to check the revocation status of the certificate. `.any`
/// by default.
/// - Returns: The `RevocationTrustEvaluator`.
public static func revocationChecking(performDefaultValidation: Bool = true,
validateHost: Bool = true,
options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator {
RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation,
validateHost: validateHost,
options: options)
}
}
#endif
/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
private let certificates: [SecCertificate]
private let acceptSelfSignedCertificates: Bool
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters.
///
/// - Parameters:
/// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der`
/// certificates in `Bundle.main` by default.
/// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing
/// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
/// FALSE IN PRODUCTION!
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. `true` by default.
public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
acceptSelfSignedCertificates: Bool = false,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.certificates = certificates
self.acceptSelfSignedCertificates = acceptSelfSignedCertificates
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !certificates.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
if acceptSelfSignedCertificates {
try trust.af.setAnchorCertificates(certificates)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let serverCertificatesData = Set(trust.af.certificateData)
let pinnedCertificatesData = Set(certificates.af.data)
let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
if !pinnedCertificatesInServerData {
throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host,
trust: trust,
pinnedCertificates: certificates,
serverCertificates: trust.af.certificates))
}
}
}
#if swift(>=5.5)
extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator {
/// Provides a default `PinnedCertificatesTrustEvaluator` instance.
public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() }
/// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters.
///
/// - Parameters:
/// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der`
/// certificates in `Bundle.main` by default.
/// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing
/// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
/// FALSE IN PRODUCTION!
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition
/// to performing the default evaluation, even if `performDefaultValidation` is
/// `false`. `true` by default.
public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates,
acceptSelfSignedCertificates: Bool = false,
performDefaultValidation: Bool = true,
validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator {
PinnedCertificatesTrustEvaluator(certificates: certificates,
acceptSelfSignedCertificates: acceptSelfSignedCertificates,
performDefaultValidation: performDefaultValidation,
validateHost: validateHost)
}
}
#endif
/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
/// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate chain in production
/// environments.
public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
private let keys: [SecKey]
private let performDefaultValidation: Bool
private let validateHost: Bool
/// Creates a `PublicKeysTrustEvaluator` from the provided parameters.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all
/// certificates included in the main bundle.
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
/// performing the default evaluation, even if `performDefaultValidation` is `false`.
/// `true` by default.
public init(keys: [SecKey] = Bundle.main.af.publicKeys,
performDefaultValidation: Bool = true,
validateHost: Bool = true) {
self.keys = keys
self.performDefaultValidation = performDefaultValidation
self.validateHost = validateHost
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
guard !keys.isEmpty else {
throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound)
}
if performDefaultValidation {
try trust.af.performDefaultValidation(forHost: host)
}
if validateHost {
try trust.af.performValidation(forHost: host)
}
let pinnedKeysInServerKeys: Bool = {
for serverPublicKey in trust.af.publicKeys {
for pinnedPublicKey in keys {
if serverPublicKey == pinnedPublicKey {
return true
}
}
}
return false
}()
if !pinnedKeysInServerKeys {
throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host,
trust: trust,
pinnedKeys: keys,
serverKeys: trust.af.publicKeys))
}
}
}
#if swift(>=5.5)
extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator {
/// Provides a default `PublicKeysTrustEvaluator` instance.
public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() }
/// Creates a `PublicKeysTrustEvaluator` from the provided parameters.
///
/// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
/// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
///
/// - Parameters:
/// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all
/// certificates included in the main bundle.
/// - performDefaultValidation: Determines whether default validation should be performed in addition to
/// evaluating the pinned certificates. `true` by default.
/// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
/// performing the default evaluation, even if `performDefaultValidation` is `false`.
/// `true` by default.
public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys,
performDefaultValidation: Bool = true,
validateHost: Bool = true) -> PublicKeysTrustEvaluator {
PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost)
}
}
#endif
/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
/// evaluators consider it valid.
public final class CompositeTrustEvaluator: ServerTrustEvaluating {
private let evaluators: [ServerTrustEvaluating]
/// Creates a `CompositeTrustEvaluator` from the provided evaluators.
///
/// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
public init(evaluators: [ServerTrustEvaluating]) {
self.evaluators = evaluators
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
try evaluators.evaluate(trust, forHost: host)
}
}
#if swift(>=5.5)
extension ServerTrustEvaluating where Self == CompositeTrustEvaluator {
/// Creates a `CompositeTrustEvaluator` from the provided evaluators.
///
/// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator {
CompositeTrustEvaluator(evaluators: evaluators)
}
}
#endif
/// Disables all evaluation which in turn will always consider any server trust as valid.
///
/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
///
/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.")
public typealias DisabledEvaluator = DisabledTrustEvaluator
/// Disables all evaluation which in turn will always consider any server trust as valid.
///
///
/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
///
/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
public final class DisabledTrustEvaluator: ServerTrustEvaluating {
/// Creates an instance.
public init() {}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {}
}
// MARK: - Extensions
extension Array where Element == ServerTrustEvaluating {
#if os(Linux) || os(Windows)
// Add this same convenience method for Linux/Windows.
#else
/// Evaluates the given `SecTrust` value for the given `host`.
///
/// - Parameters:
/// - trust: The `SecTrust` value to evaluate.
/// - host: The host for which to evaluate the `SecTrust` value.
///
/// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
for evaluator in self {
try evaluator.evaluate(trust, forHost: host)
}
}
#endif
}
extension Bundle: AlamofireExtended {}
extension AlamofireExtension where ExtendedType: Bundle {
/// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
public var certificates: [SecCertificate] {
paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
guard
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
return certificate
}
}
/// Returns all public keys for the valid certificates in the bundle.
public var publicKeys: [SecKey] {
certificates.af.publicKeys
}
/// Returns all pathnames for the resources identified by the provided file extensions.
///
/// - Parameter types: The filename extensions locate.
///
/// - Returns: All pathnames for the given filename extensions.
public func paths(forResourcesOfTypes types: [String]) -> [String] {
Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) }))
}
}
extension SecTrust: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == SecTrust {
/// Evaluates `self` after applying the `SecPolicy` value provided.
///
/// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation.
///
/// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation.
@available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
public func evaluate(afterApplying policy: SecPolicy) throws {
try apply(policy: policy).af.evaluate()
}
/// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed.
///
/// - Parameters:
/// - policy: The `SecPolicy` used to evaluate `self`.
/// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`.
/// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails.
@available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
@available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)")
@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)")
public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
try apply(policy: policy).af.validate(errorProducer: errorProducer)
}
/// Applies a `SecPolicy` to `self`, throwing if it fails.
///
/// - Parameter policy: The `SecPolicy`.
///
/// - Returns: `self`, with the policy applied.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason.
public func apply(policy: SecPolicy) throws -> SecTrust {
let status = SecTrustSetPolicies(type, policy)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type,
policy: policy,
status: status))
}
return type
}
/// Evaluate `self`, throwing an `Error` if evaluation fails.
///
/// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from
/// the underlying evaluation.
@available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
public func evaluate() throws {
var error: CFError?
let evaluationSucceeded = SecTrustEvaluateWithError(type, &error)
if !evaluationSucceeded {
throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error))
}
}
/// Validate `self`, passing any failure values through `errorProducer`.
///
/// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an
/// `Error`.
/// - Throws: The `Error` produced by the `errorProducer` closure.
@available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
@available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()")
@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()")
public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(type, &result)
guard status.af.isSuccess && result.af.isSuccess else {
throw errorProducer(status, result)
}
}
/// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain.
///
/// - Parameter certificates: The `SecCertificate`s to add to the chain.
/// - Throws: Any error produced when applying the new certificate chain.
public func setAnchorCertificates(_ certificates: [SecCertificate]) throws {
// Add additional anchor certificates.
let status = SecTrustSetAnchorCertificates(type, certificates as CFArray)
guard status.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status,
certificates: certificates))
}
// Trust only the set anchor certs.
let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true)
guard onlyStatus.af.isSuccess else {
throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus,
certificates: certificates))
}
}
/// The public keys contained in `self`.
public var publicKeys: [SecKey] {
certificates.af.publicKeys
}
#if swift(>=5.5.1) // Xcode 13.1 / 2021 SDKs.
/// The `SecCertificate`s contained in `self`.
public var certificates: [SecCertificate] {
if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) {
return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? []
} else {
return (0..<SecTrustGetCertificateCount(type)).compactMap { index in
SecTrustGetCertificateAtIndex(type, index)
}
}
}
#else
/// The `SecCertificate`s contained in `self`.
public var certificates: [SecCertificate] {
(0..<SecTrustGetCertificateCount(type)).compactMap { index in
SecTrustGetCertificateAtIndex(type, index)
}
}
#endif
/// The `Data` values for all certificates contained in `self`.
public var certificateData: [Data] {
certificates.af.data
}
/// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname.
///
/// - Parameter host: The hostname, used only in the error output if validation fails.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
public func performDefaultValidation(forHost host: String) throws {
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
try evaluate(afterApplying: SecPolicy.af.default)
} else {
try validate(policy: SecPolicy.af.default) { status, result in
AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result)))
}
}
}
/// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as
/// hostname validation.
///
/// - Parameter host: The hostname to use in the validation.
/// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
public func performValidation(forHost host: String) throws {
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
try evaluate(afterApplying: SecPolicy.af.hostname(host))
} else {
try validate(policy: SecPolicy.af.hostname(host)) { status, result in
AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result)))
}
}
}
}
extension SecPolicy: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == SecPolicy {
/// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match.
public static let `default` = SecPolicyCreateSSL(true, nil)
/// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname.
///
/// - Parameter hostname: The hostname to validate against.
///
/// - Returns: The `SecPolicy`.
public static func hostname(_ hostname: String) -> SecPolicy {
SecPolicyCreateSSL(true, hostname as CFString)
}
/// Creates a `SecPolicy` which checks the revocation of certificates.
///
/// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation.
///
/// - Returns: The `SecPolicy`.
/// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed`
/// if the policy cannot be created.
public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy {
guard let policy = SecPolicyCreateRevocation(options.rawValue) else {
throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed)
}
return policy
}
}
extension Array: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == [SecCertificate] {
/// All `Data` values for the contained `SecCertificate`s.
public var data: [Data] {
type.map { SecCertificateCopyData($0) as Data }
}
/// All public `SecKey` values for the contained `SecCertificate`s.
public var publicKeys: [SecKey] {
type.compactMap(\.af.publicKey)
}
}
extension SecCertificate: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == SecCertificate {
/// The public key for `self`, if it can be extracted.
///
/// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported.
///
public var publicKey: SecKey? {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust)
guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
#if swift(>=5.3.1) // SecTrustCopyKey not visible in Xcode <= 12.1, despite being a 2020 API.
if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) {
return SecTrustCopyKey(createdTrust)
} else {
return SecTrustCopyPublicKey(createdTrust)
}
#else
return SecTrustCopyPublicKey(createdTrust)
#endif
}
}
extension OSStatus: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == OSStatus {
/// Returns whether `self` is `errSecSuccess`.
public var isSuccess: Bool { type == errSecSuccess }
}
extension SecTrustResultType: AlamofireExtended {}
extension AlamofireExtension where ExtendedType == SecTrustResultType {
/// Returns whether `self is `.unspecified` or `.proceed`.
public var isSuccess: Bool {
type == .unspecified || type == .proceed
}
}
#endif
| mit | 399e4d01797c55e49b13b6b7568afd4a | 49.713324 | 228 | 0.651327 | 5.394417 | false | false | false | false |
rubiconmd/rubicon-ios-sdk | Source/RubiconMDiOSSDK.swift | 1 | 20560 | //
// RubiconMDiOSSDK.swift
// RubiconMDiOSSDK
//
// Created by Vanessa Cantero Gómez on 19/12/14.
// Copyright (c) 2014 RubiconMD. All rights reserved.
//
import Foundation
/**
POST response and device token format.
*/
private let POST_RESPONSE_FORMAT = "{\"response\":{\"body\":\"%@\",\"purpose\":\"specialist_opinion\",\"need_reply\":\"%@\"}}"
private let POST_DEVICE_TOKEN_FORMAT = "{\"device\": {\"token\":\"%@\"}}"
/**
Case states
*/
public enum CaseState: String {
case Accepted = "accepted"
case NeedSpecialistReply = "need_specialist_reply"
case NeedPCPReply = "need_pcp_reply"
case AwaitingReview = "awaiting_review"
case Assigned = "assigned"
case Closed = "closed"
}
/**
Actions on cases: accept or decline.
*/
public enum AssignedCaseActions {
case Accept
case Decline
}
/**
HTTP method definitions.
*/
public enum Method: String {
case GET = "GET"
case POST = "POST"
}
/**
HTTPStatusCode struct contains the HTTP status code and its description.
*/
public struct HTTPStatusCode {
public let statusCode: Int
public let description: String?
init(_ statusCode: Int) {
self.statusCode = statusCode
self.description = selectDescription(self.statusCode)
}
func selectDescription(statusCode: Int) -> String {
var description: String
switch statusCode {
case 200:
description = "Request accepted."
case 400:
description = "Bad Request – Your request is incorrect."
case 401:
description = "Unauthorized – Your access token must be expired."
case 402:
description = "Case could not be accepted at this time."
case 404:
description = "Not Found."
case 500:
description = "Internal Server Error – We had a problem with our server. Try again later."
default:
description = "The status code is not supported."
}
return description
}
}
public class Manager {
/// The session.
public var session: NSURLSession
/**
A shared instance of Manager.
*/
public class var sharedInstance : Manager {
struct Singleton {
static let instance = Manager()
}
return Singleton.instance
}
required public init() {
self.session = NSURLSession.sharedSession()
}
/**
Crates JSON object constructed from the response data using NSJSONSerialization with the specified reading options.
:param: data The data returned by the request.
:param: options The JSON serialization reading options. .AllowFragments by default.
:returns: A tuple with the JSON object and the serializationError (if any).
*/
public func JSONSResponseSerializer(data: NSData, options: NSJSONReadingOptions = .AllowFragments) -> (AnyObject?, NSError?) {
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &serializationError)
return (JSON, serializationError)
}
/** Associates an accessToken with the username and password
:param: user The username
:param: password The password
:returns: closure With accessToken, a HTTPStatusCode and a SerializationError (nil if there's no error)
*/
public func accessToken(user: String, password: String,
completionHandler: ((accessToken: String?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: ACCESS_TOKEN, BASE_URL, user, password, CLIENT_ID, CLIENT_SECRET)
let request = URLRequest(.POST, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var token: String?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
token = JSONResponse?["access_token"] as? String
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(accessToken: token, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves a list of cases given its state.
:param: state The state of cases you want the method to retrieve. Check CaseState for possibles states.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with the array of cases, the HTTPStatusCode and a SerializationError (if any)
*/
public func casesReferrals(state: CaseState, accessToken: String,
completionHandler: ((referrals: [Dictionary<String, String>]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: CASE_REFERRALS, BASE_URL, accessToken, state.rawValue)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var referrals: [Dictionary<String, String>]?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
referrals = JSONResponse? as? [Dictionary<String, String>]
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(referrals: referrals, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the description of a case.
:param: case_id The case_id of the case.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with a Dictionary with the description of cases, the HTTPStatusCode and a SerializationError (if any)
*/
public func caseDescription(case_id: String, accessToken: String,
completionHandler: ((caseDescription: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: CASE_DESCRIPTION, BASE_URL, case_id, accessToken)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var referrals: NSDictionary?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
referrals = JSONResponse? as? NSDictionary
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(caseDescription: referrals, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the case updated if a case has been successfully accepted. If the case is rejected, it retrieves a success message.
:param: case_id The case_id of the case.
:param: action The action on the case.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with a Dictionary with the case updated or a reject message, the HTTPStatusCode and a SerializationError (if any)
*/
public func actionOnAssignedCase(case_id: String, action: AssignedCaseActions, accessToken: String,
completionHandler: ((caseUpdated: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let urlAction = action == AssignedCaseActions.Accept ? ACCEPT_CASE : DECLINE_CASE
let URLString = NSString(format: urlAction, BASE_URL, case_id, accessToken)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var referral: NSDictionary?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
referral = JSONResponse? as? NSDictionary
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(caseUpdated: referral, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the responses of a case.
:param: case_id The case_id of the case.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with a Dictionary with the case's responses, the HTTPStatusCode and a SerializationError (if any)
*/
public func caseResponses(case_id: String, accessToken: String,
completionHandler: ((responses: [NSDictionary]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: CASE_RESPONSES, case_id, accessToken)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var responses: [NSDictionary]?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
responses = JSONResponse? as? [NSDictionary]
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(responses: responses, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the attachments urls of a case.
:param: case_id The case_id of the case.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with a Dictionary with the case's attachments urls, the HTTPStatusCode and a SerializationError (if any)
*/
public func caseAttachments(case_id: String, accessToken: String,
completionHandler: ((attachments: [NSDictionary]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: CASE_ATTACHMENTS, BASE_URL, case_id, accessToken)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var attachments: [NSDictionary]?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
attachments = JSONResponse? as? [NSDictionary]
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(attachments: attachments, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the user information.
:param: accessToken The accessToken associated with your username and password.
:returns: a closure with a Dictionary with the user information, the HTTPStatusCode and a SerializationError (if any)
*/
public func userInformation(accessToken: String,
completionHandler: ((userInformation: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: USER_INFORMATION, BASE_URL, accessToken)
let request = URLRequest(.GET, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
var (JSONResponse: AnyObject?, serializationError: NSError?)
var userInformation: NSDictionary?
if (error == nil) {
(JSONResponse, serializationError) = self.JSONSResponseSerializer(data)
userInformation = JSONResponse? as? NSDictionary
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(userInformation: userInformation, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the submitted response.
:param: accessToken The accessToken associated with your username and password.
:param: case_id The case_id of the case.
:param: content The content of the response.
:param: needReply Depending on your need of the PCP to reply to your response.
:returns: a closure with a Dictionary with the submitted response, the HTTPStatusCode and a SerializationError (if any)
*/
public func submitResponse(accessToken: String, case_id: String, content: String, needReply: Bool,
completionHandler: ((response: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: CASE_RESPONSES, BASE_URL, case_id, accessToken)
let POSTResponse = NSString(format: POST_RESPONSE_FORMAT, content, needReply)
POSTResponse.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
POSTResponse.stringByReplacingOccurrencesOfString("\n ", withString:"\\n")
let request = POSTRequest(POSTResponse, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
let (JSONResponse: AnyObject?, serializationError: NSError?) = self.JSONSResponseSerializer(data)
let response = JSONResponse? as? NSDictionary
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(response: response, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
/**
Retrieves the user id and the device token.
:param: accessToken The accessToken associated with your username and password.
:param: deviceToken The device token you get when you register the device for push notifications.
:returns: a closure with a Dictionary with the user is and the device token, the HTTPStatusCode and a SerializationError (if any)
*/
public func sendDeviceToken(accessToken: String, deviceToken: String,
completionHandler: ((response: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
let URLString = NSString(format: REGISTER_DEVICE_PN, BASE_URL, accessToken)
let POSTResponse = NSString(format: POST_DEVICE_TOKEN_FORMAT, deviceToken)
let request = POSTRequest(POSTResponse, URLString)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let HTTPStatusCode = self.httpStatusCode(response)
let (JSONResponse: AnyObject?, serializationError: NSError?) = self.JSONSResponseSerializer(data)
let response = JSONResponse? as? NSDictionary
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(response: response, HTTPStatusCode: HTTPStatusCode, serializationError: serializationError)
})
})
task.resume()
}
//MARK - Convenience
public func URLRequest(method: Method, _ URLString: String) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
private func POSTRequest(response: String, _ URLString: String) -> NSMutableURLRequest {
let request = URLRequest(.POST, URLString) as NSMutableURLRequest
let postResponseData: NSData = response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
request.HTTPBody = postResponseData
request.addValue("application/json;charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue(NSString(format: "%d", postResponseData.length) , forHTTPHeaderField: "Content-Length")
return request;
}
private func httpStatusCode(response: NSURLResponse) -> HTTPStatusCode {
var response = response as NSHTTPURLResponse
let httpStatusCode = HTTPStatusCode(response.statusCode)
return httpStatusCode
}
}
public func accessToken(user: String, password: String,
completionHandler: ((accessToken: String?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.accessToken(user, password: password, completionHandler: completionHandler)
}
public func casesReferrals(state: CaseState, accessToken: String,
completionHandler: ((referrals: [Dictionary<String, String>]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.casesReferrals(state, accessToken: accessToken, completionHandler: completionHandler)
}
public func caseDescription(case_id: String, accessToken: String,
completionHandler: ((caseDescription: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.caseDescription(case_id, accessToken: accessToken, completionHandler: completionHandler)
}
public func actionOnAssignedCase(case_id: String, action: AssignedCaseActions, accessToken: String,
completionHandler: ((caseUpdated: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.actionOnAssignedCase(case_id, action: action, accessToken: accessToken, completionHandler: completionHandler)
}
public func caseResponses(case_id: String, accessToken: String,
completionHandler: ((responses: [NSDictionary]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.caseResponses(case_id, accessToken: accessToken, completionHandler: completionHandler)
}
public func caseAttachments(case_id: String, accessToken: String,
completionHandler: ((attachments: [NSDictionary]?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.caseAttachments(case_id, accessToken: accessToken, completionHandler: completionHandler)
}
public func userInformation(accessToken: String,
completionHandler: ((userInformation: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.userInformation(accessToken, completionHandler: completionHandler)
}
public func submitResponse(accessToken: String, case_id: String, content: String, needReply: Bool,
completionHandler: ((response: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.submitResponse(accessToken, case_id: case_id, content: content, needReply: needReply, completionHandler: completionHandler)
}
public func sendDeviceToken(accessToken: String, deviceToken: String,
completionHandler: ((response: NSDictionary?, HTTPStatusCode: HTTPStatusCode, serializationError: NSError?) -> Void)) {
return Manager.sharedInstance.sendDeviceToken(accessToken, deviceToken: deviceToken, completionHandler: completionHandler)
} | mit | 2ad7b434a5dfcb9c9b2afff92a08ce90 | 40.691684 | 161 | 0.67922 | 5.232434 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/Hue/Source/iOS+tvOS/UIColor+Hue.swift | 3 | 7749 | import UIKit
// MARK: - Color Builders
public extension UIColor {
/// Constructing color from hex string
///
/// - Parameter hex: A hex string, can either contain # or not
convenience init(hex string: String) {
var hex = string.hasPrefix("#")
? String(string.dropFirst())
: string
guard hex.count == 3 || hex.count == 6
else {
self.init(white: 1.0, alpha: 0.0)
return
}
if hex.count == 3 {
for (index, char) in hex.enumerated() {
hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2))
}
}
guard let intCode = Int(hex, radix: 16) else {
self.init(white: 1.0, alpha: 0.0)
return
}
self.init(
red: CGFloat((intCode >> 16) & 0xFF) / 255.0,
green: CGFloat((intCode >> 8) & 0xFF) / 255.0,
blue: CGFloat((intCode) & 0xFF) / 255.0, alpha: 1.0)
}
/// Adjust color based on saturation
///
/// - Parameter minSaturation: The minimun saturation value
/// - Returns: The adjusted color
public func color(minSaturation: CGFloat) -> UIColor {
var (hue, saturation, brightness, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return saturation < minSaturation
? UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha)
: self
}
/// Convenient method to change alpha value
///
/// - Parameter value: The alpha value
/// - Returns: The alpha adjusted color
public func alpha(_ value: CGFloat) -> UIColor {
return withAlphaComponent(value)
}
}
// MARK: - Helpers
public extension UIColor {
public func hex(hashPrefix: Bool = true) -> String {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
let prefix = hashPrefix ? "#" : ""
return String(format: "\(prefix)%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
internal func rgbComponents() -> [CGFloat] {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
return [r, g, b]
}
public var isDark: Bool {
let RGB = rgbComponents()
return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5
}
public var isBlackOrWhite: Bool {
let RGB = rgbComponents()
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
public var isBlack: Bool {
let RGB = rgbComponents()
return (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
public var isWhite: Bool {
let RGB = rgbComponents()
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91)
}
public func isDistinct(from color: UIColor) -> Bool {
let bg = rgbComponents()
let fg = color.rgbComponents()
let threshold: CGFloat = 0.25
var result = false
if abs(bg[0] - fg[0]) > threshold || abs(bg[1] - fg[1]) > threshold || abs(bg[2] - fg[2]) > threshold {
if abs(bg[0] - bg[1]) < 0.03 && abs(bg[0] - bg[2]) < 0.03 {
if abs(fg[0] - fg[1]) < 0.03 && abs(fg[0] - fg[2]) < 0.03 {
result = false
}
}
result = true
}
return result
}
public func isContrasting(with color: UIColor) -> Bool {
let bg = rgbComponents()
let fg = color.rgbComponents()
let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2]
let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2]
let contrast = bgLum > fgLum
? (bgLum + 0.05) / (fgLum + 0.05)
: (fgLum + 0.05) / (bgLum + 0.05)
return 1.6 < contrast
}
}
// MARK: - Gradient
public extension Array where Element : UIColor {
public func gradient(_ transform: ((_ gradient: inout CAGradientLayer) -> CAGradientLayer)? = nil) -> CAGradientLayer {
var gradient = CAGradientLayer()
gradient.colors = self.map { $0.cgColor }
if let transform = transform {
gradient = transform(&gradient)
}
return gradient
}
}
// MARK: - Components
public extension UIColor {
var redComponent: CGFloat {
var red: CGFloat = 0
getRed(&red, green: nil , blue: nil, alpha: nil)
return red
}
var greenComponent: CGFloat {
var green: CGFloat = 0
getRed(nil, green: &green , blue: nil, alpha: nil)
return green
}
var blueComponent: CGFloat {
var blue: CGFloat = 0
getRed(nil, green: nil , blue: &blue, alpha: nil)
return blue
}
var alphaComponent: CGFloat {
var alpha: CGFloat = 0
getRed(nil, green: nil , blue: nil, alpha: &alpha)
return alpha
}
var hueComponent: CGFloat {
var hue: CGFloat = 0
getHue(&hue, saturation: nil, brightness: nil, alpha: nil)
return hue
}
var saturationComponent: CGFloat {
var saturation: CGFloat = 0
getHue(nil, saturation: &saturation, brightness: nil, alpha: nil)
return saturation
}
var brightnessComponent: CGFloat {
var brightness: CGFloat = 0
getHue(nil, saturation: nil, brightness: &brightness, alpha: nil)
return brightness
}
}
// MARK: - Blending
public extension UIColor {
/**adds hue, saturation, and brightness to the HSB components of this color (self)*/
public func add(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> UIColor {
var (oldHue, oldSat, oldBright, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
getHue(&oldHue, saturation: &oldSat, brightness: &oldBright, alpha: &oldAlpha)
// make sure new values doesn't overflow
var newHue = oldHue + hue
while newHue < 0.0 { newHue += 1.0 }
while newHue > 1.0 { newHue -= 1.0 }
let newBright: CGFloat = max(min(oldBright + brightness, 1.0), 0)
let newSat: CGFloat = max(min(oldSat + saturation, 1.0), 0)
let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0)
return UIColor(hue: newHue, saturation: newSat, brightness: newBright, alpha: newAlpha)
}
/**adds red, green, and blue to the RGB components of this color (self)*/
public func add(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
var (oldRed, oldGreen, oldBlue, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
getRed(&oldRed, green: &oldGreen, blue: &oldBlue, alpha: &oldAlpha)
// make sure new values doesn't overflow
let newRed: CGFloat = max(min(oldRed + red, 1.0), 0)
let newGreen: CGFloat = max(min(oldGreen + green, 1.0), 0)
let newBlue: CGFloat = max(min(oldBlue + blue, 1.0), 0)
let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0)
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
}
public func add(hsb color: UIColor) -> UIColor {
var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return self.add(hue: h, saturation: s, brightness: b, alpha: 0)
}
public func add(rgb color: UIColor) -> UIColor {
return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: 0)
}
public func add(hsba color: UIColor) -> UIColor {
var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return self.add(hue: h, saturation: s, brightness: b, alpha: a)
}
/**adds the rgb components of two colors*/
public func add(rgba color: UIColor) -> UIColor {
return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: color.alphaComponent)
}
}
| apache-2.0 | b693c3e744a0f0f8392de618dbe08545 | 30.37247 | 129 | 0.608466 | 3.351644 | false | false | false | false |
ppamorim/HeroinPlayer | Example/HeroinPlayer/ViewController.swift | 1 | 1868 | //
// Created by Pedro Paulo Amorim on 10/03/2015.
// Copyright (c) 2015 Pedro Paulo Amorim. 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.
//
import UIKit
import PureLayout
import HeroinPlayer
class ViewController: UIViewController {
var contraintsUpdated = false;
var heroinPlayer : HeroinPlayer = {
let heroinPlayer = HeroinPlayer.newAutoLayoutView()
heroinPlayer.backgroundColor = UIColor.greenColor()
return heroinPlayer
}()
override func loadView() {
super.loadView()
self.view.addSubview(heroinPlayer)
self.view.setNeedsUpdateConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
heroinPlayer
.setUrl("http://p.demo.flowplayer.netdna-cdn.com/vod/demo.flowplayer/bbb-800.mp4")
.build()
.start()
}
override func updateViewConstraints() {
if !contraintsUpdated {
heroinPlayer.autoMatchDimension(.Width, toDimension: .Width, ofView: self.view)
heroinPlayer.autoMatchDimension(.Height, toDimension: .Width, ofView: heroinPlayer, withMultiplier: 0.5625)
heroinPlayer.autoCenterInSuperview()
contraintsUpdated = true
}
super.updateViewConstraints()
}
override func didReceiveMemoryWarning() {
heroinPlayer.kill()
super.didReceiveMemoryWarning()
}
} | mit | 9a3fb73a38fb050bb7496ce502e622e1 | 30.15 | 113 | 0.727516 | 4.364486 | false | false | false | false |
alskipp/Argo | Argo/Extensions/RawRepresentable.swift | 4 | 740 | public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == String {
static func decode(json: JSON) -> Decoded<Self> {
switch json {
case let .String(s): return self.init(rawValue: s).map(pure) ?? .typeMismatch("rawValue for \(self)", actual: json)
default: return .typeMismatch("String", actual: json)
}
}
}
public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == Int {
static func decode(json: JSON) -> Decoded<Self> {
switch json {
case let .Number(n): return self.init(rawValue: n as Int).map(pure) ?? .typeMismatch("rawValue for \(self)", actual: json)
default: return .typeMismatch("Int", actual: json)
}
}
}
| mit | 6d9ea8838d36ead9172e18cce53c3548 | 42.529412 | 126 | 0.682432 | 3.915344 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Settings/CustomSearchViewController.swift | 3 | 10021 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import SnapKit
import Storage
import SDWebImage
import Deferred
private let log = Logger.browserLogger
class CustomSearchError: MaybeErrorType {
enum Reason {
case DuplicateEngine, FormInput
}
var reason: Reason!
internal var description: String {
return "Search Engine Not Added"
}
init(_ reason: Reason) {
self.reason = reason
}
}
class CustomSearchViewController: SettingsTableViewController {
fileprivate var urlString: String?
fileprivate var engineTitle = ""
fileprivate lazy var spinnerView: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsAddCustomEngineTitle
view.addSubview(spinnerView)
spinnerView.snp.makeConstraints { make in
make.center.equalTo(self.view.snp.center)
}
}
var successCallback: (() -> Void)?
fileprivate func addSearchEngine(_ searchQuery: String, title: String) {
spinnerView.startAnimating()
let trimmedQuery = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
createEngine(forQuery: trimmedQuery, andName: trimmedTitle).uponQueue(DispatchQueue.main) { result in
self.spinnerView.stopAnimating()
guard let engine = result.successValue else {
let alert: UIAlertController
let error = result.failureValue as? CustomSearchError
alert = (error?.reason == .DuplicateEngine) ?
ThirdPartySearchAlerts.duplicateCustomEngine() : ThirdPartySearchAlerts.incorrectCustomEngineForm()
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(engine)
CATransaction.begin() // Use transaction to call callback after animation has been completed
CATransaction.setCompletionBlock(self.successCallback)
_ = self.navigationController?.popViewController(animated: true)
CATransaction.commit()
}
}
func createEngine(forQuery query: String, andName name: String) -> Deferred<Maybe<OpenSearchEngine>> {
let deferred = Deferred<Maybe<OpenSearchEngine>>()
guard let template = getSearchTemplate(withString: query),
let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), url.isWebPage() else {
deferred.fill(Maybe(failure: CustomSearchError(.FormInput)))
return deferred
}
// ensure we haven't already stored this template
guard engineExists(name: name, template: template) == false else {
deferred.fill(Maybe(failure: CustomSearchError(.DuplicateEngine)))
return deferred
}
FaviconFetcher.fetchFavImageForURL(forURL: url, profile: profile).uponQueue(DispatchQueue.main) { result in
let image = result.successValue ?? FaviconFetcher.getDefaultFavicon(url)
let engine = OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
//Make sure a valid scheme is used
let url = engine.searchURLForQuery("test")
let maybe = (url == nil) ? Maybe(failure: CustomSearchError(.FormInput)) : Maybe(success: engine)
deferred.fill(maybe)
}
return deferred
}
private func engineExists(name: String, template: String) -> Bool {
return profile.searchEngines.orderedEngines.contains { (engine) -> Bool in
return engine.shortName == name || engine.searchTemplate == template
}
}
func getSearchTemplate(withString query: String) -> String? {
let SearchTermComponent = "%s" //Placeholder in User Entered String
let placeholder = "{searchTerms}" //Placeholder looked for when using Custom Search Engine in OpenSearch.swift
if query.contains(SearchTermComponent) {
return query.replacingOccurrences(of: SearchTermComponent, with: placeholder)
}
return nil
}
override func generateSettings() -> [SettingSection] {
func URLFromString(_ string: String?) -> URL? {
guard let string = string else {
return nil
}
return URL(string: string)
}
let titleField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineTitlePlaceholder, settingIsValid: { text in
return text != nil && text != ""
}, settingDidChange: {fieldText in
guard let title = fieldText else {
return
}
self.engineTitle = title
})
titleField.textField.accessibilityIdentifier = "customEngineTitle"
let urlField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineURLPlaceholder, height: 133, settingIsValid: { text in
//Can check url text text validity here.
return true
}, settingDidChange: {fieldText in
self.urlString = fieldText
})
urlField.textField.autocapitalizationType = .none
urlField.textField.accessibilityIdentifier = "customEngineUrl"
let settings: [SettingSection] = [
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineTitleLabel), children: [titleField]),
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineURLLabel), footerTitle: NSAttributedString(string: "http://youtube.com/search?q=%s"), children: [urlField])
]
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.addCustomSearchEngine(_:)))
self.navigationItem.rightBarButtonItem?.accessibilityIdentifier = "customEngineSaveButton"
return settings
}
func addCustomSearchEngine(_ nav: UINavigationController?) {
self.view.endEditing(true)
navigationItem.rightBarButtonItem?.isEnabled = false
if let url = self.urlString {
self.addSearchEngine(url, title: self.engineTitle)
}
}
}
class CustomSearchEngineTextView: Setting, UITextViewDelegate {
fileprivate let Padding: CGFloat = 8
fileprivate let TextLabelHeight: CGFloat = 44
fileprivate var TextFieldHeight: CGFloat = 44
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
let textField = UITextView()
let placeholderLabel = UILabel()
init(defaultValue: String? = nil, placeholder: String, height: CGFloat = 44, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.TextFieldHeight = height
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
textField.addSubview(placeholderLabel)
super.init(cellHeight: TextFieldHeight)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
placeholderLabel.adjustsFontSizeToFitWidth = true
placeholderLabel.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
placeholderLabel.text = placeholder
placeholderLabel.frame = CGRect(x: 0, y: 0, width: textField.frame.width, height: TextLabelHeight)
textField.font = placeholderLabel.font
textField.textContainer.lineFragmentPadding = 0
textField.keyboardType = .URL
textField.autocorrectionType = .no
textField.delegate = self
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
cell.selectionStyle = .none
textField.snp.makeConstraints { make in
make.height.equalTo(TextFieldHeight)
make.left.right.equalTo(cell.contentView).inset(Padding)
}
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
func prepareValidValue(userInput value: String?) -> String? {
return value
}
func textViewDidBeginEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
let color = isValid(textField.text) ? UIConstants.TableViewRowTextColor : UIConstants.DestructiveRed
textField.textColor = color
}
func textViewDidEndEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
}
}
| mpl-2.0 | 46a5b9c0f18942e4eebe6353a4e6c5b6 | 38.765873 | 199 | 0.666001 | 5.464013 | false | false | false | false |
daniel-beard/SwiftLint | Source/SwiftLintFramework/Rules/MissingDocsRule.swift | 1 | 5975 | //
// MissingDocsRule.swift
// SwiftLint
//
// Created by JP Simard on 11/15/15.
// Copyright © 2015 Realm. All rights reserved.
//
import SourceKittenFramework
private func mappedDictValues(dictionary: [String: SourceKitRepresentable], key: String,
subKey: String) -> [String] {
return (dictionary[key] as? [SourceKitRepresentable])?.flatMap({
($0 as? [String: SourceKitRepresentable]) as? [String: String]
}).flatMap({ $0[subKey] }) ?? []
}
private func declarationOverrides(dictionary: [String: SourceKitRepresentable]) -> Bool {
return mappedDictValues(dictionary, key: "key.attributes", subKey: "key.attribute")
.contains("source.decl.attribute.override")
}
private func inheritedMembersForDictionary(dictionary: [String: SourceKitRepresentable]) ->
[String] {
return mappedDictValues(dictionary, key: "key.inheritedtypes", subKey: "key.name").flatMap {
File.allDeclarationsByType[$0] ?? []
}
}
extension File {
private func missingDocOffsets(dictionary: [String: SourceKitRepresentable],
acl: [AccessControlLevel], skipping: [String] = []) -> [Int] {
if declarationOverrides(dictionary) {
return []
}
if let name = dictionary["key.name"] as? String where skipping.contains(name) {
return []
}
let inheritedMembers = inheritedMembersForDictionary(dictionary)
let substructureOffsets = (dictionary["key.substructure"] as? [SourceKitRepresentable])?
.flatMap { $0 as? [String: SourceKitRepresentable] }
.flatMap({ self.missingDocOffsets($0, acl: acl, skipping: inheritedMembers) }) ?? []
guard let _ = (dictionary["key.kind"] as? String).flatMap(SwiftDeclarationKind.init),
offset = dictionary["key.offset"] as? Int64,
accessibility = dictionary["key.accessibility"] as? String
where acl.map({ $0.sourcekitValue() }).contains(accessibility) else {
return substructureOffsets
}
if getDocumentationCommentBody(dictionary, syntaxMap: syntaxMap) != nil {
return substructureOffsets
}
return substructureOffsets + [Int(offset)]
}
}
public enum AccessControlLevel: String {
case Private = "private"
case Internal = "internal"
case Public = "public"
private func sourcekitValue() -> String {
switch self {
case Private: return "source.lang.swift.accessibility.private"
case Internal: return "source.lang.swift.accessibility.internal"
case Public: return "source.lang.swift.accessibility.public"
}
}
}
public struct MissingDocsRule: ConfigurableRule, OptInRule {
public init(config: AnyObject) throws {
guard let array = [String].arrayOf(config) else {
throw ConfigurationError.UnknownConfiguration
}
let acl = array.flatMap(AccessControlLevel.init)
parameters = zip([.Warning, .Error], acl).map(RuleParameter<AccessControlLevel>.init)
}
public init() {
parameters = [RuleParameter(severity: .Warning, value: .Public)]
}
public let parameters: [RuleParameter<AccessControlLevel>]
public static let description = RuleDescription(
identifier: "missing_docs",
name: "Missing Docs",
description: "Public declarations should be documented.",
nonTriggeringExamples: [
// public, documented using /// docs
"/// docs\npublic func a() {}\n",
// public, documented using /** docs */
"/** docs */\npublic func a() {}\n",
// internal (implicit), undocumented
"func a() {}\n",
// internal (explicit), undocumented
"internal func a() {}\n",
// private, undocumented
"private func a() {}\n",
// internal (implicit), undocumented
"// regular comment\nfunc a() {}\n",
// internal (implicit), undocumented
"/* regular comment */\nfunc a() {}\n",
// protocol member is documented, but inherited member is not
"/// docs\npublic protocol A {\n/// docs\nvar b: Int { get } }\n" +
"/// docs\npublic struct C: A {\npublic let b: Int\n}",
// locally-defined superclass member is documented, but subclass member is not
"/// docs\npublic class A {\n/// docs\npublic func b() {}\n}\n" +
"/// docs\npublic class B: A { override public func b() {} }\n",
// externally-defined superclass member is documented, but subclass member is not
"import Foundation\n/// docs\npublic class B: NSObject {\n" +
"// no docs\noverride public var description: String { fatalError() } }\n"
],
triggeringExamples: [
// public, undocumented
"public func a() {}\n",
// public, undocumented
"// regular comment\npublic func a() {}\n",
// public, undocumented
"/* regular comment */\npublic func a() {}\n",
// protocol member and inherited member are both undocumented
"/// docs\npublic protocol A {\n// no docs\nvar b: Int { get } }\n" +
"/// docs\npublic struct C: A {\n\npublic let b: Int\n}"
]
)
public func validateFile(file: File) -> [StyleViolation] {
let acl = parameters.map { $0.value }
return file.missingDocOffsets(file.structure.dictionary, acl: acl).map {
StyleViolation(ruleDescription: self.dynamicType.description,
location: Location(file: file, byteOffset: $0))
}
}
public func isEqualTo(rule: ConfigurableRule) -> Bool {
if let rule = rule as? MissingDocsRule {
return rule.parameters == self.parameters
}
return false
}
}
| mit | 7a9f9877ca3bb42086132507a08848e6 | 41.368794 | 97 | 0.598092 | 4.631008 | false | false | false | false |
eBardX/XestiMonitors | Sources/Core/UIKit/Other/MenuControllerMonitor.swift | 1 | 5272 | //
// MenuControllerMonitor.swift
// XestiMonitors
//
// Created by Paul Nyondo on 2018-04-13.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
#if os(iOS)
import UIKit
///
/// A `MenuControllerMonitor` instance monitors the menu controller for changes
/// to the visibility of the editing menu or to the frame of the editing menu.
///
public class MenuControllerMonitor: BaseNotificationMonitor {
///
/// Encapsulates changes to the visibility of the editing menu and to the
/// frame of the editing menu.
///
public enum Event {
///
/// The editing menu has been dismissed.
///
case didHideMenu(UIMenuController)
///
/// The editing menu has been displayed.
///
case didShowMenu(UIMenuController)
///
/// The frame of the editing menu has changed.
///
case menuFrameDidChange(UIMenuController)
///
/// The editing menu is about to be dismissed.
///
case willHideMenu(UIMenuController)
///
/// The editing menu is about to be displayed.
///
case willShowMenu(UIMenuController)
}
///
/// Specifies which events to monitor.
///
public struct Options: OptionSet {
///
/// Monitor `didHideMenu` events.
///
public static let didHideMenu = Options(rawValue: 1 << 0)
///
/// Monitor `didShowMenu` events.
///
public static let didShowMenu = Options(rawValue: 1 << 1)
///
/// Monitor `menuFrameDidChange` events.
///
public static let menuFrameDidChange = Options(rawValue: 1 << 2)
///
/// Monitor `willHideMenu` events.
///
public static let willHideMenu = Options(rawValue: 1 << 3)
///
/// Monitor `willShowMenu` events.
///
public static let willShowMenu = Options(rawValue: 1 << 4)
///
/// Monitor `all` events.
///
public static let all: Options = [.didHideMenu,
.didShowMenu,
.menuFrameDidChange,
.willHideMenu,
.willShowMenu]
/// :nodoc:
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// :nodoc:
public let rawValue: UInt
}
///
/// Initializes a new `MenuControllerMonitor`.
///
/// - Parameters:
/// - options: The options that specify which events to monitor.
/// By default, all events are monitored.
/// - queue: The operation queue on which the handler executes.
/// By default, the main operation queue is used.
/// - handler: The handler to call when the visibility of the editing
/// menu or the frame of the editing menu changes or is
/// about to change.
///
public init(options: Options = .all,
queue: OperationQueue = .main,
handler: @escaping (Event) -> Void) {
self.handler = handler
self.menuController = .shared
self.options = options
super.init(queue: queue)
}
private let handler: (Event) -> Void
private let menuController: UIMenuController
private let options: Options
override public func addNotificationObservers() {
super.addNotificationObservers()
if options.contains(.didHideMenu) {
observe(.UIMenuControllerDidHideMenu,
object: menuController) { [unowned self] in
if let menuController = $0.object as? UIMenuController {
self.handler(.didHideMenu(menuController))
}
}
}
if options.contains(.didShowMenu) {
observe(.UIMenuControllerDidShowMenu,
object: menuController) { [unowned self] in
if let menuController = $0.object as? UIMenuController {
self.handler(.didShowMenu(menuController))
}
}
}
if options.contains(.menuFrameDidChange) {
observe(.UIMenuControllerMenuFrameDidChange,
object: menuController) { [unowned self] in
if let menuController = $0.object as? UIMenuController {
self.handler(.menuFrameDidChange(menuController))
}
}
}
if options.contains(.willHideMenu) {
observe(.UIMenuControllerWillHideMenu,
object: menuController) { [unowned self] in
if let menuController = $0.object as? UIMenuController {
self.handler(.willHideMenu(menuController))
}
}
}
if options.contains(.willShowMenu) {
observe(.UIMenuControllerWillShowMenu,
object: menuController) { [unowned self] in
if let menuController = $0.object as? UIMenuController {
self.handler(.willShowMenu(menuController))
}
}
}
}
}
#endif
| mit | 9091872d3cb52031c2dcc4fc31c5da5d | 29.645349 | 79 | 0.5369 | 5.229167 | false | false | false | false |
zhugejunwei/LeetCode | 96. Unique Binary Search Trees.swift | 1 | 316 | import Darwin
func numTrees(n: Int) -> Int {
var array = [Int](count: n+1, repeatedValue: 0)
array[0] = 1
array[1] = 1
if n >= 2 {
for i in 2...n {
for j in 0..<i {
array[i] += array[j]*array[i-1-j]
}
}
}
return array[n]
}
numTrees(2) | mit | 6f4b778a2bf756dd4d2d90d07dd71ec0 | 17.647059 | 51 | 0.436709 | 2.953271 | false | false | false | false |
calkinssean/TIY-Assignments | Day 23/SpotifyAPI 2/ArtistTableViewCell.swift | 2 | 1314 | //
// ArtistTableViewCell.swift
// SpotifyAPI
//
// Created by Sean Calkins on 2/29/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import UIKit
class ArtistTableViewCell: UITableViewCell {
@IBOutlet weak var artistImageView: UIImageView!
@IBOutlet weak var artistNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func loadImageFromURL(urlString: String) {
if urlString.isEmpty == false {
if let url = NSURL(string: urlString) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) in
if error != nil {
debugPrint("An error occurred \(error)")
return
}
let theFinalImage = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(), {
self.artistImageView.image = theFinalImage
})
})
task.resume()
} else {
print("Not a valid url")
}
} else {
debugPrint("Invalid \(urlString)")
}
}
}
| cc0-1.0 | b64b66bbf5bbf616a5972eb5af61da2b | 29.534884 | 76 | 0.516375 | 5.273092 | false | false | false | false |
Incipia/Goalie | Goalie/SpeechBubbleTextProvider.swift | 1 | 5858 | //
// SpeechBubbleTextProvider.swift
// Goalie
//
// Created by Gregory Klein on 1/7/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import Foundation
class SpeechBubbleTextProvider
{
static let sharedProvider = SpeechBubbleTextProvider()
fileprivate let _unknownTextArray = ["BOORING", "SNOOZE FEST", "YAWN", "NAP TIME", "1 SHEEP 2...", "ZZZZZZ", "I'M BEAT"]
fileprivate let _agesTextArray = ["WE GOT THIS", "ICE, ICE, BABY", "TONS O' TIME", "SO RELAXED", "JUST CHILLIN'", "SO COOL", "JUST SWELL"]
fileprivate let _laterTextArray = ["ALRIGHT!", "LET'S DO THIS", "POWER UP", "HELLO, IT'S ME", "GO TO TOWN", "WAHOO"]
fileprivate let _soonTextArray = ["ARE YOU HOT?", "I'M FLUSHED", "SWEATIN' IT", "KEEP COOL", "FEVERISH", "UH... HMM..", "EXCUSE ME?"]
fileprivate let _asapTextArray = ["STAY CALM!", "BURNIN' UP", "WOAH BUDDY", "SEND HELP", "TOO HOT", "I NEED ICE", "!!!!!!!!!!!!"]
// For later
fileprivate let _productiveActivityArray = ["KILLING IT TODAY", "LOOK AT YOU GO", "BRAVO", "GETTIN' IT", "CRUSHED IT"]
fileprivate var _lastTextDictionary: [TaskPriority : String] = [.unknown: "", .ages : "", .later : "", .soon : "", .asap : ""]
fileprivate var _lastProductiveActivityText = ""
static func textForCharacter(_ charcter: GoalieCharacter, priority: TaskPriority) -> String
{
return sharedProvider._newTextForCharacter(charcter, priority: priority)
}
fileprivate func _textArrayForPriority(_ priority: TaskPriority) -> [String]
{
switch priority
{
case .unknown: return _unknownTextArray
case .ages: return _agesTextArray
case .later: return _laterTextArray
case .soon: return _soonTextArray
case .asap: return _asapTextArray
}
}
fileprivate func _newTextForCharacter(_ character: GoalieCharacter, priority: TaskPriority) -> String
{
let textArray = character.textArrayForPriority(priority)
var newText = textArray.randomItem()
while newText == _lastTextDictionary[priority] {
newText = textArray.randomItem()
}
_lastTextDictionary[priority] = newText
return newText
}
fileprivate func _newTextForBeingProductive() -> String
{
var newText = _productiveActivityArray.randomItem()
while newText == _lastProductiveActivityText {
newText = _productiveActivityArray.randomItem()
}
_lastProductiveActivityText = newText
return newText
}
}
extension GoalieCharacter
{
func textArrayForPriority(_ priority: TaskPriority) -> [String]
{
switch priority {
case .unknown: return unknownTextArray
case .ages: return agesTextArray
case .later: return laterTextArray
case .soon: return soonTextArray
case .asap: return asapTextArray
}
}
fileprivate var unknownTextArray: [String] {
switch self {
case .unknown: return []
case .goalie: return ["BOORING", "SNOOZE FEST", "YAWN", "NAP TIME", "1 SHEEP 2...", "ZZZZZZ", "I'M BEAT"]
case .bizeeBee: return ["total bore", "chillaxin", "beauty rest", "i’ll do yoga", "snoozefest", "need a pillow", "maybe later"]
case .fox: return ["weary times", "uninspiring", "dull", "how routine", "i’m fatigued", "nodding off", "need tea"]
case .checklistor: return ["yay, naps!", "read to me", "so cozy", "rest fest", "blanket?", "tuck me in", "bubbles!"]
}
}
fileprivate var agesTextArray: [String] {
switch self {
case .unknown: return []
case .goalie: return ["WE GOT THIS", "ICE, ICE, BABY", "TONS O' TIME", "SO RELAXED", "JUST CHILLIN'", "SO COOL", "JUST SWELL"]
case .bizeeBee: return ["i see you", "like my bow?", "fabulous", "spa day", "way to plan", "Look atchu", "mighty fine"]
case .fox: return ["quite fine", "cheerio", "just dandy", "splendid day", "superior", "tip-top shape", "lovely"]
case .checklistor: return ["so much time", "i like this", "just floatin’", "way to be", "splashing", "fun zone", "chill station"]
}
}
fileprivate var laterTextArray: [String] {
switch self {
case .unknown: return []
case .goalie: return ["ALRIGHT!", "LET'S DO THIS", "POWER UP", "HELLO, IT'S ME", "GO TO TOWN", "WAHOO"]
case .bizeeBee: return ["so perky", "it’s go time", "let’s partay", "work it", "dance off!", "mad skills", "heyooo"]
case .fox: return ["fine job", "righto", "impecable", "smashing", "i’m chipper", "oh you"]
case .checklistor: return ["play time", "oh hi!", "i feel good", "keep swimmin’", "fintastic", "whale done", "10/10 effort"]
}
}
fileprivate var soonTextArray: [String] {
switch self {
case .unknown: return []
case .goalie: return ["ARE YOU HOT?", "I'M FLUSHED", "SWEATIN' IT", "KEEP COOL", "FEVERISH", "UH... HMM..", "EXCUSE ME?"]
case .bizeeBee: return ["awkward", "hellooo?", "LOL", "cray cray", "decent", "amateur hour", "woah friend", "get movin’"]
case .fox: return ["try harder", "i’ll say", "passable", "satisfactory", "oh dear", "woah friend", "this seems…"]
case .checklistor: return ["is this bad?", "yikes!", "eek", "uh oh", "c’mon bud", "oh my", "ouch"]
}
}
fileprivate var asapTextArray: [String] {
switch self {
case .unknown: return []
case .goalie: return ["STAY CALM!", "BURNIN' UP", "WOAH BUDDY", "SEND HELP", "TOO HOT", "I NEED ICE", "!!!!!!!!!!!!"]
case .bizeeBee: return ["it’s fine", "just go", "#fail", "sigh", "...k", "meh", "really?"]
case .fox: return ["devastating", "disastrous", "good grief", "poor form", "inconceivable!", "foolish", "guilty"]
case .checklistor: return ["um, wat", "help", "i’m scared", "what stinks?", "i’ll go hide", "but why?", "come back"]
}
}
}
| apache-2.0 | 6a26d045ee1949e0254aaed1d727fec3 | 43.496183 | 141 | 0.617087 | 3.371313 | false | false | false | false |
uxmstudio/UXMPDFKit | Pod/Classes/Renderer/PDFPageTileLayer.swift | 2 | 940 | //
// PDFPageTileLayer.swift
// Pods
//
// Created by Chris Anderson on 3/5/16.
//
//
import UIKit
internal class PDFPageTileLayer: CATiledLayer {
override init() {
super.init()
levelsOfDetail = 12
levelsOfDetailBias = levelsOfDetail - 1
let mainScreen = UIScreen.main
let screenScale = mainScreen.scale
let screenBounds = mainScreen.bounds
let width = screenBounds.size.width * screenScale
let height = screenBounds.size.height * screenScale
let max = width < height ? height : width
let sizeOfTiles: CGFloat = max < 512.0 ? 512.0 : 1024.0
tileSize = CGSize(width: sizeOfTiles, height: sizeOfTiles)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: Any) {
super.init(layer: layer)
}
}
| mit | 37c28d6636fb637ae8bb2c3bb4bfb37f | 23.102564 | 66 | 0.601064 | 4.454976 | false | false | false | false |
BlueCocoa/Maria | Maria/SettingsGeneralViewController.swift | 1 | 2731 | //
// SettingsGeneralViewController.swift
// Maria
//
// Created by ShinCurry on 16/4/16.
// Copyright © 2016年 ShinCurry. All rights reserved.
//
import Cocoa
class SettingsGeneralViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
userDefaultsInit()
}
let defaults = MariaUserDefault.auto
// little bug -- use a new thread?
@IBOutlet weak var enableSpeedStatusBar: NSButton!
@IBOutlet weak var enableStatusBarMode: NSButton!
@IBOutlet weak var enableYouGet: NSButton!
@IBOutlet weak var webAppPathButton: NSPopUpButton!
@IBAction func switchOptions(_ sender: NSButton) {
let appDelegate = NSApplication.shared().delegate as! AppDelegate
let boolValue = sender.state == 1 ? true : false
switch sender {
case enableSpeedStatusBar:
defaults[.enableSpeedStatusBar] = boolValue
if boolValue {
appDelegate.enableSpeedStatusBar()
} else {
appDelegate.disableSpeedStatusBar()
}
case enableStatusBarMode:
defaults[.enableStatusBarMode] = boolValue
if boolValue {
appDelegate.enableDockIcon()
} else {
appDelegate.disableDockIcon()
}
case enableYouGet:
defaults[.enableYouGet] = boolValue
default:
break
}
}
@IBAction func finishEditing(_ sender: NSTextField) {
defaults[.webAppPath] = sender.stringValue
defaults.synchronize()
}
@IBAction func selectFilePath(_ sender: NSMenuItem) {
webAppPathButton.selectItem(at: 0)
let openPanel = NSOpenPanel()
openPanel.title = NSLocalizedString("selectWebUIPath.openPanel.title", comment: "")
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.showsHiddenFiles = true
openPanel.beginSheetModal(for: self.view.window!, completionHandler: { key in
if key == 1, let url = openPanel.url?.relativePath {
self.defaults[.webAppPath] = url
self.webAppPathButton.item(at: 0)!.title = url
}
})
}
}
extension SettingsGeneralViewController {
func userDefaultsInit() {
if let value = defaults[.webAppPath] {
webAppPathButton.item(at: 0)!.title = value
}
enableSpeedStatusBar.state = defaults[.enableSpeedStatusBar] ? 1 : 0
enableStatusBarMode.state = defaults[.enableStatusBarMode] ? 1 : 0
enableYouGet.state = defaults[.enableYouGet] ? 1 : 0
}
}
| gpl-3.0 | 30921675640295e68aeaae2de0f3a582 | 30.72093 | 91 | 0.619501 | 4.906475 | false | false | false | false |
pksprojects/ElasticSwift | Tests/ElasticSwiftQueryDSLTests/FullTextQueriesTests.swift | 1 | 27492 | //
// FullTextQueriesTests.swift
// ElasticSwiftQueryDSLTests
//
//
// Created by Prafull Kumar Soni on 3/31/20.
//
import Logging
import UnitTestSettings
import XCTest
@testable import ElasticSwiftCodableUtils
@testable import ElasticSwiftQueryDSL
class FullTextQueriesTest: XCTestCase {
let logger = Logger(label: "org.pksprojects.ElasticSwiftQueryDSLTests.FullTextQueriesTest", factory: logFactory)
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
XCTAssert(isLoggingConfigured)
logger.info("====================TEST=START===============================")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
logger.info("====================TEST=END===============================")
}
func test_01_matchQuery_encode() throws {
let query = MatchQuery(field: "message", value: "ny city", autoGenSynonymnsPhraseQuery: false)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"match" : {
"message": {
"query" : "ny city",
"auto_generate_synonyms_phrase_query" : false
}
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_02_matchQuery_decode() throws {
let query = try QueryBuilders.matchQuery().set(field: "message")
.set(value: "to be or not to be")
.set(operator: .and)
.set(zeroTermQuery: .all)
.build()
let jsonStr = """
{
"match" : {
"message" : {
"query" : "to be or not to be",
"operator" : "and",
"zero_terms_query": "all"
}
}
}
"""
let decoded = try JSONDecoder().decode(MatchQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_03_matchQuery_decode_2() throws {
let query = try QueryBuilders.matchQuery()
.set(field: "message")
.set(value: "this is a test")
.build()
let jsonStr = """
{
"match" : {
"message" : "this is a test"
}
}
"""
let decoded = try JSONDecoder().decode(MatchQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_04_matchQuery_decode_fail() throws {
let jsonStr = """
{
"match" : {
"message" : "this is a test",
"invalid_key" : "random"
}
}
"""
XCTAssertThrowsError(try JSONDecoder().decode(MatchQuery.self, from: jsonStr.data(using: .utf8)!), "invalid_key in json") { error in
if let error = error as? Swift.DecodingError {
switch error {
case let .typeMismatch(type, context):
XCTAssertEqual("\(MatchQuery.self)", "\(type)")
XCTAssertEqual(context.debugDescription, "Unable to find field name in key(s) expect: 1 key found: 2.")
default:
XCTAssert(false)
}
}
}
}
func test_05_matchPhraseQuery_encode() throws {
let query = MatchPhraseQuery(field: "message", value: "this is a test", analyzer: "my_analyzer")
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"match_phrase" : {
"message" : {
"query" : "this is a test",
"analyzer" : "my_analyzer"
}
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_06_matchPhraseQuery_decode() throws {
let query = try QueryBuilders.matchPhraseQuery()
.set(field: "message")
.set(value: "this is a test")
.set(analyzer: "my_analyzer")
.build()
let jsonStr = """
{
"match_phrase" : {
"message" : {
"query" : "this is a test",
"analyzer" : "my_analyzer"
}
}
}
"""
let decoded = try JSONDecoder().decode(MatchPhraseQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_07_matchPhraseQuery_decode_2() throws {
let query = try QueryBuilders.matchPhraseQuery()
.set(field: "message")
.set(value: "this is a test")
.build()
let jsonStr = """
{
"match_phrase" : {
"message" : "this is a test"
}
}
"""
let decoded = try JSONDecoder().decode(MatchPhraseQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_08_matchPhraseQuery_decode_fail() throws {
let jsonStr = """
{
"match_phrase" : {
"message" : "this is a test",
"invalid_key": "random"
}
}
"""
XCTAssertThrowsError(try JSONDecoder().decode(MatchPhraseQuery.self, from: jsonStr.data(using: .utf8)!), "invalid_key in json") { error in
if let error = error as? Swift.DecodingError {
switch error {
case let .typeMismatch(type, context):
XCTAssertEqual("\(MatchPhraseQuery.self)", "\(type)")
XCTAssertEqual(context.debugDescription, "Unable to find field name in key(s) expect: 1 key found: 2.")
default:
XCTAssert(false)
}
}
}
}
func test_09_matchPhrasePrefixQuery_encode() throws {
let query = MatchPhrasePrefixQuery(field: "message", value: "quick brown f", maxExpansions: 10)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"match_phrase_prefix" : {
"message" : {
"query" : "quick brown f",
"max_expansions" : 10
}
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_10_matchPhrasePrefixQuery_decode() throws {
let query = try QueryBuilders.matchPhrasePrefixQuery()
.set(field: "message")
.set(value: "quick brown f")
.set(maxExpansions: 10)
.build()
let jsonStr = """
{
"match_phrase_prefix" : {
"message" : {
"query" : "quick brown f",
"max_expansions" : 10
}
}
}
"""
let decoded = try JSONDecoder().decode(MatchPhrasePrefixQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_11_matchPhrasePrefixQuery_decode_2() throws {
let query = try QueryBuilders.matchPhrasePrefixQuery()
.set(field: "message")
.set(value: "quick brown f")
.build()
let jsonStr = """
{
"match_phrase_prefix" : {
"message" : "quick brown f"
}
}
"""
let decoded = try JSONDecoder().decode(MatchPhrasePrefixQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_12_matchPhrasePrefixQuery_decode_fail() throws {
let jsonStr = """
{
"match_phrase_prefix" : {
"message" : "quick brown f",
"invalid_key": "random"
}
}
"""
XCTAssertThrowsError(try JSONDecoder().decode(MatchPhrasePrefixQuery.self, from: jsonStr.data(using: .utf8)!), "invalid_key in json") { error in
if let error = error as? Swift.DecodingError {
switch error {
case let .typeMismatch(type, context):
XCTAssertEqual("\(MatchPhrasePrefixQuery.self)", "\(type)")
XCTAssertEqual(context.debugDescription, "Unable to find field name in key(s) expect: 1 key found: 2.")
default:
XCTAssert(false)
}
}
}
}
func test_13_multiMatchQuery_encode() throws {
let query = MultiMatchQuery(query: "this is a test", fields: ["subject", "message"], tieBreaker: nil, type: nil)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"multi_match" : {
"query": "this is a test",
"fields": [ "subject", "message" ]
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_14_multiMatchQuery_decode() throws {
let query = try QueryBuilders.multiMatchQuery()
.set(query: "brown fox")
.set(fields: "subject", "message")
.set(tieBreaker: 0.3)
.set(type: .bestFields)
.build()
let jsonStr = """
{
"multi_match" : {
"query": "brown fox",
"type": "best_fields",
"fields": [ "subject", "message" ],
"tie_breaker": 0.3
}
}
"""
let decoded = try JSONDecoder().decode(MultiMatchQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_15_multiMatchQuery_decode_2() throws {
let query = try QueryBuilders.multiMatchQuery()
.add(field: "subject^3")
.add(field: "message")
.set(query: "this is a test")
.build()
let jsonStr = """
{
"multi_match" : {
"query" : "this is a test",
"fields" : [ "subject^3", "message" ]
}
}
"""
let decoded = try JSONDecoder().decode(MultiMatchQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_16_commonTermsQuery_encode() throws {
let query = CommonTermsQuery(field: "body", query: "this is bonsai cool", cutoffFrequency: 0.001)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"common": {
"body": {
"query": "this is bonsai cool",
"cutoff_frequency": 0.001
}
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_17_commonTermsQuery_decode() throws {
let query = try QueryBuilders.commonTermsQuery()
.set(field: "body")
.set(query: "nelly the elephant as a cartoon")
.set(cutoffFrequency: 0.001)
.set(minimumShouldMatch: 2)
.build()
let jsonStr = """
{
"common": {
"body": {
"query": "nelly the elephant as a cartoon",
"cutoff_frequency": 0.001,
"minimum_should_match": 2
}
}
}
"""
let decoded = try JSONDecoder().decode(CommonTermsQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_18_commonTermsQuery_decode_2() throws {
let query = try QueryBuilders.commonTermsQuery()
.set(field: "body")
.set(query: "nelly the elephant not as a cartoon")
.set(cutoffFrequency: 0.001)
.set(minimumShouldMatchLowFreq: 2)
.set(minimumShouldMatchHighFreq: 3)
.build()
let jsonStr = """
{
"common": {
"body": {
"query": "nelly the elephant not as a cartoon",
"cutoff_frequency": 0.001,
"minimum_should_match": {
"low_freq" : 2,
"high_freq" : 3
}
}
}
}
"""
let decoded = try JSONDecoder().decode(CommonTermsQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_19_commonTermsQuery_decode_3() throws {
let query = try QueryBuilders.commonTermsQuery()
.set(field: "body")
.set(query: "nelly the elephant not as a cartoon")
.set(cutoffFrequency: 0.001)
.set(lowFrequencyOperator: .and)
.set(highFrequencyOperator: .or)
.set(minimumShouldMatchLowFreq: 2)
.set(minimumShouldMatchHighFreq: 3)
.build()
let jsonStr = """
{
"common": {
"body": {
"query": "nelly the elephant not as a cartoon",
"cutoff_frequency": 0.001,
"low_freq_operator": "and",
"high_freq_operator": "or",
"minimum_should_match": {
"low_freq" : 2,
"high_freq" : 3
}
}
}
}
"""
let decoded = try JSONDecoder().decode(CommonTermsQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_20_commonTermsQuery_encode_2() throws {
let query = CommonTermsQuery(field: "body", query: "nelly the elephant not as a cartoon", cutoffFrequency: 0.001, minimumShouldMatchLowFreq: 2, minimumShouldMatchHighFreq: 3)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"common": {
"body": {
"query": "nelly the elephant not as a cartoon",
"cutoff_frequency": 0.001,
"minimum_should_match": {
"low_freq" : 2,
"high_freq" : 3
}
}
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_21_queryStringQuery_encode() throws {
let query = QueryStringQuery("(content:this OR name:this) AND (content:that OR name:that)")
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"query_string": {
"query": "(content:this OR name:this) AND (content:that OR name:that)"
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_22_queryStringQuery_encode_2() throws {
let query = try QueryBuilders.queryStringQuery()
.set(query: "this OR that OR thus")
.set(minimumShouldMatch: 2)
.set(boost: 1)
.set(type: .bestFields)
.set(autoGenerateSynonymsPhraseQuery: false)
.set(tieBreaker: 0)
.set(fields: ["title", "content"])
.set(lenient: false)
.set(analyzer: "test_analyzer")
.set(timeZone: "UTC")
.set(fuzziness: "fuzz")
.set(phraseSlop: 1)
.set(defaultField: "test")
.set(quoteAnalyzer: "quote_analyzer")
.set(analyzeWildcard: true)
.set(defaultOperator: "OR")
.set(quoteFieldSuffix: "s")
.set(fuzzyTranspositions: false)
.set(allowLeadingWildcard: true)
.set(fuzzyPrefixLength: 1)
.set(fuzzyMaxExpansions: 2)
.set(maxDeterminizedStates: 4)
.set(enablePositionIncrements: false)
.set(autoGeneratePhraseQueries: false)
.build()
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"query_string": {
"fields": [
"title",
"content"
],
"query": "this OR that OR thus",
"minimum_should_match": 2,
"type": "best_fields",
"tie_breaker" : 0,
"auto_generate_synonyms_phrase_query" : false,
"boost": 1,
"lenient": false,
"analyzer": "test_analyzer",
"time_zone": "UTC",
"fuzziness": "fuzz",
"phrase_slop": 1,
"default_field": "test",
"quote_analyzer": "quote_analyzer",
"analyze_wildcard": true,
"default_operator": "OR",
"quote_field_suffix": "s",
"fuzzy_transpositions": false,
"allow_leading_wildcard": true,
"fuzzy_prefix_length": 1,
"fuzzy_max_expansions": 2,
"max_determinized_states": 4,
"enable_position_increments": false,
"auto_generate_phrase_queries": false
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_23_queryStringQuery_decode() throws {
let query = try QueryBuilders.queryStringQuery()
.set(query: "this OR that OR thus")
.set(fields: ["title", "content"])
.set(type: .crossFields)
.set(tieBreaker: 0)
.set(autoGenerateSynonymsPhraseQuery: false)
.set(minimumShouldMatch: 2)
.build()
let jsonStr = """
{
"query_string": {
"fields": [
"title",
"content"
],
"query": "this OR that OR thus",
"minimum_should_match": 2,
"type": "cross_fields",
"tie_breaker" : 0,
"auto_generate_synonyms_phrase_query" : false
}
}
"""
let decoded = try JSONDecoder().decode(QueryStringQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_24_queryStringQuery_decode_2() throws {
let query = try QueryBuilders.queryStringQuery()
.set(query: "this OR that OR thus")
.set(minimumShouldMatch: 2)
.set(boost: 1)
.set(type: .bestFields)
.set(autoGenerateSynonymsPhraseQuery: false)
.set(tieBreaker: 0)
.set(fields: ["title", "content"])
.set(lenient: false)
.set(analyzer: "test_analyzer")
.set(timeZone: "UTC")
.set(fuzziness: "fuzz")
.set(phraseSlop: 1)
.set(defaultField: "test")
.set(quoteAnalyzer: "quote_analyzer")
.set(analyzeWildcard: true)
.set(defaultOperator: "OR")
.set(quoteFieldSuffix: "s")
.set(fuzzyTranspositions: false)
.set(allowLeadingWildcard: true)
.set(fuzzyPrefixLength: 1)
.set(fuzzyMaxExpansions: 2)
.set(maxDeterminizedStates: 4)
.set(enablePositionIncrements: false)
.set(autoGeneratePhraseQueries: false)
.build()
let jsonStr = """
{
"query_string": {
"fields": [
"title",
"content"
],
"query": "this OR that OR thus",
"minimum_should_match": 2,
"type": "best_fields",
"tie_breaker" : 0,
"auto_generate_synonyms_phrase_query" : false,
"boost": 1,
"lenient": false,
"analyzer": "test_analyzer",
"time_zone": "UTC",
"fuzziness": "fuzz",
"phrase_slop": 1,
"default_field": "test",
"quote_analyzer": "quote_analyzer",
"analyze_wildcard": true,
"default_operator": "OR",
"quote_field_suffix": "s",
"fuzzy_transpositions": false,
"allow_leading_wildcard": true,
"fuzzy_prefix_length": 1,
"fuzzy_max_expansions": 2,
"max_determinized_states": 4,
"enable_position_increments": false,
"auto_generate_phrase_queries": false
}
}
"""
let decoded = try JSONDecoder().decode(QueryStringQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_25_simpleQueryStringQuery_encode() throws {
let query = SimpleQueryStringQuery(query: "foo bar -baz", fields: ["content"], defaultOperator: "and")
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"simple_query_string" : {
"fields" : ["content"],
"query" : "foo bar -baz",
"default_operator" : "and"
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_26_simpleQueryStringQuery_encode_2() throws {
let query = try QueryBuilders.simpleQueryStringQuery()
.set(query: "this is a test")
.set(minimumShouldMatch: 2)
.set(autoGenerateSynonymsPhraseQuery: false)
.set(fields: "test", "test2")
.set(lenient: false)
.set(flags: "OR|AND|PREFIX")
.set(analyzer: "test_analyzer")
.set(defaultOperator: "OR")
.set(quoteFieldSuffix: "s")
.set(fuzzyTranspositions: false)
.set(fuzzyPrefixLength: 1)
.set(fuzzyMaxExpansions: 2)
.build()
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"simple_query_string" : {
"fields" : ["test", "test2"],
"query" : "this is a test",
"default_operator" : "OR",
"minimum_should_match": 2,
"auto_generate_synonyms_phrase_query": false,
"lenient": false,
"flags": "OR|AND|PREFIX",
"analyzer": "test_analyzer",
"quote_field_suffix": "s",
"fuzzy_transpositions": false,
"fuzzy_prefix_length": 1,
"fuzzy_max_expansions": 2
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_27_simpleQueryStringQuery_decode() throws {
let query = SimpleQueryStringQuery(query: "foo bar -baz", fields: ["content"], defaultOperator: "and")
let jsonStr = """
{
"simple_query_string" : {
"fields" : ["content"],
"query" : "foo bar -baz",
"default_operator" : "and"
}
}
"""
let decoded = try JSONDecoder().decode(SimpleQueryStringQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_28_simpleQueryStringQuery_decode_2() throws {
let query = try QueryBuilders.simpleQueryStringQuery()
.set(query: "this is a test")
.set(minimumShouldMatch: 2)
.set(autoGenerateSynonymsPhraseQuery: false)
.set(fields: "test", "test2")
.set(lenient: false)
.set(flags: "OR|AND|PREFIX")
.set(analyzer: "test_analyzer")
.set(defaultOperator: "OR")
.set(quoteFieldSuffix: "s")
.set(fuzzyTranspositions: false)
.set(fuzzyPrefixLength: 1)
.set(fuzzyMaxExpansions: 2)
.build()
let jsonStr = """
{
"simple_query_string" : {
"fields" : ["test", "test2"],
"query" : "this is a test",
"default_operator" : "OR",
"minimum_should_match": 2,
"auto_generate_synonyms_phrase_query": false,
"lenient": false,
"flags": "OR|AND|PREFIX",
"analyzer": "test_analyzer",
"quote_field_suffix": "s",
"fuzzy_transpositions": false,
"fuzzy_prefix_length": 1,
"fuzzy_max_expansions": 2
}
}
"""
let decoded = try JSONDecoder().decode(SimpleQueryStringQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
}
| mit | 6ae8505f745e42733f9428cfcf576517 | 32.445255 | 182 | 0.506074 | 4.355513 | false | true | false | false |
powerytg/Accented | Accented/UI/Uploader/ImageLoaderViewController.swift | 1 | 7286 | //
// ImageLoaderViewController.swift
// Accented
//
// Created by Tiangong You on 8/28/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import KMPlaceholderTextView
import RMessage
class ImageLoaderViewController: UIViewController, Composer, UITextViewDelegate, SheetMenuDelegate {
@IBOutlet weak var composerView: UIView!
@IBOutlet weak var titleView: UIView!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var privacyView: UISegmentedControl!
@IBOutlet weak var categoryButton: PushButton!
@IBOutlet weak var nameEdit: UITextField!
@IBOutlet weak var descEdit: KMPlaceholderTextView!
@IBOutlet weak var composerHeightConstraint: NSLayoutConstraint!
private let transitionController = ComposerPresentationController()
private let cornerRadius : CGFloat = 20
private let titleBarMaskLayer = CAShapeLayer()
private let titleBarRectCorner = UIRectCorner([.topLeft, .topRight])
private let textEditBackgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
private let textEditCornderRadius : CGFloat = 4
let categoryModel = CategorySelectorModel()
private var imageData : Data
init(imageData : Data) {
self.imageData = imageData
super.init(nibName: "ImageLoaderViewController", bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = transitionController
categoryModel.title = "SELECT CATEGORY"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
composerView.alpha = 0
composerView.layer.cornerRadius = cornerRadius
nameEdit.backgroundColor = textEditBackgroundColor
descEdit.backgroundColor = textEditBackgroundColor
nameEdit.layer.cornerRadius = textEditCornderRadius
descEdit.layer.cornerRadius = textEditCornderRadius
descEdit.delegate = self
nameEdit.addTarget(self, action: #selector(nameEditDidChange(_:)), for: .editingChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nameEdit.becomeFirstResponder()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateTitlebarCorners()
}
private func updateTitlebarCorners() {
let path = UIBezierPath(roundedRect: titleView.bounds,
byRoundingCorners: titleBarRectCorner,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
titleBarMaskLayer.path = path.cgPath
titleView.layer.mask = titleBarMaskLayer
}
@IBAction func backButtonDidTap(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
// MARK: - EntranceAnimation
func entranceAnimationWillBegin() {
composerView.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant)
}
func performEntranceAnimation() {
composerView.transform = CGAffineTransform.identity
composerView.alpha = 1
}
func entranceAnimationDidFinish() {
// Ignore
}
// MARK: - ExitAnimation
func exitAnimationWillBegin() {
composerView.resignFirstResponder()
}
func performExitAnimation() {
self.view.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant)
self.view.alpha = 0
}
func exitAnimationDidFinish() {
// Ignore
}
// MARK: - UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
toggleUploadButtonState()
}
@objc private func nameEditDidChange(_ sender : UITextField) {
toggleUploadButtonState()
}
@IBAction func categoryButtonDidTap(_ sender: Any) {
let categorySelector = SheetMenuViewController(model: categoryModel)
categorySelector.delegate = self
let animationContext = DrawerAnimationContext(content: categorySelector)
animationContext.anchor = .bottom
animationContext.container = self
animationContext.drawerSize = CGSize(width: UIScreen.main.bounds.size.width, height: 266)
DrawerService.sharedInstance.presentDrawer(animationContext)
}
private func toggleUploadButtonState() {
if (nameEdit.text?.lengthOfBytes(using: .utf8) != 0 && descEdit.text?.lengthOfBytes(using: .utf8) != 0) {
sendButton.isEnabled = true
} else {
sendButton.isEnabled = false
}
}
@IBAction func uploadButtonDidTap(_ sender: Any) {
guard nameEdit.text != nil else { return }
guard descEdit.text != nil else { return }
let privacy : Privacy = (privacyView.selectedSegmentIndex == 0) ? .publicPhoto : .privatePhoto
var category : Category
if let selectedCategory = categoryModel.selectedItem {
category = (selectedCategory as! CategoryEntry).category
} else {
category = .uncategorized
}
view.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.3) {
self.view.alpha = 0.5
}
RMessage.showNotification(withTitle: "Publishing photo...", subtitle: "", type: .success, customTypeName: nil, duration: TimeInterval(RMessageDuration.endless.rawValue), callback: nil)
APIService.sharedInstance.uploadPhoto(name: nameEdit.text!, description: descEdit.text!, category: category, privacy: privacy, image: imageData, success: { [weak self] in
RMessage.dismissActiveNotification()
self?.uploadDidSucceed()
}) { [weak self] (errorMessage) in
RMessage.dismissActiveNotification()
self?.view.isUserInteractionEnabled = true
RMessage.showNotification(withTitle: errorMessage, type: .error, customTypeName: nil, callback: nil)
UIView.animate(withDuration: 0.3) {
self?.view.alpha = 1
}
}
}
private func uploadDidSucceed() {
RMessage.showNotification(withTitle: "Publishing completed", type: .success, customTypeName: nil, callback: nil)
// Wait for a few seconds and then go back
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
self?.dismiss(animated: true, completion: {
NavigationService.sharedInstance.popToRootController(animated: true)
})
}
}
// MARK: - SheetMenuDelegate
func sheetMenuSelectedOptionDidChange(menuSheet: SheetMenuViewController, selectedIndex: Int) {
let selectedItem = categoryModel.items[selectedIndex] as! CategoryEntry
categoryModel.selectedItem = selectedItem
menuSheet.dismiss(animated: true, completion: nil)
categoryButton.setTitle(selectedItem.text, for: .normal)
}
}
| mit | 9d21bec382019e7ce85324575b8aa848 | 35.425 | 192 | 0.663693 | 5.211016 | false | false | false | false |
jindulys/HackerRankSolutions | Sources/Leetcode/String/290_WordPattern.swift | 1 | 1936 | //
// 290_WordPattern.swift
// HRSwift
//
// Created by yansong li on 2016-08-06.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Title:290 Word Pattern
URL: https://leetcode.com/problems/word-pattern/
Space: O(n)
Time: O(n)
*/
class WordPattern_Solution {
/// This is correct but with ugly logic
func wordPattern_initial(pattern: String, _ str: String) -> Bool {
var dict: [Character : String] = [:]
var wordIndexedDict: [String: Character] = [:]
let keys:[Character] = Array(pattern.characters)
let words = str.characters.split(" ").map { String($0) }
guard words.count == keys.count else {
return false
}
for i in 0..<words.count {
let currentWord = words[i]
let currentKey: Character = keys[i]
if let existingWord = dict[currentKey] {
if currentWord != existingWord {
return false
}
} else {
if wordIndexedDict[currentWord] != nil {
return false
}
dict[currentKey] = currentWord
wordIndexedDict[currentWord] = currentKey
}
}
return true
}
func wordPattern(pattern: String, _ str: String) -> Bool {
var characterIndexedDict: [Character : String] = [:]
var wordIndexedDict: [String: Character] = [:]
let keys:[Character] = Array(pattern.characters)
let words = str.characters.split(" ").map { String($0) }
guard words.count == keys.count else {
return false
}
for i in 0..<words.count {
let currentWord = words[i]
let currentKey: Character = keys[i]
if characterIndexedDict[currentKey] == nil && wordIndexedDict[currentWord] == nil {
characterIndexedDict[currentKey] = currentWord
wordIndexedDict[currentWord] = currentKey
// Logic is interesting.
} else if wordIndexedDict[currentWord] != currentKey {
return false
}
}
return true
}
} | mit | 81fa397ae22d188a51c345d8a79385c6 | 27.470588 | 89 | 0.623773 | 3.89336 | false | false | false | false |
cwwise/CWWeChat | CWWeChat/ChatModule/CWChatClient/Bussiness/CWMessageDispatchOperation.swift | 2 | 5601 | //
// CWMessageDispatchOperation.swift
// CWWeChat
//
// Created by chenwei on 2017/3/30.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
///重复发送次数
private let kMax_RepeatCount:Int = 5
/// 还需要修改
/// 发送消息线程
class CWMessageDispatchOperation: Operation {
/// 消息发送
var messageTransmitter: CWMessageTransmitter {
let chatService = CWChatClient.share.chatManager as! CWChatService
return chatService.messageTransmitter
}
/// 消息实体
var message: CWMessage
/// 进度回调的block
var progress: CWMessageProgressBlock?
/// 完成结果
var completion: CWMessageCompletionBlock?
/// 控制并发的变量
override var isExecuting: Bool {
return local_executing
}
override var isFinished: Bool {
return local_finished
}
override var isCancelled: Bool {
return local_cancelled
}
override var isReady: Bool {
return local_ready
}
/// 实现并发需要设置为YES
override var isConcurrent: Bool {
return true
}
override var isAsynchronous: Bool {
return true
}
/// 控制并发任务的变量
// 执行中
fileprivate var local_executing:Bool = false {
willSet {
self.willChangeValue(forKey: "isExecuting")
}
didSet {
self.didChangeValue(forKey: "isExecuting")
}
}
fileprivate var local_finished:Bool = false {
willSet {
self.willChangeValue(forKey: "isFinished")
}
didSet {
self.didChangeValue(forKey: "isFinished")
}
}
fileprivate var local_cancelled:Bool = false {
willSet {
self.willChangeValue(forKey: "isCancelled")
}
didSet {
self.didChangeValue(forKey: "isCancelled")
}
}
internal var local_ready:Bool = false {
willSet {
self.willChangeValue(forKey: "isReady")
}
didSet {
self.didChangeValue(forKey: "isReady")
}
}
/// 消息发送结果
var messageSendResult: Bool
/// 重复执行的次数
var repeatCount: Int = 0
class func operationWithMessage(_ message: CWMessage,
progress: CWMessageProgressBlock? = nil,
completion: CWMessageCompletionBlock? = nil) -> CWMessageDispatchOperation {
switch message.messageType {
case .text:
return CWTextMessageDispatchOperation(message, progress: progress, completion: completion)
case .image:
return CWImageMessageDispatchOperation(message, progress: progress, completion: completion)
default:
return CWMessageDispatchOperation(message, progress: progress, completion: completion)
}
}
init(_ message: CWMessage,
progress: CWMessageProgressBlock? = nil,
completion: CWMessageCompletionBlock? = nil) {
self.message = message
self.messageSendResult = false
self.progress = progress
self.completion = completion
super.init()
}
///函数入口
override func start() {
if self.isCancelled {
self._endOperation()
return
}
self.local_executing = true
self.performSelector(inBackground: #selector(CWMessageDispatchOperation._startOperation), with: nil)
}
/// 取消线程发送
override func cancel() {
if local_cancelled == false {
local_finished = true
local_cancelled = true
local_executing = false
noticationWithOperationState()
}
super.cancel()
}
/// 发送消息
func sendMessage() {
noticationWithOperationState()
}
@objc func _startOperation() {
//发送消息的任务
sendMessage()
}
/**
结束线程
*/
func _endOperation() {
self.local_executing = false
self.local_finished = true
}
func _cancelOperation() {
}
/// 消息状态
func noticationWithOperationState(_ state:Bool = false) {
self.messageSendResult = state
_endOperation()
if state {
message.sendStatus = .successed
completion?(message, nil)
} else {
message.sendStatus = .failed
completion?(message, CWChatError(errorCode: .customer, error: "发送失败"))
}
}
func messageSendCallback(_ result:Bool) {
if result == false {
repeatCount += 1
if repeatCount > kMax_RepeatCount {
noticationWithOperationState(false)
} else {
sendMessage()
}
} else {
noticationWithOperationState(true)
}
}
override var description: String {
var string = "<\(self.classForCoder) id:\(self.message.messageId) "
string += " executing:" + (self.local_executing ?"YES":"NO")
string += " finished:" + (self.local_finished ?"YES":"NO")
string += " cancelled:" + (self.local_cancelled ?"YES":"NO")
string += " sendResult:" + (self.messageSendResult ?"YES":"NO")
string += " >"
return string
}
deinit {
log.debug("销毁:"+self.description)
}
}
| mit | 2a911a96251b321b57976fec86c70b1c | 24.013953 | 112 | 0.5582 | 4.929423 | false | false | false | false |
ChrisAU/AnagramDictionary | AnagramDictionaryTests/AnagramDictionaryTests.swift | 1 | 2023 | //
// AnagramDictionaryTests.swift
// AnagramDictionaryTests
//
// Created by Chris Nevin on 26/06/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import XCTest
@testable import AnagramDictionary
@testable import Lookup
class AnagramDictionaryTests: XCTestCase {
func testBuildAndLoad() {
let input = NSBundle(forClass: self.dynamicType).pathForResource("test", ofType: "txt")!
let data = try! NSString(contentsOfFile: input, encoding: NSUTF8StringEncoding)
let lines = data.componentsSeparatedByString("\n").sort()
let anagramBuilder = AnagramBuilder()
lines.forEach { anagramBuilder.addWord($0) }
let output = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! + "/output.txt"
XCTAssert(anagramBuilder.serialize().writeToFile(output, atomically: true))
// Test build worked
let dictionary = AnagramDictionary.load(output)!
lines.forEach { XCTAssertTrue(dictionary.lookup($0)) }
XCTAssertEqual(dictionary["part"]!, ["part", "prat", "rapt", "tarp", "trap"])
XCTAssertFalse(dictionary.lookup("arpt"))
XCTAssertFalse(dictionary.lookup("fake"))
}
func testLoadFailsIfInvalidFile() {
XCTAssertNil(AnagramDictionary.load(""))
}
func testDeserializeFails() {
XCTAssertNil(AnagramDictionary.deserialize(NSData()))
}
func testInitSucceeds() {
XCTAssertNotNil(AnagramDictionary(filename: "test", type: "bin", bundle: NSBundle(forClass: self.dynamicType)))
}
func testInitFailsIfInvalidBundledFile() {
XCTAssertNil(AnagramDictionary(filename: ""))
}
func testInitFailsIfInvalidBundledFileOfType() {
XCTAssertNil(AnagramDictionary(filename: "", type: "txt"))
}
func testInitFailsIfInvalidBundledFileOfTypeInBundle() {
XCTAssertNil(AnagramDictionary(filename: "fake", type: "bin", bundle: NSBundle(forClass: self.dynamicType)))
}
}
| mit | a0e2e5aaa68281e083ef3d41dcc0d31d | 35.763636 | 120 | 0.682987 | 4.680556 | false | true | false | false |
GyazSquare/GSLabel | GSLabel/GSLabel.swift | 1 | 1384 | //
// GSLabel.swift
//
import UIKit.UILabel
open class GSLabel: UILabel {
// MARK: Properties
open var contentInsets: UIEdgeInsets = .zero {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: NSCoding
override open func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(contentInsets, forKey: PropertyKey.contentInsets)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentInsets = aDecoder.decodeUIEdgeInsets(forKey: PropertyKey.contentInsets)
}
// MARK: UILabel
override open func drawText(in rect: CGRect) {
let newRect = UIEdgeInsetsInsetRect(rect, contentInsets)
super.drawText(in: newRect)
}
// MARK: UIView (UIConstraintBasedLayoutLayering)
override open var intrinsicContentSize : CGSize {
let size = super.intrinsicContentSize
let width = size.width + contentInsets.left + contentInsets.right
let height = size.height + contentInsets.top + contentInsets.bottom
return CGSize(width: width, height: height)
}
// MARK: Private Constants
private struct PropertyKey {
static let contentInsets = "contentInsets"
}
}
| mit | b8a733f6bfe3808fabf232dc5a5f19cb | 24.163636 | 86 | 0.656792 | 4.85614 | false | false | false | false |
Polidea/RxBluetoothKit | ExampleApp/ExampleApp/Screens/PeripheralWrite/PeripheralWriteView.swift | 2 | 1826 | import UIKit
class PeripheralWriteView: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .systemBackground
setupLayout()
}
required init?(coder: NSCoder) { nil }
// MARK: - Subviews
let serviceUuidTextField: UITextField = {
let textField = UITextField()
textField.placeholder = Labels.serviceUuidPlaceholder
return textField
}()
let characteristicUuidTextField: UITextField = {
let textField = UITextField()
textField.placeholder = Labels.characteristicUuidPlaceholder
return textField
}()
let advertiseButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Advertise", for: .normal)
button.setImage(UIImage(systemName: "wave.3.right"), for: .normal)
return button
}()
let writeLabel: UILabel = {
let label = UILabel()
label.text = "Written value: --"
label.font = UIFont.systemFont(ofSize: 20.0)
label.textColor = .magenta
return label
}()
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 20.0
return stackView
}()
// MARK: - Private
private func setupLayout() {
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
[serviceUuidTextField, characteristicUuidTextField, advertiseButton, writeLabel].forEach(stackView.addArrangedSubview)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
stackView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32)
])
}
}
| apache-2.0 | 0ac5429684912961865868ecba83bf9d | 27.984127 | 126 | 0.645674 | 5.232092 | false | false | false | false |
ITzTravelInTime/TINU | TINU/DownloadAppViewController.swift | 1 | 9658 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Cocoa
fileprivate struct AppDownloadManager: CodableDefaults, Codable, Equatable{
fileprivate struct AppDownload: Codable, Equatable{
let name: String
let version: String
let DownloadLink: String
let DownloadLinkAlternate: String?
private let imageURL: URL?
//future stuff for downloading apps from the app sotre or the settings directly.
struct DownloadCommand: Codable, Equatable{
let executableText: String
let minVersion: String
let maxVersion: String!
}
let downloadCommands: [DownloadCommand]?
var localImageName: String{
return "InstallApp"
}
var remoteImageUrl: URL?{
return imageURL
}
}
let downloads: [AppDownload]
static let defaultResourceFileName = "AppDownloads"
static let defaultResourceFileExtension = "json"
}
public class DownloadAppViewController: ShadowViewController, ViewID {
public let id: String = "DownloadAppViewController"
@IBOutlet weak var closeButton: NSButton!
@IBOutlet weak var scroller: NSScrollView!
@IBOutlet weak var spinner: NSProgressIndicator!
private var plain: NSView!
override public func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
spinner.startAnimation(self)
self.setTitleLabel(text: TextManager.getViewString(context: self, stringID: "title"))
self.showTitleLabel()
setOtherViews(respectTo: scroller)
self.scroller.hasHorizontalScroller = false
self.plain = NSView(frame: CGRect(x: 0, y: 0, width: self.scroller.frame.width - 15, height: 10))
self.plain.backgroundColor = self.scroller.backgroundColor//NSColor.windowBackgroundColor
//scroller.backgroundColor = plain.backgroundColor
//scroller.contentView.backgroundColor = plain.backgroundColor
DispatchQueue.global(qos: .background).async { [self] in
//let apps = /*AppDownloadManager.init(fromRemoteFileAtUrl: RemoteResourcesURLsManager.list["installerAppDownloads"] ?? "")?.downloads ??*/ //AppDownloadManager.init()!.downloads //.createFromDefaultFile()!.downloads
var apps: [AppDownloadManager.AppDownload] = AppDownloadManager.init()?.downloads ?? []
if let link = RemoteResourcesURLsManager.list["installerAppDownloads"], !simulateOnlyLocalInstallerAppDownloadList{
if let list = AppDownloadManager.init(fromRemoteFileAtUrl: link)?.downloads{
apps = list
}
}
DispatchQueue.main.sync {
self.displayElementsAndSetUI(apps: apps)
}
}
}
override public func viewWillAppear() {
super.viewWillAppear()
if self.window.isSheet{
self.setShadowViewsTopBottomOnly(respectTo: scroller, topBottomViewsShadowRadius: 5)
return
}
self.closeButton.isHidden = true
self.scroller.frame.size.height = self.view.frame.size.height - self.copyright.frame.size.height
self.scroller.frame.origin.y = self.copyright.frame.size.height
self.window.title = self.titleLabel.stringValue
self.hideTitleLabel()
}
/*
override func viewDidSetVibrantLook() {
super.viewDidSetVibrantLook()
}
*/
@IBAction func buttonClick(_ sender: Any) {
if self.presentingViewController == nil{
self.window.close()
}else{
self.window.sheetParent?.endSheet(self.window)
}
}
private func displayElementsAndSetUI(apps: [AppDownloadManager.AppDownload]){
let segmentHeight: CGFloat = 100
let segmentOffset: CGFloat = 20
let segmentEdge: CGFloat = 15
//self.plain = NSView(frame: CGRect(x: 0, y: 0, width: self.scroller.frame.width - 15, height: (segmentHeight + segmentOffset) * CGFloat(apps.count) + segmentOffset))
self.plain?.frame.size.height = (segmentHeight + segmentOffset) * CGFloat(apps.count) + segmentOffset
var tmp: CGFloat = segmentOffset
for app in apps.reversed(){
let segment = DownloadAppItem(frame: CGRect(x: segmentEdge, y: tmp, width: self.plain.frame.size.width - segmentOffset, height: segmentHeight))
//segment.isLast = (app == apps.last!)
segment.associtaed = app
self.plain.addSubview(segment)
tmp += segmentHeight + segmentOffset
}
if self.presentingViewController == nil{
//if self.window != sharedWindow{
self.closeButton.title = TextManager.getViewString(context: self, stringID: "backButton")
self.closeButton.image = NSImage(named: NSImage.stopProgressTemplateName)
}else{
self.closeButton.image = NSImage(named: NSImage.goLeftTemplateName)
}
self.scroller.documentView = self.plain!
self.spinner.stopAnimation(self)
self.spinner.isHidden = true
self.window.maxSize = CGSize(width: self.view.frame.width, height: self.plain.frame.height + self.scroller.frame.origin.y + (self.view.frame.size.height - self.scroller.frame.origin.y - self.scroller.frame.size.height))
self.window.minSize = CGSize(width: self.view.frame.width, height: 300)
}
}
fileprivate class DownloadAppItem: ShadowView, ViewID{
let id: String = "DownloadAppItem"
public var associtaed: AppDownloadManager.AppDownload!
//public var isLast: Bool = false
private var link: URL!
private let name = NSTextField()
private let version = NSTextField()
private let icon = NSImageView()
private let downloadButton = NSButton()
private let separator = NSView()
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
icon.frame.size = NSSize(width: 70, height: 70)
icon.frame.origin = NSPoint(x: 5, y: (self.frame.height - icon.frame.height) / 2)
icon.imageAlignment = .alignCenter
icon.imageScaling = .scaleProportionallyUpOrDown
icon.isEditable = false
icon.image = NSImage(named: associtaed.localImageName)!
DispatchQueue.main.async {
if let url = self.associtaed.remoteImageUrl{
self.icon.downloaded(from: url)
}
}
self.addSubview(icon)
name.frame.size = NSSize(width: 250, height: 25)
name.frame.origin = NSPoint(x: icon.frame.origin.x + icon.frame.size.width + 5, y: icon.frame.origin.y + icon.frame.size.height - name.frame.size.height )
name.isEditable = false
name.isSelectable = false
name.drawsBackground = false
name.isBordered = false
name.isBezeled = false
name.alignment = .left
name.stringValue = associtaed.name
//name.font = NSFont.systemFont(ofSize: NSFont.systemFontSize())
name.font = NSFont.boldSystemFont(ofSize: 18)
self.addSubview(name)
version.frame.size = NSSize(width: 250, height: 17)
version.frame.origin = NSPoint(x: name.frame.origin.x, y: name.frame.origin.y - version.frame.size.height - 5)
version.isEditable = false
version.isSelectable = false
version.drawsBackground = false
version.isBordered = false
version.isBezeled = false
version.alignment = .left
version.stringValue = associtaed.version
version.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize)
self.addSubview(version)
var isAlternate = false
if #available(OSX 10.14, *){
isAlternate = true
}
isAlternate = (isAlternate && (associtaed.DownloadLinkAlternate != nil)) || (associtaed.DownloadLink == "")
if isAlternate{
downloadButton.title = TextManager.getViewString(context: self, stringID: "downloadButtonApple")
link = URL(string: associtaed.DownloadLinkAlternate!)
}else{
downloadButton.title = TextManager.getViewString(context: self, stringID: "downloadButtonAppStore")
link = URL(string: associtaed.DownloadLink)
}
//downloadButton.bezelStyle = .roundRect
downloadButton.bezelStyle = .rounded
downloadButton.setButtonType(.momentaryPushIn)
downloadButton.frame.size = NSSize(width: 150, height: 30)
//downloadButton.frame.origin = NSPoint(x: self.frame.size.width - downloadButton.frame.size.width - 5, y: (self.frame.size.height - downloadButton.frame.height) / 2)
downloadButton.frame.origin = NSPoint(x: self.frame.size.width - downloadButton.frame.size.width - 7, y: 7)
downloadButton.font = NSFont.systemFont(ofSize: 12)
downloadButton.isContinuous = true
downloadButton.target = self
downloadButton.action = #selector(self.downloadApp(_:))
self.addSubview(downloadButton)
/*
if !isLast{
separator.frame.origin = CGPoint(x: 30, y: 1)
separator.frame.size = CGSize(width: self.frame.width - 60, height: 1)
separator.wantsLayer = true
separator.layer?.borderColor = NSColor.lightGray.cgColor
separator.layer?.borderWidth = 1
self.addSubview(separator)
}*/
}
@objc func downloadApp(_ sender: Any){
if link!.pathExtension == "dmg"{
//if dialogCustomWarning(question: "Remeber to open the download", text: "The intaller file you are about to download will need to be opened after being downloaded in order to be usable with TINU", mainButtonText: "Continue", secondButtonText: "Cancel"){
if !dialogWithManager(self, name: "downloadDialog"){
return
}
}
NSWorkspace.shared.open(link!)
}
}
| gpl-2.0 | e8f7ace08fbbee7ca1f5fc82972aceea | 30.980132 | 257 | 0.732243 | 3.796384 | false | false | false | false |
ginppian/fif2016 | ACTabScrollView/PatrocinadoresViewController.swift | 1 | 2803 | //
// PatrocinadoresViewController.swift
// FIF 16
//
// Created by ginppian on 21/11/16.
// Copyright © 2016 AzureChen. All rights reserved.
//
import UIKit
class PatrocinadoresViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let arrayImag = ["Abbaba Soul-31",
"Acajete",
"behooklogo negativo (1)",
"CAU_2014_ACTUALIZACION_h_normal",
"colecta",
"entre",
"logo_sin",
"LogoRuido3",
"Logotipo-2 Matilde Band Negro",
"manyfesto_logo_cmyk",
"ProveedoraEscolar_Logotipo",
"Subterraneos 2016H",
"UDLAP 2012",
"zonica_pos",
"amparo",
"artificial",
"bubba",
"creativo",
"Cronos logo",
"diseno tu book(1)",
"Greenpeace_logo.svg",
"Logo 19-40 café Rojo",
"logoMelilla",
"Logo Oaxaca Estenopeica",
"LogoDP",
"logofundacion",
"puebla222",
"avima",
"barrio",
"BIMESTRALlogotipo",
"casa de los mu",
"ficj",
"ibero",
"la casita de Carlo",
"la generala",
"LEXGO_FREEDOM_LOGO_PNG",
"Logo Cinema PlanetaFin",
"logouma (1)",
"photo",
"03_ZonyMaya",
"saberVer",
"CINECLUBFIF",
"foro",
"logo final fotoax lungo(1)",
"LOGO MULTICOPIAS",
"logo ok bienal nuevo",
"LOGO Revista Enfoque Visual",
"logo uo",
"Logo_Dos EquisCMYK",
"logo_mezcalshawi",
"logo_mezcalzacbe",
"oaxacafilm",
"heineken",
"FPM_cuadrado_alta",
"imac",
"inkperio",
"cinefilia",
"logo con fondo blanco",
"Logo LA CUPULA 5 cm",
"logo_fh",
"Logo_UVP-02(1)",
"modalidad Logos Ayuntamiento-IMACP",
"school"]
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return arrayImag.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "patrocinadoresIdentifier", for: indexPath) as! PatrocinadoresCollectionViewCell
cell.image.image = UIImage(named: arrayImag[indexPath.row])
return cell
}
private func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let wCell = UIScreen.main.bounds.width/2
let size = CGSize(width: wCell, height: wCell)
//(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = size
return size
}
}
| mit | ca2b20b28b45ed78c935e467c2f30954 | 20.06015 | 177 | 0.634416 | 3.581841 | false | false | false | false |
mssun/passforios | passKit/Passwords/PasswordGenerator.swift | 2 | 3719 | //
// PasswordGenerator.swift
// passKit
//
// Created by Danny Moesch on 27.02.20.
// Copyright © 2020 Bob Sun. All rights reserved.
//
public struct PasswordGenerator: Codable {
private static let digits = "0123456789"
private static let letters = "abcdefghijklmnopqrstuvwxyz"
private static let capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
private static let specialSymbols = "!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~"
private static let words: [String] = {
let bundle = Bundle(identifier: Globals.passKitBundleIdentifier)!
return ["eff_long_wordlist", "eff_short_wordlist"]
.map { name -> String in
guard let asset = NSDataAsset(name: name, bundle: bundle),
let data = String(data: asset.data, encoding: .utf8) else {
return ""
}
return data
}
.joined(separator: "\n")
.splitByNewline()
}()
public var flavor = PasswordGeneratorFlavor.random
public var length = 15
public var varyCases = true
public var useDigits = true
public var useSpecialSymbols = true
public var groups = 4
public var limitedLength: Int {
let lengthLimits = flavor.lengthLimits
return max(lengthLimits.min, min(lengthLimits.max, length))
}
private var characters: String {
var characters = Self.letters
if varyCases {
characters.append(Self.capitalLetters)
}
if useDigits {
characters.append(Self.digits)
}
if useSpecialSymbols {
characters.append(Self.specialSymbols)
}
return characters
}
private var delimiters: String {
var delimiters = ""
if useDigits {
delimiters.append(Self.digits)
}
if useSpecialSymbols {
delimiters.append(Self.specialSymbols)
}
return delimiters
}
public func generate() -> String {
switch flavor {
case .random:
return generateRandom()
case .xkcd:
return generateXkcd()
}
}
public func isAcceptable(groups: Int) -> Bool {
guard flavor == .random, groups > 0, groups < length else {
return false
}
return (length + 1).isMultiple(of: groups)
}
private func generateRandom() -> String {
let currentCharacters = characters
if groups > 1, isAcceptable(groups: groups) {
return selectRandomly(count: limitedLength - groups + 1, from: currentCharacters)
.slices(count: UInt(groups))
.map { String($0) }
.joined(separator: "-")
}
return String(selectRandomly(count: limitedLength, from: currentCharacters))
}
private func generateXkcd() -> String {
let currentDelimiters = delimiters
return getRandomDelimiter(from: currentDelimiters) + (0 ..< limitedLength)
.map { _ in getRandomWord() + getRandomDelimiter(from: currentDelimiters) }
.joined()
}
private func getRandomDelimiter(from delimiters: String) -> String {
if delimiters.isEmpty {
return ""
}
return String(delimiters.randomElement()!)
}
private func getRandomWord() -> String {
let word = Self.words.randomElement()!
if varyCases, Bool.random() {
return word.uppercased()
}
return word
}
private func selectRandomly(count: Int, from string: String) -> [Character] {
(0 ..< count).map { _ in string.randomElement()! }
}
}
extension PasswordGeneratorFlavor: Codable {}
| mit | b1e03908a37b97813b972104ecaa5103 | 29.983333 | 93 | 0.585799 | 4.754476 | false | false | false | false |
devpunk/cartesian | cartesian/Model/DrawProject/Menu/Nodes/MDrawProjectMenuNodes.swift | 1 | 1473 | import Foundation
class MDrawProjectMenuNodes
{
let items:[MDrawProjectMenuNodesItem]
init()
{
let itemOval:MDrawProjectMenuNodesItemOval = MDrawProjectMenuNodesItemOval()
let itemTriangle:MDrawProjectMenuNodesItemTriangle = MDrawProjectMenuNodesItemTriangle()
let itemRect:MDrawProjectMenuNodesItemRect = MDrawProjectMenuNodesItemRect()
let itemLozenge:MDrawProjectMenuNodesItemLozenge = MDrawProjectMenuNodesItemLozenge()
let itemPentagon:MDrawProjectMenuNodesItemPentagon = MDrawProjectMenuNodesItemPentagon()
let itemHexagon:MDrawProjectMenuNodesItemHexagon = MDrawProjectMenuNodesItemHexagon()
let itemInputOutput:MDrawProjectMenuNodesItemInputOutput = MDrawProjectMenuNodesItemInputOutput()
let itemStarThree:MDrawProjectMenuNodesItemStarThree = MDrawProjectMenuNodesItemStarThree()
let itemStarFour:MDrawProjectMenuNodesItemStarFour = MDrawProjectMenuNodesItemStarFour()
let itemStarFive:MDrawProjectMenuNodesItemStarFive = MDrawProjectMenuNodesItemStarFive()
let itemStarSix:MDrawProjectMenuNodesItemStarSix = MDrawProjectMenuNodesItemStarSix()
items = [
itemOval,
itemTriangle,
itemRect,
itemLozenge,
itemPentagon,
itemHexagon,
itemInputOutput,
itemStarThree,
itemStarFour,
itemStarFive,
itemStarSix]
}
}
| mit | 0b8016677276879eeb9b38e3700fe531 | 42.323529 | 105 | 0.732519 | 4.845395 | false | false | false | false |
kelvin13/maxpng | sources/png/common.swift | 1 | 7352 | // 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 https://mozilla.org/MPL/2.0/.
// enum General
// A namespace for general functionality.
// # [Integer storage](general-storage-types)
// # [See also](top-level-namespaces)
// ## (1:top-level-namespaces)
public
enum General
{
}
extension General
{
// struct General.Storage<I>
// where I:Swift.FixedWidthInteger & Swift.BinaryInteger
// @propertyWrapper
// A property wrapper providing an immutable [`Swift.Int`] interface backed
// by a different integer type.
// # [See also](general-storage-types)
// ## (general-storage-types)
@propertyWrapper
struct Storage<I>:Equatable where I:FixedWidthInteger & BinaryInteger
{
private
var storage:I
// init General.Storage.init(wrappedValue:)
// Creates an instance of this property wrapper, with the given value
// truncated to the width of the storage type [`I`].
// - wrappedValue : Swift.Int
// The value to wrap.
init(wrappedValue:Int)
{
self.storage = .init(truncatingIfNeeded: wrappedValue)
}
// var General.Storage.wrappedValue : Swift.Int { get }
// The value wrapped by this property wrapper, expanded to an [`Swift.Int`].
var wrappedValue:Int
{
.init(self.storage)
}
}
}
extension General.Storage:Sendable where I:Sendable
{
}
extension General
{
struct Heap<Key, Value> where Key:Comparable
{
private
var storage:[(Key, Value)]
// support 1-based indexing
private
subscript(index:Int) -> (key:Key, value:Value)
{
get
{
self.storage[index - 1]
}
set(item)
{
self.storage[index - 1] = item
}
}
var count:Int
{
self.storage.count
}
var first:(key:Key, value:Value)?
{
self.storage.first
}
var isEmpty:Bool
{
self.storage.isEmpty
}
private
var startIndex:Int
{
1
}
private
var endIndex:Int
{
1 + self.count
}
}
}
extension General.Heap
{
@inline(__always)
private static
func left(index:Int) -> Int
{
return index << 1
}
@inline(__always)
private static
func right(index:Int) -> Int
{
return index << 1 + 1
}
@inline(__always)
private static
func parent(index:Int) -> Int
{
return index >> 1
}
private
func highest(above child:Int) -> Int?
{
let p:Int = Self.parent(index: child)
// make sure it’s not the root
guard p >= self.startIndex
else
{
return nil
}
// and the element is higher than the parent
return self[child].key < self[p].key ? p : nil
}
private
func lowest(below parent:Int) -> Int?
{
let r:Int = Self.right(index: parent),
l:Int = Self.left (index: parent)
guard l < self.endIndex
else
{
return nil
}
guard r < self.endIndex
else
{
return self[l].key < self[parent].key ? l : nil
}
let c:Int = self[r].key < self[l].key ? r : l
return self[c].key < self[parent].key ? c : nil
}
@inline(__always)
private mutating
func swapAt(_ i:Int, _ j:Int)
{
self.storage.swapAt(i - 1, j - 1)
}
private mutating
func siftUp(index:Int)
{
guard let parent:Int = self.highest(above: index)
else
{
return
}
self.swapAt(index, parent)
self.siftUp(index: parent)
}
private mutating
func siftDown(index:Int)
{
guard let child:Int = self.lowest(below: index)
else
{
return
}
self.swapAt (index, child)
self.siftDown(index: child)
}
mutating
func enqueue(key:Key, value:Value)
{
self.storage.append((key, value))
self.siftUp(index: self.endIndex - 1)
}
mutating
func dequeue() -> (key:Key, value:Value)?
{
switch self.count
{
case 0:
return nil
case 1:
return self.storage.removeLast()
default:
self.swapAt(self.startIndex, self.endIndex - 1)
defer
{
self.siftDown(index: self.startIndex)
}
return self.storage.removeLast()
}
}
init<S>(_ sequence:S) where S:Sequence, S.Element == (Key, Value)
{
self.storage = .init(sequence)
// heapify
let halfway:Int = Self.parent(index: self.endIndex - 1) + 1
for i:Int in (self.startIndex ..< halfway).reversed()
{
self.siftDown(index: i)
}
}
}
extension General.Heap:ExpressibleByArrayLiteral
{
init(arrayLiteral:(key:Key, value:Value)...)
{
self.init(arrayLiteral)
}
}
extension Array where Element == UInt8
{
func load<T, U>(bigEndian:T.Type, as type:U.Type, at byte:Int) -> U
where T:FixedWidthInteger, U:BinaryInteger
{
return self[byte ..< byte + MemoryLayout<T>.size].load(bigEndian: T.self, as: U.self)
}
}
extension UnsafeMutableBufferPointer where Element == UInt8
{
func store<U, T>(_ value:U, asBigEndian type:T.Type, at byte:Int = 0)
where U:BinaryInteger, T:FixedWidthInteger
{
let cast:T = .init(truncatingIfNeeded: value)
withUnsafeBytes(of: cast.bigEndian)
{
guard let source:UnsafeRawPointer = $0.baseAddress,
let destination:UnsafeMutableRawPointer =
self.baseAddress.map(UnsafeMutableRawPointer.init(_:))
else
{
return
}
(destination + byte).copyMemory(from: source, byteCount: MemoryLayout<T>.size)
}
}
}
extension ArraySlice where Element == UInt8
{
func load<T, U>(bigEndian:T.Type, as type:U.Type) -> U
where T:FixedWidthInteger, U:BinaryInteger
{
return self.withUnsafeBufferPointer
{
(buffer:UnsafeBufferPointer<UInt8>) in
assert(buffer.count >= MemoryLayout<T>.size,
"attempt to load \(T.self) from slice of size \(buffer.count)")
var storage:T = .init()
let value:T = withUnsafeMutablePointer(to: &storage)
{
$0.deinitialize(count: 1)
let source:UnsafeRawPointer = .init(buffer.baseAddress!),
raw:UnsafeMutableRawPointer = .init($0)
raw.copyMemory(from: source, byteCount: MemoryLayout<T>.size)
return raw.load(as: T.self)
}
return U(T(bigEndian: value))
}
}
}
| gpl-3.0 | 7386f4d44ce146b63b180c31ac7372a3 | 24.609756 | 93 | 0.526531 | 4.238754 | false | false | false | false |
almazrafi/Metatron | Tests/MetatronTests/ID3v1/ID3v1TagTitleTest.swift | 1 | 7133 | //
// ID3v1TagTitleTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
class ID3v1TagTitleTest: XCTestCase {
// MARK: Instance Methods
func test() {
let textEncoding = ID3v1Latin1TextEncoding.regular
let tag = ID3v1Tag()
do {
let value = ""
tag.title = value
do {
tag.version = ID3v1Version.v0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt0
XCTAssert(tag.toData() == nil)
}
do {
tag.version = ID3v1Version.vExt1
XCTAssert(tag.toData() == nil)
}
}
do {
let value = "Abc 123"
tag.title = value
do {
tag.version = ID3v1Version.v0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.vExt0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
}
do {
let value = "Абв 123"
tag.title = value
do {
tag.version = ID3v1Version.v0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.vExt0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
}
do {
let value = Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")
tag.title = value
do {
tag.version = ID3v1Version.v0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.v1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(30))
}
do {
tag.version = ID3v1Version.vExt0
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
do {
tag.version = ID3v1Version.vExt1
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = ID3v1Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.title == value.deencoded(with: textEncoding).prefix(90))
}
}
}
}
| mit | e713f2666e6f01aca27fe98640c6835a | 26.960784 | 91 | 0.484011 | 4.762859 | false | false | false | false |
a-samarin/YouTubePlayer | YouTubePlayer/YouTubePlayer/AppDelegate.swift | 1 | 6117 | //
// AppDelegate.swift
// YouTubePlayer
//
// Created by Anton Samarin on 25.12.15.
// Copyright © 2015 Anton Samarin. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.youtubeplayer.YouTubePlayer" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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("YouTubePlayer", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 35fb8ccacf0b76f3af1ea328db3041d7 | 54.099099 | 291 | 0.720569 | 5.897782 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/AnyMessageStorage.swift | 1 | 15976 | // Sources/SwiftProtobuf/AnyMessageStorage.swift - Custom stroage for Any WKT
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Hand written storage class for Google_Protobuf_Any to support on demand
/// transforms between the formats.
///
// -----------------------------------------------------------------------------
import Foundation
private let i_2166136261 = Int(bitPattern: 2166136261)
private let i_16777619 = Int(16777619)
fileprivate func serializeAnyJSON(for message: Message, typeURL: String) throws -> String {
var visitor = try JSONEncodingVisitor(message: message)
visitor.startObject()
visitor.encodeField(name: "@type", stringValue: typeURL)
if let m = message as? _CustomJSONCodable {
let value = try m.encodedJSONString()
visitor.encodeField(name: "value", jsonText: value)
} else {
try message.traverse(visitor: &visitor)
}
visitor.endObject()
return visitor.stringResult
}
fileprivate func emitVerboseTextForm(visitor: inout TextFormatEncodingVisitor, message: Message, typeURL: String) {
let url: String
if typeURL.isEmpty {
url = buildTypeURL(forMessage: message, typePrefix: defaultTypePrefix)
} else {
url = typeURL
}
visitor.visitAnyVerbose(value: message, typeURL: url)
}
fileprivate func asJSONObject(body: Data) -> Data {
let asciiOpenCurlyBracket = UInt8(ascii: "{")
let asciiCloseCurlyBracket = UInt8(ascii: "}")
var result = Data(bytes: [asciiOpenCurlyBracket])
result.append(body)
result.append(asciiCloseCurlyBracket)
return result
}
fileprivate func unpack(contentJSON: Data, as messageType: Message.Type) throws -> Message {
guard messageType is _CustomJSONCodable.Type else {
let contentJSONAsObject = asJSONObject(body: contentJSON)
return try messageType.init(jsonUTF8Data: contentJSONAsObject)
}
var value = String()
try contentJSON.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) in
let buffer = UnsafeBufferPointer(start: bytes, count: contentJSON.count)
var scanner = JSONScanner(source: buffer)
let key = try scanner.nextQuotedString()
if key != "value" {
// The only thing within a WKT should be "value".
throw AnyUnpackError.malformedWellKnownTypeJSON
}
try scanner.skipRequiredColon() // Can't fail
value = try scanner.skip()
if !scanner.complete {
// If that wasn't the end, then there was another key,
// and WKTs should only have the one.
throw AnyUnpackError.malformedWellKnownTypeJSON
}
}
return try messageType.init(jsonString: value)
}
internal class AnyMessageStorage {
// The two properties generated Google_Protobuf_Any will reference.
var _typeURL = String()
var _value: Data {
// Remapped to the internal `state`.
get {
switch state {
case .binary(let value):
return value
case .message(let message):
do {
return try message.serializedData(partial: true)
} catch {
return Internal.emptyData
}
case .contentJSON(let contentJSON):
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else {
return Internal.emptyData
}
do {
let m = try unpack(contentJSON: contentJSON, as: messageType)
return try m.serializedData(partial: true)
} catch {
return Internal.emptyData
}
}
}
set {
state = .binary(newValue)
}
}
enum InternalState {
// a serialized binary
case binary(Data)
// a message
case message(Message)
// parsed JSON with the @type removed
case contentJSON(Data)
}
var state: InternalState = .binary(Internal.emptyData)
init() {}
init(copying source: AnyMessageStorage) {
_typeURL = source._typeURL
state = source.state
}
func isA<M: Message>(_ type: M.Type) -> Bool {
if _typeURL.isEmpty {
return false
}
let encodedType = typeName(fromURL: _typeURL)
return encodedType == M.protoMessageName
}
// This is only ever called with the expactation that target will be fully
// replaced during the unpacking and never as a merge.
func unpackTo<M: Message>(target: inout M, extensions: ExtensionMap?) throws {
guard isA(M.self) else {
throw AnyUnpackError.typeMismatch
}
switch state {
case .binary(let data):
target = try M(serializedData: data, extensions: extensions, partial: true)
case .message(let msg):
if let message = msg as? M {
// Already right type, copy it over.
target = message
} else {
// Different type, serialize and parse.
let data = try msg.serializedData(partial: true)
target = try M(serializedData: data, extensions: extensions, partial: true)
}
case .contentJSON(let contentJSON):
target = try unpack(contentJSON: contentJSON, as: M.self) as! M
}
}
// Called before the message is traversed to do any error preflights.
// Since traverse() will use _value, this is our chance to throw
// when _value can't.
func preTraverse() throws {
switch state {
case .binary:
// Nothing to be checked.
break
case .message:
// When set from a developer provided message, partial support
// is done. Any message that comes in from another format isn't
// checked, and transcoding the isInitialized requirement is
// never inserted.
break
case .contentJSON:
// contentJSON requires a good URL and our ability to look up
// the message type to transcode.
if Google_Protobuf_Any.messageType(forTypeURL: _typeURL) == nil {
// Isn't registered, we can't transform it for binary.
throw BinaryEncodingError.anyTranscodeFailure
}
}
}
}
/// Custom handling for Text format.
extension AnyMessageStorage {
func decodeTextFormat(typeURL url: String, decoder: inout TextFormatDecoder) throws {
// Decoding the verbose form requires knowing the type.
_typeURL = url
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: url) else {
// The type wasn't registered, can't parse it.
throw TextFormatDecodingError.malformedText
}
let terminator = try decoder.scanner.skipObjectStart()
var subDecoder = try TextFormatDecoder(messageType: messageType, scanner: decoder.scanner, terminator: terminator)
if messageType == Google_Protobuf_Any.self {
var any = Google_Protobuf_Any()
try any.decodeTextFormat(decoder: &subDecoder)
state = .message(any)
} else {
var m = messageType.init()
try m.decodeMessage(decoder: &subDecoder)
state = .message(m)
}
decoder.scanner = subDecoder.scanner
if try decoder.nextFieldNumber() != nil {
// Verbose any can never have additional keys.
throw TextFormatDecodingError.malformedText
}
}
// Specialized traverse for writing out a Text form of the Any.
// This prefers the more-legible "verbose" format if it can
// use it, otherwise will fall back to simpler forms.
internal func textTraverse(visitor: inout TextFormatEncodingVisitor) {
switch state {
case .binary(let valueData):
if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) {
// If we can decode it, we can write the readable verbose form:
do {
let m = try messageType.init(serializedData: valueData, partial: true)
emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL)
return
} catch {
// Fall through to just print the type and raw binary data
}
}
if !_typeURL.isEmpty {
try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1)
}
if !valueData.isEmpty {
try! visitor.visitSingularBytesField(value: valueData, fieldNumber: 2)
}
case .message(let msg):
emitVerboseTextForm(visitor: &visitor, message: msg, typeURL: _typeURL)
case .contentJSON(let contentJSON):
// If we can decode it, we can write the readable verbose form:
if let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) {
do {
let m = try unpack(contentJSON: contentJSON, as: messageType)
emitVerboseTextForm(visitor: &visitor, message: m, typeURL: _typeURL)
return
} catch {
// Fall through to just print the raw JSON data
}
}
if !_typeURL.isEmpty {
try! visitor.visitSingularStringField(value: _typeURL, fieldNumber: 1)
}
// Build a readable form of the JSON:
let contentJSONAsObject = asJSONObject(body: contentJSON)
visitor.visitAnyJSONDataField(value: contentJSONAsObject)
}
}
}
/// The obvious goal for Hashable/Equatable conformance would be for
/// hash and equality to behave as if we always decoded the inner
/// object and hashed or compared that. Unfortunately, Any typically
/// stores serialized contents and we don't always have the ability to
/// deserialize it. Since none of our supported serializations are
/// fully deterministic, we can't even ensure that equality will
/// behave this way when the Any contents are in the same
/// serialization.
///
/// As a result, we can only really perform a "best effort" equality
/// test. Of course, regardless of the above, we must guarantee that
/// hashValue is compatible with equality.
extension AnyMessageStorage {
var hashValue: Int {
var hash: Int = i_2166136261
if !_typeURL.isEmpty {
hash = (hash &* i_16777619) ^ _typeURL.hashValue
}
// Can't use _valueData for a few reasons:
// 1. Since decode is done on demand, two objects could be equal
// but created differently (one from JSON, one for Message, etc.),
// and the hashes have to be equal even if we don't have data yet.
// 2. map<> serialization order is undefined. At the time of writing
// the Swift, Objective-C, and Go runtimes all tend to have random
// orders, so the messages could be identical, but in binary form
// they could differ.
return hash
}
func isEqualTo(other: AnyMessageStorage) -> Bool {
if (_typeURL != other._typeURL) {
return false
}
// Since the library does lazy Any decode, equality is a very hard problem.
// It things exactly match, that's pretty easy, otherwise, one ends up having
// to error on saying they aren't equal.
//
// The best option would be to have Message forms and compare those, as that
// removes issues like map<> serialization order, some other protocol buffer
// implementation details/bugs around serialized form order, etc.; but that
// would also greatly slow down equality tests.
//
// Do our best to compare what is present have...
// If both have messages, check if they are the same.
if case .message(let myMsg) = state, case .message(let otherMsg) = other.state, type(of: myMsg) == type(of: otherMsg) {
// Since the messages are known to be same type, we can claim both equal and
// not equal based on the equality comparison.
return myMsg.isEqualTo(message: otherMsg)
}
// If both have serialized data, and they exactly match; the messages are equal.
// Because there could be map in the message, the fact that the data isn't the
// same doesn't always mean the messages aren't equal. Likewise, the binary could
// have been created by a library that doesn't order the fields, or the binary was
// created using the appending ability in of the binary format.
if case .binary(let myValue) = state, case .binary(let otherValue) = other.state, myValue == otherValue {
return true
}
// If both have contentJSON, and they exactly match; the messages are equal.
// Because there could be map in the message (or the JSON could just be in a different
// order), the fact that the JSON isn't the same doesn't always mean the messages
// aren't equal.
if case .contentJSON(let myJSON) = state, case .contentJSON(let otherJSON) = other.state, myJSON == otherJSON {
return true
}
// Out of options. To do more compares, the states conversions would have to be
// done to do comparisions; and since equality can be used somewhat removed from
// a developer (if they put protos in a Set, use them as keys to a Dictionary, etc),
// the conversion cost might be to high for those uses. Give up and say they aren't equal.
return false
}
}
// _CustomJSONCodable support for Google_Protobuf_Any
extension AnyMessageStorage {
// Override the traversal-based JSON encoding
// This builds an Any JSON representation from one of:
// * The message we were initialized with,
// * The JSON fields we last deserialized, or
// * The protobuf field we were deserialized from.
// The last case requires locating the type, deserializing
// into an object, then reserializing back to JSON.
func encodedJSONString() throws -> String {
switch state {
case .binary(let valueData):
// Transcode by decoding the binary data to a message object
// and then recode back into JSON.
guard let messageType = Google_Protobuf_Any.messageType(forTypeURL: _typeURL) else {
// If we don't have the type available, we can't decode the
// binary value, so we're stuck. (The Google spec does not
// provide a way to just package the binary value for someone
// else to decode later.)
throw JSONEncodingError.anyTranscodeFailure
}
let m = try messageType.init(serializedData: valueData, partial: true)
return try serializeAnyJSON(for: m, typeURL: _typeURL)
case .message(let msg):
// We should have been initialized with a typeURL, but
// ensure it wasn't cleared.
let url = !_typeURL.isEmpty ? _typeURL : buildTypeURL(forMessage: msg, typePrefix: defaultTypePrefix)
return try serializeAnyJSON(for: msg, typeURL: url)
case .contentJSON(let contentJSON):
var jsonEncoder = JSONEncoder()
jsonEncoder.startObject()
jsonEncoder.startField(name: "@type")
jsonEncoder.putStringValue(value: _typeURL)
if !contentJSON.isEmpty {
jsonEncoder.append(staticText: ",")
jsonEncoder.append(utf8Data: contentJSON)
}
jsonEncoder.endObject()
return jsonEncoder.stringResult
}
}
// TODO: If the type is well-known or has already been registered,
// we should consider decoding eagerly. Eager decoding would
// catch certain errors earlier (good) but would probably be
// a performance hit if the Any contents were never accessed (bad).
// Of course, we can't always decode eagerly (we don't always have the
// message type available), so the deferred logic here is still needed.
func decodeJSON(from decoder: inout JSONDecoder) throws {
try decoder.scanner.skipRequiredObjectStart()
// Reset state
_typeURL = String()
state = .binary(Internal.emptyData)
if decoder.scanner.skipOptionalObjectEnd() {
return
}
var jsonEncoder = JSONEncoder()
while true {
let key = try decoder.scanner.nextQuotedString()
try decoder.scanner.skipRequiredColon()
if key == "@type" {
_typeURL = try decoder.scanner.nextQuotedString()
} else {
jsonEncoder.startField(name: key)
let keyValueJSON = try decoder.scanner.skip()
jsonEncoder.append(text: keyValueJSON)
}
if decoder.scanner.skipOptionalObjectEnd() {
state = .contentJSON(jsonEncoder.dataResult)
return
}
try decoder.scanner.skipRequiredComma()
}
}
}
| mit | 84ff642aa55c46ed7015ce573deca494 | 37.220096 | 123 | 0.675764 | 4.436545 | false | false | false | false |
Coderian/SwiftedGPX | SwiftedGPX/SPXMLElement.swift | 1 | 4810 | //
// SPXMLElement.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
public enum SPXMLElementError: ErrorType {
case InvalidRelationshop
}
/// XML Attribute
public protocol XMLAttributed {
/// attribute name
///
/// - returns: attribute name
static var attributeName:String {
get
}
#if swift(>=3.0)
associatedtype Element
#else
typealias Element
#endif
/// attribute value
///
/// - returns: attribute value
var value: Element {
get
set
}
}
/// XML Root Element
public protocol XMLElementRoot: class {
static var creaters:[String:SPXMLElement.Type] { get }
static func createElement(elementName:String, attributes:[String:String], stack:Stack<SPXMLElement>) -> SPXMLElement?
}
public extension XMLElementRoot {
public static func createElement(elementName:String, attributes:[String:String], stack:Stack<SPXMLElement>) -> SPXMLElement? {
return creaters[elementName]?.init(attributes:attributes)
}
}
/// XML Element Name
public protocol HasXMLElementName : class, CustomStringConvertible {
static var elementName:String { get }
}
/// XML Element Value
public protocol HasXMLElementValue :HasXMLElementName {
#if swift(>=3.0)
associatedtype Element
#else
typealias Element
#endif
var value: Element {
get
set
}
}
// XML Leaf Element
public protocol HasXMLElementSimpleValue {
func makeRelation(contents: String, parent: SPXMLElement) -> SPXMLElement
}
public extension HasXMLElementName {
public var description: String {
get {
return Self.elementName
}
}
}
public extension SPXMLElement {
var root:SPXMLElement {
var currentParent:SPXMLElement = self
while currentParent.parent != nil {
currentParent = currentParent.parent!
}
return currentParent
}
func select<T:HasXMLElementName>(type:T.Type) -> [T] {
var ret = [T]()
for v in self.allChilds().filter({$0 is T}) {
let t = v as! T
ret.append(t)
}
return ret
}
func select(attributeName:String, attributeValue:String) ->[SPXMLElement] {
var ret:[SPXMLElement] = []
for v in self.allChilds().filter({$0.attributes[attributeName] == attributeValue}){
ret.append(v)
}
return ret
}
public func allChilds() -> [SPXMLElement]{
var all:[SPXMLElement] = []
allChilds( &all, current:self)
return all
}
internal func allChilds( inout ret:[SPXMLElement], current: SPXMLElement ){
for child in current.childs {
allChilds(&ret, current: child)
}
ret.append(current)
}
}
/// XML Element base class
public class SPXMLElement : Hashable {
// MARK: Hashable
public var hashValue: Int { return unsafeAddressOf(self).hashValue }
public var parent:SPXMLElement! {
willSet {
if newValue == nil {
self.parent.childs.remove(self)
}
}
}
public var childs:Set<SPXMLElement> = Set<SPXMLElement>()
public var attributes:[String:String] = [:]
public required init(attributes:[String:String]){
self.attributes = attributes
}
public init(){}
}
public func == ( lhs: SPXMLElement, rhs: SPXMLElement) -> Bool {
return lhs === rhs
}
public class UnSupportXMLElement:SPXMLElement, CustomStringConvertible {
public var description: String {
get {
return "{"+self.elementName + "}:{ " + self.value + "}"
}
}
public var elementName:String=""
public var value:String=""
public required init(attributes: [String : String]) {
super.init(attributes: attributes)
}
public init(elementName:String, attributes: [String:String]){
self.elementName = elementName
super.init(attributes: attributes)
}
}
public extension NSDateFormatter {
static func rfc3339Formatter(dateString:String) -> NSDateFormatter {
var dateFormat:String
switch dateString.characters.count {
case 4:
dateFormat="yyyy"
case 7:
dateFormat="yyyy'-'MM"
case 10:
dateFormat="yyyy'-'MM'-'dd"
case 20:
dateFormat="yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
default:
dateFormat="yyyy'-'MM'-'dd'T'HH':'mm':'ss'XXXXXX'"
}
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return dateFormatter
}
}
| mit | 55353ff77d2a0285a0291f24bcaf663e | 25.960674 | 130 | 0.623672 | 4.435305 | false | false | false | false |
SoneeJohn/WWDC | WWDC/SessionsSplitViewController.swift | 1 | 3201 | //
// SessionsSplitViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 05/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
enum SessionsListStyle {
case schedule
case videos
}
final class SessionsSplitViewController: NSSplitViewController {
var listViewController: SessionsTableViewController
var detailViewController: SessionDetailsViewController
var isResizingSplitView: Bool = false
var windowController: MainWindowController
var setupDone: Bool = false
init(windowController: MainWindowController, listStyle: SessionsListStyle) {
self.windowController = windowController
listViewController = SessionsTableViewController(style: listStyle)
detailViewController = SessionDetailsViewController(listStyle: listStyle)
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self, selector: #selector(syncSplitView(notification:)), name: NSSplitView.didResizeSubviewsNotification, object: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
let listItem = NSSplitViewItem(sidebarWithViewController: listViewController)
listItem.canCollapse = false
let detailItem = NSSplitViewItem(viewController: detailViewController)
addSplitViewItem(listItem)
addSplitViewItem(detailItem)
listViewController.view.setContentHuggingPriority(NSLayoutConstraint.Priority.defaultHigh, for: .horizontal)
detailViewController.view.setContentHuggingPriority(NSLayoutConstraint.Priority.defaultLow, for: .horizontal)
detailViewController.view.setContentCompressionResistancePriority(NSLayoutConstraint.Priority.defaultHigh, for: .horizontal)
}
override func viewDidAppear() {
super.viewDidAppear()
if !setupDone {
if let sidebarInitWidth = windowController.sidebarInitWidth {
splitView.setPosition(sidebarInitWidth, ofDividerAt: 0)
}
}
}
@objc private func syncSplitView(notification: Notification) {
guard isResizingSplitView == false else {
return
}
guard notification.userInfo?["NSSplitViewDividerIndex"] != nil else {
return
}
guard let otherSplitView = notification.object as? NSSplitView else {
return
}
guard otherSplitView != splitView else {
// If own split view is altered, change split view initialisation width for other tabs
windowController.sidebarInitWidth = otherSplitView.subviews[0].bounds.width
return
}
guard splitView.subviews.count > 0, otherSplitView.subviews.count > 0 else {
return
}
guard splitView.subviews[0].bounds.width != otherSplitView.subviews[0].bounds.width else {
return
}
isResizingSplitView = true
splitView.setPosition(otherSplitView.subviews[0].bounds.width, ofDividerAt: 0)
isResizingSplitView = false
}
}
| bsd-2-clause | c22782a1b0a4a6528289e1138921d1d0 | 34.164835 | 165 | 0.69875 | 5.423729 | false | false | false | false |
ivanbruel/SwipeIt | SwipeIt/Models/OpenGraph.swift | 1 | 746 | //
// OpenGraph.swift
// Reddit
//
// Created by Ivan Bruel on 10/05/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import Foundation
struct OpenGraph {
let description: String?
let title: String
let imageURL: NSURL?
let appLink: AppLink?
// MARK: HTML
init?(html: String) {
guard let parser = HTMLParser(html: html) else { return nil }
guard let titleMeta = parser.contentFromMetatag("og:title") else {
return nil
}
title = titleMeta
description = parser.contentFromMetatag("og:description")
if let imageMeta = parser.contentFromMetatag("og:image") {
imageURL = NSURL(string: imageMeta)
} else {
imageURL = nil
}
appLink = AppLink(html: html)
}
}
| mit | 6467e9f479666328f6084b202fd03a83 | 19.135135 | 70 | 0.653691 | 3.762626 | false | false | false | false |
Zewo/Epoch | Sources/HTTP/Serializer/Serializer.swift | 1 | 4227 | import Core
import Venice
// TODO: Make CustomStringConvertible
public enum SerializerError : Error {
case invalidContentLength
case writeExceedsContentLength
case noContentLengthOrChunkedEncodingHeaders
}
internal class Serializer {
final class BodyStream : Writable {
enum Mode {
case contentLength(Int)
case chunkedEncoding
}
var bytesRemaining = 0
private let stream: Writable
private let mode: Mode
init(_ stream: Writable, mode: Mode) {
self.stream = stream
self.mode = mode
if case let .contentLength(contentLength) = mode {
bytesRemaining = contentLength
}
}
func write(_ buffer: UnsafeRawBufferPointer, deadline: Deadline) throws {
guard !buffer.isEmpty else {
return
}
switch mode {
case .contentLength:
if bytesRemaining - buffer.count < 0 {
throw SerializerError.writeExceedsContentLength
}
try stream.write(buffer, deadline: deadline)
bytesRemaining -= buffer.count
case .chunkedEncoding:
let chunkLength = String(buffer.count, radix: 16) + "\r\n"
try stream.write(chunkLength, deadline: deadline)
try stream.write(buffer, deadline: deadline)
try stream.write("\r\n", deadline: deadline)
}
}
}
internal let stream: Writable
private let bufferSize: Int
private let buffer: UnsafeMutableRawBufferPointer
internal init(stream: Writable, bufferSize: Int) {
self.stream = stream
self.bufferSize = bufferSize
self.buffer = UnsafeMutableRawBufferPointer.allocate(count: bufferSize)
}
deinit {
buffer.deallocate()
}
internal func serializeHeaders(_ message: Message, deadline: Deadline) throws {
var header = ""
for (name, value) in message.headers {
header += name.description
header += ": "
header += value
header += "\r\n"
}
header += "\r\n"
try stream.write(header, deadline: deadline)
}
internal func serializeBody(_ message: Message, deadline: Deadline) throws {
if let contentLength = message.contentLength {
try writeBody(message, contentLength: contentLength, deadline: deadline)
}
if message.isChunkEncoded {
try writeChunkEncodedBody(message, deadline: deadline)
}
}
@inline(__always)
private func writeBody(_ message: Message, contentLength: Int, deadline: Deadline) throws {
guard contentLength != 0 else {
return
}
guard contentLength > 0 else {
throw SerializerError.invalidContentLength
}
let bodyStream = BodyStream(stream, mode: .contentLength(contentLength))
try write(to: bodyStream, body: message.body, deadline: deadline)
if bodyStream.bytesRemaining > 0 {
throw SerializerError.invalidContentLength
}
}
@inline(__always)
private func writeChunkEncodedBody(_ message: Message, deadline: Deadline) throws {
let bodyStream = BodyStream(stream, mode: .chunkedEncoding)
try write(to: bodyStream, body: message.body, deadline: deadline)
try stream.write("0\r\n\r\n", deadline: deadline)
}
@inline(__always)
private func write(to writable: Writable, body: Body, deadline: Deadline) throws {
switch body {
case let .readable(readable):
while true {
let read = try readable.read(buffer, deadline: deadline)
guard !read.isEmpty else {
break
}
try writable.write(read, deadline: deadline)
}
case let .writable(write):
try write(writable)
}
}
}
| mit | 3e7a60fe74270f4ed29aa09ab1675618 | 30.311111 | 95 | 0.562101 | 5.371029 | false | false | false | false |
rockarloz/WatchKit-Apps | Carthage/Checkouts/Seru/Seru/Example/Example/MasterViewController.swift | 8 | 2435 | //
// MasterViewController.swift
// test111
//
// Created by Konstantin Koval on 27/12/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import UIKit
import CoreData
import Seru
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var stack: PersistenceLayer!
var objects: [NSManagedObject]!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
fetch()
}
func updateTable() {
fetch()
tableView.reloadData()
}
func fetch() {
let fetch = NSFetchRequest(entityName: "Entity")
var error: NSError?
if let result = stack.mainMOC.executeFetchRequest(fetch, error: &error) as? [NSManagedObject] {
objects = result
}
}
func insertNewObject(sender: AnyObject) {
var object = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: stack.mainMOC) as! NSManagedObject
object.setValue(NSDate(), forKey: "time")
stack.persist()
updateTable()
}
// MARK: - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.stack.mainMOC
context.deleteObject(objects[indexPath.row] as NSManagedObject)
stack.persist()
updateTable()
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = objects[indexPath.row]
cell.textLabel!.text = object.valueForKey("time")!.description
}
}
| mit | 9d967e142ab27d86d4b8100953909305 | 29.061728 | 155 | 0.732649 | 5.104822 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Browser/BrowserViewController/BrowserViewController+KeyCommands.swift | 3 | 7831 | /* 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
// Naming functions: use the suffix 'KeyCommand' for an additional level of namespacing (bug 1415830)
extension BrowserViewController {
@objc private func reloadTabKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "reload"])
if let tab = tabManager.selectedTab, homePanelController == nil {
tab.reload()
}
}
@objc private func goBackKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "go-back"])
if let tab = tabManager.selectedTab, tab.canGoBack, homePanelController == nil {
tab.goBack()
}
}
@objc private func goForwardKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "go-forward"])
if let tab = tabManager.selectedTab, tab.canGoForward {
tab.goForward()
}
}
@objc private func findInPageKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "find-in-page"])
if let tab = tabManager.selectedTab, homePanelController == nil {
self.tab(tab, didSelectFindInPageForSelection: "")
}
}
@objc private func selectLocationBarKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "select-location-bar"])
scrollController.showToolbars(animated: true)
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
@objc private func newTabKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "new-tab"])
openBlankNewTab(focusLocationField: true, isPrivate: false)
}
@objc private func newPrivateTabKeyCommand() {
// NOTE: We cannot and should not distinguish between "new-tab" and "new-private-tab"
// when recording telemetry for key commands.
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "new-tab"])
openBlankNewTab(focusLocationField: true, isPrivate: true)
}
@objc private func closeTabKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "close-tab"])
guard let currentTab = tabManager.selectedTab else {
return
}
tabManager.removeTabAndUpdateSelectedIndex(currentTab)
}
@objc private func nextTabKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "next-tab"])
guard let currentTab = tabManager.selectedTab else {
return
}
let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let index = tabs.index(of: currentTab), index + 1 < tabs.count {
tabManager.selectTab(tabs[index + 1])
} else if let firstTab = tabs.first {
tabManager.selectTab(firstTab)
}
}
@objc private func previousTabKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "previous-tab"])
guard let currentTab = tabManager.selectedTab else {
return
}
let tabs = currentTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let index = tabs.index(of: currentTab), index - 1 < tabs.count && index != 0 {
tabManager.selectTab(tabs[index - 1])
} else if let lastTab = tabs.last {
tabManager.selectTab(lastTab)
}
}
@objc private func showTabTrayKeyCommand() {
UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "show-tab-tray"])
showTabTray()
}
@objc private func moveURLCompletionKeyCommand(sender: UIKeyCommand) {
guard let searchController = self.searchController else {
return
}
searchController.handleKeyCommands(sender: sender)
}
override var keyCommands: [UIKeyCommand]? {
let searchLocationCommands = [
UIKeyCommand(input: UIKeyInputDownArrow, modifierFlags: [], action: #selector(moveURLCompletionKeyCommand(sender:))),
UIKeyCommand(input: UIKeyInputUpArrow, modifierFlags: [], action: #selector(moveURLCompletionKeyCommand(sender:))),
]
let overidesTextEditing = [
UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: [.command, .shift], action: #selector(nextTabKeyCommand)),
UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: [.command, .shift], action: #selector(previousTabKeyCommand)),
UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: .command, action: #selector(goBackKeyCommand)),
UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: .command, action: #selector(goForwardKeyCommand)),
]
let tabNavigation = [
UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(reloadTabKeyCommand), discoverabilityTitle: Strings.ReloadPageTitle),
UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(goBackKeyCommand), discoverabilityTitle: Strings.BackTitle),
UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(goForwardKeyCommand), discoverabilityTitle: Strings.ForwardTitle),
UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(findInPageKeyCommand), discoverabilityTitle: Strings.FindTitle),
UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(selectLocationBarKeyCommand), discoverabilityTitle: Strings.SelectLocationBarTitle),
UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(newTabKeyCommand), discoverabilityTitle: Strings.NewTabTitle),
UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(newPrivateTabKeyCommand), discoverabilityTitle: Strings.NewPrivateTabTitle),
UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(closeTabKeyCommand), discoverabilityTitle: Strings.CloseTabTitle),
UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(nextTabKeyCommand), discoverabilityTitle: Strings.ShowNextTabTitle),
UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(previousTabKeyCommand), discoverabilityTitle: Strings.ShowPreviousTabTitle),
// Switch tab to match Safari on iOS.
UIKeyCommand(input: "]", modifierFlags: [.command, .shift], action: #selector(nextTabKeyCommand)),
UIKeyCommand(input: "[", modifierFlags: [.command, .shift], action: #selector(previousTabKeyCommand)),
UIKeyCommand(input: "\\", modifierFlags: [.command, .shift], action: #selector(showTabTrayKeyCommand)), // Safari on macOS
UIKeyCommand(input: "\t", modifierFlags: [.command, .alternate], action: #selector(showTabTrayKeyCommand), discoverabilityTitle: Strings.ShowTabTrayFromTabKeyCodeTitle)
]
let isEditingText = tabManager.selectedTab?.isEditing ?? false
if urlBar.inOverlayMode {
return tabNavigation + searchLocationCommands
} else if !isEditingText {
return tabNavigation + overidesTextEditing
}
return tabNavigation
}
}
| mpl-2.0 | 9049b9ae81f38dfeed5aa07d51393219 | 52.636986 | 180 | 0.682799 | 4.91897 | false | false | false | false |
eoger/firefox-ios | Client/Frontend/Settings/FxAContentViewController.swift | 2 | 10264 | /* 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 SnapKit
import UIKit
import WebKit
import SwiftyJSON
protocol FxAContentViewControllerDelegate: AnyObject {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags: FxALoginFlags)
func contentViewControllerDidCancel(_ viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
fileprivate enum RemoteCommand: String {
case canLinkAccount = "can_link_account"
case loaded = "loaded"
case login = "login"
case sessionStatus = "session_status"
case signOut = "sign_out"
}
weak var delegate: FxAContentViewControllerDelegate?
let profile: Profile
init(profile: Profile, fxaOptions: FxALaunchParams? = nil) {
self.profile = profile
super.init(backgroundColor: UIColor.Photon.Grey20, title: NSAttributedString(string: "Firefox Accounts"))
self.url = self.createFxAURLWith(fxaOptions, profile: profile)
NotificationCenter.default.addObserver(self, selector: #selector(userDidVerify), name: .FirefoxAccountVerified, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
profile.getAccount()?.updateProfile()
// If the FxAContentViewController was launched from a FxA deferred link
// onboarding might not have been shown. Check to see if it needs to be
// displayed and don't animate.
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(false, animated: false)
}
}
override func makeWebView() -> WKWebView {
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.add(LeakAvoider(delegate: self), name: "accountsCommandHandler")
// Inject our user script after the page loads.
if let path = Bundle.main.path(forResource: "FxASignIn", ofType: "js") {
if let source = try? String(contentsOfFile: path, encoding: .utf8) {
let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(userScript)
}
}
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(width: 1, height: 1),
configuration: config
)
webView.allowsLinkPreview = false
webView.navigationDelegate = self
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(_ type: String, content: [String: Any]) {
let data = [
"type": type,
"content": content,
] as [String: Any]
let json = JSON(data).stringValue() ?? ""
let script = "window.postMessage(\(json), '\(self.url.absoluteString)');"
webView.evaluateJavaScript(script, completionHandler: nil)
}
fileprivate func onCanLinkAccount(_ data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]])
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
fileprivate func onSessionStatus(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
fileprivate func onSignOut(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
fileprivate func onLogin(_ data: JSON) {
injectData("message", content: ["status": "login"])
let app = UIApplication.shared
let helper = FxALoginHelper.sharedInstance
helper.delegate = self
helper.application(app, didReceiveAccountJSON: data)
if profile.hasAccount() {
LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: true])
}
LeanPlumClient.shared.track(event: .signsInFxa)
}
@objc fileprivate func userDidVerify(_ notification: Notification) {
guard let account = profile.getAccount() else {
return
}
// We can't verify against the actionNeeded of the account,
// because of potential race conditions.
// However, we restrict visibility of this method, and make sure
// we only Notify via the FxALoginStateMachine.
let flags = FxALoginFlags(pushEnabled: account.pushRegistration != nil,
verified: true)
LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: true])
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
// The content server page is ready to be shown.
fileprivate func onLoaded() {
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(_ rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
if !isLoaded && command != .loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
onLoaded()
}
switch command {
case .loaded:
onLoaded()
case .login:
onLogin(data)
case .canLinkAccount:
onCanLinkAccount(data)
case .sessionStatus:
onSessionStatus(data)
case .signOut:
onSignOut(data)
}
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Make sure we're communicating with a trusted page. That is, ensure the origin of the
// message is the same as the origin of the URL we initially loaded in this web view.
// Note that this exploit wouldn't be possible if we were using WebChannels; see
// https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/WebChannel.jsm
let origin = message.frameInfo.securityOrigin
guard origin.`protocol` == url.scheme && origin.host == url.host && origin.port == (url.port ?? 0) else {
print("Ignoring message - \(origin) does not match expected origin: \(url.origin ?? "nil")")
return
}
if message.name == "accountsCommandHandler" {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].stringValue, data: detail["data"])
}
}
// Configure the FxA signin url based on any passed options.
public func createFxAURLWith(_ fxaOptions: FxALaunchParams?, profile: Profile) -> URL {
let profileUrl = profile.accountConfiguration.signInURL
guard let launchParams = fxaOptions else {
return profileUrl
}
// Only append `signin`, `entrypoint` and `utm_*` parameters. Note that you can't
// override the service and context params.
var params = launchParams.query
params.removeValue(forKey: "service")
params.removeValue(forKey: "context")
let queryURL = params.filter { $0.key == "signin" || $0.key == "entrypoint" || $0.key.range(of: "utm_") != nil }.map({
return "\($0.key)=\($0.value)"
}).joined(separator: "&")
return URL(string: "\(profileUrl)&\(queryURL)") ?? profileUrl
}
override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Ignore for now.
}
override func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
// Ignore for now.
}
}
extension FxAContentViewController: FxAPushLoginDelegate {
func accountLoginDidSucceed(withFlags flags: FxALoginFlags) {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
func accountLoginDidFail() {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidCancel(self)
}
}
}
/*
LeakAvoider prevents leaks with WKUserContentController
http://stackoverflow.com/questions/26383031/wkwebview-causes-my-view-controller-to-leak
*/
class LeakAvoider: NSObject, WKScriptMessageHandler {
weak var delegate: WKScriptMessageHandler?
init(delegate: WKScriptMessageHandler) {
self.delegate = delegate
super.init()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
self.delegate?.userContentController(userContentController, didReceive: message)
}
}
| mpl-2.0 | b009927a3f3eda45d342b1431254c88a | 37.732075 | 132 | 0.654813 | 4.939365 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/Creation/FetchToybooCreationRequestSpec.swift | 1 | 1825 | //
// FetchToybooCreationRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class FetchToybooCreationRequestSpec: QuickSpec {
override func spec() {
describe("Creations request") {
it("Should have a proper method") {
let request = FetchToybooCreationRequest(creationId: "")
expect(request.method) == RequestMethod.get
}
it("Should have a proper endpoint") {
let request = FetchToybooCreationRequest(creationId: "test")
expect(request.endpoint) == "creations/test/toyboo_details"
}
}
}
}
| mit | ac9f2ef12f510a54d7ab0ad7e9720015 | 40.477273 | 81 | 0.703014 | 4.462103 | false | true | false | false |
emilstahl/swift | test/decl/protocol/req/optionality.swift | 14 | 4829 | // RUN: %target-parse-verify-swift
@objc class C1 { }
@objc class C2 { }
// ------------------------------------------------------------------------
// Parameters of IUO type.
// ------------------------------------------------------------------------
@objc protocol ParameterIUO1 {
optional func f0(x: C1!)
}
@objc class ParameterIUO1a : ParameterIUO1 {
func f0(x: C1!) { } // okay: exact match
}
@objc class ParameterIUO1b : ParameterIUO1 {
func f0(x: C1) { } // okay: all is permitted with IUO requirements
}
@objc class ParameterIUO1c : ParameterIUO1 {
func f0(x: C1?) { } // okay: all is permitted with IUO requirements
}
// ------------------------------------------------------------------------
// Parameters of optional type.
// ------------------------------------------------------------------------
@objc protocol ParameterOpt1 {
optional func f0(x: C1?) // expected-note 2{{declared here}}
}
@objc class ParameterOpt1a : ParameterOpt1 {
func f0(x: C1?) { } // okay: exact match
}
@objc class ParameterOpt1b : ParameterOpt1 {
func f0(x: C1!) { } // expected-warning{{different optionality than expected}}{{16-17=?}}
}
@objc class ParameterOpt1c : ParameterOpt1 {
func f0(x: C1) { } // expected-error{{different optionality than required}}{{16-16=?}}
}
// ------------------------------------------------------------------------
// Parameters of non-optional type.
// ------------------------------------------------------------------------
@objc protocol ParameterNonOpt1 {
optional func f0(x: C1) // expected-note 2{{declared here}}
}
@objc class ParameterNonOpt1a : ParameterNonOpt1 {
func f0(x: C1) { } // okay: exact match
}
@objc class ParameterNonOpt1b : ParameterNonOpt1 {
func f0(x: C1!) { } // expected-warning{{parameter of 'f0' has different optionality than expected by protocol 'ParameterNonOpt1'}}{{16-17=}}
}
@objc class ParameterNonOpt1c : ParameterNonOpt1 {
func f0(x: C1?) { } // expected-warning{{parameter of 'f0' has different optionality than expected by protocol 'ParameterNonOpt1'}}{{16-17=}}
}
// ------------------------------------------------------------------------
// Result of IUO type.
// ------------------------------------------------------------------------
@objc protocol ResultIUO1 {
optional func f0() -> C1!
}
@objc class ResultIUO1a : ResultIUO1 {
func f0() -> C1! { return nil } // okay: exact match
}
@objc class ResultIUO1b : ResultIUO1 {
func f0() -> C1 { } // okay: all is permitted with IUO requirements
}
@objc class ResultIUO1c : ResultIUO1 {
func f0() -> C1? { } // okay: all is permitted with IUO requirements
}
// ------------------------------------------------------------------------
// Result of optional type.
// ------------------------------------------------------------------------
@objc protocol ResultOpt1 {
optional func f0() -> C1? // expected-note 2{{declared here}}
}
@objc class ResultOpt1a : ResultOpt1 {
func f0() -> C1? { return nil } // okay: exact match
}
@objc class ResultOpt1b : ResultOpt1 {
func f0() -> C1 { } // expected-warning{{different optionality}}{{18-18=?}}
}
@objc class ResultOpt1c : ResultOpt1 {
func f0() -> C1! { } // expected-warning{{different optionality}}{{18-19=?}}
}
// ------------------------------------------------------------------------
// Result of non-optional type.
// ------------------------------------------------------------------------
@objc protocol ResultNonOpt1 {
optional func f0() -> C1 // expected-note 2 {{declared here}}
}
@objc class ResultNonOpt1a : ResultNonOpt1 {
func f0() -> C1 { } // okay: exact match
}
@objc class ResultNonOpt1b : ResultNonOpt1 {
func f0() -> C1? { } // expected-error{{different optionality than required}}{{18-19=}}
}
@objc class ResultNonOpt1c : ResultNonOpt1 {
func f0() -> C1! { } // expected-warning{{different optionality}}{{18-19=}}
}
// ------------------------------------------------------------------------
// Multiple parameter mismatches
// ------------------------------------------------------------------------
@objc protocol MultiParamsOpt1 {
optional func f0(x: C1?, y: C1) // expected-note{{here}}
}
@objc class MultiParamsOpt1a : MultiParamsOpt1 {
func f0(x: C1!, y: C1!) { } // expected-warning{{parameters of 'f0(_:y:)' have different optionality than expected}}{{16-17=?}}{{24-25=}}
}
// ------------------------------------------------------------------------
// Parameter and result type mismatches
// ------------------------------------------------------------------------
@objc protocol ParamAndResult1 {
optional func f0(x: C1?) -> C1 // expected-note{{here}}
}
@objc class ParamAndResult1a : ParamAndResult1 {
func f0(x: C1!) -> C1! { } // expected-warning{{result and parameters of 'f0' have different optionality than expected}}{{16-17=?}}{{24-25=}}
}
| apache-2.0 | 3ec168568d882fd4f44800f383695db5 | 33.248227 | 143 | 0.507144 | 4.014131 | false | false | false | false |
cornerAnt/Digger | Sources/DiggerThread.swift | 1 | 1220 | //
// DiggerThread.swift
// Digger
//
// Created by ant on 2017/10/27.
// Copyright © 2017年 github.cornerant. All rights reserved.
//
import Foundation
extension DispatchQueue {
static let barrier = DispatchQueue(label: "com.github.cornerAnt.diggerThread.Barrier", attributes: .concurrent)
static let cancel = DispatchQueue(label: "com.github.cornerAnt.diggerThread.cancel", attributes: .concurrent)
static let download = DispatchQueue(label: "com.github.cornerAnt.downloadSession.download",attributes: .concurrent)
static let forFun = DispatchQueue(label: "com.github.cornerAnt.diggerThread.forFun", attributes: .concurrent)
func safeAsync(_ block: @escaping ()->()) {
if self === DispatchQueue.main && Thread.isMainThread {
block()
} else {
async { block() }
}
}
}
extension OperationQueue {
static var downloadDelegateOperationQueue : OperationQueue {
let downloadDelegateOperationQueue = OperationQueue()
downloadDelegateOperationQueue.name = "com.github.cornerAnt.diggerThread.downloadDelegateOperationQueue"
return downloadDelegateOperationQueue
}
}
| mit | 3199c1d1812e2c309419a5014184658d | 31.026316 | 119 | 0.68447 | 4.541045 | false | false | false | false |
dabing1022/AlgorithmRocks | DataStructureAlgorithm/Playground/DataStructureAlgorithm.playground/Pages/BubbleSort.xcplaygroundpage/Contents.swift | 1 | 1046 | //: [Previous](@previous)
//: BubbleSort
import Foundation
var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5]
var randomNumbers2 = [2, 1, 3, 4, 5, 6, 7, 8, 9, 10]
func swapTwoValues<T>(inout a: T, inout _ b: T) {
(a, b) = (b, a)
}
func bubbleSort(inout nums: [Int]) {
while true {
var swapped = false
for i in 1..<nums.count {
if nums[i] < nums[i - 1] {
swapTwoValues(&nums[i], &nums[i - 1])
swapped = true
}
}
if !swapped {
break
}
}
}
bubbleSort(&randomNumbers)
func bubbleSort_2(inout nums: [Int]) {
var flag = true
for (var i = 1; i < nums.count && flag; i++) {
flag = false
for j in (i..<nums.count).reverse() {
if nums[j] < nums[j - 1] {
swapTwoValues(&nums[j], &nums[j - 1])
flag = true
}
}
}
}
bubbleSort_2(&randomNumbers2)
//: [Next](@next)
| mit | 404703aa5dbc01cd94c51c1aeea9a9f7 | 19.92 | 97 | 0.459847 | 3.160121 | false | false | false | false |
asalom/Cocoa-Design-Patterns-in-Swift | DesignPatterns/DesignPatterns/Hide Complexity/Mediator/Mediator.swift | 1 | 1204 | //
// Mediator.swift
// DesignPatterns
//
// Created by Alex Salom on 18/11/15.
// Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved.
//
import Foundation
class AbstractUser {
let mediator: Mediator
let name: String
var messageReceived = false
init(_ name: String, mediator: Mediator) {
self.mediator = mediator
self.name = name
}
func send(message: String) {
self.mediator.send(message, forumUser: self)
}
func receive(message: String) {
assert(false, "Method should be overriden")
}
}
protocol Mediator {
func send(message: String, forumUser: AbstractUser)
}
class MessageMediator: Mediator {
private var users: [AbstractUser] = []
func addUser(user: AbstractUser) {
self.users.append(user)
}
func send(message: String, forumUser: AbstractUser) {
for user in self.users {
if user !== forumUser {
user.receive(message)
}
}
}
}
class RealUser: AbstractUser {
override func receive(message: String) {
self.messageReceived = true
print("\(self.name) received: \(message)")
}
} | mit | b6adb99e7687ce78ea9d6b59caa39cd8 | 20.872727 | 68 | 0.605657 | 4.033557 | false | false | false | false |
wuleijun/Zeus | Zeus/ViewControllers/LoginVerifyMobileVC.swift | 1 | 3265 | //
// LoginVerifyMobileVC.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/13.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class LoginVerifyMobileVC: BaseViewController {
@IBOutlet private weak var nextButton: UIButton!
@IBOutlet private weak var resendButton: UIButton!
@IBOutlet private weak var codeTextField: BorderTextField!
@IBOutlet private weak var mobileLabel: UILabel!
var second = ZeusConfig.resendVerifyCodeSeconds()
var haveAppropriateInput = false {
willSet{
nextButton.enabled = newValue
if newValue {
verifyMobile()
}
}
}
lazy var timer: NSTimer = {
let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(timeFired), userInfo: nil, repeats: true)
return timer
}()
var mobile:String!
override func viewDidLoad() {
super.viewDidLoad()
nextButton.enabled = false
// Do any additional setup after loading the view.
mobileLabel.text = mobile
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
timer.invalidate()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
timer.fire()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
codeTextField.becomeFirstResponder()
}
// MARK: Actions
func timeFired() {
if second > 1 {
UIView.performWithoutAnimation({
self.resendButton.setTitle("重新获取(\(self.second))", forState: .Normal)
self.resendButton.layoutIfNeeded()
})
resendButton.enabled = false
second -= 1
}else{
UIView.performWithoutAnimation({
self.resendButton.setTitle("重新获取", forState: .Normal)
self.resendButton.layoutIfNeeded()
})
resendButton.enabled = true
}
}
@IBAction func textFieldChanged(textField: UITextField) {
guard let text = textField.text else {
return
}
haveAppropriateInput = text.characters.count == ZeusConfig.verifyCodeLength()
}
@IBAction func resend_Touch(sender: AnyObject) {
second = ZeusConfig.resendVerifyCodeSeconds()
}
@IBAction func finishLogin_Touch(sender: AnyObject) {
verifyMobile()
}
func verifyMobile() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.startMainStory()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 83ffda017b484b5724427c8e59e98251 | 28.153153 | 137 | 0.621755 | 5.080063 | false | false | false | false |
Neku/easy-hodl | ios/CryptoSaver/Carthage/Checkouts/QRCodeReader.swift/Sources/QRCodeReaderView.swift | 2 | 6327 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
final public class QRCodeReaderView: UIView, QRCodeReaderDisplayable {
public lazy var overlayView: UIView? = {
let ov = ReaderOverlayView()
ov.backgroundColor = .clear
ov.clipsToBounds = true
ov.translatesAutoresizingMaskIntoConstraints = false
return ov
}()
public let cameraView: UIView = {
let cv = UIView()
cv.clipsToBounds = true
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
public lazy var cancelButton: UIButton? = {
let cb = UIButton()
cb.translatesAutoresizingMaskIntoConstraints = false
cb.setTitleColor(.gray, for: .highlighted)
return cb
}()
public lazy var switchCameraButton: UIButton? = {
let scb = SwitchCameraButton()
scb.translatesAutoresizingMaskIntoConstraints = false
return scb
}()
public lazy var toggleTorchButton: UIButton? = {
let ttb = ToggleTorchButton()
ttb.translatesAutoresizingMaskIntoConstraints = false
return ttb
}()
private weak var reader: QRCodeReader?
public func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool, showOverlayView: Bool, reader: QRCodeReader?) {
self.reader = reader
addComponents()
cancelButton?.isHidden = !showCancelButton
switchCameraButton?.isHidden = !showSwitchCameraButton
toggleTorchButton?.isHidden = !showTorchButton
overlayView?.isHidden = !showOverlayView
guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton, let ov = overlayView else { return }
let views = ["cv": cameraView, "ov": ov, "cb": cb, "scb": scb, "ttb": ttb]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views))
if showCancelButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views))
}
else {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views))
}
if showSwitchCameraButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views))
}
if showTorchButton {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views))
}
for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) {
addConstraint(NSLayoutConstraint(item: ov, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0))
}
}
public override func layoutSubviews() {
super.layoutSubviews()
reader?.previewLayer.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
}
// MARK: - Scan Result Indication
func startTimerForBorderReset() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .white
}
}
}
func addRedBorder() {
self.startTimerForBorderReset()
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .red
}
}
func addGreenBorder() {
self.startTimerForBorderReset()
if let ovl = self.overlayView as? ReaderOverlayView {
ovl.overlayColor = .green
}
}
func orientationDidChange() {
setNeedsDisplay()
overlayView?.setNeedsDisplay()
if let connection = reader?.previewLayer.connection, connection.isVideoOrientationSupported {
let orientation = UIDevice.current.orientation
let supportedInterfaceOrientations = UIApplication.shared.supportedInterfaceOrientations(for: nil)
connection.videoOrientation = QRCodeReader.videoOrientation(deviceOrientation: orientation, withSupportedOrientations: supportedInterfaceOrientations, fallbackOrientation: connection.videoOrientation)
}
}
// MARK: - Convenience Methods
private func addComponents() {
NotificationCenter.default.addObserver(self, selector: #selector(QRCodeReaderView.orientationDidChange), name: .UIDeviceOrientationDidChange, object: nil)
addSubview(cameraView)
if let ov = overlayView {
addSubview(ov)
}
if let scb = switchCameraButton {
addSubview(scb)
}
if let ttb = toggleTorchButton {
addSubview(ttb)
}
if let cb = cancelButton {
addSubview(cb)
}
if let reader = reader {
cameraView.layer.insertSublayer(reader.previewLayer, at: 0)
orientationDidChange()
}
}
}
| mit | 4d6b46373381f48b22799b4a3826510d | 32.654255 | 206 | 0.700648 | 4.840857 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Base/ViewCell/BFBaseCell.swift | 1 | 3107 | //
// BFBaseCell.swift
// BeeFun
//
// Created by wenghengcong on 16/1/17.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import UIKit
class BFBaseCell: UITableViewCell {
var topLineView: UIView?
var botLineView: UIView?
/**
* 是否为完整的底部灰线
*/
var fullBottomline: Bool?
/**
* 是否有顶部线条
*/
var topline: Bool?
static func cellFromNibNamed(_ nibName: String) -> AnyObject {
var nibContents: Array = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)!
let xibBasedCell = nibContents[0]
return xibBasedCell as AnyObject
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
p_customCellView()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
p_customCellView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func p_customCellView() {
if botLineView == nil {
botLineView = UIView()
botLineView?.backgroundColor = UIColor.bfLineBackgroundColor
self.contentView.addSubview(botLineView!)
}
let retinaPixelSize: CGFloat = 1
botLineView?.frame = CGRect(x: 10, y: self.contentView.height-retinaPixelSize, w: ScreenSize.width-10, h: retinaPixelSize)
if topLineView == nil {
topLineView = UIView()
topLineView?.backgroundColor = UIColor.bfLineBackgroundColor
topLineView?.frame = CGRect(x: 0, y: 0, w: ScreenSize.width, h: retinaPixelSize)
self.contentView.addSubview(topLineView!)
topLineView?.isHidden = true
}
}
func setBothEndsLines(_ current: Int, all rowsOfSection: Int) {
self.topline = nil
self.fullBottomline = nil
if current == 0 {
self.topline = true
} else if current > 0 {
self.topline = false
}
if rowsOfSection > 0 {
if current == rowsOfSection-1 {
self.fullBottomline = true
} else {
self.fullBottomline = false
}
}
self.layoutSubFrames()
}
func layoutSubFrames() {
if topline != nil {
topLineView?.isHidden = !(topline!)
}
if let fullBottom = fullBottomline {
let retinaPixelSize: CGFloat = 0.5
if fullBottom {
botLineView?.frame = CGRect(x: 0, y: self.contentView.height-retinaPixelSize, w: ScreenSize.width, h: retinaPixelSize)
} else {
botLineView?.frame = CGRect(x: 10, y: self.contentView.height-retinaPixelSize, w: ScreenSize.width-10, h: retinaPixelSize)
}
}
}
}
| mit | ef0d4e88bef517d6af302adbf4edff09 | 28.238095 | 138 | 0.585668 | 4.521355 | false | false | false | false |
eelcokoelewijn/StepUp | StepUp/Modules/ExerciseActive/ExerciseViewController.swift | 1 | 2781 | import UIKit
import App
protocol ExerciseResult {
func result() -> Exercise
}
class ExerciseViewController: UIViewController,
UsesExerciseViewModel,
ExerciseViewOutput {
internal let exerciseViewModel: ExerciseViewModel
private var activeVC: UIViewController!
init(viewModel: ExerciseViewModel) {
exerciseViewModel = viewModel
super.init(nibName: nil, bundle: nil)
exerciseViewModel.setOutput(output: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
exerciseViewModel.start()
}
// MARK: ViewModelOuputView
func show(exercise: Exercise) {
switch exercise.type {
case .active:
activeVC = ActiveViewController(exercise: exercise)
add(viewController: activeVC)
return
case .positive:
activeVC = PositiveViewController(exercise: exercise)
add(viewController: activeVC)
return
case .mindfulness:
activeVC = MindfulnessViewController(exercise: exercise)
add(viewController: activeVC)
return
}
}
func pop() {
activeVC.view.removeFromSuperview()
activeVC.removeFromParent()
activeVC = nil
presentingViewController?.dismiss(animated: true, completion: nil)
}
private func add(viewController vc: UIViewController) {
addChild(vc)
view.addSubview(vc.view)
vc.didMove(toParent: self)
}
private func setup() {
let leftButton = UIBarButtonItem(title: "Annuleren",
style: .plain,
target: self,
action: #selector(cancel(sender:)))
leftButton.tintColor = .cancelAction
navigationItem.leftBarButtonItem = leftButton
let rightButton = UIBarButtonItem(title: "Opslaan",
style: .done,
target: self,
action: #selector(save(sender:)))
rightButton.tintColor = .actionGreen
navigationItem.rightBarButtonItem = rightButton
view.backgroundColor = .white
}
@objc private func cancel(sender: UIBarButtonItem) {
exerciseViewModel.cancel()
}
@objc private func save(sender: UIBarButtonItem) {
guard let vc = activeVC as? ExerciseResult else { return }
exerciseViewModel.save(exercise: vc.result())
}
}
| mit | c871378bc8deef079c73c53208a773c0 | 30.602273 | 76 | 0.56886 | 5.595573 | false | false | false | false |
jacobwhite/firefox-ios | Extensions/ShareTo/ShareViewController.swift | 1 | 11795 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Shared
import Storage
import Deferred
extension UIStackView {
func addBackground(color: UIColor) {
let subView = UIView(frame: bounds)
subView.backgroundColor = color
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subView, at: 0)
}
func rightLeftEdges(inset: CGFloat) {
layoutMargins = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
isLayoutMarginsRelativeArrangement = true
}
}
extension UILabel {
// Ensures labels can span a second line and will compress to fit text
func handleLongLabels() {
numberOfLines = 2
adjustsFontSizeToFitWidth = true
allowsDefaultTighteningForTruncation = true
}
}
protocol ShareControllerDelegate: class {
func finish(afterDelay: TimeInterval)
func getValidExtensionContext() -> NSExtensionContext?
func getShareItem() -> Deferred<ShareItem?>
}
class ShareViewController: UIViewController {
private var shareItem: ShareItem?
private var viewsShownDuringDoneAnimation = [UIView]()
private var stackView: UIStackView!
private var sendToDevice: SendToDevice?
private var actionDoneRow: (row: UIStackView, label: UILabel)!
weak var delegate: ShareControllerDelegate?
override var extensionContext: NSExtensionContext? {
get {
return delegate?.getValidExtensionContext()
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupNavBar()
setupStackView()
let pageInfoRow = makePageInfoRow(addTo: stackView)
makeSeparator(addTo: stackView)
makeActionRow(addTo: stackView, label: Strings.ShareLoadInBackground, imageName: "menu-Show-Tabs", action: #selector(actionLoadInBackground), hasNavigation: false)
makeActionRow(addTo: stackView, label: Strings.ShareBookmarkThisPage, imageName: "AddToBookmarks", action: #selector(actionBookmarkThisPage), hasNavigation: false)
makeActionRow(addTo: stackView, label: Strings.ShareAddToReadingList, imageName: "AddToReadingList", action: #selector(actionAddToReadingList), hasNavigation: false)
makeSeparator(addTo: stackView)
makeActionRow(addTo: stackView, label: Strings.ShareSendToDevice, imageName: "menu-Send-to-Device", action: #selector(actionSendToDevice), hasNavigation: true)
let footerSpaceRow = UIView()
stackView.addArrangedSubview(footerSpaceRow)
// Without some growable space at the bottom there are constraint errors because the UIView space doesn't subdivide equally, and none of the rows are growable.
// Also, during the animation to the done state, without this space, the page info label moves down slightly.
footerSpaceRow.snp.makeConstraints { make in
make.height.greaterThanOrEqualTo(0)
}
actionDoneRow = makeActionDoneRow(addTo: stackView)
// Fully constructing and pre-adding as a subview ensures that only the show operation will animate during the UIView.animate(),
// and other animatable properties will not unexpectedly animate because they are modified in the same event loop as the animation.
actionDoneRow.row.isHidden = true
// All other views are hidden for the done animation.
viewsShownDuringDoneAnimation += [pageInfoRow.row, footerSpaceRow, actionDoneRow.row]
delegate?.getShareItem().uponQueue(.main) { shareItem in
guard let shareItem = shareItem, shareItem.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish(afterDelay: 0) })
self.present(alert, animated: true, completion: nil)
return
}
self.shareItem = shareItem
pageInfoRow.urlLabel.text = shareItem.url
pageInfoRow.pageTitleLabel.text = shareItem.title
}
}
private func makeSeparator(addTo parent: UIStackView) {
let view = UIView()
view.backgroundColor = UX.separatorColor
parent.addArrangedSubview(view)
view.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.height.equalTo(1)
}
}
private func makePageInfoRow(addTo parent: UIStackView) -> (row: UIStackView, pageTitleLabel: UILabel, urlLabel: UILabel) {
let row = UIStackView()
row.axis = .horizontal
row.alignment = .center
row.rightLeftEdges(inset: UX.rowInset)
parent.addArrangedSubview(row)
row.snp.makeConstraints { make in
make.height.equalTo(UX.pageInfoRowHeight)
}
let verticalStackView = UIStackView()
verticalStackView.axis = .vertical
verticalStackView.spacing = UX.pageInfoLineSpacing
row.addArrangedSubview(verticalStackView)
let pageTitleLabel = UILabel()
let urlLabel = UILabel()
[pageTitleLabel, urlLabel].forEach { label in
verticalStackView.addArrangedSubview(label)
label.allowsDefaultTighteningForTruncation = true
label.lineBreakMode = .byTruncatingMiddle
label.font = UX.baseFont
}
pageTitleLabel.font = UIFont.boldSystemFont(ofSize: UX.baseFont.pointSize)
return (row, pageTitleLabel, urlLabel)
}
private func makeActionRow(addTo parent: UIStackView, label: String, imageName: String, action: Selector, hasNavigation: Bool) {
let row = UIStackView()
row.axis = .horizontal
row.spacing = UX.actionRowSpacingBetweenIconAndTitle
row.rightLeftEdges(inset: UX.rowInset)
parent.addArrangedSubview(row)
row.snp.makeConstraints { make in
make.height.equalTo(UX.actionRowHeight)
}
let icon = UIImageView(image: UIImage(named: imageName)?.withRenderingMode(.alwaysTemplate))
icon.contentMode = .scaleAspectFit
icon.tintColor = UX.actionRowTextAndIconColor
let title = UILabel()
title.font = UX.baseFont
title.handleLongLabels()
title.textColor = UX.actionRowTextAndIconColor
title.text = label
[icon, title].forEach { row.addArrangedSubview($0) }
icon.snp.makeConstraints { make in
make.width.equalTo(UX.actionRowIconSize)
}
if hasNavigation {
let navButton = UIImageView(image: UIImage(named: "menu-Disclosure")?.withRenderingMode(.alwaysTemplate))
navButton.contentMode = .scaleAspectFit
navButton.tintColor = UX.actionRowTextAndIconColor
row.addArrangedSubview(navButton)
navButton.snp.makeConstraints { make in
make.width.equalTo(14)
}
}
let gesture = UITapGestureRecognizer(target: self, action: action)
row.addGestureRecognizer(gesture)
}
fileprivate func animateToActionDoneView(withTitle title: String = "") {
navigationItem.leftBarButtonItem = nil
navigationController?.view.snp.updateConstraints { make in
make.height.equalTo(UX.viewHeightForDoneState)
}
actionDoneRow.label.text = title
UIView.animate(withDuration: UX.doneDialogAnimationDuration) {
self.actionDoneRow.row.isHidden = false
self.stackView.arrangedSubviews
.filter { !self.viewsShownDuringDoneAnimation.contains($0) }
.forEach { $0.removeFromSuperview() }
self.navigationController?.view.superview?.layoutIfNeeded()
}
}
@objc func finish(afterDelay: TimeInterval = UX.durationToShowDoneDialog) {
delegate?.finish(afterDelay: afterDelay)
}
private func makeActionDoneRow(addTo parent: UIStackView) -> (row: UIStackView, label: UILabel) {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.addBackground(color: UX.doneLabelBackgroundColor)
stackView.rightLeftEdges(inset: UX.rowInset)
parent.addArrangedSubview(stackView)
stackView.snp.makeConstraints { make in
make.height.equalTo(UX.pageInfoRowHeight)
}
let label = UILabel()
label.font = UX.doneLabelFont
label.handleLongLabels()
let checkmark = UILabel()
checkmark.text = "✓"
checkmark.font = UIFont.boldSystemFont(ofSize: 22)
[label, checkmark].forEach {
stackView.addArrangedSubview($0)
$0.textColor = .white
}
checkmark.snp.makeConstraints { make in
make.width.equalTo(20)
}
return (stackView, label)
}
private func setupNavBar() {
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.setValue(true, forKey: "hidesShadow") // hide separator line
navigationItem.titleView = UIImageView(image: UIImage(named: "Icon-Small"))
navigationItem.titleView?.contentMode = .scaleAspectFit
navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.SendToCancelButton, style: .plain, target: self, action: #selector(finish))
}
private func setupStackView() {
stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 4
view.addSubview(stackView)
stackView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
}
extension ShareViewController {
@objc func actionLoadInBackground(gesture: UIGestureRecognizer) {
// To avoid re-rentry deom double tap, each action function disables the gesture
gesture.isEnabled = false
animateToActionDoneView(withTitle: Strings.ShareLoadInBackgroundDone)
if let shareItem = shareItem {
let profile = BrowserProfile(localName: "profile")
profile.queue.addToQueue(shareItem).uponQueue(.main) { _ in
profile.shutdown()
}
}
finish()
}
@objc func actionBookmarkThisPage(gesture: UIGestureRecognizer) {
gesture.isEnabled = false
animateToActionDoneView(withTitle: Strings.ShareBookmarkThisPageDone)
if let shareItem = shareItem {
let profile = BrowserProfile(localName: "profile")
_ = profile.bookmarks.shareItem(shareItem).value // Blocks until database has settled
profile.shutdown()
}
finish()
}
@objc func actionAddToReadingList(gesture: UIGestureRecognizer) {
gesture.isEnabled = false
animateToActionDoneView(withTitle: Strings.ShareAddToReadingListDone)
if let shareItem = shareItem {
let profile = BrowserProfile(localName: "profile")
profile.readingList.createRecordWithURL(shareItem.url, title: shareItem.title ?? "", addedBy: UIDevice.current.name)
profile.shutdown()
}
finish()
}
@objc func actionSendToDevice(gesture: UIGestureRecognizer) {
gesture.isEnabled = false
sendToDevice = SendToDevice()
guard let sendToDevice = sendToDevice else { return }
sendToDevice.sharedItem = shareItem
sendToDevice.delegate = delegate
let vc = sendToDevice.initialViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
| mpl-2.0 | 7281952e079ecab5574fd1ed111274dd | 37.539216 | 173 | 0.674383 | 5.081 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/IBBSCommentViewController.swift | 1 | 4264 | //
// IBBSCommentViewController.swift
// iBBS
//
// Created by Augus on 9/16/15.
//
// http://iAugus.com
// https://github.com/iAugux
//
// Copyright © 2015 iAugus. All rights reserved.
//
import UIKit
protocol IBBSCommentViewControllerDelegate {
func refreshData()
}
class IBBSCommentViewController: IBBSEditorBaseViewController {
var post_id = Int()
var delegate: IBBSCommentViewControllerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(cancelAction))
navigationController?.navigationBar.translucent = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
executeAfterDelay(0.3) {
self.focusTextEditor()
}
}
@objc private func cancelAction() {
if getHTML().ausTrimHtmlInWhitespaceAndNewlineCharacterSet().isEmpty {
blurTextEditor()
dismissViewControllerAnimated(true , completion: nil)
} else {
let alert = UIAlertController(title: "", message: ARE_YOU_SURE_TO_GIVE_UP, preferredStyle: .Alert)
let continueAction = UIAlertAction(title: BUTTON_CONTINUE, style: .Default, handler: { _ in
self.focusTextEditor()
})
let cancelAction = UIAlertAction(title: BUTTON_GIVE_UP, style: .Cancel, handler: { _ in
self.blurTextEditor()
self.dismissViewControllerAnimated(true , completion: nil)
})
alert.addAction(continueAction)
alert.addAction(cancelAction)
executeAfterDelay(0.5, completion: {
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
override func sendAction() {
super.sendAction()
navigationItem.rightBarButtonItem?.action = nil
let resetActionIfFailed = {
self.navigationItem.rightBarButtonItem?.action = #selector(self.sendAction)
}
blurTextEditor()
if getHTML().ausTrimHtmlInWhitespaceAndNewlineCharacterSet().isEmpty {
configureAlertController()
return
}
let content = getHTML()
let key = IBBSLoginKey()
guard key.isValid else {
IBBSContext.login(completion: {
self.sendAction()
})
return
}
APIClient.defaultClient.comment(key.uid, postID: post_id, content: content, token: key.token, success: { (json) -> Void in
let model = IBBSModel(json: json)
if model.success { //comment successfully
IBBSToast.make(model.message, interval: TIME_OF_TOAST_OF_COMMENT_SUCCESS)
self.dismissViewControllerAnimated(true , completion: {
self.delegate?.refreshData()
})
} else {
IBBSToast.make(model.message, interval: TIME_OF_TOAST_OF_COMMENT_FAILED)
resetActionIfFailed()
executeAfterDelay(0.5, completion: {
self.focusTextEditor()
})
}
}) { (error ) -> Void in
DEBUGLog(error)
resetActionIfFailed()
IBBSToast.make(SERVER_ERROR, interval: TIME_OF_TOAST_OF_SERVER_ERROR)
}
}
private func configureAlertController() {
let alertController = UIAlertController(title: "", message: YOU_HAVENOT_WROTE_ANYTHING, preferredStyle: .Alert)
let action = UIAlertAction(title: GOT_IT, style: .Cancel) { (_) -> Void in
self.focusTextEditor()
}
alertController.addAction(action)
presentViewController(alertController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 748a1419dad18a38c878c69193190c63 | 30.345588 | 135 | 0.574478 | 5.136145 | false | false | false | false |
vapor/node | Sources/Node/Convertibles/UnsignedInteger+Convertible.swift | 1 | 794 | extension UInt: NodeConvertible {}
extension UInt8: NodeConvertible {}
extension UInt16: NodeConvertible {}
extension UInt32: NodeConvertible {}
extension UInt64: NodeConvertible {}
extension UnsignedInteger {
public init(node: Node) throws {
guard let int = node.uint else {
throw NodeError.unableToConvert(input: node, expectation: "\(Self.self)", path: [])
}
#if swift(>=4)
self.init(UInt64(int))
#else
self.init(int.toUIntMax())
#endif
}
public func makeNode(in context: Context?) -> Node {
#if swift(>=4)
let max = UInt64(self)
#else
let max = self.toUIntMax()
#endif
let number = Node.Number(max)
return .number(number, in: context)
}
}
| mit | 004ef270a9c3531baf779d56577ba138 | 26.37931 | 95 | 0.594458 | 4.338798 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 2 - Robot Maze 2/Functions 1/Functions 1_Exercises.playground/Contents.swift | 1 | 3913 | //: ## Functions 1 Exercises
//: In this these, 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) -> String {
return ("\(s1)" + " ❤️ " + "\(s2)")
}
emojiLove(s1: "Junior", s2: "Heather")
// 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"
//: ### 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 {
return [num1, num2, num3].sorted()[1]
}
// 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
/*:
### 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 if string.characters[string.startIndex] == "A" {
return true
} else if string.characters[string.startIndex] == "E" {
return true
} else if string.characters[string.startIndex] == "I" {
return true
} else if string.characters[string.startIndex] == "O" {
return true
} else if string.characters[string.startIndex] == "U" {
return true
} else if string.characters[string.startIndex] == "a" {
return true
} else if string.characters[string.startIndex] == "e" {
return true
} else if string.characters[string.startIndex] == "i" {
return true
} else if string.characters[string.startIndex] == "o" {
return true
} else if string.characters[string.startIndex] == "u" {
return true
} else {
return false
}
}
// Example Function Call
beginsWithVowel(string: "Apples") // true
beginsWithVowel(string: "pIG") // false
beginsWithVowel(string: "oink") // true
beginsWithVowel(string: "udacity") // true
beginsWithVowel(string: "") // false
/*:
### 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 is lowercased if it begins with a consonant.
To uppercase a `String`, use `string.uppercased()`. To lowercase a `String`, use `string.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) == true {
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: "") // ""
| mit | 7a77df00ba50b128bbb926869db519a6 | 33.723214 | 224 | 0.664952 | 3.43248 | false | false | false | false |
rajeejones/SavingPennies | Saving Pennies/Level.swift | 1 | 2540 | //
// Level.swift
// Saving Pennies
//
// Created by Rajeé Jones on 7/26/16.
// Copyright © 2016 Rajee Jones. All rights reserved.
//
import Foundation
let NumColumns = 7
let NumRows = 7
let NumLevels = 4
struct Expenses {
var description: String
var amount: Int
var paid: Bool
init(withExpense:String, value:Int) {
description = withExpense
amount = value
paid = false
}
}
enum InsuranceType {
case life, health, property
}
enum Powerup {
case plus2Moves, plus5Moves, plus10Moves, gain, loss
}
struct Insurance {
var type:InsuranceType!
var description:String
var power:Powerup
}
struct Investment {
}
struct Credit {
}
class Level {
/**
The amount of money to carry on to next level
*/
var savingsAmount = 0
/**
If you lose money by a coin, the amount is first subtracted from this amount
*/
var emergencySavingsAmount = 0
/**
Add moves based on the insurance type when movesleft = 0
*/
var insurance:Insurance?
/**
Money that can be invested
*/
var investment:Investment?
/**
Adds money to bank, but also adds expense until paid off with interest
*/
var credit:Credit?
var levelNumber = 0
var movesLeft = 0
var expenses: [Expenses] = [Expenses]()
var targetScore = 0
var coins: Array2D<Coin> = Array2D<Coin>(columns: NumColumns, rows: NumRows)
var tiles: Array2D<Tile> = Array2D<Tile>(columns: NumColumns, rows: NumRows)
public var possibleSwaps = Set<Swap>()
init(filename: String) {
guard let dictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename) else { return }
guard let tilesArray = dictionary["tiles"] as? [[Int]] else { return }
for (row, rowArray) in tilesArray.enumerated() {
let tileRow = NumRows - row - 1
for (column, value) in rowArray.enumerated() {
if value == 1 {
tiles[column, tileRow] = Tile()
}
}
}
targetScore = dictionary["targetScore"] as! Int
movesLeft = dictionary["moves"] as! Int
let tempExpense = dictionary["expenses"] as! Array<Dictionary<String, AnyObject>>
for item in tempExpense {
expenses.append(Expenses(withExpense: item["description"] as! String, value: item["amount"] as! Int))
}
}
}
| gpl-3.0 | 79931ed376bd629997fcb919eabffe6a | 22.072727 | 113 | 0.591805 | 4.174342 | false | false | false | false |
KenanAtmaca/iOS-11-Examples | DragDrop/DragDropView.swift | 1 | 3317 | //
//
// Copyright © 2017 Kenan Atmaca. All rights reserved.
// kenanatmaca.com
//
//
import UIKit
@available(iOS 11.0, *)
class mainVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addInteraction(UIDropInteraction(delegate: self))
view.addInteraction(UIDragInteraction(delegate: self))
}
override var prefersStatusBarHidden: Bool {
return true
}
}//
@available(iOS 11.0 , *)
extension mainVC: UIDropInteractionDelegate{ // DROP
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
for dragItem in session.items {
dragItem.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { (item, error) in
if error != nil {
return
}
guard let img:UIImage = item as? UIImage else {
return
}
DispatchQueue.main.async {
let dragPoint = session.location(in: self.view)
let imgView = UIImageView()
imgView.isUserInteractionEnabled = true
imgView.image = img
imgView.frame.size = CGSize.init(width: img.size.width, height: img.size.height)
imgView.center = dragPoint
self.view.addSubview(imgView)
}
})
}
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: UIImage.self)
}
}
@available(iOS 11.0 , *)
extension mainVC: UIDragInteractionDelegate { // DRAG
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let touchPoint = session.location(in: self.view)
if let touchImageView = self.view.hitTest(touchPoint, with: nil) as? UIImageView {
let touchImage = touchImageView.image
let itemProv = NSItemProvider(object: touchImage!)
let dragItem = UIDragItem(itemProvider: itemProv)
dragItem.localObject = touchImageView
return [dragItem]
}
return []
}
func dragInteraction(_ interaction: UIDragInteraction, previewForLifting item: UIDragItem, session: UIDragSession) -> UITargetedDragPreview? {
return UITargetedDragPreview(view: (item.localObject as? UIView)!)
}
func dragInteraction(_ interaction: UIDragInteraction, willAnimateLiftWith animator: UIDragAnimating, session: UIDragSession) {
session.items.forEach { (item) in
if let tImageView = item.localObject as? UIView {
tImageView.removeFromSuperview()
}
}
}
func dragInteraction(_ interaction: UIDragInteraction, item: UIDragItem, willAnimateCancelWith animator: UIDragAnimating) {
self.view.addSubview(item.localObject as! UIView)
}
}
| mit | 1b52a7427b39194c941be726d58a02c8 | 33.185567 | 146 | 0.608866 | 5.101538 | false | false | false | false |
myandy/shi_ios | shishi/UI/Edit/PingzeView.swift | 1 | 3564 | //
// StoneView.swift
// shishi
//
// Created by andymao on 2017/4/15.
// Copyright © 2017年 andymao. All rights reserved.
//
import Foundation
import UIKit
public class PingzeView: UIView {
var currentShapeType: Int = 0
static let TYPE_PING = 1
static let TYPE_ZHONG = 2
static let TYPE_ZE = 3
static let TYPE_PING_YUN = 4
static let TYPE_ZE_YUN = 6
static let TYPE_PING_YUN_CAN = 7
static let TYPE_ZE_YUN_CAN = 9
static let COLOR_PING: UInt32 = 0x8e8e8e
static let COLOR_ZE: UInt32 = 0x666666
static let COLOR_ZE_YUN: UInt32 = 0xb03b28
static let COLOR_PING_YUN: UInt32 = 0x0070fb
static let COLOR_YUN_GREEN: UInt32 = 0x8dc63f
public init(frame: CGRect, shape: Int) {
super.init(frame: frame)
self.currentShapeType = shape
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ rect: CGRect) {
let center = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2.0);
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.beginPath()
ctx.setLineWidth(1)
let radius: CGFloat = 5.0
let endAngle: CGFloat = CGFloat(2 * Double.pi)
switch currentShapeType {
case PingzeView.TYPE_PING:
ctx.setStrokeColor(UIColor.init(hex6: PingzeView.COLOR_PING).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.strokePath()
case PingzeView.TYPE_ZHONG:
ctx.setStrokeColor(UIColor.init(hex6: PingzeView.COLOR_PING).cgColor)
ctx.addArc(center: center, radius: 3, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.strokePath()
ctx.beginPath()
ctx.setStrokeColor(UIColor.init(hex6: PingzeView.COLOR_PING).cgColor)
ctx.addArc(center: center, radius: 6, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.strokePath()
case PingzeView.TYPE_ZE:
ctx.setFillColor(UIColor.init(hex6: PingzeView.COLOR_ZE).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.fillPath()
case PingzeView.TYPE_PING_YUN:
ctx.setFillColor(UIColor.init(hex6: PingzeView.COLOR_PING_YUN).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.fillPath()
case PingzeView.TYPE_ZE_YUN:
ctx.setFillColor(UIColor.init(hex6: PingzeView.COLOR_ZE_YUN).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.fillPath()
case PingzeView.TYPE_PING_YUN_CAN:
ctx.setStrokeColor(UIColor.init(hex6: PingzeView.COLOR_YUN_GREEN).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.strokePath()
case PingzeView.TYPE_ZE_YUN_CAN:
ctx.setFillColor(UIColor.init(hex6: PingzeView.COLOR_YUN_GREEN).cgColor)
ctx.addArc(center: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
ctx.fillPath()
default: break
}
}
}
| apache-2.0 | 0444a59566704fb65184f6c9c485a38a | 32.914286 | 106 | 0.613311 | 3.870652 | false | false | false | false |
VitoNYang/VTAutoSlideView | VTAutoSlideViewDemo/UseInCodeViewController.swift | 1 | 2794 | //
// UseInCodeViewController.swift
// VTAutoSlideView
//
// Created by hao Mac Mini on 2017/2/8.
// Copyright © 2017年 Vito. All rights reserved.
//
import UIKit
import VTAutoSlideView
class UseInCodeViewController: UIViewController {
lazy var slideView: VTAutoSlideView = {
let slideView = VTAutoSlideView(direction: .vertical, dataSource: self)
return slideView
}()
lazy var imageList = {
// compactMap 不同于 map 的是, compactMap 会筛选非空元素
(1...4).compactMap { UIImage(named: "0\($0)") }
}()
override func viewDidLoad() {
super.viewDidLoad()
slideView.register(nib: UINib(nibName: "DisplayImageCell", bundle: nibBundle))
slideView.dataList = imageList
slideView.activated = false // 关闭自动轮播功能
view.addSubview(slideView)
slideView.translatesAutoresizingMaskIntoConstraints = false
// add constraints
NSLayoutConstraint.activate([
slideView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor),
slideView.topAnchor.constraint(equalTo: safeTopAnchor, constant: 20),
slideView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor),
slideView.heightAnchor.constraint(equalToConstant: view.bounds.height * 0.5)
])
}
}
extension UseInCodeViewController: VTAutoSlideViewDataSource {
func configuration(cell: UICollectionViewCell, for index: Int)
{
guard let cell = cell as? DisplayImageCell else {
return
}
cell.imageView.image = imageList[index]
}
}
extension UIViewController {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return view.safeAreaLayoutGuide.topAnchor
} else {
return topLayoutGuide.bottomAnchor
}
}
}
extension UIView {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.topAnchor
} else {
return self.topAnchor
}
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.bottomAnchor
} else {
return self.bottomAnchor
}
}
var safeLeadingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.leadingAnchor
} else {
return self.leadingAnchor
}
}
var safeTrailingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.trailingAnchor
} else {
return self.trailingAnchor
}
}
}
| mit | 4cb0fa654567474d2edae0a37e525cd4 | 27.65625 | 88 | 0.625954 | 4.974684 | false | false | false | false |
sean915213/SGYSwiftUtility | SGYSwiftUtility/Classes/CoreData/JSONValueTransformer.swift | 1 | 1129 | //
// JSONValueTransformer.swift
// SGYSwiftUtility
//
// Created by Sean G Young on 11/3/18.
//
import Foundation
public class JSONValueTransformer<T>: ValueTransformer where T: Codable {
override public class func transformedValueClass() -> AnyObject.Type {
return NSData.self
}
override public class func allowsReverseTransformation() -> Bool {
return true
}
// MARK: - Initialization
public init(encoder: JSONEncoder = JSONEncoder(), decoder: JSONDecoder = JSONDecoder()) {
self.encoder = encoder
self.decoder = decoder
}
// MARK: - Properties
private let encoder: JSONEncoder
private let decoder: JSONDecoder
// MARK: - Methods
override public func transformedValue(_ value: Any?) -> Any? {
guard let input = value as? T else { return nil }
return try? encoder.encode(input)
}
override public func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else { return nil }
return try? decoder.decode(T.self, from: data)
}
}
| mit | cbb19fc6f0ab24d1b1d7ec2d94c44ed0 | 25.255814 | 93 | 0.630647 | 4.763713 | false | false | false | false |
silt-lang/silt | Sources/Mantle/Substitution.swift | 1 | 13381 | /// Substitution.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Moho
import Basic
/// A substitution `σ: Δ → Γ` can be seen as a list of terms `Γ ⊢ vᵢ: Aᵢ`
/// with `Aᵢ` from `Δ`, that can be applied to a term `Δ ⊢ uᵢ: Bᵢ` yielding
/// `Γ ⊢ uᵢσ: Bᵢσ` by substituting each `vᵢ` for a variable in `uᵢ`.
public struct Substitution {
indirect enum Internal {
/// Identity substitution.
case id
/// Weakning substitution lifts to an extended context by the given amount.
case weaken(Int, Internal)
/// Strengthening substitution drops to a contracted context by the given
/// amount.
case strengthen(Int, Internal)
/// Extends the substitution with an instantiation.
case instantiate(TT, Internal)
/// Lifting substitution lifts the substitution under a given number
/// of binders.
case lift(Int, Internal)
}
let raw: Internal
/// Create the identity substitution.
public init() {
self.raw = .id
}
private init(raw: Internal) {
self.raw = raw
}
public var isIdentity: Bool {
switch self.raw {
case .id: return true
default: return false
}
}
public static func weaken(
_ i: Int, _ s: Substitution = .init()
) -> Substitution {
switch (i, s.raw) {
case (0, _): return s
case let (n, .weaken(m, rho)):
return Substitution(raw: .weaken(n + m, rho))
case let (n, .strengthen(m, rho)):
let level = n - m
if level == 0 {
return s
} else if level > 0 {
return Substitution(raw: .weaken(level, rho))
} else {
return Substitution(raw: .strengthen(level, rho))
}
default:
return Substitution(raw: .weaken(i, s.raw))
}
}
public static func strengthen(
_ i: Int, _ s: Substitution = .init()) -> Substitution {
switch (i, s.raw) {
case (0, _): return s
case let (n, .strengthen(m, rho)):
return Substitution(raw: .strengthen(n + m, rho))
case let (n, .weaken(m, rho)):
let level = n - m
if level == 0 {
return s
} else if level > 0 {
return Substitution(raw: .strengthen(level, rho))
} else {
return Substitution(raw: .weaken(level, rho))
}
default:
return Substitution(raw: .strengthen(i, s.raw))
}
}
public static func instantiate(
_ tt: TT, _ sub: Substitution = .init()) -> Substitution {
switch (tt, sub.raw) {
case let (.apply(.variable(v), es), .weaken(m, sigma)):
guard es.isEmpty && v.index + 1 == m else {
return Substitution(raw: .instantiate(tt, sub.raw))
}
return self.weaken(m - 1, self.lift(1, Substitution(raw: sigma)))
default:
return Substitution(raw: .instantiate(tt, sub.raw))
}
}
public static func lift(_ i: Int, _ sub: Substitution) -> Substitution {
assert(i >= 0, "Cannot lift by a negative amount")
switch (i, sub.raw) {
case (0, _): return sub
case (_, .id): return sub
case let (m, .lift(n, rho)): return Substitution(raw: .lift(n + m, rho))
default: return Substitution(raw: .lift(i, sub.raw))
}
}
enum BadStrengthen: Error {
case name(Name)
}
func lookup(
_ variable: Var, _ elim: (TT, [Elim<TT>]) -> TT
) -> Result<Term<TT>, BadStrengthen> {
func go(
_ rho: Substitution, _ i: UInt, _ elim: (TT, [Elim<TT>]) -> TT
) -> Result<Term<TT>, BadStrengthen> {
switch rho.raw {
case .id:
return .success(TT.apply(.variable(Var(variable.name, i)), []))
case let .weaken(n, .id):
let j = i + UInt(n)
return .success(TT.apply(.variable(Var(variable.name, j)), []))
case let .weaken(n, rho2):
let rec = go(Substitution(raw: rho2), i, elim)
guard case let .success(tm) = rec else {
return rec
}
guard let substTm = try? tm.applySubstitution(.weaken(n), elim) else {
return .failure(BadStrengthen.name(variable.name))
}
return .success(substTm)
case let .instantiate(u, rho2):
if i == 0 {
return .success(u)
}
return go(Substitution(raw: rho2), i-1, elim)
case let .strengthen(n, rho2):
if i >= UInt(n) {
return go(Substitution(raw: rho2), i - UInt(n), elim)
}
return .failure(BadStrengthen.name(variable.name))
case let .lift(n, rho2):
if i < n {
return .success(TT.apply(.variable(Var(variable.name, i)), []))
}
let rec = go(Substitution(raw: rho2), i - UInt(n), elim)
guard case let .success(tm) = rec else {
return rec
}
guard let substTm = try? tm.applySubstitution(.weaken(n), elim) else {
return .failure(BadStrengthen.name(variable.name))
}
return .success(substTm)
}
}
return go(self, variable.index, elim)
}
// FIXME: Stolen from Agda because I'm too lazy to figure it out myself.
func compose(_ rho2: Substitution) -> Substitution {
switch (self.raw, rho2.raw) {
case (_, .id): return self
case (.id, _): return rho2
case let (_, .strengthen(n, sgm)):
return .strengthen(n, self.compose(Substitution(raw: sgm)))
case let (_, .lift(n, _)) where n == 0:
fatalError()
case let (.instantiate(u, rho), .lift(n, sgm)):
let innerSub = Substitution(raw: rho)
.compose(.lift(n-1, Substitution(raw: sgm)))
return Substitution.instantiate(u, innerSub)
default:
fatalError("FIXME: Finish composition")
}
}
}
public protocol Substitutable {
func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) throws -> Self
}
extension Substitutable {
func forceApplySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) -> Self {
guard let substTm = try? self.applySubstitution(subst, elim) else {
fatalError()
}
return substTm
}
}
extension TypeChecker {
func forceInstantiate<A: Substitutable>(_ t: A, _ ts: [Term<TT>]) -> A {
guard let substTm = try? self.instantiate(t, ts) else {
fatalError()
}
return substTm
}
func instantiate<A: Substitutable>(_ t: A, _ ts: [Term<TT>]) throws -> A {
return try t.applySubstitution(ts.reduce(Substitution(), { acc, next in
return Substitution.instantiate(next, acc)
}), self.eliminate)
}
}
extension Contextual: Substitutable where T: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Contextual<T, A> {
return Contextual(telescope: try self.telescope.map {
return ($0.0, try $0.1.applySubstitution(subst, elim))
},
inside: self.inside)
}
}
extension Opened: Substitutable where T: Substitutable {
func forceApplySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) -> Opened<K, T> {
guard let substTm = try? self.applySubstitution(subst, elim) else {
fatalError()
}
return substTm
}
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Opened<K, T> {
return Opened(self.key, try self.args.map {
return try $0.applySubstitution(subst, elim)
})
}
}
public enum LookupError: Error {
case failed(Var)
}
extension TypeTheory: Substitutable where T == Expr {
func forceApplySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) -> TypeTheory<T> {
guard let substTm = try? self.applySubstitution(subst, elim) else {
fatalError()
}
return substTm
}
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> TypeTheory<T> {
guard !subst.isIdentity else {
return self
}
switch self {
case .type:
return .type
case .refl:
return .refl
case let .lambda(body):
return .lambda(try body.applySubstitution(.lift(1, subst), elim))
case let .pi(domain, codomain):
let substDomain = try domain.applySubstitution(subst, elim)
let substCodomain = try codomain.applySubstitution(.lift(1, subst), elim)
return .pi(substDomain, substCodomain)
case let .constructor(dataCon, args):
let substArgs = try args.map { try $0.applySubstitution(subst, elim) }
return .constructor(dataCon, substArgs)
case let .apply(head, elims):
let substElims = try elims.map { try $0.applySubstitution(subst, elim) }
switch head {
case let .variable(v):
guard case let .success(u) = subst.lookup(v, elim) else {
throw LookupError.failed(v)
}
return elim(u, substElims)
case let .definition(d):
let substDef = try d.applySubstitution(subst, elim)
return .apply(.definition(substDef), substElims)
case let .meta(mv):
return .apply(.meta(mv), substElims)
}
case let .equal(type, lhs, rhs):
let substType = try type.applySubstitution(subst, elim)
let substLHS = try lhs.applySubstitution(subst, elim)
let substRHS = try rhs.applySubstitution(subst, elim)
return .equal(substType, substLHS, substRHS)
}
}
}
extension Clause: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) throws -> Clause {
let substBody = try self.body?
.applySubstitution(.lift(self.boundCount, subst),
elim)
return Clause(patterns: self.patterns, body: substBody)
}
}
extension Elim: Substitutable where T: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT) throws -> Elim<T> {
switch self {
case let .project(p):
return .project(p)
case let .apply(t):
return .apply(try t.applySubstitution(subst, elim))
}
}
}
extension Instantiability: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Instantiability {
switch self {
case .open:
return self
case .invertible(let i):
return .invertible(try i.applySubstitution(subst, elim))
}
}
}
extension Instantiability.Invertibility: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Instantiability.Invertibility {
switch self {
case .notInvertible(let cs):
return .notInvertible(try cs.map {try $0.applySubstitution(subst, elim)})
case .invertible(let cs):
return .invertible(try cs.map {try $0.applySubstitution(subst, elim)})
}
}
}
extension Definition: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Definition {
switch self {
case let .constant(type, constant):
return .constant(try type.applySubstitution(subst, elim),
try constant.applySubstitution(subst, elim))
case let .dataConstructor(tyCon, args, dataConType):
return .dataConstructor(tyCon, args,
try dataConType.applySubstitution(subst, elim))
case let .module(mod):
return .module(Module(telescope: try mod.telescope.map {
return ($0.0, try $0.1.applySubstitution(subst, elim))
},
inside: mod.inside))
case let .projection(proj, tyName, ctxTy):
return .projection(proj, tyName, try ctxTy.applySubstitution(subst, elim))
}
}
}
extension Definition.Constant: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> Definition.Constant {
switch self {
case .function(let inst):
return .function(try inst.applySubstitution(subst, elim))
default:
return self
}
}
}
extension OpenedDefinition: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> OpenedDefinition {
switch self {
case let .constant(type, constant):
return .constant(try type.applySubstitution(subst, elim),
try constant.applySubstitution(subst, elim))
case let .dataConstructor(tyCon, args, dataConType):
return .dataConstructor(tyCon, args,
try dataConType.applySubstitution(subst, elim))
case let .module(mod):
return .module(Module(telescope: try mod.telescope.map {
return ($0.0, try $0.1.applySubstitution(subst, elim))
},
inside: mod.inside))
case let .projection(proj, tyName, ctxTy):
return .projection(proj, tyName, try ctxTy.applySubstitution(subst, elim))
}
}
}
extension OpenedDefinition.Constant: Substitutable {
public func applySubstitution(
_ subst: Substitution, _ elim: (TT, [Elim<TT>]) -> TT
) throws -> OpenedDefinition.Constant {
switch self {
case .function(let i):
return .function(try i.applySubstitution(subst, elim))
default:
return self
}
}
}
| mit | 05b8e8cef0311dfce1f3839c85fb70fc | 30.77619 | 80 | 0.606549 | 3.625645 | false | false | false | false |
rabbitinspace/Tosoka | Tests/TosokaTests/JSON/Jay/StringParser.swift | 2 | 7279 | //
// StringParser.swift
// Jay
//
// Created by Honza Dvorsky on 2/17/16.
// Copyright © 2016 Honza Dvorsky. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
struct StringParser: JsonParser {
var parsing: Jay.ParsingOptions
func parse<R: Reader>(with reader: R) throws -> JSON {
try prepareForReading(with: reader)
//ensure we're starting with a quote
guard reader.curr() == Const.QuotationMark else {
throw JayError.unexpectedCharacter(reader)
}
try reader.nextAndCheckNotDone()
//if another quote, it's just an empty string
if reader.curr() == Const.QuotationMark {
try reader.nextAndCheckNotDone()
return .string("")
}
let str = try self.parseString(reader)
return .string(str)
}
func parseString<R: Reader>(_ reader: R) throws -> String {
var chars = String.UnicodeScalarView()
while true {
let curr = reader.curr()
switch curr {
case 0x00...0x1F:
//unescaped control chars, invalid
throw JayError.unescapedControlCharacterInString(reader)
case Const.QuotationMark:
//end of string, return what we have
try reader.nextAndCheckNotDone()
return String(chars)
case Const.Escape:
//something that needs escaping, delegate
let char = try self.unescapedCharacter(reader)
chars.append(char)
default:
//nothing special, just append a regular unicode character
let char = try self.readUnicodeCharacter(reader)
chars.append(char)
}
}
}
func readUnicodeCharacter<R: Reader>(_ reader: R) throws -> UnicodeScalar {
//we need to keep reading from the reader until either
//- result is returned, at which point we parsed a valid char
//- error is returned, at which point we throw
//- emptyInput is called, at which point we throw bc we unexpectatly
// ran out of characters
//since we read 8bit chars and the largest unicode char is 32bit,
//when we're parsing a long character, we'll be getting an error
//up until we reach 32 bits. if we get an error even then, it's an
//invalid character and throw.
var buffer: [JChar] = []
buffer.reserveCapacity(4)
while buffer.count < 4 {
let curr = reader.curr()
buffer.append(curr)
var gen = buffer.makeIterator()
var utf = UTF8()
switch utf.decode(&gen) {
case .scalarValue(let unicodeScalar):
try reader.nextAndCheckNotDone()
return unicodeScalar
case .emptyInput, .error:
//continue because we might be reading a longer char
try reader.nextAndCheckNotDone()
continue
}
}
//we ran out of parsing attempts and we've read 4 8bit chars, error out
throw JayError.unicodeCharacterParsing(buffer, reader)
}
func isValidUnicodeHexDigit(_ chars: [JChar]) -> Bool {
guard chars.count == 5 else { //uXXXX
return false
}
//ensure the five characters match this format
let validHexCode = chars
.dropFirst()
.map { Const.HexDigits.contains($0) }
.reduce(true, { $0 && $1 })
guard chars[0] == Const.UnicodeStart && validHexCode else { return false }
return true
}
func unescapedCharacter<R: Reader>(_ reader: R, expectingLowSurrogate: Bool = false) throws -> UnicodeScalar {
//this MUST start with escape
guard reader.curr() == Const.Escape else {
throw JayError.invalidEscape(reader)
}
try reader.nextAndCheckNotDone()
//first check for the set escapable chars
if Const.Escaped.contains(reader.curr()) {
let char: JChar
if let replacement = Const.EscapingRules[reader.curr()] {
//rule based, replace properly
char = replacement
} else {
//we encountered one of the simple escapable characters, just add it
char = reader.curr()
}
let uniScalar = UnicodeScalar(char)
try reader.nextAndCheckNotDone()
return uniScalar
}
//now the char must be 'u', otherwise this is invalid escaping
guard reader.curr() == Const.UnicodeStart else {
throw JayError.invalidEscape(reader)
}
//validate the current + next 4 digits (total of 5)
let unicode = try reader.readNext(5)
guard self.isValidUnicodeHexDigit(unicode) else {
throw JayError.invalidUnicodeSpecifier(reader)
}
let last4 = try Array(unicode.suffix(4)).string()
let value = self.fourBytesToUnicodeCode(last4)
//check for high/low surrogate pairs
if let complexScalarRet = try self.parseSurrogate(reader, value: value) {
return complexScalarRet
}
//nope, normal unicode char
guard let char = UnicodeScalar(value) else {
throw JayError.invalidUnicodeScalar(value)
}
return char
}
func fourBytesToUnicodeCode(_ last4: String) -> UInt16 {
return UInt16(strtoul("0x\(last4)", nil, 16))
}
//nil means no surrogate found, parse normally
func parseSurrogate<R: Reader>(_ reader: R, value: UInt16) throws -> UnicodeScalar? {
//no surrogate starting
guard UTF16.isLeadSurrogate(value) else { return nil }
//this MUST start with escape - the low surrogate
guard reader.curr() == Const.Escape else {
throw JayError.invalidEscape(reader)
}
try reader.nextAndCheckNotDone()
let high = value
//validate u + next 4 digits (total of 5)
let unicode = try reader.readNext(5)
guard self.isValidUnicodeHexDigit(unicode) else {
throw JayError.invalidUnicodeSpecifier(reader)
}
let last4 = try Array(unicode.suffix(4)).string()
let low = self.fourBytesToUnicodeCode(last4)
//must be a low, otherwise invalid
guard UTF16.isTrailSurrogate(low) else {
throw JayError.invalidSurrogatePair(high, low, reader)
}
//we have a high and a low surrogate, both as UTF-16
//append and parse them as such
let data = [high, low]
var utf = UTF16()
var gen = data.makeIterator()
switch utf.decode(&gen) {
case .scalarValue(let char):
return char
case .emptyInput, .error:
throw JayError.invalidSurrogatePair(high, low, reader)
}
}
}
| mit | 8a15c3804fbbd9b3660b5910d0b29f51 | 33.169014 | 114 | 0.56238 | 4.839096 | false | false | false | false |
Touchwonders/Transition | Transition/Classes/Helpers/UIViewControllerContextTransitioning+Properties.swift | 1 | 4566 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public extension UIViewControllerContextTransitioning {
/**
Identifies the view controller that is visible at the beginning of the transition
(and at the end of a canceled transition). This view controller is typically the
one presenting the "to” view controller or is the one being replaced by the "to”
view controller.
*/
var fromViewController: UIViewController! {
return self.viewController(forKey: .from)
}
/**
Identifies the view controller that is visible at the end of a completed transition.
This view controller is the one being presented.
*/
var toViewController: UIViewController! {
return self.viewController(forKey: .to)
}
/**
Identifies the view that is shown at the beginning of the transition (and at the end
of a canceled transition). This view is typically the presenting view controller’s view.
*/
var fromView: UIView! {
return self.view(forKey: .from) ?? fromViewController.view
}
/**
Identifies the view that is shown at the end of a completed transition. This view is
typically the presented view controller’s view but may also be an ancestor of that view.
*/
var toView: UIView! {
return self.view(forKey: .to) ?? toViewController.view
}
}
public extension UIViewControllerContextTransitioning {
/**
This installs the to and from view when necessary, based on the operation.
It returns the top-most view which is either the fromView or toView.
*/
@discardableResult func defaultViewSetup(for operation: TransitionOperation) -> UIView? {
switch operation {
case .navigation(let navigationOperation): return defaultViewSetup(for: navigationOperation)
case .modal(let modalOperation): return defaultViewSetup(for: modalOperation)
case .tabBar(let tabBarOperation): return defaultViewSetup(for: tabBarOperation)
default: return nil
}
}
func defaultViewSetup(for navigationOperation: UINavigationController.Operation) -> UIView? {
switch navigationOperation {
case .push:
containerView.addSubview(toView)
case .pop:
if toView.superview == nil {
containerView.insertSubview(toView, belowSubview: fromView)
}
default: return nil
}
toView.frame = finalFrame(for: toViewController)
return navigationOperation == .push ? toView : fromView
}
func defaultViewSetup(for modalOperation: UIViewControllerModalOperation) -> UIView? {
switch modalOperation {
case .present:
containerView.addSubview(toView)
case .dismiss:
if toView.superview == nil {
containerView.insertSubview(toView, belowSubview: fromView)
}
default: return nil
}
toView.frame = finalFrame(for: toViewController)
return modalOperation == .present ? toView : fromView
}
func defaultViewSetup(for tabBarOperation: UITabBarControllerOperation) -> UIView? {
guard tabBarOperation != .none else { return nil }
containerView.addSubview(toView)
toView.frame = finalFrame(for: toViewController)
return toView
}
}
| mit | eaaeedbc23edf22f377ae5e2df0e2df0 | 38.293103 | 101 | 0.67749 | 5.070078 | false | false | false | false |
customerly/Customerly-iOS-SDK | Pods/Socket.IO-Client-Swift/Source/SocketIO/Client/SocketIOClientConfiguration.swift | 6 | 4483 | //
// SocketIOClientConfiguration.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 8/13/16.
//
// 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.
/// An array-like type that holds `SocketIOClientOption`s
public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collection, MutableCollection {
// MARK: Typealiases
/// Type of element stored.
public typealias Element = SocketIOClientOption
/// Index type.
public typealias Index = Array<SocketIOClientOption>.Index
/// Iterator type.
public typealias Iterator = Array<SocketIOClientOption>.Iterator
/// SubSequence type.
public typealias SubSequence = Array<SocketIOClientOption>.SubSequence
// MARK: Properties
private var backingArray = [SocketIOClientOption]()
/// The start index of this collection.
public var startIndex: Index {
return backingArray.startIndex
}
/// The end index of this collection.
public var endIndex: Index {
return backingArray.endIndex
}
/// Whether this collection is empty.
public var isEmpty: Bool {
return backingArray.isEmpty
}
/// The number of elements stored in this collection.
public var count: Index.Stride {
return backingArray.count
}
/// The first element in this collection.
public var first: Element? {
return backingArray.first
}
public subscript(position: Index) -> Element {
get {
return backingArray[position]
}
set {
backingArray[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
return backingArray[bounds]
}
set {
backingArray[bounds] = newValue
}
}
// MARK: Initializers
/// Creates a new `SocketIOClientConfiguration` from an array literal.
///
/// - parameter arrayLiteral: The elements.
public init(arrayLiteral elements: Element...) {
backingArray = elements
}
// MARK: Methods
/// Creates an iterator for this collection.
///
/// - returns: An iterator over this collection.
public func makeIterator() -> Iterator {
return backingArray.makeIterator()
}
/// - returns: The index after index.
public func index(after i: Index) -> Index {
return backingArray.index(after: i)
}
/// Special method that inserts `element` into the collection, replacing any other instances of `element`.
///
/// - parameter element: The element to insert.
/// - parameter replacing: Whether to replace any occurrences of element to the new item. Default is `true`.
public mutating func insert(_ element: Element, replacing replace: Bool = true) {
for i in 0..<backingArray.count where backingArray[i] == element {
guard replace else { return }
backingArray[i] = element
return
}
backingArray.append(element)
}
}
/// Declares that a type can set configs from a `SocketIOClientConfiguration`.
public protocol ConfigSettable {
// MARK: Methods
/// Called when an `ConfigSettable` should set/update its configs from a given configuration.
///
/// - parameter config: The `SocketIOClientConfiguration` that should be used to set/update configs.
mutating func setConfigs(_ config: SocketIOClientConfiguration)
}
| apache-2.0 | dd3edfe1ef6e38637060c7b2b19bb990 | 31.485507 | 112 | 0.677894 | 4.846486 | false | true | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Extensions/Intents+Extensions.swift | 1 | 3458 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
import Intents
extension INIntent {
/// The donation shortcut interaction.
///
/// Converts `self` into appropriate intent and donates it as an interaction to
/// the system so that the intent can be suggested in the future or turned into
/// a voice shortcut for quickly running the task in the future.
var interaction: INInteraction {
INInteraction(intent: self, response: nil).apply {
guard let customIdentifier = customIdentifier else { return }
$0.identifier = customIdentifier
}
}
}
// MARK: - Identifiers
extension INIntent {
private enum AssociatedKey {
static var groupIdentifier = "groupIdentifier"
static var customIdentifier = "customIdentifier"
}
/// The unique group identifier of the intent.
///
/// The group identifier is used to match group of intents that can be deleted
/// if an intent is removed.
var groupIdentifier: String? {
get { associatedObject(&AssociatedKey.groupIdentifier) }
set { setAssociatedObject(&AssociatedKey.groupIdentifier, value: newValue) }
}
/// The unique custom identifier of the intent.
///
/// The custom identifier is used to match with the donation so the interaction
/// can be deleted if an intent is removed.
var customIdentifier: String? {
get { associatedObject(&AssociatedKey.customIdentifier) }
set { setAssociatedObject(&AssociatedKey.customIdentifier, value: newValue) }
}
}
// MARK: - Convenience
extension INCurrencyAmount {
/// Initializes a currency amount object with the specified values.
///
/// - Parameters:
/// - amount: The decimal number representing the amount of money.
/// - currencyCode: The ISO 4217 currency code to apply to the specified
/// amount. You can get a list of possible currency codes using the
/// `isoCurrencyCodes` method of `Locale`. For example, the string “USD”
/// corresponds to United States dollars.
public convenience init(amount: NSDecimalNumber, currencyCode: Locale.CurrencyCode = .usd) {
self.init(amount: amount, currencyCode: currencyCode.rawValue)
}
/// Initializes a currency amount object with the specified values.
///
/// - Parameters:
/// - amount: The decimal number representing the amount of money.
/// - currencyCode: The ISO 4217 currency code to apply to the specified
/// amount. You can get a list of possible currency codes using the
/// `isoCurrencyCodes` method of `Locale`. For example, the string “USD”
/// corresponds to United States dollars.
public convenience init(amount: FloatLiteralType, currencyCode: Locale.CurrencyCode = .usd) {
self.init(amount: NSDecimalNumber(value: amount), currencyCode: currencyCode)
}
}
extension INBalanceAmount {
/// Initializes a balance amount with a monetary amount.
///
/// - Parameters:
/// - amount: The monetary amount to assign to the balance.
/// - currencyCode: The ISO 4217 currency code that applies to the monetary
/// amount.
public convenience init(amount: Double, currencyCode: Locale.CurrencyCode = .usd) {
self.init(amount: NSDecimalNumber(decimal: Decimal(amount)), currencyCode: currencyCode.rawValue)
}
}
| mit | 6c41506fa76d3d830b66c88480b9f863 | 37.752809 | 105 | 0.680487 | 4.830532 | false | false | false | false |
VirgilSecurity/virgil-sdk-pfs-x | Source/Client/Models/Errors/PFSError.swift | 1 | 3014 | //
// PFSError.swift
// VirgilSDKPFS
//
// Created by Oleksandr Deundiak on 6/13/17.
// Copyright © 2017 VirgilSecurity. All rights reserved.
//
import Foundation
public let kVSPVirgilPFSServiceErrorDomain = "VSPVirgilPFSServiceErrorDomain"
struct PFSError {
let code: PfsServiceErrorCode?
var message: String {
guard let code = self.code else {
return "Unknown error"
}
let message: String
switch code {
case .serverInternal: message = "Internal server error. Please try again later."
case .accessToken: message = "The Virgil access token or token header was not specified or is invalid"
case .cardNotAvailable: message = "The Virgil Card is not available in this application"
case .invalidJson: message = "JSON specified as a request is invalid"
case .invalidSnapshot: message = "Request snapshot invalid"
case .duplicateCardFingerprint: message = "Virgil Card with the same fingerprint exists already"
case .signatureValidationFailed: message = "SCR sign validation failed (recipient)"
case .globalCardScopeForbidden: message = "Card scope should be application"
case .maximumOtcNumberExceeded: message = "Maximum number of OTCs 100"
case .exceededNumberOfItemsInRequest: message = "Exceeded number of items in request"
case .unsupportedPublicKeyType: message = "Unsupported public key type"
}
return message
}
fileprivate init(code: Int) {
guard let code = PfsServiceErrorCode(rawValue: code) else {
self.code = nil
return
}
self.code = code
}
var nsError: NSError {
let descr = self.message
return NSError(domain: kVSPVirgilPFSServiceErrorDomain, code: self.code?.rawValue ?? 0, userInfo: [NSLocalizedDescriptionKey: descr])
}
}
extension PFSError: Deserializable {
init?(dictionary: Any) {
guard let dictionary = dictionary as? [String: Any] else {
return nil
}
guard let code = dictionary["code"] as? NSNumber else {
return nil
}
self.init(code: code.intValue)
}
}
@objc(VSPPfsServiceErrorCode) public enum PfsServiceErrorCode: Int {
case serverInternal = 10000
case accessToken = 20300
case cardNotAvailable = 20500
case invalidJson = 30000
case invalidSnapshot = 30001
case duplicateCardFingerprint = 30138
case signatureValidationFailed = 30140
case globalCardScopeForbidden = 60000
case maximumOtcNumberExceeded = 60010
case exceededNumberOfItemsInRequest = 60011
case unsupportedPublicKeyType = 60100
}
extension PFSError: Error { }
| bsd-3-clause | 35df41afdcf37b2527b6277348758444 | 34.869048 | 141 | 0.615002 | 4.867528 | false | false | false | false |
JohnSundell/SwiftKit | Source/Shared/Position.swift | 1 | 7603 | import Foundation
import CoreGraphics
import Unbox
/// Structure acting as a namespace for types describing positions
public struct Position<T: Number> {
public typealias TwoDimensional = Position_2D<T>
public typealias ThreeDimensional = Position_3D<T>
}
/// Structure describing a two-dimensional position
public struct Position_2D<T: Number>: Hashable, StringConvertible, CustomStringConvertible, CustomDebugStringConvertible, EmptyInitializable {
public var hashValue: Int { return self.description.hashValue }
public var description: String { return "\(self.x):\(self.y)" }
public var debugDescription: String { return self.description }
public var x: T
public var y: T
/// Initialize a value, nil = 0
public init(x: T? = nil, y: T? = nil) {
self.x = x ?? T(0)
self.y = y ?? T(0)
}
/// Initialize an empty value
public init() {
self.init(x: nil, y: nil)
}
/// Return a new position by offsetting this position
public func positionOffsetByX(x: T, y: T) -> Position_2D<T> {
return Position_2D(x: (self.x + x) as T, y: (self.y + y) as T)
}
/// Return a new position by moving this position by 1 unit in a direction
public func positionInDirection<D: DirectionType>(direction: D, coordinateSystem: CoordinateSystem = .OriginUpperLeft) -> Position_2D<T> {
switch direction.toEightWayDirection() {
case .Up:
if coordinateSystem.incrementalVerticalDirection == .Up {
return Position_2D(x: self.x, y: (self.y + 1) as T)
} else {
return Position_2D(x: self.x, y: (self.y - 1) as T)
}
case .UpRight:
return self.positionInDirection(Direction.FourWay.Up).positionInDirection(Direction.FourWay.Right)
case .Right:
return Position_2D(x: (self.x + 1) as T, y: self.y)
case .RightDown:
return self.positionInDirection(Direction.FourWay.Right).positionInDirection(Direction.FourWay.Down)
case .Down:
if coordinateSystem.incrementalVerticalDirection == .Down {
return Position_2D(x: self.x, y: (self.y + 1) as T)
} else {
return Position_2D(x: self.x, y: (self.y - 1) as T)
}
case .DownLeft:
return self.positionInDirection(Direction.FourWay.Down).positionInDirection(Direction.FourWay.Left)
case .Left:
return Position_2D(x: (self.x - 1) as T, y: self.y)
case .LeftUp:
return self.positionInDirection(Direction.FourWay.Left).positionInDirection(Direction.FourWay.Up)
}
}
/// Return an array of postions that are within the radius of this position, optionally ignoring a set of positions
public func positionsWithinRadius(radius: Int, ignoredPositions: Set<Position_2D<T>> = [], includeSelf: Bool = false) -> [Position_2D<T>] {
var positions = [Position_2D<T>]()
self.forEachPositionWithinRadius(radius, ignoredPositions: ignoredPositions, includeSelf: includeSelf) {
positions.append($0)
}
return positions
}
/// Run a closure on each position within a certain radius of this position
public func forEachPositionWithinRadius(radius: Int, ignoredPositions: Set<Position_2D<T>> = [], includeSelf: Bool = false, closure: Position_2D<T> -> Void) {
let selfX = self.x.toInt()
let selfY = self.y.toInt()
for x in (selfX - radius) ... (selfX + radius) {
let yRange = radius - abs(selfX - x)
for deltaY in -yRange ... yRange {
let position = Position_2D(x: T(x), y: T(selfY + deltaY))
if !includeSelf && position == self {
continue
}
if ignoredPositions.contains(position) {
continue
}
closure(position)
}
}
}
/// Return the direction (out of 4 ways) that another position is considered to be in
public func directionToPosition(position: Position_2D<T>, coordinateSystem: CoordinateSystem = .OriginUpperLeft) -> Direction.FourWay? {
if self == position {
return nil
}
let selfX = self.x.toDouble()
let selfY = self.y.toDouble()
let positionX = position.x.toDouble()
let positionY = position.y.toDouble()
if abs(selfX - positionX) > abs(selfY - positionY) {
if positionX > selfX {
return .Right
} else {
return .Left
}
} else {
let incrementalDirection = coordinateSystem.incrementalVerticalDirection
if positionY > selfY {
return incrementalDirection
} else {
return incrementalDirection.oppositeDirection()
}
}
}
/// Conver this position into a CGPoint with equivalent x & y values
public func toCGPoint() -> CGPoint {
return CGPoint(x: CGFloat(self.x), y: CGFloat(self.y))
}
/// Convert this position into a CGPoint with a certain Position:CGPoint ratio
public func toCGPointWithRatio(ratio: CGFloat) -> CGPoint {
return CGPoint(x: CGFloat(self.x) * ratio, y: CGFloat(self.y) * ratio)
}
public func toString() -> String {
return self.description
}
}
/// Extension making 2D Positions usable as Unboxable keys
extension Position_2D: UnboxableKey {
public static func transformUnboxedKey(unboxedKey: String) -> Position_2D<T>? {
let parts = unboxedKey.componentsSeparatedByString(":")
guard let first = parts.first, last = parts.last where parts.count == 2 else {
return nil
}
guard let x = T(string: first), y = T(string: last) else {
return nil
}
return self.init(x: x, y: y)
}
}
/// Structure describing a three-dimensional position
public struct Position_3D<T: Number>: Hashable, EmptyInitializable {
public var hashValue: Int { return "\(self.x):\(self.y):\(self.z)".hashValue }
public var x: T
public var y: T
public var z: T
/// Initialize a value, nil = 0
public init(x: T? = nil, y: T? = nil, z: T? = nil) {
self.x = x ?? T(0)
self.y = y ?? T(0)
self.z = z ?? T(0)
}
/// Initialize an empty value
public init() {
self.init(x: nil, y: nil, z: nil)
}
}
/// Extension making 3D Positions usable as Unboxable keys
extension Position_3D: UnboxableKey {
public static func transformUnboxedKey(unboxedKey: String) -> Position_3D<T>? {
let parts = unboxedKey.componentsSeparatedByString(":")
guard let first = parts.first, middle = parts.valueAtIndex(1), last = parts.last where parts.count == 3 else {
return nil
}
guard let x = T(string: first), y = T(string: middle), z = T(string: last) else {
return nil
}
return self.init(x: x, y: y, z: z)
}
}
// Equatable support for Position_2D
public func ==<T: Number>(lhs: Position_2D<T>, rhs: Position_2D<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
// Equatable support for Position_3D
public func ==<T: Number>(lhs: Position_3D<T>, rhs: Position_3D<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | e0d001fb4c5b27eed929b971f9cbeac6 | 35.729469 | 162 | 0.590425 | 4.188981 | false | false | false | false |
edmw/Volumio_ios | Volumio/LastFMService.swift | 1 | 3141 | //
// LastFMService.swift
// Volumio
//
// Created by Federico Sintucci on 29/09/16.
// Copyright © 2016 Federico Sintucci. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
/**
Manager to get metadata and tracklist for an album from Last.fm webservice.
*/
class LastFMService {
static let shared = LastFMService()
private var queue: DispatchQueue!
init() {
queue = DispatchQueue(
label: "LastFMServiceQueue",
qos: .utility,
attributes: .concurrent
)
}
/**
Asynchronously requests an URL to the album image for the specified artist and the specified album from Last.fm webservice.
- Parameter artist: Name of the artist.
- Parameter album: Title of the album.
- Parameter completionHandler: Callback, which will be called with a cover image url on success or nil otherwise.
- Note: While Last.fm offers various sizes of the cover image, this method will only return the url to the cover image of size 'large'.
*/
func albumGetImageURL(artist: String, album: String, completion: @escaping (URL?) -> Void) {
let albumGetInfo = LastFMRequest.albumGetInfo(artist: artist, album: album)
Alamofire.request(albumGetInfo)
.validate()
.responseJSON(queue: queue) { (response) in
switch response.result {
case .success(let value):
let infoJSON = JSON(string: value as Any)
// find album image json for image of size 'large'
let imageJSON = infoJSON["album"]["image"].arrayValue.first(where: { (json) in
return json["size"] == "large"
})
// get url from album image json
var imageURL: URL? = nil
if let urlString = imageJSON?["#text"].string {
imageURL = URL(string: urlString)
}
completion(imageURL)
case .failure(_):
completion(nil)
}
}
}
}
/// Request router for Last.fm webservice.
enum LastFMRequest: URLRequestConvertible {
case albumGetInfo(artist: String, album: String)
static let baseURLString = "http://ws.audioscrobbler.com/2.0/"
static let apiKey = "6ebfdd6251d6554e578b03c642d93ada"
func asURLRequest() throws -> URLRequest {
let result: (path: String, parameters: Parameters) = {
switch self {
case let .albumGetInfo(artist, album):
return ("/", [
"method": "album.getinfo",
"artist": artist,
"album": album,
"format": "json",
"api_key": LastFMRequest.apiKey
])
}
}()
let url = try LastFMRequest.baseURLString.asURL()
let urlRequest = URLRequest(url: url.appendingPathComponent(result.path))
return try URLEncoding.default.encode(urlRequest, with: result.parameters)
}
}
| gpl-3.0 | d0ec06b05d3f939e3c8f81c8a7cee7fb | 32.404255 | 143 | 0.573567 | 4.686567 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Tests/EurofurenceKitTests/Model Ingestion/Deletions/DeleteTrackTests.swift | 1 | 1529 | import CoreData
@testable import EurofurenceKit
import EurofurenceWebAPI
import XCTest
class DeleteTrackTests: EurofurenceKitTestCase {
func testDeletingTrackRemovesEventsThatArePartOfTrack() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
let payload = try SampleResponse.ef26.loadResponse()
await scenario.stubSyncResponse(with: .success(payload))
try await scenario.updateLocalStore()
// Once the track has been deleted, any events that were part of the track should also be deleted.
let deletedTrackIdentifier = "f23cc7f6-34c1-48d5-8acb-0ec10c353403"
let eventIdentifiers = try autoreleasepool { () -> [String] in
let fetchRequest: NSFetchRequest<EurofurenceKit.Track> = EurofurenceKit.Track.fetchRequestForExistingEntity(
identifier: deletedTrackIdentifier
)
let results = try scenario.viewContext.fetch(fetchRequest)
let track = try XCTUnwrap(results.first)
return track.events.map(\.identifier)
}
let deleteTrackPayload = try SampleResponse.deletedTrack.loadResponse()
await scenario.stubSyncResponse(with: .success(deleteTrackPayload), for: payload.synchronizationToken)
try await scenario.updateLocalStore()
for eventIdentifier in eventIdentifiers {
XCTAssertThrowsError(try scenario.model.event(identifiedBy: eventIdentifier))
}
}
}
| mit | d6a5ef836b3d251f38b0898b0f74ecd6 | 41.472222 | 120 | 0.690647 | 5.272414 | false | true | false | false |
TONEY-XZW/douyu | ZW_Swift/Common/JQProgressHUD/JQProgressHUD.swift | 1 | 10590 | //
// JQProgressHUD.swift
// JQProgressHUD
//
// Created by HJQ on 2017/6/30.
// Copyright © 2017年 HJQ. All rights reserved.
//
import UIKit
fileprivate struct Action {
static let removeToastAction = #selector(JQProgressHUD.removeToast(t:))
}
public class JQProgressHUD: UIView {
// MARK: - property
// translucent mask
public var isNeedMask: Bool = false {
didSet {
if isNeedMask {
self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
}
if isNeedShowAnimation {
addAnimations(view: self)
}
}
}
public var duration: TimeInterval = 3.0 {
didSet {
if isNeedShowAnimation {
addAnimations(view: toastLabel)
}
addTimer(duration: duration)
}
}
public var containerViewBGcolor: UIColor? {
didSet {
containerView.backgroundColor = containerViewBGcolor
}
}
public var containerViewRadius: CGFloat? = 8.0 {
didSet {
containerView.layer.cornerRadius = containerViewRadius!
}
}
public var containerViewSize: CGSize = CGSize.init(width: 65.0, height: 65.0) {
didSet {
containerView.frame = CGRect.init(x: 0, y: 0, width: containerViewSize.width, height: containerViewSize.height)
}
}
public var indicatorView: UIView! {
didSet {
for view in customIndicatorView.subviews {
view.removeFromSuperview()
}
indicatorViewSize = indicatorView.bounds.size
customIndicatorView.addSubview(indicatorView)
}
}
public var toastViewWidth: CGFloat = 0
public var isIndicatorViewLeft: Bool = false {
didSet {
}
}
private var indicatorViewSize: CGSize = CGSize.init(width: 30.0, height: 30) {
didSet {
customIndicatorView.frame = CGRect.init(x: 0, y: 0, width: indicatorViewSize.width, height: indicatorViewSize.height)
}
}
fileprivate var isNeedShowAnimation: Bool = false
fileprivate var timer: Timer?
fileprivate var pView: UIView?
fileprivate var isToast: Bool = false
override public init(frame: CGRect) {
super.init(frame: frame)
}
/// convenience constructor
convenience public init(view: UIView, isToast: Bool) {
self.init(frame: view.bounds)
self.isToast = isToast
self.toastViewWidth = bounds.size.width / 2.0
self.pView = view
commitInit()
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func layoutSubviews() {
super.layoutSubviews()
if isToast {
adjustToastLabelFrame()
}else {
containerView.frame = CGRect.init(x: 0, y: 0, width: containerViewSize.width, height: containerViewSize.height)
containerView.center = self.center
adjustIndicatorViewFrame()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
removeTimer()
//print("deinit")
}
// MARK: - private methods
private func addAnimations(view: UIView, duration: TimeInterval? = 0.3) {
view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
let alpha = view.alpha
view.alpha = 0.5
UIView.animate(withDuration: duration!, animations: {
view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
view.alpha = alpha
view.transform = CGAffineTransform.identity
})
}
private func addTimer(duration: TimeInterval) {
removeTimer()
timer = JQWeakTimerObject.scheduledTimerWithTimeInterval(duration, aTargat: self, aSelector: Action.removeToastAction, userInfo: pView!, repeats: false)
RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
}
fileprivate func removeTimer() {
guard let _ = timer else { return }
timer?.invalidate()
timer = nil
}
private func commitInit() {
registerForNotifications()
}
private func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector:#selector(statusBarOrientationDidChange(notification:)) , name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)
}
@objc private func statusBarOrientationDidChange(notification: NSNotification) {
guard let view = self.superview else { return }
frame = view.bounds
}
private func adjustIndicatorViewFrame() {
let textLength = detailLabel.text?.characters.count ?? 0
var customIndicatorViewX: CGFloat = 0
var customIndicatorViewY: CGFloat = 0
var detailLabelW: CGFloat = 0
var detailLabelX: CGFloat = 0
var detailLabelY: CGFloat = 0
let detailLabelH: CGFloat = 18.0
if textLength > 0 {
if isIndicatorViewLeft {
detailLabelW = (containerView.bounds.size.width - customIndicatorView.bounds.size.width - 13)
customIndicatorViewX = 5
customIndicatorViewY = (containerView.bounds.size.height - (customIndicatorView.frame.size.height)) / 2.0
detailLabelX = customIndicatorViewX + customIndicatorView.bounds.size.width + 3
detailLabelY = (containerView.bounds.size.height - detailLabelH) / 2.0
detailLabel.textAlignment = .left
}else {
customIndicatorViewX = (containerView.bounds.size.width - customIndicatorView.bounds.size.width) / 2.0
customIndicatorViewY = (containerView.bounds.size.height - (customIndicatorView.frame.size.height + detailLabelH)) / 2.0
detailLabelW = containerView.bounds.size.width
detailLabelY = customIndicatorView.frame.size.height + customIndicatorViewY + 3
detailLabelX = 0
}
customIndicatorView.frame.origin.x = customIndicatorViewX
customIndicatorView.frame.origin.y = customIndicatorViewY
detailLabel.frame = CGRect.init(x: detailLabelX, y: detailLabelY, width: detailLabelW, height: detailLabelH)
}else {
customIndicatorView.frame.origin.x = (containerView.bounds.size.width - customIndicatorView.bounds.size.width) / 2.0
customIndicatorView.frame.origin.y = (containerView.bounds.size.height - customIndicatorView.bounds.size.height) / 2.0
}
}
private func adjustToastLabelFrame() {
let textLength = toastLabel.text?.characters.count ?? 0
if textLength > 0 {
let height = (toastLabel.text?.jq_heightWithConstrainedWidth(width: toastViewWidth, font: toastLabel.font))! + 16.0
toastLabel.frame = CGRect.init(x: (self.bounds.size.width - toastViewWidth) / 2.0 , y: toastLabel.frame.origin.y == 0 ? (self.bounds.size.height - height) / 2.0 : toastLabel.frame.origin.y, width: toastViewWidth, height: height)
}
}
private func setupUI() {
self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
if isToast {
addSubview(toastLabel)
}else {
addSubview(containerView)
containerView.addSubview(customIndicatorView)
containerView.addSubview(detailLabel)
}
}
fileprivate var containerView: UIView = {
let containerView: UIView = UIView.init()
containerView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.9)
containerView.layer.masksToBounds = true
containerView.layer.cornerRadius = 8.0
return containerView
}()
fileprivate var customIndicatorView: UIView = {
let view: UIView = UIView.init()
view.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
return view
}()
public var toastLabel: JQProgressHUDLabel = {
let containerLabel: JQProgressHUDLabel = JQProgressHUDLabel.init()
containerLabel.textColor = UIColor.white
containerLabel.font = UIFont.systemFont(ofSize: 14)
containerLabel.numberOfLines = 0
containerLabel.layer.masksToBounds = true
containerLabel.layer.cornerRadius = 8.0
containerLabel.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.9)
containerLabel.textAlignment = .center
containerLabel.insets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
return containerLabel
}()
public var detailLabel: JQProgressHUDLabel = {
let label: JQProgressHUDLabel = JQProgressHUDLabel.init()
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 12)
label.numberOfLines = 1
label.textAlignment = .center
label.insets = UIEdgeInsets.init(top: 5, left: 5, bottom: 8, right: 5)
return label
}()
}
extension JQProgressHUD {
public class func showHUD(addTo view: UIView, animation: Bool? = false) -> JQProgressHUD {
_ = JQProgressHUD.hideHUD(fromView: view)
let hud = JQProgressHUD.init(view: view, isToast: false)
hud.isNeedShowAnimation = animation!
view.addSubview(hud)
return hud
}
public class func showToastHUD(addTo view: UIView, animation: Bool? = false) -> JQProgressHUD {
_ = JQProgressHUD.hideHUD(fromView: view)
let hud = JQProgressHUD.init(view: view, isToast: true)
view.addSubview(hud)
hud.isNeedShowAnimation = animation!
return hud
}
public class func hideHUD(fromView view: UIView ) -> Bool {
guard let hud:JQProgressHUD = JQProgressHUD.getHUD(fromView: view) else { return false}
hud.removeToast(t: nil)
return true
}
public class func getHUD(fromView view: UIView) -> JQProgressHUD? {
for subview in view.subviews where subview is JQProgressHUD {
return subview as? JQProgressHUD
}
return nil
}
@objc fileprivate func removeToast(t: Timer?) {
removeTimer()
guard let hud: JQProgressHUD = JQProgressHUD.getHUD(fromView: pView!) else { return }
hud.removeFromSuperview()
}
}
| mit | 8441b53ce9cb502d4168b3f57db06935 | 34.172757 | 240 | 0.6201 | 4.678303 | false | false | false | false |
loiclec/Apodimark | Sources/Apodimark/InlineParsing/DelimiterArray/ProcessMonospacedText.swift | 1 | 2998 | //
// ProcessMonospacedText.swift
// Apodimark
//
extension MarkdownParser {
/// Parse the monospaced text nodes contained in `delimiters` and append them to `nodes`
func processAllMonospacedText(_ delimiters: inout [Delimiter?], appendingTo nodes: inout [NonTextInline]) {
var start = delimiters.startIndex
while case let newStart? = processMonospacedText(&delimiters, indices: start ..< delimiters.endIndex, appendingTo: &nodes) {
start = newStart
}
}
/// Parse the first monospaced text node contained in `delimiters[indices]` and append them to `nodes`
/// - returns: the index of the first backtick delimiter found in `delimiters[indices]`, or `nil` if no monospaced text was found
func processMonospacedText(_ delimiters: inout [Delimiter?], indices: CountableRange<Int>, appendingTo nodes: inout [NonTextInline]) -> Int? {
guard let (openingDelIdx, openingDel, closingDelIdx, closingDel, level) = {
() -> (Int, Delimiter, Int, Delimiter, Int32)? in
var escaping: View.Index? = nil
for i in indices {
guard case let del? = delimiters[i] else {
escaping = nil
continue
}
switch del.kind {
case .escapingBackslash:
escaping = del.idx
case .code(let level):
defer { escaping = nil }
var level = level
if case view.index(before: del.idx)? = escaping {
level -= 1
view.formIndex(after: &delimiters[i]!.idx)
}
guard level > 0 else {
delimiters[i] = nil
break
}
guard let closingDelIdx = { () -> Int? in
for j in i+1 ..< indices.upperBound {
if case .code(level)? = delimiters[j]?.kind {
return j
}
}
return nil
}()
else {
delimiters[i] = nil
return nil
}
return (i, delimiters[i]!, closingDelIdx, delimiters[closingDelIdx]!, level)
default:
escaping = nil
}
}
return nil
}()
else {
return nil
}
for i in openingDelIdx ... closingDelIdx {
delimiters[i] = nil
}
nodes.append(.init(
kind: .code(level),
start: view.index(openingDel.idx, offsetBy: numericCast(-level)),
end: closingDel.idx
))
return closingDelIdx
}
}
| mit | 58f0cc8f932f009f55b804954f14f65a | 35.560976 | 146 | 0.464977 | 5.33452 | false | false | false | false |
NghiaTranUIT/Titan | Titan_macOS/Titan_macOS/PlaceholderCell.swift | 2 | 1079 | //
// PlaceholderCell.swift
// Titan_macOS
//
// Created by Nghia Tran on 4/20/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Cocoa
class PlaceholderCell: NSTableCellView {
//
// MARK: - OUTLET
@IBOutlet weak var placeholderTitleLbl: NSTextField!
@IBOutlet weak var loaderView: NSProgressIndicator!
//
// MARK: - View Cycle
override func prepareForReuse() {
super.prepareForReuse()
// Prepare
self.loaderView.stopAnimation(nil)
}
func configurePlaceholderCell(with title: String, isShowLoader: Bool) {
// Loader
if isShowLoader {
self.loaderView.isHidden = false
self.placeholderTitleLbl.isHidden = true
self.loaderView.startAnimation(nil)
}
else {
self.loaderView.isHidden = true
self.placeholderTitleLbl.isHidden = false
self.loaderView.stopAnimation(nil)
}
// Title
self.placeholderTitleLbl.stringValue = title
}
}
| mit | 6be2dad230693f28190bf575245c1e9c | 22.955556 | 75 | 0.601113 | 4.769912 | false | false | false | false |
akhilraj-rajkumar/swift-code-gen | example/Pods/ObjectMapper/Sources/Mapper.swift | 40 | 14719 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum MappingType {
case fromJSON
case toJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: BaseMappable> {
public var context: MapContext?
public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set.
public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){
self.context = context
self.shouldIncludeNilValues = shouldIncludeNilValues
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSONObject: Any?, toObject object: N) -> N {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSON: [String: Any], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSONObject: Any?) -> N? {
if let JSON = JSONObject as? [String: Any] {
return map(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSON: [String: Any]) -> N? {
let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable
if var object = klass.objectForMapping(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? Mappable.Type { // Check if object is Mappable
if var object = klass.init(map: map) as? N {
object.mapping(map: map)
return object
}
} else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable
do {
return try klass.init(map: map) as? N
} catch let error {
#if DEBUG
let exception: NSException
if let mapError = error as? MapError {
exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil)
} else {
exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil)
}
exception.raise()
#else
NSLog("\(error)")
#endif
}
} else {
// Ensure BaseMappable is not implemented directly
assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable")
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return [object]
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSONObject: Any?) -> [N]? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapArray(JSONArray: JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String: Any]]) -> [N] {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String: N]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return mapDictionary(JSONObject: parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?) -> [String: N]? {
if let JSON = JSONObject as? [String: [String: Any]] {
return mapDictionary(JSON: JSON)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? {
// map every value in dictionary to type N
let result = JSON.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] {
if let JSON = JSONObject as? [String : [String : Any]] {
return mapDictionary(JSON: JSON, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects
public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in JSON {
if let object = dictionary[key] {
_ = map(JSON: value, toObject: object)
} else {
mutableDictionary[key] = map(JSON: value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? {
if let JSON = JSONObject as? [String: [[String: Any]]] {
return mapDictionaryOfArrays(JSON: JSON)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = JSON.filterMap {
mapArray(JSONArray: $0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? {
if let JSONArray = JSONObject as? [[[String: Any]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
let array = mapArray(JSONArray: innerJSONArray)
objectArray.append(array)
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization
public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
return parsedJSON as? [String: Any]
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSONString: String) -> Any? {
let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let data = data {
let parsedJSON: Any?
do {
parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String, Any>
public func toJSON(_ object: N) -> [String: Any] {
var mutableObject = object
let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues)
mutableObject.mapping(map: map)
return map.JSON
}
///Maps an array of Objects to an array of JSON dictionaries [[String: Any]]
public func toJSONArray(_ array: [N]) -> [[String: Any]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? {
let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: String.Encoding.utf8)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? {
if JSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: Data?
do {
JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString)
if let objectArray = mapArray(JSONObject: parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(JSONObject: parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSONObject: Any?) -> Set<N>? {
if let JSONArray = JSONObject as? [[String: Any]] {
return mapSet(JSONArray: JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String: Any]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]]
public func toJSONSet(_ set: Set<N>) -> [[String: Any]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] {
var mapped = [K: V]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] {
var mapped = [K: [V]]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] {
var mapped = [Key: U]()
for (key, value) in self {
if let newValue = try f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
| apache-2.0 | 83a2c0271e12d8b98ae1d52e8d813c7b | 32.002242 | 145 | 0.697534 | 3.881593 | false | false | false | false |
leoneparise/iLog | iLogUI/TimelineDatasource.swift | 1 | 7301 | //
// LogEntryDatasource.swift
// StumpExample
//
// Created by Leone Parise Vieira da Silva on 06/05/17.
// Copyright © 2017 com.leoneparise. All rights reserved.
//
import UIKit
struct Change {
enum ChangeType { case add, update, sectionUpdate }
let indexPath:IndexPath
let createSection:Bool
let type:ChangeType
init(indexPath: IndexPath, type: ChangeType = .add, createSection: Bool = false) {
self.indexPath = indexPath
self.createSection = createSection
self.type = type
}
}
public class TimelineDatasource:NSObject {
static let cellIdentifier = "TimelineCell"
fileprivate var groups: [LogEntryGroup] = []
private(set) var offset:Int = 0
var didSet: (([LogEntry]) -> Void)?
var didInsert: (([Change]) -> Void)?
var didAppend: (([LogEntry]) -> Void)?
var configureCell: ((UITableViewCell, LogEntry, Bool) -> Void)?
var configureHeader: ((UIView, LogEntryGroup) -> Void)?
public func prepend(entries:[LogEntry]) {
guard entries.count > 0 else { return }
offset += entries.count
let changes = entries.flatMap(self.prepend)
didInsert?(changes)
}
public func append(entries:[LogEntry]) {
guard entries.count > 0 else { return }
offset += entries.count
let _ = entries.flatMap(self.append)
didAppend?(entries)
}
public func set(entries:[LogEntry]) {
groups = []
offset = entries.count
for entry in entries {
if let index = groups.index(of: LogEntryGroup(entry: entry)) {
groups[index].append(entry)
} else {
groups.append(LogEntryGroup(entry: entry))
}
}
didSet?(entries)
}
public func getEntry(for indexPath:IndexPath) -> LogEntry {
return groups[indexPath.section].entries[indexPath.row]
}
public func count(forSection section:Int) -> Int {
return groups[section].count
}
public var count: Int {
return groups.count
}
func getGroup(forSection section:Int) -> LogEntryGroup {
return groups[section]
}
// MARK: - Private
private func append(entry:LogEntry) -> [Change] {
if let section = groups.index(of: LogEntryGroup(entry: entry)) {
groups[section].append(entry)
let indexPath = IndexPath(row: groups[section].count - 1, section: section)
return [
Change(indexPath: indexPath),
Change(indexPath: lastIndexPath(from: indexPath), type: .update)
]
} else {
groups.append(LogEntryGroup(entry: entry))
let indexPath = IndexPath(row: 0, section: groups.count - 1)
return [
Change(indexPath: indexPath, createSection: true),
Change(indexPath: lastIndexPath(from: indexPath), type: .update)
]
}
}
private func prepend(entry:LogEntry) -> [Change] {
if let section = groups.index(of: LogEntryGroup(entry: entry)) {
groups[section].insert(entry, at: 0)
let indexPath = IndexPath(row: 0, section: section)
return [
Change(indexPath: indexPath)
]
} else {
groups.insert(LogEntryGroup(entry: entry), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
return [
Change(indexPath: indexPath, createSection: true),
Change(indexPath: nextIndexPath(from: indexPath), type: .sectionUpdate),
]
}
}
private func insert(entry:LogEntry) -> Change? {
let newGroup = LogEntryGroup(entry: entry)
var indexPath:IndexPath?
var createSession = false
func wasInserted() -> Bool { return indexPath != nil }
// Check if log entry belongs to a group
if let section = groups.index(of: newGroup) {
var group = groups[section]
// Check where the entry should fit inside the group
for row in 0..<group.count {
// Doesn't insert if entry was inserted before
if entry == group.entries[row] {
break
}
// Check if entry is newer
if entry > group.entries[row] {
group.insert(entry, at: row)
indexPath = IndexPath(row: row, section: section)
break
}
}
// If the entry was not inserted and append to the end
if !wasInserted() {
group.append(entry)
indexPath = IndexPath(row: group.count - 1, section: section)
}
}
// If it doesn't, create a new group and insert
else {
// Check where the group should be inserted
for section in 0..<groups.count {
if newGroup.timestamp > groups[section].timestamp {
groups.insert(newGroup, at: section)
indexPath = IndexPath(row: 0, section: section)
break
}
}
// If the group wast not inserted, append to the end
if !wasInserted() {
groups.append(newGroup)
indexPath = IndexPath(row: 0, section: groups.count - 1)
}
createSession = true
}
return wasInserted() ? Change(indexPath: indexPath!, createSection: createSession) : nil
}
private func lastIndexPath(from indexPath:IndexPath) -> IndexPath {
let (row, section) = (indexPath.row, indexPath.section)
let lastSection = row == 0 && section > 0 ? section - 1 : section
let lastRow = row > 0 ? row - 1 : count(forSection: lastSection) - 1
return IndexPath(row: lastRow, section: lastSection)
}
private func nextIndexPath(from indexPath:IndexPath) -> IndexPath {
let (row, section) = (indexPath.row, indexPath.section)
let nextRow = row < count(forSection: section) - 1 ? row + 1 : 0
let nextSection = section < count - 1 && nextRow == 0 ? section + 1 : section
return IndexPath(row: nextRow, section: nextSection)
}
}
extension TimelineDatasource: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.count(forSection: section)
}
public func numberOfSections(in tableView: UITableView) -> Int {
return self.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TimelineDatasource.cellIdentifier,
for: indexPath)
let isLast = (indexPath.section == count - 1) &&
(indexPath.row == count(forSection: indexPath.section) - 1)
self.configureCell?(cell, getEntry(for: indexPath), isLast)
return cell
}
}
| mit | 80985c735712ff8659b5d3e197b2e405 | 34.096154 | 107 | 0.562603 | 4.879679 | false | false | false | false |
michaelhayman/SeededNSURLSession | SeededNSURLSession/Classes/SeededURLSession.swift | 1 | 4687 | //
// SeededURLSession.swift
//
// Created by Michael Hayman on 2016-05-18.
let MappingFilename = "stubRules"
let MatchingURL = "matching_url"
let JSONFile = "json_file"
let StatusCode = "status_code"
let HTTPMethod = "http_method"
let InlineResponse = "inline_response"
@objc public class SeededURLSession: NSURLSession {
let jsonBundle: String!
public init(jsonBundle named: String) {
self.jsonBundle = named
}
public class func defaultSession(queue: NSOperationQueue = NSOperationQueue.mainQueue()) -> NSURLSession {
if UIStubber.isRunningAutomationTests() {
return UIStubber.stubAPICallsSession()
}
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: nil,
delegateQueue: queue)
return session
}
override public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask {
guard let url = request.URL else { return errorTask(request.URL, reason: "No URL specified", completionHandler: completionHandler) }
guard let bundle = retrieveBundle(bundleName: jsonBundle) else { return errorTask(url, reason: "No such bundle '\(jsonBundle)' found.", completionHandler: completionHandler) }
let mappings = retrieveMappingsForBundle(bundle: bundle)
let mapping = mappings?.filter({ (mapping) -> Bool in
let httpMethodMatch = request.HTTPMethod == mapping[HTTPMethod] as! String
let urlMatch = findMatch(path: mapping[MatchingURL], url: url.absoluteString)
return urlMatch && httpMethodMatch
}).first
if let mapping = mapping,
jsonFileName = mapping[JSONFile] as? String,
statusString = mapping[StatusCode] as? String,
statusCode = Int(statusString) {
var data: NSData?
if let path = bundle.pathForResource(jsonFileName, ofType: "json") {
data = NSData(contentsOfFile: path)
} else {
if let response = mapping[InlineResponse] as? String {
data = response.dataUsingEncoding(NSUTF8StringEncoding)
}
}
let task = SeededDataTask(url: url, completion: completionHandler)
if statusCode == 422 || statusCode == 500 {
let error = NSError(domain: NSURLErrorDomain, code: Int(CFNetworkErrors.CFURLErrorCannotLoadFromNetwork.rawValue), userInfo: nil)
task.nextError = error
}
let response = NSHTTPURLResponse(URL: url, statusCode: statusCode, HTTPVersion: nil, headerFields: nil)
task.data = data
task.nextResponse = response
return task
} else {
return errorTask(url, reason: "No mapping found.", completionHandler: completionHandler)
}
}
public func findMatch(path path: AnyObject?, url: String) -> Bool {
guard let regexPattern = path as? String else { return false }
let modifiedPattern = regexPattern.stringByAppendingString("$")
if let _ = url.rangeOfString(modifiedPattern, options: .RegularExpressionSearch) {
return true
}
return false
}
func retrieveBundle(bundleName bundleName: String) -> NSBundle? {
guard let bundlePath = NSBundle.mainBundle().pathForResource(bundleName, ofType: "bundle") else { return nil }
let bundle = NSBundle(path: bundlePath)
return bundle
}
func retrieveMappingsForBundle(bundle bundle: NSBundle) -> [NSDictionary]? {
guard let mappingFilePath = bundle.pathForResource(MappingFilename, ofType: "plist") else { return nil }
guard let mappings = NSArray(contentsOfFile: mappingFilePath) as? [NSDictionary] else { return nil }
return mappings
}
}
// MARK - Error cases
extension SeededURLSession {
func errorTask(url: NSURL?, reason: String, completionHandler: DataCompletion) -> SeededDataTask {
var assignedUrl: NSURL! = url == nil ? NSURL(string: "http://www.example.com/") : url
let task = SeededDataTask(url: assignedUrl, completion: completionHandler)
task.nextError = NSError(reason: reason)
return task
}
}
extension NSError {
convenience init(reason: String) {
let errorInfo = [
NSLocalizedDescriptionKey: reason,
NSLocalizedFailureReasonErrorKey: reason,
NSLocalizedRecoverySuggestionErrorKey: ""
]
self.init(domain: "SeededURLSession", code: 55, userInfo: errorInfo)
}
}
| mit | 789c994f4c371654ef8c7a87e62c93b0 | 38.058333 | 183 | 0.65415 | 4.996802 | false | false | false | false |
avito-tech/Marshroute | Example/NavigationDemo/VIPER/Banner/Presenter/BannerPresenter.swift | 1 | 1200 | import Foundation
final class BannerPresenter: BannerModuleInput {
// MARK: - Init
private let interactor: BannerInteractor
init(interactor: BannerInteractor) {
self.interactor = interactor
}
// MARK: - Weak properties
weak var view: BannerViewInput? {
didSet {
if oldValue !== view {
setupView()
}
}
}
// MARK: - Private
private func setupView() {
view?.onTap = { [weak self] in
self?.interactor.invalidateTimer()
self?.onBannerTap?()
}
view?.onTouchDown = { [weak self] in
self?.interactor.invalidateTimer()
}
view?.onTouchUpOutside = { [weak self] in
self?.onBannerTimeout?()
}
}
// MARK: - BannerModuleInput
func setTitle(_ title: String) {
view?.setTitle(title)
}
func setPresented() {
interactor.startTimer(
onTick: nil,
onFire: { [weak self] in
self?.onBannerTimeout?()
}
)
}
var onBannerTap: (() -> ())?
var onBannerTimeout: (() -> ())?
}
| mit | 79cea72bcbda9e90fb2b10167b94807b | 22.076923 | 49 | 0.499167 | 4.958678 | false | false | false | false |
tardieu/swift | validation-test/Driver/Dependencies/rdar25405605.swift | 16 | 2782 | // RUN: rm -rf %t && mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: cp %S/Inputs/rdar25405605/helper-1.swift %t/helper.swift
// RUN: touch -t 201401240005 %t/*.swift
// RUN: cd %t && %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-1 %s
// CHECK-1-NOT: warning
// CHECK-1: {{^{$}}
// CHECK-1: "kind": "began"
// CHECK-1: "name": "compile"
// CHECK-1: ".\/main.swift"
// CHECK-1: {{^}$}}
// CHECK-1: {{^{$}}
// CHECK-1: "kind": "began"
// CHECK-1: "name": "compile"
// CHECK-1: ".\/helper.swift"
// CHECK-1: {{^}$}}
// RUN: ls %t/ | %FileCheck -check-prefix=CHECK-LS %s
// CHECK-LS-DAG: main.o
// CHECK-LS-DAG: helper.o
// RUN: cd %t && %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-1-SKIPPED %s
// CHECK-1-SKIPPED-NOT: warning
// CHECK-1-SKIPPED: {{^{$}}
// CHECK-1-SKIPPED: "kind": "skipped"
// CHECK-1-SKIPPED: "name": "compile"
// CHECK-1-SKIPPED: ".\/main.swift"
// CHECK-1-SKIPPED: {{^}$}}
// CHECK-1-SKIPPED: {{^{$}}
// CHECK-1-SKIPPED: "kind": "skipped"
// CHECK-1-SKIPPED: "name": "compile"
// CHECK-1-SKIPPED: ".\/helper.swift"
// CHECK-1-SKIPPED: {{^}$}}
// RUN: cp %S/Inputs/rdar25405605/helper-2.swift %t/helper.swift
// RUN: touch -t 201401240006 %t/helper.swift
// RUN: cd %t && not %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-2 %s
// CHECK-2-NOT: warning
// CHECK-2: {{^{$}}
// CHECK-2: "kind": "began"
// CHECK-2: "name": "compile"
// CHECK-2: ".\/helper.swift"
// CHECK-2: {{^}$}}
// CHECK-2: {{^{$}}
// CHECK-2: "kind": "skipped"
// CHECK-2: "name": "compile"
// CHECK-2: ".\/main.swift"
// CHECK-2: {{^}$}}
// RUN: cp %S/Inputs/rdar25405605/helper-3.swift %t/helper.swift
// RUN: touch -t 201401240007 %t/helper.swift
// RUN: cd %t && not %target-build-swift -c -incremental -output-file-map %S/Inputs/rdar25405605/output.json -parse-as-library ./main.swift ./helper.swift -parseable-output -j1 -module-name main 2>&1 | %FileCheck -check-prefix=CHECK-3 %s
// CHECK-3-NOT: warning
// CHECK-3: {{^{$}}
// CHECK-3: "kind": "began"
// CHECK-3: "name": "compile"
// CHECK-3: ".\/helper.swift"
// CHECK-3: {{^}$}}
// CHECK-3: {{^{$}}
// CHECK-3: "kind": "began"
// CHECK-3: "name": "compile"
// CHECK-3: ".\/main.swift"
// CHECK-3: {{^}$}}
func foo(_ value: Foo) -> Bool {
switch value {
case .one: return true
case .two: return false
}
}
| apache-2.0 | 962fc61244d08f4181da9ee74766e289 | 33.345679 | 241 | 0.617901 | 2.798793 | false | false | false | false |
railsware/Sleipnir | Sleipnir/Spec/Internals/SharedExampleGroupSpec.swift | 1 | 2306 | //
// SharedExampleGroupSpec.swift
// Sleipnir
//
// Created by Artur Termenji on 7/30/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
var globalValue: AnyObject? = nil
class SharedExampleGroupSpec : SleipnirSpec {
var groupWithBeforeEach : () =
sharedExamplesFor("a describe context that contains a beforeEach in a shared example group") {
beforeEach {
globalValue = "Not Nil"
}
it("should run the shared beforeEach before specs inside the shared example group") {
expect(globalValue).toNot(beNil())
}
}
var groupWithContext : () =
sharedExamplesFor("a shared example group that receives a value in the context") {
(sharedContext : SharedContext) in
var value: String? = nil
beforeEach {
value = sharedContext()["value"] as? String
}
it("should receive the values set in the shared example context") {
expect(value).to(equal("Some String"))
}
}
var groupWithFailure : () = sharedExamplesFor("a shared example group that contains a failing spec") {
it("should fail with a sensible failure message") {
let failureMessage = "Expected <some> to equal <string>"
expectFailureWithMessage(failureMessage) {
expect("some").to(equal("string"))
}
}
}
var sharedExamplesSpec : () = describe("a describe block") {
beforeEach {
globalValue = nil
}
describe("that contains a beforeEach in a shared example group") {
itShouldBehaveLike("a describe context that contains a beforeEach in a shared example group")
it("should not run the shared beforeEach before specs outside the shared example group") {
expect(globalValue).to(beNil())
}
}
describe("that passes a value to the shared example context") {
itShouldBehaveLike("a shared example group that receives a value in the context", sharedContext: { ["value" : "Some String"] })
}
itShouldBehaveLike("a shared example group that contains a failing spec")
}
} | mit | 3ca4dfa7ab68a5a09493b464475b4467 | 31.957143 | 139 | 0.596704 | 5.002169 | false | false | false | false |
tsaievan/XYReadBook | XYReadBook/XYReadBook/Classes/Views/Profile/XYSettingController.swift | 1 | 2440 | //
// XYSettingController.swift
// XYReadBook
//
// Created by tsaievan on 2017/9/3.
// Copyright © 2017年 tsaievan. All rights reserved.
//
import UIKit
fileprivate let kSettingCellId = "kSettingCellId"
class XYSettingController: XYViewController {
lazy var tableView = UITableView()
var cellInfo = [[XYElement]]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
fileprivate func setupUI() {
if let info = XYProfileElementVM.settingElements() {
cellInfo = info
}
setupTableView()
}
fileprivate func setupTableView() {
tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
tableView.isPagingEnabled = false
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(XYSettingCell.self, forCellReuseIdentifier: kSettingCellId)
}
}
// MARK: - 数据源方法, 代理方法
extension XYSettingController: UITableViewDataSource, UITableViewDelegate{
///< 返回组数
func numberOfSections(in tableView: UITableView) -> Int {
return cellInfo.count
}
///< 返回行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellInfo[section].count
}
///< 返回cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:kSettingCellId , for: indexPath) as? XYSettingCell
let model = cellInfo[indexPath.section][indexPath.row]
if let cell = cell {
cell.model = model
cell.accViewName = model.accessViewName
return cell
}
return UITableViewCell()
}
///< 返回cell高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
///< 返回组尾高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
///< 返回组头高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.2
}
}
| mit | a397bf97a61b5208f12a93c81d08f1d4 | 28.222222 | 114 | 0.65188 | 4.93125 | false | false | false | false |
kumabook/MusicFav | MusicFav/ChannelLoader.swift | 1 | 7027 | //
// ChannelLoader.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 7/11/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import ReactiveSwift
import Result
import FeedlyKit
import YouTubeKit
class ChannelLoader {
enum State {
case `init`
case fetching
case normal
case error
}
enum Event {
case startLoading
case completeLoading
case failToLoad
}
var categories: [GuideCategory]
fileprivate var channelsOfCategory: [GuideCategory:[Channel]]
var offset = 0
var perPage = 5
var state: State
var signal: Signal<Event, NSError>
var observer: Signal<Event, NSError>.Observer
var subscriptions: [YouTubeKit.Subscription]
var channels: [Channel]
var searchResults: [Channel]
var channelsPageTokenOfCategory: [GuideCategory: String]
var categoriesPageToken: String?
var subscriptionPageToken: String?
var channelPageToken: String?
var searchPageToken: String?
var channelDisposableOfCategory: [GuideCategory: Disposable?]
var categoriesDisposable: Disposable?
var subscriptionDisposable: Disposable?
var searchDisposable: Disposable?
init() {
categories = []
channelsOfCategory = [:]
subscriptions = []
channels = []
searchResults = []
self.state = .init
let pipe = Signal<Event, NSError>.pipe()
signal = pipe.0
observer = pipe.1
categoriesPageToken = ""
subscriptionPageToken = ""
searchPageToken = ""
channelsPageTokenOfCategory = [:]
channelDisposableOfCategory = [:]
}
func clearSearch() {
searchResults = []
searchPageToken = ""
state = .normal
searchDisposable?.dispose()
}
func channelsOf(_ category: GuideCategory) -> [Channel]? {
return channelsOfCategory[category]
}
fileprivate func fetchNextGuideCategory() -> SignalProducer<Void, NSError> {
state = State.fetching
observer.send(value: .startLoading)
return YouTubeKit.APIClient.shared.fetchGuideCategories(regionCode: "JP", pageToken: categoriesPageToken).map {
self.categories.append(contentsOf: $0.items)
self.categoriesPageToken = $0.nextPageToken
for c in $0.items {
self.channelsOfCategory[c] = []
self.channelsPageTokenOfCategory[c] = ""
}
self.observer.send(value: .completeLoading)
self.state = State.normal
if self.categoriesPageToken == nil {
self.state = .normal
}
}
}
fileprivate func fetchNextChannels(_ category: GuideCategory) -> SignalProducer<Void, NSError> {
state = State.fetching
observer.send(value: .startLoading)
return YouTubeKit.APIClient.shared.fetchChannels(of: category, pageToken: channelsPageTokenOfCategory[category]).map {
self.channelsOfCategory[category]?.append(contentsOf: $0.items)
self.channelsPageTokenOfCategory[category] = $0.nextPageToken
self.observer.send(value: .completeLoading)
self.state = State.normal
}
}
fileprivate func fetchNextSubscriptions() -> SignalProducer<Void, NSError> {
state = State.fetching
observer.send(value: .startLoading)
return YouTubeKit.APIClient.shared.fetchSubscriptions(pageToken: subscriptionPageToken)
.map {
self.subscriptions.append(contentsOf: $0.items)
self.subscriptionPageToken = $0.nextPageToken
self.observer.send(value: .completeLoading)
self.state = State.normal
}.mapError { e in
self.observer.send(value: .failToLoad)
self.state = State.error
return e
}
}
fileprivate func searchNextChannels(_ query: String) -> SignalProducer<Void, NSError> {
state = State.fetching
observer.send(value: .startLoading)
return YouTubeKit.APIClient.shared.searchChannel(by: query, pageToken: searchPageToken)
.map {
self.searchResults.append(contentsOf: $0.items)
self.searchPageToken = $0.nextPageToken
self.observer.send(value: .completeLoading)
self.state = State.normal
}.mapError { e in
self.observer.send(value: .failToLoad)
self.state = State.error
return e
}
}
func needFetchCategories() -> Bool {
return categoriesPageToken != nil
}
func fetchCategories() {
if !needFetchCategories() { return }
switch state {
case .init: categoriesDisposable = fetchNextGuideCategory().start()
case .fetching: break
case .normal: categoriesDisposable = fetchNextGuideCategory().start()
case .error: categoriesDisposable = fetchNextGuideCategory().start()
}
}
func needFetchChannels(_ category: GuideCategory) -> Bool {
return channelsPageTokenOfCategory[category] != nil
}
func fetchChannels(_ category: GuideCategory) {
if !needFetchChannels(category) { return }
switch state {
case .init: channelDisposableOfCategory[category] = fetchNextChannels(category).start()
case .fetching: break
case .normal: channelDisposableOfCategory[category] = fetchNextChannels(category).start()
case .error: channelDisposableOfCategory[category] = fetchNextChannels(category).start()
}
}
func needFetchSubscriptions() -> Bool {
return subscriptionPageToken != nil
}
func fetchSubscriptions() {
if !needFetchSubscriptions() { return }
switch state {
case .init: subscriptionDisposable = fetchNextSubscriptions().start()
case .fetching: break
case .normal: subscriptionDisposable = fetchNextSubscriptions().start()
case .error: subscriptionDisposable = fetchNextSubscriptions().start()
}
}
func needFetchSearchResults() -> Bool {
return searchPageToken != nil
}
func searchChannels(_ query: String) {
if query.isEmpty || !needFetchSearchResults() { return }
switch state {
case .init: searchDisposable = searchNextChannels(query).start()
case .fetching: break
case .normal: searchDisposable = searchNextChannels(query).start()
case .error: searchDisposable = searchNextChannels(query).start()
}
}
}
| mit | aa1f456dbc15c90b4278ce9c140dd4f3 | 34.852041 | 126 | 0.595702 | 4.962571 | false | false | false | false |
piercifani/MemeKeyboard | MemeKeyboard/Model/PCCoreDataStack+Meme.swift | 1 | 2027 | //
// PCCoreDataStack+Meme.swift
// MemeKeyboard
//
// Created by Pierluigi Cifani on 14/6/14.
// Copyright (c) 2014 Voalte. All rights reserved.
//
import Foundation
let MemeEntityName :String = "Meme"
let MemeEntityFRCCache :String = "MemeEntityFRCCache"
typealias MemeCreationHandler = (meme: Meme?, error: NSError?) -> ()
extension PCCoreDataStack {
func memeEntityDescription (moc :NSManagedObjectContext?) -> NSEntityDescription{
var context = moc
if context == nil {
context = defaultContext()
}
let entityDescription = NSEntityDescription.entityForName(MemeEntityName, inManagedObjectContext: context)
return entityDescription
}
func memesFRC () -> NSFetchedResultsController! {
let mainContext = defaultContext()
let entityDescription = memeEntityDescription(nil)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
fetchRequest.fetchBatchSize = 20
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let memesFRC = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: mainContext, sectionNameKeyPath: nil, cacheName: MemeEntityFRCCache)
return memesFRC;
}
func createMeme (name :String, url :String, tags :Meme[], completionBlock: MemeCreationHandler) {
let operationBlock: (NSManagedObjectContext!) -> Void = {(moc: NSManagedObjectContext!) in
let createdMeme = Meme(entity: self.memeEntityDescription(moc), insertIntoManagedObjectContext: moc)
}
let completionBlock: (NSError!) -> Void = {(error : NSError!) in
//Handle error
}
performBackgroundCoreDataOperation(operationBlock as PCBackgroundCoreDataBlock, completionBlock as PCBackgroundCoreDataCompletionBlock)
}
}
| gpl-2.0 | 6e6a9a6dcc3ec12e98bea60403051fc4 | 32.229508 | 168 | 0.670449 | 5.478378 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/AlamofireCached/CSAlamofireCache.swift | 1 | 1365 | ////
//// Created by Rene Dohan on 1/1/20.
//// Copyright (c) 2020 Renetik. All rights reserved.
////
//
//import Foundation
//
//public struct CSAlamofireCache {
// public static var HTTPVersion = "HTTP/1.1"
// static var canUseCacheControl: Bool { !HTTPVersion.contains("1.0") }
// static let frameworkName = "RenetikAlamofireCache"
// static let refreshCacheKey = "refreshCache"
// static let refreshCacheValueRefresh = "refreshCache"
// static let refreshCacheValueUse = "useCache"
//}
//
//extension Dictionary where Key == String, Value == String {
// mutating func addCacheControlField(maxAge: TimeInterval, isPrivate: Bool) {
// //TODO check format of result string should be just number without punctuation
// var cacheValue = "max-age=\(maxAge)"
// if isPrivate { cacheValue += ",private" }
// self["Cache-Control"] = cacheValue
// }
//
// mutating func addCacheExpiresField(maxAge: TimeInterval) {
// let formatter = DateFormatter()
// formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss zzz"
// formatter.timeZone = TimeZone(identifier: "UTC")
// let date = formatter.date(from: self["Date"]!)!
// let expireDate = Date(timeInterval: maxAge, since: date)
// let cacheValue = formatter.string(from: expireDate)
// self["Expires"] = cacheValue
// }
//} | mit | bb3d96e2d55bc3ef18e6d2168d478846 | 39.176471 | 88 | 0.65348 | 3.877841 | false | false | false | false |
lacyrhoades/GLSlideshow | GLSlideshow/SlideshowController.swift | 1 | 2729 | //
// SlideshowController.swift
// GLSlideshow
//
// Created by Lacy Rhoades on 8/12/16.
// Copyright © 2016 Colordeaf. All rights reserved.
//
import GLKit
typealias TextureReadyBlock = ((texture: GLuint, size: CGSize)->())
typealias TextureRenderBlock = () -> ()
class SlideshowController: NSObject {
var context: EAGLContext
weak var renderDelegate: SlideshowRenderDelegate? {
didSet {
self.renderer.outputTextureReadyBlock = {
texture, size in
self.renderDelegate?.slideshowTextureIsReady(texture)
}
self.renderer.outputTextureRenderBlock = {
self.renderDelegate?.slideshowRenderFrameIsDone()
}
}
}
weak var dataSource: SlideshowDataSource?
var renderer = SlideshowRenderer()
init(context: EAGLContext) {
self.context = context
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
var time: NSTimeInterval = 0.0
func render() {
let newTime = NSDate.timeIntervalSinceReferenceDate()
self.renderer.update(newTime - time)
self.time = newTime
self.renderer.render()
}
func startSlideshow() {
self.renderer.bottomSlide = self.nextSlide()
self.performSelector(#selector(didTap), withObject: nil, afterDelay: 3.0)
}
func didTap() {
guard self.renderer.isAnimating == false else {
return
}
if let next = self.nextSlide() {
self.renderer.animateIn(next)
}
self.performSelector(#selector(didTap), withObject: nil, afterDelay: 3.0)
}
var textureCache: [Int: AnyObject] = [:]
func nextSlide() -> SlideModel? {
if let item = self.dataSource?.nextItem() {
let slide = SlideModel(image: item.image)
if let texture = self.textureCache[item.image.hash] as? GLKTextureInfo {
slide.texture = texture
} else {
do {
print("Good load")
EAGLContext.setCurrentContext(context)
slide.texture = try GLKTextureLoader.textureWithCGImage(item.image.CGImage!, options: nil)
self.textureCache[item.image.hash] = slide.texture
} catch {
print(error)
}
}
return slide
}
return nil
}
func updateOutputSize(width: GLsizei, height: GLsizei) {
self.renderer.setupGL(self.context, outputSize: OutputSize(width: width, height: height))
}
}
| mit | d515d3aa73e457ef2cdbb6d6f62129d4 | 27.416667 | 110 | 0.565982 | 4.811287 | false | false | false | false |
PureSwift/BluetoothLinux | Sources/BluetoothLinux/HCI/IOCTL/HCIDeviceList.swift | 1 | 3594 | //
// DeviceList.swift
//
//
// Created by Alsey Coleman Miller on 16/10/21.
//
import Bluetooth
import SystemPackage
import Socket
public extension HostControllerIO {
/// HCI Device List
struct DeviceList: IOControlValue {
@_alwaysEmitIntoClient
public static var id: HostControllerIO { .getDeviceList }
@usableFromInline
internal private(set) var bytes: CInterop.HCIDeviceList
@usableFromInline
internal init(_ bytes: CInterop.HCIDeviceList) {
self.bytes = bytes
}
public init(request count: Int = CInterop.HCIDeviceList.capacity) {
self.init(.request(count: numericCast(count)))
}
public mutating func withUnsafeMutablePointer<Result>(_ body: (UnsafeMutableRawPointer) throws -> (Result)) rethrows -> Result {
try Swift.withUnsafeMutableBytes(of: &bytes) { buffer in
try body(buffer.baseAddress!)
}
}
}
}
// MARK: - CustomStringConvertible
extension HostControllerIO.DeviceList: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _buildDescription()
}
public var debugDescription: String {
return description
}
}
// MARK: - RandomAccessCollection
extension HostControllerIO.DeviceList: RandomAccessCollection {
public func makeIterator() -> IndexingIterator<HostControllerIO.DeviceList> {
return IndexingIterator(_elements: self)
}
public subscript (index: Int) -> Element {
return Element(bytes[index])
}
public var count: Int {
return bytes.count
}
/// The start `Index`.
public var startIndex: Int {
return 0
}
/// The end `Index`.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
public var endIndex: Int {
return count
}
public func index(before i: Int) -> Int {
return i - 1
}
public func index(after i: Int) -> Int {
return i + 1
}
public subscript(bounds: Range<Int>) -> Slice<HostControllerIO.DeviceList> {
return Slice<HostControllerIO.DeviceList>(base: self, bounds: bounds)
}
}
// MARK: - Supporting Types
public extension HostControllerIO.DeviceList {
/// HCI Device
struct Element: Equatable, Hashable {
public let id: HostController.ID
public let options: HCIDeviceOptions
@usableFromInline
internal init(_ bytes: CInterop.HCIDeviceList.Element) {
self.id = .init(rawValue: bytes.id)
self.options = .init(rawValue: bytes.options)
}
}
}
// MARK: - File Descriptor
internal extension SocketDescriptor {
/// List all HCI devices.
@usableFromInline
func deviceList(count: Int = CInterop.HCIDeviceList.capacity) throws -> HostControllerIO.DeviceList {
var deviceList = HostControllerIO.DeviceList(request: count)
try inputOutput(&deviceList)
return deviceList
}
}
// MARK: - Host Controller
public extension HostController {
/// Get device information.
static func deviceList(count: Int = CInterop.HCIDeviceList.capacity) throws -> HostControllerIO.DeviceList {
let fileDescriptor = try SocketDescriptor.bluetooth(.hci, flags: [.closeOnExec])
return try fileDescriptor.closeAfter {
try fileDescriptor.deviceList(count: count)
}
}
}
| mit | f366c8aee535a7ab4642e933b211d061 | 25.233577 | 136 | 0.629382 | 4.943604 | false | false | false | false |
elationfoundation/Reporta-iOS | IWMF/ViewControllers/AppDelegate.swift | 1 | 36206 |
//
// AppDelegate.swift
// IWMF
//
// Appdelgate used for initialize SOS, Hangle Lock Screen, Set RootView, check device is Rooted or not, Fetch country list, check check-in status when app decome active.
//
//
import UIKit
enum ContactsFrom : Int
{
case Home = 1
case CheckIn = 2
case Alert = 3
case CreateAccount = 4
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITextFieldDelegate,SOSModalProtocol
{
var window: UIWindow?
var SOSButton : UIButton! //SOS
var SOSBGVIew : UIView! // SOS BAckground
var strLanguage : NSString! // Language Code For App
var tableBackground : UIColor! //Background Graycolor in app
//Flag for Update contact list
var isContactUpdated: Bool!
//Flag for display UI right to left
var isArabic: Bool!
//Flag for AppLock alert is open or not
var isUnlockAppAlertOpen : Bool!
//Dict for display false status of all ws.
var dictCommonResult : NSDictionary!
var dictSelectToUpdate : NSDictionary!
var dictSignUpCircle : NSMutableDictionary!
var arrCountryList : NSMutableArray!
var alertAppLock : UIAlertController!
var commonLocation : CommonLocation!
var contactScreensFrom : ContactsFrom!
var userSignUpDetail = User() // Use for Store Signup Detail and for Store User Profile
let isDeviceJailbroken : Bool = CommonUnit.isDeviceJailbroken()
var prefrence = AppPrefrences()
var headerCell : MapTableviewCell!
var isFromSOS : Bool!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
userSignUpDetail = User.sharedInstance
//Load App prefrences
if let pref = prefrence.getAppPrefrences()
{
prefrence = pref
}
//Check here device is Rooted or not? if true than we dont allow to use app
if isDeviceJailbroken == false {
//Store NYC location. If cant get current location than we use this. if get current location than update it from "CommonLocation.swift"
if prefrence.UsersLastKnownLocation.count == 0{
prefrence.UsersLastKnownLocation[Structures.Constant.Latitude] = NSNumber(double: Structures.AppKeys.DefaultLatitude)
prefrence.UsersLastKnownLocation[Structures.Constant.Longitude] = NSNumber(double: Structures.AppKeys.DefaultLongitude)
AppPrefrences.saveAppPrefrences(prefrence)
}
commonLocation = CommonLocation()
commonLocation.intializeLocationManager()
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
isContactUpdated = false
isArabic = false
isUnlockAppAlertOpen = false
dictSelectToUpdate = NSMutableDictionary()
dictCommonResult = NSDictionary()
dictSignUpCircle = NSMutableDictionary()
arrCountryList = NSMutableArray()
tableBackground = Utility.UIColorFromHex(0xEBEBEB, alpha: 1)
SVProgressHUD().hudBackgroundColor = UIColor.blackColor()
self.initializeSOSButton()
self.hideSOSButton()
//SetRootView
strLanguage = Structures.Constant.English
if prefrence.LanguageCode != nil
{
if prefrence.LanguageCode == Structures.Constant.Spanish
{
strLanguage = Structures.Constant.Spanish
}
else if prefrence.LanguageCode == Structures.Constant.Arabic
{
isArabic = true
strLanguage = Structures.Constant.Arabic
}
else if prefrence.LanguageCode == Structures.Constant.Turkish
{
strLanguage = Structures.Constant.Turkish
}
else if prefrence.LanguageCode == Structures.Constant.French
{
strLanguage = Structures.Constant.French
}
else if prefrence.LanguageCode == Structures.Constant.Hebrew
{
isArabic = true
strLanguage = Structures.Constant.Hebrew
}
else
{
strLanguage = Structures.Constant.English
}
}
else
{
strLanguage = Structures.Constant.English
}
Structures.Constant.languageBundle = CommonUnit.setLanguage(strLanguage as String)
setRootViewController()
//Common map declaration for reduce memory usage in app.
let arr : NSArray = NSBundle.mainBundle().loadNibNamed("MapTableviewCell", owner: self, options: nil)
headerCell = arr[0] as? MapTableviewCell
//Notification
if application.respondsToSelector("isRegisteredForRemoteNotifications")
{
// iOS 8 Notifications
let types: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound]
let settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )
application.registerUserNotificationSettings( settings )
application.registerForRemoteNotifications()
}
/* else
{
// iOS < 8 Notifications
application.registerForRemoteNotificationTypes([.Badge, .Sound, .Alert])
}*/
if let options = launchOptions
{
let lauchOpt = options as! Dictionary<String, AnyObject>
if let noti = lauchOpt["UIApplicationLaunchOptionsLocalNotificationKey"] as? UILocalNotification{
showCheckInNotificationScreen(noti.userInfo!)
}
if let noti = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
self.application(application, didReceiveRemoteNotification: noti as [NSObject : AnyObject])
}
}
}
else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.deviceRootedAlert()
})
}
return true
}
//Device is rooted than display this alert
func deviceRootedAlert(){
let alertController = UIAlertController(title: "Jailbreak Detected" , message: "Reporta cannot run on a jailbroken device", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
self.deviceRootedAlert()
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
})
}
//Set Root view if User selected language at first time
func setRootViewController(){
let isLoggedIn = prefrence.UserAlredyLoggedIn
let userStayLoggedIn = prefrence.userStayLoggedIn
if CheckIn.isAnyCheckInActive(){
if isLoggedIn.boolValue == true
{
if var _ : UINavigationController = self.window?.rootViewController as? UINavigationController
{
let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC")
self.window?.rootViewController? = homeNavController
}
}
else
{
setLoginScreen()
}
}
else{
if (userStayLoggedIn != nil && userStayLoggedIn == true)
{
if (isLoggedIn != nil)
{
if isLoggedIn.boolValue == true
{
if var _ : UINavigationController = self.window?.rootViewController as? UINavigationController
{
let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC")
self.window?.rootViewController? = homeNavController
}
}
else
{
setLoginScreen()
}
}
else
{
setLoginScreen()
}
}
else
{
setLoginScreen()
}
}
}
//Set Login Screen
func setLoginScreen(){
if prefrence.LanguageCode != nil
{
if prefrence.LanguageSelected == true
{
prefrence.UserAlredyLoggedIn = false
AppPrefrences.saveAppPrefrences(prefrence)
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController")
navigationController.viewControllers = [rootViewController]
self.window?.rootViewController = navigationController
}
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
if isDeviceJailbroken == false {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
prefrence.DeviceToken = tokenString
AppPrefrences.saveAppPrefrences(prefrence)
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
prefrence.DeviceToken = ""
AppPrefrences.saveAppPrefrences(prefrence)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if isDeviceJailbroken == false {
let isLoggedIn = prefrence.UserAlredyLoggedIn
if userInfo[Structures.Constant.Status] as! NSString == "unlockapp"
{
if (isLoggedIn != nil && isLoggedIn.boolValue == true){
Utility.removeAllPendingMedia()
var userDetail = User()
userDetail = userDetail.getLoggedInUser()!
userDetail.lockstatus = 0
User.saveUserObject(userDetail)
prefrence.ApplicationState = 0
AppPrefrences.saveAppPrefrences(prefrence)
self.isUnlockAppAlertOpen = false
self.SOSButton.userInteractionEnabled = true
if CheckIn.isAnyCheckInActive()
{
CheckIn.removeActiveCheckInObject()
}
if alertAppLock != nil {
alertAppLock.dismissViewControllerAnimated(true, completion: nil)
}
let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC")
self.window?.rootViewController? = homeNavController
}
}
else if userInfo[Structures.Constant.Status] as! NSString == "lockapp"
{
UIApplication.sharedApplication().cancelAllLocalNotifications()
if (isLoggedIn != nil && isLoggedIn.boolValue == true){
Utility.removeAllPendingMedia()
if isUnlockAppAlertOpen == false{
prefrence.ApplicationState = 1
AppPrefrences.saveAppPrefrences(prefrence)
var userDetail = User()
userDetail = userDetail.getLoggedInUser()!
userDetail.lockstatus = 1
User.saveUserObject(userDetail)
isFromSOS = false
showLockedAppAlert(isFromSOS)
}
}
}
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
{
if isDeviceJailbroken == false {
showCheckInNotificationScreen(notification.userInfo!)
}
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if isDeviceJailbroken == false {
showCheckInNotificationScreen(notification.userInfo!)
}
completionHandler()
}
func setUpLocalNotificationsReActive(action : NSString, body : NSString, fireDate : NSDate, userInfo : NSDictionary){
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = action as String
localNotification.alertBody = body as String
localNotification.fireDate = fireDate
localNotification.userInfo = userInfo as [NSObject : AnyObject]
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func setUpLocalNotifications(action : NSString, body : NSString, fireDate : NSDate){
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = action as String
localNotification.alertBody = body as String
localNotification.fireDate = fireDate
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//MARK:- CountryList Update
func countryListUpdate()
{
self.arrCountryList = NSMutableArray()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.arrCountryList = CommonUnit.GetCountryList(self.prefrence.LanguageCode as NSString as String).mutableCopy() as! NSMutableArray
let arrTemp : NSMutableArray = NSMutableArray(array: self.arrCountryList)
for (index, element) in arrTemp.enumerate()
{
if var innerDict = element.mutableCopy() as? Dictionary<String, AnyObject>
{
let strTitle = innerDict["Title"] as! String!
if strTitle.characters.count != 0
{
innerDict["RowHeight"] = CGFloat(46)
innerDict["CellIdentifier"] = "DetailTableViewCellIdentifier"
innerDict["IsSelected"] = Bool(0)
innerDict["Level"] = "Middle"
innerDict["Method"] = ""
innerDict["Type"] = Int(1)
innerDict["ConnectedID"] = Int(1)
self.arrCountryList.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
})
}
//MARK:- SOS Button Methods
func initializeSOSButton()
{
let SOSButtonImage = UIImage(named: "sos")
SOSButton = UIButton(type: UIButtonType.Custom)
SOSButton.setBackgroundImage(SOSButtonImage, forState: UIControlState.Normal)
let longPress = UILongPressGestureRecognizer(target: self, action: "SOSbtnTouched:")
SOSButton.addGestureRecognizer(longPress)
SOSButton.translatesAutoresizingMaskIntoConstraints = false
self.window?.addSubview(SOSButton)
self.window?.bringSubviewToFront(SOSButton)
if isUnlockAppAlertOpen == true{
self.SOSButton.userInteractionEnabled = false
}else{
self.SOSButton.userInteractionEnabled = true
}
let verticalSpaceFromBotton = NSLayoutConstraint(item: SOSButton, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.window, attribute: .BottomMargin, multiplier: 1, constant: -5)
self.window?.addConstraint(verticalSpaceFromBotton)
let trailingSpace = NSLayoutConstraint(item: SOSButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.window, attribute: .Trailing, multiplier: 1, constant: -5)
self.window?.addConstraint(trailingSpace)
let width = NSLayoutConstraint(item: SOSButton, attribute: .Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: UIScreen.mainScreen().bounds.size.width - 10)
self.window?.addConstraint(width)
let height = NSLayoutConstraint(item: SOSButton, attribute: .Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44)
self.window?.addConstraint(height)
}
func hideSOSButton()
{
SOSButton.hidden = true
}
func showSOSButton()
{
SOSButton.hidden = false
}
func SOSbtnTouched(gesture : UILongPressGestureRecognizer)
{
if isUnlockAppAlertOpen == true
{
return
}
if gesture.state == UIGestureRecognizerState.Ended
{
isUnlockAppAlertOpen = false
startLockingTheApp()
}
}
func startLockingTheApp()
{
SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("locking_reporta"),comment:"") , maskType: 4)
if !Utility.isConnectedToNetwork(){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
Utility.removeAllPendingMedia()
self.isFromSOS = true
self.showLockedAppAlert(self.isFromSOS)
CheckIn.removeActiveCheckInObject()
self.prefrence.ApplicationState = 1
AppPrefrences.saveAppPrefrences(self.prefrence)
return
})
}
let objSOS = SOS()
objSOS.sos()
SOS.sharedInstance.delegate = self
}
func showLockedAppAlert(isFromSOS : Bool)
{
let isLoggedIn = prefrence.UserAlredyLoggedIn
if (isLoggedIn != nil && isLoggedIn.boolValue == true){
if isUnlockAppAlertOpen == false{
isUnlockAppAlertOpen = true
self.SOSButton.userInteractionEnabled = false
alertAppLock = UIAlertController(title: NSLocalizedString(Utility.getKey("reporta"),comment:""), message:NSLocalizedString(Utility.getKey("app_locked"),comment:"") , preferredStyle: .Alert)
let okAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("login"),comment:""), style: .Default) { (_) in
self.showUnlockAppAlert(isFromSOS)
}
alertAppLock.addAction(okAction)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(self.alertAppLock, animated: true, completion: nil)
})
}
}
}
func showUnlockAppAlert(isFromSOS : Bool){
let objSOS = SOS.getCurrentSOSObject()
alertAppLock = UIAlertController(title: NSLocalizedString(Utility.getKey("unlock_reporta"),comment:"") , message: NSLocalizedString(Utility.getKey("app_unlocked"),comment:""), preferredStyle: .Alert)
alertAppLock.addTextFieldWithConfigurationHandler{(textField) in
textField.placeholder = NSLocalizedString(Utility.getKey("Enter Password"),comment:"")
textField.secureTextEntry = true
if self.isArabic == true{
textField.textAlignment = NSTextAlignment.Right
}else{
textField.textAlignment = NSTextAlignment.Left
}
}
alertAppLock.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = NSLocalizedString(Utility.getKey("enter_passcode"),comment:"")
textField.secureTextEntry = true
textField.keyboardType = UIKeyboardType.PhonePad
textField.delegate = self
if self.isArabic == true{
textField.textAlignment = NSTextAlignment.Right
}else{
textField.textAlignment = NSTextAlignment.Left
}
}
let okAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default) { (_) in
let tfPassword = self.alertAppLock.textFields![0]
let tfPasscode = self.alertAppLock.textFields![1]
if (tfPassword.text != nil && tfPasscode.text != nil) {
let password : String = tfPassword.text!
let passCode : String = tfPasscode.text!
if password.characters.count>0 && passCode.characters.count>0{
if !Utility.isConnectedToNetwork(){
self.isUnlockAppAlertOpen = false
self.showLockedAppAlert(isFromSOS)
return
}
self.isFromSOS = isFromSOS
SVProgressHUD.showWithStatus(NSLocalizedString(Utility.getKey("unlocking_reporta"),comment:""), maskType: 4)
objSOS.unlockSOS(password, passcode: passCode)
SOS.sharedInstance.delegate = self
}else{
self.showUnlockAppAlert(isFromSOS)
}
}
else{
self.showUnlockAppAlert(isFromSOS)
}
}
let cancelAction = UIAlertAction(title: NSLocalizedString(Utility.getKey("Cancel"),comment:""), style: .Default) { (_) in
self.isUnlockAppAlertOpen = false
self.showLockedAppAlert(isFromSOS)
}
alertAppLock.addAction(cancelAction)
alertAppLock.addAction(okAction)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(self.alertAppLock, animated: true, completion: nil)
})
}
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) {
//CheckIn.removeActiveCheckInObject()
// 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)
{
if isDeviceJailbroken == false {
let isLoggedIn = prefrence.UserAlredyLoggedIn
if (isLoggedIn != nil && isLoggedIn.boolValue == true)
{
application.applicationIconBadgeNumber = 0
if let activeState = prefrence.ApplicationState {
if activeState.integerValue == 1
{
if self.isUnlockAppAlertOpen == false
{
self.showLockedAppAlert(false)
}
}
}
self.changeCheckInStatus()
}
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.deviceRootedAlert()
})
}
// 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)
{
removeLoginUser()
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let strTemp : NSString = textField.text!
let strReplacing : NSString!
strReplacing = strTemp.stringByReplacingCharactersInRange(range, withString: string)
return strReplacing.length <= 6
}
//MARK:- Remove User Prefrence if Stay Login False
func removeLoginUser()
{
if !CheckIn.isAnyCheckInActive(){
let userStayLoggedIn = prefrence.userStayLoggedIn
if (userStayLoggedIn != nil && userStayLoggedIn == false){
prefrence.UserAlredyLoggedIn = false
SOS.removeActiveSOSObject()
SOS.setActiveSosID(NSNumber(integer: 0))
CheckIn.removeActiveCheckInObject()
User.removeActiveUser()
prefrence.ApplicationState = 0
AppPrefrences.saveAppPrefrences(prefrence)
}
}
}
//MARK:- changeCheckInStatus
func changeCheckInStatus()
{
let isLoggedIn = prefrence.UserAlredyLoggedIn
if CheckIn.isAnyCheckInActive()
{
let checkIn : CheckIn = CheckIn.getCurrentCheckInObject()
if (isLoggedIn != nil && isLoggedIn.boolValue == true)
{
if checkIn.status.rawValue == 5
{
Utility.removeAllPendingMedia()
UIApplication.sharedApplication().cancelAllLocalNotifications()
prefrence.ApplicationState = 1
AppPrefrences.saveAppPrefrences(prefrence)
if self.isUnlockAppAlertOpen == false
{
showMissedCheckInScreen()
}
return
}
let currentDate = NSDate()
let missedTim = NSDate(timeInterval: (checkIn.frequency.doubleValue + 1) * 60 , sinceDate: prefrence.laststatustime) //currentDate > missedTim
if currentDate.compare(missedTim) == NSComparisonResult.OrderedDescending
{
checkIn.status = .Missed
CheckIn.saveCurrentCheckInObject(checkIn)
Utility.removeAllPendingMedia()
UIApplication.sharedApplication().cancelAllLocalNotifications()
prefrence.ApplicationState = 1
AppPrefrences.saveAppPrefrences(prefrence)
if self.isUnlockAppAlertOpen == false
{
showMissedCheckInScreen()
}
return
}
//currentDate < checkIn.startTime
if currentDate.compare(checkIn.startTime) == NSComparisonResult.OrderedAscending
{
checkIn.status = .Pending
CheckIn.saveCurrentCheckInObject(checkIn)
}
else
{
if checkIn.status.rawValue > 1
{
if currentDate.compare(checkIn.endTime) == NSComparisonResult.OrderedDescending
{
Utility.removeAllPendingMedia()
checkIn.status = .Closed
CheckIn.removeActiveCheckInObject()
}
}
else
{
checkIn.status = .Started
CheckIn.saveCurrentCheckInObject(checkIn)
}
}
}
}
}
//MARK:- MissCheckinView
func showCheckInNotificationScreen(dictUserInfo : NSDictionary)
{
self.changeCheckInStatus()
let checkIn : CheckIn = CheckIn.getCurrentCheckInObject()
if checkIn.status.rawValue != 5
{
NSNotificationCenter.defaultCenter().postNotificationName("showCheckInNotification", object: dictUserInfo)
}
}
func showMissedCheckInScreen()
{
if isUnlockAppAlertOpen == false{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC")
self.window?.rootViewController? = homeNavController
self.showLockedAppAlert(false)
})
}
}
//MARK: - Core Data Helper
lazy var cdstore: CoreDataStore = {
let cdstore = CoreDataStore()
return cdstore
}()
lazy var cdh: CoreDataHelper = {
let cdh = CoreDataHelper()
return cdh
}()
func commonSOSResponse(wsType : WSRequestType, dict : NSDictionary, isSuccess : Bool)
{
if wsType == WSRequestType.LockSOS{
if isSuccess
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
Utility.removeAllPendingMedia()
})
self.showLockedAppAlert(true)
CheckIn.removeActiveCheckInObject()
self.prefrence.ApplicationState = 1
AppPrefrences.saveAppPrefrences(self.prefrence)
}
else
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
})
if (dict.valueForKey(Structures.Constant.Status) as! NSString) .isEqualToString("3"){
if dict.valueForKey(Structures.Constant.Message) != nil
{
let alertController = UIAlertController(title: dict.valueForKey(Structures.Constant.Message) as? String , message: "", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in
Utility.forceSignOut()
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
})
}
}else{
if dict.valueForKey(Structures.Constant.Message) != nil
{
let alert = UIAlertController(title: NSLocalizedString(Utility.getKey("reporta"),comment:""), message: dict.valueForKey(Structures.Constant.Message) as? String, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
})
}
}
}
}
if wsType == WSRequestType.UnlockSOS{
if isSuccess{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
self.isUnlockAppAlertOpen = false
self.initializeSOSButton()
CheckIn.removeActiveCheckInObject()
self.SOSButton.userInteractionEnabled = true
self.prefrence.ApplicationState = 0
AppPrefrences.saveAppPrefrences(self.prefrence)
let homeNavController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyContainerVC")
self.window?.rootViewController? = homeNavController
})
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss()
})
if (dict.valueForKey(Structures.Constant.Status) as! NSString) .isEqualToString("3"){
if dict.valueForKey(Structures.Constant.Message) != nil
{
let alertController = UIAlertController(title: dict.valueForKey(Structures.Constant.Message) as? String , message: "", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in
Utility.forceSignOut()
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
})
}
}else{
if dict.valueForKey(Structures.Constant.Message) != nil
{
self.alertAppLock = UIAlertController(title: NSLocalizedString(Utility.getKey("reporta"),comment:""), message: dict.valueForKey(Structures.Constant.Message) as? String, preferredStyle: UIAlertControllerStyle.Alert)
self.alertAppLock.addAction(UIAlertAction(title: NSLocalizedString(Utility.getKey("Ok"),comment:""), style: .Default, handler: { action in
self.showUnlockAppAlert(self.isFromSOS)
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.window?.rootViewController?.presentViewController(self.alertAppLock, animated: true, completion: nil)
})
}else{
self.isUnlockAppAlertOpen = false
self.showLockedAppAlert(isFromSOS)
}
}
}
}
}
}
| gpl-3.0 | 72d060f94cd16c6a7007dcaf5844f1e2 | 45.063613 | 286 | 0.582224 | 5.684723 | false | false | false | false |
WilliamHester/Breadit-iOS | Pods/Fuzi/Fuzi/Error.swift | 2 | 1979 | // Error.swift
// Copyright (c) 2015 Ce Zheng
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import libxml2
/**
* XMLError enumeration.
*/
public enum XMLError: ErrorType {
/// No error
case NoError
/// Contains a libxml2 error with error code and message
case LibXMLError(code: Int, message: String)
/// Failed to convert String to bytes using given string encoding
case InvalidData
/// XML Parser failed to parse the document
case ParserFailure
internal static func lastError(defaultError: XMLError = .NoError) -> XMLError {
let errorPtr = xmlGetLastError()
guard errorPtr != nil else {
return defaultError
}
let message = String.fromCString(errorPtr.memory.message)?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let code = Int(errorPtr.memory.code)
xmlResetError(errorPtr)
return .LibXMLError(code: code, message: message ?? "")
}
} | apache-2.0 | e1e44fce0075926e5461a3f2dc0e6cb2 | 40.25 | 145 | 0.750379 | 4.63466 | false | false | false | false |
jamesbond12/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Conversation/ConversationViewController.swift | 1 | 19769 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MobileCoreServices
class ConversationViewController: ConversationBaseViewController, UIDocumentMenuDelegate, UIDocumentPickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Data binder
private let binder: Binder = Binder()
// Internal state
// Members for autocomplete
var filteredMembers = [ACMentionFilterResult]()
// Views
private let titleView: UILabel = UILabel()
private let subtitleView: UILabel = UILabel()
private let navigationView: UIView = UIView()
private let avatarView = BarAvatarView(frameSize: 36, type: .Rounded)
private let backgroundView = UIImageView()
override init(peer: ACPeer) {
super.init(peer: peer);
// Background
backgroundView.contentMode = .ScaleAspectFill
backgroundView.clipsToBounds = true
backgroundView.backgroundColor = UIColor(
patternImage:UIImage(named: "bg_foggy_birds")!.tintBgImage(MainAppTheme.bubbles.chatBgTint))
// Custom background if available
if let bg = Actor.getSelectedWallpaper() {
if bg.startsWith("local:") {
backgroundView.image = UIImage(named: bg.skip(6))
}
}
view.insertSubview(backgroundView, atIndex: 0)
// Text Input
self.textInputbar.backgroundColor = MainAppTheme.chat.chatField
self.textInputbar.autoHideRightButton = false;
self.textView.placeholder = NSLocalizedString("ChatPlaceholder",comment: "Placeholder")
self.rightButton.setTitle(NSLocalizedString("ChatSend", comment: "Send"), forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendEnabled, forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendDisabled, forState: UIControlState.Disabled)
self.keyboardPanningEnabled = true
self.registerPrefixesForAutoCompletion(["@"])
self.textView.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
self.leftButton.setImage(UIImage(named: "conv_attach")!
.tintImage(MainAppTheme.chat.attachColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
forState: UIControlState.Normal)
// Navigation Title
navigationView.frame = CGRectMake(0, 0, 200, 44);
navigationView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
titleView.font = UIFont.mediumSystemFontOfSize(17)
titleView.adjustsFontSizeToFitWidth = false;
titleView.textColor = Resources.PrimaryLightText
titleView.textAlignment = NSTextAlignment.Center;
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
titleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
subtitleView.font = UIFont.systemFontOfSize(13);
subtitleView.adjustsFontSizeToFitWidth = true;
subtitleView.textColor = Resources.SecondaryLightText
subtitleView.textAlignment = NSTextAlignment.Center;
subtitleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
subtitleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
navigationView.addSubview(titleView)
navigationView.addSubview(subtitleView)
self.navigationItem.titleView = navigationView;
// Navigation Avatar
avatarView.frame = CGRectMake(0, 0, 36, 36)
let avatarTapGesture = UITapGestureRecognizer(target: self, action: "onAvatarTap");
avatarTapGesture.numberOfTapsRequired = 1
avatarTapGesture.numberOfTouchesRequired = 1
avatarView.addGestureRecognizer(avatarTapGesture)
let barItem = UIBarButtonItem(customView: avatarView)
self.navigationItem.rightBarButtonItem = barItem
}
required init(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
// Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.text = Actor.loadDraftWithPeer(peer)
// Installing bindings
if (UInt(peer.getPeerType().ordinal()) == ACPeerType.PRIVATE.rawValue) {
let user = Actor.getUserWithUid(peer.getPeerId())
let nameModel = user.getNameModel();
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(user.getNameModel().get(), id: user.getId(), avatar: value)
})
binder.bind(Actor.getTypingWithUid(peer.getPeerId())!, valueModel2: user.getPresenceModel()!, closure:{ (typing:JavaLangBoolean?, presence:ACUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = Actor.getFormatter().formatTyping();
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
let stateText = Actor.getFormatter().formatPresence(presence, withSex: user.getSex())
self.subtitleView.text = stateText;
let state = UInt(presence!.getState().ordinal())
if (state == ACUserPresence_State.ONLINE.rawValue) {
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
self.subtitleView.textColor = Resources.SecondaryLightText
}
}
})
} else if (UInt(peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue) {
let group = Actor.getGroupWithGid(peer.getPeerId())
let nameModel = group.getNameModel()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(group.getNameModel().get(), id: group.getId(), avatar: value)
})
binder.bind(Actor.getGroupTypingWithGid(group.getId())!, valueModel2: group.getMembersModel(), valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, members:JavaUtilHashSet?, onlineCount:JavaLangInteger?) -> () in
// if (!group.isMemberModel().get().booleanValue()) {
// self.subtitleView.text = NSLocalizedString("ChatNoGroupAccess", comment: "You is not member")
// self.textInputbar.hidden = true
// return
// } else {
// self.textInputbar.hidden = false
// }
if (typingValue != nil && typingValue!.length() > 0) {
self.subtitleView.textColor = Resources.PrimaryLightText
if (typingValue!.length() == 1) {
let uid = typingValue!.intAtIndex(0);
let user = Actor.getUserWithUid(uid)
self.subtitleView.text = Actor.getFormatter().formatTypingWithName(user.getNameModel().get())
} else {
self.subtitleView.text = Actor.getFormatter().formatTypingWithCount(typingValue!.length());
}
} else {
var membersString = Actor.getFormatter().formatGroupMembers(members!.size())
if (onlineCount == nil || onlineCount!.integerValue == 0) {
self.subtitleView.textColor = Resources.SecondaryLightText
self.subtitleView.text = membersString;
} else {
membersString = membersString + ", ";
let onlineString = Actor.getFormatter().formatGroupOnline(onlineCount!.intValue());
let attributedString = NSMutableAttributedString(string: (membersString + onlineString))
attributedString.addAttribute(NSForegroundColorAttributeName, value: Resources.PrimaryLightText, range: NSMakeRange(membersString.length, onlineString.length))
self.subtitleView.attributedText = attributedString
}
}
})
}
Actor.onConversationOpenWithPeer(peer)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backgroundView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
titleView.frame = CGRectMake(0, 4, (navigationView.frame.width - 0), 20)
subtitleView.frame = CGRectMake(0, 22, (navigationView.frame.width - 0), 20)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !isIPad {
(UIApplication.sharedApplication().delegate as! AppDelegate).showBadge()
}
if navigationController!.viewControllers.count > 2 {
let firstController = navigationController!.viewControllers[0]
let currentController = navigationController!.viewControllers[navigationController!.viewControllers.count - 1]
navigationController!.setViewControllers([firstController, currentController], animated: false)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.onConversationClosedWithPeer(peer)
if !isIPad {
(UIApplication.sharedApplication().delegate as! AppDelegate).hideBadge()
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
Actor.saveDraftWithPeer(peer, withDraft: textView.text)
// Releasing bindings
binder.unbindAll()
}
// Chat avatar tap
func onAvatarTap() {
let id = Int(peer.getPeerId())
var controller: AAViewController
if (UInt(peer.getPeerType().ordinal()) == ACPeerType.PRIVATE.rawValue) {
controller = UserViewController(uid: id)
} else if (UInt(peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue) {
controller = GroupViewController(gid: id)
} else {
return
}
if (isIPad) {
let navigation = AANavigationController()
navigation.viewControllers = [controller]
let popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItem!,
permittedArrowDirections: UIPopoverArrowDirection.Up,
animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
// Text bar actions
override func textWillUpdate() {
super.textWillUpdate();
Actor.onTypingWithPeer(peer);
}
override func didPressRightButton(sender: AnyObject!) {
Actor.trackTextSendWithPeer(peer)
Actor.sendMessageWithMentionsDetect(peer, withText: textView.text)
super.didPressRightButton(sender)
}
override func didPressLeftButton(sender: AnyObject!) {
super.didPressLeftButton(sender)
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
let builder = MenuBuilder()
if hasCamera {
builder.add("PhotoCamera") { () -> () in
self.pickImage(.Camera)
}
}
builder.add("PhotoLibrary") { () -> () in
self.pickImage(.PhotoLibrary)
}
if #available(iOS 8.0, *) {
builder.add("SendDocument") { () -> () in
self.pickDocument()
}
}
if !isIPad {
// For iPhone fast action sheet
showActionSheetFast(builder.items, cancelButton: "AlertCancel", tapClosure: builder.tapClosure)
} else {
// For iPad use old action sheet
showActionSheet(builder.items, cancelButton: "AlertCancel", destructButton: nil, sourceView: self.leftButton, sourceRect: self.leftButton.bounds, tapClosure: builder.tapClosure)
}
}
// Completition
override func canShowAutoCompletion() -> Bool {
if UInt(self.peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue {
if self.foundPrefix == "@" {
let oldCount = filteredMembers.count
filteredMembers.removeAll(keepCapacity: true)
let res = Actor.findMentionsWithGid(self.peer.getPeerId(), withQuery: self.foundWord)
for index in 0..<res.size() {
filteredMembers.append(res.getWithInt(index) as! ACMentionFilterResult)
}
if oldCount == filteredMembers.count {
self.autoCompletionView.reloadData()
}
return filteredMembers.count > 0
}
return false
}
return false
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredMembers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let res = AutoCompleteCell(style: UITableViewCellStyle.Default, reuseIdentifier: "user_name")
res.bindData(filteredMembers[indexPath.row], highlightWord: foundWord)
return res
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let user = filteredMembers[indexPath.row]
var postfix = " "
if foundPrefixRange.location == 0 {
postfix = ": "
}
acceptAutoCompletionWithString(user.getMentionString() + postfix, keepPrefix: !user.isNickname())
}
override func heightForAutoCompletionView() -> CGFloat {
let cellHeight: CGFloat = 44.0;
return cellHeight * CGFloat(filteredMembers.count)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// Remove separator inset
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset = UIEdgeInsetsZero
}
// Prevent the cell from inheriting the Table View's margin settings
if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
if #available(iOS 8.0, *) {
cell.preservesSuperviewLayoutMargins = false
} else {
// Fallback on earlier versions
}
}
// Explictly set your cell's layout margins
if cell.respondsToSelector("setLayoutMargins:") {
if #available(iOS 8.0, *) {
cell.layoutMargins = UIEdgeInsetsZero
} else {
// Fallback on earlier versions
}
}
}
// Document picking
@available(iOS 8.0, *)
func pickDocument() {
let documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll as! [String], inMode: UIDocumentPickerMode.Import)
documentPicker.view.backgroundColor = UIColor.clearColor()
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
}
@available(iOS 8.0, *)
func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
}
@available(iOS 8.0, *)
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
// Loading path and file name
let path = url.path!
let fileName = url.lastPathComponent
// Check if file valid or directory
var isDir : ObjCBool = false
if !NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDir) {
// Not exists
return
}
// Destination file
let descriptor = "/tmp/\(NSUUID().UUIDString)"
let destPath = CocoaFiles.pathFromDescriptor(descriptor)
if isDir {
// Zipping contents and sending
execute(Tools.zipDirectoryCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocumentWithPeer(self.peer, withName: fileName, withMime: "application/zip", withDescriptor: descriptor)
}
} else {
// Sending file itself
execute(Tools.copyFileCommand(path, to: destPath)) { (val) -> Void in
Actor.sendDocumentWithPeer(self.peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor)
}
}
}
// Image picking
func pickImage(source: UIImagePickerControllerSourceType) {
let pickerController = AAImagePickerController()
pickerController.sourceType = source
pickerController.mediaTypes = [kUTTypeImage as String]
pickerController.view.backgroundColor = MainAppTheme.list.bgColor
pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor]
self.presentViewController(pickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
Actor.trackPhotoSendWithPeer(peer)
Actor.sendUIImage(image, peer: peer)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
Actor.sendUIImage(info[UIImagePickerControllerOriginalImage] as! UIImage, peer: peer)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
}
} | mit | 7d21b082ada642b19ead009724ed7a4b | 41.334047 | 248 | 0.623856 | 5.741795 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatMessageBubbleImages.swift | 1 | 9122 | //
// ChatMessageBubbleImages.swift
// Telegram
//
// Created by keepcoder on 04/12/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
enum MessageBubbleImageNeighbors {
case none
case top
case bottom
case both
}
func messageSingleBubbleLikeImage(fillColor: NSColor, strokeColor: NSColor) -> CGImage {
let diameter: CGFloat = 36.0
return generateImage(CGSize(width: 36.0, height: diameter), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
let lineWidth: CGFloat = 0.5
context.setFillColor(strokeColor.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(), size: size))
context.setFillColor(fillColor.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(x: lineWidth, y: lineWidth), size: CGSize(width: size.width - lineWidth * 2.0, height: size.height - lineWidth * 2.0)))
})!
}
func messageBubbleImageModern(incoming: Bool, fillColor: NSColor, strokeColor: NSColor, neighbors: MessageBubbleImageNeighbors, mask: Bool = false) -> (CGImage, NSEdgeInsets) {
let diameter: CGFloat = 36.0
let corner: CGFloat = 7.0
let image = generateImage(CGSize(width: 42.0, height: diameter), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
let additionalOffset: CGFloat
switch neighbors {
case .none, .bottom:
additionalOffset = 0.0
case .both, .top:
additionalOffset = 6.0
}
context.translateBy(x: size.width / 2.0, y: size.height / 2.0)
context.scaleBy(x: incoming ? 1.0 : -1.0, y: -1.0)
context.translateBy(x: -size.width / 2.0 + 0.5 + additionalOffset, y: -size.height / 2.0 + 0.5)
let lineWidth: CGFloat = 1.0
if mask {
context.setBlendMode(.copy)
context.setFillColor(NSColor.clear.cgColor)
context.setStrokeColor(NSColor.clear.cgColor)
} else {
context.setFillColor(fillColor.cgColor)
context.setLineWidth(lineWidth)
context.setStrokeColor(strokeColor.cgColor)
}
switch neighbors {
case .none:
let _ = try? drawSvgPath(context, path: "M6,17.5 C6,7.83289181 13.8350169,0 23.5,0 C33.1671082,0 41,7.83501688 41,17.5 C41,27.1671082 33.1649831,35 23.5,35 C19.2941198,35 15.4354328,33.5169337 12.4179496,31.0453367 C9.05531719,34.9894816 -2.41102995e-08,35 0,35 C5.972003,31.5499861 6,26.8616169 6,26.8616169 L6,17.5 L6,17.5 ")
context.strokePath()
let _ = try? drawSvgPath(context, path: "M6,17.5 C6,7.83289181 13.8350169,0 23.5,0 C33.1671082,0 41,7.83501688 41,17.5 C41,27.1671082 33.1649831,35 23.5,35 C19.2941198,35 15.4354328,33.5169337 12.4179496,31.0453367 C9.05531719,34.9894816 -2.41102995e-08,35 0,35 C5.972003,31.5499861 6,26.8616169 6,26.8616169 L6,17.5 L6,17.5 ")
context.fillPath()
case .top:
let _ = try? drawSvgPath(context, path: "M35,17.5 C35,7.83501688 27.1671082,0 17.5,0 L17.5,0 C7.83501688,0 0,7.83289181 0,17.5 L0,29.0031815 C0,32.3151329 2.6882755,35 5.99681848,35 L17.5,35 C27.1649831,35 35,27.1671082 35,17.5 L35,17.5 L35,17.5 ")
context.strokePath()
let _ = try? drawSvgPath(context, path: "M35,17.5 C35,7.83501688 27.1671082,0 17.5,0 L17.5,0 C7.83501688,0 0,7.83289181 0,17.5 L0,29.0031815 C0,32.3151329 2.6882755,35 5.99681848,35 L17.5,35 C27.1649831,35 35,27.1671082 35,17.5 L35,17.5 L35,17.5 ")
context.fillPath()
case .bottom:
let _ = try? drawSvgPath(context, path: "M6,17.5 L6,5.99681848 C6,2.6882755 8.68486709,0 11.9968185,0 L23.5,0 C33.1671082,0 41,7.83501688 41,17.5 C41,27.1671082 33.1649831,35 23.5,35 C19.2941198,35 15.4354328,33.5169337 12.4179496,31.0453367 C9.05531719,34.9894816 -2.41103066e-08,35 0,35 C5.972003,31.5499861 6,26.8616169 6,26.8616169 L6,17.5 L6,17.5 ")
context.strokePath()
let _ = try? drawSvgPath(context, path: "M6,17.5 L6,5.99681848 C6,2.6882755 8.68486709,0 11.9968185,0 L23.5,0 C33.1671082,0 41,7.83501688 41,17.5 C41,27.1671082 33.1649831,35 23.5,35 C19.2941198,35 15.4354328,33.5169337 12.4179496,31.0453367 C9.05531719,34.9894816 -2.41103066e-08,35 0,35 C5.972003,31.5499861 6,26.8616169 6,26.8616169 L6,17.5 L6,17.5 ")
context.fillPath()
case .both:
let _ = try? drawSvgPath(context, path: "M17.5,0 C27.1649831,1.94289029e-15 35,7.83501688 35,17.5 C35,27.1649831 27.1649831,35 17.5,35 C7.83501688,35 0,27.1649831 0,17.5 C3.88578059e-15,7.83501688 7.83501688,-1.94289029e-15 17.5,0 ")
context.strokePath()
let _ = try? drawSvgPath(context, path: "M17.5,0 C27.1649831,1.94289029e-15 35,7.83501688 35,17.5 C35,27.1649831 27.1649831,35 17.5,35 C7.83501688,35 0,27.1649831 0,17.5 C3.88578059e-15,7.83501688 7.83501688,-1.94289029e-15 17.5,0 ")
context.fillPath()
}
})!
let leftCapWidth: CGFloat = CGFloat(incoming ? Int(corner + diameter / 2.0) : Int(diameter / 2.0))
let topCapHeight: CGFloat = diameter / 2.0
let rightCapWidth: CGFloat = image.backingSize.width - leftCapWidth - 1.0
let bottomCapHeight: CGFloat = image.backingSize.height - topCapHeight - 1.0
return (image, NSEdgeInsetsMake(topCapHeight, leftCapWidth, bottomCapHeight, rightCapWidth))
}
func drawNinePartImage(_ context: CGContext, frame: NSRect, topLeftCorner: CGImage, topEdgeFill: CGImage, topRightCorner: CGImage, leftEdgeFill: CGImage, centerFill: CGImage, rightEdgeFill: CGImage, bottomLeftCorner: CGImage, bottomEdgeFill: CGImage, bottomRightCorner: CGImage){
let imageWidth: CGFloat = frame.size.width;
let imageHeight: CGFloat = frame.size.height;
let leftCapWidth: CGFloat = topLeftCorner.backingSize.width;
let topCapHeight: CGFloat = topLeftCorner.backingSize.height;
let rightCapWidth: CGFloat = bottomRightCorner.backingSize.width;
let bottomCapHeight: CGFloat = bottomRightCorner.backingSize.height;
let centerSize = NSMakeSize(imageWidth - leftCapWidth - rightCapWidth, imageHeight - topCapHeight - bottomCapHeight);
let topLeftCornerRect: NSRect = NSMakeRect(0.0, imageHeight - topCapHeight, leftCapWidth, topCapHeight);
let topEdgeFillRect: NSRect = NSMakeRect(leftCapWidth, imageHeight - topCapHeight, centerSize.width, topCapHeight);
let topRightCornerRect: NSRect = NSMakeRect(imageWidth - rightCapWidth, imageHeight - topCapHeight, rightCapWidth, topCapHeight);
let leftEdgeFillRect: NSRect = NSMakeRect(0.0, bottomCapHeight, leftCapWidth, centerSize.height);
let centerFillRect: NSRect = NSMakeRect(leftCapWidth, bottomCapHeight, centerSize.width, centerSize.height);
let rightEdgeFillRect: NSRect = NSMakeRect(imageWidth - rightCapWidth, bottomCapHeight, rightCapWidth, centerSize.height);
let bottomLeftCornerRect: NSRect = NSMakeRect(0.0, 0.0, leftCapWidth, bottomCapHeight);
let bottomEdgeFillRect: NSRect = NSMakeRect(leftCapWidth, 0.0, centerSize.width, bottomCapHeight);
let bottomRightCornerRect: NSRect = NSMakeRect(imageWidth - rightCapWidth, 0.0, rightCapWidth, bottomCapHeight);
drawStretchedImageInRect(topLeftCorner, context: context, rect: topLeftCornerRect);
drawStretchedImageInRect(topEdgeFill, context: context, rect: topEdgeFillRect);
drawStretchedImageInRect(topRightCorner, context: context, rect: topRightCornerRect);
drawStretchedImageInRect(leftEdgeFill, context: context, rect: leftEdgeFillRect);
drawStretchedImageInRect(centerFill, context: context, rect: centerFillRect);
drawStretchedImageInRect(rightEdgeFill, context: context, rect: rightEdgeFillRect);
drawStretchedImageInRect(bottomLeftCorner, context: context, rect: bottomLeftCornerRect);
drawStretchedImageInRect(bottomEdgeFill, context: context, rect: bottomEdgeFillRect);
drawStretchedImageInRect(bottomRightCorner, context: context, rect: bottomRightCornerRect);
}
func imageByReferencingRectOfExistingImage(_ image: CGImage, _ rect: NSRect) -> CGImage {
if (!NSIsEmptyRect(rect)){
let pixelsHigh = CGFloat(image.height)
let scaleFactor:CGFloat = pixelsHigh / image.backingSize.height
var captureRect = NSMakeRect(scaleFactor * rect.origin.x, scaleFactor * rect.origin.y, scaleFactor * rect.size.width, scaleFactor * rect.size.height)
captureRect.origin.y = pixelsHigh - captureRect.origin.y - captureRect.size.height;
return image.cropping(to: captureRect)!
}
return image.cropping(to: NSMakeRect(0, 0, image.size.width, image.size.height))!
}
func drawStretchedImageInRect(_ image: CGImage, context: CGContext, rect: NSRect) -> Void {
context.saveGState()
context.setBlendMode(.normal) //NSCompositeSourceOver
context.clip(to: rect)
context.draw(image, in: rect)
context.restoreGState()
}
| gpl-2.0 | 8e24ab445ca3ad1dd83f58fe0cf3a22f | 52.970414 | 366 | 0.695538 | 3.303513 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.