repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Xiomara7/bookiao-ios
|
refs/heads/master
|
bookiao-ios/EmployeeViewController.swift
|
mit
|
1
|
//
// EmployeeViewController.swift
// bookiao-ios
//
// Created by Xiomara on 11/1/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
class EmployeeViewController: UIViewController, UIPickerViewDelegate {
let application = UIApplication.sharedApplication().delegate as AppDelegate
class Singleton {
class var sharedInstance : Singleton {
struct Static {
static let instance : Singleton = Singleton()
}
return Static.instance
}
}
let pickerView = UIPickerView()
var businessResponse: Int = Int()
var placetxtField: UITextField = CustomDesign.getNameTxtField
var emailtxtField: UITextField = CustomDesign.getNameTxtField
var passwtxtField: UITextField = CustomDesign.getNameTxtField
var confirmsField: UITextField = CustomDesign.getNameTxtField
var nameTextField: UITextField = CustomDesign.getNameTxtField
var localTxtField: UITextField = CustomDesign.getNameTxtField
let registerButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
override func viewDidLoad() {
let customDesign = CustomDesign()
self.view.backgroundColor = customDesign.UIColorFromRGB(0xE4E4E4)
super.viewDidLoad()
nameTextField.frame = (CGRectMake(20, 70, self.view.bounds.width - 40, 40))
nameTextField.placeholder = "Nombre"
emailtxtField.frame = CGRectMake(20, 120, self.view.bounds.width - 40, 40)
emailtxtField.placeholder = "Correo electrónico"
passwtxtField.frame = CGRectMake(20, 170, self.view.bounds.width - 40, 40)
passwtxtField.placeholder = "Contraseña"
confirmsField.frame = CGRectMake(20, 220, self.view.bounds.width - 40, 40)
confirmsField.placeholder = "Número telefónico"
placetxtField.frame = CGRectMake(20, 270, self.view.bounds.width - 40, 40)
placetxtField.placeholder = "Negocio"
localTxtField.frame = (CGRectMake(20, 320, self.view.bounds.width - 40, 40))
localTxtField.placeholder = "Localización"
registerButton.frame = CGRectMake(20, 440, self.view.bounds.width - 40, 40)
registerButton.tintColor = UIColor.whiteColor()
registerButton.backgroundColor = customDesign.UIColorFromRGB(0x34A3DB)
registerButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16.0)
registerButton.setTitle("Registrarme", forState: UIControlState.Normal)
registerButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview( emailtxtField)
self.view.addSubview( placetxtField)
self.view.addSubview( passwtxtField)
self.view.addSubview( localTxtField)
self.view.addSubview( confirmsField)
self.view.addSubview( nameTextField)
self.view.addSubview(registerButton)
pickerView.delegate = self
placetxtField.inputView = pickerView
// Do any additional setup after loading the view.
let postButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss"))
self.navigationItem.leftBarButtonItem = postButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.navigationItem.title = "Empleado"
self.tabBarController?.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.tabBarController?.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func dismiss() {
let back = LoginViewController(nibName: nil, bundle: nil)
self.presentViewController(back, animated: true, completion: nil)
}
func buttonAction(sender:UIButton!) {
let request = HTTPrequests()
let name = nameTextField.text
let email = emailtxtField.text
let phone = confirmsField.text
let password = passwtxtField.text
let location = localTxtField.text
let business = placetxtField.text
let businessID = businessResponse
request.registerRequest(email, name: name, phone: phone, passwd: password) {(str, error) -> Void in
if let ok = str {request.authRequest(email, passwd: password) {(str, error) -> Void in
if let ok = str {request.employeeReq(email, name: name, phone: phone, business: 1) {(str, error) -> Void in
if let ok = str {request.getUserInfo(email, completion: { (str, error) -> Void in
if let ok = str {
dispatch_async(dispatch_get_main_queue(), {
let views = ViewController()
self.presentViewController(views, animated: true, completion: nil)
})}})}}}}}
}
}
// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 1
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return DataManager.sharedManager.titles.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return DataManager.sharedManager.titles[row]["name"] as String
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
println("titles: \(DataManager.sharedManager.titles)")
placetxtField.text = DataManager.sharedManager.titles[row]["name"] as String
businessResponse = row + 1
}
}
|
c5f91d280c95094ec9938a4bde099cd7
| 40.451389 | 133 | 0.666052 | false | false | false | false |
NikitaAsabin/pdpDecember
|
refs/heads/master
|
Pods/FSHelpers+Swift/Swift/Helpers/FSExtensions/FSE+UIImage.swift
|
mit
|
1
|
//
// FSE+UIImage.swift
// DayPhoto
//
// Created by Kruperfone on 23.09.15.
// Copyright © 2015 Flatstack. All rights reserved.
//
import UIKit
public struct FSBitmapPixel {
public var r: UInt8
public var g: UInt8
public var b: UInt8
public var a: UInt8
public init (value: UInt32) {
self.r = UInt8((value >> 0) & 0xFF)
self.g = UInt8((value >> 8) & 0xFF)
self.b = UInt8((value >> 16) & 0xFF)
self.a = UInt8((value >> 24) & 0xFF)
}
public init (color: UIColor) {
var red: CGFloat = -1
var green: CGFloat = -1
var blue: CGFloat = -1
var alpha: CGFloat = -1
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
self.r = UInt8(red * 255)
self.g = UInt8(green * 255)
self.b = UInt8(blue * 255)
self.a = UInt8(alpha * 255)
}
public var value: UInt32 {
let red = UInt32(self.r) << 0
let green = UInt32(self.g) << 8
let blue = UInt32(self.b) << 16
let alpha = UInt32(self.a) << 24
let result = red+green+blue+alpha
return result
}
public var color: UIColor {
return UIColor(
red: CGFloat(self.r)/255,
green: CGFloat(self.g)/255,
blue: CGFloat(self.b)/255,
alpha: CGFloat(self.a)/255)
}
public var description: String {
return "\(self.r)|\(self.g)|\(self.b)|\(self.a)"
}
public var brightness: UInt8 {
return UInt8((CGFloat(self.brightness32)/(255*3))*255)
}
private var brightness32: UInt32 {
return UInt32(self.r) + UInt32(self.g) + UInt32(self.b)
}
}
public class FSBitmap: NSObject {
private var bytesPerRow: Int {
return Int(self.size.width)
}
public var data: UnsafeMutablePointer<UInt32>
public var size: (width: Int, height: Int)
public init (data: UnsafeMutablePointer<UInt32>, size: (width: Int, height: Int)) {
self.size = size
self.data = data
super.init()
}
public init (size: (width: Int, height: Int)) {
self.size = size
self.data = UnsafeMutablePointer<UInt32>(calloc(self.size.width*self.size.height, sizeof(UInt32)))
super.init()
}
convenience public init (size: CGSize) {
self.init(size: (width: Int(size.width), height: Int(size.height)))
}
public func getCGImage () -> CGImage {
let width = self.size.width
let height = self.size.height
let bitsPerComponent = 8
let bytesPerPixel = 4
let bitsPerPixel = bytesPerPixel * 8
let bytesPerRow = width * bytesPerPixel
let colorSpace = CGColorSpaceCreateDeviceRGB()
let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)
let bitmapData = self.data
let bufferLength = width * height * bytesPerPixel
let provider = CGDataProviderCreateWithData(nil, bitmapData, bufferLength, nil)
let image = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider, nil, true, renderingIntent)
return image!
}
public func getUIImage (scale: CGFloat = UIScreen.mainScreen().scale, orientation: UIImageOrientation = UIImageOrientation.Up) -> UIImage {
let image = self.getCGImage()
return UIImage(CGImage: image, scale: scale, orientation: orientation)
}
public func getPixel (x: Int, _ y: Int) -> FSBitmapPixel {
return FSBitmapPixel(value: self.data[self.index(x, y)])
}
public func setPixel (pixel: FSBitmapPixel, point: (x: Int, y: Int)) {
self.data[self.index(point.x, point.y)] = pixel.value
}
private func index (x: Int, _ y: Int) -> Int {
return self.bytesPerRow*y + x
}
}
public extension UIImage {
public func fs_getBitmap () -> FSBitmap {
let imageRef: CGImageRef? = self.CGImage
//Get image width, height
let pixelsWide = CGImageGetWidth(imageRef)
let pixelsHigh = CGImageGetHeight(imageRef)
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and alpha.
let bytesPerPixel = 4
let bitsPerComponent = 8
let bitmapBytesPerRow = Int(pixelsWide) * bytesPerPixel
// Use the generic RGB color space.
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
let bitmapData = UnsafeMutablePointer<UInt32>(calloc(pixelsWide*pixelsHigh, sizeof(UInt32)))
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, bitsPerComponent, bitmapBytesPerRow, colorSpace, bitmapInfo)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(pixelsWide), CGFloat(pixelsHigh)), imageRef)
return FSBitmap(data: bitmapData, size: (pixelsWide, pixelsHigh))
}
public var fs_base64: String {
let imageData = UIImagePNGRepresentation(self)!
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return base64String
}
}
|
e01c489f400c63cab5c3729957daebd7
| 33.04023 | 164 | 0.605099 | false | false | false | false |
ibari/ios-twitter
|
refs/heads/master
|
Twitter/User.swift
|
gpl-2.0
|
1
|
//
// User.swift
// Twitter
//
// Created by Ian on 5/20/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var id: Int?
var name: String?
var screenName: String?
var profileImageURL: NSURL?
var profileBackgroundImageURL: NSURL?
var statusesCount: Int?
var followersCount: Int?
var friendsCount: Int?
var dictionary: NSDictionary?
init(dictionary: NSDictionary) {
self.dictionary = dictionary
id = dictionary["id"] as? Int
name = dictionary["name"] as? String
screenName = dictionary["screen_name"] as? String
let profileImageURLString = dictionary["profile_image_url"] as? String
if profileImageURLString != nil {
profileImageURL = NSURL(string: profileImageURLString!)!
} else {
profileImageURL = nil
}
let profileBackgroundImageURLString = dictionary["profile_background_image_url"] as? String
if profileBackgroundImageURLString != nil {
profileBackgroundImageURL = NSURL(string: profileBackgroundImageURLString!)!
} else {
profileBackgroundImageURL = nil
}
statusesCount = dictionary["statuses_count"] as? Int
followersCount = dictionary["followers_count"] as? Int
friendsCount = dictionary["friends_count"] as? Int
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
var dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(user!.dictionary!, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
|
d744be74e4f557474f9ff268ac8f1f42
| 28.534091 | 115 | 0.688342 | false | false | false | false |
scoremedia/Fisticuffs
|
refs/heads/master
|
Sources/Fisticuffs/ComposedBindingHandler.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2019 theScore Inc.
//
// 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
/// A `BindingHandler` whose input and output is a function of the two components `BindingHandler`s
class ComposedBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler1: BindingHandler<Control, InDataValue, OutDataValue>
let bindingHandler2: BindingHandler<Control, OutDataValue, PropertyValue>
private var bindingHandler1OldValue: OutDataValue?
init(handler1: BindingHandler<Control, InDataValue, OutDataValue>, handler2: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler1 = handler1
self.bindingHandler2 = handler2
}
override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
bindingHandler1.set(control: control, oldValue: oldValue, value: value) { [handler = self.bindingHandler2, oldValue = bindingHandler1OldValue, weak self] (control, value) in
handler.set(control: control, oldValue: oldValue, value: value, propertySetter: propertySetter)
self?.bindingHandler1OldValue = value
}
}
override func get(control: Control, propertyGetter: @escaping PropertyGetter) throws -> InDataValue {
try bindingHandler1.get(control: control, propertyGetter: { [handler = self.bindingHandler2] (control) -> OutDataValue in
try! handler.get(control: control, propertyGetter: propertyGetter)
})
}
override func dispose() {
bindingHandler1.dispose()
bindingHandler2.dispose()
super.dispose()
}
}
/// Composes two `BindingHandler` objcts so that the data flows through the LHS first performing and transfromations and then the RHS
///
/// - Parameters:
/// - lhs: The first binding handler
/// - rhs: the second binding handler
/// - Returns: A binding handle that composes the functions of the two `BindingHandler`s provided
public func && <Control: AnyObject, InDataValue, OutDataValue, PropertyValue>(lhs: BindingHandler<Control, InDataValue, OutDataValue>, rhs:BindingHandler<Control, OutDataValue, PropertyValue>) -> BindingHandler<Control, InDataValue, PropertyValue> {
ComposedBindingHandler(handler1: lhs, handler2: rhs)
}
|
e9d8bcb38f5ae5d7ce2b6c47b329c34d
| 51.575758 | 249 | 0.739769 | false | false | false | false |
abdullah-chhatra/iLayout
|
refs/heads/master
|
Example/Example/ExampleViewController.swift
|
mit
|
1
|
//
// ExampleViewController.swift
// Example
//
// Created by Abdulmunaf Chhatra on 6/6/15.
// Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved.
//
import UIKit
class ExampleViewController: UIViewController {
let myView : UIView
let titleText : String
init(view: UIView, titleText: String) {
myView = view
self.titleText = titleText
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = myView
navigationItem.title = titleText
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.plain, target: self, action: nil)
}
}
|
eab082898406342d2ce152301dd43416
| 24.459459 | 135 | 0.649682 | false | false | false | false |
stone-payments/onestap-sdk-ios
|
refs/heads/master
|
OnestapSDK/User/Entities/Vehicle.swift
|
apache-2.0
|
1
|
//
// Vehicle.swift
// OnestapSDK
//
// Created by Munir Wanis on 22/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
public struct Vehicle {
public init(licensePlate: String) {
self.licensePlate = licensePlate
}
public internal(set) var key: String = ""
public var licensePlate: String
public var licensePlateCity: String? = nil
public var licensePlateState: String? = nil
public var licensePlateCountry: String? = nil
}
extension Vehicle: Encondable {
func toDictionary() -> JSON {
return [
"licensePlate": licensePlate,
"licensePlateCity": licensePlateCity as Any,
"licensePlateState": licensePlateState as Any,
"licensePlateCountry": licensePlateCountry as Any
]
}
}
|
f8ed1722df44603ee63e448c5d91ed89
| 25.516129 | 61 | 0.656934 | false | true | false | false |
xgdgsc/AlecrimCoreData
|
refs/heads/master
|
Source/AlecrimCoreData/Core/Protocols/AttributeQueryType.swift
|
mit
|
1
|
//
// AttributeQueryType.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 2015-08-08.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
import CoreData
public protocol AttributeQueryType: CoreDataQueryable {
var returnsDistinctResults: Bool { get set }
var propertiesToFetch: [String] { get set }
}
// MARK: -
extension AttributeQueryType {
public func distinct() -> Self {
var clone = self
clone.returnsDistinctResults = true
return self
}
}
// MARK: - GenericQueryable
extension AttributeQueryType {
public func toArray() -> [Self.Item] {
var results: [Self.Item] = []
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
for dict in dicts {
guard dict.count == 1, let value = dict.allValues.first as? Self.Item else {
throw AlecrimCoreDataError.UnexpectedValue(value: dict)
}
results.append(value)
}
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
}
return results
}
}
extension AttributeQueryType where Self.Item: NSDictionary {
public func toArray() -> [NSDictionary] {
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
return dicts
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
return [NSDictionary]()
}
}
}
// MARK: - CoreDataQueryable
extension AttributeQueryType {
public func toFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = self.entityDescription
fetchRequest.fetchOffset = self.offset
fetchRequest.fetchLimit = self.limit
fetchRequest.fetchBatchSize = (self.limit > 0 && self.batchSize > self.limit ? 0 : self.batchSize)
fetchRequest.predicate = self.predicate
fetchRequest.sortDescriptors = self.sortDescriptors
//
fetchRequest.resultType = .DictionaryResultType
fetchRequest.returnsDistinctResults = self.returnsDistinctResults
fetchRequest.propertiesToFetch = self.propertiesToFetch
//
return fetchRequest
}
}
|
421f829b32f92a16fd65c53fc458d8ec
| 25.036364 | 106 | 0.582053 | false | false | false | false |
jmgc/swift
|
refs/heads/master
|
test/attr/global_actor.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -typecheck -verify %s -enable-experimental-concurrency
// REQUIRES: concurrency
actor class SomeActor { }
// -----------------------------------------------------------------------
// @globalActor attribute itself.
// -----------------------------------------------------------------------
// Well-formed global actor.
@globalActor
struct GA1 {
static let shared = SomeActor()
}
@globalActor
struct GenericGlobalActor<T> {
static var shared: SomeActor { SomeActor() }
}
// Ill-formed global actors.
@globalActor
open class GA2 { // expected-error{{global actor 'GA2' requires a static property 'shared' that produces an actor instance}}{{17-17=\n public static let shared = <#actor instance#>}}
}
@globalActor
struct GA3 { // expected-error{{global actor 'GA3' requires a static property 'shared' that produces an actor instance}}
let shared = SomeActor() // expected-note{{'shared' property in global actor is not 'static'}}{{3-3=static }}
}
@globalActor
struct GA4 { // expected-error{{global actor 'GA4' requires a static property 'shared' that produces an actor instance}}
private static let shared = SomeActor() // expected-note{{'shared' property has more restrictive access (private) than its global actor (internal)}}{{3-11=}}
}
@globalActor
open class GA5 { // expected-error{{global actor 'GA5' requires a static property 'shared' that produces an actor instance}}
static let shared = SomeActor() // expected-note{{'shared' property has more restrictive access (internal) than its global actor (public)}}{{3-3=public}}
}
@globalActor
struct GA6<T> { // expected-error{{global actor 'GA6' requires a static property 'shared' that produces an actor instance}}
}
extension GA6 where T: Equatable {
static var shared: SomeActor { SomeActor() } // expected-note{{'shared' property in global actor cannot be in a constrained extension}}
}
@globalActor
class GA7 { // expected-error{{global actor 'GA7' requires a static property 'shared' that produces an actor instance}}
static let shared = 5 // expected-note{{'shared' property type 'Int' does not conform to the 'Actor' protocol}}
}
// -----------------------------------------------------------------------
// Applying global actors to entities.
// -----------------------------------------------------------------------
@globalActor
struct OtherGlobalActor {
static let shared = SomeActor()
}
@GA1 func f() {
@GA1 let x = 17 // expected-error{{local variable 'x' cannot have a global actor}}
_ = x
}
@GA1 struct X {
@GA1 var member: Int // expected-error{{stored property 'member' of a struct cannot have a global actor}}
}
struct Y {
@GA1 subscript(i: Int) -> Int { i }
}
@GA1 extension Y { }
@GA1 func g() { }
class SomeClass {
@GA1 init() { }
@GA1 deinit { } // expected-error{{deinitializer cannot have a global actor}}
}
@GA1 typealias Integer = Int // expected-error{{type alias cannot have a global actor}}
@GA1 actor class ActorInTooManyPlaces { } // expected-error{{actor class 'ActorInTooManyPlaces' cannot have a global actor}}
@GA1 @OtherGlobalActor func twoGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('OtherGlobalActor' and 'GA1')}}
struct Container {
// FIXME: Diagnostic could be improved to show the generic arguments.
@GenericGlobalActor<Int> @GenericGlobalActor<String> func twoGenericGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('GenericGlobalActor' and 'GenericGlobalActor')}}
}
// -----------------------------------------------------------------------
// Redundant attributes
// -----------------------------------------------------------------------
extension SomeActor {
@GA1 @actorIndependent func conflict1() { } // expected-error{{instance method 'conflict1()' has multiple actor-isolation attributes ('actorIndependent' and 'GA1')}}
}
|
c9b9b46ead9daa5dd9df9c223930b1a4
| 38.16 | 213 | 0.645557 | false | false | false | false |
tomisacat/AudioTips
|
refs/heads/master
|
AudioTips/AudioFormatService.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
import AudioToolbox
// function
func openFile() -> AudioFileID? {
let url = Bundle.main.url(forResource: "guitar", withExtension: "m4a")
var fd: AudioFileID? = nil
AudioFileOpenURL(url! as CFURL, .readPermission, kAudioFileM4AType, &fd)
// Or in iOS platform, the file type could be 0 directly
// AudioFileOpenURL(url! as CFURL, .readPermission, 0, &fd)
return fd
}
func closeFile(fd: AudioFileID) {
AudioFileClose(fd)
}
// use
let fd: AudioFileID? = openFile()
if let fd = fd {
var status: OSStatus = noErr
var propertySize: UInt32 = 0
var writable: UInt32 = 0
// magic cookie
status = AudioFileGetPropertyInfo(fd, kAudioFilePropertyMagicCookieData, &propertySize, &writable)
// if status != noErr {
// return
// }
let magic: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: Int(propertySize))
status = AudioFileGetProperty(fd, kAudioFilePropertyMagicCookieData, &propertySize, magic)
// if status != noErr {
// return
// }
// format info
var desc: AudioStreamBasicDescription = AudioStreamBasicDescription()
var descSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, propertySize, magic, &descSize, &desc)
// if status != noErr {
// return
// }
print(desc)
// format name
status = AudioFileGetProperty(fd, kAudioFilePropertyDataFormat, &descSize, &desc)
// if status != noErr {
// return
// }
var formatName: CFString = String() as CFString
var formatNameSize: UInt32 = UInt32(MemoryLayout<CFString>.size)
status = AudioFormatGetProperty(kAudioFormatProperty_FormatName, descSize, &desc, &formatNameSize, &formatName)
// if status != noErr {
// return
// }
print(formatName)
// format info
var formatInfo: AudioFormatInfo = AudioFormatInfo(mASBD: desc,
mMagicCookie: magic,
mMagicCookieSize: propertySize)
var outputFormatInfoSize: UInt32 = 0
status = AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize)
// format list
let formatListItem: UnsafeMutablePointer<AudioFormatListItem> = UnsafeMutablePointer<AudioFormatListItem>.allocate(capacity: Int(outputFormatInfoSize))
status = AudioFormatGetProperty(kAudioFormatProperty_FormatList,
UInt32(MemoryLayout<AudioFormatInfo>.size),
&formatInfo,
&outputFormatInfoSize,
formatListItem)
// if status != noErr {
// return
// }
let itemCount = outputFormatInfoSize / UInt32(MemoryLayout<AudioFormatListItem>.size)
for idx in 0..<itemCount {
let item: AudioFormatListItem = formatListItem.advanced(by: Int(idx)).pointee
print("channel layout tag is \(item.mChannelLayoutTag), mASBD is \(item.mASBD)")
}
closeFile(fd: fd)
}
|
55b27c307b0e03ab71bc0ef989775278
| 33.34 | 155 | 0.618521 | false | false | false | false |
amagain/Typhoon-Swift-Example
|
refs/heads/master
|
PocketForecastTests/Integration/WeatherClientTests.swift
|
apache-2.0
|
3
|
////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import PocketForecast
public class WeatherClientTests : XCTestCase {
var weatherClient: WeatherClient!
public override func setUp() {
let assembly = ApplicationAssembly().activate()
let configurer = TyphoonConfigPostProcessor()
configurer.useResourceWithName("Configuration.plist")
assembly.attachPostProcessor(configurer)
self.weatherClient = assembly.coreComponents.weatherClient() as! WeatherClient
}
public func test_it_receives_a_wather_report_given_a_valid_city() {
var receivedReport : WeatherReport?
self.weatherClient.loadWeatherReportFor("Manila", onSuccess: {
(weatherReport) in
receivedReport = weatherReport
}, onError: {
(message) in
println("Unexpected error: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedReport != nil
}, andPerformTests: {
println(String(format: "Got report: %@", receivedReport!))
})
}
public func test_it_invokes_error_block_given_invalid_city() {
var receivedMessage : String?
self.weatherClient.loadWeatherReportFor("Foobarville", onSuccess: nil, onError: {
(message) in
receivedMessage = message
println("Got message: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedMessage == "Unable to find any matching weather location to the query submitted!"
})
}
}
|
0321de8e326e191a33ba5bbf9f7dfcd6
| 28.333333 | 108 | 0.543182 | false | true | false | false |
googleprojectzero/fuzzilli
|
refs/heads/main
|
Sources/Fuzzilli/Base/Contributor.swift
|
apache-2.0
|
1
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Something that contributes to the creation of a program.
/// This class is used to compute detailed statistics about correctness and timeout rates as well as the number of interesting or crashing programs generated, etc.
public class Contributor {
// Number of valid programs produced (i.e. programs that run to completion)
private var validSamples = 0
// Number of interesting programs produces (i.e. programs that triggered new interesting behavior). All interesting programs are also valid.
private var interestingSamples = 0
// Number of invalid programs produced (i.e. programs that raised an exception or timed out)
private var invalidSamples = 0
// Number of produced programs that resulted in a timeout.
private var timedOutSamples = 0
// Number of crashing programs produced.
private var crashingSamples = 0
// Number of times this instance failed to generate/mutate code.
private var failures = 0
// Total number of instructions added to programs by this contributor.
private var totalInstructionProduced = 0
func generatedValidSample() {
validSamples += 1
}
func generatedInterestingSample() {
interestingSamples += 1
}
func generatedInvalidSample() {
invalidSamples += 1
}
func generatedTimeOutSample() {
timedOutSamples += 1
}
func generatedCrashingSample() {
crashingSamples += 1
}
func addedInstructions(_ n: Int) {
totalInstructionProduced += n
}
func failedToGenerate() {
failures += 1
}
public var crashesFound: Int {
return crashingSamples
}
public var totalSamples: Int {
return validSamples + interestingSamples + invalidSamples + timedOutSamples + crashingSamples
}
public var correctnessRate: Double {
guard totalSamples > 0 else { return 1.0 }
return Double(validSamples + interestingSamples) / Double(totalSamples)
}
public var interestingSamplesRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(interestingSamples) / Double(totalSamples)
}
public var timeoutRate: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(timedOutSamples) / Double(totalSamples)
}
public var failureRate: Double {
let totalAttempts = totalSamples + failures
guard totalAttempts > 0 else { return 0.0 }
return Double(failures) / Double(totalAttempts)
}
// Note: even if for example a CodeGenerator always generates exactly one instruction, this number may be
// slightly higher than one as the same CodeGenerator may run multiple times to generate one program.
public var avgNumberOfInstructionsGenerated: Double {
guard totalSamples > 0 else { return 0.0 }
return Double(totalInstructionProduced) / Double(totalSamples)
}
}
/// All "things" (Mutators, CodeGenerators, ProgramTemplates, ...) that contributed directly (i.e. not including parent programs) to the creation of a particular program.
public struct Contributors {
private var chain = [Contributor]()
public init() {}
public mutating func add(_ contributor: Contributor) {
// The chains should be pretty short, so a linear search is probably faster than using an additional Set.
if !chain.contains(where: { $0 === contributor}) {
chain.append(contributor)
}
}
public func generatedValidSample() {
chain.forEach { $0.generatedValidSample() }
}
public func generatedInterestingSample() {
chain.forEach { $0.generatedInterestingSample() }
}
public func generatedInvalidSample() {
chain.forEach { $0.generatedInvalidSample() }
}
public func generatedCrashingSample() {
chain.forEach { $0.generatedCrashingSample() }
}
public func generatedTimeOutSample() {
chain.forEach { $0.generatedTimeOutSample() }
}
public mutating func removeAll() {
chain.removeAll()
}
}
|
fc46af64146d78e8ac13c8a1ca1e7c0b
| 32.978102 | 170 | 0.690226 | false | false | false | false |
daaavid/TIY-Assignments
|
refs/heads/master
|
14--High-Voltage/High-Voltage/High-Voltage/Brainerino.swift
|
cc0-1.0
|
1
|
//
// CalculatorBrainerino.swift
// High-Voltage
//
// Created by david on 10/22/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class Brainerino
{
var watts: Float = 0.0
var volts: Float = 0.0
var amps: Float = 0.0
var ohms: Float = 0.0
var wattStr = ""
var voltStr = ""
var ampStr = ""
var ohmStr = ""
var calculateFinished = false
func calculate()
{
if watts != 0 && amps != 0
{
ohms = ohmsCalc(3)
volts = voltsCalc(2)
}
else if watts != 0 && volts != 0
{
ohms = ohmsCalc(2)
amps = ampsCalc(2)
}
else if watts != 0 && ohms != 0
{
amps = ampsCalc(2)
volts = voltsCalc(3)
}
else if volts != 0 && amps != 0
{
ohms = ohmsCalc(1)
watts = wattsCalc(1)
}
else if volts != 0 && ohms != 0
{
watts = wattsCalc(2)
amps = ampsCalc(1)
}
else if ohms != 0 && amps != 0
{
watts = wattsCalc(3)
volts = voltsCalc(1)
}
wattStr = String(watts)
voltStr = String(volts)
ampStr = String(amps)
ohmStr = String(ohms)
calculateFinished = true
}
func ohmsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
ohms = volts / amps
case 2:
ohms = (volts * volts) / watts
case 3:
ohms = watts / (amps * amps)
default:
ohms = 1000000
}
return ohms
}
func ampsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
amps = volts / ohms
case 2:
amps = watts / volts
case 3:
amps = Float(sqrt(Double(watts) / Double(ohms)))
default:
amps = 1000000
}
return amps
}
func voltsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
volts = amps * ohms
case 2:
volts = watts / amps
case 3:
volts = Float(sqrt(Double(watts) * Double(ohms)))
default:
volts = 1000000
}
return volts
}
func wattsCalc(cv: Int) -> Float
{
switch cv
{
case 1:
watts = volts * amps
case 2:
watts = (volts * volts) / ohms
case 3:
watts = (amps * amps) * ohms
default:
watts = 1000000
}
return watts
}
func reset()
{
watts = 0
volts = 0
amps = 0
ohms = 0
wattStr = ""
voltStr = ""
ampStr = ""
ohmStr = ""
}
}
|
663262ac257915832ccc8c6afdf60106
| 19.190141 | 61 | 0.417306 | false | false | false | false |
mgadda/zig
|
refs/heads/master
|
Sources/zig/Shell.swift
|
mit
|
1
|
//
// Shell.swift
// zigPackageDescription
//
// Created by Matt Gadda on 11/14/17.
//
import Foundation
struct Shell {
/// Run command at `path` with `arguments`. `run` does not use `Process`
/// because it does not correctly set up `STDIN`, `STDOUT`, `STDERR` for the
/// child process. Instead it uses posix_spawn directly.
static func run(path: String, arguments: [String]) throws {
var pid: pid_t = pid_t()
let cPath = strdup("/usr/bin/env")
let cArgs = ([path] + arguments).map { $0.withCString { strdup($0) }} + [nil]
let cEnv = ProcessInfo.processInfo.environment.map { (key, value) in strdup("\(key)=\(value)") } + [nil]
defer {
free(cPath)
cEnv.forEach { free($0) }
cArgs.forEach { free($0) }
}
#if os(macOS)
var fileActions: posix_spawn_file_actions_t? = nil
#else
var fileActions = posix_spawn_file_actions_t()
#endif
posix_spawn_file_actions_init(&fileActions)
// posix_spawn_file_actions_addinherit_np(&fileActions, STDIN_FILENO)
posix_spawn_file_actions_adddup2(&fileActions, 0, 0)
posix_spawn_file_actions_adddup2(&fileActions, 1, 1)
posix_spawn_file_actions_adddup2(&fileActions, 2, 2)
guard posix_spawn(&pid, cPath, &fileActions, nil, cArgs, cEnv) != -1 else {
throw ZigError.genericError("Failed to execute \(path)")
}
var res: Int32 = 0
waitpid(pid, &res, 0)
guard res == 0 else {
throw ZigError.shellError(res)
}
}
static func replace(with path: String, arguments: [String]) throws {
let cPath = path.withCString { strdup($0) }
let cArgs = arguments.map { $0.withCString { strdup($0) }} + [nil]
guard execv(cPath, cArgs) != -1 else {
let scriptName = String(describing: path.split(separator: "/").last)
throw ZigError.genericError("Failed to load \(scriptName) with error \(errno)")
}
}
}
|
fa6e6b19db6cf2f42f56d618e4b25a93
| 31.067797 | 108 | 0.634778 | false | false | false | false |
renzifeng/ZFZhiHuDaily
|
refs/heads/master
|
ZFZhiHuDaily/Other/Extension/SwiftExtension/UIKit/UINaVigationBar/NavigationBarExtension.swift
|
apache-2.0
|
1
|
//
// NavigationBarExtension.swift
// ParallaxHeaderView
//
// Created by wl on 15/11/5.
// Copyright © 2015年 wl. All rights reserved.
//
import UIKit
var key: String = "coverView"
extension UINavigationBar {
/// 定义的一个计算属性,如果可以我更希望直接顶一个存储属性。它用来返回和设置我们需要加到
/// UINavigationBar上的View
var coverView: UIView? {
get {
//这句的意思大概可以理解为利用key在self中取出对应的对象,如果没有key对应的对象就返回niu
return objc_getAssociatedObject(self, &key) as? UIView
}
set {
//与上面对应是重新设置这个对象,最后一个参数如果学过oc的话很好理解,就是代表这个newValue的属性
//OBJC_ASSOCIATION_RETAIN_NONATOMIC意味着:strong,nonatomic
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func setMyBackgroundColor(color: UIColor) {
if self.coverView != nil {
self.coverView!.backgroundColor = color
}else {
self.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.shadowImage = UIImage()
let view = UIView(frame: CGRectMake(0, -20, UIScreen.mainScreen().bounds.size.width, CGRectGetHeight(self.bounds) + 20))
view.userInteractionEnabled = false
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
self.insertSubview(view, atIndex: 0)
view.backgroundColor = color
self.coverView = view
}
}
func setMyBackgroundColorAlpha(alpha: CGFloat) {
guard let coverView = self.coverView else {
return
}
self.coverView!.backgroundColor = coverView.backgroundColor?.colorWithAlphaComponent(alpha)
}
}
|
512b0321866f348d11c92537e455407d
| 30.333333 | 132 | 0.624113 | false | false | false | false |
beepscore/WebKitty
|
refs/heads/master
|
WebKitty/FileUtils.swift
|
mit
|
1
|
//
// FileUtils.swift
// WebKitty
//
// Created by Steve Baker on 4/22/15.
// Copyright (c) 2015 Beepscore LLC. All rights reserved.
//
// In general, Apple recommends references files via NSURL instead of NSString path.
// For more info see Apple NSFileManager and NSURL class references.
import Foundation
class FileUtils: NSObject {
/**
* If source file exists at destination, replaces it.
* http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file
*/
class func duplicateFileToTempDir(_ fileUrl: URL?) -> URL? {
if fileUrl == nil {
return nil
}
let fileMgr = FileManager.default
let tempPath = NSTemporaryDirectory()
let tempWwwUrl = URL(fileURLWithPath: tempPath).appendingPathComponent("www")
do {
try fileMgr.createDirectory(at: tempWwwUrl, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error createDirectoryAtURL at \(tempWwwUrl)")
print(error.debugDescription)
return nil
}
let pathComponent = fileUrl!.lastPathComponent
let destinationUrl = tempWwwUrl.appendingPathComponent(pathComponent)
let _ = deleteFileAtUrl(destinationUrl)
do {
try fileMgr.copyItem(at: fileUrl!, to: destinationUrl)
} catch let error as NSError {
print("copyItemAtURL error \(error.localizedDescription)")
return nil
}
return destinationUrl
}
/** If file exists, deletes it.
return true if fileUrl was nil or file didn't exist or file was deleted
return false if file existed but couldn't delete it
*/
class func deleteFileAtUrl(_ fileUrl : URL?) -> Bool {
let fileMgr = FileManager.default
if let url = fileUrl {
if fileMgr.fileExists(atPath: url.path) {
do {
try fileMgr.removeItem(at: url)
return true
} catch let error as NSError {
print("Error removeItemAtURL at \(url)")
print(error.debugDescription)
return false
}
} else {
// file doesn't exist
return true
}
} else {
// fileURL nil
return true
}
}
func fileNamesAtBundleResourcePath() -> [String] {
// Returns list of all files in bundle resource path
// NOTE:
// I tried writing a function to enumerate the contents of a subdirectory
// such as webViewResources
// func fileNamesInSubdirectory(subpath: String?) -> [String]
// It didn't work.
// Apparently the bundle contains many files at the same heirarchical level,
// doesn't keep index.html and style.css in a subdirectory
// http://stackoverflow.com/questions/25285016/swift-iterate-through-files-in-a-folder-and-its-subfolders?lq=1
var fileNames : [String] = []
let bundle = Bundle.main
// let bundlePath = bundle.bundlePath
// let sourcePath = resourcePath!.stringByAppendingPathComponent(subpath!)
let resourcePath = bundle.resourcePath
let fileManager = FileManager()
// this returns empty
// if let enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(sourcePath) {
// this returns many files, could filter by file extension
if let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: resourcePath!) {
for element in enumerator.allObjects {
fileNames.append(element as! String)
}
}
return fileNames
}
func fileNamesAtURL() -> [String] {
let bundle = Bundle.main
guard let resourcePath = bundle.resourcePath else {
return []
}
var urlComponents = URLComponents()
urlComponents.scheme = "file"
urlComponents.host = ""
urlComponents.path = resourcePath
let resourceURL = urlComponents.url
let fileManager = FileManager()
var lastPathComponents : [String] = []
if let enumerator = fileManager.enumerator(at: resourceURL!,
includingPropertiesForKeys: nil,
options: .skipsSubdirectoryDescendants,
errorHandler: nil) {
for element in enumerator.allObjects {
lastPathComponents.append((element as! URL).lastPathComponent)
}
}
return lastPathComponents
}
func fileNamesWithExtensionHtml() -> [String] {
let bundle = Bundle.main
let urls = bundle.urls(forResourcesWithExtension: "html", subdirectory: "")
var lastPathComponents : [String] = []
for url in urls! {
lastPathComponents.append(url.lastPathComponent)
}
return lastPathComponents
}
}
|
56b258ddcb6ceed06ed15aa8af3b2b27
| 33.569536 | 118 | 0.583525 | false | false | false | false |
andersio/MantleData
|
refs/heads/master
|
MantleData/ReactiveArray.swift
|
mit
|
1
|
//
// ArraySet.swift
// MantleData
//
// Created by Anders on 13/1/2016.
// Copyright © 2016 Anders. All rights reserved.
//
import Foundation
import ReactiveSwift
import enum Result.NoError
private struct BatchingState<Element> {
var seq = 0
var removals: [Int] = []
var insertions: [(index: Int?, value: Element)] = []
var updates: Set<Int> = []
}
final public class ReactiveArray<E> {
public var name: String? = nil
public let events: Signal<SectionedCollectionEvent, NoError>
fileprivate let eventObserver: Observer<SectionedCollectionEvent, NoError>
fileprivate var storage: [E] = []
private var batchingState: BatchingState<E>?
public init<S: Sequence>(_ content: S) where S.Iterator.Element == E {
(events, eventObserver) = Signal.pipe()
storage = Array(content)
}
public required convenience init() {
self.init([])
}
/// Batch mutations to the array for one collection changed event.
///
/// Removals respect the old indexes, while insertions and update respect
/// the order after the removals are applied.
///
/// - parameters:
/// - action: The action which mutates the array.
public func batchUpdate(action: () -> Void) {
batchingState = BatchingState()
action()
if let state = batchingState {
apply(state)
batchingState = nil
}
}
private func apply(_ state: BatchingState<E>) {
let removals = state.removals.sorted(by: >)
var updates = state.updates.sorted(by: >)
for index in removals {
storage.remove(at: index)
for i in updates.indices {
if updates[i] < index {
break
} else {
assert(updates[i] != index, "Attempt to update an element to be deleted.")
updates[i] -= 1
}
}
}
let insertions = state.insertions
var insertedRows = [Int]()
insertedRows.reserveCapacity(insertions.count)
for (index, value) in insertions {
let index = index ?? storage.endIndex
storage.insert(value, at: index)
for i in insertedRows.indices {
if insertedRows[i] >= index {
insertedRows[i] += 1
}
}
insertedRows.append(index)
for i in updates.indices.reversed() {
if updates[i] < index {
break
} else {
assert(updates[i] != index, "Attempt to update a element to be inserted.")
updates[i] += 1
}
}
}
let changes = SectionedCollectionChanges(deletedRows: removals.map { IndexPath(row: $0, section: 0) },
insertedRows: insertedRows.map { IndexPath(row: $0, section: 0) },
updatedRows: updates.map { IndexPath(row: $0, section: 0) })
eventObserver.send(value: .updated(changes))
}
public func append(_ element: E) {
_insert(element, at: nil)
}
public func append<S: Sequence>(contentsOf elements: S) where S.Iterator.Element == E {
for element in elements {
_insert(element, at: nil)
}
}
public func insert(_ element: E, at index: Int) {
_insert(element, at: index)
}
private func _insert(_ element: E, at index: Int?) {
if batchingState == nil {
let index = index ?? storage.endIndex
storage.insert(element, at: index)
let changes = SectionedCollectionChanges(insertedRows: [IndexPath(row: index, section: 0)])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.insertions.append((index, element))
}
}
@discardableResult
public func remove(at index: Int) -> E {
if batchingState == nil {
let value = storage.remove(at: index)
let changes = SectionedCollectionChanges(deletedRows: [IndexPath(row: index, section: 0)])
eventObserver.send(value: .updated(changes))
return value
} else {
batchingState!.removals.append(index)
return storage[index]
}
}
public func removeAll() {
storage.removeAll()
batchingState = nil
let changes = SectionedCollectionChanges(deletedSections: [0])
eventObserver.send(value: .updated(changes))
}
public func move(elementAt index: Int, to newIndex: Int) {
if batchingState == nil {
let value = storage.remove(at: index)
storage.insert(value, at: newIndex)
let changes = SectionedCollectionChanges(movedRows: [(from: IndexPath(row: index, section: 0),
to: IndexPath(row: newIndex, section: 0))])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.removals.append(index)
batchingState!.insertions.append((newIndex, storage[index]))
}
}
public subscript(position: Int) -> E {
get {
return storage[position]
}
set {
storage[position] = newValue
if batchingState == nil {
let changes = SectionedCollectionChanges(updatedRows: [IndexPath(row: position, section: 0)])
eventObserver.send(value: .updated(changes))
} else {
batchingState!.updates.insert(position)
}
}
}
deinit {
eventObserver.sendCompleted()
}
}
extension ReactiveArray: SectionedCollection {
public typealias Index = IndexPath
public var sectionCount: Int {
return 0
}
public var startIndex: IndexPath {
return IndexPath(row: storage.startIndex, section: 0)
}
public var endIndex: IndexPath {
return IndexPath(row: storage.endIndex, section: 0)
}
public func index(after i: IndexPath) -> IndexPath {
return IndexPath(row: i.row + 1, section: 0)
}
public func index(before i: IndexPath) -> IndexPath {
return IndexPath(row: i.row - 1, section: 0)
}
public subscript(row row: Int, section section: Int) -> E {
assert(section == 0, "ReactiveArray supports only one section.")
return storage[row]
}
public func sectionName(for section: Int) -> String? {
return nil
}
public func rowCount(for section: Int) -> Int {
return section > 0 ? 0 : storage.count
}
}
|
dd29bfc81789d429e21f5b64ee2e4238
| 24.446429 | 109 | 0.666491 | false | false | false | false |
CosmicMind/Samples
|
refs/heads/development
|
Projects/Programmatic/Grid/Grid/ViewController.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind 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 HOLDER 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 UIKit
import Material
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
prepareHorizontalExample()
prepareVerticalExample()
}
}
extension ViewController {
fileprivate func prepareHorizontalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.columns = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
fileprivate func prepareVerticalExample() {
let container = View()
container.backgroundColor = nil
container.shapePreset = .square
container.grid.axis.direction = .vertical
container.grid.interimSpacePreset = .interimSpace3
view.layout(container).center().left(20).right(20).height(300)
for _ in 0..<12 {
let v = View()
v.grid.rows = 1
v.backgroundColor = Color.blue.base
container.grid.views.append(v)
}
}
}
|
8f2f6da2b048e9093959759df7bf61ce
| 32.625 | 87 | 0.752045 | false | false | false | false |
citysite102/kapi-kaffeine
|
refs/heads/master
|
kapi-kaffeine/kapi-kaffeine/KPNomadDataModel.swift
|
mit
|
1
|
//
// KPNomadDataModel.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/26.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import ObjectMapper
class KPNomadDataModel: NSObject, Mappable, GMUClusterItem {
var identifier: String!
var name: String!
var city: String!
var wifi: NSNumber?
var seat: NSNumber?
var quite: NSNumber?
var tasty: NSNumber?
var cheap: NSNumber?
var music: NSNumber?
var url: String?
var address: String?
var latitude: String?
var longitude: String?
var limitedTime: String?
var socket: String?
var standingDesk: String?
var mrt: String?
var openTime: String?
var usableFeatureCount: Int? {
get {
var count:Int = 0
count += self.wifi?.intValue == 0 ? 0 : 1;
count += self.seat?.intValue == 0 ? 0 : 1;
count += self.quite?.intValue == 0 ? 0 : 1;
count += self.tasty?.intValue == 0 ? 0 : 1;
count += self.cheap?.intValue == 0 ? 0 : 1;
count += self.music?.intValue == 0 ? 0 : 1;
return count
}
}
var score: Double? {
get {
var sum = 0.0;
sum += (self.wifi?.doubleValue) ?? 0;
sum += (self.seat?.doubleValue) ?? 0;
sum += (self.quite?.doubleValue) ?? 0;
sum += (self.tasty?.doubleValue) ?? 0;
sum += (self.cheap?.doubleValue) ?? 0;
sum += (self.music?.doubleValue) ?? 0;
return sum/Double(self.usableFeatureCount!)
}
}
var position: CLLocationCoordinate2D {
get {
if let latstr = self.latitude, let latitude = Double(latstr),
let longstr = self.longitude, let longitude = Double(longstr) {
return CLLocationCoordinate2DMake(latitude, longitude)
}
return CLLocationCoordinate2DMake(-90, 0)
}
}
required init?(map: Map) {
}
func mapping(map: Map) {
identifier <- map["identifier"]
name <- map["name"]
city <- map["city"]
wifi <- map["wifi"]
seat <- map["seat"]
quite <- map["quite"]
tasty <- map["tasty"]
cheap <- map["cheap"]
music <- map["music"]
url <- map["url"]
address <- map["address"]
latitude <- map["latitude"]
longitude <- map["longitude"]
limitedTime <- map["limited_time"]
socket <- map["socket"]
standingDesk <- map["standing_desk"]
mrt <- map["mrt"]
openTime <- map["open_time"]
}
}
|
83fc4e83e51b4b1a8102e99462c8ed49
| 29.414141 | 79 | 0.466955 | false | false | false | false |
aahmedae/blitz-news-ios
|
refs/heads/master
|
Blitz News/Model/Model.swift
|
mit
|
1
|
//
// Model.swift
// Blitz News
//
// Created by Asad Ahmed on 5/13/17.
// Contains classes used to represent the parsed JSON data from the NewsAPI service
//
import Foundation
// Represents a single news item
class NewsItem
{
var newsTitle = "Title"
var newsDescription = "Description"
var sourceName = "Source Name"
var imageURL = "http://www.google.com"
var contentURL = "http://www.google.com"
}
|
a236ef749e375a88d2e15a7ef5630f16
| 20.35 | 84 | 0.681499 | false | false | false | false |
frograin/FluidValidator
|
refs/heads/master
|
Pod/Classes/Core/FailMessage.swift
|
mit
|
1
|
//
// FailMessage.swift
// TestValidator
//
// Created by FrogRain on 31/01/16.
// Copyright © 2016 FrogRain. All rights reserved.
//
import Foundation
open class FailMessage : NSObject {
open var summary:ErrorMessage
open var localizedSubject:String?
open var errors:Array<ErrorMessage>
fileprivate var opaqueDict:Dictionary<String, FailMessage>
override init() {
self.summary = ErrorMessage()
self.errors = Array<ErrorMessage>()
self.opaqueDict = Dictionary<String, FailMessage>()
super.init()
}
open func failingFields () -> [String] {
return self.opaqueDict.keys.map { (key) -> String in
key
}
}
func setObject(_ object:FailMessage, forKey:String) {
self.opaqueDict[forKey] = object;
}
override open func value(forKeyPath keyPath: String) -> Any? {
let dict = self.opaqueDict as NSDictionary
return dict.value(forKeyPath: keyPath) as? FailMessage
}
open func failMessageForPath(_ keyPath: String) -> FailMessage? {
return self.value(forKeyPath: keyPath) as? FailMessage
}
}
|
7dc065c3992057898bb97be32e82c3b9
| 25.044444 | 69 | 0.633106 | false | false | false | false |
TENDIGI/Obsidian-iOS-SDK
|
refs/heads/master
|
Obsidian-iOS-SDK/ResourceCodingWrapper.swift
|
mit
|
1
|
//
// CodingWrapper.swift
// ObsidianSDK
//
// Created by Nick Lee on 9/27/15.
// Copyright © 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
@objc public final class ResourceCodingWrapper: NSObject, NSSecureCoding {
// MARK: Constants
private struct ResourceCodingWrapperConstants {
static let objectKey = "object"
static let headersKey = "headers"
static let caseSensitiveKey = "caseSensitive"
}
// MARK: Private Properties
internal let mapper: Mapper!
// MARK: Initialization
internal init(mapper: Mapper) {
self.mapper = mapper
}
// MARK: NSCoding
/// :nodoc:
public init?(coder aDecoder: NSCoder) {
let headers = aDecoder.decodeObjectForKey(ResourceCodingWrapperConstants.headersKey) as? [String : String]
let caseSensitive = aDecoder.decodeBoolForKey(ResourceCodingWrapperConstants.caseSensitiveKey)
if let object = aDecoder.decodeObjectForKey(ResourceCodingWrapperConstants.objectKey) as? [String : AnyObject] {
mapper = Mapper(object: object, requestHeaders: headers, caseSensitive: caseSensitive)
} else {
mapper = nil
}
super.init()
if mapper == nil {
return nil
}
}
/// :nodoc:
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(mapper.object, forKey: ResourceCodingWrapperConstants.objectKey)
aCoder.encodeBool(mapper.caseSensitive, forKey: ResourceCodingWrapperConstants.caseSensitiveKey)
if let headers = mapper.headers?.unbox.object {
aCoder.encodeObject(headers, forKey: ResourceCodingWrapperConstants.headersKey)
}
}
/// :nodoc:
public static func supportsSecureCoding() -> Bool {
return true
}
}
|
5ce1b18cf71d311ff4eded326cb78ceb
| 26.338028 | 120 | 0.624936 | false | false | false | false |
vishalvshekkar/realmDemo
|
refs/heads/master
|
RealmDemo/ContactsTableViewCell.swift
|
mit
|
1
|
//
// ContactsTableViewCell.swift
// RealmDemo
//
// Created by Vishal V Shekkar on 10/08/16.
// Copyright © 2016 Vishal. All rights reserved.
//
import UIKit
class ContactsTableViewCell: UITableViewCell {
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var otherLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
leftImageView.layer.cornerRadius = 26.5
leftImageView.layer.borderColor = UIColor(colorType: .PinkishRed).CGColor
leftImageView.layer.borderWidth = 1
self.backgroundColor = UIColor.clearColor()
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if highlighted {
self.backgroundColor = UIColor(colorType: .PinkishRedWith15Alpha)
} else {
self.backgroundColor = UIColor.clearColor()
}
}
}
|
4aad23da604629a73b65388f0c98c40f
| 27.941176 | 81 | 0.676829 | false | false | false | false |
QuarkX/Quark
|
refs/heads/master
|
Sources/Quark/OpenSSL/IO.swift
|
mit
|
1
|
import COpenSSL
public enum SSLIOError: Error {
case io(description: String)
case shouldRetry(description: String)
case unsupportedMethod(description: String)
}
public class IO {
public enum Method {
case memory
var method: UnsafeMutablePointer<BIO_METHOD> {
switch self {
case .memory:
return BIO_s_mem()
}
}
}
var bio: UnsafeMutablePointer<BIO>?
public init(method: Method = .memory) throws {
initialize()
bio = BIO_new(method.method)
if bio == nil {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
public convenience init(buffer: Data) throws {
try self.init()
try write(buffer, length: buffer.count)
}
// TODO: crash???
// deinit {
// BIO_free(bio)
// }
public var pending: Int {
return BIO_ctrl_pending(bio)
}
public var shouldRetry: Bool {
return (bio!.pointee.flags & BIO_FLAGS_SHOULD_RETRY) != 0
}
@discardableResult
public func write(_ data: Data, length: Int) throws -> Int {
let result = data.withUnsafeBytes {
BIO_write(bio, $0, Int32(length))
}
if result < 0 {
if shouldRetry {
throw SSLIOError.shouldRetry(description: lastSSLErrorDescription)
} else {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
return Int(result)
}
public func read(into buffer: inout Data, length: Int) throws -> Int {
let result = buffer.withUnsafeMutableBytes {
BIO_read(bio, $0, Int32(length))
}
if result < 0 {
if shouldRetry {
throw SSLIOError.shouldRetry(description: lastSSLErrorDescription)
} else {
throw SSLIOError.io(description: lastSSLErrorDescription)
}
}
return Int(result)
}
}
|
951aa19d1d54c1a15cb66bf457d5254d
| 19.402439 | 74 | 0.674836 | false | false | false | false |
pablogsIO/MadridShops
|
refs/heads/master
|
MadridShopsTests/ExecuteOnce/SetExecuteOnceTest.swift
|
mit
|
1
|
//
// SetExecuteOnceTest.swift
// MadridShopsTests
//
// Created by Pablo García on 19/09/2017.
// Copyright © 2017 KC. All rights reserved.
//
import XCTest
@testable import MadridShops
class SetExecuteOnceTest: XCTestCase {
let defaults = UserDefaults.standard
override func setUp() {
super.setUp()
defaults.removeObject(forKey: Constants.executeOnceShopKey)
defaults.removeObject(forKey: Constants.executeOnceActivityKey)
defaults.removeObject(forKey: Constants.executeOnceServiceKey)
defaults.synchronize()
}
func testSetExecuteOnce(){
let setExecuteOnce = SetExecuteOnceInteractorImpl()
setExecuteOnce.execute(key: Constants.executeOnceShopKey)
var value = defaults.string(forKey: Constants.executeOnceShopKey)
XCTAssert(value == Constants.executeOnceValue)
value = ""
value = defaults.string(forKey: Constants.executeOnceActivityKey)
XCTAssert(value == Constants.executeOnceValue)
value = ""
value = defaults.string(forKey: Constants.executeOnceServiceKey)
XCTAssert(value == Constants.executeOnceValue)
}
}
|
4c83bd7513c4dcd6216c353a4f81b577
| 22.166667 | 67 | 0.741906 | false | true | false | false |
LimCrazy/SwiftProject3.0-Master
|
refs/heads/master
|
SwiftPreject-Master/SwiftPreject-Master/Class/CustomNavigationVC.swift
|
apache-2.0
|
1
|
//
// CustomNavigationVC.swift
// SwiftPreject-Master
//
// Created by lim on 2016/12/11.
// Copyright © 2016年 Lim. All rights reserved.
//
import UIKit
class CustomNavigationVC: UINavigationController {
let imageExtension = YM_ImageExtension()
override func viewDidLoad() {
super.viewDidLoad()
// setup(bar: self)
}
public func setup(bar:UINavigationController) -> () {
//黑色导航栏
bar.navigationBar.barTintColor = kNavColor
//修改导航栏按钮颜色和文字大小
//bar.navigationBar.tintColor = UIColor.white
let dict = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.systemFont(ofSize: 20)]
//修改导航栏文字颜色
bar.navigationBar.titleTextAttributes = dict
//修改状态栏文字白色
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
//透明导航栏
public func setTranslucent(bar:UINavigationController) -> () {
//设置标题颜色
let dict = [NSForegroundColorAttributeName:UIColor.clear,NSFontAttributeName:UIFont.systemFont(ofSize: 20)]
//修改导航栏文字颜色
bar.navigationBar.titleTextAttributes = dict
bar.navigationBar.setBackgroundImage(UIImage(), for:.default)
//设置导航栏按钮颜色
bar.navigationBar.tintColor = UIColor.black
//设置背景空图片
bar.navigationBar.shadowImage = UIImage()
//导航栏透明
bar.navigationBar.isTranslucent = true
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
if self.viewControllers.count > 0 {
let vc = self.viewControllers[self.viewControllers.count - 1]
print(vc)
//自定义返回按钮
let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil)
vc.navigationItem.backBarButtonItem = backBtn
}
super.pushViewController(viewController, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
106870c8061605ca7efd967b5efd03dd
| 32.121212 | 115 | 0.645471 | false | false | false | false |
nsagora/validation-toolkit
|
refs/heads/main
|
Tests/Constraints/ConstraintBuilderTests.swift
|
mit
|
1
|
import XCTest
@testable import Peppermint
class ConstraintBuilderTests: XCTestCase {
func testItCanBuildWithBlock() {
let varBool = false
let varInt = 2
@ConstraintBuilder<String, FakeError> var constraints: [AnyConstraint<String, FakeError>] {
RequiredConstraint { .Ordered(1) }
RequiredConstraint { .Ordered(2) }
BlockConstraint {
$0.count == 6
} errorBuilder: {
.Ordered(3)
}
if varBool == false {
RequiredConstraint { .Ordered(4) }
RequiredConstraint { .Ordered(5) }
RequiredConstraint { .Ordered(6) }
}
else {
RequiredConstraint { .Ordered(-1) }
}
if varBool == true {
RequiredConstraint { .Ordered(-1) }
}
else {
RequiredConstraint { .Ordered(7) }
RequiredConstraint { .Ordered(8)}
}
for _ in 1...3 {
RequiredConstraint { .Ordered(9) }
}
if varInt % 2 == 0 {
RequiredConstraint { .Ordered(10) }
}
if varInt % 3 == 0 {
RequiredConstraint { .Ordered(-1) }
}
if #available(*) {
RequiredConstraint { .Ordered(11) }
}
else {
RequiredConstraint { .Ordered(-1) }
}
}
let sut = GroupConstraint<String, FakeError>(constraints: constraints)
let result = sut.evaluate(with: "")
let expected = Summary<FakeError>(errors: [
.Ordered(1),
.Ordered(2),
.Ordered(3),
.Ordered(4),
.Ordered(5),
.Ordered(6),
.Ordered(7),
.Ordered(8),
.Ordered(9),
.Ordered(9),
.Ordered(9),
.Ordered(10),
.Ordered(11),
])
switch result {
case .failure(let summary):
XCTAssertEqual(expected, summary)
default: XCTFail()
}
}
}
|
4b0ccb9809c9e5f3380e35429ba041cf
| 26.807229 | 99 | 0.425043 | false | true | false | false |
tilltue/FSCalendar
|
refs/heads/custom
|
Example-Swift/SwiftExample/InterfaceBuilderViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SwiftExample
//
// Created by Wenchao Ding on 9/3/15.
// Copyright (c) 2015 wenchao. All rights reserved.
//
import UIKit
class InterfaceBuilderViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate {
@IBOutlet weak var calendar: FSCalendar!
@IBOutlet weak var calendarHeightConstraint: NSLayoutConstraint!
private let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
return formatter
}()
private let gregorian: NSCalendar! = NSCalendar(calendarIdentifier:NSCalendar.Identifier.gregorian)
let datesWithCat = ["2015/05/05","2015/06/05","2015/07/05","2015/08/05","2015/09/05","2015/10/05","2015/11/05","2015/12/05","2016/01/06",
"2016/02/06","2016/03/06","2016/04/06","2016/05/06","2016/06/06","2016/07/06"]
override func viewDidLoad() {
super.viewDidLoad()
self.calendar.appearance.caseOptions = [.headerUsesUpperCase,.weekdayUsesUpperCase]
self.calendar.select(self.formatter.date(from: "2015/10/10")!)
// self.calendar.scope = .week
self.calendar.scopeGesture.isEnabled = true
// calendar.allowsMultipleSelection = true
// Uncomment this to test month->week and week->month transition
/*
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.calendar.setScope(.Week, animated: true)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.calendar.setScope(.Month, animated: true)
}
}
*/
}
func minimumDate(for calendar: FSCalendar) -> Date {
return self.formatter.date(from: "2015/01/01")!
}
func maximumDate(for calendar: FSCalendar) -> Date {
return self.formatter.date(from: "2016/10/31")!
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let day: Int! = self.gregorian.component(.day, from: date)
return day % 5 == 0 ? day/5 : 0;
}
func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
NSLog("change page to \(self.formatter.string(from: calendar.currentPage))")
}
func calendar(_ calendar: FSCalendar, didSelect date: Date) {
NSLog("calendar did select date \(self.formatter.string(from: date))")
}
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
calendarHeightConstraint.constant = bounds.height
view.layoutIfNeeded()
}
func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {
let day: Int! = self.gregorian.component(.day, from: date)
return [13,24].contains(day) ? UIImage(named: "icon_cat") : nil
}
}
|
eb2059db155ec0c1468f5bf32b0c9296
| 36.658228 | 141 | 0.641345 | false | false | false | false |
wesbillman/JSONFeed
|
refs/heads/master
|
JSONFeedTests/AttachmentTests.swift
|
mit
|
1
|
//
// Created by Wes Billman on 5/19/17.
// Copyright © 2017 wesbillman. All rights reserved.
//
import XCTest
@testable import JSONFeed
class AttachmentTests: XCTestCase {
let url = "https://jsonfeed.org/version/1"
let text = "Some Text"
let size = 120
let duration = 60
func testInvalidURL() {
XCTAssertThrowsError(try Attachment(json: [:])) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidURL)
}
}
func testInvalidMimeType() {
XCTAssertThrowsError(try Attachment(json: ["url": url])) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidMimeType)
}
}
func testValidAttachment() {
let json: [String : Any] = [
"url": url,
"mime_type": text,
"title": text,
"size_in_bytes": size,
"duration_in_seconds": duration,
]
let attachment = try? Attachment(json: json)
XCTAssertEqual(attachment?.url.absoluteString, url)
XCTAssertEqual(attachment?.mimeType, text)
XCTAssertEqual(attachment?.title, text)
XCTAssertEqual(attachment?.bytes, size)
XCTAssertEqual(attachment?.seconds, duration)
}
}
|
f8cee476f9b1854574022ffdab288041
| 28.904762 | 82 | 0.618631 | false | true | false | false |
qaisjp/mta-luac-osx
|
refs/heads/develop
|
MTA Lua Compiler/FileManagerViewController.swift
|
apache-2.0
|
1
|
//
// FileManagerViewController.swift
// MTA Lua Compiler
//
// Created by Qais Patankar on 02/11/2014.
// Copyright (c) 2014 qaisjp. All rights reserved.
//
import Cocoa
class FileManagerViewController: NSViewController {
var urls: Array<NSURL>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onClosePressed(sender: AnyObject) {
self.dismissController(self)
if (urls != nil) {
(self.representedObject as MTAMainViewController).parameters = urls!
}
}
@IBOutlet weak var fileTableView: NSTableView!
@IBAction func onBrowseClick(sender: AnyObject) {
// Create the File Open Dialog class.
var panel:NSOpenPanel = NSOpenPanel();
panel.canChooseFiles = true;
panel.canChooseDirectories = false;
panel.title = "Select file(s) or folder(s) to compile";
panel.allowsMultipleSelection = true;
// Display the dialog. If the OK button was pressed, process the path
var buttonPressed:NSInteger = panel.runModal();
if ( buttonPressed == NSOKButton ) {
self.urls = panel.URLs as? Array<NSURL>
}
}
}
|
c130d462f8ca4d26fcfa8289bdd65d89
| 24.92 | 80 | 0.619599 | false | false | false | false |
MrSongzj/MSDouYuZB
|
refs/heads/master
|
MSDouYuZB/MSDouYuZB/Classes/Home/Presenter/FunnyPresenter.swift
|
mit
|
1
|
//
// FunnyPresenter.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/8/9.
// Copyright © 2017年 mrsong. All rights reserved.
//
import Foundation
class FunnyPresenter:
BaseTVCateVCDataSource
{
lazy var tvCateArr = [TVCate]()
func requestFunnyData(responseCallback: (() -> ())? = nil ) {
NetworkTools.get(urlString: "http://capi.douyucdn.cn/api/v1/getColumnRoom/3", parameters: ["limit": 30, "offset": 0]) { (result) in
// 将 result 转成字典
guard let responseData = result as? [String: Any] else { return }
// 获取字典里的 data 数据
guard let dataArray = responseData["data"] as? [[String: NSObject]] else { return }
// 遍历数组里的字典,转成 model 对象
let cate = TVCate()
for dict in dataArray {
cate.roomArr.append(TVRoom(dict: dict))
}
self.tvCateArr.append(cate)
// 回调
if let callback = responseCallback {
callback()
}
}
}
}
|
f999f6e0db7ad8c18f276775d016184b
| 29.205882 | 139 | 0.555015 | false | false | false | false |
eito/geometry-api-swift
|
refs/heads/master
|
Geometry/Geometry/MathUtils.swift
|
apache-2.0
|
1
|
//
// MathUtils.swift
// Geometry
//
// Created by Eric Ito on 10/25/15.
// Copyright © 2015 Eric Ito. All rights reserved.
//
import Foundation
final class MathUtils {
/**
The implementation of the Kahan summation algorithm. Use to get better
precision when adding a lot of values.
*/
final class KahanSummator {
/** The accumulated sum */
private var sum: Double = 0.0
private var compensation: Double = 0.0
/** the Base (the class returns sum + startValue) */
private var startValue: Double = 0.0
/**
initialize to the given start value. \param startValue_ The value to
be added to the accumulated sum.
*/
init(startValue: Double) {
self.startValue = startValue
reset()
}
/**
Resets the accumulated sum to zero. The getResult() returns
startValue_ after this call.
*/
func reset() {
sum = 0
compensation = 0
}
/** add a value. */
func add(v: Double) {
let y: Double = v - compensation
let t: Double = sum + y
let h: Double = t - sum
compensation = h - y
sum = t;
}
/** Subtracts a value. */
func sub(v: Double) {
add(-v)
}
/** add another summator. */
func add(/* const */ v: KahanSummator) {
let y: Double = (v.result() + v.compensation) - compensation
let t: Double = sum + y
let h: Double = t - sum
compensation = h - y
sum = t
}
/** Subtracts another summator. */
func sub(/* const */ v: KahanSummator) {
let y: Double = -(v.result() - v.compensation) - compensation
let t: Double = sum + y
let h: Double = t - sum
compensation = h - y
sum = t
}
/** Returns current value of the sum. */
func result() -> Double /* const */{
return startValue + sum
}
}
/** Returns one value with the sign of another (like copysign). */
class func copySign(x: Double, y: Double) -> Double {
return y >= 0.0 ? abs(x) : -abs(x)
}
/** Calculates sign of the given value. Returns 0 if the value is equal to 0. */
class func sign(value: Double) -> Int {
return value < 0 ? -1 : (value > 0) ? 1 : 0;
}
/** C fmod function. */
class func FMod(x: Double, y: Double) -> Double {
return x - floor(x / y) * y
}
/** Rounds double to the closest integer value. */
class func round(v: Double) -> Double {
return floor(v + 0.5)
}
class func sqr(v: Double) -> Double {
return v * v
}
/**
Computes interpolation between two values, using the interpolation factor t.
The interpolation formula is (end - start) * t + start.
However, the computation ensures that t = 0 produces exactly start, and t = 1, produces exactly end.
It also guarantees that for 0 <= t <= 1, the interpolated value v is between start and end.
*/
class func lerp(start_: Double, end_: Double,t: Double) -> Double {
// When end == start, we want result to be equal to start, for all t
// values. At the same time, when end != start, we want the result to be
// equal to start for t==0 and end for t == 1.0
// The regular formula end_ * t + (1.0 - t) * start_, when end_ ==
// start_, and t at 1/3, produces value different from start
var v: Double = 0
if t <= 0.5 {
v = start_ + (end_ - start_) * t
} else {
v = end_ - (end_ - start_) * (1.0 - t)
}
assert (t < 0 || t > 1.0 || (v >= start_ && v <= end_) || (v <= start_ && v >= end_) || NumberUtils.isNaN(start_) || NumberUtils.isNaN(end_))
return v
}
/**
Computes interpolation between two values, using the interpolation factor t.
The interpolation formula is (end - start) * t + start.
However, the computation ensures that t = 0 produces exactly start, and t = 1, produces exactly end.
It also guarantees that for 0 <= t <= 1, the interpolated value v is between start and end.
*/
class func lerp(start_: Point2D , end_: Point2D , t: Double, result: Point2D ) {
// When end == start, we want result to be equal to start, for all t
// values. At the same time, when end != start, we want the result to be
// equal to start for t==0 and end for t == 1.0
// The regular formula end_ * t + (1.0 - t) * start_, when end_ ==
// start_, and t at 1/3, produces value different from start
if t <= 0.5 {
result.x = start_.x + (end_.x - start_.x) * t
result.y = start_.y + (end_.y - start_.y) * t
} else {
result.x = end_.x - (end_.x - start_.x) * (1.0 - t)
result.y = end_.y - (end_.y - start_.y) * (1.0 - t)
}
assert (t < 0 || t > 1.0 || (result.x >= start_.x && result.x <= end_.x) || (result.x <= start_.x && result.x >= end_.x))
assert (t < 0 || t > 1.0 || (result.y >= start_.y && result.y <= end_.y) || (result.y <= start_.y && result.y >= end_.y))
}
class func lerp(start_x: Double, start_y: Double, end_x: Double, end_y: Double, t: Double, result: Point2D) {
// When end == start, we want result to be equal to start, for all t
// values. At the same time, when end != start, we want the result to be
// equal to start for t==0 and end for t == 1.0
// The regular formula end_ * t + (1.0 - t) * start_, when end_ ==
// start_, and t at 1/3, produces value different from start
if t <= 0.5 {
result.x = start_x + (end_x - start_x) * t
result.y = start_y + (end_y - start_y) * t
} else {
result.x = end_x - (end_x - start_x) * (1.0 - t)
result.y = end_y - (end_y - start_y) * (1.0 - t)
}
assert (t < 0 || t > 1.0 || (result.x >= start_x && result.x <= end_x) || (result.x <= start_x && result.x >= end_x))
assert (t < 0 || t > 1.0 || (result.y >= start_y && result.y <= end_y) || (result.y <= start_y && result.y >= end_y))
}
}
// MARK: Operators for KahanSummator
func +=(inout left: MathUtils.KahanSummator, right: Double) {
left.add(right)
}
func -=(inout left: MathUtils.KahanSummator, right: Double) {
left.add(-right)
}
func +=(inout left: MathUtils.KahanSummator, right: MathUtils.KahanSummator) {
left.add(right)
}
func -=(inout left: MathUtils.KahanSummator, right: MathUtils.KahanSummator) {
left.sub(right)
}
|
98a0584a6dd73e3fc2d285e522d2fa83
| 34.984293 | 149 | 0.521897 | false | false | false | false |
tectijuana/iOS
|
refs/heads/master
|
IvanMendoza/decimo.swift
|
mit
|
2
|
import Foundation
var a:Int=1
var b:Int=90
var x:Double=0
var seno:Double = 0
var coseno:Double = 0
for index in a...b {
seno=sin(Double(index))
print("seno \(index): ",seno)
coseno=cos(Double(index))
print("coseno \(index):",coseno)
}
|
6f05a20218a65b55b9eb680bacbcf61f
| 20 | 36 | 0.653386 | false | false | false | false |
PureSwift/GATT
|
refs/heads/master
|
Sources/DarwinGATT/DarwinCentral.swift
|
mit
|
1
|
//
// DarwinCentral.swift
// GATT
//
// Created by Alsey Coleman Miller on 4/3/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if swift(>=5.5) && canImport(CoreBluetooth)
import Foundation
import Dispatch
import CoreBluetooth
import Bluetooth
import GATT
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public final class DarwinCentral: CentralManager, ObservableObject {
// MARK: - Properties
public var log: ((String) -> ())?
public let options: Options
public var state: DarwinBluetoothState {
get async {
return await withUnsafeContinuation { [unowned self] continuation in
self.async { [unowned self] in
let state = unsafeBitCast(self.centralManager.state, to: DarwinBluetoothState.self)
continuation.resume(returning: state)
}
}
}
}
/// Currently scanned devices, or restored devices.
public var peripherals: [Peripheral: Bool] {
get async {
return await withUnsafeContinuation { [unowned self] continuation in
self.async { [unowned self] in
var peripherals = [Peripheral: Bool]()
peripherals.reserveCapacity(self.cache.peripherals.count)
for (peripheral, coreBluetoothPeripheral) in self.cache.peripherals {
peripherals[peripheral] = coreBluetoothPeripheral.state == .connected
}
continuation.resume(returning: peripherals)
}
}
}
}
private var centralManager: CBCentralManager!
private var delegate: Delegate!
private let queue = DispatchQueue(label: "org.pureswift.DarwinGATT.DarwinCentral")
@Published
fileprivate var cache = Cache()
fileprivate var continuation = Continuation()
// MARK: - Initialization
/// Initialize with the specified options.
///
/// - Parameter options: An optional dictionary containing initialization options for a central manager.
/// For available options, see [Central Manager Initialization Options](apple-reference-documentation://ts1667590).
public init(
options: Options = Options()
) {
self.options = options
self.delegate = options.restoreIdentifier == nil ? Delegate(self) : RestorableDelegate(self)
self.centralManager = CBCentralManager(
delegate: self.delegate,
queue: queue,
options: options.dictionary
)
}
// MARK: - Methods
/// Scans for peripherals that are advertising services.
public func scan(
filterDuplicates: Bool = true
) async throws -> AsyncCentralScan<DarwinCentral> {
return scan(with: [], filterDuplicates: filterDuplicates)
}
/// Scans for peripherals that are advertising services.
public func scan(
with services: Set<BluetoothUUID>,
filterDuplicates: Bool = true
) -> AsyncCentralScan<DarwinCentral> {
return AsyncCentralScan(onTermination: { [weak self] in
guard let self = self else { return }
self.async {
self.stopScan()
self.log?("Discovered \(self.cache.peripherals.count) peripherals")
}
}) { continuation in
self.async { [unowned self] in
self.stopScan()
}
Task {
await self.disconnectAll()
self.async { [unowned self] in
// queue scan operation
let operation = Operation.Scan(
services: services,
filterDuplicates: filterDuplicates,
continuation: continuation
)
self.continuation.scan = operation
self.execute(operation)
}
}
}
}
private func stopScan() {
if self.centralManager.isScanning {
self.centralManager.stopScan()
}
self.continuation.scan?.continuation.finish(throwing: CancellationError())
self.continuation.scan = nil
}
public func connect(
to peripheral: Peripheral
) async throws {
try await connect(to: peripheral, options: nil)
}
/// Connect to the specifed peripheral.
/// - Parameter peripheral: The peripheral to which the central is attempting to connect.
/// - Parameter options: A dictionary to customize the behavior of the connection.
/// For available options, see [Peripheral Connection Options](apple-reference-documentation://ts1667676).
public func connect(
to peripheral: Peripheral,
options: [String: Any]?
) async throws {
try await queue(for: peripheral) { continuation in
Operation.Connect(
peripheral: peripheral,
options: options,
continuation: continuation
)
}
}
public func disconnect(_ peripheral: Peripheral) async {
try? await queue(for: peripheral) { continuation in
Operation.Disconnect(
peripheral: peripheral,
continuation: continuation
)
}
}
public func disconnectAll() async {
let connected = await self.peripherals
.filter { $0.value }
.keys
for peripheral in connected {
await disconnect(peripheral)
}
}
public func discoverServices(
_ services: Set<BluetoothUUID> = [],
for peripheral: Peripheral
) async throws -> [DarwinCentral.Service] {
return try await queue(for: peripheral) { continuation in
Operation.DiscoverServices(
peripheral: peripheral,
services: services,
continuation: continuation
)
}
}
public func discoverIncludedServices(
_ services: Set<BluetoothUUID> = [],
for service: DarwinCentral.Service
) async throws -> [DarwinCentral.Service] {
return try await queue(for: service.peripheral) { continuation in
Operation.DiscoverIncludedServices(
service: service,
services: services,
continuation: continuation
)
}
}
public func discoverCharacteristics(
_ characteristics: Set<BluetoothUUID> = [],
for service: DarwinCentral.Service
) async throws -> [DarwinCentral.Characteristic] {
return try await queue(for: service.peripheral) { continuation in
Operation.DiscoverCharacteristics(
service: service,
characteristics: characteristics,
continuation: continuation
)
}
}
public func readValue(
for characteristic: DarwinCentral.Characteristic
) async throws -> Data {
return try await queue(for: characteristic.peripheral) { continuation in
Operation.ReadCharacteristic(
characteristic: characteristic,
continuation: continuation
)
}
}
public func writeValue(
_ data: Data,
for characteristic: DarwinCentral.Characteristic,
withResponse: Bool = true
) async throws {
if withResponse == false {
try await self.waitUntilCanSendWriteWithoutResponse(for: characteristic.peripheral)
}
try await self.write(data, withResponse: withResponse, for: characteristic)
}
public func discoverDescriptors(
for characteristic: DarwinCentral.Characteristic
) async throws -> [DarwinCentral.Descriptor] {
return try await queue(for: characteristic.peripheral) { continuation in
Operation.DiscoverDescriptors(
characteristic: characteristic,
continuation: continuation
)
}
}
public func readValue(
for descriptor: DarwinCentral.Descriptor
) async throws -> Data {
return try await queue(for: descriptor.peripheral) { continuation in
Operation.ReadDescriptor(
descriptor: descriptor,
continuation: continuation
)
}
}
public func writeValue(
_ data: Data,
for descriptor: DarwinCentral.Descriptor
) async throws {
try await queue(for: descriptor.peripheral) { continuation in
Operation.WriteDescriptor(
descriptor: descriptor,
data: data,
continuation: continuation
)
}
}
public func notify(
for characteristic: DarwinCentral.Characteristic
) async throws -> AsyncCentralNotifications<DarwinCentral> {
// enable notifications
try await self.setNotification(true, for: characteristic)
// central
return AsyncCentralNotifications(onTermination: { [unowned self] in
Task {
// disable notifications
do { try await self.setNotification(false, for: characteristic) }
catch CentralError.disconnected {
return
}
catch {
self.log?("Unable to stop notifications for \(characteristic.uuid). \(error.localizedDescription)")
}
// remove notification stream
self.async { [unowned self] in
let context = self.continuation(for: characteristic.peripheral)
context.notificationStream[characteristic.id] = nil
}
}
}, { continuation in
self.async { [unowned self] in
// store continuation
let context = self.continuation(for: characteristic.peripheral)
context.notificationStream[characteristic.id] = continuation
}
})
}
public func maximumTransmissionUnit(for peripheral: Peripheral) async throws -> MaximumTransmissionUnit {
self.log?("Will read MTU for \(peripheral)")
return try await withThrowingContinuation(for: peripheral) { [weak self] continuation in
guard let self = self else { return }
self.async {
do {
let mtu = try self._maximumTransmissionUnit(for: peripheral)
continuation.resume(returning: mtu)
}
catch {
continuation.resume(throwing: error)
}
}
}
}
public func rssi(for peripheral: Peripheral) async throws -> RSSI {
try await queue(for: peripheral) { continuation in
Operation.ReadRSSI(
peripheral: peripheral,
continuation: continuation
)
}
}
// MARK - Private Methods
@inline(__always)
private func async(_ body: @escaping () -> ()) {
queue.async(execute: body)
}
private func queue<Operation>(
for peripheral: Peripheral,
function: String = #function,
_ operation: (PeripheralContinuation<Operation.Success, Error>) -> Operation
) async throws -> Operation.Success where Operation: DarwinCentralOperation {
#if DEBUG
log?("Queue \(function) for peripheral \(peripheral)")
#endif
let value = try await withThrowingContinuation(for: peripheral, function: function) { continuation in
let queuedOperation = QueuedOperation(operation: operation(continuation))
self.async { [unowned self] in
self.stopScan() // stop scanning
let context = self.continuation(for: peripheral)
context.operations.push(queuedOperation)
}
}
try Task.checkCancellation()
return value
}
private func dequeue<Operation>(
for peripheral: Peripheral,
function: String = #function,
result: Result<Operation.Success, Error>,
filter: (DarwinCentral.Operation) -> (Operation?)
) where Operation: DarwinCentralOperation {
#if DEBUG
log?("Dequeue \(function) for peripheral \(peripheral)")
#endif
let context = self.continuation(for: peripheral)
context.operations.popFirst(where: { filter($0.operation) }) { (queuedOperation, operation) in
// resume continuation
if queuedOperation.isCancelled == false {
operation.continuation.resume(with: result)
}
}
}
private func continuation(for peripheral: Peripheral) -> PeripheralContinuationContext {
if let context = self.continuation.peripherals[peripheral] {
return context
} else {
let context = PeripheralContinuationContext(self)
self.continuation.peripherals[peripheral] = context
return context
}
}
private func write(
_ data: Data,
withResponse: Bool,
for characteristic: DarwinCentral.Characteristic
) async throws {
try await queue(for: characteristic.peripheral) { continuation in
Operation.WriteCharacteristic(
characteristic: characteristic,
data: data,
withResponse: withResponse,
continuation: continuation
)
}
}
private func waitUntilCanSendWriteWithoutResponse(
for peripheral: Peripheral
) async throws {
try await queue(for: peripheral) { continuation in
Operation.WriteWithoutResponseReady(
peripheral: peripheral,
continuation: continuation
)
}
}
private func setNotification(
_ isEnabled: Bool,
for characteristic: Characteristic
) async throws {
try await queue(for: characteristic.peripheral, { continuation in
Operation.NotificationState(
characteristic: characteristic,
isEnabled: isEnabled,
continuation: continuation
)
})
}
private func _maximumTransmissionUnit(for peripheral: Peripheral) throws -> MaximumTransmissionUnit {
// get peripheral
guard let peripheralObject = self.cache.peripherals[peripheral] else {
throw CentralError.unknownPeripheral
}
// get MTU
let rawValue = peripheralObject.maximumWriteValueLength(for: .withoutResponse) + 3
assert(peripheralObject.mtuLength.intValue == rawValue)
guard let mtu = MaximumTransmissionUnit(rawValue: UInt16(rawValue)) else {
assertionFailure("Invalid MTU \(rawValue)")
return .default
}
return mtu
}
}
// MARK: - Supporting Types
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension DarwinCentral {
typealias Advertisement = DarwinAdvertisementData
typealias State = DarwinBluetoothState
typealias AttributeID = ObjectIdentifier
typealias Service = GATT.Service<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
typealias Characteristic = GATT.Characteristic<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
typealias Descriptor = GATT.Descriptor<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
/// Central Peer
///
/// Represents a remote central device that has connected to an app implementing the peripheral role on a local device.
struct Peripheral: Peer {
public let id: UUID
internal init(_ peripheral: CBPeripheral) {
self.id = peripheral.id
}
}
/**
Darwin GATT Central Options
*/
struct Options {
/**
A Boolean value that specifies whether the system should display a warning dialog to the user if Bluetooth is powered off when the peripheral manager is instantiated.
*/
public let showPowerAlert: Bool
/**
A string (an instance of NSString) containing a unique identifier (UID) for the peripheral manager that is being instantiated.
The system uses this UID to identify a specific peripheral manager. As a result, the UID must remain the same for subsequent executions of the app in order for the peripheral manager to be successfully restored.
*/
public let restoreIdentifier: String?
/**
Initialize options.
*/
public init(showPowerAlert: Bool = false,
restoreIdentifier: String? = nil) {
self.showPowerAlert = showPowerAlert
self.restoreIdentifier = restoreIdentifier
}
internal var dictionary: [String: Any] {
var options = [String: Any](minimumCapacity: 2)
if showPowerAlert {
options[CBCentralManagerOptionShowPowerAlertKey] = showPowerAlert as NSNumber
}
options[CBCentralManagerOptionRestoreIdentifierKey] = restoreIdentifier
return options
}
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private extension DarwinCentral {
struct Cache {
var peripherals = [Peripheral: CBPeripheral]()
var services = [DarwinCentral.Service: CBService]()
var characteristics = [DarwinCentral.Characteristic: CBCharacteristic]()
var descriptors = [DarwinCentral.Descriptor: CBDescriptor]()
}
final class Continuation {
var scan: Operation.Scan?
var peripherals = [DarwinCentral.Peripheral: PeripheralContinuationContext]()
fileprivate init() { }
}
final class PeripheralContinuationContext {
var operations: Queue<QueuedOperation>
var notificationStream = [AttributeID: AsyncIndefiniteStream<Data>.Continuation]()
var readRSSI: Operation.ReadRSSI?
fileprivate init(_ central: DarwinCentral) {
operations = .init({ [unowned central] in
central.execute($0)
})
}
}
}
fileprivate extension DarwinCentral.PeripheralContinuationContext {
func didDisconnect(_ error: Swift.Error? = nil) {
let error = error ?? CentralError.disconnected
// resume all pending operations
while operations.isEmpty == false {
operations.pop {
$0.operation.resume(throwing: error)
}
}
// end all notifications with disconnect error
notificationStream.values.forEach {
$0.finish(throwing: error)
}
notificationStream.removeAll(keepingCapacity: true)
}
}
internal extension DarwinCentral {
final class QueuedOperation {
let operation: DarwinCentral.Operation
var isCancelled = false
fileprivate init<T: DarwinCentralOperation>(operation: T) {
self.operation = operation.operation
self.isCancelled = false
}
func cancel() {
guard !isCancelled else {
return
}
isCancelled = true
operation.cancel()
}
}
}
internal extension DarwinCentral {
enum Operation {
case connect(Connect)
case disconnect(Disconnect)
case discoverServices(DiscoverServices)
case discoverIncludedServices(DiscoverIncludedServices)
case discoverCharacteristics(DiscoverCharacteristics)
case readCharacteristic(ReadCharacteristic)
case writeCharacteristic(WriteCharacteristic)
case discoverDescriptors(DiscoverDescriptors)
case readDescriptor(ReadDescriptor)
case writeDescriptor(WriteDescriptor)
case isReadyToWriteWithoutResponse(WriteWithoutResponseReady)
case setNotification(NotificationState)
case readRSSI(ReadRSSI)
}
}
internal extension DarwinCentral.Operation {
func resume(throwing error: Swift.Error) {
switch self {
case let .connect(operation):
operation.continuation.resume(throwing: error)
case let .disconnect(operation):
operation.continuation.resume(throwing: error)
case let .discoverServices(operation):
operation.continuation.resume(throwing: error)
case let .discoverIncludedServices(operation):
operation.continuation.resume(throwing: error)
case let .discoverCharacteristics(operation):
operation.continuation.resume(throwing: error)
case let .writeCharacteristic(operation):
operation.continuation.resume(throwing: error)
case let .readCharacteristic(operation):
operation.continuation.resume(throwing: error)
case let .discoverDescriptors(operation):
operation.continuation.resume(throwing: error)
case let .readDescriptor(operation):
operation.continuation.resume(throwing: error)
case let .writeDescriptor(operation):
operation.continuation.resume(throwing: error)
case let .isReadyToWriteWithoutResponse(operation):
operation.continuation.resume(throwing: error)
case let .setNotification(operation):
operation.continuation.resume(throwing: error)
case let .readRSSI(operation):
operation.continuation.resume(throwing: error)
}
}
func cancel() {
resume(throwing: CancellationError())
}
}
internal protocol DarwinCentralOperation {
associatedtype Success
var continuation: PeripheralContinuation<Success, Error> { get }
var operation: DarwinCentral.Operation { get }
}
internal extension DarwinCentralOperation {
func resume(throwing error: Swift.Error) {
continuation.resume(throwing: error)
}
func cancel() {
resume(throwing: CancellationError())
}
}
internal extension DarwinCentral.Operation {
struct Connect: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let options: [String: Any]?
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .connect(self) }
}
struct Disconnect: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .disconnect(self) }
}
struct DiscoverServices: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let services: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Service], Error>
var operation: DarwinCentral.Operation { .discoverServices(self) }
}
struct DiscoverIncludedServices: DarwinCentralOperation {
let service: DarwinCentral.Service
let services: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Service], Error>
var operation: DarwinCentral.Operation { .discoverIncludedServices(self) }
}
struct DiscoverCharacteristics: DarwinCentralOperation {
let service: DarwinCentral.Service
let characteristics: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Characteristic], Error>
var operation: DarwinCentral.Operation { .discoverCharacteristics(self) }
}
struct ReadCharacteristic: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let continuation: PeripheralContinuation<Data, Error>
var operation: DarwinCentral.Operation { .readCharacteristic(self) }
}
struct WriteCharacteristic: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let data: Data
let withResponse: Bool
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .writeCharacteristic(self) }
}
struct DiscoverDescriptors: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let continuation: PeripheralContinuation<[DarwinCentral.Descriptor], Error>
var operation: DarwinCentral.Operation { .discoverDescriptors(self) }
}
struct ReadDescriptor: DarwinCentralOperation {
let descriptor: DarwinCentral.Descriptor
let continuation: PeripheralContinuation<Data, Error>
var operation: DarwinCentral.Operation { .readDescriptor(self) }
}
struct WriteDescriptor: DarwinCentralOperation {
let descriptor: DarwinCentral.Descriptor
let data: Data
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .writeDescriptor(self) }
}
struct WriteWithoutResponseReady: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .isReadyToWriteWithoutResponse(self) }
}
struct NotificationState: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let isEnabled: Bool
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .setNotification(self) }
}
struct ReadRSSI: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<RSSI, Error>
var operation: DarwinCentral.Operation { .readRSSI(self) }
}
struct Scan {
let services: Set<BluetoothUUID>
let filterDuplicates: Bool
let continuation: AsyncIndefiniteStream<ScanData<DarwinCentral.Peripheral, DarwinCentral.Advertisement>>.Continuation
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension DarwinCentral {
/// Executes a queued operation and informs whether a continuation is pending.
func execute(_ operation: QueuedOperation) -> Bool {
return operation.isCancelled ? false : execute(operation.operation)
}
/// Executes an operation and informs whether a continuation is pending.
func execute(_ operation: DarwinCentral.Operation) -> Bool {
switch operation {
case let .connect(operation):
return execute(operation)
case let .disconnect(operation):
return execute(operation)
case let .discoverServices(operation):
return execute(operation)
case let .discoverIncludedServices(operation):
return execute(operation)
case let .discoverCharacteristics(operation):
return execute(operation)
case let .readCharacteristic(operation):
return execute(operation)
case let .writeCharacteristic(operation):
return execute(operation)
case let .discoverDescriptors(operation):
return execute(operation)
case let .readDescriptor(operation):
return execute(operation)
case let .writeDescriptor(operation):
return execute(operation)
case let .setNotification(operation):
return execute(operation)
case let .isReadyToWriteWithoutResponse(operation):
return execute(operation)
case let .readRSSI(operation):
return execute(operation)
}
}
func execute(_ operation: Operation.Connect) -> Bool {
log?("Will connect to \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// connect
self.centralManager.connect(peripheralObject, options: operation.options)
return true
}
func execute(_ operation: Operation.Disconnect) -> Bool {
log?("Will disconnect \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// disconnect
guard peripheralObject.state != .disconnected else {
operation.continuation.resume() // already disconnected
return false
}
self.centralManager.cancelPeripheralConnection(peripheralObject)
return true
}
func execute(_ operation: Operation.DiscoverServices) -> Bool {
log?("Peripheral \(operation.peripheral) will discover services")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// discover
let serviceUUIDs = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
peripheralObject.discoverServices(serviceUUIDs)
return true
}
func execute(_ operation: Operation.DiscoverIncludedServices) -> Bool {
log?("Peripheral \(operation.service.peripheral) will discover included services of service \(operation.service.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.service.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get service
guard let serviceObject = validateService(operation.service, for: operation.continuation) else {
return false
}
let serviceUUIDs = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
peripheralObject.discoverIncludedServices(serviceUUIDs, for: serviceObject)
return true
}
func execute(_ operation: Operation.DiscoverCharacteristics) -> Bool {
log?("Peripheral \(operation.service.peripheral) will discover characteristics of service \(operation.service.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.service.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get service
guard let serviceObject = validateService(operation.service, for: operation.continuation) else {
return false
}
// discover
let characteristicUUIDs = operation.characteristics.isEmpty ? nil : operation.characteristics.map { CBUUID($0) }
peripheralObject.discoverCharacteristics(characteristicUUIDs, for: serviceObject)
return true
}
func execute(_ operation: Operation.ReadCharacteristic) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will read characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// read value
peripheralObject.readValue(for: characteristicObject)
return true
}
func execute(_ operation: Operation.WriteCharacteristic) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will write characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
assert(operation.withResponse || peripheralObject.canSendWriteWithoutResponse, "Cannot write without response")
// calls `peripheral:didWriteValueForCharacteristic:error:` only
// if you specified the write type as `.withResponse`.
let writeType: CBCharacteristicWriteType = operation.withResponse ? .withResponse : .withoutResponse
peripheralObject.writeValue(operation.data, for: characteristicObject, type: writeType)
guard operation.withResponse else {
operation.continuation.resume()
return false
}
return true
}
func execute(_ operation: Operation.DiscoverDescriptors) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will discover descriptors of characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// discover
peripheralObject.discoverDescriptors(for: characteristicObject)
return true
}
func execute(_ operation: Operation.ReadDescriptor) -> Bool {
log?("Peripheral \(operation.descriptor.peripheral) will read descriptor \(operation.descriptor.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.descriptor.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get descriptor
guard let descriptorObject = validateDescriptor(operation.descriptor, for: operation.continuation) else {
return false
}
// write
peripheralObject.readValue(for: descriptorObject)
return true
}
func execute(_ operation: Operation.WriteDescriptor) -> Bool {
log?("Peripheral \(operation.descriptor.peripheral) will write descriptor \(operation.descriptor.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.descriptor.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get descriptor
guard let descriptorObject = validateDescriptor(operation.descriptor, for: operation.continuation) else {
return false
}
// write
peripheralObject.writeValue(operation.data, for: descriptorObject)
return true
}
func execute(_ operation: Operation.WriteWithoutResponseReady) -> Bool {
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
guard peripheralObject.canSendWriteWithoutResponse == false else {
operation.continuation.resume()
return false
}
// wait until delegate is called
return true
}
func execute(_ operation: Operation.NotificationState) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will \(operation.isEnabled ? "enable" : "disable") notifications for characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// notify
peripheralObject.setNotifyValue(operation.isEnabled, for: characteristicObject)
return true
}
func execute(_ operation: Operation.ReadRSSI) -> Bool {
self.log?("Will read RSSI for \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// read value
peripheralObject.readRSSI()
return true
}
func execute(_ operation: Operation.Scan) {
log?("Will scan for nearby devices")
let serviceUUIDs: [CBUUID]? = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
let options: [String: Any] = [
CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: operation.filterDuplicates == false)
]
// reset cache
self.cache = Cache()
// start scanning
//self.continuation.isScanning.yield(true)
self.centralManager.scanForPeripherals(
withServices: serviceUUIDs,
options: options
)
}
}
private extension DarwinCentral {
func validateState<T>(
_ state: DarwinBluetoothState,
for continuation: PeripheralContinuation<T, Error>
) -> Bool {
let state = self.centralManager._state
guard state == .poweredOn else {
continuation.resume(throwing: DarwinCentralError.invalidState(state))
return false
}
return true
}
func validatePeripheral<T>(
_ peripheral: Peripheral,
for continuation: PeripheralContinuation<T, Error>
) -> CBPeripheral? {
// get peripheral
guard let peripheralObject = self.cache.peripherals[peripheral] else {
continuation.resume(throwing: CentralError.unknownPeripheral)
return nil
}
assert(peripheralObject.delegate != nil)
return peripheralObject
}
func validateConnected<T>(
_ peripheral: CBPeripheral,
for continuation: PeripheralContinuation<T, Error>
) -> Bool {
guard peripheral.state == .connected else {
continuation.resume(throwing: CentralError.disconnected)
return false
}
return true
}
func validateService<T>(
_ service: Service,
for continuation: PeripheralContinuation<T, Error>
) -> CBService? {
guard let serviceObject = self.cache.services[service] else {
continuation.resume(throwing: CentralError.invalidAttribute(service.uuid))
return nil
}
return serviceObject
}
func validateCharacteristic<T>(
_ characteristic: Characteristic,
for continuation: PeripheralContinuation<T, Error>
) -> CBCharacteristic? {
guard let characteristicObject = self.cache.characteristics[characteristic] else {
continuation.resume(throwing: CentralError.invalidAttribute(characteristic.uuid))
return nil
}
return characteristicObject
}
func validateDescriptor<T>(
_ descriptor: Descriptor,
for continuation: PeripheralContinuation<T, Error>
) -> CBDescriptor? {
guard let descriptorObject = self.cache.descriptors[descriptor] else {
continuation.resume(throwing: CentralError.invalidAttribute(descriptor.uuid))
return nil
}
return descriptorObject
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension DarwinCentral {
@objc(GATTAsyncCentralManagerRestorableDelegate)
class RestorableDelegate: Delegate {
@objc
func centralManager(_ centralManager: CBCentralManager, willRestoreState state: [String : Any]) {
assert(self.central.centralManager === centralManager)
log("Will restore state: \(NSDictionary(dictionary: state).description)")
// An array of peripherals for use when restoring the state of a central manager.
if let peripherals = state[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] {
for peripheralObject in peripherals {
self.central.cache.peripherals[Peripheral(peripheralObject)] = peripheralObject
}
}
}
}
@objc(GATTAsyncCentralManagerDelegate)
class Delegate: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private(set) unowned var central: DarwinCentral
fileprivate init(_ central: DarwinCentral) {
self.central = central
super.init()
}
fileprivate func log(_ message: String) {
self.central.log?(message)
}
// MARK: - CBCentralManagerDelegate
@objc(centralManagerDidUpdateState:)
func centralManagerDidUpdateState(_ centralManager: CBCentralManager) {
assert(self.central.centralManager === centralManager)
let state = unsafeBitCast(centralManager.state, to: DarwinBluetoothState.self)
log("Did update state \(state)")
self.central.objectWillChange.send()
}
@objc(centralManager:didDiscoverPeripheral:advertisementData:RSSI:)
func centralManager(
_ centralManager: CBCentralManager,
didDiscover corePeripheral: CBPeripheral,
advertisementData: [String : Any],
rssi: NSNumber
) {
assert(self.central.centralManager === centralManager)
if corePeripheral.delegate == nil {
corePeripheral.delegate = self
}
let peripheral = Peripheral(corePeripheral)
let advertisement = Advertisement(advertisementData)
let scanResult = ScanData(
peripheral: peripheral,
date: Date(),
rssi: rssi.doubleValue,
advertisementData: advertisement,
isConnectable: advertisement.isConnectable ?? false
)
// cache value
self.central.cache.peripherals[peripheral] = corePeripheral
// yield value to stream
guard let operation = self.central.continuation.scan else {
assertionFailure("Not currently scanning")
return
}
operation.continuation.yield(scanResult)
}
#if os(iOS)
func centralManager(
_ central: CBCentralManager,
connectionEventDidOccur event: CBConnectionEvent,
for corePeripheral: CBPeripheral
) {
log("\(corePeripheral.id.uuidString) connection event")
}
#endif
@objc(centralManager:didConnectPeripheral:)
func centralManager(
_ centralManager: CBCentralManager,
didConnect corePeripheral: CBPeripheral
) {
log("Did connect to peripheral \(corePeripheral.id.uuidString)")
assert(corePeripheral.state != .disconnected, "Should be connected")
assert(self.central.centralManager === centralManager)
let peripheral = Peripheral(corePeripheral)
central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (Operation.Connect?) in
guard case let .connect(operation) = operation else {
return nil
}
return operation
})
self.central.objectWillChange.send()
}
@objc(centralManager:didFailToConnectPeripheral:error:)
func centralManager(
_ centralManager: CBCentralManager,
didFailToConnect corePeripheral: CBPeripheral,
error: Swift.Error?
) {
log("Did fail to connect to peripheral \(corePeripheral.id.uuidString) (\(error!))")
assert(self.central.centralManager === centralManager)
assert(corePeripheral.state != .connected)
let peripheral = Peripheral(corePeripheral)
let error = error ?? CentralError.disconnected
central.dequeue(for: peripheral, result: .failure(error), filter: { (operation: DarwinCentral.Operation) -> (Operation.Connect?) in
guard case let .connect(operation) = operation else {
return nil
}
return operation
})
}
@objc(centralManager:didDisconnectPeripheral:error:)
func centralManager(
_ centralManager: CBCentralManager,
didDisconnectPeripheral corePeripheral: CBPeripheral,
error: Swift.Error?
) {
if let error = error {
log("Did disconnect peripheral \(corePeripheral.id.uuidString) due to error \(error.localizedDescription)")
} else {
log("Did disconnect peripheral \(corePeripheral.id.uuidString)")
}
let peripheral = Peripheral(corePeripheral)
guard let context = self.central.continuation.peripherals[peripheral] else {
assertionFailure("Missing context")
return
}
// user requested disconnection
if error == nil {
self.central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (Operation.Disconnect?) in
guard case let .disconnect(disconnectOperation) = operation else {
return nil
}
return disconnectOperation
})
}
context.didDisconnect(error)
self.central.objectWillChange.send()
}
// MARK: - CBPeripheralDelegate
@objc(peripheral:didDiscoverServices:)
func peripheral(
_ corePeripheral: CBPeripheral,
didDiscoverServices error: Swift.Error?
) {
if let error = error {
log("Peripheral \(corePeripheral.id.uuidString) failed discovering services (\(error))")
} else {
log("Peripheral \(corePeripheral.id.uuidString) did discover \(corePeripheral.services?.count ?? 0) services")
}
let peripheral = Peripheral(corePeripheral)
let result: Result<[DarwinCentral.Service], Error>
if let error = error {
result = .failure(error)
} else {
let serviceObjects = corePeripheral.services ?? []
let services = serviceObjects.map { serviceObject in
Service(
service: serviceObject,
peripheral: corePeripheral
)
}
for (index, service) in services.enumerated() {
self.central.cache.services[service] = serviceObjects[index]
}
result = .success(services)
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverServices?) in
guard case let .discoverServices(discoverServices) = operation else {
return nil
}
return discoverServices
})
}
@objc(peripheral:didDiscoverCharacteristicsForService:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverCharacteristicsFor serviceObject: CBService,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering characteristics (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(serviceObject.characteristics?.count ?? 0) characteristics for service \(serviceObject.uuid.uuidString)")
}
let service = Service(
service: serviceObject,
peripheral: peripheralObject
)
let result: Result<[DarwinCentral.Characteristic], Error>
if let error = error {
result = .failure(error)
} else {
let characteristicObjects = serviceObject.characteristics ?? []
let characteristics = characteristicObjects.map { characteristicObject in
Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
}
for (index, characteristic) in characteristics.enumerated() {
self.central.cache.characteristics[characteristic] = characteristicObjects[index]
}
result = .success(characteristics)
}
central.dequeue(for: service.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverCharacteristics?) in
guard case let .discoverCharacteristics(discoverCharacteristics) = operation else {
return nil
}
return discoverCharacteristics
})
}
@objc(peripheral:didUpdateValueForCharacteristic:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateValueFor characteristicObject: CBCharacteristic,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed reading characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update value for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
let data = characteristicObject.value ?? Data()
guard let context = self.central.continuation.peripherals[characteristic.peripheral] else {
assertionFailure("Missing context")
return
}
// either read operation or notification
if let queuedOperation = context.operations.current,
case let .readCharacteristic(operation) = queuedOperation.operation {
if queuedOperation.isCancelled {
return
}
if let error = error {
operation.continuation.resume(throwing: error)
} else {
operation.continuation.resume(returning: data)
}
context.operations.pop({ _ in }) // remove first
} else if characteristicObject.isNotifying {
guard let stream = context.notificationStream[characteristic.id] else {
assertionFailure("Missing notification stream")
return
}
assert(error == nil, "Notifications should never fail")
stream.yield(data)
} else {
assertionFailure("Missing continuation, not read or notification")
}
}
@objc(peripheral:didWriteValueForCharacteristic:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didWriteValueFor characteristicObject: CBCharacteristic,
error: Swift.Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed writing characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did write value for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
// should only be called for write with response
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: characteristic.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteCharacteristic?) in
guard case let .writeCharacteristic(operation) = operation else {
return nil
}
assert(operation.withResponse)
return operation
})
}
@objc
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateNotificationStateFor characteristicObject: CBCharacteristic,
error: Swift.Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed setting notifications for characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update notification state for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: characteristic.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.NotificationState?) in
guard case let .setNotification(notificationOperation) = operation else {
return nil
}
assert(characteristicObject.isNotifying == notificationOperation.isEnabled)
return notificationOperation
})
}
func peripheralIsReady(toSendWriteWithoutResponse peripheralObject: CBPeripheral) {
log("Peripheral \(peripheralObject.id.uuidString) is ready to send write without response")
let peripheral = Peripheral(peripheralObject)
central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteWithoutResponseReady?) in
guard case let .isReadyToWriteWithoutResponse(writeWithoutResponseReady) = operation else {
return nil
}
return writeWithoutResponseReady
})
}
func peripheralDidUpdateName(_ peripheralObject: CBPeripheral) {
log("Peripheral \(peripheralObject.id.uuidString) updated name \(peripheralObject.name ?? "")")
}
func peripheral(_ peripheralObject: CBPeripheral, didReadRSSI rssiObject: NSNumber, error: Error?) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed to read RSSI (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did read RSSI \(rssiObject.description)")
}
let peripheral = Peripheral(peripheralObject)
guard let context = self.central.continuation.peripherals[peripheral] else {
assertionFailure("Missing context")
return
}
guard let operation = context.readRSSI else {
assertionFailure("Invalid continuation")
return
}
if let error = error {
operation.continuation.resume(throwing: error)
} else {
guard let rssi = Bluetooth.RSSI(rawValue: rssiObject.int8Value) else {
assertionFailure("Invalid RSSI \(rssiObject)")
operation.continuation.resume(returning: RSSI(rawValue: -127)!)
return
}
operation.continuation.resume(returning: rssi)
}
}
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverIncludedServicesFor serviceObject: CBService,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering included services for service \(serviceObject.uuid.description) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(serviceObject.includedServices?.count ?? 0) included services for service \(serviceObject.uuid.uuidString)")
}
let service = Service(
service: serviceObject,
peripheral: peripheralObject
)
let result: Result<[DarwinCentral.Service], Error>
if let error = error {
result = .failure(error)
} else {
let serviceObjects = (serviceObject.includedServices ?? [])
let services = serviceObjects.map { serviceObject in
Service(
service: serviceObject,
peripheral: peripheralObject
)
}
for (index, service) in services.enumerated() {
self.central.cache.services[service] = serviceObjects[index]
}
result = .success(services)
}
central.dequeue(for: service.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverIncludedServices?) in
guard case let .discoverIncludedServices(writeWithoutResponseReady) = operation else {
return nil
}
return writeWithoutResponseReady
})
}
@objc
func peripheral(_ peripheralObject: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
log("Peripheral \(peripheralObject.id.uuidString) did modify \(invalidatedServices.count) services")
// TODO: Try to rediscover services
}
@objc
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverDescriptorsFor characteristicObject: CBCharacteristic,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering descriptors for characteristic \(characteristicObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(characteristicObject.descriptors?.count ?? 0) descriptors for characteristic \(characteristicObject.uuid.uuidString)")
}
let peripheral = Peripheral(peripheralObject)
let result: Result<[DarwinCentral.Descriptor], Error>
if let error = error {
result = .failure(error)
} else {
let descriptorObjects = (characteristicObject.descriptors ?? [])
let descriptors = descriptorObjects.map { descriptorObject in
Descriptor(
descriptor: descriptorObject,
peripheral: peripheralObject
)
}
// store objects in cache
for (index, descriptor) in descriptors.enumerated() {
self.central.cache.descriptors[descriptor] = descriptorObjects[index]
}
// resume
result = .success(descriptors)
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverDescriptors?) in
guard case let .discoverDescriptors(discoverDescriptors) = operation else {
return nil
}
return discoverDescriptors
})
}
func peripheral(
_ peripheralObject: CBPeripheral,
didWriteValueFor descriptorObject: CBDescriptor,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed writing descriptor \(descriptorObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did write value for descriptor \(descriptorObject.uuid.uuidString)")
}
let peripheral = Peripheral(peripheralObject)
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteDescriptor?) in
guard case let .writeDescriptor(writeDescriptor) = operation else {
return nil
}
return writeDescriptor
})
}
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateValueFor descriptorObject: CBDescriptor,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed updating value for descriptor \(descriptorObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update value for descriptor \(descriptorObject.uuid.uuidString)")
}
let descriptor = Descriptor(
descriptor: descriptorObject,
peripheral: peripheralObject
)
let result: Result<Data, Error>
if let error = error {
result = .failure(error)
} else {
let data: Data
if let descriptor = DarwinDescriptor(descriptorObject) {
data = descriptor.data
} else if let dataObject = descriptorObject.value as? NSData {
data = dataObject as Data
} else {
data = Data()
}
result = .success(data)
}
central.dequeue(for: descriptor.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.ReadDescriptor?) in
guard case let .readDescriptor(readDescriptor) = operation else {
return nil
}
return readDescriptor
})
}
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Service where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
service serviceObject: CBService,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(serviceObject),
uuid: BluetoothUUID(serviceObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject),
isPrimary: serviceObject.isPrimary
)
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Characteristic where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
characteristic characteristicObject: CBCharacteristic,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(characteristicObject),
uuid: BluetoothUUID(characteristicObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject),
properties: .init(rawValue: numericCast(characteristicObject.properties.rawValue))
)
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Descriptor where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
descriptor descriptorObject: CBDescriptor,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(descriptorObject),
uuid: BluetoothUUID(descriptorObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject)
)
}
}
#endif
|
c89c50d69f6907ec7328e0db04663704
| 38.53619 | 220 | 0.607786 | false | false | false | false |
lexchou/swallow
|
refs/heads/master
|
stdlib/core/Comparable.swift
|
bsd-3-clause
|
1
|
/// Instances of conforming types can be compared using relational
/// operators, which define a `strict total order
/// <http://en.wikipedia.org/wiki/Total_order#Strict_total_order>`_.
///
/// A type conforming to `Comparable` need only supply the `<` and
/// `==` operators; default implementations of `<=`, `>`, `>=`, and
/// `!=` are supplied by the standard library::
///
/// struct Singular : Comparable {}
/// func ==(x: Singular, y: Singular) -> Bool { return true }
/// func <(x: Singular, y: Singular) -> Bool { return false }
///
/// **Axioms**, in addition to those of `Equatable`:
///
/// - `x == y` implies `x <= y`, `x >= y`, `!(x < y)`, and `!(x > y)`
/// - `x < y` implies `x <= y` and `y > x`
/// - `x > y` implies `x >= y` and `y < x`
/// - `x <= y` implies `y >= x`
/// - `x >= y` implies `y <= x`
protocol Comparable : _Comparable, Equatable {
func <=(lhs: Self, rhs: Self) -> Bool
func >=(lhs: Self, rhs: Self) -> Bool
func >(lhs: Self, rhs: Self) -> Bool
}
|
c7f01a1e4a36179c7d7177d649fe1130
| 40.583333 | 69 | 0.562124 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
refs/heads/master
|
Carthage/Checkouts/APIKit/Carthage/Checkouts/OHHTTPStubs/OHHTTPStubs/UnitTests/Test Suites/SwiftHelpersTests.swift
|
gpl-3.0
|
4
|
//
// SwiftHelpersTests.swift
// OHHTTPStubs
//
// Created by Olivier Halligon on 20/09/2015.
// Copyright © 2015 AliSoftware. All rights reserved.
//
import Foundation
import XCTest
import OHHTTPStubs
class SwiftHelpersTests : XCTestCase {
func testHTTPMethod() {
let methods = ["GET", "PUT", "PATCH", "POST", "DELETE", "FOO"]
let matchers = [isMethodGET(), isMethodPUT(), isMethodPATCH(), isMethodPOST(), isMethodDELETE()]
for (idxMethod, method) in methods.enumerate() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
req.HTTPMethod = method
for (idxMatcher, matcher) in matchers.enumerate() {
let expected = idxMethod == idxMatcher // expect to be true only if indexes match
XCTAssert(matcher(req) == expected, "Function is\(methods[idxMatcher])() failed to test request with HTTP method \(method).")
}
}
}
func testIsScheme() {
let matcher = isScheme("foo")
let urls = [
"foo:": true,
"foo://": true,
"foo://bar/baz": true,
"bar://": false,
"bar://foo/": false,
"foobar://": false
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert(matcher(req) == result, "isScheme(\"foo\") matcher failed when testing url \(url)")
}
}
func testIsHost() {
let matcher = isHost("foo")
let urls = [
"foo:": false,
"foo://": false,
"foo://bar/baz": false,
"bar://foo": true,
"bar://foo/baz": true,
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert(matcher(req) == result, "isHost(\"foo\") matcher failed when testing url \(url)")
}
}
func testIsPath_absoluteURL() {
testIsPath("/foo/bar/baz", isAbsoluteMatcher: true)
}
func testIsPath_relativeURL() {
testIsPath("foo/bar/baz", isAbsoluteMatcher: false)
}
func testIsPath(path: String, isAbsoluteMatcher: Bool) {
let matcher = isPath(path)
let urls = [
// Absolute URLs
"scheme:": false,
"scheme://": false,
"scheme://foo/bar/baz": false,
"scheme://host/foo/bar": false,
"scheme://host/foo/bar/baz": isAbsoluteMatcher,
"scheme://host/foo/bar/baz?q=1": isAbsoluteMatcher,
"scheme://host/foo/bar/baz#anchor": isAbsoluteMatcher,
"scheme://host/foo/bar/baz;param": isAbsoluteMatcher,
"scheme://host/foo/bar/baz/wizz": false,
"scheme://host/path#/foo/bar/baz": false,
"scheme://host/path?/foo/bar/baz": false,
"scheme://host/path;/foo/bar/baz": false,
// Relative URLs
"foo/bar/baz": !isAbsoluteMatcher,
"foo/bar/baz?q=1": !isAbsoluteMatcher,
"foo/bar/baz#anchor": !isAbsoluteMatcher,
"foo/bar/baz;param": !isAbsoluteMatcher,
"foo/bar/baz/wizz": false,
"path#/foo/bar/baz": false,
"path?/foo/bar/baz": false,
"path;/foo/bar/baz": false,
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
let p = req.URL?.path
print("URL: \(url) -> Path: \(p)")
XCTAssert(matcher(req) == result, "isPath(\"\(path)\" matcher failed when testing url \(url)")
}
}
func testPathStartsWith_absoluteURL() {
testPathStartsWith("/foo/bar", isAbsoluteMatcher: true)
}
func testPathStartsWith_relativeURL() {
testPathStartsWith("foo/bar", isAbsoluteMatcher: false)
}
func testPathStartsWith(path: String, isAbsoluteMatcher: Bool) {
let matcher = pathStartsWith(path)
let urls = [
// Absolute URLs
"scheme:": false,
"scheme://": false,
"scheme://foo/bar/baz": false,
"scheme://host/foo/bar": isAbsoluteMatcher,
"scheme://host/foo/bar/baz": isAbsoluteMatcher,
"scheme://host/foo/bar?q=1": isAbsoluteMatcher,
"scheme://host/foo/bar#anchor": isAbsoluteMatcher,
"scheme://host/foo/bar;param": isAbsoluteMatcher,
"scheme://host/path/foo/bar/baz": false,
"scheme://host/path#/foo/bar/baz": false,
"scheme://host/path?/foo/bar/baz": false,
"scheme://host/path;/foo/bar/baz": false,
// Relative URLs
"foo/bar": !isAbsoluteMatcher,
"foo/bar/baz": !isAbsoluteMatcher,
"foo/bar?q=1": !isAbsoluteMatcher,
"foo/bar#anchor": !isAbsoluteMatcher,
"foo/bar;param": !isAbsoluteMatcher,
"path/foo/bar/baz": false,
"path#/foo/bar/baz": false,
"path?/foo/bar/baz": false,
"path;/foo/bar/baz": false,
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
let p = req.URL?.path
print("URL: \(url) -> Path: \(p)")
XCTAssert(matcher(req) == result, "pathStartsWith(\"\(path)\" matcher failed when testing url \(url)")
}
}
func testIsExtension() {
let matcher = isExtension("txt")
let urls = [
"txt:": false,
"txt://": false,
"txt://txt/txt/txt": false,
"scheme://host/foo/bar.png": false,
"scheme://host/foo/bar.txt": true,
"scheme://host/foo/bar.txt?q=1": true,
"scheme://host/foo/bar.baz?q=wizz.txt": false,
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert(matcher(req) == result, "isExtension(\"txt\") matcher failed when testing url \(url)")
}
}
@available(iOS 8.0, OSX 10.10, *)
func testContainsQueryParams() {
let params: [String: String?] = ["q":"test", "lang":"en", "empty":"", "flag":nil]
let matcher = containsQueryParams(params)
let urls = [
"foo://bar": false,
"foo://bar?q=test": false,
"foo://bar?lang=en": false,
"foo://bar#q=test&lang=en&empty=&flag": false,
"foo://bar#lang=en&empty=&flag&q=test": false,
"foo://bar;q=test&lang=en&empty=&flag": false,
"foo://bar;lang=en&empty=&flag&q=test": false,
"foo://bar?q=test&lang=en&empty=&flag": true,
"foo://bar?lang=en&flag&empty=&q=test": true,
"foo://bar?q=test&lang=en&empty=&flag#anchor": true,
"foo://bar?q=test&lang=en&empty&flag": false, // key "empty" with no value is matched against nil, not ""
"foo://bar?q=test&lang=en&empty=&flag=": false, // key "flag" with empty value is matched against "", not nil
"foo://bar?q=en&lang=test&empty=&flag": false, // param keys and values mismatch
"foo://bar?q=test&lang=en&empty=&flag&&wizz=fuzz": true,
"foo://bar?wizz=fuzz&empty=&lang=en&flag&&q=test": true,
"?q=test&lang=en&empty=&flag": true,
"?lang=en&flag&empty=&q=test": true,
]
for (url, result) in urls {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert(matcher(req) == result, "containsQueryParams(\"\(params)\") matcher failed when testing url \(url)")
}
}
func testHasHeaderNamedIsTrue() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
req.addValue("1234567890", forHTTPHeaderField: "ArbitraryKey")
let hasHeader = hasHeaderNamed("ArbitraryKey")(req)
XCTAssertTrue(hasHeader)
}
func testHasHeaderNamedIsFalse() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
let hasHeader = hasHeaderNamed("ArbitraryKey")(req)
XCTAssertFalse(hasHeader)
}
func testHeaderValueForKeyEqualsIsTrue() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
req.addValue("bar", forHTTPHeaderField: "foo")
let matchesHeader = hasHeaderNamed("foo", value: "bar")(req)
XCTAssertTrue(matchesHeader)
}
func testHeaderValueForKeyEqualsIsFalse() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
req.addValue("bar", forHTTPHeaderField: "foo")
let matchesHeader = hasHeaderNamed("foo", value: "baz")(req)
XCTAssertFalse(matchesHeader)
}
func testHeaderValueForKeyEqualsDoesNotExist() {
let req = NSMutableURLRequest(URL: NSURL(string: "foo://bar")!)
let matchesHeader = hasHeaderNamed("foo", value: "baz")(req)
XCTAssertFalse(matchesHeader)
}
let sampleURLs = [
// Absolute URLs
"scheme:",
"scheme://",
"scheme://foo/bar/baz",
"scheme://host/foo/bar",
"scheme://host/foo/bar/baz",
"scheme://host/foo/bar/baz?q=1",
"scheme://host/foo/bar/baz#anchor",
"scheme://host/foo/bar/baz;param",
"scheme://host/foo/bar/baz/wizz",
"scheme://host/path#/foo/bar/baz",
"scheme://host/path?/foo/bar/baz",
"scheme://host/path;/foo/bar/baz",
// Relative URLs
"foo/bar/baz",
"foo/bar/baz?q=1",
"foo/bar/baz#anchor",
"foo/bar/baz;param",
"foo/bar/baz/wizz",
"path#/foo/bar/baz",
"path?/foo/bar/baz",
"path;/foo/bar/baz"
]
let trueMatcher: OHHTTPStubsTestBlock = { _ in return true }
let falseMatcher: OHHTTPStubsTestBlock = { _ in return false }
func testOrOperator() {
for url in sampleURLs {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert((trueMatcher || trueMatcher)(req) == true, "trueMatcher || trueMatcher should result in a trueMatcher")
XCTAssert((trueMatcher || falseMatcher)(req) == true, "trueMatcher || falseMatcher should result in a trueMatcher")
XCTAssert((falseMatcher || trueMatcher)(req) == true, "falseMatcher || trueMatcher should result in a trueMatcher")
XCTAssert((falseMatcher || falseMatcher)(req) == false, "falseMatcher || falseMatcher should result in a falseMatcher")
}
}
func testAndOperator() {
for url in sampleURLs {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert((trueMatcher && trueMatcher)(req) == true, "trueMatcher && trueMatcher should result in a trueMatcher")
XCTAssert((trueMatcher && falseMatcher)(req) == false, "trueMatcher && falseMatcher should result in a falseMatcher")
XCTAssert((falseMatcher && trueMatcher)(req) == false, "falseMatcher && trueMatcher should result in a falseMatcher")
XCTAssert((falseMatcher && falseMatcher)(req) == false, "falseMatcher && falseMatcher should result in a falseMatcher")
}
}
func testNotOperator() {
for url in sampleURLs {
let req = NSURLRequest(URL: NSURL(string: url)!)
XCTAssert((!trueMatcher)(req) == false, "!trueMatcher should result in a falseMatcher")
XCTAssert((!falseMatcher)(req) == true, "!falseMatcher should result in a trueMatcher")
}
}
}
|
5b7f579738e61a28461befdec4e846ef
| 33.463576 | 133 | 0.618178 | false | true | false | false |
testpress/ios-app
|
refs/heads/master
|
ios-app/Extensions/UIDevice+ModelName.swift
|
mit
|
1
|
//
// UIDevice+ModelName.swift
// ios-app
//
// Created by Karthik raja on 9/8/19.
// Copyright © 2019 Testpress. All rights reserved.
//
import UIKit
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
|
f9a2a981ec776d1353730b606a89d256
| 28.619048 | 91 | 0.643087 | false | false | false | false |
UW-AppDEV/AUXWave
|
refs/heads/master
|
AUXWave/ScannerViewController.swift
|
gpl-2.0
|
1
|
//
// ScannerViewController.swift
// AUXWave
//
// Created by Nico Cvitak on 2015-02-28.
// Copyright (c) 2015 UW-AppDEV. All rights reserved.
//
import UIKit
import MultipeerConnectivity
class ScannerViewController: UITableViewController, UITableViewDataSource, MCNearbyServiceBrowserDelegate {
var peerID: MCPeerID?
var browser: MCNearbyServiceBrowser?
var discoveredPeers: [MCPeerID : [NSObject : AnyObject]?] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let userState = UserState.localUserState()
peerID = MCPeerID(displayName: userState.displayName)
browser = MCNearbyServiceBrowser(peer: peerID, serviceType: kServiceTypeAUXWave)
browser?.delegate = self
// Sample Data
//discoveredPeers[MCPeerID(displayName: "Nico Cvitak")] = ["facebookID" : "ncvitak"]
// Start searching for DJs when the view is visible
browser?.startBrowsingForPeers()
println("load")
}
override func viewWillAppear(animated: Bool) {
if let selectedRow = self.tableView.indexPathForSelectedRow() {
self.tableView.deselectRowAtIndexPath(selectedRow, animated: animated)
}
}
override func viewWillDisappear(animated: Bool) {
// Stop searching for DJs when the view is not visible
//browser?.stopBrowsingForPeers()
}
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.
if let djInformationViewController = segue.destinationViewController as? DJInformationViewController {
if let selectedCell = sender as? ScannerTableViewCell {
djInformationViewController.peerID = selectedCell.peerID
djInformationViewController.djFacebookID = selectedCell.facebookID
djInformationViewController.djName = selectedCell.peerID?.displayName
djInformationViewController.browser = self.browser
}
}
}
/*
// MARK: - UITableViewDataSource
*/
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let peerID = discoveredPeers.keys.array[indexPath.row]
let discoveryInfo = discoveredPeers[peerID]
// Load ScannerTableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("ScannerCell") as ScannerTableViewCell
// Initialize default properties
cell.peerID = peerID
// Load information from Facebook
cell.facebookID = discoveryInfo??["facebookID"] as? String
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return discoveredPeers.keys.array.count
}
/*
// MARK: - MCNearbyServiceBrowserDelegate
*/
func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) {
println("found: \(peerID.displayName)")
tableView.beginUpdates()
discoveredPeers[peerID] = info
if let index = find(discoveredPeers.keys.array, peerID) {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade)
}
tableView.endUpdates()
}
func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!) {
tableView.beginUpdates()
if let index = find(discoveredPeers.keys.array, peerID) {
tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade)
}
discoveredPeers.removeValueForKey(peerID)
tableView.endUpdates()
}
/*
// MARK: - Received Actions
*/
}
|
491aa387a3c02178277e1961a6e8d4a1
| 31.956204 | 130 | 0.640753 | false | false | false | false |
bwitt2/rendezvous
|
refs/heads/master
|
Rendezvous/ContainerViewController.swift
|
mit
|
1
|
//
// ContainerViewController.swift
// Rendezvous
//
import UIKit
class ContainerViewController: UIViewController, UIScrollViewDelegate, GMSMapViewDelegate {
@IBOutlet var scrollView: UIScrollView?
var mapView: MapViewController!
var feedView: FeedViewController!
var postView: PostViewController!
var feedData: NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
if(PFUser.currentUser() == nil){
var user: PFUser = PFUser()
//user.username = "connor"
//user.password = "giles"
//Sign up for user
/*user.signUpInBackgroundWithBlock({
(success:Bool!, error:NSError!) -> Void in
if error == nil{
println("success!")
}
})*/
//Login to existing user
//PFUser.logInWithUsernameInBackground(user.username, password: user.password)
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
println("Scrolled")
}
override func viewDidLoad() {
super.viewDidLoad()
//Create the three views used in the view container
mapView = MapViewController(nibName: "MapViewController", bundle: nil)
feedView = FeedViewController(nibName: "FeedViewController", bundle: nil)
postView = PostViewController(nibName: "PostViewController", bundle: nil)
//Set container object in each view
mapView.container = self
feedView.container = self
postView.container = self
//Add in each view to the container view hierarchy
//Add them in opposite order since the view hieracrhy is a stack
self.addChildViewController(feedView)
self.scrollView!.addSubview(feedView.view)
feedView.didMoveToParentViewController(self)
self.addChildViewController(mapView)
self.scrollView!.addSubview(mapView.view)
mapView.didMoveToParentViewController(self)
//Will add from mapview
//self.addChildViewController(postView)
//self.scrollView!.addSubview(postView.view)
//postView.didMoveToParentViewController(self)
//Set up the frames of the view controllers to align
//with eachother inside the container view
mapView.view.frame.origin.x = 0
feedView.view.frame.origin.x = self.view.frame.width
//Set the size of the scroll view that contains the frames
var scrollWidth: CGFloat = 2 * self.view.frame.width
var scrollHeight: CGFloat = self.view.frame.size.height
self.scrollView!.contentSize = CGSizeMake(scrollWidth, scrollHeight)
self.scrollView!.scrollRectToVisible(mapView.view.frame, animated: false)
}
override func viewWillAppear(animated: Bool){
loadData()
}
func loadData(){
feedData.removeAllObjects()
var findFeedData: PFQuery = PFQuery(className: "Posts")
//Must find better solution
feedData = NSMutableArray(array: findFeedData.findObjects().reverse())
feedView.feedTable.reloadData()
mapView.loadMarkers()
println("Loaded \(feedData.count) points")
//Has issues where table is being reloaded before array is populated
/*findFeedData.findObjectsInBackgroundWithBlock(){
(objects: [AnyObject]!, error: NSError!)->Void in
if error == nil{
for object in objects{
//NSLog("Loaded: %@", object.objectId) //FOR TESTING
self.feedData.addObject(object)
}
//Reverse array
var array: NSArray = self.feedData.reverseObjectEnumerator().allObjects
self.feedData = NSMutableArray(array: array)
println("Loaded \(self.feedData.count) points")
self.feedView.feedTable.reloadData()
self.mapView.loadMarkers()
}
else{
NSLog("Error: %@ %@", error, error.userInfo!)
}
}*/
}
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.
}
*/
}
|
5bf3ea0414bd29d6290b9cd51e591319
| 31.85906 | 106 | 0.598448 | false | false | false | false |
richterd/BirthdayGroupReminder
|
refs/heads/master
|
BirthdayGroupReminder/BGRAdressBook.swift
|
gpl-2.0
|
1
|
//
// BGRAdressBook.swift
// BirthdayGroupReminder
//
// Created by Daniel Richter on 16.07.14.
// Copyright (c) 2014 Daniel Richter. All rights reserved.
//
import UIKit
class BGRAdressBook: NSObject {
var delegate = UIApplication.shared.delegate as! AppDelegate
func usersSortedByBirthday(_ selectedGroups : [ABRecordID]) -> [RHPerson]{
let addressBook = delegate.addressBook
var users : [RHPerson] = []
for groupID : ABRecordID in selectedGroups{
let group : RHGroup = addressBook.group(forABRecordID: groupID)
let friends = group.members as! [RHPerson]
for user in friends{
if ((user.birthday) != nil){
users.append(user)
}
}
}
//Sort by birthday
users.sort(){
let leftDate : Date = $0.birthday
let rightDate : Date = $1.birthday
let left = (Calendar.current as NSCalendar).components([.day, .month, .year], from: leftDate)
let right = (Calendar.current as NSCalendar).components([.day, .month, .year], from: rightDate)
let current = (Calendar.current as NSCalendar).components([.day, .month, .year], from: Date())
//Its save to unwrap the information here
let lday = left.day!
var lmonth = left.month!
let rday = right.day!
var rmonth = right.month!
//Shift dates depending on current date
if(lmonth < current.month!){
lmonth += 12
} else if(lmonth == current.month){
if(lday < current.day!){
lmonth += 12
}
}
if(rmonth < current.month!){
rmonth += 12
} else if(rmonth == current.month){
if(rday < current.day!){
rmonth += 12
}
}
//Now sort them
var diff = lmonth - rmonth
if(diff == 0){diff = lday - rday}
if(diff < 0){
return true
}else{
return false
}
}
return users
}
}
|
3f30f842b23bdd01b7ab726d97223f00
| 31.056338 | 107 | 0.494728 | false | false | false | false |
crspybits/SMCoreLib
|
refs/heads/master
|
Deprecated/HttpOperation.swift
|
gpl-3.0
|
1
|
//
// HttpOperation.swift
// WhatDidILike
//
// Created by Christopher Prince on 9/28/14.
// Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
class HttpOperation {
/* Carry out an HTTP GET operation. For a "GET" method, the parameters are sent as part of the URL string.
e.g., /test/demo_form.asp?name1=value1&name2=value2
See http://www.w3schools.com/tags/ref_httpmethods.asp
*/
func get(url: NSURL, parameters: NSDictionary?,
extraHeaders: ((request: NSURLRequest?) -> Dictionary<String, String>?)?,
completion: (NSDictionary?, NSError?) -> ()) -> NetOp?
{
var errorResult: NSError?
print("parameters: \(parameters)")
let urlString: String = url.absoluteString
let request: NSMutableURLRequest!
do {
request = try AFHTTPRequestSerializer().requestWithMethod("GET", URLString: urlString, parameters: parameters)
} catch var error as NSError {
errorResult = error
request = nil
}
Log.msg("extraHeaders: \(extraHeaders)")
var headers: Dictionary<String, String>?
if (extraHeaders != nil) {
// Call the extraHeaders function, because it was given.
headers = extraHeaders!(request: request)
for (headerField, fieldValue) in headers! {
request.setValue(fieldValue, forHTTPHeaderField: headerField)
}
}
if (nil == request) || (nil != errorResult) {
completion(nil, Error.Create("Error executing requestWithMethod"))
return nil
}
func successFunc(operation: AFHTTPRequestOperation?, response: AnyObject?) {
if let responseDict = response as? NSDictionary {
completion(responseDict, nil)
} else {
completion(nil, Error.Create("Response was not a dictionary"))
}
}
func failureFunc(operation: AFHTTPRequestOperation?, error: NSError?) {
completion(nil, error)
}
// I thought I was having quoting, but it turned out to be a problem with the oauth signature because I wasn't including the final URL from the NSURLRequest.
let operation = AFHTTPRequestOperation(request: request)
// 10/5/15; See bridging header. I was having a problem with just AFJSONResponseSerializer()
operation.responseSerializer = AFJSONResponseSerializer.sharedSerializer()
operation.setCompletionBlockWithSuccess(successFunc, failure: failureFunc)
operation.start()
let netOp = NetOp(operation: operation)
return netOp
}
func get(url: NSURL, parameters: NSDictionary?,
completion: (NSDictionary?, NSError?) -> ()) -> NetOp?
{
return get(url, parameters: parameters, extraHeaders: nil, completion: completion)
}
}
|
8ecb58546aaa9cd7b4a4d7e4f5325119
| 36.4375 | 165 | 0.614896 | false | false | false | false |
edmoks/RecordBin
|
refs/heads/master
|
RecordBin/Class/Model/Store.swift
|
mit
|
1
|
//
// Store.swift
// RecordBin
//
// Created by Eduardo Rangel on 05/10/2017.
// Copyright © 2017 Eduardo Rangel. All rights reserved.
//
import Foundation
import CoreLocation
struct Store {
//////////////////////////////////////////////////
// MARK: - Variables
public private(set) var about: String?
public private(set) var address: String?
// public private(set) var businessHours
public private(set) var city: String?
public private(set) var country: String?
public private(set) var email: String?
// public private(set) var identifier: String
public private(set) var latitude: String?
public private(set) var longitude: String?
public private(set) var mobilePhone: String?
public private(set) var name: String?
public private(set) var neighborhood: String?
public private(set) var state: String?
public private(set) var telephone: String?
public private(set) var url: String?
public private(set) var zipCode: String?
public private(set) var coordinate: CLLocationCoordinate2D?
//////////////////////////////////////////////////
// MARK: - Methods
init(about: String?,
address: String?,
city: String?,
country: String?,
email: String?,
latitude: String?,
longitude: String?,
mobilePhone: String?,
name: String?,
neighborhood: String?,
state: String?,
telephone: String?,
url: String?,
zipCode: String?) {
self.about = about
self.address = address
self.city = city
self.country = country
self.email = email
self.latitude = latitude
self.longitude = longitude
self.mobilePhone = mobilePhone
self.name = name
self.neighborhood = neighborhood
self.state = state
self.telephone = telephone
self.url = url
self.zipCode = zipCode
self.coordinate = self.getCoordinate()
}
private func getCoordinate() -> CLLocationCoordinate2D? {
if let latitude = self.latitude,
let longitude = self.longitude {
let coordinate = CLLocationCoordinate2D(latitude: Double(latitude)!, longitude: Double(longitude)!)
return coordinate
}
return nil
}
}
|
c7ffa7c1d82d83cf103b1de94ceb1d1d
| 27.2 | 111 | 0.580726 | false | false | false | false |
imk2o/MK2Router
|
refs/heads/master
|
MK2Router/Models/ItemProvider.swift
|
mit
|
1
|
//
// ItemProvider.swift
// MK2Router
//
// Created by k2o on 2016/05/14.
// Copyright © 2016年 Yuichi Kobayashi. All rights reserved.
//
import UIKit
class ItemProvider {
static let shared: ItemProvider = ItemProvider()
fileprivate init() {
}
func getAllItems(_ handler: ([Item]) -> Void) {
let items = [
self.itemForID(1, imageQuarity: "small"),
self.itemForID(2, imageQuarity: "small"),
self.itemForID(3, imageQuarity: "small"),
self.itemForID(4, imageQuarity: "small"),
self.itemForID(5, imageQuarity: "small")
]
handler(items)
}
func getItems(keyword: String, handler: ([Item]) -> Void) {
self.getAllItems { (items) in
if keyword.isEmpty {
handler(items)
} else {
let matchItems = items.filter({ (item) -> Bool in
return item.title.contains(keyword) || item.detail.contains(keyword)
})
handler(matchItems)
}
}
}
func getAllItemIDs(_ handler: ([Int]) -> Void) {
self.getAllItems { (items) in
let itemIDs = items.map { $0.ID }
handler(itemIDs)
}
}
func getItemDetail(_ ID: Int, handler: (Item) -> Void) {
let item = self.itemForID(ID, imageQuarity: "large")
handler(item)
}
// MARK: -
fileprivate func itemForID(_ ID: Int, imageQuarity: String) -> Item {
guard let fixture = self.fixtures[ID] else {
fatalError()
}
guard
let title = fixture["title"],
let detail = fixture["detail"],
let imagePrefix = fixture["image_prefix"]
else {
fatalError()
}
return Item(ID: ID, title: title, detail: detail, image: UIImage(named: "\(imagePrefix)_\(imageQuarity)"))
}
fileprivate let fixtures = [
1: [
"title": "弁当",
"detail": "弁当(辨當、べんとう)とは、携帯できるようにした食糧のうち、食事に相当するものである。家庭で作る手作り弁当と、市販される商品としての弁当の2種に大別される。後者を「買い弁」ということがある[1]。海外でも'Bento'として日本式の弁当箱とともに普及し始めた。",
"image_prefix": "bento"
],
2: [
"title": "夕焼け",
"detail": "夕焼け(ゆうやけ)は、日没の頃、西の地平線に近い空が赤く見える現象のこと。夕焼けの状態の空を夕焼け空、夕焼けで赤く染まった雲を「夕焼け雲」と称する。日の出の頃に東の空が同様に見えるのは朝焼け(あさやけ)という。",
"image_prefix": "evening"
],
3: [
"title": "クラゲ",
"detail": "クラゲ(水母、海月、水月)は、刺胞動物門に属する動物のうち、淡水または海水中に生息し浮遊生活をする種の総称。体がゼラチン質で、普通は触手を持って捕食生活をしている。また、それに似たものもそう呼ぶこともある。",
"image_prefix": "jellyfish"
],
4: [
"title": "バラ",
"detail": "バラ(薔薇)は、バラ科バラ属の総称である[1][2][3]。あるいは、そのうち特に園芸種(園芸バラ・栽培バラ)を総称する[1]。ここでは、後者の園芸バラ・栽培バラを扱うこととする。",
"image_prefix": "rose"
],
5: [
"title": "塔",
"detail": "塔(とう)とは、接地面積に比較して著しく高い構造物のことである。",
"image_prefix": "tower"
]
]
}
|
bb807125234960e6cf2b4132fae9c543
| 29.346535 | 155 | 0.52137 | false | false | false | false |
haawa799/WaniKani-iOS
|
refs/heads/master
|
Pods/WaniKit/Sources/WaniKit/ParseVocabListOperation.swift
|
gpl-3.0
|
2
|
//
// ParseUserInfoOperation.swift
// Pods
//
// Created by Andriy K. on 12/14/15.
//
//
import Foundation
public typealias VocabListResponse = (userInfo: UserInfo?, vocab: [WordInfo]?)
public typealias VocabListResponseHandler = (Result<VocabListResponse, NSError>) -> Void
public class ParseVocabListOperation: ParseOperation<VocabListResponse> {
override init(cacheFile: NSURL, handler: ResponseHandler) {
super.init(cacheFile: cacheFile, handler: handler)
name = "Parse Vocab list"
}
override func parsedValue(rootDictionary: NSDictionary?) -> VocabListResponse? {
var user: UserInfo?
if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary {
user = UserInfo(dict: userInfo)
}
var vocab: [WordInfo]?
if let requestedInfo = rootDictionary?[WaniKitConstants.ResponseKeys.RequestedInfoKey] as? [NSDictionary] {
vocab = requestedInfo.map({ (dict) -> WordInfo in
return WordInfo(dict: dict)
})
}
return (user, vocab)
}
}
|
c3eb12594f73efe79eed11b2286b978b
| 26.153846 | 111 | 0.698772 | false | false | false | false |
dankogai/swift-json
|
refs/heads/master
|
Sources/JSONRun/main.swift
|
mit
|
1
|
import JSON
import Foundation
let json0:JSON = [
"null": nil,
"bool": true,
"int": -42,
"double": 42.1953125,
"String": "漢字、カタカナ、ひらがなと\"引用符\"の入ったstring😇",
"array": [nil, true, 1, "one", [1], ["one":1]],
"object": [
"null":nil, "bool":false, "number":0, "string":"" ,"array":[], "object":[:]
],
"url":"https://github.com/dankogai/",
"keys that contain space":"remains unquoted",
"keys that contain\nnewlines":"is quoted",
"values that contain newlines":"is\nquoted"
]
print(json0)
var data = try JSONEncoder().encode(json0)
let json1 = try JSONDecoder().decode(JSON.self, from:data)
print(json1)
print(json0 == json1)
struct Point:Hashable, Codable { let (x, y):(Int, Int) }
data = try JSONEncoder().encode(Point(x:3, y:4))
print( try JSONDecoder().decode(JSON.self, from:data) )
extension JSON {
var yaml:String {
return self.walk(depth:0, collect:{ node, pairs, depth in
let indent = Swift.String(repeating:" ", count:depth)
var result = ""
switch node.type {
case .array:
guard !pairs.isEmpty else { return "[]"}
result = pairs.map{ "- " + $0.1}.map{indent + $0}.joined(separator: "\n")
case .object:
guard !pairs.isEmpty else { return "{}"}
result = pairs.sorted{ $0.0.key! < $1.0.key! }.map{
let k = $0.0.key!
let q = k.rangeOfCharacter(from: .newlines) != nil
return (q ? k.debugDescription : k) + ": " + $0.1
}.map{indent + $0}.joined(separator: "\n")
default:
break // never reaches here
}
return "\n" + result
},visit:{
if $0.isNull { return "~" }
if let s = $0.string {
return s.rangeOfCharacter(from: .newlines) == nil ? s : s.debugDescription
}
return $0.description
})
}
}
print(json0.yaml)
|
ca88f4da2de9ef410df8bfe0f73f19b0
| 31.919355 | 90 | 0.516414 | false | false | false | false |
kybernetyk/netmap
|
refs/heads/master
|
NetMap/NmapXMLParser.swift
|
agpl-3.0
|
1
|
//
// NmapXMLParser.swift
// NetMap
//
// Created by kyb on 24/12/15.
// Copyright © 2015 Suborbital Softworks Ltd. All rights reserved.
//
import Foundation
import SWXMLHash
class NmapXMLParser {
var nextNodeID: Int = 0
enum ParserError : Error {
case fileOpenError(String)
case invalidXMLError(Int)
}
func parseXMLFile(_ file: String) throws -> Project {
guard let xmldata = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
throw ParserError.fileOpenError(file)
}
let xml = SWXMLHash.parse(xmldata)
self.nextNodeID = 0
let rootNode = try self.makeTreeFromXML(xml)
let p = Project(representedFile: file, rootNode: rootNode)
return p
}
}
extension NmapXMLParser {
func makeTreeFromXML(_ xml: XMLIndexer) throws -> Node {
self.nextNodeID += 1
let nodeid = self.nextNodeID
var rootNode = Node(id: nodeid, kind: .network)
//let's just do this here
let root = try xml.byKey("nmaprun")
if let hname = root.element?.allAttributes["startstr"] {
rootNode.hostname = hname.text
} else {
throw ParserError.invalidXMLError(1)
}
if let addr = root.element?.allAttributes["args"] {
rootNode.address = addr.text
} else {
throw ParserError.invalidXMLError(2)
}
let hosts = root.children.filter({$0.element?.name == "host"})
for h in hosts {
let addresses = h.children.filter({$0.element?.name == "address"})
let hostnames = h["hostnames"].children.filter({$0.element?.name == "hostname"})
let ports = h["ports"].children.filter({$0.element?.name == "port"})
self.nextNodeID += 1
let nodeid = self.nextNodeID
var hnode = Node(id: nodeid, kind: .host)
hnode.address = addresses.first?.element?.allAttributes["addr"]?.text ?? "Unknown Address"
hnode.hostname = hostnames.first?.element?.allAttributes["name"]?.text // ?? "Unknown Hostname"
for p in ports {
var port = Port()
port.rawValue = Int(p.element?.allAttributes["portid"]?.text ?? "0") ?? 0
port.proto = Port.Proto(string: p.element?.allAttributes["protocol"]?.text ?? "Unknown")
port.state = Port.State(string: p["state"].element?.allAttributes["state"]?.text ?? "Unknown")
hnode.ports.append(port)
}
rootNode.appendChild(hnode)
}
return rootNode;
}
}
|
ce0b77c40e799c5ddbb7e0a60158eabe
| 33 | 110 | 0.561397 | false | false | false | false |
pixlwave/Stingtk-iOS
|
refs/heads/main
|
Source/Views/AddStingButton.swift
|
mpl-2.0
|
1
|
import UIKit
class AddStingButton: UIControl {
let shape = CAShapeLayer()
required init?(coder: NSCoder) {
super.init(coder: coder)
shape.fillColor = UIColor.clear.cgColor
shape.strokeColor = UIColor.secondaryLabel.cgColor
shape.lineWidth = 4
shape.lineDashPattern = [8, 8]
layer.addSublayer(shape)
}
override func layoutSubviews() {
super.layoutSubviews()
shape.path = CGPath(roundedRect: bounds.insetBy(dx: shape.lineWidth, dy: shape.lineWidth), cornerWidth: 8, cornerHeight: 8, transform: nil)
}
}
|
d8e4809b296f1d3949457a072d59ec9b
| 26.954545 | 147 | 0.634146 | false | false | false | false |
neoneye/SwiftyFORM
|
refs/heads/master
|
Example/HeaderFooter/NoHeaderViewController.swift
|
mit
|
1
|
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import SwiftyFORM
class NoHeaderViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "No Header"
builder.suppressHeaderForFirstSection = true
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
builder += SectionFormItem()
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
builder += SectionFormItem()
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
builder += StaticTextFormItem().title("Empty Row")
}
}
|
22ce588edb8806631c29dcb7cda06964
| 38.047619 | 67 | 0.739024 | false | false | false | false |
mnespor/transit-swift
|
refs/heads/master
|
Common/Link.swift
|
apache-2.0
|
1
|
//
// Link.swift
// Transit
//
// Created by Matthew Nespor on 9/25/14.
//
//
import Foundation
public struct Link : Hashable
{
public let URI: NSURL
public let rel: String
public let name: String?
public let prompt: String?
public let render: String?
public enum Render: String {
case Image = "image"
case Link = "link"
}
public var hashValue: Int {
get {
if var fullDescription = URI.absoluteString {
fullDescription = fullDescription + rel
if let n = name { fullDescription += n }
if let p = prompt { fullDescription += p }
if let r = render { fullDescription += r }
return fullDescription.hashValue
}
else {
var fullDescription = rel
if let n = name { fullDescription += n }
if let p = prompt { fullDescription += p }
if let r = render { fullDescription += r }
return fullDescription.hashValue
}
}
}
public init(uri: NSURL, rel: String, name: String?, prompt: String?, render: Render?) {
self.URI = uri
self.rel = rel
self.name = name
self.prompt = prompt
self.render = render?.toRaw()
}
}
public func == (lhs: Link, rhs: Link) -> Bool {
return lhs.URI.isEqual(rhs.URI) && lhs.rel == rhs.rel && lhs.name == rhs.name && lhs.prompt == rhs.prompt && lhs.render == rhs.render
}
public func != (lhs: Link, rhs: Link) -> Bool {
return !(lhs == rhs)
}
|
4da8ddd8175112c8bfbcd1efc234cd44
| 26.637931 | 137 | 0.534956 | false | false | false | false |
sstanic/OnTheMap
|
refs/heads/master
|
On The Map/On The Map/MapViewController.swift
|
mit
|
1
|
//
// MapViewController.swift
// On The Map
//
// Created by Sascha Stanic on 31.03.16.
// Copyright © 2016 Sascha Stanic. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
//# MARK: Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
//# MARK: Attributes
var locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 1000000
var isMapInitialized = false
var observeDataStore = false {
didSet {
if observeDataStore {
DataStore.sharedInstance().addObserver(self, forKeyPath: Utils.OberserverKeyIsLoading, options: .new, context: nil)
}
}
}
//# MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
initializeMapAndLocationManager()
observeDataStore = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
checkLocationAuthorizationStatus()
getData()
}
deinit {
if observeDataStore {
DataStore.sharedInstance().removeObserver(self, forKeyPath: Utils.OberserverKeyIsLoading)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard activityIndicator != nil else {
return
}
if keyPath == Utils.OberserverKeyIsLoading {
// show or hide the activity indicator dependent of the value
if let val = change![.newKey] as! Int? {
if val == 0 {
Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator)
}
else {
Utils.showActivityIndicator(self.view, activityIndicator: self.activityIndicator)
}
}
self.getData()
}
}
//# MARK: - Initialization
fileprivate func initializeMapAndLocationManager() {
mapView.delegate = self
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
//# MARK: Data access
fileprivate func getData() {
Utils.GlobalMainQueue.async {
if DataStore.sharedInstance().isNotLoading {
if let students = DataStore.sharedInstance().studentInformationList {
self.createMapItems(students)
}
}
}
}
//# MARK: Location & Geocoding
fileprivate func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
mapView.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
fileprivate func setCurrentLocation(_ location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
fileprivate func createMapItems(_ results: [StudentInformation]) {
var mapItems = [StudentInformationMapItem]()
for r in results {
// use name from parse data
let name = (r.firstName + " ") + r.lastName
let mapItem = StudentInformationMapItem(uniqueKey: r.uniqueKey, name: name, mediaUrl: r.mediaURL, location: CLLocationCoordinate2D(latitude: r.latitude, longitude: r.longitude))
mapItems.append(mapItem)
}
// in case of a reload: keep it simple. Remove all available annotations and re-add them.
self.mapView.removeAnnotations(self.mapView.annotations)
self.mapView.addAnnotations(mapItems)
}
//# MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? StudentInformationMapItem {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
let btn = UIButton(type: .detailDisclosure)
view.rightCalloutAccessoryView = btn as UIView
}
return view
}
return nil
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView{
if let url = view.annotation!.subtitle {
UIApplication.shared.openURL(URL(string: url!)!)
}
}
}
//# MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if !isMapInitialized {
setCurrentLocation(locations.last!)
isMapInitialized = true
}
}
}
|
bc2ba79dd6946d8c913d84d0744f6232
| 32.44382 | 189 | 0.601545 | false | false | false | false |
li1024316925/Swift-TimeMovie
|
refs/heads/master
|
Swift-TimeMovie/Swift-TimeMovie/FirstViewController.swift
|
apache-2.0
|
1
|
//
// FirstViewController.swift
// SwiftTimeMovie
//
// Created by DahaiZhang on 16/10/25.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var closeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//将button隐藏
closeButton.isHidden = true
createScrollView()
}
@IBAction func closeBtnAction(_ sender: UIButton) {
//显示主页面
MainViewController().createMainViewContorller()
}
//设置滑动视图
func createScrollView() -> Void {
//分页
scrollView.isPagingEnabled = true
scrollView.delegate = self
scrollView.contentSize = CGSize(width: kScreen_W()*3, height: kScreen_H())
for i in 0 ..< 3 {
let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*kScreen_W(), y: 0, width: kScreen_W(), height: kScreen_H()))
imageView.image = UIImage(named: String(format: "wizard%d_920.jpg", arguments: [i+1]))
scrollView.addSubview(imageView)
}
}
}
extension FirstViewController:UIScrollViewDelegate{
//已经结束减速
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//判断当前页数
let index = Int(scrollView.contentOffset.x/kScreen_W())
if index == 2 {
closeButton.isHidden = false
} else {
closeButton.isHidden = true
}
}
}
|
14933658862093d70027807f8c766992
| 22.57971 | 128 | 0.570375 | false | false | false | false |
joshpar/Lyrebird
|
refs/heads/master
|
LyrebirdSynth/Lyrebird/LyrebirdMain.swift
|
artistic-2.0
|
1
|
//
// Lyrebird.swift
// Lyrebird
//
// Created by Joshua Parmenter on 5/1/16.
// Copyright © 2016 Op133Studios. All rights reserved.
//
open class Lyrebird {
/// ---
/// The number of audio channels (physical and internal) to support
///
/// - Warning: keep these values as powers of 2 for efficiency reasons!
fileprivate (set) open var numberOfAudioChannels : LyrebirdInt
/// ---
/// number of physical input channels to account for
///
fileprivate (set) open var numberOfInputChannels : LyrebirdInt
/// ---
/// number of physical output channels to account for
///
fileprivate (set) open var numberOfOutputChannels : LyrebirdInt
/// ---
/// The number of control channels to support
///
/// - Warning: keep these values as powers of 2 for efficiency reasons!
fileprivate (set) open var numberOfControlChannels : LyrebirdInt
/// ---
/// The number of wires for Graph audio communication
///
/// - Warning: keep these values as powers of 2 for efficiency reasons!
fileprivate (set) open var numberOfWires : LyrebirdInt
/// ---
/// The size of the internal control block
///
/// - Warning: keep these values as powers of 2 for efficiency reasons!
/// - Warning: this is NOT the size of the system callback size. This is internal only
fileprivate (set) open var blockSize : LyrebirdInt {
didSet {
self.iBlockSize = 1.0 / LyrebirdFloat(blockSize)
}
}
/// ---
/// A scaler for calculating steps for interpolation across control periods
///
fileprivate var iBlockSize : LyrebirdFloat = 1.0
/// ---
/// The audio sample rate, in HZ, the system is running at shuld be used for internal calculations
///
fileprivate (set) open var sampleRate : LyrebirdFloat = 44100.0
fileprivate (set) open var iSampleRate : LyrebirdFloat = 0.000022676
/// ---
/// The processing engine
///
static let engine : LyrebirdEngine = LyrebirdEngine.engine
/**
Designated initializer for the main synth environment.
- parameter numberOfAudioChannels: the number of audio channels to allocate memory for
- parameter numberOfInputChannels: the number of physical input channels to reserve space for
- parameter numberOfOutputChannels: the number of physical output channels to reserve space for
- parameter numberOfControlChannels: the number of control channels to allocate
- parameter numberOfWires: the number of audio wires to allocate, which is the limit for the number of interconnects in a graph
- parameter internalMemoryPoolSize: the size of the preallocated internal memory pool for fast allocation
- parameter controlBlockSize: the internal
- Returns:
- Throws:
*/
public required init(numberOfAudioChannels: LyrebirdInt,
numberOfInputChannels: LyrebirdInt,
numberOfOutputChannels: LyrebirdInt,
numberOfControlChannels: LyrebirdInt,
sampleRate: LyrebirdFloat,
numberOfWires: LyrebirdInt,
blockSize: LyrebirdInt
){
self.numberOfAudioChannels = numberOfAudioChannels
self.numberOfInputChannels = numberOfInputChannels
self.numberOfOutputChannels = numberOfOutputChannels
self.numberOfControlChannels = numberOfControlChannels
self.numberOfWires = numberOfWires
self.blockSize = blockSize
self.sampleRate = sampleRate
self.iSampleRate = 1.0 / sampleRate
self.iBlockSize = 1.0 / LyrebirdFloat(self.blockSize)
Lyrebird.engine.numberOfAudioChannels = self.numberOfAudioChannels
Lyrebird.engine.numberOfControlChannels = self.numberOfControlChannels
Lyrebird.engine.blockSize = self.blockSize
Lyrebird.engine.iBlockSize = self.iBlockSize
startEngine()
}
public convenience init() {
self.init(numberOfAudioChannels: 128,
numberOfInputChannels: 2,
numberOfOutputChannels: 2,
numberOfControlChannels: 256,
sampleRate: 44100.0,
numberOfWires: 256,
blockSize: 64)
}
open func startEngine(){
Lyrebird.engine.delegate = self
Lyrebird.engine.start()
}
open func stopEngine(){
Lyrebird.engine.delegate = self
Lyrebird.engine.stop()
}
open func runTests(){
Lyrebird.engine.runTests()
}
open func processBlock(){
// dummy for now
Lyrebird.engine.processWithInputChannels(inputChannels: [])
}
open func addNodeToHead(node: LyrebirdNode?){
if let node = node {
Lyrebird.engine.tree.defaultGroup.addNodeToHead(node: node)
}
}
open func addNodeToTail(node: LyrebirdNode?){
if let node = node {
Lyrebird.engine.tree.defaultGroup.addNodeToTail(node: node)
}
}
open func createParallelGroup() -> LyrebirdParallelGroup {
let group = LyrebirdParallelGroup()
Lyrebird.engine.tree.addParallelGroup(parallelGroup: group)
return group
}
open func removeParallelGroup(parallelGroup: LyrebirdParallelGroup){
Lyrebird.engine.tree.removeParallelGroup(parallelGroup: parallelGroup)
}
open func freeAll(){
Lyrebird.engine.tree.freeAll()
}
open func processWithInputChannels(inputChannels: [LyrebirdAudioChannel]){
Lyrebird.engine.processWithInputChannels(inputChannels: inputChannels)
}
open func audioBlocks() -> [LyrebirdAudioChannel] {
return Lyrebird.engine.audioBlock
}
}
extension Lyrebird: LyrebirdEngineDelegate {
func synthEngineHasStarted(engine: LyrebirdEngine) {
print("Engine started!")
// if let inputChannels : [LyrebirdAudioChannel] = audioBlock[0 ..< 1] as? [LyrebirdAudioChannel] {
// engine.processWithInputChannels(inputChannels) { (finished) in
// print("\(finished)")
// }
// }
}
func synthEngineHasStopped(engine: LyrebirdEngine) {
print("Engine quit!")
}
}
|
297a5b2f91766d2a6ec871c3ea0ae5ea
| 32.47449 | 132 | 0.623685 | false | false | false | false |
remirobert/Splime
|
refs/heads/master
|
example/Example/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Example
//
// Created by Remi Robert on 21/01/16.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
import Splime
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var splimeVideo: Splime!
var frames = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
if let stringPath = NSBundle.mainBundle().pathForResource("video", ofType: "mp4") {
self.splimeVideo = Splime(url: stringPath)
self.splimeVideo.everyFrames = 10
self.splimeVideo.split({ (images) -> () in
self.frames = images
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.collectionView.reloadData()
})
}, progressBlock: { (progress) -> () in
print("current progress : \(progress)")
})
}
self.collectionView.registerNib(UINib(nibName: "FrameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
self.collectionView.dataSource = self
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.frames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! FrameCollectionViewCell
cell.imageViewFrame.image = self.frames[indexPath.row]
return cell
}
}
|
a6499042512f4c16895a1a5ddd2c755f
| 32.236364 | 133 | 0.612144 | false | false | false | false |
BenEmdon/swift-algorithm-club
|
refs/heads/master
|
Longest Common Subsequence/LongestCommonSubsequence.playground/Contents.swift
|
mit
|
9
|
extension String {
public func longestCommonSubsequence(_ other: String) -> String {
func lcsLength(_ other: String) -> [[Int]] {
var matrix = [[Int]](repeating: [Int](repeating: 0, count: other.characters.count+1), count: self.characters.count+1)
for (i, selfChar) in self.characters.enumerated() {
for (j, otherChar) in other.characters.enumerated() {
if otherChar == selfChar {
matrix[i+1][j+1] = matrix[i][j] + 1
} else {
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
}
}
}
return matrix
}
func backtrack(_ matrix: [[Int]]) -> String {
var i = self.characters.count
var j = other.characters.count
var charInSequence = self.endIndex
var lcs = String()
while i >= 1 && j >= 1 {
if matrix[i][j] == matrix[i][j - 1] {
j -= 1
} else if matrix[i][j] == matrix[i - 1][j] {
i -= 1
charInSequence = self.index(before: charInSequence)
} else {
i -= 1
j -= 1
charInSequence = self.index(before: charInSequence)
lcs.append(self[charInSequence])
}
}
return String(lcs.characters.reversed())
}
return backtrack(lcsLength(other))
}
}
// Examples
let a = "ABCBX"
let b = "ABDCAB"
let c = "KLMK"
a.longestCommonSubsequence(c) // ""
a.longestCommonSubsequence("") // ""
a.longestCommonSubsequence(b) // "ABCB"
b.longestCommonSubsequence(a) // "ABCB"
a.longestCommonSubsequence(a) // "ABCBX"
"Hello World".longestCommonSubsequence("Bonjour le monde")
|
a085b38bec1beb2d978f494aee575981
| 27.034483 | 123 | 0.565806 | false | false | false | false |
stormpath/stormpath-swift-example
|
refs/heads/master
|
Pods/Stormpath/Stormpath/Networking/RegistrationForm.swift
|
mit
|
1
|
//
// RegistrationAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 2/5/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
/**
Model for the account registration form. The fields requested in the initializer
are required.
*/
@objc(SPHRegistrationForm)
public class RegistrationForm: NSObject {
/**
Given (first) name of the user. Required by default, but can be turned off
in the Framework configuration.
*/
public var givenName = ""
/**
Sur (last) name of the user. Required by default, but can be turned off in
the Framework configuration.
*/
public var surname = ""
/// Email address of the user. Only validated server-side at the moment.
public var email: String
/// Password for the user. Only validated server-side at the moment.
public var password: String
/**
Username. Optional, but if not set retains the value of the email address.
*/
public var username = ""
/**
Custom fields may be configured in the server-side API. Include them in
this
*/
public var customFields = [String: String]()
/**
Initializer for Registration Model. After initialization, all fields can be
modified.
- parameters:
- givenName: Given (first) name of the user.
- surname: Sur (last) name of the user.
- email: Email address of the user.
- password: Password for the user.
*/
public init(email: String, password: String) {
self.email = email
self.password = password
}
var asDictionary: [String: Any] {
var registrationDictionary: [String: Any] = customFields
let accountDictionary = ["username": username, "email": email, "password": password, "givenName": givenName, "surname": surname]
for (key, value) in accountDictionary {
if value != "" {
registrationDictionary[key] = value
}
}
return registrationDictionary
}
}
|
2c45820960bb30a361a2afb226a2f64e
| 27.364865 | 136 | 0.620295 | false | false | false | false |
CYXiang/CYXSwiftDemo
|
refs/heads/master
|
CYXSwiftDemo/CYXSwiftDemo/Classes/Profile/ProfileTableViewController.swift
|
apache-2.0
|
1
|
//
// ProfileTableViewController.swift
// CYXSwiftDemo
//
// Created by Macx on 15/11/7.
// Copyright © 2015年 cyx. All rights reserved.
//
import UIKit
class ProfileTableViewController: BaseViewController {
private var headView: MineHeadView!
private var tableView: CYXTableView!
private var headViewHeight: CGFloat = 150
private var couponNum: Int = 0
private let shareActionSheet: LFBActionSheet = LFBActionSheet()
// private lazy var mines: [MineCellModel]
// MARK: - Lief Cycle
override func loadView() {
super.loadView()
self.navigationController?.navigationBar.hidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
buildUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
weak var weakSelf = self
}
// MARK: - CreatUI
private func buildUI(){
}
}
|
ce2a6832e43e018405ba4eaae3aeaa8e
| 20.44 | 74 | 0.625933 | false | false | false | false |
robbdimitrov/pixelgram-ios
|
refs/heads/master
|
PixelGram/Classes/Screens/Feed/FeedViewModel.swift
|
mit
|
1
|
//
// FeedViewModel.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/27/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import RxSwift
class FeedViewModel {
enum FeedType: Int {
case feed
case single
case likes
var title: String {
switch self {
case .feed:
return "Feed"
case .single:
return "Photo"
case .likes:
return "Likes"
}
}
}
var type = FeedType.feed
var images = Variable<[Image]>([])
var page = 0 // Page number (used for data loading)
var loadingFinished: ((Int, Int) -> Void)?
var loadingFailed: ((String) -> Void)?
var numberOfItems: Int {
return images.value.count
}
var title: String {
return type.title
}
init(with type: FeedType = .feed, images: [Image] = []) {
self.type = type
self.images.value.append(contentsOf: images)
}
// MARK: - Getters
func imageViewModel(forIndex index: Int) -> ImageViewModel {
return ImageViewModel(with: images.value[index])
}
// MARK: - Data loading
func loadData() {
if type == .single {
loadImage()
} else {
loadImages()
}
}
private func loadImage() {
guard let image = images.value.first else {
return
}
APIClient.shared.loadImage(withId: image.id, completion: { [weak self] images in
let oldCount = self?.images.value.count ?? 0
self?.images.value.removeAll()
self?.images.value.append(contentsOf: images)
let count = self?.images.value.count ?? 0
self?.loadingFinished?(oldCount, count)
}) { [weak self] error in
self?.loadingFailed?(error)
}
}
private func loadImages() {
let oldCount = numberOfItems
let completion: APIClient.ImageCompletion = { [weak self] images in
if images.count > 0 {
self?.page += 1
self?.images.value.append(contentsOf: images)
}
let count = self?.numberOfItems ?? 0
self?.loadingFinished?(oldCount, count)
}
let failure: APIClient.ErrorBlock = { [weak self] error in
print("Loading images failed: \(error)")
self?.loadingFailed?(error)
}
if type == .feed {
APIClient.shared.loadImages(forPage: page, completion: completion, failure: failure)
} else if type == .likes, let userId = Session.shared.currentUser?.id {
APIClient.shared.loadImages(forUserId: userId,
likes: true, page: page,
completion: completion, failure: failure)
}
}
}
|
498a9dd3e172effd2e88ec94ca1f8b52
| 26.214286 | 96 | 0.508202 | false | false | false | false |
CD1212/Doughnut
|
refs/heads/master
|
Doughnut/View Controllers/DetailViewController.swift
|
gpl-3.0
|
1
|
/*
* Doughnut Podcast Client
* Copyright (C) 2017 Chris Dyer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
import WebKit
enum DetailViewType {
case BlankDetail
case PodcastDetail
case EpisodeDetail
}
class DetailViewController: NSViewController, WKNavigationDelegate {
@IBOutlet weak var detailTitle: NSTextField!
@IBOutlet weak var secondaryTitle: NSTextField!
@IBOutlet weak var miniTitle: NSTextField!
@IBOutlet weak var coverImage: NSImageView!
@IBOutlet weak var webView: WKWebView!
let dateFormatter = DateFormatter()
var detailType: DetailViewType = .BlankDetail {
didSet {
switch detailType {
case .PodcastDetail:
showPodcast()
case .EpisodeDetail:
showEpisode()
default:
showBlank()
}
}
}
var episode: Episode? {
didSet {
if episode != nil {
detailType = .EpisodeDetail
} else if podcast != nil {
detailType = .PodcastDetail
} else {
detailType = .BlankDetail
}
}
}
var podcast: Podcast? {
didSet {
if podcast != nil {
if podcast?.id != oldValue?.id {
detailType = .PodcastDetail
}
} else {
detailType = .BlankDetail
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let darkMode = DoughnutApp.darkMode()
dateFormatter.dateStyle = .long
view.wantsLayer = true
if darkMode {
view.layer?.backgroundColor = NSColor(calibratedRed:0.220, green:0.204, blue:0.208, alpha:1.00).cgColor
} else {
view.layer?.backgroundColor = CGColor.white
}
webView.navigationDelegate = self
webView.loadHTMLString(MarkupGenerator.blankMarkup(), baseURL: nil)
}
func showBlank() {
detailTitle.stringValue = ""
secondaryTitle.stringValue = ""
miniTitle.stringValue = ""
}
func showPodcast() {
guard let podcast = podcast else {
showBlank()
return
}
detailTitle.stringValue = podcast.title
secondaryTitle.stringValue = podcast.author ?? ""
miniTitle.stringValue = podcast.link ?? ""
coverImage.image = podcast.image
webView.loadHTMLString(MarkupGenerator.markup(forPodcast: podcast), baseURL: nil)
}
func showEpisode() {
guard let episode = episode else {
showBlank()
return
}
detailTitle.stringValue = episode.title
secondaryTitle.stringValue = podcast?.title ?? ""
if let pubDate = episode.pubDate {
miniTitle.stringValue = dateFormatter.string(for: pubDate) ?? ""
}
if let artwork = episode.artwork {
coverImage.image = artwork
} else {
coverImage.image = podcast?.image
}
webView.loadHTMLString(MarkupGenerator.markup(forEpisode: episode), baseURL: nil)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url {
NSWorkspace.shared.open(url)
}
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}
|
8ba6f6eac4aa9ff2665cd687ca3de917
| 25.135135 | 155 | 0.655636 | false | false | false | false |
cdtschange/SwiftMKit
|
refs/heads/master
|
SwiftMKit/Extension/Action+Extension.swift
|
mit
|
1
|
//
// Action+Extension.swift
// SwiftMKitDemo
//
// Created by Mao on 5/19/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
import ReactiveCocoa
import ReactiveSwift
import UIKit
public extension Action {
public func bindEnabled(_ button: UIButton) {
self.privateCocoaAction.isEnabled.producer.startWithValues { enabled in
button.isEnabled = enabled
button.viewContainingController?.view.isUserInteractionEnabled = enabled
button.viewContainingController?.view.endEditing(false)
}
}
public var toCocoaAction: CocoaAction<Any> {
get {
privateCocoaAction = CocoaAction(self) { input in
if let button = input as? UIButton {
self.bindEnabled(button)
}
return input as! Input
}
return privateCocoaAction
}
}
}
private var privateCocoaActionAssociationKey: UInt8 = 0
extension Action {
var privateCocoaAction: CocoaAction<Any> {
get {
return objc_getAssociatedObject(self, &privateCocoaActionAssociationKey) as! CocoaAction
}
set(newValue) {
objc_setAssociatedObject(self, &privateCocoaActionAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
|
f18c3a2d6d3472db2f629f32b5832ce2
| 27.723404 | 135 | 0.646667 | false | false | false | false |
kaltura/playkit-ios
|
refs/heads/develop
|
Classes/Models/PKBoundary.swift
|
agpl-3.0
|
1
|
// ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
/// `PKBoundary` used as abstract for boundary types (% and time).
@objc public protocol PKBoundary {
var time: TimeInterval { get }
}
/// `PKBoundaryFactory` factory class used to create boundary objects easily.
@objc public class PKBoundaryFactory: NSObject {
let duration: TimeInterval
@objc public init (duration: TimeInterval) {
self.duration = duration
}
@objc public func percentageTimeBoundary(boundary: Int) -> PKPercentageTimeBoundary {
return PKPercentageTimeBoundary(boundary: boundary, duration: self.duration)
}
@objc public func timeBoundary(boundaryTime: TimeInterval) -> PKTimeBoundary {
return PKTimeBoundary(boundaryTime: boundaryTime, duration: self.duration)
}
}
/// `PKPercentageTimeBoundary` represents a time boundary in % against the media duration.
@objc public class PKPercentageTimeBoundary: NSObject, PKBoundary {
/// The time to set the boundary on.
public let time: TimeInterval
/// Creates a new `PKPercentageTimeBoundary` object from %.
/// - Attention: boundary value should be between 1 and 100 otherwise will use default values!
@objc public init(boundary: Int, duration: TimeInterval) {
switch boundary {
case 1...100: self.time = duration * TimeInterval(boundary) / TimeInterval(100)
case Int.min...0: self.time = 0
case 101...Int.max: self.time = duration
default: self.time = 0
}
}
}
/// `PKTimeBoundary` represents a time boundary in seconds.
@objc public class PKTimeBoundary: NSObject, PKBoundary {
/// The time to set the boundary on.
@objc public let time: TimeInterval
/// Creates a new `PKTimeBoundary` object from seconds.
/// - Attention: boundary value should be between 0 and duration otherwise will use default values!
@objc public init(boundaryTime: TimeInterval, duration: TimeInterval) {
if boundaryTime <= 0 {
self.time = 0
} else if boundaryTime >= duration {
self.time = duration
} else {
self.time = boundaryTime
}
}
}
|
f05185ca0dea22c131cbd3667cd128b1
| 36.126761 | 103 | 0.625569 | false | false | false | false |
DarielChen/DemoCode
|
refs/heads/master
|
iOS动画指南/iOS动画指南 - 4.右拉的3D抽屉效果/SideMenu/MenuItem.swift
|
mit
|
1
|
//
// MenuItem.swift
// SideMenu
//
// Created by Dariel on 16/7/13.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
let menuColors = [
UIColor(red: 118/255, green: 165/255, blue: 175/255, alpha: 1.0),
UIColor(red: 213/255, green: 166/255, blue: 189/255, alpha: 1.0),
UIColor(red: 106/255, green: 168/255, blue: 79/255, alpha: 1.0),
UIColor(red: 103/255, green: 78/255, blue: 167/255, alpha: 1.0),
UIColor(red: 188/255, green: 238/255, blue: 104/255, alpha: 1.0),
UIColor(red: 102/255, green: 139/255, blue: 139/255, alpha: 1.0),
UIColor(red: 230/255, green: 145/255, blue: 56/255, alpha: 1.0)
]
class MenuItem {
let title: String
let symbol: String
let color: UIColor
init(symbol: String, color: UIColor, title: String) {
self.symbol = symbol
self.color = color
self.title = title
}
class var sharedItems: [MenuItem] {
struct Static {
static let items = MenuItem.sharedMenuItems()
}
return Static.items
}
class func sharedMenuItems() -> [MenuItem] {
var items = [MenuItem]()
items.append(MenuItem(symbol: "🐱", color: menuColors[0], title: "鼠"))
items.append(MenuItem(symbol: "🐂", color: menuColors[1], title: "牛"))
items.append(MenuItem(symbol: "🐯", color: menuColors[2], title: "虎"))
items.append(MenuItem(symbol: "🐰", color: menuColors[3], title: "兔"))
items.append(MenuItem(symbol: "🐲", color: menuColors[4], title: "龙"))
items.append(MenuItem(symbol: "🐍", color: menuColors[5], title: "蛇"))
items.append(MenuItem(symbol: "🐴", color: menuColors[6], title: "马"))
return items
}
}
|
556ebcd821cb8204c39e124b05d7b062
| 30.192982 | 77 | 0.579303 | false | false | false | false |
oddnetworks/odd-sample-apps
|
refs/heads/master
|
apple/tvos/tvOSSampleApp/tvOSSampleApp/CollectionCell.swift
|
apache-2.0
|
1
|
//
// CollectionCell.swift
// tvOSSampleApp
//
// Created by Patrick McConnell on 1/28/16.
// Copyright © 2016 Odd Networks. All rights reserved.
//
import UIKit
import OddSDKtvOS
class CollectionCell: UICollectionViewCell {
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
func configureWithCollection(_ collection: OddMediaObjectCollection) {
self.titleLabel?.text = collection.title
collection.thumbnail { (image) -> Void in
if let thumbnail = image {
DispatchQueue.main.async(execute: { () -> Void in
self.thumbnailImageView?.image = thumbnail
})
}
}
}
func becomeFocusedUsingAnimationCoordinator(_ coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({ () -> Void in
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 10, height: 10)
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 5
}) { () -> Void in }
}
func resignFocusUsingAnimationCoordinator(_ coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({ () -> Void in
self.transform = CGAffineTransform.identity
self.layer.shadowColor = nil
self.layer.shadowOffset = CGSize.zero
}) { () -> Void in }
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
guard let nextFocusedView = context.nextFocusedView else { return }
if nextFocusedView == self {
self.becomeFocusedUsingAnimationCoordinator(coordinator)
self.addParallaxMotionEffects()
} else {
self.resignFocusUsingAnimationCoordinator(coordinator)
self.motionEffects = []
}
}
}
|
3b44f5839c5045ad90829c5e591568e8
| 30.129032 | 113 | 0.695337 | false | false | false | false |
koutalou/iOS-CleanArchitecture
|
refs/heads/master
|
iOSCleanArchitectureTwitterSample/Application/Builder/LoginAccountBuilder.swift
|
mit
|
1
|
//
// LoginAccountBuilder.swift
// iOSCleanArchitectureTwitterSample
//
// Created by koutalou on 2016/11/13.
// Copyright © 2016年 koutalou. All rights reserved.
//
import UIKit
struct LoginAccountBuilder {
func build() -> UIViewController {
let wireframe = LoginAccountWireframeImpl()
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Login") as! LoginAccountViewController
let useCase = LoginAccountUseCaseImpl(
loginAccountRepository: LoginAccountRepositoryImpl(
dataStore: LoginAccountDataStoreImpl()
),
socialAccountRepository: SocialAccountRepositoryImpl(
dataStore: SocialAccountDataStoreImpl()
)
)
let presenter = LoginAccountPresenterImpl(useCase: useCase, viewInput: viewController, wireframe: wireframe, observer: SharedObserver.instance)
viewController.inject(presenter: presenter)
wireframe.viewController = viewController
return viewController
}
}
|
9369e2d001549e0089327111fc4332e0
| 35.4 | 151 | 0.692308 | false | false | false | false |
larryhou/swift
|
refs/heads/master
|
TexasHoldem/TexasHoldem/PokerHand.swift
|
mit
|
1
|
//
// PokerHand.swift
// TexasHoldem
//
// Created by larryhou on 9/3/2016.
// Copyright © 2016 larryhou. All rights reserved.
//
import Foundation
enum HandPattern: UInt8 {
case highCard = 1, onePair, twoPair, threeOfKind, straight, flush, fullHouse, fourOfKind, straightFlush
var description: String {
switch self {
case .highCard: return "高牌"
case .onePair: return "一对"
case .twoPair: return "两对"
case .threeOfKind: return "三张" //绿色
case .straight: return "顺子" //蓝色
case .flush: return "同花" //紫色
case .fullHouse: return "葫芦" //橙色
case .fourOfKind: return "炸弹" //红色
case .straightFlush:return "花顺" //
}
}
}
class PokerHand {
var givenCards: [PokerCard]
var tableCards: [PokerCard]
var pattern: HandPattern!
var matches: [PokerCard]!
private var _isReady: Bool = false
var isReady: Bool { return _isReady }
init() {
self.givenCards = []
self.tableCards = []
}
init(givenCards: [PokerCard], tableCards: [PokerCard]) {
self.givenCards = givenCards
self.tableCards = tableCards
}
func reset() {
self.givenCards = []
self.tableCards = []
self.matches = nil
self.pattern = nil
}
func checkQualified() {
assert(givenCards.count == 2)
assert(tableCards.count == 5)
}
func recognize() -> HandPattern {
var cards = (givenCards + tableCards).sort()
var colorStats: [PokerColor: Int] = [:]
var maxSameColorCount = 0
var dict: [Int: [PokerCard]] = [:]
for i in 0..<cards.count {
let item = cards[i]
if dict[item.value] == nil {
dict[item.value] = []
}
dict[item.value]?.append(item)
if colorStats[item.color] == nil {
colorStats[item.color] = 0
}
colorStats[item.color]! += 1
maxSameColorCount = max(colorStats[item.color]!, maxSameColorCount)
}
var kindStats: [Int: Int] = [:]
for (_, list) in dict {
if kindStats[list.count] == nil {
kindStats[list.count] = 0
}
kindStats[list.count]! += 1
}
if let v4 = kindStats[4] where v4 >= 1 {
return .fourOfKind
}
if let v3 = kindStats[3], v2 = kindStats[2] where (v3 == 1 && v2 >= 1) || (v3 >= 2) {
return .fullHouse
}
if cards[0].value == 1 {
cards.append(cards[0])
}
var stack = [cards[0]]
for i in 1..<cards.count {
if (cards[i - 1].value - cards[i].value == 1) || (cards[i - 1].value == 1/*A*/ && cards[i].value == 13/*K*/) {
stack.append(cards[i])
} else
if stack.count < 5 {
stack = [cards[i]]
}
}
if stack.count >= 5 {
for i in 0..<stack.count - 5 {
var count = 1
for j in i + 1..<i + 5 {
if stack[j - 1].color != stack[j].color {
break
}
count += 1
}
if count == 5 {
return .straightFlush
}
}
return .straight
}
if maxSameColorCount >= 5 {
return .flush
}
if let v3 = kindStats[3] where v3 == 1 {
return .threeOfKind
}
if let v2 = kindStats[2] {
if v2 >= 2 {
return .twoPair
} else
if v2 == 1 {
return .onePair
}
}
return .highCard
}
func evaluate() {
pattern = recognize()
switch pattern! {
case .highCard:HandV1HighCard.evaluate(self)
case .onePair:HandV2OnePair.evaluate(self)
case .twoPair:HandV3TwoPair.evaluate(self)
case .threeOfKind:HandV4TreeOfKind.evaluate(self)
case .straight:HandV5Straight.evaluate(self)
case .flush:HandV6Flush.evaluate(self)
case .fullHouse:HandV7FullHouse.evaluate(self)
case .fourOfKind:HandV8FourOfKind.evaluate(self)
case .straightFlush:HandV9StraightFlush.evaluate(self)
}
_isReady = true
}
var description: String {
return String(format: "%@ {%@} [%@] [%@]", pattern.description, matches.toString(), givenCards.toString(), tableCards.toString())
}
}
func == (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return false
}
}
return true
}
func != (left: PokerHand, right: PokerHand) -> Bool {
return !(left == right)
}
func > (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] > right.matches[i]
}
}
return false
}
func >= (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] > right.matches[i]
}
}
return true
}
func < (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] < right.matches[i]
}
}
return false
}
func <= (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] < right.matches[i]
}
}
return true
}
|
49c1d9dc0c673e72648d08126f40a088
| 24.447368 | 137 | 0.496553 | false | false | false | false |
MLSDev/TRON
|
refs/heads/main
|
Source/Tests/PluginTester.swift
|
mit
|
1
|
//
// PluginTester.swift
// TRON
//
// Created by Denys Telezhkin on 30.01.16.
// Copyright © 2016 Denys Telezhkin. All rights reserved.
//
import TRON
import Foundation
class PluginTester: Plugin {
var willSendCalled = false
var willSendAlamofireCalled = false
var didSendAlamofireCalled = false
var didReceiveResponseCalled = false
var didReceiveError = false
var didReceiveSuccess = false
func willSendRequest<Model, ErrorModel>(_ request: BaseRequest<Model, ErrorModel>) {
willSendCalled = true
}
func willSendAlamofireRequest<Model, ErrorModel>(_ request: Request, formedFrom: BaseRequest<Model, ErrorModel>) {
willSendAlamofireCalled = true
}
func didSendAlamofireRequest<Model, ErrorModel>(_ request: Request, formedFrom: BaseRequest<Model, ErrorModel>) {
didSendAlamofireCalled = true
}
func willProcessResponse<Model, ErrorModel>(response: (URLRequest?, HTTPURLResponse?, Data?, Error?), forRequest request: Request, formedFrom: BaseRequest<Model, ErrorModel>) {
didReceiveResponseCalled = true
}
func didSuccessfullyParseResponse<Model, ErrorModel>(_ response: (URLRequest?, HTTPURLResponse?, Data?, Error?), creating result: Model, forRequest request: Request, formedFrom tronRequest: BaseRequest<Model, ErrorModel>) {
didReceiveSuccess = true
}
func didReceiveError<Model, ErrorModel>(_ error: ErrorModel, forResponse response: (URLRequest?, HTTPURLResponse?, Data?, Error?), request: Request, formedFrom tronRequest: BaseRequest<Model, ErrorModel>) where ErrorModel: ErrorSerializable {
didReceiveError = true
}
}
|
8f92511df0437ffbfa44f24bc0fe819a
| 37.581395 | 246 | 0.731163 | false | false | false | false |
tony-dinh/today
|
refs/heads/master
|
today/today/SettingsController.swift
|
mit
|
1
|
//
// SettingsController.swift
// today
//
// Created by Tony Dinh on 2016-11-10.
// Copyright © 2016 Tony Dinh. All rights reserved.
//
import Foundation
import UIKit
class SettingsController:
BaseTableViewController,
UITableViewDelegate,
UITableViewDataSource
{
let settings: [String] = ["Calendars"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Settings"
tableView.delegate = self
tableView.dataSource = self
tableView.register(
DefaultCell.self,
forCellReuseIdentifier: DefaultCell.constants.reuseIdentifier
)
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return DefaultCell(accessoryType: .disclosureIndicator, text: settings[indexPath.row])
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch settings[indexPath.row] {
case "Calendars":
let calendarSettingsController = CalendarSettingsController()
navigationController?.pushViewController(calendarSettingsController, animated: true)
break;
default:
break;
}
}
}
|
8ddf6c5c11b284b3871880a1e18483da
| 26.649123 | 100 | 0.665609 | false | false | false | false |
AlexChekanov/Gestalt
|
refs/heads/master
|
Gestalt/SupportingClasses/General classes Extensions/DirectionalGradient 2.swift
|
apache-2.0
|
2
|
//
// SwiftyGardient.swift
//
//
// Created by Alexey Chekanov on 5/28/17.
// Copyright © 2017 Alexey Chekanov. All rights reserved.
//
import UIKit
@IBDesignable class DirectionalGradient: UIView {
/// The startColor for the Gardient
@IBInspectable var startColor: UIColor = UIColor.clear {
didSet{
setupDirectionalGradient()
}
}
/// The endColor for the Gardient
@IBInspectable var endColor: UIColor = UIColor.blue {
didSet{
setupDirectionalGradient()
}
}
// Angle
@IBInspectable var angle: Double = 0 {
didSet{
setupDirectionalGradient()
}
}
func setupDirectionalGradient() {
let colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: CGFloat(cos(angle*Double.pi/180.0)), y: CGFloat(sin(angle*Double.pi/180.0)))
setNeedsDisplay()
}
var gradientLayer: CAGradientLayer {
return self.layer as! CAGradientLayer
}
override class var layerClass: AnyClass{
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
setupDirectionalGradient()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupDirectionalGradient()
}
}
|
41fe20be2cdc8f8b6b26f7e7fdca270b
| 20.838235 | 120 | 0.606734 | false | false | false | false |
arttuperala/kmbmpdc
|
refs/heads/master
|
kmbmpdc/Search.swift
|
apache-2.0
|
1
|
import Cocoa
struct Identifiers {
static let searchTrackAlbum = NSUserInterfaceItemIdentifier("searchTrackAlbum")
static let searchTrackArtist = NSUserInterfaceItemIdentifier("searchTrackArtist")
static let searchTrackLength = NSUserInterfaceItemIdentifier("searchTrackLength")
static let searchTrackNumber = NSUserInterfaceItemIdentifier("searchTrackNumber")
static let searchTrackTitle = NSUserInterfaceItemIdentifier("searchTrackTitle")
}
class Search: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var resultTable: NSTableView!
var results: [Track] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
super.viewWillAppear()
resetTableSize()
}
/// Returns an array of `Track` objects based on what rows are selected in the table.
var selectedRows: [Track] {
var tracks: [Track] = []
if resultTable.selectedRowIndexes.isEmpty {
tracks.append(results[resultTable.clickedRow])
} else {
for index in resultTable.selectedRowIndexes {
tracks.append(results[index])
}
}
return tracks
}
@IBAction func addAfterCurrentAlbum(_ sender: Any) {
MPDClient.shared.insertAfterCurrentAlbum(selectedRows)
}
@IBAction func addAfterCurrentSong(_ sender: Any) {
MPDClient.shared.insertAfterCurrentTrack(selectedRows)
}
@IBAction func addToEnd(_ sender: Any) {
MPDClient.shared.append(selectedRows)
}
@IBAction func addToBeginning(_ sender: Any) {
MPDClient.shared.insertAtBeginning(selectedRows)
}
@IBAction func itemDoubleClicked(_ sender: Any) {
guard resultTable.clickedRow >= 0, resultTable.clickedRow < results.count else {
return
}
let track = results[resultTable.clickedRow]
MPDClient.shared.append([track])
}
func numberOfRows(in tableView: NSTableView) -> Int {
return results.count
}
/// Performs the search on the `NSSearchField` string value. Empty string clears the results.
@IBAction func performSearch(_ sender: NSSearchField) {
if sender.stringValue.isEmpty {
results.removeAll()
} else {
results = MPDClient.shared.search(for: sender.stringValue)
}
resultTable.reloadData()
}
/// Resizes the table columns to their predefined widths.
func resetTableSize() {
for column in resultTable.tableColumns {
if column.identifier == Identifiers.searchTrackAlbum {
column.width = 170
} else if column.identifier == Identifiers.searchTrackArtist {
column.width = 170
} else if column.identifier == Identifiers.searchTrackLength {
column.width = 43
} else if column.identifier == Identifiers.searchTrackNumber {
column.width = 29
} else if column.identifier == Identifiers.searchTrackTitle {
column.width = 255
}
}
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
guard let identifier = tableColumn?.identifier else {
return nil
}
switch identifier {
case Identifiers.searchTrackAlbum:
return results[row].album
case Identifiers.searchTrackArtist:
return results[row].artist
case Identifiers.searchTrackLength:
return results[row].durationString
case Identifiers.searchTrackNumber:
return results[row].number
case Identifiers.searchTrackTitle:
return results[row].name
default:
return nil
}
}
}
|
1805a9b378a67b343ec4d62112443309
| 33.061947 | 108 | 0.645622 | false | false | false | false |
heshamsalman/OctoViewer
|
refs/heads/master
|
OctoViewer/APIKeys.swift
|
apache-2.0
|
1
|
//
// APIKeys.swift
// OctoViewer
//
// Created by Hesham Salman on 5/24/17.
// Copyright © 2017 Hesham Salman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
private let minimumKeyLength = 2
// MARK: - API Keys
struct APIKeys {
let clientId: String
let clientSecret: String
fileprivate struct SharedKeys {
static var instance = APIKeys()
}
static var sharedKeys: APIKeys {
get {
return SharedKeys.instance
}
set {
SharedKeys.instance = newValue
}
}
// MARK: - Methods
var stubResponses: Bool {
return clientId.characters.count < minimumKeyLength || clientSecret.characters.count < minimumKeyLength
}
// MARK: - Initializers
init(clientId: String, secret: String) {
self.clientId = clientId
clientSecret = secret
}
init() {
guard let dictionary = Bundle.main.infoDictionary,
let clientId = dictionary[Keys.clientId] as? String,
let clientSecret = dictionary[Keys.clientSecret] as? String else {
fatalError("Client ID and Secret don't exist in the current xcconfig or are not referenced in Info.plist")
}
self.init(clientId: clientId, secret: clientSecret)
}
}
private struct Keys {
static let clientId = "ClientId"
static let clientSecret = "ClientSecret"
}
|
035ba0ff0716dc6e66917273dc06b329
| 24.942857 | 112 | 0.701542 | false | false | false | false |
qxuewei/XWPageView
|
refs/heads/master
|
XWPageViewDemo/XWPageViewDemo/XWPageView/UIColor_Extension.swift
|
apache-2.0
|
1
|
//
// UIColor_Extension.swift
// XWPageViewDemo
//
// Created by 邱学伟 on 2016/12/9.
// Copyright © 2016年 邱学伟. All rights reserved.
// swift3 颜色工具类
import UIKit
extension UIColor {
//MARK: - 传入R G B A(可选) 返回对应颜色
convenience init(R: CGFloat, G: CGFloat, B: CGFloat, A: CGFloat = 1.0) {
self.init(red: R / 255.0, green: G / 255.0, blue: B / 255.0, alpha: A)
}
//MARK: - 传入16进制代码 返回对应颜色
convenience init?(hex : String, alpha : CGFloat = 1.0) {
guard hex.characters.count >= 6 else {
return nil
}
// 0xffffff
var tempHex = hex.uppercased()
//判断开头 0x/#/#
if tempHex.hasPrefix("0X") || tempHex.hasPrefix("##") {
tempHex = (tempHex as NSString).substring(from: 2)
}
if tempHex.hasPrefix("#") {
tempHex = (tempHex as NSString).substring(from: 1)
}
//分别取出 RGB
var range : NSRange = NSRange(location : 0, length : 2)
let R_HEX = (tempHex as NSString).substring(with: range)
range.location += 2
let G_HEX = (tempHex as NSString).substring(with: range)
range.location += 2
let B_HEX = (tempHex as NSString).substring(with: range)
var R : UInt32 = 0, G : UInt32 = 0, B : UInt32 = 0
Scanner(string: R_HEX).scanHexInt32(&R)
Scanner(string: G_HEX).scanHexInt32(&G)
Scanner(string: B_HEX).scanHexInt32(&B)
self.init(R : CGFloat(R), G : CGFloat(G), B : CGFloat(B))
}
//MARK: - 随机颜色
class func getRandomColor() -> UIColor {
return UIColor(R: CGFloat(arc4random_uniform(256)), G: CGFloat(arc4random_uniform(256)), B: CGFloat(arc4random_uniform(256)))
}
//MARK: - 返回两RGB传入的颜色差值
class func getRGBDelta(oldRGBColor : UIColor, newRGBColor : UIColor) -> (CGFloat,CGFloat,CGFloat) {
let RGBCompsOld = oldRGBColor.getRGBComps()
let RGBCompsNew = newRGBColor.getRGBComps()
return (RGBCompsOld.0 - RGBCompsNew.0,RGBCompsOld.1 - RGBCompsNew.1,RGBCompsOld.2 - RGBCompsNew.2)
}
//MARK: - 获取颜色RGB
func getRGBComps() -> (CGFloat ,CGFloat, CGFloat) {
guard let colorComps = cgColor.components else {
fatalError("Afferent must RGB Color")
}
return (colorComps[0] * 255.0, colorComps[1] * 255.0, colorComps[2] * 255.0)
}
}
|
740dc0babee4b85c9f94d7ddff5196a4
| 33.724638 | 133 | 0.581386 | false | false | false | false |
larcus94/Sweets
|
refs/heads/master
|
Sweets/UIViewExtensions.swift
|
mit
|
1
|
//
// UIViewExtensions.swift
// Sweets
//
// Created by Laurin Brandner on 10/05/15.
// Copyright (c) 2015 Laurin Brandner. All rights reserved.
//
import UIKit
extension UIView {
public class func animate(#duration: NSTimeInterval, delay: NSTimeInterval = 0, springDamping: CGFloat?, initialSpringVelocity springVelocity: CGFloat?, options: UIViewAnimationOptions = UIViewAnimationOptions(0), timingFunction: CAMediaTimingFunction? = nil, animations: () -> Void, completion: ((Bool) -> Void)? = nil) {
CATransaction.begin()
if let timingFunction = timingFunction {
CATransaction.setAnimationTimingFunction(timingFunction)
}
if let springDamping = springDamping,
springVelocity = springVelocity {
animateWithDuration(duration, delay: delay, usingSpringWithDamping: springDamping, initialSpringVelocity: springVelocity, options: options, animations: animations, completion: completion)
}
else {
animateWithDuration(duration, delay: delay, options: options, animations: animations, completion: completion)
}
CATransaction.commit()
}
}
|
7b5c60543b4f9718618fd52dc8cab198
| 38.566667 | 326 | 0.689132 | false | false | false | false |
sammyd/Concurrency-VideoSeries
|
refs/heads/master
|
projects/001_NSOperation/001_ChallengeComplete/Decompressor.playground/Contents.swift
|
mit
|
1
|
import Compressor
import UIKit
//: # Compressor Operation
//: You've decided that you want to use some funky new compression algorithm to store the images in your app. Unfortunately this compression algorithm isn't natively supported by `UIImage`, so you need to use your own custom Decompressor.
//:
//: Decompression is a fairly expensive process, so you'd like to be able to wrap it in an `NSOperation` and eventually have the images decompressing in the background.
//:
//: The `Compressor` struct accessible within this playground has a decompression function on it that will take a path to a file and return the decompressed `NSData`
//:
//: > __Challenge:__ Your challenge is to create an `NSOperation` subclass that decompresses a file. Use __dark\_road\_small.compressed__ as a test file.
let compressedFilePath = NSBundle.mainBundle().pathForResource("dark_road_small", ofType: "compressed")!
class ImageDecompressor: NSOperation {
var inputPath: String?
var outputImage: UIImage?
override func main() {
guard let inputPath = inputPath else { return }
if let decompressedData = Compressor.loadCompressedFile(inputPath) {
outputImage = UIImage(data: decompressedData)
}
}
}
let decompOp = ImageDecompressor()
decompOp.inputPath = compressedFilePath
if(decompOp.ready) {
decompOp.start()
}
decompOp.outputImage
|
79e5e2e437f54b1dc6ca00b446769a67
| 36.861111 | 238 | 0.752751 | false | false | false | false |
renzifeng/ZFZhiHuDaily
|
refs/heads/master
|
ZFZhiHuDaily/Home/View/ParallaxHeaderView.swift
|
apache-2.0
|
1
|
//
// ParallaxHeaderView.swift
// ParallaxHeaderView
//
// Created by 任子丰 on 15/11/3.
// Copyright © 2015年 任子丰. All rights reserved.
//
import UIKit
protocol ParallaxHeaderViewDelegate: class {
func LockScorllView(maxOffsetY: CGFloat)
func autoAdjustNavigationBarAplha(aplha: CGFloat)
}
enum ParallaxHeaderViewStyle {
case Default
case Thumb
}
class ParallaxHeaderView: UIView {
var subView: UIView
var contentView: UIView = UIView()
/// 最大的下拉限度(因为是下拉所以总是为负数),超过(小于)这个值,下拉将不会有效果
var maxOffsetY: CGFloat
/// 是否需要自动调节导航栏的透明度
var autoAdjustAplha: Bool = true
weak var delegate: ParallaxHeaderViewDelegate!
/// 模糊效果的view
private var blurView: UIVisualEffectView?
private let defaultBlurViewAlpha: CGFloat = 0.7
private let style: ParallaxHeaderViewStyle
private let originY:CGFloat = -64
// MARK: - 初始化方法
init(style: ParallaxHeaderViewStyle,subView: UIView, headerViewSize: CGSize, maxOffsetY: CGFloat, delegate: ParallaxHeaderViewDelegate) {
self.subView = subView
self.maxOffsetY = maxOffsetY < 0 ? maxOffsetY : -maxOffsetY
self.delegate = delegate
self.style = style
super.init(frame: CGRectMake(0, 0, headerViewSize.width, headerViewSize.height))
//这里是自动布局的设置,大概意思就是subView与它的superView拥有一样的frame
subView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleWidth, .FlexibleHeight]
self.clipsToBounds = false; //必须得设置成false
self.contentView.frame = self.bounds
self.contentView.addSubview(subView)
self.contentView.clipsToBounds = true
self.addSubview(contentView)
self.setupStyle()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// let rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)
// self.contentView.frame = rect
}
private func setupStyle() {
switch style {
case .Default:
self.autoAdjustAplha = true
case .Thumb:
self.autoAdjustAplha = false
let blurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.alpha = defaultBlurViewAlpha
blurView.frame = self.subView.frame
blurView.autoresizingMask = self.subView.autoresizingMask
self.blurView = blurView
self.contentView.addSubview(blurView)
}
}
// MARK: - 其他方法
func layoutHeaderViewWhenScroll(offset: CGPoint) {
let delta:CGFloat = offset.y
if delta < maxOffsetY {
self.delegate.LockScorllView(maxOffsetY)
}else if delta < 0{
var rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)
rect.origin.y += delta ;
rect.size.height -= delta;
self.contentView.frame = rect;
}
switch style {
case .Default:
self.layoutDefaultViewWhenScroll(delta)
case .Thumb:
self.layoutThumbViewWhenScroll(delta)
}
if self.autoAdjustAplha {
var alpha = CGFloat((-originY + delta) / (self.frame.size.height))
if delta < 64 {
alpha = CGFloat((delta) / (self.frame.size.height))
}
self.delegate.autoAdjustNavigationBarAplha(alpha)
}
}
private func layoutDefaultViewWhenScroll(delta: CGFloat) {
// do nothing
}
private func layoutThumbViewWhenScroll(delta: CGFloat) {
if delta > 0 {
self.contentView.frame.origin.y = delta
}
if let blurView = self.blurView where delta < 0{
blurView.alpha = defaultBlurViewAlpha - CGFloat(delta / maxOffsetY) < 0 ? 0 : defaultBlurViewAlpha - CGFloat(delta / maxOffsetY)
}
}
}
|
f41059242e02f4596a3ef06adb5f4833
| 29.079137 | 154 | 0.618512 | false | false | false | false |
cacawai/Tap2Read
|
refs/heads/master
|
tap2read/tap2read/CategoryBar.swift
|
mit
|
1
|
//
// CategoryBar.swift
// tap2read
//
// Created by 徐新元 on 14/05/2017.
// Copyright © 2017 Last4 Team. All rights reserved.
//
import UIKit
protocol CategoryBarDelegate: class {
func onCategorySelected(index: NSInteger!)
func onSettingsSelected()
}
class CategoryBar: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
var categoryModels: [CategoryModel] = [CategoryModel]()
weak var categoryBarDelegate:CategoryBarDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.dataSource = self
self.delegate = self
self.register(UINib(nibName: "CategoryBarCell", bundle: nil), forCellWithReuseIdentifier: "CategoryBarCell")
}
func loadData(categories: [CategoryModel]?) {
if categories == nil {
return
}
categoryModels = categories!
self.reloadData()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryBarCell", for: indexPath) as! CategoryBarCell
let index = indexPath.row
if index == categoryModels.count {
cell.imageView.image = UIImage.init(named: "settings")
cell.emojiLabel.text = NSLocalizedString("settings", comment: "")
cell.setHighlighted(isHighlighted: false)
return cell
}
if index < categoryModels.count {
cell.loadData(category: categoryModels[index])
}
cell.setHighlighted(isHighlighted: index == CardModelMgr.sharedInstance.currentCategoryIndex)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categoryModels.count+1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
{
return CGSize(width:20, height:0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize
{
return CGSize(width:20, height:0)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let currentCell = collectionView.cellForItem(at: indexPath) as! CategoryBarCell
currentCell.doZoomAnimation()
let index = indexPath.row
if index == categoryModels.count {
categoryBarDelegate?.onSettingsSelected()
return
}
categoryBarDelegate?.onCategorySelected(index: index)
let cells = collectionView.visibleCells as! [CategoryBarCell]
for cell in cells {
cell.setHighlighted(isHighlighted: false)
}
currentCell.setHighlighted(isHighlighted: index == CardModelMgr.sharedInstance.currentCategoryIndex)
}
}
|
9bee9b800851279e086c2651bbeb5d2b
| 34.685393 | 168 | 0.677267 | false | false | false | false |
gnachman/iTerm2
|
refs/heads/master
|
BetterFontPicker/BetterFontPicker/FontPickerCompositeView.swift
|
gpl-2.0
|
2
|
//
// FontPickerCompositeView.swift
// BetterFontPicker
//
// Created by George Nachman on 4/9/19.
// Copyright © 2019 George Nachman. All rights reserved.
//
import Cocoa
@objc(BFPCompositeViewDelegate)
public protocol FontPickerCompositeViewDelegate: NSObjectProtocol {
func fontPickerCompositeView(_ view: FontPickerCompositeView,
didSelectFont font: NSFont)
}
@objc(BFPCompositeView)
public class FontPickerCompositeView: NSView, AffordanceDelegate, FontFamilyMemberPickerViewDelegate, SizePickerViewDelegate, OptionsButtonControllerDelegate {
@objc public weak var delegate: FontPickerCompositeViewDelegate?
private var accessories: [NSView] = []
@objc public let affordance = Affordance()
private let optionsButtonController = OptionsButtonController()
var memberPicker: FontFamilyMemberPickerView? = FontFamilyMemberPickerView()
var sizePicker: SizePickerView? = SizePickerView()
@objc private(set) public var horizontalSpacing: SizePickerView? = nil
@objc private(set) public var verticalSpacing: SizePickerView? = nil
@objc var options: Set<Int> {
return optionsButtonController.options
}
@objc(BFPCompositeViewMode)
public enum Mode: Int {
case normal
case fixedPitch
}
@objc public var mode: Mode = .normal {
didSet {
switch mode {
case .normal:
affordance.vc.systemFontDataSources = [SystemFontsDataSource()]
case .fixedPitch:
affordance.vc.systemFontDataSources = [
SystemFontsDataSource(filter: .fixedPitch),
SystemFontsDataSource(filter: .variablePitch) ]
}
}
}
@objc public var font: NSFont? {
set {
let temp = delegate
delegate = nil
if let font = newValue, let familyName = font.familyName {
affordance.familyName = familyName
memberPicker?.set(member: font.fontName)
sizePicker?.size = Double(font.pointSize)
updateOptionsMenu()
optionsButtonController.set(font: font)
}
delegate = temp
}
get {
guard let memberPicker = memberPicker else {
guard let familyName = affordance.familyName else {
return nil
}
return NSFont(name: familyName,
size: CGFloat(sizePicker?.size ?? 12))
}
guard let name = memberPicker.selectedFontName else {
return nil
}
if options.isEmpty {
return NSFont(name: name,
size: CGFloat(sizePicker?.size ?? 12))
}
let size = CGFloat(sizePicker?.size ?? 12)
var descriptor = NSFontDescriptor(name: name, size: size)
let settings = Array(options).map {
[NSFontDescriptor.FeatureKey.typeIdentifier: kStylisticAlternativesType,
NSFontDescriptor.FeatureKey.selectorIdentifier: $0]
}
descriptor = descriptor.addingAttributes([.featureSettings: settings])
return NSFont(descriptor: descriptor, size: size)
}
}
public init(font: NSFont) {
super.init(frame: NSRect.zero)
postInit()
self.font = font
}
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
postInit()
}
public required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
postInit()
}
private func postInit() {
affordance.delegate = self
memberPicker?.delegate = self
sizePicker?.delegate = self
sizePicker?.clamp(min: 1, max: 256)
addSubview(affordance)
if let memberPicker = memberPicker {
addSubview(memberPicker)
affordance.memberPicker = memberPicker
}
if let sizePicker = sizePicker {
addSubview(sizePicker)
}
layoutSubviews()
}
public override func resizeSubviews(withOldSize oldSize: NSSize) {
layoutSubviews()
}
@objc public func removeSizePicker() {
if let sizePicker = sizePicker {
sizePicker.removeFromSuperview()
self.sizePicker = nil
layoutSubviews()
}
}
@objc public func removeMemberPicker() {
if let memberPicker = memberPicker {
memberPicker.removeFromSuperview()
self.memberPicker?.delegate = nil
self.memberPicker = nil
layoutSubviews()
}
}
private func imageViewForImage(withName name: String) -> NSImageView {
let bundle = Bundle(for: FontPickerCompositeView.self)
if let image = bundle.image(forResource: NSImage.Name(name)) {
return NSImageView(image: image)
} else {
return NSImageView(image: NSImage(size: NSSize(width: 1, height: 1)))
}
}
@objc(addHorizontalSpacingAccessoryWithInitialValue:)
public func addHorizontalSpacingAccessory(_ initialValue: Double) -> SizePickerView {
let view = SizePickerView()
view.clamp(min: 1, max: 200)
horizontalSpacing = view
view.size = initialValue
let imageView = imageViewForImage(withName: "HorizontalSpacingIcon")
if #available(macOS 10.14, *) {
imageView.image?.isTemplate = true
imageView.contentTintColor = NSColor.labelColor
}
add(accessory: imageView)
add(accessory: view)
return view
}
@objc(addVerticalSpacingAccessoryWithInitialValue:)
public func addVerticalSpacingAccessory(_ initialValue: Double) -> SizePickerView {
let view = SizePickerView()
view.clamp(min: 1, max: 200)
verticalSpacing = view
view.size = initialValue
let imageView = imageViewForImage(withName: "VerticalSpacingIcon")
if #available(macOS 10.14, *) {
imageView.image?.isTemplate = true
imageView.contentTintColor = NSColor.labelColor
}
add(accessory: imageView)
add(accessory: view)
return view
}
public func add(accessory view: NSView) {
accessories.append(view)
ensureAccessoryOrder()
addSubview(view)
layoutSubviews()
}
private func ensureAccessoryOrder() {
guard let i = indexOfOptionsButton, i != accessories.count - 1 else {
return
}
// Move options button to end.
let button = accessories[i]
accessories.remove(at: i)
accessories.append(button)
}
private func layoutSubviews() {
let margin = CGFloat(3.0)
var accessoryWidths: [CGFloat] = []
var totalAccessoryWidth = CGFloat(0)
var maxAccessoryHeight = CGFloat(0)
for accessory in accessories {
accessoryWidths.append(accessory.fittingSize.width)
maxAccessoryHeight = max(maxAccessoryHeight, accessory.fittingSize.height)
totalAccessoryWidth += accessory.fittingSize.width
}
totalAccessoryWidth += max(0.0, CGFloat(accessories.count - 1)) * margin
let sizePickerWidth: CGFloat = sizePicker == nil ? CGFloat(0) : CGFloat(54.0)
var numViews = 1
if sizePicker != nil {
numViews += 1
}
if memberPicker != nil {
numViews += 1
}
let memberPickerWidth: CGFloat = memberPicker == nil ? CGFloat(0) : CGFloat(100.0)
let width: CGFloat = bounds.size.width
// This would be a let constant but the Swift compiler can't type check it in a reasonable amount of time.
var preferredWidth: CGFloat = width
preferredWidth -= sizePickerWidth
preferredWidth -= memberPickerWidth
preferredWidth -= totalAccessoryWidth
preferredWidth -= margin * CGFloat(numViews)
let affordanceWidth = max(200.0, preferredWidth)
var x = CGFloat(0)
affordance.frame = NSRect(x: x, y: CGFloat(0), width: affordanceWidth, height: CGFloat(25))
x += affordanceWidth + margin
if let memberPicker = memberPicker {
memberPicker.frame = NSRect(x: x, y: CGFloat(0), width: memberPickerWidth, height: CGFloat(25))
x += memberPickerWidth + margin
}
if let sizePicker = sizePicker {
sizePicker.frame = NSRect(x: x, y: CGFloat(0), width: sizePickerWidth, height: CGFloat(27))
x += sizePickerWidth + margin
}
for accessory in accessories {
let size = accessory.fittingSize
accessory.frame = NSRect(x: x, y: CGFloat(0), width: size.width, height: size.height)
x += size.width + margin
}
}
public func affordance(_ affordance: Affordance, didSelectFontFamily fontFamily: String) {
if let font = font {
delegate?.fontPickerCompositeView(self, didSelectFont: font)
}
updateOptionsMenu()
}
private var indexOfOptionsButton: Int? {
return accessories.firstIndex { view in
(view as? AccessoryWrapper)?.subviews.first === optionsButtonController.optionsButton
}
}
private var haveAddedOptionsButton: Bool {
return indexOfOptionsButton != nil
}
private func updateOptionsMenu() {
guard let optionsButton = optionsButtonController.optionsButton else {
return
}
if optionsButtonController.set(familyName: affordance.familyName) {
if !haveAddedOptionsButton {
optionsButton.sizeToFit()
optionsButtonController.delegate = self
let wrapper = AccessoryWrapper(optionsButton, height: bounds.height)
add(accessory: wrapper)
}
return
}
if let i = indexOfOptionsButton {
accessories.remove(at: i)
optionsButtonController.delegate = nil
layoutSubviews()
}
}
public func fontFamilyMemberPickerView(_ fontFamilyMemberPickerView: FontFamilyMemberPickerView,
didSelectFontName name: String) {
if let font = font {
delegate?.fontPickerCompositeView(self, didSelectFont: font)
}
}
public func sizePickerView(_ sizePickerView: SizePickerView,
didChangeSizeTo size: Double) {
if let font = font {
delegate?.fontPickerCompositeView(self, didSelectFont: font)
}
}
func optionsDidChange(_ controller: OptionsButtonController, options: Set<Int>) {
if let font = font {
delegate?.fontPickerCompositeView(self, didSelectFont: font)
}
}
}
|
c39ae1a7d9e86db729bd43a066aa2fd3
| 34.819672 | 159 | 0.610252 | false | false | false | false |
meetkei/KxUI
|
refs/heads/master
|
KxUI/ViewController/KUVC+Snapshot.swift
|
mit
|
1
|
//
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public extension KUCommonViewController {
/// A Snapshot taken from view controller's root view
var viewSnapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/// Returns the snapshot of the target view.
///
/// - Parameters:
/// - target: A view object
/// - opaque: A Boolean flag indicating whether the bitmap is opaque. The default value is true.
/// - scale: The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen. The default value is 0.0.
/// - afterScreenUpdates: A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes. The default value is false.
/// - Returns: The image object representing snapshot, or nil if the method could not generate snapshot or invalid target view
func generate(snapshotOf target: UIView?, opaque: Bool = true, scale: CGFloat = 0, afterScreenUpdates: Bool = false) -> UIImage? {
guard let v = target else {
return nil
}
UIGraphicsBeginImageContextWithOptions(v.bounds.size, opaque, scale)
v.drawHierarchy(in: v.bounds, afterScreenUpdates: afterScreenUpdates)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
|
50bfe2dc616dcb15240e545fd0f19f25
| 52.309091 | 311 | 0.716917 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/PackagePlugin/Path.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A simple representation of a path in the file system.
public struct Path: Hashable {
private let _string: String
/// Initializes the path from the contents a string, which should be an
/// absolute path in platform representation.
public init(_ string: String) {
self._string = string
}
/// A string representation of the path.
public var string: String {
return _string
}
/// The last path component (including any extension).
public var lastComponent: String {
// Check for a special case of the root directory.
if _string == "/" {
// Root directory, so the basename is a single path separator (the
// root directory is special in this regard).
return "/"
}
// Find the last path separator.
guard let idx = _string.lastIndex(of: "/") else {
// No path separators, so the basename is the whole string.
return _string
}
// Otherwise, it's the string from (but not including) the last path
// separator.
return String(_string.suffix(from: _string.index(after: idx)))
}
/// The last path component (without any extension).
public var stem: String {
let filename = self.lastComponent
if let ext = self.extension {
return String(filename.dropLast(ext.count + 1))
} else {
return filename
}
}
/// The filename extension, if any (without any leading dot).
public var `extension`: String? {
// Find the last path separator, if any.
let sIdx = _string.lastIndex(of: "/")
// Find the start of the basename.
let bIdx = (sIdx != nil) ? _string.index(after: sIdx!) : _string.startIndex
// Find the last `.` (if any), starting from the second character of
// the basename (a leading `.` does not make the whole path component
// a suffix).
let fIdx = _string.index(bIdx, offsetBy: 1, limitedBy: _string.endIndex) ?? _string.startIndex
if let idx = _string[fIdx...].lastIndex(of: ".") {
// Unless it's just a `.` at the end, we have found a suffix.
if _string.distance(from: idx, to: _string.endIndex) > 1 {
return String(_string.suffix(from: _string.index(idx, offsetBy: 1)))
}
}
// If we get this far, there is no suffix.
return nil
}
/// The path except for the last path component.
public func removingLastComponent() -> Path {
// Find the last path separator.
guard let idx = string.lastIndex(of: "/") else {
// No path separators, so the directory name is `.`.
return Path(".")
}
// Check if it's the only one in the string.
if idx == string.startIndex {
// Just one path separator, so the directory name is `/`.
return Path("/")
}
// Otherwise, it's the string up to (but not including) the last path
// separator.
return Path(String(_string.prefix(upTo: idx)))
}
/// The result of appending a subpath, which should be a relative path in
/// platform representation.
public func appending(subpath: String) -> Path {
return Path(_string + (_string.hasSuffix("/") ? "" : "/") + subpath)
}
/// The result of appending one or more path components.
public func appending(_ components: [String]) -> Path {
return self.appending(subpath: components.joined(separator: "/"))
}
/// The result of appending one or more path components.
public func appending(_ components: String...) -> Path {
return self.appending(components)
}
}
extension Path: CustomStringConvertible {
public var description: String {
return self.string
}
}
extension Path: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.string)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
self.init(string)
}
}
public extension String.StringInterpolation {
mutating func appendInterpolation(_ path: Path) {
self.appendInterpolation(path.string)
}
}
|
40be79bd3205a2e403c0eb1c7e88c02c
| 34.630435 | 102 | 0.591621 | false | false | false | false |
tiagobsbraga/HotmartTest
|
refs/heads/master
|
HotmartTest/SaleTableViewCell.swift
|
mit
|
1
|
//
// SaleTableViewCell.swift
// HotmartTest
//
// Created by Tiago Braga on 08/02/17.
// Copyright © 2017 Tiago Braga. All rights reserved.
//
import UIKit
class SaleTableViewCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var warningImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.warningImageView.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// Public Methods
func populateSale(_ sale: Sale, withWarning warning: Bool = false) {
self.descriptionLabel!.text = sale.description!
self.idLabel!.text = sale.id!
self.dateLabel!.text = sale.date!
self.priceLabel!.text = sale.price!
self.warningImageView.isHidden = !warning
}
}
|
2712e6052a478268b3f37ff4474853d2
| 25.717949 | 72 | 0.663148 | false | false | false | false |
martinschilliger/SwissGrid
|
refs/heads/master
|
SwissGrid/GradientView.swift
|
mit
|
1
|
//
// GradientView.swift
// SwissGrid
//
// Created by Leo Dabus on 15.05.16.
// Seen here: https://stackoverflow.com/a/37243106/1145706
//
import Foundation
import UIKit
@IBDesignable
class GradientView: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() } }
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() } }
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() } }
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() } }
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() } }
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() } }
override class var layerClass: AnyClass { return CAGradientLayer.self }
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
override func layoutSubviews() {
super.layoutSubviews()
updatePoints()
updateLocations()
updateColors()
}
}
|
269f0010ed0638313ad9320ba6f7bd61
| 34.75 | 97 | 0.649184 | false | false | false | false |
Stitch7/Instapod
|
refs/heads/master
|
Instapod/Feed/FeedOperation/FeedOperation.swift
|
mit
|
1
|
//
// FeedOperation.swift
// Instapod
//
// Created by Christopher Reitz on 02.04.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
class FeedOperation: AsynchronousOperation {
// MARK: - Properties
let uuid: String
var url: URL
var parser: FeedParser
var task: URLSessionTask!
var delegate: FeedOperationDelegate?
var session = URLSession.shared
// MARK: - Initializer
init(uuid: String, url: URL, parser: FeedParser) {
self.uuid = uuid
self.parser = parser
self.url = url
super.init()
configureTask()
}
fileprivate func configureTask() {
task = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self else { return }
defer {
strongSelf.completeOperation()
}
if let requestError = error {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: requestError)
return
}
guard let xmlData = data else {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: error)
return
}
do {
let parser = strongSelf.parser
var podcast = try parser.parseFeed(uuid: strongSelf.uuid,
url: strongSelf.url,
xmlData: xmlData)
podcast.nextPage = try parser.nextPage(xmlData)
podcast.image = try parser.parseImage(xmlData)
podcast.episodes = try parser.parseEpisodes(xmlData)
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithPodcast: podcast)
} catch {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: error)
}
})
}
// MARK: - NSOperation
override func main() {
print("📦⬇️: \(url.absoluteString)")
task.resume()
}
override func cancel() {
task.cancel()
super.cancel()
}
}
|
34425a727235d34cfb8d300d46fb5acb
| 28.053333 | 102 | 0.558513 | false | false | false | false |
gservera/TaxonomyKit
|
refs/heads/master
|
Tests/TaxonomyKitTests/FindIdentifiersTests.swift
|
mit
|
1
|
/*
* FindIdentifiersTests.swift
* TaxonomyKitTests
*
* Created: Guillem Servera on 24/09/2016.
* Copyright: © 2016-2017 Guillem Servera (https://github.com/gservera)
*
* 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 TaxonomyKit
final class FindIdentifiersTests: XCTestCase {
override class func setUp() {
super.setUp()
Taxonomy.internalUrlSession = Taxonomy.makeUrlSession()
}
override func setUp() {
super.setUp()
/// Wait 1 second to avoid NCBI too many requests error (429)
sleep(1)
}
func testQueryWithSingleResult() {
Taxonomy.internalUrlSession = Taxonomy.makeUrlSession()
let condition = expectation(description: "Should have succeeded")
Taxonomy.findIdentifiers(for: "Quercus ilex") { result in
if case .success(let identifiers) = result {
XCTAssertEqual(identifiers.count, 1)
XCTAssertEqual(identifiers[0], 58334)
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testUnmatchedQuery() {
Taxonomy.internalUrlSession = Taxonomy.makeUrlSession()
let condition = expectation(description: "Unmatched query")
Taxonomy.findIdentifiers(for: "invalid-invalid") { result in
if case .success(let identifiers) = result {
XCTAssertEqual(identifiers.count, 0)
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testFakeMalformedJSON() {
Taxonomy.internalUrlSession = MockSession()
let anyUrl = URL(string: "https://gservera.com")!
let response = HTTPURLResponse(url: anyUrl, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])!
let data = Data(base64Encoded: "SGVsbG8gd29ybGQ=")
MockSession.mockResponse = (data, response, nil)
let condition = expectation(description: "Finished")
Taxonomy.findIdentifiers(for: "anything") { result in
if case .failure(let error) = result, case .parseError(_) = error {
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testUnknownResponse() {
Taxonomy.internalUrlSession = MockSession()
let anyUrl = URL(string: "https://gservera.com")!
let response = HTTPURLResponse(url: anyUrl, statusCode: 500, httpVersion: "HTTP/1.1", headerFields: [:])!
let data = Data(base64Encoded: "SGVsbG8gd29ybGQ=")
MockSession.mockResponse = (data, response, nil)
let condition = expectation(description: "Finished")
Taxonomy.findIdentifiers(for: "anything") { result in
if case .failure(let error) = result,
case .unexpectedResponse(500) = error {
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testNetworkError() {
Taxonomy.internalUrlSession = MockSession()
let error = NSError(domain: "Custom", code: -1, userInfo: nil)
MockSession.mockResponse = (nil, nil, error)
let condition = expectation(description: "Finished")
Taxonomy.findIdentifiers(for: "anything") { result in
if case .failure(let error) = result,
case .networkError(_) = error {
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testOddBehavior() {
Taxonomy.internalUrlSession = MockSession()
MockSession.mockResponse = (nil, nil, nil)
let condition = expectation(description: "Finished")
Taxonomy.findIdentifiers(for: "anything") { result in
if case .failure(let error) = result,
case .unknownError = error {
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testOddBehavior2() {
Taxonomy.internalUrlSession = MockSession()
let anyUrl = URL(string: "https://gservera.com")!
let response = HTTPURLResponse(url: anyUrl, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])!
do {
let data = try JSONEncoder().encode(["Any JSON"])
MockSession.mockResponse = (data, response, nil)
} catch let error {
XCTFail("Test implementation fault. \(error)")
}
let condition = expectation(description: "Finished")
Taxonomy.findIdentifiers(for: "anything") { result in
if case .failure(let error) = result,
case .unknownError = error {
condition.fulfill()
}
}
waitForExpectations(timeout: 10)
}
func testCancellation() {
let mockSession = MockSession.shared
mockSession.wait = 5
Taxonomy.internalUrlSession = mockSession
let anyUrl = URL(string: "https://gservera.com")!
let response = HTTPURLResponse(url: anyUrl, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])!
do {
let data = try JSONEncoder().encode(["Any JSON"])
MockSession.mockResponse = (data, response, nil)
} catch let error {
XCTFail("Test implementation fault. \(error)")
}
let condition = expectation(description: "Finished")
let dataTask = Taxonomy.findIdentifiers(for: "anything") { _ in
XCTFail("Should have been canceled")
}
dataTask.cancel()
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 7.0) {
condition.fulfill()
}
waitForExpectations(timeout: 10)
}
}
|
f0919f0d3856969a11bdaf29a66093c2
| 39.214286 | 113 | 0.627442 | false | true | false | false |
Urinx/Vu
|
refs/heads/master
|
唯舞/唯舞/MessageViewController.swift
|
apache-2.0
|
2
|
//
// MessageViewController.swift
// 唯舞
//
// Created by Eular on 8/28/15.
// Copyright © 2015 eular. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var msgTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
scrollView.delegate = self
msgTextField.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardShow(note:NSNotification){
if let info = note.userInfo {
let keyboardFrame:CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let deltay = keyboardFrame.size.height as CGFloat
scrollView.setContentOffset(CGPointMake(0, deltay), animated: true)
}
}
func keyboardHide(note:NSNotification){
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
e6d6aacb2cf51524a9f9eb883a91ea43
| 32.916667 | 140 | 0.694717 | false | false | false | false |
OHeroJ/twicebook
|
refs/heads/master
|
Sources/App/Controllers/RecommendController.swift
|
mit
|
1
|
//
// RecommendController.swift
// App
//
// Created by laijihua on 16/01/2018.
//
import Foundation
import Vapor
final class RecommendController: ControllerRoutable {
init(builder: RouteBuilder) {
builder.get("/", handler: list)
builder.delete("/", handler: delete)
builder.post("/", handler: create)
builder.put("/", handler: update)
}
/// 更新
func update(req: Request) throws -> ResponseRepresentable {
guard let rid = req.data["id"]?.int else {
return try ApiRes.error(code: 1, msg: "缺少id")
}
guard let rec = try Recommend.makeQuery().find(rid) else {
return try ApiRes.error(code: 2, msg: "未找到recommed")
}
if let imgurl = req.data["cover"]?.string {
rec.cover = imgurl
}
if let h5url = req.data["h5url"]?.string {
rec.linkUrl = h5url
}
if let bookid = req.data["bookId"]?.int {
rec.bookId = bookid
}
try rec.save()
return try ApiRes.success(data:["success": true])
}
/// 创建
func create(req: Request) throws -> ResponseRepresentable {
guard let type = req.data["type"]?.int else {
return try ApiRes.error(code: 1, msg: "miss type")
}
guard let cover = req.data["cover"]?.string else {
return try ApiRes.error(code: 2, msg: "miss cover")
}
let h5url = req.data["linkUrl"]?.string ?? ""
let bookId = req.data["bookId"]?.int ?? 0
let rec = Recommend(type: type, bookId: bookId, linkUrl: h5url, cover: cover)
try rec.save()
return try ApiRes.success(data:["success": true])
}
/// 删除
func delete(req: Request) throws -> ResponseRepresentable {
guard let id = req.data["id"]?.int else {
return try ApiRes.error(code: 1, msg: "miss id")
}
guard let rec = try Recommend.makeQuery().find(id) else {
return try ApiRes.error(code: 2, msg: "miss recommend")
}
try rec.delete()
return try ApiRes.success(data:["success": true])
}
/// 列表
func list(req: Request) throws -> ResponseRepresentable {
let result = try Recommend.makeQuery().all().makeJSON()
return try ApiRes.success(data:["recommends": result])
}
}
|
7db67d6168c4b3e874b6e14246c3aee7
| 31.472222 | 85 | 0.567151 | false | false | false | false |
DanilaVladi/Microsoft-Cognitive-Services-Swift-SDK
|
refs/heads/master
|
Sample Project/CognitiveServices/CognitiveServices/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// CognitiveServices
//
// Created by Vladimir Danila on 13/04/16.
// Copyright © 2016 Vladimir Danila. All rights reserved.
//
import UIKit
import SafariServices
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cognitiveServices = CognitiveServices.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableView Delegate
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let identifier = tableView.cellForRow(at: indexPath)!.textLabel!.text!
switch identifier {
case "Powered by Microsoft Cognitive Services":
let url = URL(string: "https://microsoft.com/cognitive-services/")!
if #available(iOS 9.0, *) {
let sfViewController = SFSafariViewController(url: url)
self.present(sfViewController, animated: true, completion: nil)
} else {
UIApplication.shared.openURL(url)
}
case "Analyze Image", "OCR":
self.performSegue(withIdentifier: identifier, sender: self)
default:
let alert = UIAlertController(title: "Missing", message: "This hasn't been implemented yet.", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let text = demos[(indexPath as NSIndexPath).row]
cell.textLabel?.text = text
if text == "Powered by Microsoft Cognitive Services" {
cell.accessoryType = .none
cell.textLabel?.textColor = .blue
}
else {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textColor = .black
}
return cell
}
// MARK: - UITableViewDataSource Delegate
let demos = ["Analyze Image","Get Thumbnail","List Domain Specific Model","OCR","Recognize Domain Specfic Content","Tag Image", "Powered by Microsoft Cognitive Services"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demos.count
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.destination.navigationItem.title = demos[(tableView.indexPathForSelectedRow! as NSIndexPath).row]
tableView.deselectRow(at: tableView.indexPathForSelectedRow!, animated: true)
}
}
|
106353cdaa33001503fbead76668b266
| 31.160377 | 174 | 0.62071 | false | false | false | false |
jackTang11/TlySina
|
refs/heads/master
|
TlySina/TlySina/Classes/View(视图和控制器)/Home/TLYHomeViewController.swift
|
apache-2.0
|
1
|
//
// TLYHomeViewController.swift
// TlySina
//
// Created by jack_tang on 17/4/28.
// Copyright © 2017年 jack_tang. All rights reserved.
//
import UIKit
private let cell = "cellId"
class TLYHomeViewController: TLYBaseViewController {
lazy var arrayM = [String]()
@objc fileprivate func showFriends(){
print(#function)
let vc = TLYTestController()
vc.hidesBottomBarWhenPushed = true;
navigationController?.pushViewController(vc , animated: true);
}
override func loadData(){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) {
for i in 0..<20 {
self.arrayM.append("这是第\(i)个数据")
}
self.tabview?.reloadData()
self.refresh?.endRefreshing()
}
}
}
extension TLYHomeViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayM.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tabcell = tableView.dequeueReusableCell(withIdentifier: cell, for: indexPath)
tabcell.textLabel?.text = arrayM[indexPath.item]
return tabcell
}
}
extension TLYHomeViewController{
override func setTableView() {
super.setTableView()
navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 15, self, action: #selector(showFriends),false)
tabview?.register(UITableViewCell.self, forCellReuseIdentifier: cell)
}
}
|
ac7ee139aa14f50788149220f45428ff
| 22.492958 | 122 | 0.621703 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/UICollectionViewDemo/UICollectionViewDemo/IconLabel.swift
|
mit
|
1
|
//
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
enum IconDirection: Int {
case left, right, top, bottom
}
class IconLabel: UILabel {
var edgeInsets = UIEdgeInsets() // 文字偏移量
var direction = IconDirection.top
var gap: CGFloat = 5
private var iconView: UIImageView?
func set(_ text: String?, with image: UIImage?) {
self.text = text
if let iconView = iconView {
iconView.image = image
} else {
iconView = UIImageView(image: image)
}
iconView?.frame.origin = CGPoint.zero
addSubview(iconView ?? UIImageView())
// 1
sizeToFit()
// 3
}
private var offsetX: CGFloat = 0
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
// 2
var rect = super.textRect(forBounds: bounds.inset(by: edgeInsets), limitedToNumberOfLines: numberOfLines)
let h = edgeInsets.left + edgeInsets.right
let v = edgeInsets.bottom + edgeInsets.top
let w = max(rect.width, iconView?.frame.width ?? 0)
offsetX = (w - rect.width) / 2
rect.size.height = (max(rect.height, iconView?.frame.height ?? 0)) + v
rect.size.width = w + h
switch direction {
case .left, .right:
rect.origin.x -= edgeInsets.left
if let iconView = iconView {
rect.size.width += (gap + iconView.frame.width)
}
default:
rect.origin.y -= edgeInsets.top
if let iconView = iconView {
rect.size.height += (gap + iconView.frame.height)
}
}
return rect
}
override func drawText(in rect: CGRect) {
// 4(这里应该是异步的,如果循环创建多个IconDirection,最后同时执行这个方法)
var temp = edgeInsets
if let iconView = iconView {
switch direction {
case .left, .right:
iconView.center.y = bounds.height / 2
if direction == .left {
iconView.frame.origin.x = edgeInsets.left
temp = UIEdgeInsets(top: edgeInsets.top, left: edgeInsets.left + gap + iconView.frame.width, bottom: edgeInsets.bottom, right: edgeInsets.right)
} else {
iconView.frame.origin.x = frame.width - edgeInsets.right - iconView.frame.width
temp = UIEdgeInsets(top: edgeInsets.top, left: edgeInsets.left, bottom: edgeInsets.bottom, right: edgeInsets.right + gap + iconView.frame.width)
}
default:
iconView.center.x = bounds.width / 2
if direction == .top {
iconView.frame.origin.y = 0
temp = UIEdgeInsets(top: edgeInsets.top + gap + iconView.frame.height, left: offsetX + edgeInsets.left, bottom: edgeInsets.bottom, right: edgeInsets.right)
} else {
iconView.frame.origin.y = edgeInsets.bottom + iconView.frame.height
temp = UIEdgeInsets(top: edgeInsets.top, left: offsetX + edgeInsets.left, bottom: edgeInsets.bottom + gap + iconView.frame.height, right: edgeInsets.right)
}
}
}
super.drawText(in: rect.inset(by: temp))
}
}
|
3456b84d2363d29454fb3d9592d59a6a
| 37.823529 | 175 | 0.573636 | false | false | false | false |
maxoumime/emoji-data-ios
|
refs/heads/master
|
emojidataios/Classes/EmojiParser.swift
|
mit
|
1
|
//
// EmojiParser.swift
// Pods
//
// Created by Maxime Bertheau on 4/12/17.
//
//
import Foundation
open class EmojiParser {
fileprivate static var loading = false
fileprivate static var _emojiManager: EmojiManager?
fileprivate static var emojiManager: EmojiManager {
get {
if _emojiManager == nil { _emojiManager = EmojiManager() }
return _emojiManager!
}
}
fileprivate static var _aliasMatchingRegex: NSRegularExpression?
fileprivate static var aliasMatchingRegex: NSRegularExpression {
if _aliasMatchingRegex == nil {
do {
_aliasMatchingRegex = try NSRegularExpression(pattern: ":([\\w_+-]+)(?:(?:\\||::)((type_|skin-tone-\\d+)[\\w_]*))*:", options: .caseInsensitive)
} catch {
}
}
return _aliasMatchingRegex!
}
fileprivate static var _aliasMatchingRegexOptionalColon: NSRegularExpression?
fileprivate static var aliasMatchingRegexOptionalColon: NSRegularExpression {
if _aliasMatchingRegexOptionalColon == nil {
do {
_aliasMatchingRegexOptionalColon = try NSRegularExpression(pattern: ":?([\\w_+-]+)(?:(?:\\||::)((type_|skin-tone-\\d+)[\\w_]*))*:?", options: .caseInsensitive)
} catch {
}
}
return _aliasMatchingRegexOptionalColon!
}
public static func prepare() {
if loading || _emojiManager != nil { return }
loading = true
DispatchQueue.global(qos: .background).async {
let emojiManager = EmojiManager()
DispatchQueue.main.async {
loading = false
if self._emojiManager == nil {
self._emojiManager = emojiManager
}
}
}
}
public static func getAliasesFromUnicode(_ unicode: String) -> [String] {
let escapedUnicode = unicode.unicodeScalars.map { $0.escaped(asASCII: true) }
.map { (escaped: String) -> String? in
if (!escaped.hasPrefix("\\u{")) {
return escaped.unicodeScalars.map { (unicode: Unicode.Scalar) -> String in
var hexValue = String(unicode.value, radix: 16).uppercased()
while(hexValue.count < 4) {
hexValue = "0" + hexValue
}
return hexValue
}.reduce("", +)
}
// Cleaning
// format \u{XXXXX}
var cleaned = escaped.dropFirst(3).dropLast()
// removing unecessary 0s
while (cleaned.hasPrefix("0") && cleaned.count > 4) {
cleaned = cleaned.dropFirst()
}
return String(cleaned)
}
if escapedUnicode.contains(where: { $0 == nil }) {
return []
}
let unified = (escapedUnicode as! [String]).joined(separator: "-")
return emojiManager.emojiForUnified[unified]?.map { $0.shortName } ?? []
}
public static func getUnicodeFromAlias(_ alias: String) -> String? {
let input = alias as NSString
let matches = aliasMatchingRegexOptionalColon.matches(in: alias, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: alias.count))
if(matches.count == 0) {
return nil
}
let match = matches[0]
let aliasMatch = match.range(at: 1)
let alias = input.substring(with: aliasMatch)
let skinVariationsString = input.substring(from: aliasMatch.upperBound)
.split(separator: ":")
.map { $0.trimmingCharacters(in: [":"]) }
.filter { !$0.isEmpty }
guard let emojiObject = getEmojiFromAlias(alias) else { return nil }
let emoji: String
let skinVariations = skinVariationsString.compactMap {
SkinVariationTypes(rawValue: $0.uppercased()) ?? SkinVariationTypes.getFromAlias($0.lowercased())
}
emoji = emojiObject.getEmojiWithSkinVariations(skinVariations)
return emoji
}
public static func getEmojiFromUnified(_ unified: String) -> String {
Emoji(shortName: "", unified: unified).emoji
}
static func getEmojiFromAlias(_ alias: String) -> Emoji? {
guard let emoji = emojiManager.shortNameForUnified[alias] else { return nil }
return emoji.first
}
public static func parseUnicode(_ input: String) -> String {
return input
.map {
($0, $0.unicodeScalars.map { $0.escaped(asASCII: true) })
}
.reduce("") { result, mapped in
let fallback = mapped.0
let unicode = mapped.1
let maybeEmojiAlias = unicode.map { (escaped: String) -> String in
if (!escaped.hasPrefix("\\u{")) {
return escaped
}
// Cleaning
// format \u{XXXXX}
var cleaned = escaped.dropFirst(3).dropLast()
// removing unecessary 0s
while (cleaned.hasPrefix("0")) {
cleaned = cleaned.dropFirst()
}
return String(cleaned)
}.joined(separator: "-")
let toDisplay: String
if let emoji = emojiManager.emojiForUnified[maybeEmojiAlias]?.first {
toDisplay = ":\(emoji.shortName):"
} else {
toDisplay = String(fallback)
}
return "\(result)\(toDisplay)"
}
}
public static func parseAliases(_ input: String) -> String {
var result = input
getUnicodesForAliases(input).forEach { alias, emoji in
if let emoji = emoji {
result = result.replacingOccurrences(of: alias, with: emoji)
}
}
return result
}
public static func getUnicodesForAliases(_ input: String) -> [(key: String, value: String?)] {
let matches = aliasMatchingRegex.matches(in: input, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: input.count))
if(matches.count == 0) {
return []
}
let nsInput = input as NSString
var uniqueMatches: [String:String?] = [:]
matches.forEach {
let fullAlias = nsInput.substring(with: $0.range(at: 0))
if uniqueMatches.index(forKey: fullAlias) == nil {
uniqueMatches[fullAlias] = getUnicodeFromAlias(fullAlias)
}
}
return uniqueMatches.sorted(by: {
$0.key.count > $1.key.count // Execute the longer first so emojis with skin variations are executed before the ones without
})
}
public static var emojisByCategory: [EmojiCategory: [Emoji]]{
return emojiManager.emojisForCategory
}
public static var emojisByUnicode: [String: Emoji] {
return emojiManager.emojiForUnicode
}
public static func getEmojisForCategory(_ category: EmojiCategory) -> [String] {
let emojis = emojiManager.getEmojisForCategory(category) ?? []
return emojis.map { $0.emoji }
}
}
|
3de5edcd0a256e472c6c07a0d9712c12
| 27.27572 | 167 | 0.590307 | false | false | false | false |
CCIP-App/CCIP-iOS
|
refs/heads/master
|
OPass/Views/Tabs/Settings/AppearanceView.swift
|
gpl-3.0
|
1
|
//
// AppearanceView.swift
// OPass
//
// Created by 張智堯 on 2022/8/8.
// 2022 OPass.
//
import SwiftUI
struct AppearanceView: View {
var body: some View {
Form {
Section("SCHEDULE") {
ScheduleOptions()
}
Section {
DarkModePicker()
}
Section {
ResetAllAppearanceButton()
}
}
.navigationTitle("Appearance")
.navigationBarTitleDisplayMode(.inline)
}
}
private struct ScheduleOptions: View {
@AppStorage("DimPastSession") var dimPastSession = true
@AppStorage("PastSessionOpacity") var pastSessionOpacity: Double = 0.4
let sampleTimeHour: [Int] = [
Calendar.current.component(.hour, from: Date.now.advanced(by: -3600)),
Calendar.current.component(.hour, from: Date.now),
Calendar.current.component(.hour, from: Date.now.advanced(by: 3600)),
Calendar.current.component(.hour, from: Date.now.advanced(by: 7200))
]
var body: some View {
List {
HStack {
VStack(alignment: .leading, spacing: 3) {
HStack() {
Text("OPass Room 1")
.font(.caption2)
.padding(.vertical, 1)
.padding(.horizontal, 8)
.foregroundColor(.white)
.background(.blue)
.cornerRadius(5)
Text(String(format: "%d:00 ~ %d:00", sampleTimeHour[0], sampleTimeHour[1]))
.foregroundColor(.gray)
.font(.footnote)
}
Text("PastSession")
.lineLimit(2)
}
.opacity(self.dimPastSession ? self.pastSessionOpacity : 1)
.padding(.horizontal, 5)
.padding(10)
Spacer()
}
.background(Color("SectionBackgroundColor"))
.cornerRadius(8)
HStack {
VStack(alignment: .leading, spacing: 3) {
HStack() {
Text("OPass Room 2")
.font(.caption2)
.padding(.vertical, 1)
.padding(.horizontal, 8)
.foregroundColor(.white)
.background(.blue)
.cornerRadius(5)
Text(String(format: "%d:00 ~ %d:00", sampleTimeHour[2], sampleTimeHour[3]))
.foregroundColor(.gray)
.font(.footnote)
}
Text("FutureSession")
.lineLimit(2)
}
.padding(.horizontal, 5)
.padding(10)
Spacer()
}
.background(Color("SectionBackgroundColor"))
.cornerRadius(8)
}
.listRowBackground(Color.transparent)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets(top: 0, leading: 10, bottom: 6, trailing: 10))
Toggle("Dim Past Session", isOn: $dimPastSession.animation())
if self.dimPastSession {
Slider(
value: $pastSessionOpacity.animation(),
in: 0.1...0.9,
onEditingChanged: {_ in},
minimumValueLabel: Image(systemName: "sun.min"),
maximumValueLabel: Image(systemName: "sun.min.fill"),
label: {}
)
}
}
}
private struct DarkModePicker: View {
@Environment(\.colorScheme) var colorScheme
@AppStorage("UserInterfaceStyle") var userInterfaceStyle: UIUserInterfaceStyle = .unspecified
private let buttons: [(LocalizedStringKey, UIUserInterfaceStyle)] = [("System", .unspecified), ("On", .dark), ("Off", .light)]
private let darkModeStatusText: [UIUserInterfaceStyle : LocalizedStringKey] = [.unspecified : "System", .dark : "On", .light : "Off"]
var body: some View {
NavigationLink {
Form {
Section {
ForEach(buttons, id: \.1) { (name, interfaceStyle) in
Button {
self.userInterfaceStyle = interfaceStyle
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).overrideUserInterfaceStyle = interfaceStyle
} label: {
HStack {
Text(name)
.foregroundColor(colorScheme == .dark ? .white : .black)
Spacer()
if self.userInterfaceStyle == interfaceStyle {
Image(systemName: "checkmark")
}
}
}
}
}
}
.navigationTitle("DarkMode")
.navigationBarTitleDisplayMode(.inline)
} label: {
HStack {
Text("DarkMode")
Spacer()
Text(darkModeStatusText[userInterfaceStyle]!)
.foregroundColor(.gray)
}
}
}
}
private struct ResetAllAppearanceButton: View {
@AppStorage("DimPastSession") var dimPastSession = true
@AppStorage("PastSessionOpacity") var pastSessionOpacity: Double = 0.4
@AppStorage("UserInterfaceStyle") var userInterfaceStyle: UIUserInterfaceStyle = .unspecified
var body: some View {
Button {
withAnimation {
self.dimPastSession = true
self.pastSessionOpacity = 0.4
}
self.userInterfaceStyle = .unspecified
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).overrideUserInterfaceStyle = userInterfaceStyle
} label: {
Text("ResetAllAppearance")
.foregroundColor(.red)
}
}
}
#if DEBUG
struct AppearanceView_Previews: PreviewProvider {
static var previews: some View {
AppearanceView()
}
}
#endif
|
f89785ae3e5e3e9295d52eacbaeb744e
| 34.384615 | 143 | 0.478416 | false | false | false | false |
dn-m/PitchSpellingTools
|
refs/heads/master
|
PitchSpellingToolsTests/SpelledPitchTests.swift
|
mit
|
1
|
//
// SpelledPitchTests.swift
// PitchSpellingTools
//
// Created by James Bean on 6/15/16.
//
//
import XCTest
import Pitch
@testable import PitchSpellingTools
class SpelledPitchTests: XCTestCase {
func testOctaveMiddleC() {
let c = SpelledPitch(60, PitchSpelling(.c))
XCTAssertEqual(c.octave, 5)
}
func testOctaveDAboveMiddleC() {
let d = SpelledPitch(62, PitchSpelling(.d))
XCTAssertEqual(d.octave, 5)
}
func testOctaveBBelowMiddleC() {
let b = SpelledPitch(59, PitchSpelling(.b))
XCTAssertEqual(b.octave, 4)
}
func testOctaveCFlat() {
let cflat = SpelledPitch(59, PitchSpelling(.c, .flat))
XCTAssertEqual(cflat.octave, 5)
}
func testOctaveBSharp() {
let bsharp = SpelledPitch(60, PitchSpelling(.b, .sharp))
XCTAssertEqual(bsharp.octave, 4)
}
func testOctaveCQuarterFlat() {
let cqflat = SpelledPitch(59.5, PitchSpelling(.c, .quarterFlat))
XCTAssertEqual(cqflat.octave, 5)
}
func testOctaveCNaturalDown() {
let cdown = SpelledPitch(59.75, PitchSpelling(.c, .natural, .down))
XCTAssertEqual(cdown.octave, 5)
}
func testBQuarterSharp() {
let bqsharp = SpelledPitch(59.5, PitchSpelling(.b, .quarterSharp))
XCTAssertEqual(bqsharp.octave, 4)
}
func testBSharpDown() {
let bsharpdown = SpelledPitch(59.75, PitchSpelling(.b, .sharp, .down))
XCTAssertEqual(bsharpdown.octave, 4)
}
}
|
ebb3cf040cca6c607d30d3851a3854f9
| 25.169492 | 78 | 0.626295 | false | true | false | false |
ingresse/ios-sdk
|
refs/heads/dev
|
IngresseSDKTests/Model/EventAttributesTests.swift
|
mit
|
1
|
//
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class EventAttributesTests: XCTestCase {
func testDecode() {
// Given
var json = [String: Any]()
json["accepted_apps"] = ["site", "android"]
json["ticket_transfer_enabled"] = false
json["ticket_transfer_required"] = true
// When
let obj = JSONDecoder().decodeDict(of: EventAttributes.self, from: json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.acceptedApps[0], "site")
XCTAssertEqual(obj?.acceptedApps[1], "android")
XCTAssertEqual(obj?.transferEnabled, false)
XCTAssertEqual(obj?.transferRequired, true)
}
func testFromJSON() {
// Given
var json = [String: Any]()
json["accepted_apps"] = ["site", "android"]
json["ticket_transfer_enabled"] = false
json["ticket_transfer_required"] = true
// When
let obj = EventAttributes.fromJSON(json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.acceptedApps[0], "site")
XCTAssertEqual(obj?.acceptedApps[1], "android")
XCTAssertEqual(obj?.transferEnabled, false)
XCTAssertEqual(obj?.transferRequired, true)
}
}
|
d1c55cf7ccbb51f9236bc3b17b93b523
| 27.8 | 80 | 0.607253 | false | true | false | false |
royhsu/chocolate-foundation
|
refs/heads/master
|
Chocolate/Pods/CHFoundation/Source/CAAnimation+Handlers..swift
|
mit
|
2
|
//
// CAAnimation+Handlers.swift
// CHFoundation
//
// Created by 許郁棋 on 2016/8/30.
// Copyright © 2016年 Tiny World. All rights reserved.
import QuartzCore
public typealias AnimationBeginHandler = (CAAnimation) -> Void
public typealias AnimationCompletionHandler = (CAAnimation, Bool) -> Void
// MARK: - AnimationDelegate
private class AnimationDelegate: NSObject {
var beginHandler: AnimationBeginHandler?
var completionHandler: AnimationCompletionHandler?
}
// MARK: - CAAnimationDelegate
extension AnimationDelegate: CAAnimationDelegate {
func animationDidStart(_ animation: CAAnimation) {
guard let beginHandler = beginHandler else { return }
beginHandler(animation)
}
func animationDidStop(_ animation: CAAnimation, finished: Bool) {
guard let completionHandler = completionHandler else { return }
completionHandler(animation, finished)
}
}
// MARK: - CAAnimation
public extension CAAnimation {
/// This handler will be executed at the beginning of animation.
var beginHandler: AnimationBeginHandler? {
get {
let delegate = self.delegate as? AnimationDelegate
return delegate?.beginHandler
}
set {
let animationDelegate =
(self.delegate as? AnimationDelegate) ??
AnimationDelegate()
animationDelegate.beginHandler = newValue
delegate = animationDelegate
}
}
/// This handler will be executed after animation finished.
var completionHandler: AnimationCompletionHandler? {
get {
let delegate = self.delegate as? AnimationDelegate
return delegate?.completionHandler
}
set {
let animationDelegate =
(self.delegate as? AnimationDelegate) ??
AnimationDelegate()
animationDelegate.completionHandler = newValue
delegate = animationDelegate
}
}
}
|
8aa3243cc6f5ce46721a90e67d7edd3d
| 22.131313 | 73 | 0.572926 | false | false | false | false |
shergin/SherginScrollableNavigationBar
|
refs/heads/master
|
SherginScrollableNavigationBar.swift
|
mit
|
1
|
//
// SherginScrollableNavigationBar.swift
// ScrollableNavigationBarDemo
//
// Created by Valentin Shergin on 19/09/14.
// Copyright (c) 2014 shergin research. All rights reserved.
//
import UIKit
enum ScrollState {
case None
case Gesture
case Finishing
}
let ScrollViewContentOffsetPropertyName: String = "contentOffset"
let NavigationBarAnimationName: String = "NavigationBarScrollAnimation"
let DefaultScrollTolerance: CGFloat = 44.0;
public class SherginScrollableNavigationBar: UINavigationBar, UIGestureRecognizerDelegate
{
var scrollView: UIScrollView?
var panGestureRecognizer: UIPanGestureRecognizer!
var scrollTolerance = DefaultScrollTolerance
var scrollOffsetStart: CGFloat = 0.0
var scrollState: ScrollState = .None
var barOffsetStart: CGFloat = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init(coder: NSCoder) {
super.init(coder: coder)
self.commonInit()
}
func commonInit() {
self.panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
self.panGestureRecognizer.delegate = self
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "applicationDidBecomeActive",
name: UIApplicationDidBecomeActiveNotification,
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "statusBarOrientationDidChange",
name: UIApplicationDidChangeStatusBarOrientationNotification,
object: nil
)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationDidBecomeActiveNotification,
object: nil
)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UIApplicationDidChangeStatusBarOrientationNotification,
object: nil
)
self.scrollView = nil
}
func statusBarOrientationDidChange() {
self.resetToDefaultPosition(false);
}
func applicationDidBecomeActive() {
self.resetToDefaultPosition(false);
}
//pragma mark - UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true;
}
var scrollable: Bool {
let scrollView = self.scrollView!
let contentSize = scrollView.contentSize;
let contentInset = scrollView.contentInset;
let containerSize = scrollView.bounds.size;
let containerHeight = containerSize.height - contentInset.top - contentInset.bottom;
let contentHeight = contentSize.height;
let barHeight = self.frame.size.height;
return contentHeight - self.scrollTolerance - barHeight > containerHeight;
}
var scrollOffset: CGFloat {
let scrollView = self.scrollView!
return -(scrollView.contentOffset.y + scrollView.contentInset.top);
}
var scrollOffsetRelative: CGFloat {
return self.scrollOffset - self.scrollOffsetStart;
}
public func setScrollView(scrollView: UIScrollView?) {
if self.scrollView != nil {
self.scrollView!.removeObserver(
self,
forKeyPath: ScrollViewContentOffsetPropertyName
)
scrollView?.removeGestureRecognizer(self.panGestureRecognizer)
}
self.scrollView = scrollView
if self.scrollView != nil {
scrollView?.addObserver(
self,
forKeyPath: ScrollViewContentOffsetPropertyName,
options: NSKeyValueObservingOptions.New,
context: nil
)
scrollView?.addGestureRecognizer(self.panGestureRecognizer)
}
}
public func resetToDefaultPosition(animated: Bool) {
self.setBarOffset(0.0, animated: animated)
}
override public func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<()>) {
if (self.scrollView != nil) && (keyPath == ScrollViewContentOffsetPropertyName) && (object as NSObject == self.scrollView!) {
self.scrollViewDidScroll()
}
//super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
func setBarOffset(offset: CGFloat, animated: Bool) {
var offset: CGFloat = offset;
if offset > 0 {
offset = 0;
}
let barHeight: CGFloat = self.frame.size.height
let statusBarHeight: CGFloat = self.statusBarHeight()
offset = max(offset, -barHeight)
let alpha: CGFloat = min(1.0 - abs(offset / barHeight) + CGFloat(FLT_EPSILON), 1.0)
let currentOffset: CGFloat = self.frame.origin.y
let targetOffset: CGFloat = statusBarHeight + offset
if (abs(currentOffset - targetOffset) < CGFloat(FLT_EPSILON)) {
return;
}
if (animated) {
UIView.beginAnimations(NavigationBarAnimationName, context: nil)
}
let subviews: [UIView] = self.subviews as [UIView]
let backgroundView: UIView = subviews[0]
// apply alpha
for view in subviews {
let isBackgroundView: Bool = (view == backgroundView)
let isInvisible: Bool = view.hidden || view.alpha < CGFloat(FLT_EPSILON)
if isBackgroundView || isInvisible {
continue;
}
view.alpha = alpha;
}
// apply offset
var frame: CGRect = self.frame;
frame.origin.y = targetOffset;
self.frame = frame;
if (animated) {
UIView.commitAnimations()
}
}
var barOffset: CGFloat {
get {
return self.frame.origin.y - self.statusBarHeight()
}
set(offset) {
self.setBarOffset(offset, animated: false);
}
}
func statusBarHeight() -> CGFloat {
let orientation = UIApplication.sharedApplication().statusBarOrientation
let frame = UIApplication.sharedApplication().statusBarFrame
switch (orientation) {
case .Portrait, .PortraitUpsideDown:
return CGRectGetHeight(frame)
case .LandscapeLeft, .LandscapeRight:
return CGRectGetWidth(frame)
default:
assertionFailure("Unknown orientation.")
}
}
func handlePanGesture(gesture: UIPanGestureRecognizer) {
if self.scrollView == nil || gesture.view != self.scrollView {
return
}
let gestureState: UIGestureRecognizerState = gesture.state
if gestureState == .Began {
// Begin state
self.scrollState = .Gesture
self.scrollOffsetStart = self.scrollOffset
self.barOffsetStart = self.barOffset;
}
else if gestureState == .Changed {
// Changed state
self.scrollViewDidScroll()
}
else if
gestureState == .Ended ||
gestureState == .Cancelled ||
gestureState == .Failed
{
// End state
self.scrollState = .Finishing
self.scrollFinishing()
}
}
func scrollViewDidScroll() {
if (!self.scrollable) {
self.resetToDefaultPosition(false);
return;
}
var offset = self.scrollOffsetRelative
var tolerance = self.scrollTolerance
if self.scrollOffsetRelative > 0 {
let maxTolerance = self.barOffsetStart - self.scrollOffsetStart
if tolerance > maxTolerance {
tolerance = maxTolerance;
}
}
if abs(offset) < tolerance {
offset = 0.0;
}
else {
offset = offset + (offset < 0 ? +tolerance : -tolerance);
}
self.barOffset = self.barOffsetStart + offset
self.scrollFinishing();
}
var timer: NSTimer?
func scrollFinishing() {
if let timer = self.timer {
timer.invalidate()
}
if self.scrollState != .Finishing {
return;
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "scrollFinishActually", userInfo: nil, repeats: false)
}
func scrollFinishActually() {
self.scrollState = .None;
var barOffset = self.barOffset;
var barHeight = self.frame.size.height;
if
(abs(barOffset) < barHeight / 2.0) ||
(-self.scrollOffset < barHeight)
{
// show bar
barOffset = 0;
}
else {
// hide bar
barOffset = -barHeight;
}
self.setBarOffset(barOffset, animated:true);
self.barOffsetStart = 0.0;
}
}
|
d0f06802add5113aaf33cc731457076a
| 28.149682 | 179 | 0.608434 | false | false | false | false |
producthunt/producthunt-osx
|
refs/heads/master
|
Source/Models/PHAnalitycsAPIEndpoint.swift
|
mit
|
1
|
//
// PHAnalitycsAPIEndpoint.swift
// Product Hunt
//
// Created by Vlado on 5/5/16.
// Copyright © 2016 ProductHunt. All rights reserved.
//
import Foundation
import AFNetworking
class PHAnalitycsAPIEndpoint {
static let kPHAnalitycsEndpointHost = "https://api.segment.io"
fileprivate let manager = AFHTTPSessionManager(baseURL: URL(string: "\(kPHAnalitycsEndpointHost)/v1"))
init(key: String) {
manager.responseSerializer = AFJSONResponseSerializer()
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")
manager.requestSerializer.setValue(Credentials.basic(key, password: ""), forHTTPHeaderField: "Authorization")
}
func get(_ url: String, parameters: [String: Any]?, completion: PHAPIEndpointCompletion? = nil) {
manager.get(url, parameters: parameters, progress: nil, success: { (task, response) in
completion?((response as? [String: AnyObject]), nil)
}) { (task, error) in
print(error)
completion?(nil, error as NSError?)
}
}
func post(_ url: String, parameters: [String: Any]?, completion: PHAPIEndpointCompletion? = nil) {
manager.post(url, parameters: parameters, progress: nil, success: { (task, response) in
completion?((response as? [String: AnyObject]), nil)
}) { (task, error) in
print(error)
completion?(nil, error as NSError?)
}
}
}
|
860c1b3f867c24f1ba5633cc3023fb91
| 36.456522 | 117 | 0.669182 | false | false | false | false |
oddnetworks/odd-sample-apps
|
refs/heads/master
|
apple/tvos/tvOSTemplate/Odd tvOS Template/MediaInfoTableViewCell.swift
|
apache-2.0
|
1
|
//
// MediaInfoTableViewCell.swift
// Odd-iOS
//
// Created by Patrick McConnell on 12/1/15.
// Copyright © 2015 Patrick McConnell. All rights reserved.
//
import UIKit
import OddSDKtvOS
class MediaInfoTableViewCell: UITableViewCell {
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var notesLabel: UILabel!
func reset() {
DispatchQueue.main.async {
self.thumbnailImageView.image = UIImage(named: "defaultThumbnail")
self.titleLabel.text = "Loading..."
self.notesLabel.text = "Loading..."
}
}
func configure(withMediaObject mediaObject: OddMediaObject) {
DispatchQueue.main.async {
if mediaObject is OddMediaObjectCollection {
if let collection = mediaObject as? OddMediaObjectCollection,
let title = collection.title {
self.titleLabel.text = "\(title) - (\(collection.numberOfObjects)) items"
}
} else {
self.titleLabel.text = mediaObject.title
}
self.notesLabel.text = mediaObject.notes
self.thumbnailImageView.image = UIImage(named: "defaultThumbnail")
}
mediaObject.thumbnail { (image) -> Void in
if let thumbnail = image {
DispatchQueue.main.async { () -> Void in
UIView.animate(withDuration: 0.3, animations: {
self.thumbnailImageView.alpha = 0
}, completion: { (complete) in
self.thumbnailImageView.image = thumbnail
UIView.animate(withDuration: 0.3, animations: {
self.thumbnailImageView.alpha = 1
})
})
}
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
self.backgroundColor = .gray
self.titleLabel.textColor = .darkGray
}
func becomeFocused(withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
self.titleLabel.textColor = .black
}, completion: {
})
}
func resignFocus(withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
self.titleLabel.textColor = .darkGray
}, completion: {
})
}
}
|
8531e35cb46ea6ef7b13b02350841f6d
| 28.298701 | 89 | 0.648493 | false | false | false | false |
chrisdhaan/CDMarkdownKit
|
refs/heads/master
|
Source/CDMarkdownHeader.swift
|
mit
|
1
|
//
// CDMarkdownHeader.swift
// CDMarkdownKit
//
// Created by Christopher de Haan on 11/7/16.
//
// Copyright © 2016-2022 Christopher de Haan <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
open class CDMarkdownHeader: CDMarkdownLevelElement {
fileprivate static let regex = "^\\s*(#{1,%@})\\s*(.+)$\n*"
fileprivate struct CDMarkdownHeadingHashes {
static let one = 9
static let two = 5
static let three = 4
static let four = 3
static let five = 2
static let six = 1
static let zero = 0
}
open var maxLevel: Int
open var font: CDFont?
open var color: CDColor?
open var backgroundColor: CDColor?
open var paragraphStyle: NSParagraphStyle?
open var fontIncrease: Int
open var regex: String {
let level: String = maxLevel > 0 ? "\(maxLevel)" : ""
return String(format: CDMarkdownHeader.regex, level)
}
public init(font: CDFont? = CDFont.boldSystemFont(ofSize: 12),
maxLevel: Int = 0,
fontIncrease: Int = 2,
color: CDColor? = nil,
backgroundColor: CDColor? = nil,
paragraphStyle: NSParagraphStyle? = nil) {
self.maxLevel = maxLevel
self.font = font
self.color = color
self.backgroundColor = backgroundColor
if let paragraphStyle = paragraphStyle {
self.paragraphStyle = paragraphStyle
} else {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 6
paragraphStyle.paragraphSpacingBefore = 12
self.paragraphStyle = paragraphStyle
}
self.fontIncrease = fontIncrease
}
open func formatText(_ attributedString: NSMutableAttributedString,
range: NSRange,
level: Int) {
attributedString.deleteCharacters(in: range)
let string = attributedString.mutableString
if range.location - 2 > 0 && string.substring(with: NSRange(location: range.location - 2,
length: 2)) == "\n\n" {
string.deleteCharacters(in: NSRange(location: range.location - 1,
length: 1))
}
}
open func attributesForLevel(_ level: Int) -> [CDAttributedStringKey: AnyObject] {
var attributes = self.attributes
var fontMultiplier: CGFloat
switch level {
case 0:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.one)
case 1:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.two)
case 2:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.three)
case 3:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.four)
case 4:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.five)
case 5:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.six)
case 6:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.zero)
default:
fontMultiplier = CGFloat(CDMarkdownHeadingHashes.four)
}
if let font = font {
let headerFontSize: CGFloat = font.pointSize + (CGFloat(fontMultiplier) * CGFloat(fontIncrease))
let headerFont = font.withSize(headerFontSize)
attributes.addFont(headerFont)
}
return attributes
}
}
|
447dd4e36bd39a72c1ae52cac4fb1851
| 37.204918 | 108 | 0.63098 | false | false | false | false |
MartinOSix/DemoKit
|
refs/heads/master
|
dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_Function.swift
|
apache-2.0
|
1
|
//
// ViewController_Function.swift
// SwiftSyntaxDemo
//
// Created by runo on 16/12/5.
// Copyright © 2016年 com.runo. All rights reserved.
//
import UIKit
class ViewController_Function: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.functionType1()
self.functionType2(Height: 10)
self.functionType3(Height: 10, Width: 20)
print("返回值\(self.functionType4(Height: 10, Width: 20))")
var sum = 10
self.functionType5(Sum: &sum)
print("sum=\(sum)")
self.functionType6(1, 2)
let value = self.functionType7()
print("第一个返回值\(value.a)")
print("第二个返回值\(value.b)")
//采用下标的方式返回
print("第一个返回值\(value.0)");
print("第二个返回值\(value.1)");
self.functionType8(fun: functionType4)
print("\(self.functionType5(Height: 1, Width: 2, Length: 3))")
print("函数嵌套\n\(functionType9())");
print("不定参数函数\n\(functionType11(parameters: 1,23,4,10))");
}
func functionType1(){
print("无参无返回值函数")
}
func functionType2(Height: Int){
print("带一个Int参数无返回值的函数\(Height)")
}
func functionType3(Height: Int, Width: Int){
print("带两个Int参数的函数\(Height)和\(Width)")
}
func functionType4(Height: Int, Width: Int) -> Int {
print("带两个Int参数的函数\(Height)和\(Width)返回两个数之和")
return Height + Width
}
func functionType5(Height: Int, Width: Int, Length: Int) -> Int {
print("函数重载")
return Height * Width * Length
}
func functionType5(Sum:inout Int) {
print("不管传进来的数是多少都会把原来的数改成0")
Sum = 0
}
//一般冒号前面是参数名,如果只有一个默认是外部参数名 “_”表示忽略名字 空格后面表示内部参数名
func functionType6(_ a:Int, _ b:Int) {
print("忽略外部参数名的函数\(a)和\(b)")
}
func functionType7() -> (a:Int,b:Int) {
print("元祖的形式返回两个参数")
return (1,2)
}
func functionType8(fun:(Int,Int)->Int) {
print("函数作为参数的形式执行结果为\(fun(10,20))")
}
/**函数嵌套
*item1
*item2
*/
func functionType9() -> Int {
func functionType10(num :Int) -> Int{
return num * num
}
return functionType10(num: 2)
}
///可变参数的函数
func functionType11(parameters :Int...) -> Int {
var sum = 0
for number in parameters {
sum = sum + number
}
return sum
}
}
|
1069e80df95a95094c20d531206cd837
| 22.851852 | 70 | 0.53882 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/PackageModel/PackageIdentity.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
/// The canonical identifier for a package, based on its source location.
public struct PackageIdentity: CustomStringConvertible {
/// A textual representation of this instance.
public let description: String
/// Creates a package identity from a string.
/// - Parameter value: A string used to identify a package.
init(_ value: String) {
self.description = value
}
/// Creates a package identity from a URL.
/// - Parameter url: The package's URL.
public init(url: URL) {
self.init(urlString: url.absoluteString)
}
/// Creates a package identity from a URL.
/// - Parameter urlString: The package's URL.
// FIXME: deprecate this
public init(urlString: String) {
self.description = PackageIdentityParser(urlString).description
}
/// Creates a package identity from a file path.
/// - Parameter path: An absolute path to the package.
public init(path: AbsolutePath) {
self.description = PackageIdentityParser(path.pathString).description
}
/// Creates a plain package identity for a root package
/// - Parameter value: A string used to identify a package, will be used unmodified
public static func plain(_ value: String) -> PackageIdentity {
PackageIdentity(value)
}
// TODO: formalize package registry identifier
public var scopeAndName: (scope: Scope, name: Name)? {
let components = description.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true)
guard components.count == 2,
let scope = Scope(components.first),
let name = Name(components.last)
else { return .none }
return (scope: scope, name: name)
}
}
extension PackageIdentity: Equatable, Comparable {
private func compare(to other: PackageIdentity) -> ComparisonResult {
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
}
extension PackageIdentity: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
}
extension PackageIdentity: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let description = try container.decode(String.self)
self.init(description)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.description)
}
}
// MARK: -
extension PackageIdentity {
/// Provides a namespace for related packages within a package registry.
public struct Scope: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral {
public let description: String
public init(validating description: String) throws {
guard !description.isEmpty else {
throw StringError("The minimum length of a package scope is 1 character.")
}
guard description.count <= 39 else {
throw StringError("The maximum length of a package scope is 39 characters.")
}
for (index, character) in zip(description.indices, description) {
guard character.isASCII,
character.isLetter ||
character.isNumber ||
character == "-"
else {
throw StringError("A package scope consists of alphanumeric characters and hyphens.")
}
if character.isPunctuation {
switch (index, description.index(after: index)) {
case (description.startIndex, _):
throw StringError("Hyphens may not occur at the beginning of a scope.")
case (_, description.endIndex):
throw StringError("Hyphens may not occur at the end of a scope.")
case (_, let nextIndex) where description[nextIndex].isPunctuation:
throw StringError("Hyphens may not occur consecutively within a scope.")
default:
continue
}
}
}
self.description = description
}
public init?(_ description: String) {
guard let scope = try? Scope(validating: description) else { return nil }
self = scope
}
fileprivate init?(_ substring: String.SubSequence?) {
guard let substring = substring else { return nil }
self.init(String(substring))
}
// MARK: - Equatable & Comparable
private func compare(to other: Scope) -> ComparisonResult {
// Package scopes are case-insensitive (for example, `mona` ≍ `MONA`).
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: Scope, rhs: Scope) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
// MARK: - ExpressibleByStringLiteral
public init(stringLiteral value: StringLiteralType) {
try! self.init(validating: value)
}
}
/// Uniquely identifies a package in a scope
public struct Name: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral {
public let description: String
public init(validating description: String) throws {
guard !description.isEmpty else {
throw StringError("The minimum length of a package name is 1 character.")
}
guard description.count <= 100 else {
throw StringError("The maximum length of a package name is 100 characters.")
}
for (index, character) in zip(description.indices, description) {
guard character.isASCII,
character.isLetter ||
character.isNumber ||
character == "-" ||
character == "_"
else {
throw StringError("A package name consists of alphanumeric characters, underscores, and hyphens.")
}
if character.isPunctuation {
switch (index, description.index(after: index)) {
case (description.startIndex, _):
throw StringError("Hyphens and underscores may not occur at the beginning of a name.")
case (_, description.endIndex):
throw StringError("Hyphens and underscores may not occur at the end of a name.")
case (_, let nextIndex) where description[nextIndex].isPunctuation:
throw StringError("Hyphens and underscores may not occur consecutively within a name.")
default:
continue
}
}
}
self.description = description
}
public init?(_ description: String) {
guard let name = try? Name(validating: description) else { return nil }
self = name
}
fileprivate init?(_ substring: String.SubSequence?) {
guard let substring = substring else { return nil }
self.init(String(substring))
}
// MARK: - Equatable & Comparable
private func compare(to other: Name) -> ComparisonResult {
// Package scopes are case-insensitive (for example, `LinkedList` ≍ `LINKEDLIST`).
return self.description.caseInsensitiveCompare(other.description)
}
public static func == (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedSame
}
public static func < (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedAscending
}
public static func > (lhs: Name, rhs: Name) -> Bool {
return lhs.compare(to: rhs) == .orderedDescending
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(description.lowercased())
}
// MARK: - ExpressibleByStringLiteral
public init(stringLiteral value: StringLiteralType) {
try! self.init(validating: value)
}
}
}
// MARK: -
struct PackageIdentityParser {
/// A textual representation of this instance.
public let description: String
/// Instantiates an instance of the conforming type from a string representation.
public init(_ string: String) {
self.description = Self.computeDefaultName(fromLocation: string).lowercased()
}
/// Compute the default name of a package given its URL.
public static func computeDefaultName(fromURL url: URL) -> String {
Self.computeDefaultName(fromLocation: url.absoluteString)
}
/// Compute the default name of a package given its path.
public static func computeDefaultName(fromPath path: AbsolutePath) -> String {
Self.computeDefaultName(fromLocation: path.pathString)
}
/// Compute the default name of a package given its location.
public static func computeDefaultName(fromLocation url: String) -> String {
#if os(Windows)
let isSeparator : (Character) -> Bool = { $0 == "/" || $0 == "\\" }
#else
let isSeparator : (Character) -> Bool = { $0 == "/" }
#endif
// Get the last path component of the URL.
// Drop the last character in case it's a trailing slash.
var endIndex = url.endIndex
if let lastCharacter = url.last, isSeparator(lastCharacter) {
endIndex = url.index(before: endIndex)
}
let separatorIndex = url[..<endIndex].lastIndex(where: isSeparator)
let startIndex = separatorIndex.map { url.index(after: $0) } ?? url.startIndex
var lastComponent = url[startIndex..<endIndex]
// Strip `.git` suffix if present.
if lastComponent.hasSuffix(".git") {
lastComponent = lastComponent.dropLast(4)
}
return String(lastComponent)
}
}
/// A canonicalized package location.
///
/// A package may declare external packages as dependencies in its manifest.
/// Each external package is uniquely identified by the location of its source code.
///
/// An external package dependency may itself have one or more external package dependencies,
/// known as _transitive dependencies_.
/// When multiple packages have dependencies in common,
/// Swift Package Manager determines which version of that package should be used
/// (if any exist that satisfy all specified requirements)
/// in a process called package resolution.
///
/// External package dependencies are located by a URL
/// (which may be an implicit `file://` URL in the form of a file path).
/// For the purposes of package resolution,
/// package URLs are case-insensitive (mona ≍ MONA)
/// and normalization-insensitive (n + ◌̃ ≍ ñ).
/// Swift Package Manager takes additional steps to canonicalize URLs
/// to resolve insignificant differences between URLs.
/// For example,
/// the URLs `https://example.com/Mona/LinkedList` and `[email protected]:mona/linkedlist`
/// are equivalent, in that they both resolve to the same source code repository,
/// despite having different scheme, authority, and path components.
///
/// The `PackageIdentity` type canonicalizes package locations by
/// performing the following operations:
///
/// * Removing the scheme component, if present
/// ```
/// https://example.com/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Removing the userinfo component (preceded by `@`), if present:
/// ```
/// [email protected]/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Removing the port subcomponent, if present:
/// ```
/// example.com:443/mona/LinkedList → example.com/mona/LinkedList
/// ```
/// * Replacing the colon (`:`) preceding the path component in "`scp`-style" URLs:
/// ```
/// [email protected]:mona/LinkedList.git → example.com/mona/LinkedList
/// ```
/// * Expanding the tilde (`~`) to the provided user, if applicable:
/// ```
/// ssh://[email protected]/~/LinkedList.git → example.com/~mona/LinkedList
/// ```
/// * Removing percent-encoding from the path component, if applicable:
/// ```
/// example.com/mona/%F0%9F%94%97List → example.com/mona/🔗List
/// ```
/// * Removing the `.git` file extension from the path component, if present:
/// ```
/// example.com/mona/LinkedList.git → example.com/mona/LinkedList
/// ```
/// * Removing the trailing slash (`/`) in the path component, if present:
/// ```
/// example.com/mona/LinkedList/ → example.com/mona/LinkedList
/// ```
/// * Removing the fragment component (preceded by `#`), if present:
/// ```
/// example.com/mona/LinkedList#installation → example.com/mona/LinkedList
/// ```
/// * Removing the query component (preceded by `?`), if present:
/// ```
/// example.com/mona/LinkedList?utm_source=forums.swift.org → example.com/mona/LinkedList
/// ```
/// * Adding a leading slash (`/`) for `file://` URLs and absolute file paths:
/// ```
/// file:///Users/mona/LinkedList → /Users/mona/LinkedList
/// ```
public struct CanonicalPackageLocation: Equatable, CustomStringConvertible {
/// A textual representation of this instance.
public let description: String
/// Instantiates an instance of the conforming type from a string representation.
public init(_ string: String) {
var description = string.precomposedStringWithCanonicalMapping.lowercased()
// Remove the scheme component, if present.
let detectedScheme = description.dropSchemeComponentPrefixIfPresent()
// Remove the userinfo subcomponent (user / password), if present.
if case (let user, _)? = description.dropUserinfoSubcomponentPrefixIfPresent() {
// If a user was provided, perform tilde expansion, if applicable.
description.replaceFirstOccurenceIfPresent(of: "/~/", with: "/~\(user)/")
}
// Remove the port subcomponent, if present.
description.removePortComponentIfPresent()
// Remove the fragment component, if present.
description.removeFragmentComponentIfPresent()
// Remove the query component, if present.
description.removeQueryComponentIfPresent()
// Accomodate "`scp`-style" SSH URLs
if detectedScheme == nil || detectedScheme == "ssh" {
description.replaceFirstOccurenceIfPresent(of: ":", before: description.firstIndex(of: "/"), with: "/")
}
// Split the remaining string into path components,
// filtering out empty path components and removing valid percent encodings.
var components = description.split(omittingEmptySubsequences: true, whereSeparator: isSeparator)
.compactMap { $0.removingPercentEncoding ?? String($0) }
// Remove the `.git` suffix from the last path component.
var lastPathComponent = components.popLast() ?? ""
lastPathComponent.removeSuffixIfPresent(".git")
components.append(lastPathComponent)
description = components.joined(separator: "/")
// Prepend a leading slash for file URLs and paths
if detectedScheme == "file" || string.first.flatMap(isSeparator) ?? false {
description.insert("/", at: description.startIndex)
}
self.description = description
}
}
#if os(Windows)
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" || $0 == "\\" }
#else
fileprivate let isSeparator: (Character) -> Bool = { $0 == "/" }
#endif
private extension Character {
var isDigit: Bool {
switch self {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
return true
default:
return false
}
}
var isAllowedInURLScheme: Bool {
return isLetter || self.isDigit || self == "+" || self == "-" || self == "."
}
}
private extension String {
@discardableResult
mutating func removePrefixIfPresent<T: StringProtocol>(_ prefix: T) -> Bool {
guard hasPrefix(prefix) else { return false }
removeFirst(prefix.count)
return true
}
@discardableResult
mutating func removeSuffixIfPresent<T: StringProtocol>(_ suffix: T) -> Bool {
guard hasSuffix(suffix) else { return false }
removeLast(suffix.count)
return true
}
@discardableResult
mutating func dropSchemeComponentPrefixIfPresent() -> String? {
if let rangeOfDelimiter = range(of: "://"),
self[startIndex].isLetter,
self[..<rangeOfDelimiter.lowerBound].allSatisfy({ $0.isAllowedInURLScheme })
{
defer { self.removeSubrange(..<rangeOfDelimiter.upperBound) }
return String(self[..<rangeOfDelimiter.lowerBound])
}
return nil
}
@discardableResult
mutating func dropUserinfoSubcomponentPrefixIfPresent() -> (user: String, password: String?)? {
if let indexOfAtSign = firstIndex(of: "@"),
let indexOfFirstPathComponent = firstIndex(where: isSeparator),
indexOfAtSign < indexOfFirstPathComponent
{
defer { self.removeSubrange(...indexOfAtSign) }
let userinfo = self[..<indexOfAtSign]
var components = userinfo.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false)
guard components.count > 0 else { return nil }
let user = String(components.removeFirst())
let password = components.last.map(String.init)
return (user, password)
}
return nil
}
@discardableResult
mutating func removePortComponentIfPresent() -> Bool {
if let indexOfFirstPathComponent = firstIndex(where: isSeparator),
let startIndexOfPort = firstIndex(of: ":"),
startIndexOfPort < endIndex,
let endIndexOfPort = self[index(after: startIndexOfPort)...].lastIndex(where: { $0.isDigit }),
endIndexOfPort <= indexOfFirstPathComponent
{
self.removeSubrange(startIndexOfPort ... endIndexOfPort)
return true
}
return false
}
@discardableResult
mutating func removeFragmentComponentIfPresent() -> Bool {
if let index = firstIndex(of: "#") {
self.removeSubrange(index...)
}
return false
}
@discardableResult
mutating func removeQueryComponentIfPresent() -> Bool {
if let index = firstIndex(of: "?") {
self.removeSubrange(index...)
}
return false
}
@discardableResult
mutating func replaceFirstOccurenceIfPresent<T: StringProtocol, U: StringProtocol>(
of string: T,
before index: Index? = nil,
with replacement: U
) -> Bool {
guard let range = range(of: string) else { return false }
if let index = index, range.lowerBound >= index {
return false
}
self.replaceSubrange(range, with: replacement)
return true
}
}
|
af470c35698a89568ea24c4c21278103
| 35.994633 | 118 | 0.617311 | false | false | false | false |
alessiobrozzi/firefox-ios
|
refs/heads/master
|
Client/Frontend/Home/ActivityStreamTopSitesCell.swift
|
mpl-2.0
|
1
|
/* 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 Foundation
import Shared
import WebImage
import Storage
struct TopSiteCellUX {
static let TitleHeight: CGFloat = 20
static let TitleBackgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.7)
static let TitleTextColor = UIColor.black
static let TitleFont = DynamicFontHelper.defaultHelper.DefaultSmallFont
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CellCornerRadius: CGFloat = 4
static let TitleOffset: CGFloat = 5
static let OverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let IconSize = CGSize(width: 40, height: 40)
static let BorderColor = UIColor(white: 0, alpha: 0.1)
static let BorderWidth: CGFloat = 0.5
}
/*
* The TopSite cell that appears in the ASHorizontalScrollView.
*/
class TopSiteItemCell: UICollectionViewCell {
var url: URL?
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
return imageView
}()
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.layer.masksToBounds = true
titleLabel.textAlignment = .center
titleLabel.font = TopSiteCellUX.TitleFont
titleLabel.textColor = TopSiteCellUX.TitleTextColor
titleLabel.backgroundColor = UIColor.clear
return titleLabel
}()
lazy private var faviconBG: UIView = {
let view = UIView()
view.layer.cornerRadius = TopSiteCellUX.CellCornerRadius
view.layer.masksToBounds = true
view.layer.borderWidth = TopSiteCellUX.BorderWidth
view.layer.borderColor = TopSiteCellUX.BorderColor.cgColor
return view
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = TopSiteCellUX.OverlayColor
selectedOverlay.isHidden = true
return selectedOverlay
}()
lazy var titleBorder: CALayer = {
let border = CALayer()
border.backgroundColor = TopSiteCellUX.BorderColor.cgColor
return border
}()
override var isSelected: Bool {
didSet {
self.selectedOverlay.isHidden = !isSelected
}
}
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = true
accessibilityIdentifier = "TopSite"
contentView.addSubview(titleLabel)
contentView.addSubview(faviconBG)
contentView.addSubview(imageView)
contentView.addSubview(selectedOverlay)
titleLabel.snp.makeConstraints { make in
make.left.equalTo(self).offset(TopSiteCellUX.TitleOffset)
make.right.equalTo(self).offset(-TopSiteCellUX.TitleOffset)
make.height.equalTo(TopSiteCellUX.TitleHeight)
make.bottom.equalTo(self)
}
imageView.snp.makeConstraints { make in
make.size.equalTo(TopSiteCellUX.IconSize)
make.centerX.equalTo(self)
make.centerY.equalTo(self).inset(-TopSiteCellUX.TitleHeight/2)
}
selectedOverlay.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
faviconBG.snp.makeConstraints { make in
make.top.left.right.equalTo(self)
make.bottom.equalTo(self).inset(TopSiteCellUX.TitleHeight)
}
}
override func layoutSubviews() {
super.layoutSubviews()
titleBorder.frame = CGRect(x: 0, y: frame.height - TopSiteCellUX.TitleHeight - TopSiteCellUX.BorderWidth, width: frame.width, height: TopSiteCellUX.BorderWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
contentView.backgroundColor = UIColor.clear
imageView.image = nil
imageView.backgroundColor = UIColor.clear
faviconBG.backgroundColor = UIColor.clear
imageView.sd_cancelCurrentImageLoad()
titleLabel.text = ""
}
func configureWithTopSiteItem(_ site: Site) {
url = site.tileURL
if let provider = site.metadata?.providerName {
titleLabel.text = provider.lowercased()
} else {
titleLabel.text = site.tileURL.hostSLD
}
accessibilityLabel = titleLabel.text
if let suggestedSite = site as? SuggestedSite {
let img = UIImage(named: suggestedSite.faviconImagePath!)
imageView.image = img
// This is a temporary hack to make amazon/wikipedia have white backrounds instead of their default blacks
// Once we remove the old TopSitesPanel we can change the values of amazon/wikipedia to be white instead of black.
self.faviconBG.backgroundColor = suggestedSite.backgroundColor.isBlackOrWhite ? UIColor.white : suggestedSite.backgroundColor
imageView.backgroundColor = self.faviconBG.backgroundColor
} else {
imageView.setFavicon(forSite: site, onCompletion: { [weak self] (color, url) in
if let url = url, url == self?.url {
self?.faviconBG.backgroundColor = color
self?.imageView.backgroundColor = color
}
})
}
}
}
struct ASHorizontalScrollCellUX {
static let TopSiteCellIdentifier = "TopSiteItemCell"
static let TopSiteItemSize = CGSize(width: 75, height: 75)
static let BackgroundColor = UIColor.white
static let PageControlRadius: CGFloat = 3
static let PageControlSize = CGSize(width: 30, height: 15)
static let PageControlOffset: CGFloat = 12
static let MinimumInsets: CGFloat = 15
}
/*
The View that describes the topSite cell that appears in the tableView.
*/
class ASHorizontalScrollCell: UICollectionViewCell {
lazy var collectionView: UICollectionView = {
let layout = HorizontalFlowLayout()
layout.itemSize = ASHorizontalScrollCellUX.TopSiteItemSize
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.register(TopSiteItemCell.self, forCellWithReuseIdentifier: ASHorizontalScrollCellUX.TopSiteCellIdentifier)
collectionView.backgroundColor = UIColor.clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
return collectionView
}()
lazy fileprivate var pageControl: FilledPageControl = {
let pageControl = FilledPageControl()
pageControl.tintColor = UIColor.gray
pageControl.indicatorRadius = ASHorizontalScrollCellUX.PageControlRadius
pageControl.isUserInteractionEnabled = true
pageControl.isAccessibilityElement = true
pageControl.accessibilityIdentifier = "pageControl"
pageControl.accessibilityLabel = Strings.ASPageControlButton
pageControl.accessibilityTraits = UIAccessibilityTraitButton
return pageControl
}()
lazy fileprivate var pageControlPress: UITapGestureRecognizer = {
let press = UITapGestureRecognizer(target: self, action: #selector(ASHorizontalScrollCell.handlePageTap(_:)))
// press.delegate = self
return press
}()
weak var delegate: ASHorizontalScrollCellManager? {
didSet {
collectionView.delegate = delegate
collectionView.dataSource = delegate
delegate?.pageChangedHandler = { [weak self] progress in
self?.currentPageChanged(progress)
}
DispatchQueue.main.async {
self.setNeedsLayout()
self.collectionView.reloadData()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = false
accessibilityIdentifier = "TopSitesCell"
backgroundColor = UIColor.clear
contentView.addSubview(collectionView)
contentView.addSubview(pageControl)
pageControl.addGestureRecognizer(self.pageControlPress)
collectionView.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
pageControl.snp.makeConstraints { make in
make.size.equalTo(ASHorizontalScrollCellUX.PageControlSize)
make.top.equalTo(collectionView.snp.bottom).inset(ASHorizontalScrollCellUX.PageControlOffset)
make.centerX.equalTo(self.snp.centerX)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! HorizontalFlowLayout
pageControl.pageCount = layout.numberOfPages(with: self.frame.size)
pageControl.isHidden = pageControl.pageCount <= 1
}
func currentPageChanged(_ currentPage: CGFloat) {
pageControl.progress = currentPage
if currentPage == floor(currentPage) {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
self.setNeedsLayout()
}
}
func handlePageTap(_ gesture: UITapGestureRecognizer) {
guard pageControl.pageCount > 1 else {
return
}
if pageControl.pageCount > pageControl.currentPage + 1 {
pageControl.progress = CGFloat(pageControl.currentPage + 1)
} else {
pageControl.progress = CGFloat(pageControl.currentPage - 1)
}
let swipeCoordinate = CGFloat(pageControl.currentPage) * self.collectionView.frame.size.width
self.collectionView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/*
A custom layout used to show a horizontal scrolling list with paging. Similar to iOS springboard.
A modified version of http://stackoverflow.com/a/34167915
*/
class HorizontalFlowLayout: UICollectionViewLayout {
var itemSize = CGSize.zero
fileprivate var cellCount: Int {
if let collectionView = collectionView, let dataSource = collectionView.dataSource {
return dataSource.collectionView(collectionView, numberOfItemsInSection: 0)
}
return 0
}
var boundsSize = CGSize.zero
private var insets = UIEdgeInsets(equalInset: ASHorizontalScrollCellUX.MinimumInsets)
private var sectionInsets: CGFloat = 0
override func prepare() {
super.prepare()
boundsSize = self.collectionView?.frame.size ?? CGSize.zero
}
func numberOfPages(with bounds: CGSize) -> Int {
let itemsPerPage = maxVerticalItemsCount(height: bounds.height) * maxHorizontalItemsCount(width: bounds.width)
// Sometimes itemsPerPage is 0. In this case just return 0. We dont want to try dividing by 0.
return itemsPerPage == 0 ? 0 : Int(ceil(Double(cellCount) / Double(itemsPerPage)))
}
func calculateLayout(for size: CGSize) -> (size: CGSize, cellSize: CGSize, cellInsets: UIEdgeInsets) {
let width = size.width
let height = size.height
guard width != 0 else {
return (size: CGSize.zero, cellSize: self.itemSize, cellInsets: self.insets)
}
let horizontalItemsCount = maxHorizontalItemsCount(width: width)
var verticalItemsCount = maxVerticalItemsCount(height: height)
if cellCount <= horizontalItemsCount {
// If we have only a few items don't provide space for multiple rows.
verticalItemsCount = 1
}
// Take the number of cells and subtract its space in the view from the height. The left over space is the white space.
// The left over space is then devided evenly into (n + 1) parts to figure out how much space should be inbetween a cell
var verticalInsets = floor((height - (CGFloat(verticalItemsCount) * itemSize.height)) / CGFloat(verticalItemsCount + 1))
var horizontalInsets = floor((width - (CGFloat(horizontalItemsCount) * itemSize.width)) / CGFloat(horizontalItemsCount + 1))
// We want a minimum inset to make things not look crowded. We also don't want uneven spacing.
// If we dont have this. Set a minimum inset and recalculate the size of a cell
var estimatedItemSize = itemSize
if horizontalInsets < ASHorizontalScrollCellUX.MinimumInsets || horizontalInsets != verticalInsets {
verticalInsets = ASHorizontalScrollCellUX.MinimumInsets
horizontalInsets = ASHorizontalScrollCellUX.MinimumInsets
estimatedItemSize.width = floor((width - (CGFloat(horizontalItemsCount + 1) * horizontalInsets)) / CGFloat(horizontalItemsCount))
estimatedItemSize.height = estimatedItemSize.width + TopSiteCellUX.TitleHeight
}
//calculate our estimates.
let estimatedHeight = floor(estimatedItemSize.height * CGFloat(verticalItemsCount)) + (verticalInsets * (CGFloat(verticalItemsCount) + 1))
let estimatedSize = CGSize(width: CGFloat(numberOfPages(with: boundsSize)) * width, height: estimatedHeight)
let estimatedInsets = UIEdgeInsets(top: verticalInsets, left: horizontalInsets, bottom: verticalInsets, right: horizontalInsets)
return (size: estimatedSize, cellSize: estimatedItemSize, cellInsets: estimatedInsets)
}
override var collectionViewContentSize: CGSize {
let estimatedLayout = calculateLayout(for: boundsSize)
insets = estimatedLayout.cellInsets
itemSize = estimatedLayout.cellSize
boundsSize = estimatedLayout.size
return estimatedLayout.size
}
func maxVerticalItemsCount(height: CGFloat) -> Int {
let verticalItemsCount = Int(floor(height / (ASHorizontalScrollCellUX.TopSiteItemSize.height + insets.top)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfVerticalItems()
} else {
return verticalItemsCount
}
}
func maxHorizontalItemsCount(width: CGFloat) -> Int {
let horizontalItemsCount = Int(floor(width / (ASHorizontalScrollCellUX.TopSiteItemSize.width + insets.left)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfHorizontalItems() > horizontalItemsCount ? horizontalItemsCount : delegate.numberOfHorizontalItems()
} else {
return horizontalItemsCount
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElements(in: rect)
var allAttributes = [UICollectionViewLayoutAttributes]()
for i in 0 ..< cellCount {
let indexPath = IndexPath(row: i, section: 0)
let attr = self.computeLayoutAttributesForCellAtIndexPath(indexPath)
allAttributes.append(attr)
}
return allAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.computeLayoutAttributesForCellAtIndexPath(indexPath)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
// Sometimes when the topsiteCell isnt on the screen the newbounds that it tries to layout in is very tiny
// Resulting in incorrect layouts. So only layout when the width is greater than 320.
return newBounds.width <= 320
}
func computeLayoutAttributesForCellAtIndexPath(_ indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
let row = indexPath.row
let bounds = self.collectionView!.bounds
let verticalItemsCount = maxVerticalItemsCount(height: bounds.size.height)
let horizontalItemsCount = maxHorizontalItemsCount(width: bounds.size.width)
let itemsPerPage = verticalItemsCount * horizontalItemsCount
let columnPosition = row % horizontalItemsCount
let rowPosition = (row / horizontalItemsCount) % verticalItemsCount
let itemPage = Int(floor(Double(row)/Double(itemsPerPage)))
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
var frame = CGRect.zero
frame.origin.x = CGFloat(itemPage) * bounds.size.width + CGFloat(columnPosition) * (itemSize.width + insets.left) + insets.left
// If there is only 1 page. and only 1 row. Make sure to center.
if cellCount < horizontalItemsCount {
sectionInsets = floor((bounds.width - (CGFloat(cellCount) * (itemSize.width + insets.left))) / 2)
frame.origin.x += sectionInsets
}
frame.origin.y = CGFloat(rowPosition) * (itemSize.height + insets.top) + insets.top
frame.size = itemSize
attr.frame = frame
return attr
}
}
/*
Defines the number of items to show in topsites for different size classes.
*/
struct ASTopSiteSourceUX {
static let verticalItemsForTraitSizes = [UIUserInterfaceSizeClass.compact: 1, UIUserInterfaceSizeClass.regular: 2, UIUserInterfaceSizeClass.unspecified: 0]
static let horizontalItemsForTraitSizes = [UIUserInterfaceSizeClass.compact: 4, UIUserInterfaceSizeClass.regular: 8, UIUserInterfaceSizeClass.unspecified: 0]
static let maxNumberOfPages = 2
static let CellIdentifier = "TopSiteItemCell"
}
protocol ASHorizontalLayoutDelegate {
func numberOfVerticalItems() -> Int
func numberOfHorizontalItems() -> Int
}
/*
This Delegate/DataSource is used to manage the ASHorizontalScrollCell's UICollectionView.
This is left generic enough for it to be re used for other parts of Activity Stream.
*/
class ASHorizontalScrollCellManager: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, ASHorizontalLayoutDelegate {
var content: [Site] = []
var urlPressedHandler: ((URL, IndexPath) -> Void)?
var pageChangedHandler: ((CGFloat) -> Void)?
// The current traits that define the parent ViewController. Used to determine how many rows/columns should be created.
var currentTraits: UITraitCollection?
// Size classes define how many items to show per row/column.
func numberOfVerticalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
return ASTopSiteSourceUX.verticalItemsForTraitSizes[traits.verticalSizeClass]!
}
func numberOfHorizontalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
// An iPhone 5 in both landscape/portrait is considered compactWidth which means we need to let the layout determine how many items to show based on actual width.
if traits.horizontalSizeClass == .compact && traits.verticalSizeClass == .compact {
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[.regular]!
}
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[traits.horizontalSizeClass]!
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.content.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ASTopSiteSourceUX.CellIdentifier, for: indexPath) as! TopSiteItemCell
let contentItem = content[indexPath.row]
cell.configureWithTopSiteItem(contentItem)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let contentItem = content[indexPath.row]
guard let url = contentItem.url.asURL else {
return
}
urlPressedHandler?(url, indexPath)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
pageChangedHandler?(scrollView.contentOffset.x / pageWidth)
}
}
|
7c86a2b9e58ffb2957d0141afc9154a3
| 40.652977 | 170 | 0.692038 | false | false | false | false |
sabensm/playgrounds
|
refs/heads/develop
|
some-dictonary-stuff.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var webster: [String: String] = ["krill":"any of the small crustceans","fire":"a burning mass of material"]
var anotherDictonary: [Int: String] = [44:"my fav number",349:"i hate this number"]
if let krill = webster["krill"] {
print(krill)
}
//CLears dictionary
webster = [:]
if webster.isEmpty {
print("Our dictionary is quite the empty!")
}
var highScores: [String: Int] = ["spentak": 401, "Player1": 200, "Tomtendo": 1]
for (user, score) in highScores {
print("\(user): \(score)")
}
|
84e9e5a36e4febc24e764c23de811c99
| 17.0625 | 107 | 0.652249 | false | false | false | false |
leftdal/youslow
|
refs/heads/master
|
iOS/YouSlow/Controllers/VideoTableViewController.swift
|
gpl-3.0
|
1
|
//
// VideoTableViewController.swift
// Demo
//
// Created by to0 on 2/7/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import UIKit
class VideoTableViewController: UITableViewController, UISearchBarDelegate, VideoListProtocol {
@IBOutlet var videoSearchBar: UISearchBar!
var videoDataSource = VideoTableDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = videoDataSource
self.tableView.delegate = videoDataSource
videoSearchBar.delegate = self
self.videoDataSource.videoList.delegate = self
self.videoDataSource.videoList.requestDataForRefresh("Grumpy cat")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didReloadVideoData() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
let query = searchBar.text
self.videoDataSource.videoList.requestDataForRefresh(query!)
searchBar.resignFirstResponder()
}
// 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?) {
let dest = segue.destinationViewController as! SingleVideoViewController
let cell = sender as! UITableViewCell
let row = self.tableView.indexPathForCell(cell)!.row
cell.selected = false
dest.hidesBottomBarWhenPushed = true
dest.videoId = self.videoDataSource.videoList.videoIdOfIndex(row)
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
|
4a3126785db2c9553351d26e0020c47a
| 32.430556 | 113 | 0.695887 | false | false | false | false |
jurre/TravisToday
|
refs/heads/master
|
Today/RepoService.swift
|
mit
|
1
|
//
// RepoService.swift
// Travis
//
// Created by Jurre Stender on 22/10/14.
// Copyright (c) 2014 jurre. All rights reserved.
//
import Foundation
class RepoService: BaseService {
class var sharedService: RepoService {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : RepoService? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = RepoService()
}
return Static.instance!
}
func find(repo: Repo, completion: (Bool, Repo?) -> Void) {
let request = self.request(repo.url)
let fetchRepo = {() -> Void in
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, request, error) -> Void in
if (error != nil) {
println(error.localizedDescription)
completion(false, .None)
} else {
if let parsedRepo = RepoParser.fromJSONData(data) {
parsedRepo.access = repo.access
completion(true, parsedRepo)
} else {
completion(false, .None)
}
}
})
task.resume()
}
if (repo.access == .Private) {
TokenService().fetchToken({ (success, token) -> Void in
if (success) {
request.setValue(token!, forHTTPHeaderField: "Authorization")
fetchRepo()
} else {
println("Error fetching token")
completion(false, .None)
}
})
} else {
fetchRepo()
}
}
}
|
288c16dc7a8314b663e2ff715021b2b4
| 22.431034 | 126 | 0.638705 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.