repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
ShinCurry/Maria | refs/heads/master | YouGet/YouGet.swift | gpl-3.0 | 1 | //
// YouGet.swift
// YouGet
//
// Created by ShinCurry on 2016/12/12.
// Copyright © 2016年 ShinCurry. All rights reserved.
//
import Foundation
import SwiftyJSON
public enum ProcessMode {
case single
case multiply
}
public class YouGet {
public init?() {
if let bin = sh(command: "/usr/bin/which you-get"), !bin.isEmpty {
self.bin = bin.replacingOccurrences(of: "\n", with: "")
} else {
return nil
}
}
public var processMode = ProcessMode.single
private var bin = ""
private var task: Process?
/**
Add uris to download task
- parameter uris: download task links
*/
public func fetchData(fromLink link: String) -> YGResult? {
guard let jsonString = sh(command: "\(bin) --json \(link)"), !jsonString.isEmpty else {
print("you-get fetch data failed.")
return nil
}
guard let data = revise(JSONString: jsonString).data(using: .utf8, allowLossyConversion: false) else {
return nil
}
do {
let json = try JSON(data: data)
return YGResult(json: json)
} catch(let error) {
print(error)
return nil
}
}
/**
extracted information.
- parameter uris: download task links
*/
public func fetchInfo(fromLink link: String) -> String? {
return sh(command: "\(bin) --info \(link)")
}
/**
extracted information with URLs.
- parameter link: target link url
*/
public func fetchUrl(fromLink link: String) -> String? {
return sh(command: "\(bin) --url \(link)")?.components(separatedBy: "\n").dropLast().last
}
private func sh(command: String) -> String? {
var task: Process
switch processMode {
case .single:
self.task = Process()
task = self.task!
case .multiply:
task = Process()
}
task.launchPath = "/bin/sh"
task.environment = ["PATH": String(cString: getenv("PATH")) + ":/usr/local/bin",
"LC_CTYPE": "en_US.UTF-8"]
task.arguments = ["-c", command]
let pip = Pipe()
task.standardOutput = pip
let outHandle = pip.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var output = "";
NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandle, queue: nil) { notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = String(data: data, encoding: String.Encoding.utf8) as String? {
output += str
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
NotificationCenter.default.removeObserver(self)
}
}
NotificationCenter.default.addObserver(forName: Process.didTerminateNotification, object: task, queue: nil) { notification -> Void in
NotificationCenter.default.removeObserver(self)
}
task.launch()
task.waitUntilExit()
return output
}
// revise wrong json from you-get
private func revise(JSONString str: String) -> String {
if str.contains("163.com") {
return str.components(separatedBy: "\n").dropLast(2).reduce("", { $0 + $1 + "\n" })
}
return str
}
}
| e4bfc8d44ca1ece084eb56657878e505 | 27.808 | 159 | 0.551791 | 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 |
aschwaighofer/swift | refs/heads/master | test/expr/cast/set_bridge.swift | apache-2.0 | 9 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class Root : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(x: Root, y: Root) -> Bool { return true }
class ObjC : Root {
var x = 0
}
class DerivesObjC : ObjC { }
class Unrelated : Root { }
struct BridgedToObjC : Hashable, _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> ObjC {
return ObjC()
}
static func _forceBridgeFromObjectiveC(
_ x: ObjC,
result: inout BridgedToObjC?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ObjC,
result: inout BridgedToObjC?
) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
func ==(x: BridgedToObjC, y: BridgedToObjC) -> Bool { return true }
func testUpcastBridge() {
var setR = Set<Root>()
var setO = Set<ObjC>()
var setD = Set<DerivesObjC>()
var setB = Set<BridgedToObjC>()
// Upcast to object types.
setR = setB as Set<Root>; _ = setR
setO = setB as Set<ObjC>; _ = setO
// Upcast object to bridged type
setB = setO // expected-error{{cannot assign value of type 'Set<ObjC>' to type 'Set<BridgedToObjC>'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('ObjC' and 'BridgedToObjC') are expected to be equal}}
// Failed upcast
setD = setB // expected-error{{cannot assign value of type 'Set<BridgedToObjC>' to type 'Set<DerivesObjC>'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('BridgedToObjC' and 'DerivesObjC') are expected to be equal}}
}
func testForcedDowncastBridge() {
let setR = Set<Root>()
let setO = Set<ObjC>()
let setD = Set<DerivesObjC>()
let setB = Set<BridgedToObjC>()
_ = setR as! Set<BridgedToObjC>
_ = setO as Set<BridgedToObjC>
_ = setD as! Set<BridgedToObjC> // expected-warning{{forced cast from 'Set<DerivesObjC>' to 'Set<BridgedToObjC>' always succeeds; did you mean to use 'as'?}}
_ = setB as! Set<Root> // expected-warning{{forced cast from 'Set<BridgedToObjC>' to 'Set<Root>' always succeeds; did you mean to use 'as'?}}
_ = setB as! Set<ObjC> // expected-warning{{forced cast from 'Set<BridgedToObjC>' to 'Set<ObjC>' always succeeds; did you mean to use 'as'?}}
_ = setB as! Set<DerivesObjC>
}
func testConditionalDowncastBridge() {
let setR = Set<Root>()
let setO = Set<ObjC>()
let setD = Set<DerivesObjC>()
let setB = Set<BridgedToObjC>()
if let s = setR as? Set<BridgedToObjC> { _ = s }
let s1 = setO as Set<BridgedToObjC>
if let s = setD as? Set<BridgedToObjC> { _ = s } // expected-warning {{conditional cast from 'Set<DerivesObjC>' to 'Set<BridgedToObjC>' always succeeds}}
if let s = setB as? Set<Root> { _ = s } // expected-warning{{conditional cast from 'Set<BridgedToObjC>' to 'Set<Root>' always succeeds}}
if let s = setB as? Set<ObjC> { _ = s } // expected-warning{{conditional cast from 'Set<BridgedToObjC>' to 'Set<ObjC>' always succeeds}}
if let s = setB as? Set<DerivesObjC> { _ = s }
if let s = setB as? Set<Unrelated> { _ = s } // expected-warning {{cast from 'Set<BridgedToObjC>' to unrelated type 'Set<Unrelated>' always fails}}
_ = setR
_ = setO
_ = setD
_ = setB
_ = s1
}
| 025a93b47b8e38d4bc4812fc205d72cd | 30.87963 | 159 | 0.666279 | 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 |
IvanVorobei/Sparrow | refs/heads/master | sparrow/ui/views/views/SPAligmentView.swift | mit | 1 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPAligmentView: UIView {
var minSpace: CGFloat = 0
var maxItemSideSize: CGFloat?
var spaceFactor: CGFloat = 0.07
var aliment: Aliment
required init?(coder aDecoder: NSCoder) {
self.aliment = .vertical
super.init(coder: aDecoder)
}
init(aliment: Aliment) {
self.aliment = aliment
super.init(frame: CGRect.zero)
}
override func layoutSubviews() {
super.layoutSubviews()
let countViews: CGFloat = CGFloat(self.subviews.count)
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
var space: CGFloat = 0
switch self.aliment {
case .horizontal:
itemHeight = self.frame.height
space = self.frame.width * self.spaceFactor
if space < self.minSpace {
space = self.minSpace
}
let spaceForButton = self.frame.width - (space * (countViews - 1))
itemWidth = spaceForButton / countViews
if self.maxItemSideSize != nil {
if (itemWidth > self.maxItemSideSize!) {
itemWidth = self.maxItemSideSize!
if countViews > 1 {
space = (self.frame.width - (itemWidth * countViews)) / (countViews - 1)
} else {
space = 0
}
}
}
case .vertical:
itemWidth = self.frame.width
space = self.frame.height * self.spaceFactor
if space < self.minSpace {
space = self.minSpace
}
let spaceForButton = self.frame.height - (space * (countViews - 1))
itemHeight = spaceForButton / countViews
if self.maxItemSideSize != nil {
if (itemHeight > self.maxItemSideSize!) {
itemHeight = self.maxItemSideSize!
if countViews > 1 {
space = (self.frame.height - (itemHeight * countViews)) / (countViews - 1)
} else {
space = 0
}
}
}
}
var xPoint: CGFloat = 0
var yPoint: CGFloat = 0
for (index, view) in self.subviews.enumerated() {
switch self.aliment {
case .horizontal:
xPoint = CGFloat(index) * (itemWidth + space)
case .vertical:
yPoint = CGFloat(index) * (itemHeight + space)
}
view.frame = CGRect.init(
x: xPoint, y: yPoint,
width: itemWidth,
height: itemHeight
)
}
}
enum Aliment {
case vertical
case horizontal
}
}
class SPCenteringAligmentView: SPAligmentView {
override func layoutSubviews() {
super.layoutSubviews()
if self.subviews.count == 0 {
return
}
var itemHeight: CGFloat = self.subviews[0].frame.height
var itemWidth: CGFloat = self.subviews[0].frame.width
let countViews: CGFloat = CGFloat(self.subviews.count)
if countViews < 3 {
switch self.aliment {
case .horizontal:
switch self.subviews.count {
case 1:
self.subviews[0].center.x = self.frame.width / 2
case 2:
let allFreeSpace = self.frame.width - (itemWidth * countViews)
var space = allFreeSpace / 2
if space < self.minSpace {
space = self.minSpace
itemWidth = (self.frame.width - (space * 2)) / 2
}
self.subviews[0].frame = CGRect.init(x: space / 2, y: self.subviews[0].frame.origin.y, width: itemWidth, height: self.subviews[0].frame.height)
self.subviews[1].frame = CGRect.init(x: space / 2 + itemWidth + space, y: self.subviews[1].frame.origin.y, width: itemWidth, height: self.subviews[1].frame.height)
default:
break
}
case .vertical:
switch self.subviews.count {
case 1:
self.subviews[0].center.y = self.frame.height / 2
case 2:
let allFreeSpace = self.frame.height - (itemHeight * countViews)
var space = allFreeSpace / 2
if space < self.minSpace {
space = self.minSpace
itemHeight = (self.frame.height - (space * 2)) / 2
}
self.subviews[0].frame = CGRect.init(x: self.subviews[0].frame.origin.x, y: space / 2, width: self.subviews[0].frame.width, height: itemHeight)
self.subviews[1].frame = CGRect.init(x: self.subviews[1].frame.origin.x, y: (space / 2) + itemHeight + space, width: self.subviews[1].frame.width, height: itemHeight)
default:
break
}
}
}
}
}
class SPDinamicAligmentView: UIView {
var aliment: Aliment
var itemSideSize: CGFloat = 50
var space: CGFloat = 10
var needSize: CGSize {
get {
self.layoutSubviews()
switch aliment {
case .horizontal:
return CGSize.init(width: ((self.subviews.last?.frame.origin.x) ?? 0) + ((self.subviews.last?.frame.width) ?? 0), height: (self.subviews.last?.frame.height) ?? 0)
case .vertical:
return CGSize.init(width: (self.subviews.last?.frame.width) ?? 0, height: (self.subviews.last?.frame.bottomYPosition) ?? 0)
}
}
}
required init?(coder aDecoder: NSCoder) {
self.aliment = .vertical
super.init(coder: aDecoder)
}
init(aliment: Aliment) {
self.aliment = aliment
super.init(frame: CGRect.zero)
}
override func layoutSubviews() {
super.layoutSubviews()
var xPoint: CGFloat = 0
var yPoint: CGFloat = 0
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
for (index, view) in self.subviews.enumerated() {
switch self.aliment {
case .horizontal:
xPoint = CGFloat(index) * (self.itemSideSize + space)
itemWidth = self.itemSideSize
itemHeight = self.frame.height
case .vertical:
yPoint = CGFloat(index) * (self.itemSideSize + space)
itemWidth = self.frame.width
itemHeight = self.itemSideSize
}
view.frame = CGRect.init(
x: xPoint, y: yPoint,
width: itemWidth,
height: itemHeight
)
}
var needSideSize: CGFloat = 0
let lastView = self.subviews.last
if lastView != nil {
switch self.aliment {
case .horizontal:
needSideSize = lastView!.frame.origin.x + lastView!.frame.width
self.setWidth(needSideSize)
break
case .vertical:
needSideSize = lastView!.frame.origin.y + lastView!.frame.height
self.setHeight(needSideSize)
break
}
}
}
enum Aliment {
case vertical
case horizontal
}
}
| c7529be7020d5a98507cbb4d308a46f2 | 35.606695 | 186 | 0.536633 | false | false | false | false |
cfraz89/RxSwift | refs/heads/master | Tests/Microoptimizations/PerformanceTools.swift | mit | 1 | //
// PerformanceTools.swift
// Tests
//
// Created by Krunoslav Zaher on 9/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if os(Linux)
import Dispatch
#endif
fileprivate var mallocFunctions: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = []
fileprivate var allocCalls: Int64 = 0
fileprivate var bytesAllocated: Int64 = 0
func call0(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[0](p, size)
}
func call1(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[1](p, size)
}
func call2(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[2](p, size)
}
var proxies: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = [call0, call1, call2]
func getMemoryInfo() -> (bytes: Int64, allocations: Int64) {
return (bytesAllocated, allocCalls)
}
fileprivate var registeredMallocHooks = false
func registerMallocHooks() {
if registeredMallocHooks {
return
}
registeredMallocHooks = true
var _zones: UnsafeMutablePointer<vm_address_t>?
var count: UInt32 = 0
// malloc_zone_print(nil, 1)
let res = malloc_get_all_zones(mach_task_self_, nil, &_zones, &count)
assert(res == 0)
_zones?.withMemoryRebound(to: UnsafeMutablePointer<malloc_zone_t>.self, capacity: Int(count), { zones in
assert(Int(count) <= proxies.count)
for i in 0 ..< Int(count) {
let zoneArray = zones.advanced(by: i)
let name = malloc_get_zone_name(zoneArray.pointee)
var zone = zoneArray.pointee.pointee
//print(String.fromCString(name))
assert(name != nil)
mallocFunctions.append(zone.malloc)
zone.malloc = proxies[i]
let protectSize = vm_size_t(MemoryLayout<malloc_zone_t>.size) * vm_size_t(count)
if true {
zoneArray.withMemoryRebound(to: vm_address_t.self, capacity: Int(protectSize), { addressPointer in
let res = vm_protect(mach_task_self_, addressPointer.pointee, protectSize, 0, PROT_READ | PROT_WRITE)
assert(res == 0)
})
}
zoneArray.pointee.pointee = zone
if true {
let res = vm_protect(mach_task_self_, _zones!.pointee, protectSize, 0, PROT_READ)
assert(res == 0)
}
}
})
}
// MARK: Benchmark tools
let NumberOfIterations = 10000
final class A {
let _0 = 0
let _1 = 0
let _2 = 0
let _3 = 0
let _4 = 0
let _5 = 0
let _6 = 0
}
final class B {
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
}
let numberOfObjects = 1000000
let aliveAtTheEnd = numberOfObjects / 10
fileprivate var objects: [AnyObject] = []
func fragmentMemory() {
objects = [AnyObject](repeating: A(), count: aliveAtTheEnd)
for _ in 0 ..< numberOfObjects {
objects[Int(arc4random_uniform(UInt32(aliveAtTheEnd)))] = arc4random_uniform(2) == 0 ? A() : B()
}
}
func approxValuePerIteration(_ total: Int) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func approxValuePerIteration(_ total: UInt64) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func measureTime(_ work: () -> ()) -> UInt64 {
var timebaseInfo: mach_timebase_info = mach_timebase_info()
let res = mach_timebase_info(&timebaseInfo)
assert(res == 0)
let start = mach_absolute_time()
for _ in 0 ..< NumberOfIterations {
work()
}
let timeInNano = (mach_absolute_time() - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom)
return approxValuePerIteration(timeInNano) / 1000
}
func measureMemoryUsage(work: () -> ()) -> (bytesAllocated: UInt64, allocations: UInt64) {
let (bytes, allocations) = getMemoryInfo()
for _ in 0 ..< NumberOfIterations {
work()
}
let (bytesAfter, allocationsAfter) = getMemoryInfo()
return (approxValuePerIteration(bytesAfter - bytes), approxValuePerIteration(allocationsAfter - allocations))
}
fileprivate var fragmentedMemory = false
func compareTwoImplementations(benchmarkTime: Bool, benchmarkMemory: Bool, first: () -> (), second: () -> ()) {
if !fragmentedMemory {
print("Fragmenting memory ...")
fragmentMemory()
print("Benchmarking ...")
fragmentedMemory = true
}
// first warm up to keep it fair
let time1: UInt64
let time2: UInt64
if benchmarkTime {
first()
second()
time1 = measureTime(first)
time2 = measureTime(second)
}
else {
time1 = 0
time2 = 0
}
let memory1: (bytesAllocated: UInt64, allocations: UInt64)
let memory2: (bytesAllocated: UInt64, allocations: UInt64)
if benchmarkMemory {
registerMallocHooks()
first()
second()
memory1 = measureMemoryUsage(work: first)
memory2 = measureMemoryUsage(work: second)
}
else {
memory1 = (0, 0)
memory2 = (0, 0)
}
// this is good enough
print(String(format: "#1 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory1.bytesAllocated,
memory1.allocations,
time1
]))
print(String(format: "#2 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory2.bytesAllocated,
memory2.allocations,
time2
]))
}
| c2606a4957acf4499c53b14c2a3ec3c4 | 27.171946 | 129 | 0.629296 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/SizeThatFitsView.swift | mit | 1 | import UIKit
// SizeThatFitsView is the base class of views that use manual layout.
// These views use a manual layout rather than auto layout for convienence within a CollectionViewCell
@objc(WMFSizeThatFitsView)
open class SizeThatFitsView: SetupView {
// MARK - Methods for subclassing
// Subclassers should override setup instead of any of the initializers. Subclassers must call super.setup()
override open func setup() {
super.setup()
translatesAutoresizingMaskIntoConstraints = false
autoresizesSubviews = false
setNeedsLayout()
}
// Subclassers should override sizeThatFits:apply: instead of layoutSubviews to lay out subviews.
// In this method, subclassers should calculate the appropriate layout size and if apply is `true`,
// apply the layout to the subviews.
open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
return size
}
// Subclassers should override updateAccessibilityElements to update any accessibility elements
// that should be updated after layout. Subclassers must call super.updateAccessibilityElements()
open func updateAccessibilityElements() {
}
// MARK - Layout
final override public func layoutSubviews() {
super.layoutSubviews()
let size = bounds.size
let _ = sizeThatFits(size, apply: true)
updateAccessibilityElements()
#if DEBUG
for view in subviews {
assert(view.autoresizingMask == [])
assert(view.constraints == [])
}
#endif
}
final override public func sizeThatFits(_ size: CGSize) -> CGSize {
return sizeThatFits(size, apply: false)
}
}
| f5d6b568a8dec67cdece095813acab7e | 34.836735 | 112 | 0.669134 | 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 |
StormXX/RefreshView | refs/heads/master | RefreshView/CustomRefreshHeaderView.swift | mit | 1 | //
// RefreshView.swift
// RefreshDemo
//
// Created by ZouLiangming on 16/1/28.
// Copyright © 2016年 ZouLiangming. All rights reserved.
//
import UIKit
open class CustomRefreshHeaderView: CustomRefreshView {
fileprivate var customBackgroundColor = UIColor.clear
fileprivate var circleLayer: CAShapeLayer?
fileprivate let angle: CGFloat = 0
var state: RefreshState? {
willSet {
willSetRefreshState(newValue)
}
didSet {
didSetRefreshState()
}
}
lazy var logoImageView: UIImageView? = {
var image = UIImage()
if let logoImage = CustomLogoManager.shared.logoImage {
image = logoImage
} else {
image = self.getImage(of: CustomLogoManager.shared.logoName)
}
let imageView = UIImageView(image: image)
self.addSubview(imageView)
return imageView
}()
lazy var circleImageView: UIImageView? = {
let image = self.getImage(of: "loading_circle")
let imageView = UIImageView(image: image)
self.addSubview(imageView)
return imageView
}()
fileprivate func willSetRefreshState(_ newValue: RefreshState?) {
if newValue == .idle {
if state != .refreshing {
return
}
UIView.animate(withDuration: kCustomRefreshSlowAnimationTime, animations: {
self.scrollView?.insetTop += self.insetTDelta
self.pullingPercent = 0.0
self.alpha = 0.0
}, completion: { (_) -> Void in
self.circleImageView?.layer.removeAnimation(forKey: kCustomRefreshAnimationKey)
self.circleImageView?.isHidden = true
self.circleLayer?.isHidden = false
})
}
}
fileprivate func didSetRefreshState() {
if state == .refreshing {
UIView.animate(withDuration: kCustomRefreshFastAnimationTime, animations: {
let top = (self.scrollViewOriginalInset?.top)! + self.sizeHeight
self.scrollView?.insetTop = top
self.scrollView?.offsetY = -top
}, completion: { (_) -> Void in
self.circleImageView?.isHidden = false
self.circleLayer?.isHidden = true
self.startAnimation()
self.executeRefreshingCallback()
})
}
}
fileprivate func getImage(of name: String) -> UIImage {
let traitCollection = UITraitCollection(displayScale: 3)
let bundle = Bundle(for: classForCoder)
let image = UIImage(named: name, in: bundle, compatibleWith: traitCollection)
guard let newImage = image else {
return UIImage()
}
return newImage
}
fileprivate func initCircleLayer() {
if circleLayer == nil {
circleLayer = CAShapeLayer()
}
circleLayer?.shouldRasterize = false
circleLayer?.contentsScale = UIScreen.main.scale
layer.addSublayer(circleLayer!)
}
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
state = .idle
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func layoutSubviews() {
super.layoutSubviews()
placeSubviews()
}
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if let newScrollView = newSuperview as? UIScrollView {
removeObservers()
sizeWidth = newScrollView.sizeWidth
originX = 0
scrollView = newScrollView
scrollView?.alwaysBounceVertical = true
scrollViewOriginalInset = scrollView?.contentInset
originInset = scrollView?.contentInset
addObservers()
}
if newSuperview == nil {
removeObservers()
}
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
if state == .willRefresh {
state = .refreshing
}
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if !isUserInteractionEnabled || isHidden {
return
}
if keyPath == kRefreshKeyPathContentOffset {
scrollViewContentOffsetDidChange(change)
}
}
fileprivate func executeRefreshingCallback() {
if let newStart = start {
newStart()
}
}
fileprivate func changeCircleLayer(to value: CGFloat) {
let startAngle = kPai/2
let endAngle = kPai/2+2*kPai*CGFloat(value)
let ovalRect = CGRect(x: round(sizeWidth/2-6), y: 26, width: 12, height: 12)
let x = ovalRect.midX
let y = ovalRect.midY
let point = CGPoint(x: x, y: y)
let radius = ovalRect.width
let ovalPath = UIBezierPath(arcCenter: point, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
circleLayer?.path = ovalPath.cgPath
circleLayer?.strokeColor = UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1).cgColor
circleLayer?.fillColor = nil
circleLayer?.lineWidth = 2
circleLayer?.lineCap = kCALineCapRound
}
open func autoBeginRefreshing() {
if state == .idle {
let offsetY = -scrollViewOriginalInset!.top - kRefreshNotCircleHeight + 14
self.scrollView?.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
state = .pulling
beginRefreshing()
}
}
fileprivate func scrollViewContentOffsetDidChange(_ change: [NSKeyValueChangeKey : Any]?) {
if state == .refreshing {
if window != nil {
var insetT = -scrollView!.offsetY > scrollViewOriginalInset!.top ? -scrollView!.offsetY : scrollViewOriginalInset!.top
insetT = insetT > sizeHeight + scrollViewOriginalInset!.top ? sizeHeight + scrollViewOriginalInset!.top : insetT
scrollView?.insetTop = insetT
insetTDelta = scrollViewOriginalInset!.top - insetT
return
} else {
return
}
}
scrollViewOriginalInset = scrollView?.contentInset
let offsetY = scrollView!.offsetY
let happenOffsetY = -scrollViewOriginalInset!.top
let realOffsetY = happenOffsetY - offsetY - kRefreshNotCircleHeight
if realOffsetY > 0 {
if state != .pulling {
let value = realOffsetY / (kRefreshHeaderHeight - 20)
if value < 1 {
changeCircleLayer(to: value)
} else {
changeCircleLayer(to: 1)
}
} else {
changeCircleLayer(to: 1)
}
}
if offsetY > happenOffsetY {
return
}
let currentPullingPercent = (happenOffsetY - offsetY) / (sizeHeight - 5)
alpha = currentPullingPercent * 0.8
if scrollView!.isDragging {
pullingPercent = currentPullingPercent
if pullingPercent >= 1 {
state = .pulling
} else {
state = .idle
}
} else if state == .pulling {
beginRefreshing()
} else if pullingPercent < 1 {
pullingPercent = currentPullingPercent
}
}
open class func headerWithRefreshingBlock(_ customBackgroundColor: UIColor = UIColor.clear, startLoading: @escaping () -> Void) -> CustomRefreshHeaderView {
let header = self.init()
header.start = startLoading
header.customBackgroundColor = customBackgroundColor
return header
}
fileprivate func startAnimation() {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = -angle
rotateAnimation.toValue = -angle + CGFloat.pi * 2.0
rotateAnimation.duration = 1
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
circleImageView?.layer.add(rotateAnimation, forKey: kCustomRefreshAnimationKey)
}
fileprivate func addObservers() {
let options = NSKeyValueObservingOptions([.new, .old])
scrollView?.addObserver(self, forKeyPath: kRefreshKeyPathContentOffset, options: options, context: nil)
}
fileprivate func removeObservers() {
superview?.removeObserver(self, forKeyPath: kRefreshKeyPathContentOffset)
}
fileprivate func placeSubviews() {
if customBackgroundColor != UIColor.clear {
backgroundColor = customBackgroundColor
} else {
backgroundColor = scrollView?.backgroundColor
}
logoImageView?.center = CGPoint(x: sizeWidth/2, y: 32)
circleImageView?.center = CGPoint(x: sizeWidth/2, y: 32)
circleImageView?.isHidden = true
initCircleLayer()
originY = -sizeHeight
}
fileprivate func prepare() {
autoresizingMask = .flexibleWidth
sizeHeight = kRefreshHeaderHeight
}
fileprivate func beginRefreshing() {
UIView.animate(withDuration: kCustomRefreshFastAnimationTime, animations: { () -> Void in
self.alpha = 1.0
})
pullingPercent = 1.0
if window != nil {
state = .refreshing
} else {
if state != .refreshing {
state = .refreshing
setNeedsDisplay()
}
}
}
open func endRefreshing() {
state = .idle
}
func isRefreshing() -> Bool {
return state == .refreshing || state == .willRefresh
}
}
| ffcbd32954a96914a4ecdafb5c428dee | 31.831683 | 160 | 0.593788 | 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 |
arietis/codility-swift | refs/heads/master | 6.4.swift | mit | 1 | public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2
let N = A.count
if N < 2 {
return 0
}
var discStart: [Int] = Array(count: N, repeatedValue: 0)
var discEnd: [Int] = Array(count: N, repeatedValue: 0)
for i in 0..<N {
discStart[max(0, i - A[i])] += 1
if i + A[i] < 0 {
discEnd[N - 1] += 1
} else {
discEnd[min(N - 1, i + A[i])] += 1
}
}
var n = 0
var result = 0
for i in 0..<N {
if discStart[i] > 0 {
result += n * discStart[i]
result += discStart[i] * (discStart[i] - 1) / 2
if result > 10000000 {
return -1
}
n += discStart[i]
}
if discEnd[i] > 0 {
n -= discEnd[i]
}
}
return result
}
| 20546b56585b97d5f027bae4d7fea423 | 18.711111 | 60 | 0.404735 | false | false | false | false |
JakeLin/SwiftWeather | refs/heads/master | SwiftWeather/WeatherIcon.swift | mit | 2 | //
// Created by Jake Lin on 9/9/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import Foundation
/*
`WeatherIcon` is used to map Open Weather Map icon string to Weather Icons unicode string.
It is generated by
```
var caseString = '';
var caseAndReturnString = '';
Array.prototype.forEach.call(document.styleSheets[1].cssRules,function(element){
if (element.selectorText && element.selectorText.startsWith('.wi-owm')) {
var caseName = element.selectorText.substring(8,
element.selectorText.indexOf('::before')).replace('-', '')
caseString += 'case ' + caseName + ' = "' + caseName + '"\n';
caseAndReturnString += 'case .' + caseName + ': return "\\u{'
+ element.style['content'].charCodeAt(1).toString(16) + '}"\n'
}
});
console.log(caseString);
console.log(caseAndReturnString);
```
*/
// swiftlint:disable type_body_length
struct WeatherIcon {
let iconText: String
enum IconType: String, CustomStringConvertible {
case day200 = "day200"
case day201 = "day201"
case day202 = "day202"
case day210 = "day210"
case day211 = "day211"
case day212 = "day212"
case day221 = "day221"
case day230 = "day230"
case day231 = "day231"
case day232 = "day232"
case day300 = "day300"
case day301 = "day301"
case day302 = "day302"
case day310 = "day310"
case day311 = "day311"
case day312 = "day312"
case day313 = "day313"
case day314 = "day314"
case day321 = "day321"
case day500 = "day500"
case day501 = "day501"
case day502 = "day502"
case day503 = "day503"
case day504 = "day504"
case day511 = "day511"
case day520 = "day520"
case day521 = "day521"
case day522 = "day522"
case day531 = "day531"
case day600 = "day600"
case day601 = "day601"
case day602 = "day602"
case day611 = "day611"
case day612 = "day612"
case day615 = "day615"
case day616 = "day616"
case day620 = "day620"
case day621 = "day621"
case day622 = "day622"
case day701 = "day701"
case day711 = "day711"
case day721 = "day721"
case day731 = "day731"
case day741 = "day741"
case day761 = "day761"
case day762 = "day762"
case day781 = "day781"
case day800 = "day800"
case day801 = "day801"
case day802 = "day802"
case day803 = "day803"
case day804 = "day804"
case day900 = "day900"
case day902 = "day902"
case day903 = "day903"
case day904 = "day904"
case day906 = "day906"
case day957 = "day957"
case night200 = "night200"
case night201 = "night201"
case night202 = "night202"
case night210 = "night210"
case night211 = "night211"
case night212 = "night212"
case night221 = "night221"
case night230 = "night230"
case night231 = "night231"
case night232 = "night232"
case night300 = "night300"
case night301 = "night301"
case night302 = "night302"
case night310 = "night310"
case night311 = "night311"
case night312 = "night312"
case night313 = "night313"
case night314 = "night314"
case night321 = "night321"
case night500 = "night500"
case night501 = "night501"
case night502 = "night502"
case night503 = "night503"
case night504 = "night504"
case night511 = "night511"
case night520 = "night520"
case night521 = "night521"
case night522 = "night522"
case night531 = "night531"
case night600 = "night600"
case night601 = "night601"
case night602 = "night602"
case night611 = "night611"
case night612 = "night612"
case night615 = "night615"
case night616 = "night616"
case night620 = "night620"
case night621 = "night621"
case night622 = "night622"
case night701 = "night701"
case night711 = "night711"
case night721 = "night721"
case night731 = "night731"
case night741 = "night741"
case night761 = "night761"
case night762 = "night762"
case night781 = "night781"
case night800 = "night800"
case night801 = "night801"
case night802 = "night802"
case night803 = "night803"
case night804 = "night804"
case night900 = "night900"
case night902 = "night902"
case night903 = "night903"
case night904 = "night904"
case night906 = "night906"
case night957 = "night957"
var description: String {
switch self {
case .day200: return "\u{f010}"
case .day201: return "\u{f010}"
case .day202: return "\u{f010}"
case .day210: return "\u{f005}"
case .day211: return "\u{f005}"
case .day212: return "\u{f005}"
case .day221: return "\u{f005}"
case .day230: return "\u{f010}"
case .day231: return "\u{f010}"
case .day232: return "\u{f010}"
case .day300: return "\u{f00b}"
case .day301: return "\u{f00b}"
case .day302: return "\u{f008}"
case .day310: return "\u{f008}"
case .day311: return "\u{f008}"
case .day312: return "\u{f008}"
case .day313: return "\u{f008}"
case .day314: return "\u{f008}"
case .day321: return "\u{f00b}"
case .day500: return "\u{f00b}"
case .day501: return "\u{f008}"
case .day502: return "\u{f008}"
case .day503: return "\u{f008}"
case .day504: return "\u{f008}"
case .day511: return "\u{f006}"
case .day520: return "\u{f009}"
case .day521: return "\u{f009}"
case .day522: return "\u{f009}"
case .day531: return "\u{f00e}"
case .day600: return "\u{f00a}"
case .day601: return "\u{f0b2}"
case .day602: return "\u{f00a}"
case .day611: return "\u{f006}"
case .day612: return "\u{f006}"
case .day615: return "\u{f006}"
case .day616: return "\u{f006}"
case .day620: return "\u{f006}"
case .day621: return "\u{f00a}"
case .day622: return "\u{f00a}"
case .day701: return "\u{f009}"
case .day711: return "\u{f062}"
case .day721: return "\u{f0b6}"
case .day731: return "\u{f063}"
case .day741: return "\u{f003}"
case .day761: return "\u{f063}"
case .day762: return "\u{f063}"
case .day781: return "\u{f056}"
case .day800: return "\u{f00d}"
case .day801: return "\u{f000}"
case .day802: return "\u{f000}"
case .day803: return "\u{f000}"
case .day804: return "\u{f00c}"
case .day900: return "\u{f056}"
case .day902: return "\u{f073}"
case .day903: return "\u{f076}"
case .day904: return "\u{f072}"
case .day906: return "\u{f004}"
case .day957: return "\u{f050}"
case .night200: return "\u{f02d}"
case .night201: return "\u{f02d}"
case .night202: return "\u{f02d}"
case .night210: return "\u{f025}"
case .night211: return "\u{f025}"
case .night212: return "\u{f025}"
case .night221: return "\u{f025}"
case .night230: return "\u{f02d}"
case .night231: return "\u{f02d}"
case .night232: return "\u{f02d}"
case .night300: return "\u{f02b}"
case .night301: return "\u{f02b}"
case .night302: return "\u{f028}"
case .night310: return "\u{f028}"
case .night311: return "\u{f028}"
case .night312: return "\u{f028}"
case .night313: return "\u{f028}"
case .night314: return "\u{f028}"
case .night321: return "\u{f02b}"
case .night500: return "\u{f02b}"
case .night501: return "\u{f028}"
case .night502: return "\u{f028}"
case .night503: return "\u{f028}"
case .night504: return "\u{f028}"
case .night511: return "\u{f026}"
case .night520: return "\u{f029}"
case .night521: return "\u{f029}"
case .night522: return "\u{f029}"
case .night531: return "\u{f02c}"
case .night600: return "\u{f02a}"
case .night601: return "\u{f0b4}"
case .night602: return "\u{f02a}"
case .night611: return "\u{f026}"
case .night612: return "\u{f026}"
case .night615: return "\u{f026}"
case .night616: return "\u{f026}"
case .night620: return "\u{f026}"
case .night621: return "\u{f02a}"
case .night622: return "\u{f02a}"
case .night701: return "\u{f029}"
case .night711: return "\u{f062}"
case .night721: return "\u{f0b6}"
case .night731: return "\u{f063}"
case .night741: return "\u{f04a}"
case .night761: return "\u{f063}"
case .night762: return "\u{f063}"
case .night781: return "\u{f056}"
case .night800: return "\u{f02e}"
case .night801: return "\u{f022}"
case .night802: return "\u{f022}"
case .night803: return "\u{f022}"
case .night804: return "\u{f086}"
case .night900: return "\u{f056}"
case .night902: return "\u{f073}"
case .night903: return "\u{f076}"
case .night904: return "\u{f072}"
case .night906: return "\u{f024}"
case .night957: return "\u{f050}"
}
}
}
init(condition: Int, iconString: String) {
var rawValue: String
// if iconString has 'n', it means night time.
if iconString.range(of: "n") != nil {
rawValue = "night" + String(condition)
} else {
// day time
rawValue = "day" + String(condition)
}
guard let iconType = IconType(rawValue: rawValue) else {
iconText = ""
return
}
iconText = iconType.description
}
}
// swiftlint:enable type_body_length
| 29531d4b15685a4674d4219bf9817e6d | 31.657439 | 92 | 0.595147 | false | false | false | false |
frootloops/swift | refs/heads/master | stdlib/public/core/SetAlgebra.swift | apache-2.0 | 1 | //===--- SetAlgebra.swift - Protocols for set operations ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//
//
//===----------------------------------------------------------------------===//
/// A type that provides mathematical set operations.
///
/// You use types that conform to the `SetAlgebra` protocol when you need
/// efficient membership tests or mathematical set operations such as
/// intersection, union, and subtraction. In the standard library, you can
/// use the `Set` type with elements of any hashable type, or you can easily
/// create bit masks with `SetAlgebra` conformance using the `OptionSet`
/// protocol. See those types for more information.
///
/// - Note: Unlike ordinary set types, the `Element` type of an `OptionSet` is
/// identical to the `OptionSet` type itself. The `SetAlgebra` protocol is
/// specifically designed to accommodate both kinds of set.
///
/// Conforming to the SetAlgebra Protocol
/// =====================================
///
/// When implementing a custom type that conforms to the `SetAlgebra` protocol,
/// you must implement the required initializers and methods. For the
/// inherited methods to work properly, conforming types must meet the
/// following axioms. Assume that `S` is a custom type that conforms to the
/// `SetAlgebra` protocol, `x` and `y` are instances of `S`, and `e` is of
/// type `S.Element`---the type that the set holds.
///
/// - `S() == []`
/// - `x.intersection(x) == x`
/// - `x.intersection([]) == []`
/// - `x.union(x) == x`
/// - `x.union([]) == x`
/// - `x.contains(e)` implies `x.union(y).contains(e)`
/// - `x.union(y).contains(e)` implies `x.contains(e) || y.contains(e)`
/// - `x.contains(e) && y.contains(e)` if and only if
/// `x.intersection(y).contains(e)`
/// - `x.isSubset(of: y)` if and only if `y.isSuperset(of: x)`
/// - `x.isStrictSuperset(of: y)` if and only if
/// `x.isSuperset(of: y) && x != y`
/// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y`
public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral {
/// A type for which the conforming type provides a containment test.
associatedtype Element
/// Creates an empty set.
///
/// This initializer is equivalent to initializing with an empty array
/// literal. For example, you create an empty `Set` instance with either
/// this initializer or with an empty array literal.
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
init()
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
func contains(_ member: Element) -> Bool
/// Returns a new set with the elements of both this and the given set.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` and `visitors` sets:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set with the unique elements of this set and `other`.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func union(_ other: Self) -> Self
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func intersection(_ other: Self) -> Self
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func symmetricDifference(_ other: Self) -> Self
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In this example, a new element is inserted into
/// `classDays`, a set of days of the week. When an existing element is
/// inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
@discardableResult
mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element)
/// Removes the given element and any elements subsumed by the given element.
///
/// - Parameter member: The element of the set to remove.
/// - Returns: For ordinary sets, an element equal to `member` if `member` is
/// contained in the set; otherwise, `nil`. In some cases, a returned
/// element may be distinguishable from `newMember` by identity comparison
/// or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the set
/// and `[member]`, or `nil` if the intersection is empty.
@discardableResult
mutating func remove(_ member: Element) -> Element?
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: For ordinary sets, an element equal to `newMember` if the set
/// already contained such a member; otherwise, `nil`. In some cases, the
/// returned element may be distinguishable from `newMember` by identity
/// comparison or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the
/// set and `[newMember]`, or `nil` if the intersection is empty.
@discardableResult
mutating func update(with newMember: Element) -> Element?
/// Adds the elements of the given set to the set.
///
/// In the following example, the elements of the `visitors` set are added to
/// the `attendees` set:
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors: Set = ["Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// var initialIndices = Set(0..<5)
/// initialIndices.formUnion([2, 3, 6, 7])
/// print(initialIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formUnion(_ other: Self)
/// Removes the elements of this set that aren't also in the given set.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formIntersection(_ other: Self)
/// Removes the elements of the set that are also in the given set and adds
/// the members of the given set that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Bethany"` and `"Eric"` are
/// removed from `employees` while the name `"Forlani"` is added.
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type.
mutating func formSymmetricDifference(_ other: Self)
//===--- Requirements with default implementations ----------------------===//
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func subtracting(_ other: Self) -> Self
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
func isSubset(of other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
func isDisjoint(with other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
func isSuperset(of other: Self) -> Bool
/// A Boolean value that indicates whether the set has no elements.
var isEmpty: Bool { get }
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
init<S : Sequence>(_ sequence: S) where S.Element == Element
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func subtract(_ other: Self)
}
/// `SetAlgebra` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `SetAlgebra` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension SetAlgebra {
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
@_inlineable // FIXME(sil-serialize-all)
public init<S : Sequence>(_ sequence: S)
where S.Element == Element {
self.init()
for e in sequence { insert(e) }
}
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
@_inlineable // FIXME(sil-serialize-all)
public mutating func subtract(_ other: Self) {
self.formIntersection(self.symmetricDifference(other))
}
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
@_inlineable // FIXME(sil-serialize-all)
public func isSubset(of other: Self) -> Bool {
return self.intersection(other) == self
}
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public func isSuperset(of other: Self) -> Bool {
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@_inlineable // FIXME(sil-serialize-all)
public func isDisjoint(with other: Self) -> Bool {
return self.intersection(other).isEmpty
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtract(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
@_inlineable // FIXME(sil-serialize-all)
public func subtracting(_ other: Self) -> Self {
return self.intersection(self.symmetricDifference(other))
}
/// A Boolean value that indicates whether the set has no elements.
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return self == Self()
}
/// Returns a Boolean value that indicates whether this set is a strict
/// superset of the given set.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
///
/// // A set is never a strict superset of itself:
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict superset of `other`; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public func isStrictSuperset(of other: Self) -> Bool {
return self.isSuperset(of: other) && self != other
}
/// Returns a Boolean value that indicates whether this set is a strict
/// subset of the given set.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict subset of `other`; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public func isStrictSubset(of other: Self) -> Bool {
return other.isStrictSuperset(of: self)
}
}
extension SetAlgebra where Element == ArrayLiteralElement {
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings:
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter arrayLiteral: A list of elements of the new set.
@_inlineable // FIXME(sil-serialize-all)
public init(arrayLiteral: Element...) {
self.init(arrayLiteral)
}
}
| e522b82363726f4125506111a034c3cb | 41.602763 | 83 | 0.620384 | 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 |
wesj/firefox-ios-1 | refs/heads/master | ClientTests/TestHistory.swift | mpl-2.0 | 1 | import Foundation
import XCTest
import Storage
class TestHistory : ProfileTest {
private func innerAddSite(history: History, url: String, title: String, callback: (success: Bool) -> Void) {
// Add an entry
let site = Site(url: url, title: title)
let visit = Visit(site: site, date: NSDate())
history.addVisit(visit) { success in
callback(success: success)
}
}
private func addSite(history: History, url: String, title: String, s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
innerAddSite(history, url: url, title: title) { success in
XCTAssertEqual(success, s, "Site added \(url)")
expectation.fulfill()
}
}
private func innerCheckSites(history: History, callback: (cursor: Cursor) -> Void) {
// Retrieve the entry
history.get(nil, complete: { cursor in
callback(cursor: cursor)
})
}
private func checkSites(history: History, urls: [String: String], s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
// Retrieve the entry
innerCheckSites(history) { cursor in
XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)")
XCTAssertEqual(cursor.count, urls.count, "cursor has \(urls.count) entries")
for index in 0..<cursor.count {
let s = cursor[index] as Site
XCTAssertNotNil(s, "cursor has a site for entry")
let title = urls[s.url]
XCTAssertNotNil(title, "Found right url")
XCTAssertEqual(s.title, title!, "Found right title")
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
private func innerClear(history: History, callback: (s: Bool) -> Void) {
history.clear({ success in
callback(s: success)
})
}
private func clear(history: History, s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
innerClear(history) { success in
XCTAssertEqual(s, success, "Sites cleared")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
private func checkVisits(history: History, url: String) {
let expectation = self.expectationWithDescription("Wait for history")
history.get(nil) { cursor in
let options = QueryOptions()
options.filter = url
history.get(options) { cursor in
XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)")
// XXX - We don't allow querying much info about visits here anymore, so there isn't a lot to do
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
// This is a very basic test. Adds an entry. Retrieves it, and then clears the database
func testHistory() {
withTestProfile { profile -> Void in
let h = profile.history
self.addSite(h, url: "url1", title: "title")
self.addSite(h, url: "url1", title: "title")
self.addSite(h, url: "url1", title: "title 2")
self.addSite(h, url: "url2", title: "title")
self.addSite(h, url: "url2", title: "title")
self.checkSites(h, urls: ["url1": "title 2", "url2": "title"])
self.checkVisits(h, url: "url1")
self.checkVisits(h, url: "url2")
self.clear(h)
}
}
func testAboutUrls() {
withTestProfile { (profile) -> Void in
let h = profile.history
self.addSite(h, url: "about:home", title: "About Home", s: false)
self.clear(h)
}
}
let NumThreads = 5
let NumCmds = 10
func testInsertPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
self.measureBlock({ () -> Void in
for i in 0...self.NumCmds {
self.addSite(h, url: "url \(j)", title: "title \(j)")
j++
}
self.clear(h)
})
}
}
func testGetPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
var urls = [String: String]()
self.clear(h)
for i in 0...self.NumCmds {
self.addSite(h, url: "url \(j)", title: "title \(j)")
urls["url \(j)"] = "title \(j)"
j++
}
self.measureBlock({ () -> Void in
self.checkSites(h, urls: urls)
return
})
self.clear(h)
}
}
// Fuzzing tests. These fire random insert/query/clear commands into the history database from threads. The don't check
// the results. Just look for crashes.
func testRandomThreading() {
withTestProfile { profile -> Void in
var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var done = [Bool]()
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for i in 0..<self.NumThreads {
var history = profile.history
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Same as testRandomThreading, but uses one history connection for all threads
func testRandomThreading2() {
withTestProfile { profile -> Void in
var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var history = profile.history
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for i in 0..<self.NumThreads {
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Runs a random command on a database. Calls cb when finished
private func runRandom(inout history: History, cmdIn: Int, cb: () -> Void) {
var cmd = cmdIn
if cmd < 0 {
cmd = Int(rand() % 5)
}
switch cmd {
case 0...1:
let url = "url \(rand() % 100)"
let title = "title \(rand() % 100)"
innerAddSite(history, url: url, title: title) { success in cb() }
case 2...3:
innerCheckSites(history) { cursor in
for site in cursor {
let s = site as Site
}
}
cb()
default:
innerClear(history) { success in cb() }
}
}
// Calls numCmds random methods on this database. val is a counter used by this interally (i.e. always pass zero for it)
// Calls cb when finished
private func runMultiRandom(inout history: History, val: Int, numCmds: Int, cb: () -> Void) {
if val == numCmds {
cb()
return
} else {
runRandom(&history, cmdIn: -1) { _ in
self.runMultiRandom(&history, val: val+1, numCmds: numCmds, cb: cb)
}
}
}
// Helper for starting a new thread running NumCmds random methods on it. Calls cb when done
private func runRandom(inout history: History, queue: dispatch_queue_t, cb: () -> Void) {
dispatch_async(queue) {
// Each thread creates its own history provider
self.runMultiRandom(&history, val: 0, numCmds: self.NumCmds) { _ in
dispatch_async(dispatch_get_main_queue(), cb)
}
}
}
} | 59ac4b6d1ffe05849016255efd1e3640 | 34.324895 | 124 | 0.542707 | false | true | false | false |
carsonmcdonald/AVSExample-Swift | refs/heads/master | AVSExample/AVSUploader.swift | mit | 1 | //
// AVSUploader.swift
// AVSExample
//
import Foundation
struct PartData {
var headers: [String:String]
var data: NSData
}
class AVSUploader: NSObject, NSURLSessionTaskDelegate {
var authToken:String?
var jsonData:String?
var audioData:NSData?
var errorHandler: ((error:NSError) -> Void)?
var progressHandler: ((progress:Double) -> Void)?
var successHandler: ((data:NSData, parts:[PartData]) -> Void)?
private var session: NSURLSession!
func start() throws {
if self.authToken == nil || self.jsonData == nil || self.audioData == nil {
throw NSError(domain: Config.Error.ErrorDomain, code: Config.Error.AVSUploaderSetupIncompleteErrorCode, userInfo: [NSLocalizedDescriptionKey : "AVS upload options not set"])
}
if self.session == nil {
self.session = NSURLSession(configuration: NSURLSession.sharedSession().configuration, delegate: self, delegateQueue: nil)
}
self.postRecording(self.authToken!, jsonData: self.jsonData!, audioData: self.audioData!)
}
private func parseResponse(data:NSData, boundry:String) -> [PartData] {
let innerBoundry = "\(boundry)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!
let endBoundry = "\r\n\(boundry)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!
var innerRanges = [NSRange]()
var lastStartingLocation = 0
var boundryRange = data.rangeOfData(innerBoundry, options: NSDataSearchOptions(), range: NSMakeRange(lastStartingLocation, data.length))
while(boundryRange.location != NSNotFound) {
lastStartingLocation = boundryRange.location + boundryRange.length
boundryRange = data.rangeOfData(innerBoundry, options: NSDataSearchOptions(), range: NSMakeRange(lastStartingLocation, data.length - lastStartingLocation))
if boundryRange.location != NSNotFound {
innerRanges.append(NSMakeRange(lastStartingLocation, boundryRange.location - innerBoundry.length))
} else {
innerRanges.append(NSMakeRange(lastStartingLocation, data.length - lastStartingLocation))
}
}
var partData = [PartData]()
for innerRange in innerRanges {
let innerData = data.subdataWithRange(innerRange)
let headerRange = innerData.rangeOfData("\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!, options: NSDataSearchOptions(), range: NSMakeRange(0, innerRange.length))
var headers = [String:String]()
if let headerData = NSString(data: innerData.subdataWithRange(NSMakeRange(0, headerRange.location)), encoding: NSUTF8StringEncoding) as? String {
let headerLines = headerData.characters.split{$0 == "\r\n"}.map{String($0)}
for headerLine in headerLines {
let headerSplit = headerLine.characters.split{ $0 == ":" }.map{String($0)}
headers[headerSplit[0]] = headerSplit[1].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
let startLocation = headerRange.location + headerRange.length
let contentData = innerData.subdataWithRange(NSMakeRange(startLocation, innerRange.length - startLocation))
let endContentRange = contentData.rangeOfData(endBoundry, options: NSDataSearchOptions(), range: NSMakeRange(0, contentData.length))
if endContentRange.location != NSNotFound {
partData.append(PartData(headers: headers, data: contentData.subdataWithRange(NSMakeRange(0, endContentRange.location))))
} else {
partData.append(PartData(headers: headers, data: contentData))
}
}
return partData
}
private func postRecording(authToken:String, jsonData:String, audioData:NSData) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize")!)
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.HTTPShouldHandleCookies = false
request.timeoutInterval = 60
request.HTTPMethod = "POST"
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
let boundry = NSUUID().UUIDString
let contentType = "multipart/form-data; boundary=\(boundry)"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
let bodyData = NSMutableData()
bodyData.appendData("--\(boundry)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("Content-Disposition: form-data; name=\"metadata\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("Content-Type: application/json; charset=UTF-8\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData(jsonData.dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("--\(boundry)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("Content-Disposition: form-data; name=\"audio\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("Content-Type: audio/L16; rate=16000; channels=1\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData(audioData)
bodyData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
bodyData.appendData("--\(boundry)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let uploadTask = self.session.uploadTaskWithRequest(request, fromData: bodyData) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
self.progressHandler?(progress: 100.0)
if let e = error {
self.errorHandler?(error: e)
} else {
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299 {
if let responseData = data, let contentTypeHeader = httpResponse.allHeaderFields["Content-Type"] {
var boundry: String?
let ctbRange = contentTypeHeader.rangeOfString("boundary=.*?;", options: .RegularExpressionSearch)
if ctbRange.location != NSNotFound {
let boundryNSS = contentTypeHeader.substringWithRange(ctbRange) as NSString
boundry = boundryNSS.substringWithRange(NSRange(location: 9, length: boundryNSS.length - 10))
}
if let b = boundry {
self.successHandler?(data: responseData, parts:self.parseResponse(responseData, boundry: b))
} else {
self.errorHandler?(error: NSError(domain: Config.Error.ErrorDomain, code: Config.Error.AVSResponseBorderParseErrorCode, userInfo: [NSLocalizedDescriptionKey : "Could not find boundry in AVS response"]))
}
}
} else {
var message: NSString?
if data != nil {
do {
if let errorDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as? [String:AnyObject], let errorValue = errorDictionary["error"] as? [String:String], let errorMessage = errorValue["message"] {
message = errorMessage
} else {
message = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
} catch {
message = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
}
let finalMessage = message == nil ? "" : message!
self.errorHandler?(error: NSError(domain: Config.Error.ErrorDomain, code: Config.Error.AVSAPICallErrorCode, userInfo: [NSLocalizedDescriptionKey : "AVS error: \(httpResponse.statusCode) - \(finalMessage)"]))
}
}
}
}
uploadTask.resume()
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
self.progressHandler?(progress:Double(Double(totalBytesSent) / Double(totalBytesExpectedToSend)) * 100.0)
}
} | 35a36ac8d8f9cde33342194253258f86 | 51.745665 | 280 | 0.604011 | 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 |
eric1202/LZJ_Coin | refs/heads/master | Instagram/Pods/LeanCloud/Sources/Storage/DataType/GeoPoint.swift | mit | 5 | //
// LCGeoPoint.swift
// LeanCloud
//
// Created by Tang Tianyong on 4/1/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
LeanCloud geography point type.
This type can be used to represent a 2D location with latitude and longitude.
*/
public final class LCGeoPoint: NSObject, LCValue, LCValueExtension {
public fileprivate(set) var latitude: Double = 0
public fileprivate(set) var longitude: Double = 0
public enum Unit: String {
case mile = "Miles"
case kilometer = "Kilometers"
case radian = "Radians"
}
public struct Distance {
let value: Double
let unit: Unit
public init(value: Double, unit: Unit) {
self.value = value
self.unit = unit
}
}
public override init() {
super.init()
}
public convenience init(latitude: Double, longitude: Double) {
self.init()
self.latitude = latitude
self.longitude = longitude
}
init?(dictionary: [String: AnyObject]) {
guard let type = dictionary["__type"] as? String else {
return nil
}
guard let dataType = RESTClient.DataType(rawValue: type) else {
return nil
}
guard case dataType = RESTClient.DataType.geoPoint else {
return nil
}
guard let latitude = dictionary["latitude"] as? Double else {
return nil
}
guard let longitude = dictionary["longitude"] as? Double else {
return nil
}
self.latitude = latitude
self.longitude = longitude
}
public required init?(coder aDecoder: NSCoder) {
latitude = aDecoder.decodeDouble(forKey: "latitude")
longitude = aDecoder.decodeDouble(forKey: "longitude")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(latitude, forKey: "latitude")
aCoder.encode(longitude, forKey: "longitude")
}
public func copy(with zone: NSZone?) -> Any {
return LCGeoPoint(latitude: latitude, longitude: longitude)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? LCGeoPoint {
return object === self || (object.latitude == latitude && object.longitude == longitude)
} else {
return false
}
}
public var jsonValue: AnyObject {
return [
"__type" : "GeoPoint",
"latitude" : latitude,
"longitude" : longitude
] as AnyObject
}
public var jsonString: String {
return ObjectProfiler.getJSONString(self)
}
public var rawValue: LCValueConvertible {
return self
}
var lconValue: AnyObject? {
return jsonValue
}
static func instance() -> LCValue {
return self.init()
}
func forEachChild(_ body: (_ child: LCValue) -> Void) {
/* Nothing to do. */
}
func add(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be added.")
}
func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be concatenated.")
}
func differ(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be differed.")
}
}
| 2363ae05c00e6c852c2c265bc8942f5b | 25.71875 | 100 | 0.593275 | 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 |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/FeedItemSectionController.swift | apache-2.0 | 2 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
final class FeedItemSectionController: ListSectionController, ListSupplementaryViewSource {
private var feedItem: FeedItem!
override init() {
super.init()
supplementaryViewSource = self
}
// MARK: IGListSectionController Overrides
override func numberOfItems() -> Int {
return feedItem.comments.count
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as? LabelCell else {
fatalError()
}
cell.text = feedItem.comments[index]
return cell
}
override func didUpdate(to object: Any) {
feedItem = object as? FeedItem
}
// MARK: ListSupplementaryViewSource
func supportedElementKinds() -> [String] {
return [UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
switch elementKind {
case UICollectionElementKindSectionHeader:
return userHeaderView(atIndex: index)
case UICollectionElementKindSectionFooter:
return userFooterView(atIndex: index)
default:
fatalError()
}
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 40)
}
// MARK: Private
private func userHeaderView(atIndex index: Int) -> UICollectionReusableView {
guard let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
for: self,
nibName: "UserHeaderView",
bundle: nil,
at: index) as? UserHeaderView else {
fatalError()
}
view.handle = "@" + feedItem.user.handle
view.name = feedItem.user.name
return view
}
private func userFooterView(atIndex index: Int) -> UICollectionReusableView {
guard let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter,
for: self,
nibName: "UserFooterView",
bundle: nil,
at: index) as? UserFooterView else {
fatalError()
}
view.commentsCount = "\(feedItem.comments.count)"
return view
}
}
| 79617c8df65ab540a0ae49a8a8abefe2 | 40.736842 | 126 | 0.57024 | false | false | false | false |
kjifw/Senses | refs/heads/master | senses-client/Senses/Senses/ViewControllers/TopUsersTableViewController.swift | mit | 1 | //
// TopUsersTableViewController.swift
// Senses
//
// Created by Jeff on 4/1/17.
// Copyright © 2017 Telerik Academy. All rights reserved.
//
import UIKit
class TopUsersTableViewController: UITableViewController, HttpRequesterDelegate {
var url: String {
get {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.baseUrl
}
}
var http: HttpRequester? {
get {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.http
}
}
var userList: [UserListModel] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Top users"
self.http?.delegate = self
let cellNib = UINib(nibName: "UserListTableViewCell", bundle: nil)
self.tableView.register(cellNib, forCellReuseIdentifier: "top-users-list-custom-cell")
self.tableView.rowHeight = 124
self.loadingScreenStart()
self.http?.get(fromUrl: "\(self.url)/user/list/top")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "top-users-list-custom-cell", for: indexPath) as! UserListTableViewCell
cell.city.text = self.userList[indexPath.row].city
cell.username.text = self.userList[indexPath.row].username
cell.kudos.text = self.userList[indexPath.row].kudos
cell.cellImage.contentMode = .scaleAspectFit
if(self.userList[indexPath.row].picture != nil && self.userList[indexPath.row].picture != "") {
let imageData = Data(base64Encoded: (self.userList[indexPath.row].picture)!)
cell.cellImage.image = UIImage(data: imageData! as Data)
} else {
cell.cellImage.image = UIImage(named: "user-image")
}
return cell
}
func didRecieveData(data: Any) {
DispatchQueue.main.async {
let listOfUsers = data as! Dictionary<String, Any>
if(listOfUsers["users"] != nil) {
let userDictArr = listOfUsers["users"] as! [Dictionary<String, Any>]
userDictArr.forEach({ (item) in
self.userList.append(UserListModel.init(withDict: item))
})
}
self.tableView.reloadData()
self.loadingScreenStop()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nextVC = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "UserDetailsVC") as! UserDetailsViewController
nextVC.userUsername = self.userList[indexPath.row].username
self.show(nextVC, sender: self)
}
}
| 5911c404d8eaaff114fece6495e17e97 | 32.090909 | 136 | 0.618437 | 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 |
JGiola/swift | refs/heads/main | test/SILGen/metatype_abstraction.swift | apache-2.0 | 5 |
// RUN: %target-swift-emit-silgen -module-name Swift -parse-stdlib %s | %FileCheck %s
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {}
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
struct S {}
class C {}
struct Generic<T> {
var value: T
}
struct GenericMetatype<T> {
var value: T.Type
}
// CHECK-LABEL: sil hidden [ossa] @$ss26genericMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<T.Type>, #Generic.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick T.Type
// CHECK: return [[META]] : $@thick T.Type
// CHECK: }
func genericMetatypeFromGeneric<T>(_ x: Generic<T.Type>) -> T.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden [ossa] @$ss26dynamicMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*Generic<C.Type>, #Generic.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick C.Type
// CHECK: return [[META]] : $@thick C.Type
// CHECK: }
func dynamicMetatypeFromGeneric(_ x: Generic<C.Type>) -> C.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden [ossa] @$ss25staticMetatypeFromGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[META:%.*]] = metatype $@thin S.Type
// CHECK: return [[META]] : $@thin S.Type
// CHECK: }
func staticMetatypeFromGeneric(_ x: Generic<S.Type>) -> S.Type {
return x.value
}
// CHECK-LABEL: sil hidden [ossa] @$ss026genericMetatypeFromGenericB0{{[_0-9a-zA-Z]*}}F
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}} : $*GenericMetatype<T>, #GenericMetatype.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick T.Type
// CHECK: return [[META]] : $@thick T.Type
// CHECK: }
func genericMetatypeFromGenericMetatype<T>(_ x: GenericMetatype<T>)-> T.Type {
var x = x
return x.value
}
// CHECK-LABEL: sil hidden [ossa] @$ss026dynamicMetatypeFromGenericB0ys1CCms0dB0VyACGF
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var GenericMetatype<C> }
// CHECK: [[XBOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[PX:%[0-9]+]] = project_box [[XBOX_LIFETIME]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*GenericMetatype<C>
// CHECK: [[ADDR:%.*]] = struct_element_addr [[READ]] : $*GenericMetatype<C>, #GenericMetatype.value
// CHECK: [[META:%.*]] = load [trivial] [[ADDR]] : $*@thick C.Type
// CHECK: return [[META]] : $@thick C.Type
// CHECK: }
func dynamicMetatypeFromGenericMetatype(_ x: GenericMetatype<C>) -> C.Type {
var x = x
return x.value
}
func takeGeneric<T>(_ x: T) {}
func takeGenericMetatype<T>(_ x: T.Type) {}
// CHECK-LABEL: sil hidden [ossa] @$ss23staticMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick S.Type
// CHECK: [[META:%.*]] = metatype $@thick S.Type
// CHECK: store [[META]] to [trivial] [[MAT]] : $*@thick S.Type
// CHECK: apply {{%.*}}<S.Type>([[MAT]])
func staticMetatypeToGeneric(_ x: S.Type) {
takeGeneric(x)
}
// CHECK-LABEL: sil hidden [ossa] @$ss023staticMetatypeToGenericB0{{[_0-9a-zA-Z]*}}F
// CHECK: [[META:%.*]] = metatype $@thick S.Type
// CHECK: apply {{%.*}}<S>([[META]])
func staticMetatypeToGenericMetatype(_ x: S.Type) {
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden [ossa] @$ss24dynamicMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick C.Type
// CHECK: apply {{%.*}}<C.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> ()
func dynamicMetatypeToGeneric(_ x: C.Type) {
var x = x
takeGeneric(x)
}
// CHECK-LABEL: sil hidden [ossa] @$ss024dynamicMetatypeToGenericB0yys1CCmF
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var @thick C.Type }
// CHECK: [[XBOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[PX:%[0-9]+]] = project_box [[XBOX_LIFETIME]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*@thick C.Type
// CHECK: [[META:%.*]] = load [trivial] [[READ]] : $*@thick C.Type
// CHECK: apply {{%.*}}<C>([[META]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> ()
func dynamicMetatypeToGenericMetatype(_ x: C.Type) {
var x = x
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden [ossa] @$ss24genericMetatypeToGeneric{{[_0-9a-zA-Z]*}}F
// CHECK: [[MAT:%.*]] = alloc_stack $@thick U.Type
// CHECK: apply {{%.*}}<U.Type>([[MAT]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> ()
func genericMetatypeToGeneric<U>(_ x: U.Type) {
var x = x
takeGeneric(x)
}
func genericMetatypeToGenericMetatype<U>(_ x: U.Type) {
takeGenericMetatype(x)
}
// CHECK-LABEL: sil hidden [ossa] @$ss019static_metatype_of_B0ys1SVmmACF
// CHECK: metatype $@thin S.Type.Type
func static_metatype_of_metatype(_ x: S) -> S.Type.Type {
return type(of: type(of: x))
}
// CHECK-LABEL: sil hidden [ossa] @$ss018class_metatype_of_B0ys1CCmmACF
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick C.Type
// CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick C.Type.Type, [[METATYPE]]
func class_metatype_of_metatype(_ x: C) -> C.Type.Type {
return type(of: type(of: x))
}
// CHECK-LABEL: sil hidden [ossa] @$ss020generic_metatype_of_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick T.Type
// CHECK: [[META_METATYPE:%.*]] = value_metatype $@thick T.Type.Type, [[METATYPE]]
func generic_metatype_of_metatype<T>(_ x: T) -> T.Type.Type {
return type(of: type(of: x))
}
// FIXME rdar://problem/18419772
/*
func existential_metatype_of_metatype(_ x: Any) -> Any.Type.Type {
return type(of: type(of: x))
}
*/
func function_metatype_of_metatype(_ x: @escaping () -> ()) -> (() -> ()).Type.Type {
return type(of: type(of: x))
}
| a33d7620186dc32ee66a511c978ae9a6 | 39.408163 | 108 | 0.590236 | 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 |
magi82/MGRelativeKit | refs/heads/master | Sources/RelativeLayout+of.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension RelativeLayout {
public func leftOf(from: UIView, margin: CGFloat = 0) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.x = from.frame.origin.x - (myView.frame.size.width + margin)
self.layoutChanged.insert(.leftOf)
return self
}
public func rightOf(from: UIView, margin: CGFloat = 0) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.x = from.frame.origin.x + (from.frame.size.width + margin)
self.layoutChanged.insert(.rightOf)
return self
}
public func topOf(from: UIView, margin: CGFloat = 0) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.y = from.frame.origin.y - (myView.frame.size.height + margin)
self.layoutChanged.insert(.topOf)
return self
}
public func bottomOf(from: UIView, margin: CGFloat = 0) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.y = from.frame.origin.y + (from.frame.size.height + margin)
self.layoutChanged.insert(.bottomOf)
return self
}
public func centerHorizontalOf(from: UIView) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.x = from.frame.origin.x + (from.frame.size.width - myView.frame.size.width) * 0.5
return self
}
public func centerVerticalOf(from: UIView) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.y = from.frame.origin.y + (from.frame.size.height - myView.frame.size.height) * 0.5
return self
}
public func centerOf(from: UIView) -> Self {
guard let myView = self.myView else { return self }
myView.frame.origin.x = from.frame.origin.x + (from.frame.size.width - myView.frame.size.width) * 0.5
myView.frame.origin.y = from.frame.origin.y + (from.frame.size.height - myView.frame.size.height) * 0.5
return self
}
}
| 44bb6a6f2ec12cabc872c41ab8fcb29b | 35.197674 | 107 | 0.708962 | 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 |
jngd/advanced-ios10-training | refs/heads/master | T2E04/T2E04/SecondViewController.swift | apache-2.0 | 1 | //
// SecondViewController.swift
// T2E04
//
// Created by jngd on 18/09/16.
// Copyright © 2016 jngd. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController,
UIViewControllerTransitioningDelegate {
var crossfade : CrossfadeTransition!
override func viewDidLoad() {
self.crossfade = CrossfadeTransition()
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender:
Any?) {
if (segue.identifier == "showCrossfadeTransition"){
let toVC : UIViewController = segue.destination
as UIViewController
toVC.transitioningDelegate = self
}
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) ->
UIViewControllerAnimatedTransitioning? {
return self.crossfade
}
}
| 3a783f486c7123f2a57a2e43e124f50b | 22.8 | 67 | 0.716387 | 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 |
jasonsturges/SwiftLabs | refs/heads/master | SceneKitSkybox/SceneKitSkybox/GameViewController.swift | mit | 2 | //
// GameViewController.swift
// SceneKitSkybox
//
// Created by Jason Sturges on 11/5/15.
// Copyright (c) 2015 Jason Sturges. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
//let scene = SCNScene(named: "art.scnassets/ship.scn")!
let scene = SkyboxScene()
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLight.LightType.omni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLight.LightType.ambient
ambientLightNode.light!.color = UIColor.darkGray
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.black
}
override var shouldAutorotate : Bool {
return true
}
override var prefersStatusBarHidden : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| 9cd5c6d1bcbfdc072e0a31f22aee51d2 | 28.296296 | 78 | 0.614834 | 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 |
CodaFi/swift | refs/heads/master | stdlib/public/Differentiation/DifferentialOperators.swift | apache-2.0 | 9 | //===--- DifferentialOperators.swift --------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// APIs for computing derivatives of functions.
//
//===----------------------------------------------------------------------===//
import Swift
// Transpose
@inlinable
public func transpose<T, R>(
of body: @escaping @differentiable(linear) (T) -> R
) -> @differentiable(linear) (R) -> T {
let original = body as (T) -> R
let transpose = { x in Builtin.applyTranspose_arity1(body, x) }
return Builtin.linearFunction_arity1(transpose, original)
}
// Value with differential
@inlinable
public func valueWithDifferential<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, differential: (T.TangentVector) -> R.TangentVector) {
return Builtin.applyDerivative_jvp(f, x)
}
@inlinable
public func valueWithDifferential<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R,
differential: (T.TangentVector, U.TangentVector) -> R.TangentVector) {
return Builtin.applyDerivative_jvp_arity2(f, x, y)
}
@inlinable
public func valueWithDifferential<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
differential: (T.TangentVector, U.TangentVector, V.TangentVector)
-> (R.TangentVector)) {
return Builtin.applyDerivative_jvp_arity3(f, x, y, z)
}
// Value with pullback
@inlinable
public func valueWithPullback<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, pullback: (R.TangentVector) -> T.TangentVector) {
return Builtin.applyDerivative_vjp(f, x)
}
@inlinable
public func valueWithPullback<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R,
pullback: (R.TangentVector) -> (T.TangentVector, U.TangentVector)) {
return Builtin.applyDerivative_vjp_arity2(f, x, y)
}
@inlinable
public func valueWithPullback<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
pullback: (R.TangentVector)
-> (T.TangentVector, U.TangentVector, V.TangentVector)) {
return Builtin.applyDerivative_vjp_arity3(f, x, y, z)
}
// Differential
@inlinable
public func differential<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (T.TangentVector) -> R.TangentVector {
return valueWithDifferential(at: x, in: f).1
}
@inlinable
public func differential<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (T.TangentVector, U.TangentVector) -> R.TangentVector {
return valueWithDifferential(at: x, y, in: f).1
}
@inlinable
public func differential<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (T.TangentVector, U.TangentVector, V.TangentVector) -> (R.TangentVector) {
return valueWithDifferential(at: x, y, z, in: f).1
}
// Pullback
@inlinable
public func pullback<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (R.TangentVector) -> T.TangentVector {
return Builtin.applyDerivative_vjp(f, x).1
}
@inlinable
public func pullback<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (R.TangentVector) -> (T.TangentVector, U.TangentVector) {
return Builtin.applyDerivative_vjp_arity2(f, x, y).1
}
@inlinable
public func pullback<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (R.TangentVector)
-> (T.TangentVector, U.TangentVector, V.TangentVector) {
return Builtin.applyDerivative_vjp_arity3(f, x, y, z).1
}
// Derivative
@inlinable
public func derivative<T: FloatingPoint, R>(
at x: T, in f: @differentiable (T) -> R
) -> R.TangentVector
where T.TangentVector == T {
return differential(at: x, in: f)(T(1))
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U {
return differential(at: x, y, in: f)(T(1), U(1))
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return differential(at: x, y, z, in: f)(T(1), U(1), V(1))
}
// Gradient
@inlinable
public func gradient<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> T.TangentVector
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, in: f)(R(1))
}
@inlinable
public func gradient<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (T.TangentVector, U.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, y, in: f)(R(1))
}
@inlinable
public func gradient<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (T.TangentVector, U.TangentVector, V.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, y, z, in: f)(R(1))
}
// Value with derivative
@inlinable
public func valueWithDerivative<T: FloatingPoint, R>(
at x: T, in f: @escaping @differentiable (T) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T {
let (y, differential) = valueWithDifferential(at: x, in: f)
return (y, differential(T(1)))
}
@inlinable
public func valueWithDerivative<T: FloatingPoint, U: FloatingPoint, R>(
at x: T, _ y: U, in f: @escaping @differentiable (T, U) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U {
let (y, differential) = valueWithDifferential(at: x, y, in: f)
return (y, differential(T(1), U(1)))
}
@inlinable
public func valueWithDerivative<
T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
at x: T, _ y: U, _ z: V, in f: @escaping @differentiable (T, U, V) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
let (y, differential) = valueWithDifferential(at: x, y, z, in: f)
return (y, differential(T(1), U(1), V(1)))
}
// Value with gradient
@inlinable
public func valueWithGradient<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, gradient: T.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, in: f)
return (y, pullback(R(1)))
}
@inlinable
public func valueWithGradient<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R, gradient: (T.TangentVector, U.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, y, in: f)
return (y, pullback(R(1)))
}
@inlinable
public func valueWithGradient<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
gradient: (T.TangentVector, U.TangentVector, V.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, y, z, in: f)
return (y, pullback(R(1)))
}
// Derivative (curried)
@inlinable
public func derivative<T: FloatingPoint, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> R.TangentVector
where T.TangentVector == T {
return { x in derivative(at: x, in: f) }
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U {
return { (x, y) in derivative(at: x, y, in: f) }
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return { (x, y, z) in derivative(at: x, y, z, in: f) }
}
// Gradient (curried)
@inlinable
public func gradient<T, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> T.TangentVector
where R : FloatingPoint, R.TangentVector == R {
return { x in gradient(at: x, in: f) }
}
@inlinable
public func gradient<T, U, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (T.TangentVector, U.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x, y in gradient(at: x, y, in: f) }
}
@inlinable
public func gradient<T, U, V, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> (T.TangentVector, U.TangentVector, V.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x, y, z in gradient(at: x, y, z, in: f) }
}
// Value with derivative (curried)
@inlinable
public func valueWithDerivative<T: FloatingPoint, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T {
return { x in valueWithDerivative(at: x, in: f) }
}
@inlinable
public func valueWithDerivative<T: FloatingPoint, U: FloatingPoint, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U {
return { (x, y) in valueWithDerivative(at: x, y, in: f) }
}
@inlinable
public func valueWithDerivative<
T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return { (x, y, z) in valueWithDerivative(at: x, y, z, in: f) }
}
// Value with gradient (curried)
@inlinable
public func valueWithGradient<T, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> (value: R, gradient: T.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x in valueWithGradient(at: x, in: f) }
}
@inlinable
public func valueWithGradient<T, U, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (value: R, gradient: (T.TangentVector, U.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
return { x, y in valueWithGradient(at: x, y, in: f) }
}
@inlinable
public func valueWithGradient<T, U, V, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V)
-> (value: R,
gradient: (T.TangentVector, U.TangentVector, V.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
return { x, y, z in valueWithGradient(at: x, y, z, in: f) }
}
| 243475534a19663bb5ede187e4e3f96a | 29.097493 | 80 | 0.629986 | 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 |
shajrawi/swift | refs/heads/master | test/ParseableInterface/Inputs/enums-layout-helper.swift | apache-2.0 | 1 | // CHECK-LABEL: public enum FutureproofEnum : Int
public enum FutureproofEnum: Int {
// CHECK-NEXT: case a{{$}}
case a = 1
// CHECK-NEXT: case b{{$}}
case b = 10
// CHECK-NEXT: case c{{$}}
case c = 100
}
// CHECK-LABEL: public enum FrozenEnum : Int
@_frozen public enum FrozenEnum: Int {
// CHECK-NEXT: case a{{$}}
case a = 1
// CHECK-NEXT: case b{{$}}
case b = 10
// CHECK-NEXT: case c{{$}}
case c = 100
}
// CHECK-LABEL: public enum FutureproofObjCEnum : Int32
@objc public enum FutureproofObjCEnum: Int32 {
// CHECK-NEXT: case a = 1{{$}}
case a = 1
// CHECK-NEXT: case b = 10{{$}}
case b = 10
// CHECK-NEXT: case c = 100{{$}}
case c = 100
}
// CHECK-LABEL: public enum FrozenObjCEnum : Int32
@_frozen @objc public enum FrozenObjCEnum: Int32 {
// CHECK-NEXT: case a = 1{{$}}
case a = 1
// CHECK-NEXT: case b = 10{{$}}
case b = 10
// CHECK-NEXT: case c = 100{{$}}
case c = 100
}
| f0c39d70fc05cc8f84d796e777d17d97 | 22.3 | 55 | 0.592275 | 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 |
ALHariPrasad/BluetoothKit | refs/heads/master | Pods/BluetoothKit/Source/BKAvailability.swift | gpl-3.0 | 14 | //
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreBluetooth
public func ==(lhs: BKAvailability, rhs: BKAvailability) -> Bool {
switch (lhs, rhs) {
case (.Available, .Available): return true
case (.Unavailable(cause: .Any), .Unavailable): return true
case (.Unavailable, .Unavailable(cause: .Any)): return true
case (.Unavailable(let lhsCause), .Unavailable(let rhsCause)): return lhsCause == rhsCause
default: return false
}
}
/**
Bluetooth LE availability.
- Available: Bluetooth LE is available.
- Unavailable: Bluetooth LE is unavailable.
The unavailable case can be accompanied by a cause.
*/
public enum BKAvailability: Equatable {
case Available
case Unavailable(cause: BKUnavailabilityCause)
internal init(centralManagerState: CBCentralManagerState) {
switch centralManagerState {
case .PoweredOn: self = .Available
default: self = .Unavailable(cause: BKUnavailabilityCause(centralManagerState: centralManagerState))
}
}
internal init(peripheralManagerState: CBPeripheralManagerState) {
switch peripheralManagerState {
case .PoweredOn: self = .Available
default: self = .Unavailable(cause: BKUnavailabilityCause(peripheralManagerState: peripheralManagerState))
}
}
}
/**
Bluetooth LE unavailability cause.
- Any: When initialized with nil.
- Resetting: Bluetooth is resetting.
- Unsupported: Bluetooth LE is not supported on the device.
- Unauthorized: The app isn't allowed to use Bluetooth.
- PoweredOff: Bluetooth is turned off.
*/
public enum BKUnavailabilityCause: NilLiteralConvertible {
case Any
case Resetting
case Unsupported
case Unauthorized
case PoweredOff
public init(nilLiteral: Void) {
self = Any
}
internal init(centralManagerState: CBCentralManagerState) {
switch centralManagerState {
case .PoweredOff: self = PoweredOff
case .Resetting: self = Resetting
case .Unauthorized: self = Unauthorized
case .Unsupported: self = Unsupported
default: self = nil
}
}
internal init(peripheralManagerState: CBPeripheralManagerState) {
switch peripheralManagerState {
case .PoweredOff: self = PoweredOff
case .Resetting: self = Resetting
case .Unauthorized: self = Unauthorized
case .Unsupported: self = Unsupported
default: self = nil
}
}
}
/**
Classes that can be observed for Bluetooth LE availability implement this protocol.
*/
public protocol BKAvailabilityObservable: class {
var availabilityObservers: [BKWeakAvailabilityObserver] { get set }
func addAvailabilityObserver(availabilityObserver: BKAvailabilityObserver)
func removeAvailabilityObserver(availabilityObserver: BKAvailabilityObserver)
}
/**
Class used to hold a weak reference to an observer of Bluetooth LE availability.
*/
public class BKWeakAvailabilityObserver {
weak var availabilityObserver : BKAvailabilityObserver?
init (availabilityObserver: BKAvailabilityObserver) {
self.availabilityObserver = availabilityObserver
}
}
public extension BKAvailabilityObservable {
/**
Add a new availability observer. The observer will be weakly stored. If the observer is already subscribed the call will be ignored.
- parameter availabilityObserver: The availability observer to add.
*/
func addAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) {
if !availabilityObservers.contains({ $0.availabilityObserver === availabilityObserver }) {
availabilityObservers.append(BKWeakAvailabilityObserver(availabilityObserver: availabilityObserver))
}
}
/**
Remove an availability observer. If the observer isn't subscribed the call will be ignored.
- parameter availabilityObserver: The availability observer to remove.
*/
func removeAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) {
if availabilityObservers.contains({ $0.availabilityObserver === availabilityObserver }) {
availabilityObservers.removeAtIndex(availabilityObservers.indexOf({ $0 === availabilityObserver })!)
}
}
}
/**
Observers of Bluetooth LE availability should implement this protocol.
*/
public protocol BKAvailabilityObserver: class {
/**
Informs the observer about a change in Bluetooth LE availability.
- parameter availabilityObservable: The object that registered the availability change.
- parameter availability: The new availability value.
*/
func availabilityObserver(availabilityObservable: BKAvailabilityObservable, availabilityDidChange availability: BKAvailability)
/**
Informs the observer that the cause of Bluetooth LE unavailability changed.
- parameter availabilityObservable: The object that registered the cause change.
- parameter unavailabilityCause: The new cause of unavailability.
*/
func availabilityObserver(availabilityObservable: BKAvailabilityObservable, unavailabilityCauseDidChange unavailabilityCause: BKUnavailabilityCause)
}
| 953788a5936de95bfa81fa1abc5f804e | 37.550296 | 152 | 0.714965 | 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 |
luzefeng/MLSwiftBasic | refs/heads/master | MLSwiftBasic/Classes/Refresh/ZLSwifthRefresh/ZLSwiftRefreshExtension.swift | mit | 1 | //
// ZLSwiftRefreshExtension.swift
// ZLSwiftRefresh
//
// Created by 张磊 on 15-3-6.
// Copyright (c) 2015年 com.zixue101.www. All rights reserved.
//
import UIKit
enum RefreshStatus{
case Normal, Refresh, LoadMore
}
enum HeaderViewRefreshAnimationStatus{
case headerViewRefreshPullAnimation, headerViewRefreshLoadingAnimation, headerViewRefreshArrowAnimation
}
var loadMoreAction: (() -> ()) = {}
var refreshStatus:RefreshStatus = .Normal
let animations:CGFloat = 60.0
var tableViewOriginContentInset:UIEdgeInsets = UIEdgeInsetsZero
extension UIScrollView: UIScrollViewDelegate {
public var headerRefreshView: ZLSwiftHeadView? {
get {
var headerRefreshView = viewWithTag(ZLSwiftHeadViewTag)
return headerRefreshView as? ZLSwiftHeadView
}
}
public var footerRefreshView: ZLSwiftFootView? {
get {
var footerRefreshView = viewWithTag(ZLSwiftFootViewTag)
return footerRefreshView as? ZLSwiftFootView
}
}
//MARK: Refresh
//下拉刷新
func toRefreshAction(action :(() -> Void)){
self.alwaysBounceVertical = true
if self.headerRefreshView == nil{
var headView:ZLSwiftHeadView = ZLSwiftHeadView(action: action,frame: CGRectMake(0, -ZLSwithRefreshHeadViewHeight, self.frame.size.width, ZLSwithRefreshHeadViewHeight))
headView.scrollView = self
headView.tag = ZLSwiftHeadViewTag
self.addSubview(headView)
}
}
//MARK: LoadMore
//上拉加载更多
func toLoadMoreAction(action :(() -> Void)){
if (refreshStatus == .LoadMore){
refreshStatus = .Normal
}
self.addLoadMoreView(action)
}
func addLoadMoreView(action :(() -> Void)){
self.alwaysBounceVertical = true
loadMoreAction = action
if self.footerRefreshView == nil {
var footView = ZLSwiftFootView(action: action, frame: CGRectMake( 0 , UIScreen.mainScreen().bounds.size.height - ZLSwithRefreshFootViewHeight, self.frame.size.width, ZLSwithRefreshFootViewHeight))
footView.scrollView = self
footView.tag = ZLSwiftFootViewTag
self.addSubview(footView)
}
}
//MARK: nowRefresh
//立马上拉刷新
func nowRefresh(action :(() -> Void)){
self.alwaysBounceVertical = true
if self.headerRefreshView == nil {
var headView:ZLSwiftHeadView = ZLSwiftHeadView(action: action,frame: CGRectMake(0, -ZLSwithRefreshHeadViewHeight, self.frame.size.width, ZLSwithRefreshHeadViewHeight))
headView.scrollView = self
headView.tag = ZLSwiftHeadViewTag
self.addSubview(headView)
}else{
self.headerRefreshView?.action = action
}
self.headerRefreshView?.nowLoading = true
self.headerRefreshView?.nowAction = action
}
func headerViewRefreshAnimationStatus(status:HeaderViewRefreshAnimationStatus, images:[UIImage]){
// 箭头动画是自带的效果
if self.headerRefreshView == nil {
var headView:ZLSwiftHeadView = ZLSwiftHeadView(action: {},frame: CGRectMake(0, -ZLSwithRefreshHeadViewHeight, self.frame.size.width, ZLSwithRefreshHeadViewHeight))
headView.scrollView = self
headView.tag = ZLSwiftHeadViewTag
self.addSubview(headView)
}
if (status != .headerViewRefreshArrowAnimation){
self.headerRefreshView?.customAnimation = true
}
self.headerRefreshView?.animationStatus = status
if (status == .headerViewRefreshLoadingAnimation){
self.headerRefreshView?.headImageView.animationImages = images
}else{
self.headerRefreshView?.headImageView.image = images.first
self.headerRefreshView?.pullImages = images
}
}
//MARK: endLoadMoreData
//数据加载完毕
func endLoadMoreData() {
var footView:ZLSwiftFootView = self.viewWithTag(ZLSwiftFootViewTag) as! ZLSwiftFootView
footView.isEndLoadMore = true
}
//MARK: doneRefersh
//完成刷新
func doneRefresh(){
if var headerView:ZLSwiftHeadView = self.viewWithTag(ZLSwiftHeadViewTag) as? ZLSwiftHeadView {
headerView.stopAnimation()
}
refreshStatus = .Normal
// if (loadMoreAction != nil){
// toLoadMoreAction(loadMoreAction)
// }
}
}
| 657d549719be9a4be5cf8fe829b8b986 | 32.066176 | 208 | 0.647543 | 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 |
anilkumarbp/ringcentral-swift-v2 | refs/heads/master | RingCentral/Platform/Auth.swift | mit | 1 | //
// Auth.swift
// RingCentral
//
// Created by Anil Kumar BP on 2/10/16.
// Copyright © 2016 Anil Kumar BP. All rights reserved.
//
import Foundation
/// Authorization object for the platform.
public class Auth {
static let MAINCOMPANY = "101"
// Authorization information
var token_type: String?
var access_token: String?
var expires_in: Double = 0
var expire_time: Double = 0
var refresh_token: String?
var refresh_token_expires_in: Double = 0
var refresh_token_expire_time: Double = 0
var scope: String?
var owner_id: String?
/// Constructor for the Auth Object
///
/// - parameter appKey: The appKey of your app
/// - parameter appSecet: The appSecret of your app
/// - parameter server: Choice of PRODUCTION or SANDBOX
public init() {
self.token_type = nil
self.access_token = nil
self.expires_in = 0
self.expire_time = 0
self.refresh_token = nil
self.refresh_token_expires_in = 0
self.refresh_token_expire_time = 0
self.scope = nil
self.owner_id = nil
}
/// func setData()
///
/// - parameter data: Dictionary of Data from the ApiResposne ( token information )
/// @response: Auth Instance of Auth class
public func setData(data: Dictionary<String, AnyObject>) -> Auth {
if data.count < 0 {
return self
}
// Misc
if let token_type = data["token_type"] as? String {
self.token_type = token_type
}
if let owner_id = data["owner_id"] as? String {
self.owner_id = owner_id
}
if let scope = data["scope"] as? String {
self.scope = scope
}
// Access Token
if let access_token = data["access_token"] as? String {
self.access_token = access_token
}
if let expires_in = data["expires_in"] as? Double {
self.expires_in = expires_in
}
if data["expire_time"] == nil {
if data["expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.expire_time = time + self.expires_in
}
} else if let expire_time = data["expire_time"] as? Double {
self.expire_time = expire_time
}
// Refresh Token
if let access_token = data["refresh_token"] as? String {
self.refresh_token = access_token
}
if let refresh_token_expires_in = data["refresh_token_expires_in"] as? Double {
self.refresh_token_expires_in = refresh_token_expires_in
}
if data["refresh_token_expire_time"] == nil {
if data["refresh_token_expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.refresh_token_expire_time = time + self.refresh_token_expires_in
}
} else if let refresh_token_expire_time = data["refresh_token_expire_time"] as? Double {
self.refresh_token_expire_time = refresh_token_expire_time
}
return self
}
/// Reset the authentication data.
///
/// func reset()
/// @response: Void
public func reset() -> Void {
self.token_type = " ";
self.access_token = "";
self.expires_in = 0;
self.expire_time = 0;
self.refresh_token = "";
self.refresh_token_expires_in = 0;
self.refresh_token_expire_time = 0;
self.scope = "";
self.owner_id = "";
// return self
}
/// Return the authnetication data
///
/// func data()
/// @response: Return a list of authentication data ( List of Token Information )
public func data()-> [String: AnyObject] {
var data: [String: AnyObject] = [:]
data["token_type"]=self.token_type
data["access_token"]=self.access_token
data["expires_in"]=self.expires_in
data["expire_time"]=self.expire_time
data["refresh_token"]=self.refresh_token
data["refresh_token_expires_in"]=self.refresh_token_expires_in
data["refresh_token_expire_time"]=self.refresh_token_expire_time
data["scope"]=self.scope
data["owner_id"]=self.owner_id
return data
}
/// Checks whether or not the access token is valid
///
/// - returns: A boolean for validity of access token
public func isAccessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if(self.expire_time > time) {
return true
}
return false
}
/// Checks for the validity of the refresh token
///
/// - returns: A boolean for validity of the refresh token
public func isRefreshTokenVald() -> Bool {
return false
}
/// Returns the 'access token'
///
/// - returns: String of 'access token'
public func accessToken() -> String {
return self.access_token!
}
/// Returns the 'refresh token'
///
/// - returns: String of 'refresh token'
public func refreshToken() -> String {
return self.refresh_token!
}
/// Returns the 'tokenType'
///
/// - returns: String of 'token Type'
public func tokenType() -> String {
return self.token_type!
}
/// Returns bool if 'accessTokenValid'
///
/// - returns: Bool if 'access token valid'
public func accessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.expire_time > time {
return true
}
return false
}
/// Returns bool if 'refreshTokenValid'
///
/// - returns: String of 'refresh token valid'
public func refreshTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.refresh_token_expire_time > time {
return true
}
return false
}
}
| 83ade280a72779fe67515cdffecaae48 | 28.416268 | 97 | 0.549935 | 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 |
Ataraxiis/MGW-Esport | refs/heads/develop | Carthage/Checkouts/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift | apache-2.0 | 26 | //
// VirtualTimeScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Base class for virtual time schedulers using a priority queue for scheduled items.
*/
public class VirtualTimeScheduler<Converter: VirtualTimeConverterType>
: SchedulerType
, CustomDebugStringConvertible {
public typealias VirtualTime = Converter.VirtualTimeUnit
public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit
private var _running : Bool
private var _clock: VirtualTime
private var _schedulerQueue : PriorityQueue<VirtualSchedulerItem<VirtualTime>>
private var _converter: Converter
private var _nextId = 0
/**
- returns: Current time.
*/
public var now: RxTime {
return _converter.convertFromVirtualTime(clock)
}
/**
- returns: Scheduler's absolute time clock value.
*/
public var clock: VirtualTime {
return _clock
}
/**
Creates a new virtual time scheduler.
- parameter initialClock: Initial value for the clock.
*/
public init(initialClock: VirtualTime, converter: Converter) {
_clock = initialClock
_running = false
_converter = converter
_schedulerQueue = PriorityQueue(hasHigherPriority: {
switch converter.compareVirtualTime($0.time, $1.time) {
case .LessThan:
return true
case .Equal:
return $0.id < $1.id
case .GreaterThan:
return false
}
})
#if TRACE_RESOURCES
AtomicIncrement(&resourceCount)
#endif
}
/**
Schedules an action to be executed immediatelly.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
return self.scheduleRelative(state, dueTime: 0.0) { a in
return action(a)
}
}
/**
Schedules an action to be executed.
- parameter state: State passed to the action to be executed.
- parameter dueTime: Relative time after which to execute the action.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func scheduleRelative<StateType>(state: StateType, dueTime: RxTimeInterval, action: StateType -> Disposable) -> Disposable {
let time = self.now.dateByAddingTimeInterval(dueTime)
let absoluteTime = _converter.convertToVirtualTime(time)
let adjustedTime = self.adjustScheduledTime(absoluteTime)
return scheduleAbsoluteVirtual(state, time: adjustedTime, action: action)
}
/**
Schedules an action to be executed after relative time has passed.
- parameter state: State passed to the action to be executed.
- parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func scheduleRelativeVirtual<StateType>(state: StateType, dueTime: VirtualTimeInterval, action: StateType -> Disposable) -> Disposable {
let time = _converter.offsetVirtualTime(time: self.clock, offset: dueTime)
return scheduleAbsoluteVirtual(state, time: time, action: action)
}
/**
Schedules an action to be executed at absolute virtual time.
- parameter state: State passed to the action to be executed.
- parameter time: Absolute time when to execute the action.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func scheduleAbsoluteVirtual<StateType>(state: StateType, time: Converter.VirtualTimeUnit, action: StateType -> Disposable) -> Disposable {
MainScheduler.ensureExecutingOnScheduler()
let compositeDisposable = CompositeDisposable()
let item = VirtualSchedulerItem(action: {
let dispose = action(state)
return dispose
}, time: time, id: _nextId)
_nextId += 1
_schedulerQueue.enqueue(item)
compositeDisposable.addDisposable(item)
return compositeDisposable
}
/**
Adjusts time of scheduling before adding item to schedule queue.
*/
public func adjustScheduledTime(time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit {
return time
}
/**
Starts the virtual time scheduler.
*/
public func start() {
MainScheduler.ensureExecutingOnScheduler()
if _running {
return
}
_running = true
repeat {
guard let next = findNext() else {
break
}
if _converter.compareVirtualTime(next.time, self.clock).greaterThan {
_clock = next.time
}
next.invoke()
_schedulerQueue.remove(next)
} while _running
_running = false
}
func findNext() -> VirtualSchedulerItem<VirtualTime>? {
while let front = _schedulerQueue.peek() {
if front.disposed {
_schedulerQueue.remove(front)
continue
}
return front
}
return nil
}
/**
Advances the scheduler's clock to the specified time, running all work till that point.
- parameter virtualTime: Absolute time to advance the scheduler's clock to.
*/
public func advanceTo(virtualTime: VirtualTime) {
MainScheduler.ensureExecutingOnScheduler()
if _running {
fatalError("Scheduler is already running")
}
_running = true
repeat {
guard let next = findNext() else {
break
}
if _converter.compareVirtualTime(next.time, virtualTime).greaterThan {
break
}
if _converter.compareVirtualTime(next.time, self.clock).greaterThan {
_clock = next.time
}
next.invoke()
_schedulerQueue.remove(next)
} while _running
_clock = virtualTime
_running = false
}
/**
Advances the scheduler's clock by the specified relative time.
*/
public func sleep(virtualInterval: VirtualTimeInterval) {
MainScheduler.ensureExecutingOnScheduler()
let sleepTo = _converter.offsetVirtualTime(time: clock, offset: virtualInterval)
if _converter.compareVirtualTime(sleepTo, clock).lessThen {
fatalError("Can't sleep to past.")
}
_clock = sleepTo
}
/**
Stops the virtual time scheduler.
*/
public func stop() {
MainScheduler.ensureExecutingOnScheduler()
_running = false
}
#if TRACE_RESOURCES
deinit {
AtomicDecrement(&resourceCount)
}
#endif
}
// MARK: description
extension VirtualTimeScheduler {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription: String {
return self._schedulerQueue.debugDescription
}
}
class VirtualSchedulerItem<Time>
: Disposable {
typealias Action = () -> Disposable
let action: Action
let time: Time
let id: Int
var disposed: Bool {
return disposable.disposed
}
var disposable = SingleAssignmentDisposable()
init(action: Action, time: Time, id: Int) {
self.action = action
self.time = time
self.id = id
}
func invoke() {
self.disposable.disposable = action()
}
func dispose() {
self.disposable.dispose()
}
}
extension VirtualSchedulerItem
: CustomDebugStringConvertible {
var debugDescription: String {
return "\(time)"
}
} | 752e8a720ebaa72ee1a3ee49a832fe9a | 27.280822 | 150 | 0.626741 | 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 |
kosicki123/eidolon | refs/heads/master | Kiosk/Bid Fulfillment/ConfirmYourBidViewController.swift | mit | 1 | import UIKit
import ECPhoneNumberFormatter
import Moya
public class ConfirmYourBidViewController: UIViewController {
dynamic var number: String = ""
let phoneNumberFormatter = ECPhoneNumberFormatter()
@IBOutlet public var bidDetailsPreviewView: BidDetailsPreviewView!
@IBOutlet public var numberAmountTextField: TextField!
@IBOutlet public var cursor: CursorView!
@IBOutlet public var keypadContainer: KeypadContainerView!
@IBOutlet public var enterButton: UIButton!
@IBOutlet public var useArtsyLoginButton: UIButton!
public lazy var keypadSignal:RACSignal! = self.keypadContainer.keypad?.keypadSignal
public lazy var clearSignal:RACSignal! = self.keypadContainer.keypad?.rightSignal
public lazy var deleteSignal:RACSignal! = self.keypadContainer.keypad?.leftSignal
public lazy var provider:ReactiveMoyaProvider<ArtsyAPI> = Provider.sharedProvider
public class func instantiateFromStoryboard() -> ConfirmYourBidViewController {
return UIStoryboard.fulfillment().viewControllerWithID(.ConfirmYourBid) as ConfirmYourBidViewController
}
override public func viewDidLoad() {
super.viewDidLoad()
let titleString = useArtsyLoginButton.titleForState(useArtsyLoginButton.state)! ?? ""
var attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
NSFontAttributeName: useArtsyLoginButton.titleLabel!.font];
let attrTitle = NSAttributedString(string: titleString, attributes:attributes)
useArtsyLoginButton.setAttributedTitle(attrTitle, forState:useArtsyLoginButton.state)
RAC(numberAmountTextField, "text") <~ RACObserve(self, "number").map(toPhoneNumberString)
keypadSignal.subscribeNext(addDigitToNumber)
deleteSignal.subscribeNext(deleteDigitFromNumber)
clearSignal.subscribeNext(clearNumber)
let nav = self.fulfillmentNav()
RAC(nav.bidDetails.newUser, "phoneNumber") <~ RACObserve(self, "number")
RAC(nav.bidDetails, "paddleNumber") <~ RACObserve(self, "number")
bidDetailsPreviewView.bidDetails = nav.bidDetails
// Does a bidder exist for this phone number?
// if so forward to PIN input VC
// else send to enter email
if let nav = self.navigationController as? FulfillmentNavigationController {
let numberIsZeroLengthSignal = RACObserve(self, "number").map(isZeroLengthString)
enterButton.rac_command = RACCommand(enabled: numberIsZeroLengthSignal.not()) { [weak self] _ in
if (self == nil) {
return RACSignal.empty()
}
let endpoint: ArtsyAPI = ArtsyAPI.FindBidderRegistration(auctionID: nav.auctionID!, phone: self!.number)
return XAppRequest(endpoint, provider:self!.provider, parameters:endpoint.defaultParameters).filterStatusCode(400).doError { (error) -> Void in
// Due to AlamoFire restrictions we can't stop HTTP redirects
// so to figure out if we got 302'd we have to introspect the
// error to see if it's the original URL to know if the
// request suceedded
let moyaResponse = error.userInfo?["data"] as? MoyaResponse
let responseURL = moyaResponse?.response?.URL?.absoluteString?
if let responseURL = responseURL {
if (responseURL as NSString).containsString("v1/bidder/") {
self?.performSegue(.ConfirmyourBidBidderFound)
return
}
}
self?.performSegue(.ConfirmyourBidBidderNotFound)
return
}
}
}
}
func addDigitToNumber(input:AnyObject!) -> Void {
self.number = "\(self.number)\(input)"
}
func deleteDigitFromNumber(input:AnyObject!) -> Void {
self.number = dropLast(self.number)
}
func clearNumber(input:AnyObject!) -> Void {
self.number = ""
}
func toOpeningBidString(cents:AnyObject!) -> AnyObject! {
if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) {
return "Enter \(dollars) or more"
}
return ""
}
func toPhoneNumberString(number:AnyObject!) -> AnyObject! {
let numberString = number as String
if countElements(numberString) >= 7 {
return self.phoneNumberFormatter.stringForObjectValue(numberString)
} else {
return numberString
}
}
}
private extension ConfirmYourBidViewController {
@IBAction func dev_noPhoneNumberFoundTapped(sender: AnyObject) {
self.performSegue(.ConfirmyourBidArtsyLogin )
}
@IBAction func dev_phoneNumberFoundTapped(sender: AnyObject) {
self.performSegue(.ConfirmyourBidBidderFound)
}
}
| 5595198c231c2e7f2dea08573474bc75 | 38.595238 | 159 | 0.660854 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.