repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
SocialObjects-Software/AMSlideMenu
AMSlideMenu/Animation/Animators/AMSlidingBlurAnimator.swift
1
2657
// // AMSlidingBlureAnimator.swift // AMSlideMenu // // The MIT License (MIT) // // Created by : arturdev // Copyright (c) 2020 arturdev. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE import UIKit open class AMSlidingBlurAnimator: AMSlidingAnimatorProtocol { open var duration: TimeInterval = 0.25 open var maxBlurRadius: CGFloat = 0.2 let effectsView: BlurryOverlayView = { let view = BlurryOverlayView(effect: UIBlurEffect(style: .light)) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.isUserInteractionEnabled = false return view }() open func animate(leftMenuView: UIView, contentView: UIView, progress: CGFloat, animated: Bool, completion: (() -> Void)?) { if effectsView.superview == nil { effectsView.frame = contentView.bounds contentView.addSubview(effectsView) } self.effectsView.blur(amount: progress * maxBlurRadius, duration: animated ? duration : 0) DispatchQueue.main.asyncAfter(deadline: .now() + duration) { completion?() } } open func animate(rightMenuView: UIView, contentView: UIView, progress: CGFloat = 1, animated: Bool = true, completion: (() -> Void)? = nil) { if effectsView.superview == nil { effectsView.frame = contentView.bounds contentView.addSubview(effectsView) } self.effectsView.blur(amount: progress * maxBlurRadius, duration: animated ? duration : 0) DispatchQueue.main.asyncAfter(deadline: .now() + duration) { completion?() } } }
mit
nguyenantinhbk77/practice-swift
Notifications/Listening Notifications/Listening Notifications/AppDelegate.swift
2
1933
// // AppDelegate.swift // Listening Notifications // // Created by Domenico Solazzo on 15/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? /* The name of the notification that we are going to send */ class func notificationName() -> String{ return "SetPersonInfoNotification" } /* The first-name key in the user-info dictionary of our notification */ class func personInfoKeyFirstName () -> String{ return "firstName" } /* The last-name key in the user-info dictionary of our notification */ class func personInfoKeyLastName() -> String{ return "lastName" } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let person = Person() // Dictionary to be sent with the notification let additionalInfo = [ self.classForCoder.personInfoKeyFirstName(): "Domenico", self.classForCoder.personInfoKeyLastName(): "Solazzo" ] // Notification let notification = NSNotification(name: self.classForCoder.notificationName(), object: self, userInfo: additionalInfo) /* The person class is currently listening for this notification. That class will extract the first name and last name from it and set its own first name and last name based on the userInfo dictionary of the notification. */ NSNotificationCenter.defaultCenter().postNotification(notification) if let firstName = person.firstName{ println("Person's first name is: \(firstName)") } if let lastName = person.lastName{ println("Person's last name is: \(lastName)") } return true } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/11098-swift-sourcemanager-getmessage.swift
11
256
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S { func a( = { { protocol C { enum S { let a { class A { func a { class case ,
mit
digitalsurgeon/SwiftWebSocket
websocketserver/handler.swift
1
2639
// // handler.swift // websocketserver // // Created by Ahmad Mushtaq on 17/05/15. // Copyright (c) 2015 Ahmad Mushtaq. All rights reserved. // import Foundation @objc(Handler) class Handler : GCDAsyncSocketDelegate { var socket: GCDAsyncSocket? = nil func handle(var request:Request, var socket: GCDAsyncSocket) { self.socket = socket; socket.synchronouslySetDelegate(self) } func disconnect() { socket?.disconnect() } } @objc(HttpHandler) class HttpHandler : Handler { let folderPath : String let webRoot : String init (webRoot: String, folderPath: String) { self.webRoot = webRoot self.folderPath = folderPath } override func handle(var request:Request, var socket: GCDAsyncSocket) { super.handle(request, socket: socket) Swell.info("Http request for " + request.path) request.path.removeRange(webRoot.startIndex...webRoot.endIndex.predecessor()) if request.path.isEmpty { request.path = "index.html" } let filePath = folderPath + request.path let fileExists = NSFileManager.defaultManager() .fileExistsAtPath(filePath) var response = Response(socket: socket) response.setCode( fileExists ? .Ok : .NotFound ) if fileExists { response.setCode(.Ok) if request.path == "index.html" { var err: NSError if let data = NSMutableString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) { data.replaceOccurrencesOfString("$IP", withString: Server.getIFAddresses().first!, options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, data.length)) response.set(data: data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)) } } else { response.set(data:NSData(contentsOfFile: filePath)) } } else { response.setCode(.NotFound) } response.generateResponse() disconnect() } } @objc(DefaultHttpHandler) class DefaultHttpHandler:HttpHandler { init () { super.init(webRoot: "", folderPath: "") } override func handle(request: Request, socket: GCDAsyncSocket) { Swell.info("DefaultHttpHandler - handle") let response = Response(socket:socket) response.setCode(.NotFound) response.generateResponse() disconnect() } }
mit
hyperoslo/Brick
Sources/Shared/ItemConfigurable.swift
1
480
/** A class protocol that requires configure(item: Item), it can be applied to UI components to annotate that they are intended to use Item. */ public protocol ItemConfigurable: class { /** A configure method that is used on reference types that can be configured using a view model - parameter item: A inout Item so that the ItemConfigurable object can configure the view model width and height based on its UI components */ func configure(_ item: inout Item) }
mit
rawrjustin/Bridge
Example/BridgeTest/BridgeTest/ViewController.swift
2
500
// // ViewController.swift // BridgeTest // // Created by Justin Huang on 8/6/15. // Copyright © 2015 Zumper. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
mit
csontosgabor/Twitter_Post
Twitter_Post/NSTimer+Closure.swift
3
1625
// // NSTimer+Closure.swift // // Created by Sergey Demchenko on 11/5/15. // Copyright © 2015 antrix1989. All rights reserved. // import Foundation extension Timer { /** Creates and schedules a one-time `NSTimer` instance. - parameter delay: The delay before execution. - parameter handler: A closure to execute after `delay`. - returns: The newly-created `NSTimer` instance. */ class func schedule(delay: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer { let fireDate = delay + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes) return timer! } /** Creates and schedules a repeating `NSTimer` instance. - parameter repeatInterval: The interval between each execution of `handler`. Note that individual calls may be delayed; subsequent calls to `handler` will be based on the time the `NSTimer` was created. - parameter handler: A closure to execute after `delay`. - returns: The newly-created `NSTimer` instance. */ class func schedule(repeatInterval interval: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer { let fireDate = interval + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes) return timer! } }
mit
sarahspins/Loop
WatchApp Extension/Models/CarbEntryUserInfo.swift
2
2068
// // CarbEntryUserInfo.swift // Naterade // // Created by Nathan Racklyeft on 1/23/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation enum AbsorptionTimeType { case Fast case Medium case Slow } struct CarbEntryUserInfo { let value: Double let absorptionTimeType: AbsorptionTimeType let startDate: NSDate init(value: Double, absorptionTimeType: AbsorptionTimeType, startDate: NSDate) { self.value = value self.absorptionTimeType = absorptionTimeType self.startDate = startDate } } extension AbsorptionTimeType: RawRepresentable { typealias RawValue = Int init?(rawValue: RawValue) { switch rawValue { case 0: self = .Fast case 1: self = .Medium case 2: self = .Slow default: return nil } } var rawValue: RawValue { switch self { case .Fast: return 0 case .Medium: return 1 case .Slow: return 2 } } } extension CarbEntryUserInfo: RawRepresentable { typealias RawValue = [String: AnyObject] static let version = 1 static let name = "CarbEntryUserInfo" init?(rawValue: RawValue) { guard rawValue["v"] as? Int == self.dynamicType.version && rawValue["name"] as? String == CarbEntryUserInfo.name, let value = rawValue["cv"] as? Double, absorptionTimeRaw = rawValue["ca"] as? Int, absorptionTime = AbsorptionTimeType(rawValue: absorptionTimeRaw), startDate = rawValue["sd"] as? NSDate else { return nil } self.value = value self.startDate = startDate self.absorptionTimeType = absorptionTime } var rawValue: RawValue { return [ "v": self.dynamicType.version, "name": CarbEntryUserInfo.name, "cv": value, "ca": absorptionTimeType.rawValue, "sd": startDate ] } }
apache-2.0
lllyyy/LY
U17-master/U17/U17/Procedure/Base/View/UBaseTableViewCell.swift
1
573
// // UBaseTableViewCell.swift // U17 // // Created by charles on 2017/10/24. // Copyright © 2017年 None. All rights reserved. // import UIKit import Reusable class UBaseTableViewCell: UITableViewCell, Reusable { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func configUI() {} }
mit
lllyyy/LY
U17-master/U17/Pods/HandyJSON/Source/HexColorTransform.swift
1
3043
// // HexColorTransform.swift // ObjectMapper // // Created by Vitaliy Kuzmenko on 10/10/16. // Copyright © 2016 hearst. All rights reserved. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #else import Cocoa #endif open class HexColorTransform: TransformType { #if os(iOS) || os(tvOS) || os(watchOS) public typealias Object = UIColor #else public typealias Object = NSColor #endif public typealias JSON = String var prefix: Bool = false var alpha: Bool = false public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { alpha = alphaToJSON prefix = prefixToJSON } open func transformFromJSON(_ value: Any?) -> Object? { if let rgba = value as? String { if rgba.hasPrefix("#") { let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = String(rgba[index...]) return getColor(hex: hex) } else { return getColor(hex: rgba) } } return nil } open func transformToJSON(_ value: Object?) -> JSON? { if let value = value { return hexString(color: value) } return nil } fileprivate func hexString(color: Object) -> String { let comps = color.cgColor.components! let r = Int(comps[0] * 255) let g = Int(comps[1] * 255) let b = Int(comps[2] * 255) let a = Int(comps[3] * 255) var hexString: String = "" if prefix { hexString = "#" } hexString += String(format: "%02X%02X%02X", r, g, b) if alpha { hexString += String(format: "%02X", a) } return hexString } fileprivate func getColor(hex: String) -> Object? { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 return nil } } else { // "Scan hex error return nil } #if os(iOS) || os(tvOS) || os(watchOS) return UIColor(red: red, green: green, blue: blue, alpha: alpha) #else return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) #endif } }
mit
jad6/DataStore
DataStore/DatStore-CommonTests/DataStoreCloudTests.swift
1
974
// // DataStoreCloudTests.swift // DataStore // // Created by Jad Osseiran on 24/11/2014. // Copyright (c) 2015 Jad Osseiran. All rights reserved. // import XCTest import CoreData import DataStore class DataStoreCloudTests: DataStoreTests { override func setUp() { // delegateObject = self super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
bsd-2-clause
Monits/swift-compiler-crashes
crashes/23892-swift-archetypebuilder-resolvearchetype.swift
1
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/CodaFi (Robert Widmann) public protocol F { typealias A } class B<F : F where F.A == B<F>> { let c : F }
mit
ura14h/OpenCVSample
OpenCVSample_iOS/OpenCVSample_iOS/SceneDelegate.swift
1
2222
// // SceneDelegate.swift // OpenCVSample_iOS // // Created by Hiroki Ishiura on 2020/01/04. // Copyright © 2020 Hiroki Ishiura. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
odigeoteam/TableViewKit
Examples/Viper/TableViewKit+VIPER/AboutModule/AboutModuleProtocols.swift
1
678
import Foundation import UIKit protocol AboutWireFrameProtocol: class { func presentAboutViewModule(_ navigationController: UINavigationController) func presentHelpCenter() } protocol AboutPresenterProtocol: class { var router: AboutWireFrameProtocol? { get set } var view: AboutViewControllerProtocol? { get set } func showHelpCenter() func showFaq() func showContactUs() func showTermsAndConditions() func showFeedback() func showShareApp() func showRateApp() } protocol AboutViewControllerProtocol: class { var presenter: AboutPresenterProtocol? { get set } func presentMessage(_ message: String, title: String) }
mit
danielhour/DINC
DINC WatchKit Extension/NSDateExtensions.swift
1
711
// // NSDateExtensions.swift // DINC // // Created by dhour on 4/17/16. // Copyright © 2016 DHour. All rights reserved. // import Foundation extension Date { /** Gets the short weekday symbol for given date - returns: String */ func dayOfWeek() -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let symbols = formatter.shortWeekdaySymbols let myCalendar = Calendar(identifier: Calendar.Identifier.gregorian) let myComponents = (myCalendar as NSCalendar).components(.weekday, from: self) let weekDayIndex = myComponents.weekday!-1 return symbols![weekDayIndex] } }
mit
ahoppen/swift
test/DebugInfo/sugar.swift
32
948
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // Apart from typealiases, sugared types are just mangled as their desugared type. // // This test makes sure that we don't mess up type substitutions when mangling // types containing sugared types by virtue of all manglings getting round-tripped // through the remangler. let o: (Int?, Optional<Int>) = (nil, nil) let a: ([[Int]], [Array<Int>], Array<[Int]>, Array<Array<Int>>) = ([], [], [], []) let d: ([Int : Float], Dictionary<Int, Float>) = ([:], [:]) let p: (((((Int)))), Int) = (0, 0) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "$sSiXSq_SiSgtD", {{.*}}) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "$sSiXSaXSa_SaySiGXSaSaySiXSaGSayAAGtD", {{.*}}) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "$sSiSfXSD_SDySiSfGtD", {{.*}}) // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "$sSiXSpXSpXSpXSp_SitD", {{.*}})
apache-2.0
KeithPiTsui/Pavers
Pavers/Pavers.playground/Pages/GitHotFrontPage.xcplaygroundpage/Contents.swift
2
371
import Pavers import PaversUI import UIKit final class HitRepositoriesTableViewController: UIViewController { private lazy var tableView: UITableView = UITableView() override func viewDidLoad() { super.viewDidLoad() self.bindStyle() } private func bindStyle() { self.view.addSubview(self.tableView) } private func bindViewModel() { } }
mit
TENDIGI/Obsidian-UI-iOS
src/InputFormatter.swift
1
13202
// // InputFormatter.swift // Alfredo // // Created by Eric Kunz on 9/15/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation /// Formatting style options public enum InputFormattingType { /// Use with custom validation case none /// e.g. $00.00. Valid with any value greater than $0. case dollarAmount /// e.g. 00/00/0000 case date /// e.g. 00/00 case creditCardExpirationDate /// e.g. 0000 0000 0000 0000 - VISA/MASTERCARD case creditCardSixteenDigits /// e.g. 0000 000000 00000 - AMEX case creditCardFifteenDigits /// e.g. 000 case creditCardCVVThreeDigits /// e.g. 0000 case creditCardCVVFourDigits /// Allows any characters. Limits the character count and valid only when at limit case limitNumberOfCharacters(Int) /// Limits the count of numbers entered. Valid only at set limit case limitNumberOfDigits(Int) /// Only allows characters from the NSCharacterSet to be entered case limitToCharacterSet(CharacterSet) /// Any input with more than zero characters case anyLength } class InputFormatter { typealias inputTextFormatter = ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int))? typealias validChecker = ((_ input: String) -> Bool)? var formattingType = InputFormattingType.none fileprivate lazy var numberFormatter = NumberFormatter() fileprivate lazy var currencyFormatter = NumberFormatter() fileprivate lazy var dateFormatter = DateFormatter() init(type: InputFormattingType) { formattingType = type } var textFormatter: inputTextFormatter { switch self.formattingType { case .none: return nil case .dollarAmount: return formatCurrency case .date: return formatDate case .creditCardExpirationDate: return formatCreditCardExpirationDate case .creditCardSixteenDigits: return formatCreditCardSixteenDigits case .creditCardFifteenDigits: return formatCreditCardFifteenDigits case .creditCardCVVThreeDigits: return formatCreditCardCVVThreeDigits case .creditCardCVVFourDigits: return formatCreditCardCVVFourDigits case .limitNumberOfCharacters(let length): return limitToLength(length) case .limitNumberOfDigits(let length): return limitToDigitsWithLength(length) case .limitToCharacterSet(let characterSet): return limitToCharacterSet(characterSet) case .anyLength: return nil } } var validityChecker: validChecker { switch self.formattingType { case .none: return nil case .dollarAmount: return validateCurrency case .date: return isLength(10) case .creditCardExpirationDate: return isLength(5) case .creditCardSixteenDigits: return isLength(19) case .creditCardFifteenDigits: return isLength(17) case .creditCardCVVThreeDigits: return isLength(3) case .creditCardCVVFourDigits: return isLength(4) case .limitNumberOfCharacters(let numberOfCharacters): return isLength(numberOfCharacters) case .limitNumberOfDigits(let length): return isLength(length) case .limitToCharacterSet: return nil case .anyLength: return hasLength } } // MARK:- Formatters fileprivate func formatCurrency(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 21 else { return (text, cursorPosition) } } let (noSpecialsString, newCursorPosition) = removeNonDigits(text, cursorPosition: cursorPosition) let removedCharsCorrectedRange = NSRange(location: range.location + (newCursorPosition - cursorPosition), length: range.length) let (newText, _) = resultingString(noSpecialsString, newInput: newInput, range: removedCharsCorrectedRange, cursorPosition: newCursorPosition) currencyFormatter.numberStyle = .decimal let number = currencyFormatter.number(from: newText) ?? 0 let newValue = NSNumber(value: number.doubleValue / 100.0 as Double) currencyFormatter.numberStyle = .currency if let currencyString = currencyFormatter.string(from: newValue) { return (currencyString, cursorPosition + (currencyString.length - text.length)) } return (text, cursorPosition) } fileprivate func formatDate(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 10 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(2, "\\"), (4, "\\")]) } fileprivate func formatCreditCardExpirationDate(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 5 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(2, "\\")]) } fileprivate func formatCreditCardSixteenDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 19 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(4, " "), (8, " "), (12, " ")]) } fileprivate func formatCreditCardFifteenDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 17 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(4, " "), (10, " ")]) } fileprivate func formatCreditCardCVVThreeDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { return limitToDigitsAndLength(3, text: text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func formatCreditCardCVVFourDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { return limitToDigitsAndLength(4, text: text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func limitToDigitsAndLength(_ length: Int, text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { if text.length == length { return (text, cursorPosition) } else if !isDigit(Character(newInput)) { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func limitToLength(_ limit: Int) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitText(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if text.length == limit && newInput != "" { return (text, cursorPosition) } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitText } fileprivate func limitToDigitsWithLength(_ limit: Int) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitText(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < limit else { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitText } fileprivate func limitToCharacterSet(_ set: CharacterSet) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitToSet(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard newInput.rangeOfCharacter(from: set) != nil else { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitToSet } // MARK: Validators fileprivate func validateCurrency(_ text: String) -> Bool { currencyFormatter.numberStyle = .currency let number = currencyFormatter.number(from: text) ?? 0 return number.doubleValue > 0.0 } fileprivate func isLength(_ length: Int) -> ((_ text: String) -> Bool) { func checkLength(_ text: String) -> Bool { return text.length == length } return checkLength } fileprivate func hasLength(_ text: String) -> Bool { return text.length > 0 } // MARK:- Characters fileprivate func isDigit(_ character: Character) -> Bool { return isDigitOrCharacter("", character: character) } fileprivate func isDigitOrCharacter(_ additionalCharacters: String, character: Character) -> Bool { let digits = CharacterSet.decimalDigits let fullSet = NSMutableCharacterSet(charactersIn: additionalCharacters) fullSet.formUnion(with: digits) if isCharacter(character, aMemberOf: fullSet as CharacterSet) { return true } return false } func resultingString(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { guard range.location >= 0 else { return (text, cursorPosition) } let newText = (text as NSString).replacingCharacters(in: range, with: newInput) return (newText, cursorPosition + (newText.length - text.length)) } fileprivate func removeNonDigits(_ text: String, cursorPosition: Int) -> (String, Int) { var originalCursorPosition = cursorPosition let theText = text var digitsOnlyString = "" for i in 0 ..< theText.length { let characterToAdd = theText[i] if isDigit(characterToAdd) { let stringToAdd = String(characterToAdd) digitsOnlyString.append(stringToAdd) } else if i < cursorPosition { originalCursorPosition -= 1 } } return (digitsOnlyString, originalCursorPosition) } func insertCharactersAtIndexes(_ text: String, characters: [(Int, Character)], cursorPosition: Int) -> (String, Int) { var stringWithAddedChars = "" var newCursorPosition = cursorPosition for i in 0 ..< text.length { for (index, char) in characters { if index == i { stringWithAddedChars.append(char) if i < cursorPosition { newCursorPosition += 1 } } } let characterToAdd = text[i] let stringToAdd = String(characterToAdd) stringWithAddedChars.append(stringToAdd) } return (stringWithAddedChars, newCursorPosition) } func isCharacter(_ c: Character, aMemberOf set: CharacterSet) -> Bool { return set.contains(UnicodeScalar(String(c).utf16.first!)!) } fileprivate func removeNonDigitsAndAddCharacters(_ text: String, newInput: String, range: NSRange, cursorPosition: Int, characters: [(Int, Character)]) -> (String, Int) { let (onlyDigitsText, cursorPos) = removeNonDigits(text, cursorPosition: cursorPosition) let correctedRange = NSRange(location: range.location + (cursorPos - cursorPosition), length: range.length) let (newText, cursorAfterEdit) = resultingString(onlyDigitsText, newInput: newInput, range: correctedRange, cursorPosition: cursorPos) let (withCharacters, newCursorPosition) = insertCharactersAtIndexes(newText, characters: characters, cursorPosition: cursorAfterEdit) return (withCharacters, newCursorPosition) } }
mit
emilstahl/swift
test/IDE/dump_swift_lookup_tables.swift
6
1732
// RUN: %target-swift-ide-test -dump-importer-lookup-table -source-filename %s -import-objc-header %S/Inputs/swift_name.h > %t.log 2>&1 // RUN: FileCheck %s < %t.log // REQUIRES: objc_interop // CHECK: Base -> full name mappings: // CHECK-NEXT: Bar --> Bar // CHECK-NEXT: Blue --> Blue // CHECK-NEXT: Green --> Green // CHECK-NEXT: MyInt --> MyInt // CHECK-NEXT: Point --> Point // CHECK-NEXT: Rouge --> Rouge // CHECK-NEXT: SNColorChoice --> SNColorChoice // CHECK-NEXT: SomeStruct --> SomeStruct // CHECK-NEXT: __SNTransposeInPlace --> __SNTransposeInPlace // CHECK-NEXT: makeSomeStruct --> makeSomeStruct(x:y:), makeSomeStruct(x:) // CHECK-NEXT: x --> x // CHECK-NEXT: y --> y // CHECK-NEXT: z --> z // CHECK: Full name -> entry mappings: // CHECK-NEXT: Bar: // CHECK-NEXT: TU: SNFoo // CHECK-NEXT: Blue: // CHECK-NEXT: SNColorChoice: SNColorBlue // CHECK-NEXT: Green: // CHECK-NEXT: SNColorChoice: SNColorGreen // CHECK-NEXT: MyInt: // CHECK-NEXT: TU: SNIntegerType // CHECK-NEXT: Point: // CHECK-NEXT: TU: SNPoint // CHECK-NEXT: Rouge: // CHECK-NEXT: SNColorChoice: SNColorRed // CHECK-NEXT: SNColorChoice: // CHECK-NEXT: TU: SNColorChoice, SNColorChoice // CHECK-NEXT: SomeStruct: // CHECK-NEXT: TU: SNSomeStruct // CHECK-NEXT: __SNTransposeInPlace: // CHECK-NEXT: TU: SNTransposeInPlace // CHECK-NEXT: makeSomeStruct(x:): // CHECK-NEXT: TU: SNMakeSomeStructForX // CHECK-NEXT: makeSomeStruct(x:y:): // CHECK-NEXT: TU: SNMakeSomeStruct // CHECK-NEXT: x: // CHECK-NEXT: SNSomeStruct: X // CHECK-NEXT: SNPoint: x // CHECK-NEXT: y: // CHECK-NEXT: SNPoint: y // CHECK-NEXT: z: // CHECK-NEXT: SNPoint: z
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00268-swift-typechecker-typecheckexpression.swift
1
465
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var f = 1 var ate le class func f<T>() ->T -> <d>(() -> d) } }
apache-2.0
Anviking/Tentacle
Tentacle/Client.swift
1
8633
// // Client.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Argo import Foundation import ReactiveCocoa import Result extension Decodable { internal static func decode(JSON: NSDictionary) -> Result<DecodedType, DecodeError> { switch decode(.parse(JSON)) { case let .Success(object): return .Success(object) case let .Failure(error): return .Failure(error) } } } extension DecodeError: Hashable { public var hashValue: Int { switch self { case let .TypeMismatch(expected: expected, actual: actual): return expected.hashValue ^ actual.hashValue case let .MissingKey(string): return string.hashValue case let .Custom(string): return string.hashValue } } } public func ==(lhs: DecodeError, rhs: DecodeError) -> Bool { switch (lhs, rhs) { case let (.TypeMismatch(expected: expected1, actual: actual1), .TypeMismatch(expected: expected2, actual: actual2)): return expected1 == expected2 && actual1 == actual2 case let (.MissingKey(string1), .MissingKey(string2)): return string1 == string2 case let (.Custom(string1), .Custom(string2)): return string1 == string2 default: return false } } extension NSJSONSerialization { internal static func deserializeJSON(data: NSData) -> Result<NSDictionary, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary) } } extension NSURLRequest { internal static func create(server: Server, _ endpoint: Client.Endpoint, _ credentials: Client.Credentials?) -> NSURLRequest { let URL = NSURL(string: server.endpoint)!.URLByAppendingPathComponent(endpoint.path) let request = NSMutableURLRequest(URL: URL) request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept") if let userAgent = Client.userAgent { request.setValue(userAgent, forHTTPHeaderField: "User-Agent") } if let credentials = credentials { request.setValue(credentials.authorizationHeader, forHTTPHeaderField: "Authorization") } return request } } /// A GitHub API Client public final class Client { /// An error from the Client. public enum Error: Hashable, ErrorType { /// An error occurred in a network operation. case NetworkError(NSError) /// An error occurred while deserializing JSON. case JSONDeserializationError(NSError) /// An error occurred while decoding JSON. case JSONDecodingError(DecodeError) /// A status code and error that was returned from the API. case APIError(Int, GitHubError) /// The requested object does not exist. case DoesNotExist public var hashValue: Int { switch self { case let .NetworkError(error): return error.hashValue case let .JSONDeserializationError(error): return error.hashValue case let .JSONDecodingError(error): return error.hashValue case let .APIError(statusCode, error): return statusCode.hashValue ^ error.hashValue case .DoesNotExist: return 4 } } } /// Credentials for the GitHub API. internal enum Credentials { case Token(String) case Basic(username: String, password: String) var authorizationHeader: String { switch self { case let .Token(token): return "token \(token)" case let .Basic(username, password): let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! let encodedString = data.base64EncodedStringWithOptions([]) return "Basic \(encodedString)" } } } /// A GitHub API endpoint. internal enum Endpoint: Hashable { case ReleaseByTagName(owner: String, repository: String, tag: String) var path: String { switch self { case let .ReleaseByTagName(owner, repo, tag): return "/repos/\(owner)/\(repo)/releases/tags/\(tag)" } } var hashValue: Int { switch self { case let .ReleaseByTagName(owner, repo, tag): return owner.hashValue ^ repo.hashValue ^ tag.hashValue } } } /// The user-agent to use for API requests. public static var userAgent: String? /// The Server that the Client connects to. public let server: Server /// The Credentials for the API. private let credentials: Credentials? /// Create an unauthenticated client for the given Server. public init(_ server: Server) { self.server = server self.credentials = nil } /// Create an authenticated client for the given Server with a token. public init(_ server: Server, token: String) { self.server = server self.credentials = .Token(token) } /// Create an authenticated client for the given Server with a username and password. public init(_ server: Server, username: String, password: String) { self.server = server self.credentials = .Basic(username: username, password: password) } /// Fetch the release corresponding to the given tag in the given repository. /// /// If the tag exists, but there's not a correspoding GitHub Release, this method will return a /// `.DoesNotExist` error. This is indistinguishable from a nonexistent tag. public func releaseForTag(tag: String, inRepository repository: Repository) -> SignalProducer<Release, Error> { precondition(repository.server == server) return fetchOne(Endpoint.ReleaseByTagName(owner: repository.owner, repository: repository.name, tag: tag)) } /// Fetch an object from the API. internal func fetchOne<Object: Decodable where Object.DecodedType == Object>(endpoint: Endpoint) -> SignalProducer<Object, Error> { return NSURLSession .sharedSession() .rac_dataWithRequest(NSURLRequest.create(server, endpoint, credentials)) .mapError(Error.NetworkError) .flatMap(.Concat) { data, response -> SignalProducer<Object, Error> in let response = response as! NSHTTPURLResponse return SignalProducer .attempt { return NSJSONSerialization.deserializeJSON(data).mapError(Error.JSONDeserializationError) } .attemptMap { JSON in if response.statusCode == 404 { return .Failure(.DoesNotExist) } if response.statusCode >= 400 && response.statusCode < 600 { return GitHubError.decode(JSON) .mapError(Error.JSONDecodingError) .flatMap { .Failure(Error.APIError(response.statusCode, $0)) } } return Object.decode(JSON).mapError(Error.JSONDecodingError) } } } } public func ==(lhs: Client.Error, rhs: Client.Error) -> Bool { switch (lhs, rhs) { case let (.NetworkError(error1), .NetworkError(error2)): return error1 == error2 case let (.JSONDeserializationError(error1), .JSONDeserializationError(error2)): return error1 == error2 case let (.JSONDecodingError(error1), .JSONDecodingError(error2)): return error1 == error2 case let (.APIError(statusCode1, error1), .APIError(statusCode2, error2)): return statusCode1 == statusCode2 && error1 == error2 case (.DoesNotExist, .DoesNotExist): return true default: return false } } internal func ==(lhs: Client.Endpoint, rhs: Client.Endpoint) -> Bool { switch (lhs, rhs) { case let (.ReleaseByTagName(owner1, repo1, tag1), .ReleaseByTagName(owner2, repo2, tag2)): return owner1 == owner2 && repo1 == repo2 && tag1 == tag2 } }
mit
Suninus/SwiftFilePath
SwiftFilePath/Path.swift
1
3090
// // Path.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // public class Path { // MARK: - Class methods public class func isDir(path:NSString) -> Bool { var isDirectory: ObjCBool = false let isFileExists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory:&isDirectory) return isDirectory ? true : false } // MARK: - Instance properties and initializer lazy var fileManager = NSFileManager.defaultManager() public let path_string:String public init(_ p: String) { self.path_string = p } // MARK: - Instance val public var attributes:NSDictionary?{ get { return self.loadAttributes() } } public var asString: String { return path_string } public var exists: Bool { return fileManager.fileExistsAtPath(path_string) } public var isDir: Bool { return Path.isDir(path_string); } public var basename:NSString { return path_string.lastPathComponent } public var parent: Path{ return Path( path_string.stringByDeletingLastPathComponent ) } // MARK: - Instance methods public func toString() -> String { return path_string } public func remove() -> Result<Path,NSError> { assert(self.exists,"To remove file, file MUST be exists") var error: NSError? let result = fileManager.removeItemAtPath(path_string, error:&error) return result ? Result(success: self) : Result(failure: error!); } public func copyTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To copy file, file MUST be exists") var error: NSError? let result = fileManager.copyItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } public func moveTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To move file, file MUST be exists") var error: NSError? let result = fileManager.moveItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } private func loadAttributes() -> NSDictionary? { assert(self.exists,"File must be exists to load file.< \(path_string) >") var loadError: NSError? let result = self.fileManager.attributesOfItemAtPath(path_string, error: &loadError) if let error = loadError { println("Error< \(error.localizedDescription) >") } return result } } // MARK: - extension Path: Printable { public var description: String { return "\(NSStringFromClass(self.dynamicType))<path:\(path_string)>" } }
mit
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/SelfSizingSectionController.swift
4
3116
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. 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 import UIKit final class SelfSizingSectionController: ListSectionController { private var model: SelectionModel! override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 40, right: 0) minimumLineSpacing = 4 minimumInteritemSpacing = 4 } override func numberOfItems() -> Int { return model.options.count } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { let text = model.options[index] let cell: UICollectionViewCell switch model.type { case .none: guard let manualCell = collectionContext?.dequeueReusableCell(of: ManuallySelfSizingCell.self, for: self, at: index) as? ManuallySelfSizingCell else { fatalError() } manualCell.text = text cell = manualCell case .fullWidth: guard let manualCell = collectionContext?.dequeueReusableCell(of: FullWidthSelfSizingCell.self, for: self, at: index) as? FullWidthSelfSizingCell else { fatalError() } manualCell.text = text cell = manualCell case .nib: guard let nibCell = collectionContext?.dequeueReusableCell(withNibName: "NibSelfSizingCell", bundle: nil, for: self, at: index) as? NibSelfSizingCell else { fatalError() } nibCell.contentLabel.text = text cell = nibCell } return cell } override func didUpdate(to object: Any) { self.model = object as? SelectionModel } }
mit
frootloops/swift
stdlib/public/core/CString.swift
1
8164
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, this /// initializer replaces them with the Unicode replacement character /// (`"\u{FFFD}"`). /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Café" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Caf�" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. @_inlineable // FIXME(sil-serialize-all) public init(cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len) { _decodeCString( $0, as: UTF8.self, length: len, repairingInvalidCodeUnits: true)! } self = result } /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// This is identical to init(cString: UnsafePointer<CChar> but operates on an /// unsigned sequence of bytes. @_inlineable // FIXME(sil-serialize-all) public init(cString: UnsafePointer<UInt8>) { self = String.decodeCString( cString, as: UTF8.self, repairingInvalidCodeUnits: true)!.result } /// Creates a new string by copying and validating the null-terminated UTF-8 /// data referenced by the given pointer. /// /// This initializer does not try to repair ill-formed UTF-8 code unit /// sequences. If any are found, the result of the initializer is `nil`. /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "Optional(Café)" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "nil" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. @_inlineable // FIXME(sil-serialize-all) public init?(validatingUTF8 cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) guard let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len, { _decodeCString($0, as: UTF8.self, length: len, repairingInvalidCodeUnits: false) }) else { return nil } self = result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// When you pass `true` as `isRepairing`, this method replaces ill-formed /// sequences with the Unicode replacement character (`"\u{FFFD}"`); /// otherwise, an ill-formed sequence causes this method to stop decoding /// and return `nil`. /// /// The following example calls this method with pointers to the contents of /// two different `CChar` arrays---the first with well-formed UTF-8 code /// unit sequences and the second with an ill-formed sequence at the end. /// /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Café, false))" /// /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Caf�, true))" /// /// - Parameters: /// - cString: A pointer to a null-terminated code sequence encoded in /// `encoding`. /// - encoding: The Unicode encoding of the data referenced by `cString`. /// - isRepairing: Pass `true` to create a new string, even when the data /// referenced by `cString` contains ill-formed sequences. Ill-formed /// sequences are replaced with the Unicode replacement character /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new /// string if an ill-formed sequence is detected. /// - Returns: A tuple with the new string and a Boolean value that indicates /// whether any repairs were made. If `isRepairing` is `false` and an /// ill-formed sequence is detected, this method returns `nil`. @_inlineable // FIXME(sil-serialize-all) public static func decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { guard let cString = cString else { return nil } var end = cString while end.pointee != 0 { end += 1 } let len = end - cString return _decodeCString( cString, as: encoding, length: len, repairingInvalidCodeUnits: isRepairing) } } /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. @_inlineable // FIXME(sil-serialize-all) public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// This internal helper takes the string length as an argument. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, length: Int, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { let buffer = UnsafeBufferPointer<Encoding.CodeUnit>( start: cString, count: length) let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits( buffer, encoding: encoding, repairIllFormedSequences: isRepairing) return stringBuffer.map { (result: String(_storage: $0), repairsMade: hadError) } }
apache-2.0
mrdepth/Neocom
Neocom/Neocom/Home/MenuItems/CertificatesItem.swift
2
606
// // CertificatesItem.swift // Neocom // // Created by Artem Shimanski on 3/29/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI struct CertificatesItem: View { var body: some View { NavigationLink(destination: CertificateGroups()) { Icon(Image("certificates")) Text("Certificates") } } } struct CertificatesItem_Previews: PreviewProvider { static var previews: some View { NavigationView { List { CertificatesItem() }.listStyle(GroupedListStyle()) } } }
lgpl-2.1
micchyboy1023/Today
Today iOS App/Today iOS App/RSDFTodayDatePickerCollectionViewLayout.swift
1
451
// // RSDFTodayDatePickerCollectionViewLayout.swift // Today // // Created by UetaMasamichi on 9/10/16. // Copyright © 2016 Masamichi Ueta. All rights reserved. // import UIKit class RSDFTodayDatePickerCollectionViewLayout: RSDFDatePickerCollectionViewLayout { override func selfHeaderReferenceSize() -> CGSize { let size = super.selfHeaderReferenceSize() return CGSize(width: size.width, height: 32) } }
mit
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallSpinFadeLoader.swift
2
3771
// // NVActivityIndicatorAnimationBallSpinFadeLoader.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationBallSpinFadeLoader: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = -2 let circleSize = (size.width - 4 * circleSpacing) / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84] // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.4, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimaton = CAKeyframeAnimation(keyPath: "opacity") opacityAnimaton.keyTimes = [0, 0.5, 1] opacityAnimaton.values = [1, 0.3, 1] opacityAnimaton.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimaton] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 8 { let circle = circleAt(angle: CGFloat(M_PI_4 * Double(i)), size: circleSize, origin: CGPoint(x: x, y: y), containerSize: size, color: color) animation.beginTime = beginTime + beginTimes[i] circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } func circleAt(angle: CGFloat, size: CGFloat, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer { let radius = containerSize.width / 2 - size / 2 let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect( x: origin.x + radius * (cos(angle) + 1), y: origin.y + radius * (sin(angle) + 1), width: size, height: size) circle.frame = frame return circle } }
mit
kiliankoe/DVB
Sources/DVB/Models/RouteChange/RouteChange+ValidityPeriod.swift
1
412
import Foundation extension RouteChange { public struct ValidityPeriod { public let begin: Date public let end: Date? } } extension RouteChange.ValidityPeriod: Decodable { private enum CodingKeys: String, CodingKey { case begin = "Begin" case end = "End" } } extension RouteChange.ValidityPeriod: Equatable {} extension RouteChange.ValidityPeriod: Hashable {}
mit
siuying/SignalKit
SignalKitTests/Observables/SignalTests.swift
1
8716
// // SignalTests.swift // SignalKit // // Created by Yanko Dimitrov on 7/15/15. // Copyright (c) 2015 Yanko Dimitrov. All rights reserved. // import UIKit import XCTest class SignalTests: XCTestCase { let initialUserName = "John" var signal: Signal<Int>! var lock: MockLock! var userName: ObservableValue<String>! var signalsBag: SignalBag! override func setUp() { super.setUp() let observable = ObservableOf<Int>() lock = MockLock() signal = Signal<Int>(observable: observable, lock: lock) userName = ObservableValue<String>(value: initialUserName, lock: lock) signalsBag = SignalBag() } func testAddObserver() { signal.addObserver { _ in } XCTAssertEqual(signal.observersCount, 1, "Should add observer") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testRemoveObserver() { let observer = signal.addObserver { _ in } lock.lockCalled = false lock.unlockCalled = false observer.dispose() XCTAssertEqual(signal.observersCount, 0, "Should remove the observer") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testDispatch() { var result = 0 signal.addObserver { result = $0 } signal.dispatch(2) XCTAssertEqual(result, 2, "Should dispatch the new value") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testRemoveObservers() { signal.addObserver { _ in } signal.addObserver { _ in } signal.addObserver { _ in } signal.removeObservers() XCTAssertEqual(signal.observersCount, 0, "Should remove the observers") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testAddDisposableItem() { let item = MockDisposable() signal.addDisposable(item) XCTAssertEqual(signal.disposablesCount, 1, "Should add disposable item") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testDispose() { let item = MockDisposable() signal.addDisposable(item) signal.dispose() XCTAssertEqual(item.disposed, true, "Should call dispose on each disposable item") XCTAssertEqual(signal.observersCount, 0, "Should remove all observers") XCTAssertEqual(signal.disposablesCount, 0, "Should remove all disposables") XCTAssertEqual(lock.lockCalled, true, "Should perform lock") XCTAssertEqual(lock.unlockCalled, true, "Should perform unlock") XCTAssertEqual(lock.syncCounter, 0, "Should perform balanced calls to lock() / unlock()") } func testDisposeSignalSource() { let sourceSignal = MockSignal() signal.sourceSignal = sourceSignal signal.dispose() XCTAssertEqual(sourceSignal.disposed, true, "Should call the signal source to dispose") } /// MARK: Signal Extensions Tests func testNext() { var result = "" let signal = observe(userName).next { result = $0 } XCTAssertEqual(result, initialUserName, "Should add a new observer to the signal") } func testAddToSignalContainer() { var result = "" observe(userName) .next{ result = $0 } .addTo(signalsBag) userName.dispatch("Jane") XCTAssertEqual(signalsBag.signalsCount, 1, "Should add the signal chain to signal container") XCTAssertEqual(result, "Jane", "Should retain the signal chain") } func testMap() { var result: Int = 0 observe(userName) .map { count($0) } .next { result = $0 } .addTo(signalsBag) XCTAssertEqual(result, 4, "Should transform a signal of type T to signal of type U") } func testFilter() { var result: Int = 0 let number = ObservableOf<Int>() observe(number) .filter { $0 > 3 } .next { result = $0 } .addTo(signalsBag) number.dispatch(1) number.dispatch(4) number.dispatch(3) XCTAssertEqual(result, 4, "Should dispatch only the value that matches the filter predicate") } func testSkip() { var result: Int = 0 let number = ObservableOf<Int>() observe(number) .skip(2) .next { result = $0 } .addTo(signalsBag) number.dispatch(1) number.dispatch(4) number.dispatch(3) XCTAssertEqual(result, 3, "Should skip a certain number of dispatched values") } func testSkipWhenSignalDispatchesImmediately() { var result: Int = 0 let number = ObservableOf<Int>() number.dispatch(8) observe(number) .skip(2) .next { result = $0 } .addTo(signalsBag) number.dispatch(1) number.dispatch(4) number.dispatch(3) XCTAssertEqual(result, 3, "Should skip a certain number of dispatched values when the signal dispatches the latest value on addObserver") } func testDeliverOnMain() { let expectation = expectationWithDescription("Should deliver on main queue") let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) var dispatchCounter = 0 observe(userName) .deliverOn(.Main) .next { [weak expectation] _ in dispatchCounter += 1 if dispatchCounter == 2 && NSThread.isMainThread() == true { expectation?.fulfill() } } .addTo(signalsBag) userName.dispatch("John", on: .Background(queue)) waitForExpectationsWithTimeout(0.5, handler: nil) } func testDeliverOnBackgroundQueue() { let expectation = expectationWithDescription("Should deliver on background queue") let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) var dispatchCounter = 0 observe(userName) .deliverOn(.Background(queue)) .next { [weak expectation] _ in dispatchCounter += 1 if dispatchCounter == 2 && NSThread.isMainThread() == false { expectation?.fulfill() } } .addTo(signalsBag) dispatch_async(dispatch_get_main_queue()) { self.userName.dispatch("John") } waitForExpectationsWithTimeout(0.5, handler: nil) } func testBindToObservable() { let destination = ObservableValue<String>("") observe(userName) .bindTo(destination) .addTo(signalsBag) userName.dispatch("Jack") XCTAssertEqual(destination.value, "Jack", "Should bind a signal value to observable of the same type") } func testBindTo() { var result = "" observe(userName) .bindTo { result = $0 } .addTo(signalsBag) XCTAssertEqual(result, initialUserName, "Should bind the signal value") } }
mit
nghialv/MaterialKit
Source/MKEmbedDrawerControllerSegue.swift
2
576
// // MKEmbedDrawerControllerSegue.swift // MaterialKit // // Created by Rahul Iyer on 10/02/16. // Copyright © 2016 Le Van Nghia. All rights reserved. // import UIKit public class MKEmbedDrawerControllerSegue: UIStoryboardSegue { final override public func perform() { if let sourceViewController = sourceViewController as? MKSideDrawerViewController { sourceViewController.drawerViewController = destinationViewController } else { assertionFailure("SourceViewController must be MKDrawerViewController!") } } }
mit
Wakup/Wakup-iOS-SDK
Wakup/CouponAnnotationView.swift
1
2212
// // CouponAnnotationView.swift // Wakup // // Created by Guillermo Gutiérrez on 7/1/16. // Copyright © 2016 Yellow Pineapple. All rights reserved. // import Foundation import MapKit @objc open class ColorForTags: NSObject { public let tags: Set<String> public let color: UIColor public let mapIcon: String public init(tags: Set<String>, mapIcon: String, color: UIColor) { self.tags = tags self.color = color self.mapIcon = mapIcon } } open class CouponAnnotationView: MKAnnotationView { @objc open dynamic var mapPinSize = CGSize(width: 46, height: 60) @objc open dynamic var iconAndColorForTags: [ColorForTags] = [ ColorForTags(tags: ["restaurants"], mapIcon: "map-restaurant-pin", color: StyleKit.restaurantCategoryColor), ColorForTags(tags: ["leisure"], mapIcon: "map-leisure-pin", color: StyleKit.leisureCategoryColor), ColorForTags(tags: ["services"], mapIcon: "map-services-pin", color: StyleKit.servicesCategoryColor), ColorForTags(tags: ["shopping"], mapIcon: "map-shopping-pin", color: StyleKit.shoppingCategoryColor), ColorForTags(tags: [], mapIcon: "map-pin", color: StyleKit.corporateDarkColor) // Empty tag list for default pin and color ] func mapIconId(forOffer offer: Coupon) -> (String, UIColor) { let offerTags = Set(offer.tags) for element in iconAndColorForTags { if !offerTags.intersection(element.tags).isEmpty || element.tags.isEmpty { return (element.mapIcon, element.color) } } return ("map-pin", StyleKit.corporateDarkColor) } open override func layoutSubviews() { super.layoutSubviews() guard let couponAnnotation = annotation as? CouponAnnotation else { return } let iconFrame = CGRect(x: 0, y: 0, width: mapPinSize.width, height: mapPinSize.height) let (mapPinId, pinColor) = mapIconId(forOffer: couponAnnotation.coupon) let iconImage = CodeIcon(iconIdentifier: mapPinId).getImage(iconFrame, color: pinColor) image = iconImage centerOffset = CGPoint(x: 0, y: (-mapPinSize.height / 2) + 1) } }
mit
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Renderers/CandleStickChartRenderer.swift
20
9754
// // CandleStickChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class CandleStickChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: CandleChartDataProvider? public init(dataProvider: CandleChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } for set in candleData.dataSets as! [CandleChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint()) private var _bodyRect = CGRect() private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(context context: CGContext, dataSet: CandleChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency) else { return } let phaseX = _animator.phaseX let phaseY = _animator.phaseY let bodySpace = dataSet.bodySpace var entries = dataSet.yVals as! [CandleChartDataEntry] let minx = max(_minX, 0) let maxx = min(_maxX + 1, entries.count) CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.shadowWidth) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { // get the entry let e = entries[j] if (e.xIndex < _minX || e.xIndex > _maxX) { continue } // calculate the shadow _shadowPoints[0].x = CGFloat(e.xIndex) _shadowPoints[0].y = CGFloat(e.high) * phaseY _shadowPoints[1].x = CGFloat(e.xIndex) _shadowPoints[1].y = CGFloat(e.low) * phaseY trans.pointValuesToPixel(&_shadowPoints) // draw the shadow var shadowColor: UIColor! = nil if (dataSet.shadowColorSameAsCandle) { if (e.open > e.close) { shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j) } else if (e.open < e.close) { shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j) } } if (shadowColor === nil) { shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j); } CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeLineSegments(context, _shadowPoints, 2) // calculate the body _bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace _bodyRect.origin.y = CGFloat(e.close) * phaseY _bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x _bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y trans.rectValueToPixel(&_bodyRect) // draw body differently for increasing and decreasing entry if (e.open > e.close) { let color = dataSet.decreasingColor ?? dataSet.colorAt(j) if (dataSet.isDecreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else if (e.open < e.close) { let color = dataSet.increasingColor ?? dataSet.colorAt(j) if (dataSet.isIncreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else { CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeRect(context, _bodyRect) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } // if values are drawn if (candleData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { var dataSets = candleData.dataSets for (var i = 0; i < dataSets.count; i++) { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor let formatter = dataSet.valueFormatter let trans = dataProvider.getTransformer(dataSet.axisDependency) var entries = dataSet.yVals as! [CandleChartDataEntry] let minx = max(_minX, 0) let maxx = min(_maxX + 1, entries.count) var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY) let lineHeight = valueFont.lineHeight let yOffset: CGFloat = lineHeight + 5.0 for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++) { let x = positions[j].x let y = positions[j].y if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y)) { continue } let val = entries[j].high ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { let xIndex = indices[i].xIndex; // get the x-position let set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } let e = set.entryForXIndex(xIndex) as! CandleChartDataEntry! if (e === nil || e.xIndex != xIndex) { continue } let trans = dataProvider.getTransformer(set.axisDependency) CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let low = CGFloat(e.low) * _animator.phaseY let high = CGFloat(e.high) * _animator.phaseY let y = (low + high) / 2.0 _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
michael-yuji/spartanX
Sources/SXService.swift
2
4445
// Copyright (c) 2016, Yuji // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 9/5/16. // Copyright © 2016 yuuji. All rights reserved. // import struct Foundation.Data public typealias ShouldProceed = Bool public let YES = true public let NO = false /// a SXService is a protocol to define a service that can use in spartanX public protocol SXService { // this is here to support low-level optimization, for example, if we are sending pure http content with // static files, it is much less expensive to use sendfile() instead of send(), since it can implement by // both sendfile() and send(), the supportingMethods should include both. // when the service is nested in another service, for example TLS, sendfile is no longer available // but send() is still available, this supporting method here hints what kind of optimazation is available // in the end var supportingMethods: SendMethods { get set } /// What to do when a package is received /// /// - Parameters: /// - data: The payload received /// - connection: in which connection /// - Returns: depends on the payload, should the server retain this connection(true) or disconnect(false) /// - Throws: Raise an exception and handle with exceptionRaised() func received(data: Data, from connection: SXConnection) throws -> ShouldProceed /// Handle Raised exceptions raised in received() /// /// - Parameters: /// - exception: Which exception raised /// - connection: in which connection /// - Returns: should the server retain this connection(true) or disconnect(false) func exceptionRaised(_ exception: Error, on connection: SXConnection) -> ShouldProceed } /// a SXStreamService is smaliar to SXService that slightly powerful but can only use on stream connections /// a SXSrreamService can perform actions when a new connection is accepted, when a connection is going to /// terminate, and when a connection has terminated public protocol SXStreamService : SXService { func accepted(socket: SXClientSocket, as connection: SXConnection) throws func connectionWillTerminate(_ connection: SXConnection) func connectionDidTerminate(_ connection: SXConnection) } /// a simple data transfer service open class SXConnectionService: SXService { open func exceptionRaised(_ exception: Error, on connection: SXConnection) -> ShouldProceed { return false } open var supportingMethods: SendMethods = [.send, .sendfile, .sendto] open func received(data: Data, from connection: SXConnection) throws -> ShouldProceed { return try self.dataHandler(data, connection) } open var dataHandler: (Data, SXConnection) throws -> ShouldProceed public init(handler: @escaping (Data, SXConnection) throws -> ShouldProceed) { self.dataHandler = handler } }
bsd-2-clause
Lucky-Orange/Tenon
Pitaya/JSONNeverDie/Source/JSONNDModel.swift
1
2479
// The MIT License (MIT) // Copyright (c) 2015 JohnLui <wenhanlv@gmail.com> https://github.com/johnlui // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // JSONNDModel.swift // JSONNeverDie // // Created by 吕文翰 on 15/10/3. // import Foundation public class JSONNDModel: NSObject { public var JSONNDObject: JSONND! public required init(JSONNDObject json: JSONND) { self.JSONNDObject = json super.init() let mirror = Mirror(reflecting: self) for (k, v) in AnyRandomAccessCollection(mirror.children)! { if let key = k { let json = self.JSONNDObject[key] var valueWillBeSet: AnyObject? switch v { case _ as String: valueWillBeSet = json.stringValue case _ as Int: valueWillBeSet = json.intValue case _ as Float: valueWillBeSet = json.floatValue case _ as Bool: valueWillBeSet = json.boolValue default: break } self.setValue(valueWillBeSet, forKey: key) } } } public var jsonString: String? { get { return self.JSONNDObject?.jsonString } } public var jsonStringValue: String { get { return self.jsonString ?? "" } } }
mit
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Layouting/AABubbleBackgroundProcessor.swift
1
11188
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation private let ENABLE_LOGS = false /** Display list preprocessed list state */ class AAPreprocessedList: NSObject { // Array of items in list var items: [ACMessage]! // Map from rid to index of item var indexMap: [jlong: Int]! // Current settings of cell look and feel var cellSettings: [AACellSetting]! // Prepared layouts of cells var layouts: [AACellLayout]! // Height of item var heights: [CGFloat]! // Is item need to be force-udpated var forceUpdated: [Bool]! // Is item need to be soft-updated var updated: [Bool]! } /** Display list preprocessor. Used for performing all required calculations before collection is updated */ class AAListProcessor: NSObject, ARListProcessor { let layoutCache = AALayoutCache() let settingsCache = AACache<AACachedSetting>() let peer: ACPeer init(peer: ACPeer) { self.peer = peer } func process(withItems items: JavaUtilListProtocol, withPrevious previous: Any?) -> Any? { var objs = [ACMessage]() var indexes = [jlong: Int]() var layouts = [AACellLayout]() var settings = [AACellSetting]() var heights = [CGFloat]() var forceUpdates = [Bool]() var updates = [Bool]() autoreleasepool { let start = CFAbsoluteTimeGetCurrent() var section = start // Capacity objs.reserveCapacity(Int(items.size())) layouts.reserveCapacity(Int(items.size())) settings.reserveCapacity(Int(items.size())) heights.reserveCapacity(Int(items.size())) forceUpdates.reserveCapacity(Int(items.size())) updates.reserveCapacity(Int(items.size())) // Building content list and dictionary from rid to index list for i in 0..<items.size() { let msg = items.getWith(i) as! ACMessage indexes.updateValue(Int(i), forKey: msg.rid) objs.append(msg) } if ENABLE_LOGS { log("processing(items): \(CFAbsoluteTimeGetCurrent() - section)") } section = CFAbsoluteTimeGetCurrent() // Calculating cell settings // TODO: Cache and avoid recalculation of whole list for i in 0..<objs.count { settings.append(buildCellSetting(i, items: objs)) } if ENABLE_LOGS { log("processing(settings): \(CFAbsoluteTimeGetCurrent() - section)") } section = CFAbsoluteTimeGetCurrent() // Building cell layouts for i in 0..<objs.count { layouts.append(buildLayout(objs[i], layoutCache: layoutCache)) } if ENABLE_LOGS { log("processing(layouts): \(CFAbsoluteTimeGetCurrent() - section)") } section = CFAbsoluteTimeGetCurrent() // Calculating force and simple updates if let prevList = previous as? AAPreprocessedList { for i in 0..<objs.count { var isForced = false var isUpdated = false let obj = objs[i] let oldIndex: Int! = prevList.indexMap[obj.rid] if oldIndex != nil { // Check if layout keys are same // If text was replaced by media it might force-updated // If size of bubble changed you might to change layout key // to update it's size // TODO: In the future releases it might be implemented // in more flexible way if prevList.layouts[oldIndex].key != layouts[i].key { // Mark as forced update isForced = true // Hack for rewriting layout information // Removing layout from cache layoutCache.revoke(objs[i].rid) // Building new layout layouts[i] = buildLayout(objs[i], layoutCache: layoutCache) } else { // Otherwise check bubble settings to check // if it is changed and we need to recalculate size let oldSetting = prevList.cellSettings[oldIndex] let setting = settings[i] if setting != oldSetting { if setting.showDate != oldSetting.showDate { // Date separator change size so make cell for resize isForced = true } else { // Other changes doesn't change size, so just update content // without resizing isUpdated = true } } } } // Saving update state value if isForced { forceUpdates.append(true) updates.append(false) } else if isUpdated { forceUpdates.append(false) updates.append(true) } else { forceUpdates.append(false) updates.append(false) } } } else { for _ in 0..<objs.count { forceUpdates.append(false) updates.append(false) } } if ENABLE_LOGS { log("processing(updates): \(CFAbsoluteTimeGetCurrent() - section)") } section = CFAbsoluteTimeGetCurrent() // Updating cell heights // TODO: Need to implement width calculations too // to make bubble menu appear at right place for i in 0..<objs.count { let height = measureHeight(objs[i], setting: settings[i], layout: layouts[i]) heights.append(height) } if ENABLE_LOGS { log("processing(heights): \(CFAbsoluteTimeGetCurrent() - section)") } if ENABLE_LOGS { log("processing(all): \(CFAbsoluteTimeGetCurrent() - start)") } } // Put everything together let res = AAPreprocessedList() res.items = objs res.cellSettings = settings res.layouts = layouts res.heights = heights res.indexMap = indexes res.forceUpdated = forceUpdates res.updated = updates return res } /** Building Cell Setting: Information about decorators like date separator and clenching of bubbles */ func buildCellSetting(_ index: Int, items: [ACMessage]) -> AACellSetting { let current = items[index] let id = Int64(current.rid) let next: ACMessage! = index > 0 ? items[index - 1] : nil let prev: ACMessage! = index + 1 < items.count ? items[index + 1] : nil let cached: AACachedSetting! = settingsCache.pick(id) if cached != nil { if cached.isValid(prev, next: next) { return cached.cached } } var isShowDate = true var clenchTop = false var clenchBottom = false if (prev != nil) { isShowDate = !areSameDate(current, prev: prev) if !isShowDate { clenchTop = useCompact(current, next: prev) } } if (next != nil) { if areSameDate(next, prev: current) { clenchBottom = useCompact(current, next: next) } } let res = AACellSetting(showDate: isShowDate, clenchTop: clenchTop, clenchBottom: clenchBottom) settingsCache.cache(id, value: AACachedSetting(cached: res, prevId: prev?.rid, nextId: next?.rid)) return res } /** Checking if messages have same send day */ func areSameDate(_ source:ACMessage, prev: ACMessage) -> Bool { let calendar = Calendar.current let currentDate = Date(timeIntervalSince1970: Double(source.date)/1000.0) let currentDateComp = (calendar as NSCalendar).components([.day, .year, .month], from: currentDate) let nextDate = Date(timeIntervalSince1970: Double(prev.date)/1000.0) let nextDateComp = (calendar as NSCalendar).components([.day, .year, .month], from: nextDate) return (currentDateComp.year == nextDateComp.year && currentDateComp.month == nextDateComp.month && currentDateComp.day == nextDateComp.day) } /** Checking if it is good to make bubbles clenched */ func useCompact(_ source: ACMessage, next: ACMessage) -> Bool { if (source.content is ACServiceContent) { if (next.content is ACServiceContent) { return true } } else { if (next.content is ACServiceContent) { return false } if (source.senderId == next.senderId) { return true } } return false } func measureHeight(_ message: ACMessage, setting: AACellSetting, layout: AACellLayout) -> CGFloat { let content = message.content! var height = layout.height if content is ACServiceContent { height += AABubbleCell.bubbleTop height += AABubbleCell.bubbleBottom } else { height += (setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop) height += (setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom) } // Date separator if (setting.showDate) { height += AABubbleCell.dateSize } return height } func buildLayout(_ message: ACMessage, layoutCache: AALayoutCache) -> AACellLayout { var layout: AACellLayout! = layoutCache.pick(message.rid) if (layout == nil) { // Usually never happens layout = AABubbles.buildLayout(peer, message: message) layoutCache.cache(message.rid, value: layout!) } return layout } }
agpl-3.0
srn214/Floral
Floral/Pods/SwiftDate/Sources/SwiftDate/DateInRegion/DateInRegion+Compare.swift
2
11038
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: hello@danielemargutti.com // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation // MARK: - Comparing DateInRegion public func == (lhs: DateInRegion, rhs: DateInRegion) -> Bool { return (lhs.date.timeIntervalSince1970 == rhs.date.timeIntervalSince1970) } public func <= (lhs: DateInRegion, rhs: DateInRegion) -> Bool { let result = lhs.date.compare(rhs.date) return (result == .orderedAscending || result == .orderedSame) } public func >= (lhs: DateInRegion, rhs: DateInRegion) -> Bool { let result = lhs.date.compare(rhs.date) return (result == .orderedDescending || result == .orderedSame) } public func < (lhs: DateInRegion, rhs: DateInRegion) -> Bool { return lhs.date.compare(rhs.date) == .orderedAscending } public func > (lhs: DateInRegion, rhs: DateInRegion) -> Bool { return lhs.date.compare(rhs.date) == .orderedDescending } // The type of comparison to do against today's date or with the suplied date. /// /// - isToday: hecks if date today. /// - isTomorrow: Checks if date is tomorrow. /// - isYesterday: Checks if date is yesterday. /// - isSameDay: Compares date days /// - isThisWeek: Checks if date is in this week. /// - isNextWeek: Checks if date is in next week. /// - isLastWeek: Checks if date is in last week. /// - isSameWeek: Compares date weeks /// - isThisMonth: Checks if date is in this month. /// - isNextMonth: Checks if date is in next month. /// - isLastMonth: Checks if date is in last month. /// - isSameMonth: Compares date months /// - isThisYear: Checks if date is in this year. /// - isNextYear: Checks if date is in next year. /// - isLastYear: Checks if date is in last year. /// - isSameYear: Compare date years /// - isInTheFuture: Checks if it's a future date /// - isInThePast: Checks if the date has passed /// - isEarlier: Checks if earlier than date /// - isLater: Checks if later than date /// - isWeekday: Checks if it's a weekday /// - isWeekend: Checks if it's a weekend /// - isInDST: Indicates whether the represented date uses daylight saving time. /// - isMorning: Return true if date is in the morning (>=5 - <12) /// - isAfternoon: Return true if date is in the afternoon (>=12 - <17) /// - isEvening: Return true if date is in the morning (>=17 - <21) /// - isNight: Return true if date is in the morning (>=21 - <5) public enum DateComparisonType { // Days case isToday case isTomorrow case isYesterday case isSameDay(_ : DateRepresentable) // Weeks case isThisWeek case isNextWeek case isLastWeek case isSameWeek(_: DateRepresentable) // Months case isThisMonth case isNextMonth case isLastMonth case isSameMonth(_: DateRepresentable) // Years case isThisYear case isNextYear case isLastYear case isSameYear(_: DateRepresentable) // Relative Time case isInTheFuture case isInThePast case isEarlier(than: DateRepresentable) case isLater(than: DateRepresentable) case isWeekday case isWeekend // Day time case isMorning case isAfternoon case isEvening case isNight // TZ case isInDST } public extension DateInRegion { /// Decides whether a DATE is "close by" another one passed in parameter, /// where "Being close" is measured using a precision argument /// which is initialized a 300 seconds, or 5 minutes. /// /// - Parameters: /// - refDate: reference date compare against to. /// - precision: The precision of the comparison (default is 5 minutes, or 300 seconds). /// - Returns: A boolean; true if close by, false otherwise. func compareCloseTo(_ refDate: DateInRegion, precision: TimeInterval = 300) -> Bool { return (abs(date.timeIntervalSince(refDate.date)) <= precision) } /// Compare the date with the rule specified in the `compareType` parameter. /// /// - Parameter compareType: comparison type. /// - Returns: `true` if comparison succeded, `false` otherwise func compare(_ compareType: DateComparisonType) -> Bool { switch compareType { case .isToday: return compare(.isSameDay(region.nowInThisRegion())) case .isTomorrow: let tomorrow = DateInRegion(region: region).dateByAdding(1, .day) return compare(.isSameDay(tomorrow)) case .isYesterday: let yesterday = DateInRegion(region: region).dateByAdding(-1, .day) return compare(.isSameDay(yesterday)) case .isSameDay(let refDate): return calendar.isDate(date, inSameDayAs: refDate.date) case .isThisWeek: return compare(.isSameWeek(region.nowInThisRegion())) case .isNextWeek: let nextWeek = region.nowInThisRegion().dateByAdding(1, .weekOfYear) return compare(.isSameWeek(nextWeek)) case .isLastWeek: let lastWeek = region.nowInThisRegion().dateByAdding(-1, .weekOfYear) return compare(.isSameWeek(lastWeek)) case .isSameWeek(let refDate): guard weekOfYear == refDate.weekOfYear else { return false } // Ensure time interval is under 1 week return (abs(date.timeIntervalSince(refDate.date)) < 1.weeks.timeInterval) case .isThisMonth: return compare(.isSameMonth(region.nowInThisRegion())) case .isNextMonth: let nextMonth = region.nowInThisRegion().dateByAdding(1, .month) return compare(.isSameMonth(nextMonth)) case .isLastMonth: let lastMonth = region.nowInThisRegion().dateByAdding(-1, .month) return compare(.isSameMonth(lastMonth)) case .isSameMonth(let refDate): return (date.year == refDate.date.year) && (date.month == refDate.date.month) case .isThisYear: return compare(.isSameYear(region.nowInThisRegion())) case .isNextYear: let nextYear = region.nowInThisRegion().dateByAdding(1, .year) return compare(.isSameYear(nextYear)) case .isLastYear: let lastYear = region.nowInThisRegion().dateByAdding(-1, .year) return compare(.isSameYear(lastYear)) case .isSameYear(let refDate): return (date.year == refDate.date.year) case .isInTheFuture: return compare(.isLater(than: region.nowInThisRegion())) case .isInThePast: return compare(.isEarlier(than: region.nowInThisRegion())) case .isEarlier(let refDate): return ((date as NSDate).earlierDate(refDate.date) == date) case .isLater(let refDate): return ((date as NSDate).laterDate(refDate.date) == date) case .isWeekday: return !compare(.isWeekend) case .isWeekend: let range = calendar.maximumRange(of: Calendar.Component.weekday)! return (weekday == range.lowerBound || weekday == range.upperBound - range.lowerBound) case .isInDST: return region.timeZone.isDaylightSavingTime(for: date) case .isMorning: return (hour >= 5 && hour < 12) case .isAfternoon: return (hour >= 12 && hour < 17) case .isEvening: return (hour >= 17 && hour < 21) case .isNight: return (hour >= 21 || hour < 5) } } /// Returns a ComparisonResult value that indicates the ordering of two given dates based on /// their components down to a given unit granularity. /// /// - parameter date: date to compare. /// - parameter granularity: The smallest unit that must, along with all larger units /// - returns: `ComparisonResult` func compare(toDate refDate: DateInRegion, granularity: Calendar.Component) -> ComparisonResult { switch granularity { case .nanosecond: // There is a possible rounding error using Calendar to compare two dates below the minute granularity // So we've added this trick and use standard Date compare which return correct results in this case // https://github.com/malcommac/SwiftDate/issues/346 return date.compare(refDate.date) default: return region.calendar.compare(date, to: refDate.date, toGranularity: granularity) } } /// Compares whether the receiver is before/before equal `date` based on their components down to a given unit granularity. /// /// - Parameters: /// - refDate: reference date /// - orEqual: `true` to also check for equality /// - granularity: smallest unit that must, along with all larger units, be less for the given dates /// - Returns: Boolean func isBeforeDate(_ date: DateInRegion, orEqual: Bool = false, granularity: Calendar.Component) -> Bool { let result = compare(toDate: date, granularity: granularity) return (orEqual ? (result == .orderedSame || result == .orderedAscending) : result == .orderedAscending) } /// Compares whether the receiver is after `date` based on their components down to a given unit granularity. /// /// - Parameters: /// - refDate: reference date /// - orEqual: `true` to also check for equality /// - granularity: Smallest unit that must, along with all larger units, be greater for the given dates. /// - Returns: Boolean func isAfterDate(_ refDate: DateInRegion, orEqual: Bool = false, granularity: Calendar.Component) -> Bool { let result = compare(toDate: refDate, granularity: granularity) return (orEqual ? (result == .orderedSame || result == .orderedDescending) : result == .orderedDescending) } /// Compares equality of two given dates based on their components down to a given unit /// granularity. /// /// - parameter date: date to compare /// - parameter granularity: The smallest unit that must, along with all larger units, be equal for the given /// dates to be considered the same. /// /// - returns: `true` if the dates are the same down to the given granularity, otherwise `false` func isInside(date: DateInRegion, granularity: Calendar.Component) -> Bool { return (compare(toDate: date, granularity: granularity) == .orderedSame) } /// Return `true` if receiver data is contained in the range specified by two dates. /// /// - Parameters: /// - startDate: range upper bound date /// - endDate: range lower bound date /// - orEqual: `true` to also check for equality on date and date2, default is `true` /// - granularity: smallest unit that must, along with all larger units, be greater /// - Returns: Boolean func isInRange(date startDate: DateInRegion, and endDate: DateInRegion, orEqual: Bool = true, granularity: Calendar.Component = .nanosecond) -> Bool { return isAfterDate(startDate, orEqual: orEqual, granularity: granularity) && isBeforeDate(endDate, orEqual: orEqual, granularity: granularity) } // MARK: - Date Earlier/Later /// Return the earlier of two dates, between self and a given date. /// /// - Parameter date: The date to compare to self /// - Returns: The date that is earlier func earlierDate(_ date: DateInRegion) -> DateInRegion { return (self.date.timeIntervalSince1970 <= date.date.timeIntervalSince1970) ? self : date } /// Return the later of two dates, between self and a given date. /// /// - Parameter date: The date to compare to self /// - Returns: The date that is later func laterDate(_ date: DateInRegion) -> DateInRegion { return (self.date.timeIntervalSince1970 >= date.date.timeIntervalSince1970) ? self : date } }
mit
allenngn/firefox-ios
Storage/History.swift
14
2517
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared public class IgnoredSiteError: ErrorType { public var description: String { return "Ignored site." } } /** * The base history protocol for front-end code. * * Note that the implementation of these methods might be complicated if * the implementing class also implements SyncableHistory -- for example, * `clear` might or might not need to set a bunch of flags to upload deletions. */ public protocol BrowserHistory { func addLocalVisit(visit: SiteVisit) -> Success func clearHistory() -> Success func removeHistoryForURL(url: String) -> Success func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Result<Cursor<Site>>> func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Result<Cursor<Site>>> func getSitesByLastVisit(limit: Int) -> Deferred<Result<Cursor<Site>>> } /** * The interface that history storage needs to provide in order to be * synced by a `HistorySynchronizer`. */ public protocol SyncableHistory { /** * Make sure that the local place with the provided URL has the provided GUID. * Succeeds if no place exists with that URL. */ func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success /** * Delete the place with the provided GUID, and all of its visits. Succeeds if the GUID is unknown. */ func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Result<GUID>> func getModifiedHistoryToUpload() -> Deferred<Result<[(Place, [Visit])]>> func getDeletedHistoryToUpload() -> Deferred<Result<[GUID]>> /** * Chains through the provided timestamp. */ func markAsSynchronized([GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> func markAsDeleted(guids: [GUID]) -> Success /** * Clean up any metadata. */ func onRemovedAccount() -> Success } // TODO: integrate Site with this. public class Place { public let guid: GUID public let url: String public let title: String public init(guid: GUID, url: String, title: String) { self.guid = guid self.url = url self.title = title } }
mpl-2.0
radex/swift-compiler-crashes
crashes-fuzzing/21566-no-stacktrace.swift
11
250
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func < { { for { case { case [ { case let { { { { deinit { class case c, class }
mit
radex/swift-compiler-crashes
crashes-duplicates/19247-swift-type-walk.swift
11
2394
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct g: c func b<I : d<U : a { protocol A : B<d { { class B } class B<U : A") func a<H : A class d { } A { let a { { enum A ) -> Voi func d: A" struct g: a { } A { } protocol A : a { } struct B<T where T.h protocol A : a { { enum A : S class A : A case , protocol A : a { struct c: T.h protocol l : a<H : A") class b func f protocol A ) -> { g: C { class d<T where g: d , j where f enum S for c { let a { func b<I : a { class typealias e : d typealias e : a { } protocol A : T>: a<U : d class d<I : c: a { let a { protocol P { protocol A : d where H.Element == c : Any { func b<T where T.h: d struct B<d where h : B<T where f import CoreData let a { enum A { enum S protocol P { for c { struct g: T.Element == c : T: b<g : c: String { let : B<T where T>: a { class A : A") class d struct g: A") protocol A : d<T where T>: a let a { class B<T.h: d<I : a { class d class d<H : T>: d<U : a { protocol A { } import CoreData class d<T> ( ) class { class B<T where h : d where f: d where j : T.Element == d let a { class d: d: a<g : d { { class d<T.Element == c typealias F = 0 protocol c : a { protocol l : A") for c : T.Element == e) -> Voi A : c } { } } } let a { } struct g: d , j = " " " " class d struct B<U : Any { } class A { for c : c<H : a { " ") func f class d class d<T where f: a<I : c<I : String = d , j = d where T where g: B } A { A : a { struct c struct g: S<j : B var f = c : a<T where h : A struct c { protocol c { class d<T where T> Voi typealias F = d { } class A : Any { } protocol A ) -> Voi let a { class d<T where g: A") class b typealias e : B<T where T> { let a { protocol l : T>(v: String { struct c: T>: a { enum A { struct B protocol c : S A : a { } typealias b = 0 func b<T where T where g: a protocol A { protocol A : d enum S<d where h : a { { protocol A { protocol c { func a<T where g: a { class d class B } let : a<T where T> Voi } enum S func f " " " " " class d: d<T where h : d class B<U : String = d class A { let a { { let a { protocol A : a { class } } class B<g : B<T>: String = " { let a { class B<T where T where T>: d class A { class A { let a { let a { class d protocol c { typealias b = e) -> Voi } A { class d<T>: B<T where h: A } protocol A { let a { class d<T where H.Element =
mit
justin999/gitap
gitap/StateController+AlertHelper.swift
1
494
// // AlertHelper.swift // gitap // // Created by Koichi Sato on 1/9/17. // Copyright © 2017 Koichi Sato. All rights reserved. // import UIKit extension StateController { func presentAlert(title: String, message: String?, style: UIAlertControllerStyle, actions: [UIAlertAction], completion: (() -> Void)?) { Utils.presentAlert(inViewController: self.viewController, title: title, message: message, style: style, actions: actions, completion: completion) } }
mit
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Event/EventCell/BFEventLayout.swift
1
24167
// // BFEventLayout.swift // BeeFun // // Created by WengHengcong on 23/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit import YYText // 异步绘制导致的闪烁解决方案:https://github.com/ibireme/YYKit/issues/64 // https://github.com/ibireme/YYText/issues/103 /// 布局样式 /// /// - pullRequest: pull request /// - pushCommit: push commit /// - textPicture: 图文布局 /// - text: 文本布局 public enum EventLayoutStyle: Int { case pullRequest case pushCommit case textPicture case text } class BFEventLayout: NSObject { //数据 var event: ObjEvent? var style: EventLayoutStyle = .textPicture //布局 var eventTypeActionImage: String? { return BFEventParase.actionImage(event: event) } //上下左右留白 var marginTop: CGFloat = 0 var marginBottom: CGFloat = 0 var marginLeft: CGFloat = 0 var marginRight: CGFloat = 0 //action 图片 var actionHeight: CGFloat = 0 var actionSize: CGSize = CGSize.zero //时间 var timeHeight: CGFloat = 0 var timeLayout: YYTextLayout? //title var titleHeight: CGFloat = 0 var titleLayout: YYTextLayout? //---->>>> 内容区域 <<<<------- var actionContentHeight: CGFloat = 0 //actor 图片 var actorHeight: CGFloat = 0 var actorSize: CGSize = CGSize.zero //文字content内容 var textHeight: CGFloat = 0 var textLayout: YYTextLayout? //commit 内容 var commitHeight: CGFloat = 0 var commitLayout: YYTextLayout? //pull request detail var prDetailWidth: CGFloat = 0 //1 commit with .....文字的宽度 var prDetailHeight: CGFloat = 0 var prDetailLayout: YYTextLayout? var totalHeight: CGFloat = 0 init(event: ObjEvent?) { super.init() if event == nil { return } self.event = event layout() } /// 布局 func layout() { marginTop = 0 actionHeight = 0 timeHeight = 0 titleHeight = 0 actorHeight = 0 actionContentHeight = 0 textHeight = 0 commitHeight = 0 prDetailHeight = 0 marginBottom = 5 _layoutActionImage() _layoutTime() _layoutTitle() _layoutActorImage() _layoutTextContent() _layoutCommit() _layoutPRDetail() //计算高度 let timeMargin = BFEventConstants.TIME_Y let actorImgMargin = BFEventConstants.ACTOR_IMG_TOP let textMargin = BFEventConstants.TEXT_Y totalHeight = timeMargin+timeHeight+titleHeight+marginBottom style = BFEventParase.layoutType(event: event) switch style { case .pullRequest: totalHeight += textMargin + max(actorImgMargin+actorHeight, textHeight+prDetailHeight) case .pushCommit: totalHeight += textMargin + max(actorImgMargin+actorHeight, commitHeight) case .textPicture: totalHeight += textMargin + max(actorImgMargin+actorHeight, textHeight) case .text: break } actionContentHeight = totalHeight-timeMargin-timeHeight-titleHeight } private func _layoutActionImage() { actionHeight = BFEventConstants.ACTOR_IMG_WIDTH } private func _layoutTime() { timeHeight = 0 timeLayout = nil if let time = event?.created_at { if let showTime = BFTimeHelper.shared.readableTime(rare: time, prefix: nil) { let timeAtt = NSMutableAttributedString(string: showTime) let container = YYTextContainer(size: CGSize(width: BFEventConstants.TIME_W, height: CGFloat.greatestFiniteMagnitude)) timeAtt.yy_font = UIFont.bfSystemFont(ofSize: BFEventConstants.TIME_FONT_SIZE) let layout = YYTextLayout(container: container, text: timeAtt) timeLayout = layout timeHeight = timeLayout!.textBoundingSize.height } } } private func _layoutTitle() { titleHeight = 0 titleLayout = nil let titleText: NSMutableAttributedString = NSMutableAttributedString() //用户名 if let actorName = BFEventParase.actorName(event: event) { let actorAttriText = NSMutableAttributedString(string: actorName) actorAttriText.yy_setTextHighlight(actorAttriText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpUserDetailView(user: self.event?.actor) }, longPressAction: nil) titleText.append(actorAttriText) } let actionText = NSMutableAttributedString(string: BFEventParase.action(event: event)) titleText.append(actionText) //介于actor与repo中间的部分 if let type = event?.type { if type == .pushEvent { //[aure] pushed to [develop] at [AudioKit/AudioKit] if let ref = event?.payload?.ref { if let reponame = event?.repo?.name, let branch = ref.components(separatedBy: "/").last { //https://github.com/AudioKit/AudioKit/tree/develop let url = "https://github.com/"+reponame+"/tree/"+branch let branchText = NSMutableAttributedString(string: branch) branchText.yy_setTextHighlight(branchText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpWebView(url: url) }, longPressAction: nil) titleText.append(branchText) } } } else if type == .releaseEvent { //[ckrey] released [Session Manager and CoreDataPersistence] at [ckrey/MQTT-Client-Framework] if let releaseName = event?.payload?.release?.name, let releaseUrl = event?.payload?.release?.html_url { let releaseText = NSMutableAttributedString(string: releaseName) releaseText.yy_setTextHighlight(releaseText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpWebView(url: releaseUrl) }, longPressAction: nil) titleText.append(releaseText) titleText.append(NSMutableAttributedString(string: " at ")) } } else if type == .createEvent { //[ckrey] created [tag] [0.9.9] at [ckrey/MQTT-Client-Framework] if let tag = event?.payload?.ref { let tagText = NSMutableAttributedString(string: tag) tagText.yy_setTextHighlight(tagText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in //https://github.com/user/repo/tree/tag if let repoName = self.event?.repo?.name { let url = "https://github.com/"+repoName+"/tree/"+tag JumpManager.shared.jumpWebView(url: url) } }, longPressAction: nil) titleText.append(tagText) titleText.append(NSMutableAttributedString(string: " at ")) } } else if type == .forkEvent { //[cloudwu] forked [bkaradzic/bx] to [cloudwu/bx] if let repo = BFEventParase.repoName(event: event) { let repoAttrText = NSMutableAttributedString(string: repo) repoAttrText.yy_setTextHighlight(repoAttrText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpReposDetailView(repos: self.event?.repo, from: .other) }, longPressAction: nil) titleText.append(repoAttrText) titleText.append(NSMutableAttributedString(string: " to ")) } } else if type == .deleteEvent { if let branch = event?.payload?.ref { let branchText = NSMutableAttributedString(string: branch) branchText.yy_setTextHighlight(branchText.yy_rangeOfAll(), color: UIColor.bfLabelSubtitleTextColor, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in }, longPressAction: nil) titleText.append(branchText) titleText.append(NSMutableAttributedString(string: " at ")) } } else if type == .memberEvent { if let memberName = event?.payload?.member?.login { let memberText = NSMutableAttributedString(string: memberName) memberText.yy_setTextHighlight(memberText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpReposDetailView(repos: self.event?.repo, from: .other) }, longPressAction: nil) titleText.append(memberText) titleText.append(NSMutableAttributedString(string: " to ")) } } } //repos if let type = event?.type { if type == .forkEvent { if let user = BFEventParase.actorName(event: event), let repoName = event?.payload?.forkee?.name { let repoAttrText = NSMutableAttributedString(string: user+repoName) repoAttrText.yy_setTextHighlight(repoAttrText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpReposDetailView(repos: self.event?.repo, from: .other) }, longPressAction: nil) titleText.append(repoAttrText) } } else { if let repo = BFEventParase.repoName(event: event) { var actionNumberStr = "" if let actionNumber = event?.payload?.issue?.number { actionNumberStr = "#\(actionNumber)" } else if let actionNumber = event?.payload?.pull_request?.number { //https://github.com/user/repo/pull/number actionNumberStr = "#\(actionNumber)" } let repoAttrText = NSMutableAttributedString(string: " " + repo + "\(actionNumberStr)") repoAttrText.yy_setTextHighlight(repoAttrText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in if let eventType = self.event?.type { switch eventType { case .pullRequestEvent: JumpManager.shared.jumpWebView(url: self.event?.payload?.pull_request?.html_url) return default: break } } if let comment = self.event?.payload?.comment { JumpManager.shared.jumpWebView(url: comment.html_url) } else { JumpManager.shared.jumpReposDetailView(repos: self.event?.repo, from: .other) } }, longPressAction: nil) titleText.append(repoAttrText) } } } titleText.yy_font = UIFont.bfSystemFont(ofSize: BFEventConstants.TITLE_FONT_SIZE) let container = YYTextContainer(size: CGSize(width: BFEventConstants.TITLE_W, height: CGFloat.greatestFiniteMagnitude)) let layout = YYTextLayout(container: container, text: titleText) titleHeight = layout!.textBoundingSize.height titleLayout = layout } private func _layoutActorImage() { actorHeight = BFEventConstants.ACTOR_IMG_WIDTH } private func _layoutTextContent() { textHeight = 0 textLayout = nil let textText: NSMutableAttributedString = NSMutableAttributedString() if let type = event?.type { if type == .issueCommentEvent || type == .pullRequestReviewCommentEvent || type == .commitCommentEvent { if let commentBody = BFEventParase.contentBody(event: event) { let clipLength = 130 let commentBodyAttText = NSMutableAttributedString(string: commentBody) if commentBodyAttText.length > clipLength { let moreRange = NSRange(location: clipLength, length: commentBodyAttText.length-clipLength) commentBodyAttText.replaceCharacters(in: moreRange, with: YYTextManager.moreDotCharacterAttribute(count: 3)) } textText.append(commentBodyAttText) } } else if type == .issuesEvent { if let issueBody = BFEventParase.contentBody(event: event) { let clipLength = 130 let commentBodyAttText = NSMutableAttributedString(string: issueBody) if commentBodyAttText.length > clipLength { let moreRange = NSRange(location: clipLength, length: commentBodyAttText.length-clipLength) commentBodyAttText.replaceCharacters(in: moreRange, with: YYTextManager.moreDotCharacterAttribute(count: 3)) } textText.append(commentBodyAttText) } } else if type == .releaseEvent { if let releaseText = BFEventParase.contentBody(event: event) { let releaseAttText = NSMutableAttributedString(string: releaseText) textText.append(releaseAttText) } } else if type == .pullRequestEvent { if let pullRequestText = BFEventParase.contentBody(event: event) { let clipLength = 130 let pullRequestAttText = NSMutableAttributedString(string: pullRequestText) if pullRequestAttText.length > clipLength { let moreRange = NSRange(location: clipLength, length: pullRequestAttText.length-clipLength) pullRequestAttText.replaceCharacters(in: moreRange, with: YYTextManager.moreDotCharacterAttribute(count: 3)) } textText.append(pullRequestAttText) } } else if type == .gollumEvent { if let pages = event?.payload?.pages { let page: ObjPage = pages.first! let act = page.action! let actText = NSMutableAttributedString(string: act) textText.append(actText) textText.addBlankSpaceCharacterAttribute(1) //AFNetworking 3.0 Migration Guide 跳转 if let pageName = page.title { let pageNameText = NSMutableAttributedString(string: pageName) pageNameText.yy_setTextHighlight(pageNameText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpWebView(url: page.html_url) }, longPressAction: nil) textText.append(pageNameText) textText.addBlankSpaceCharacterAttribute(1) } //View the diff if let sha = page.sha { let shaText = NSMutableAttributedString(string: "View the diff>>") if let html_url = page.html_url { let jump_url = html_url + "/_compare/"+sha shaText.yy_setTextHighlight(shaText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in JumpManager.shared.jumpWebView(url: jump_url) }, longPressAction: nil) } textText.append(shaText) } } } textText.yy_font = UIFont.bfSystemFont(ofSize: BFEventConstants.TEXT_FONT_SIZE) let container = YYTextContainer(size: CGSize(width: BFEventConstants.TEXT_W, height: CGFloat.greatestFiniteMagnitude)) let layout = YYTextLayout(container: container, text: textText) textHeight = layout!.textBoundingSize.height textLayout = layout } } private func _layoutCommit() { commitHeight = 0 commitLayout = nil if let eventtype = event?.type { if eventtype != .pushEvent { return } } let pushText: NSMutableAttributedString = NSMutableAttributedString() let font = UIFont.bfSystemFont(ofSize: BFEventConstants.COMMIT_FONT_SIZE) if let commits = event?.payload?.commits { let allCommitText = NSMutableAttributedString() for (index, commit) in commits.reversed().enumerated() where index < 2 { if let hashStr = commit.sha?.substring(to: 6), let message = commit.message { let commitText = NSMutableAttributedString(string: hashStr) commitText.yy_setTextHighlight(commitText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in //跳转到具体commit if let reponame = self.event?.repo?.name, let sha = commit.sha { //https://github.com/user/repo/commit/sha let url = "https://github.com/"+reponame+"/commit/"+sha JumpManager.shared.jumpWebView(url: url) } }, longPressAction: nil) let messageText = NSMutableAttributedString(string: message) commitText.addBlankSpaceCharacterAttribute(2) commitText.append(messageText) commitText.addLineBreakCharacterAttribute() allCommitText.append(commitText) } } pushText.append(allCommitText) if commits.count == 2 { let moreText = NSMutableAttributedString(string: "View comparison for these 2 commits »") moreText.yy_setTextHighlight(moreText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in if let reponame = self.event?.repo?.name, let before = self.event?.payload?.before, let head = self.event?.payload?.head { //https://github.com/user/repo/comare/before_sha...header_sha let url = "https://github.com/"+reponame+"/compare/"+before+"..."+head JumpManager.shared.jumpWebView(url: url) } }, longPressAction: nil) pushText.append(moreText) } else if commits.count > 2 { //commist.count > 2 if let all = event?.payload?.distinct_size { let more = all - 2 var moreStr = "\(more) more cmmmit" if more > 0 { if more > 1 { moreStr.append("s >>") } else if more == 1 { moreStr.append(" >>") } let moreText = NSMutableAttributedString(string: moreStr) moreText.yy_setTextHighlight(moreText.yy_rangeOfAll(), color: UIColor.blue, backgroundColor: UIColor.white, userInfo: nil, tapAction: { (_, _, _, _) in if let reponame = self.event?.repo?.name, let before = self.event?.payload?.before, let head = self.event?.payload?.head { //https://github.com/user/repo/comare/before_sha...header_sha let url = "https://github.com/"+reponame+"/compare/"+before+"..."+head JumpManager.shared.jumpWebView(url: url) } }, longPressAction: nil) pushText.append(moreText) } } } pushText.yy_font = font let container = YYTextContainer(size: CGSize(width: BFEventConstants.COMMIT_W, height: CGFloat.greatestFiniteMagnitude)) let layout = YYTextLayout(container: container, text: pushText) commitHeight = layout!.textBoundingSize.height commitLayout = layout } } private func _layoutPRDetail() { prDetailHeight = 0 prDetailLayout = nil if let eventtype = event?.type { if eventtype != .pullRequestEvent { return } } let prDetailText: NSMutableAttributedString = NSMutableAttributedString() let font = UIFont.bfSystemFont(ofSize: BFEventConstants.PRDETAIL_FONT_SIZE) if let pull_request = event?.payload?.pull_request { if let commits = pull_request.commits, let additions = pull_request.additions, let deletions = pull_request.deletions { //图片 let size = CGSize(width: 10, height: 10) var image = UIImage(named: "event_commit_icon") if image != nil { image = UIImage(cgImage: image!.cgImage!, scale: 2.0, orientation: UIImageOrientation.up) let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .center, attachmentSize: size, alignTo: font, alignment: .center) prDetailText.append(imageText) prDetailText.addBlankSpaceCharacterAttribute(1) } //1 commit with 1 addition and 0 deletions let commitStirng = commits <= 1 ? "commit" : "commits" let additionString = additions == 1 ? "addition" : "additions" let deletionString = deletions == 1 ? "deletion" : "deletions" let detailString = "\(pull_request.commits!) " + commitStirng + " with " + "\(pull_request.additions!) " + additionString + " and " + "\(pull_request.deletions!) " + deletionString let textText = NSMutableAttributedString(string: detailString) prDetailText.append(textText) prDetailText.yy_font = font let container = YYTextContainer(size: CGSize(width: BFEventConstants.PRDETAIL_W, height: CGFloat.greatestFiniteMagnitude)) let layout = YYTextLayout(container: container, text: prDetailText) prDetailHeight = layout!.textBoundingSize.height prDetailWidth = layout!.textBoundingRect.width prDetailLayout = layout } } } }
mit
dunkelstern/FastString
src/appending.swift
1
3123
// Copyright (c) 2016 Johannes Schriewer. // // 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. /// String appending public extension FastString { /// Return new string by appending other string /// /// - parameter string: string to append /// - returns: new string instance with both strings concatenated public func appending(_ string: FastString) -> FastString { let result = FastString() if self.byteCount == 0 && string.byteCount == 0 { // 2 empty strings -> return empty string return result } let count = self.byteCount + string.byteCount let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1) memory[count] = 0 var index = 0 for c in self.buffer { memory[index] = c index += 1 } for c in string.buffer { memory[index] = c index += 1 } result.buffer.baseAddress!.deallocateCapacity(result.buffer.count + 1) result.buffer = UnsafeMutableBufferPointer(start: memory, count: count) return result } public func appending(_ string: String) -> FastString { return self.appending(FastString(string)) } /// Append string to self /// /// - parameter string: string to append public func append(_ string: FastString) { if string.byteCount == 0 { // Nothing to do return } let count = self.byteCount + string.byteCount let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1) memory[count] = 0 var index = 0 for c in self.buffer { memory[index] = c index += 1 } for c in string.buffer { memory[index] = c index += 1 } self.buffer.baseAddress!.deallocateCapacity(self.buffer.count + 1) self.buffer = UnsafeMutableBufferPointer(start: memory, count: count) } public func append(_ string: String) { self.append(FastString(string)) } } public func +(lhs: FastString, rhs: FastString) -> FastString { return lhs.appending(rhs) } public func +=(lhs: inout FastString, rhs: FastString) { lhs.append(rhs) } public func +(lhs: FastString, rhs: String) -> FastString { return lhs.appending(rhs) } public func +=(lhs: inout FastString, rhs: String) { lhs.append(rhs) } public func +(lhs: String, rhs: FastString) -> String { return lhs + rhs.description } public func +=(lhs: inout String, rhs: FastString) { lhs += rhs.description }
apache-2.0
BrothaStrut96/ProjectPUBG
AppDelegate.swift
1
4825
// // AppDelegate.swift // ProjectPUBG // // Created by Ruaridh Wylie on 01/10/2017. // Copyright © 2017 Ruaridh Wylie. All rights reserved. // import UIKit import CoreData import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //Initialise Firebase Project FirebaseApp.configure() UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable") return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "ProjectPUBG") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
eugeneego/utilities-ios
Legacy-iOSTests/Generated/PostLightTransformer.swift
1
1652
// Generated using Sourcery 0.16.2 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT import Foundation import CoreGraphics import Legacy // swiftlint:disable all struct PostLightTransformer: LightTransformer { typealias T = Post let userIdName = "userId" let idName = "id" let titleName = "title" let bodyName = "body" let userIdTransformer = NumberLightTransformer<Int64>() let idTransformer = NumberLightTransformer<Int64>() let titleTransformer = CastLightTransformer<String>() let bodyTransformer = CastLightTransformer<String>() func from(any value: Any?) -> T? { guard let dictionary = value as? [String: Any] else { return nil } guard let userId = userIdTransformer.from(any: dictionary[userIdName]) else { return nil } guard let id = idTransformer.from(any: dictionary[idName]) else { return nil } guard let title = titleTransformer.from(any: dictionary[titleName]) else { return nil } guard let body = bodyTransformer.from(any: dictionary[bodyName]) else { return nil } return T( userId: userId, id: id, title: title, body: body ) } func to(any value: T?) -> Any? { guard let value = value else { return nil } var dictionary: [String: Any] = [:] dictionary[userIdName] = userIdTransformer.to(any: value.userId) dictionary[idName] = idTransformer.to(any: value.id) dictionary[titleName] = titleTransformer.to(any: value.title) dictionary[bodyName] = bodyTransformer.to(any: value.body) return dictionary } }
mit
fawadsuhail/weather-app
WeatherApp/View Controllers/Home/HomeContract.swift
1
470
// // HomeContract.swift // WeatherApp // // Created by Fawad Suhail on 4/23/17. // Copyright © 2017 Fawad Suhail. All rights reserved. // import Foundation import UIKit protocol HomePresenterProtocol: BasePresenterProtocol { func didStartTyping() func didSelectSuggestion(suggestion: String) } protocol HomeViewProtocol: BaseViewProtocol { func showSuggestions(suggestions: [String]) func pushViewController(viewController: UIViewController) }
mit
stephentyrone/swift
test/Driver/Dependencies/check-interface-implementation-fine.swift
5
2444
/// The fine-grained dependency graph has implicit dependencies from interfaces to implementations. /// These are not presently tested because depends nodes are marked as depending in the interface, /// as of 1/9/20. But this test will check fail if those links are not followed. // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/check-interface-implementation-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./a.swift ./c.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled a.swift // CHECK-FIRST: Handled c.swift // CHECK-FIRST: Handled bad.swift // CHECK-RECORD-CLEAN-DAG: "./a.swift": [ // CHECK-RECORD-CLEAN-DAG: "./bad.swift": [ // CHECK-RECORD-CLEAN-DAG: "./c.swift": [ // RUN: touch -t 201401240006 %t/a.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental > %t/a.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=NEGATIVE-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-A %s < %t/main~buildrecord.swiftdeps // CHECK-A: Handled a.swift // CHECK-A: Handled bad.swift // NEGATIVE-A-NOT: Handled c.swift // CHECK-RECORD-A-DAG: "./a.swift": [ // CHECK-RECORD-A-DAG: "./bad.swift": !private [ // CHECK-RECORD-A-DAG: "./c.swift": !private [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix CHECK-BC %s // CHECK-BC-NOT: Handled a.swift // CHECK-BC-DAG: Handled bad.swift // CHECK-BC-DAG: Handled c.swift
apache-2.0
stephentyrone/swift
test/Sema/property_wrappers.swift
3
823
// RUN: %target-swift-frontend -typecheck -disable-availability-checking -dump-ast %s | %FileCheck %s struct Transaction { var state: Int? } @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value init(wrappedValue: Value, reset: @escaping (Value, inout Transaction) -> Void) { self.wrappedValue = wrappedValue } } // rdar://problem/59685601 // CHECK-LABEL: R_59685601 struct R_59685601 { // CHECK: tuple_expr implicit type='(wrappedValue: String, reset: (String, inout Transaction) -> Void)' // CHECK-NEXT: property_wrapper_value_placeholder_expr implicit type='String' // CHECK-NEXT: opaque_value_expr implicit type='String' // CHECK-NEXT: string_literal_expr type='String' @Wrapper(reset: { value, transaction in transaction.state = 10 }) private var value = "hello" }
apache-2.0
pvzig/SlackKit
SlackKit/Sources/ClientConnection.swift
2
390
// // ClientConnection.swift // SlackKit // // Created by Emory Dunn on 12/28/17. // import Foundation public class ClientConnection { public var client: Client? public var rtm: SKRTMAPI? public var webAPI: WebAPI? public init(client: Client?, rtm: SKRTMAPI?, webAPI: WebAPI?) { self.client = client self.rtm = rtm self.webAPI = webAPI } }
mit
raulriera/Bike-Compass
App/CityBikesKit/Location.swift
1
1222
// // Location.swift // Bike Compass // // Created by Raúl Riera on 23/04/2016. // Copyright © 2016 Raul Riera. All rights reserved. // import Foundation import Decodable import CoreLocation public struct Location { public let coordinates: CLLocationCoordinate2D public let city: String public let country: String private let countryCode: String } extension Location: Decodable { public static func decode(_ j: AnyObject) throws -> Location { return try Location( coordinates: CLLocationCoordinate2D(latitude: j => "latitude", longitude: j => "longitude"), city: j => "city", country: Location.transformCountryCodeToDisplayName(j => "country"), countryCode: j => "country" ) } static func transformCountryCodeToDisplayName(_ code: String) -> String { return Locale.system().displayName(forKey: Locale.Key.countryCode, value: code) ?? code } } extension Location: Encodable { public func encode() -> AnyObject { return ["latitude": coordinates.latitude, "longitude": coordinates.longitude, "city": city, "country": countryCode] } }
mit
superk589/CGSSGuide
DereGuide/Unit/Information/View/UnitInformationUnitCell.swift
2
4143
// // UnitInformationUnitCell.swift // DereGuide // // Created by zzk on 2017/5/20. // Copyright © 2017 zzk. All rights reserved. // import UIKit protocol UnitInformationUnitCellDelegate: class { func unitInformationUnitCell(_ unitInformationUnitCell: UnitInformationUnitCell, didClick cardIcon: CGSSCardIconView) } class UnitInformationUnitCell: UITableViewCell, CGSSIconViewDelegate { let selfLeaderSkillLabel = UnitLeaderSkillView() let friendLeaderSkillLabel = UnitLeaderSkillView() var iconStackView: UIStackView! weak var delegate: UnitInformationUnitCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(selfLeaderSkillLabel) selfLeaderSkillLabel.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.equalTo(10) make.right.equalTo(-10) } selfLeaderSkillLabel.arrowDirection = .down var icons = [UIView]() for _ in 0...5 { let icon = CGSSCardIconView() icon.delegate = self icons.append(icon) icon.snp.makeConstraints { (make) in make.height.equalTo(icon.snp.width) } } iconStackView = UIStackView(arrangedSubviews: icons) iconStackView.spacing = 5 iconStackView.distribution = .fillEqually contentView.addSubview(iconStackView) iconStackView.snp.makeConstraints { (make) in make.top.equalTo(selfLeaderSkillLabel.snp.bottom).offset(3) make.left.greaterThanOrEqualTo(10) make.right.lessThanOrEqualTo(-10) // make the view as wide as possible make.right.equalTo(-10).priority(900) make.left.equalTo(10).priority(900) // make.width.lessThanOrEqualTo(96 * 6 + 25) make.centerX.equalToSuperview() } contentView.addSubview(friendLeaderSkillLabel) friendLeaderSkillLabel.snp.makeConstraints { (make) in make.top.equalTo(iconStackView.snp.bottom).offset(3) make.left.equalTo(10) make.right.equalTo(-10) make.bottom.equalTo(-10) } friendLeaderSkillLabel.arrowDirection = .up friendLeaderSkillLabel.descLabel.textAlignment = .right selfLeaderSkillLabel.sourceView = icons[0] friendLeaderSkillLabel.sourceView = icons[5] selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(with unit: Unit) { for i in 0...5 { let member = unit[i] if let card = member.card, let view = iconStackView.arrangedSubviews[i] as? CGSSCardIconView { view.cardID = card.id } } if let selfLeaderRef = unit.leader.card { selfLeaderSkillLabel.setupWith(text: "\(NSLocalizedString("队长技能", comment: "队伍详情页面")): \(selfLeaderRef.leaderSkill?.name ?? NSLocalizedString("无", comment: ""))\n\(selfLeaderRef.leaderSkill?.localizedExplain ?? "")", backgroundColor: selfLeaderRef.attColor.mixed(withColor: .white)) } else { selfLeaderSkillLabel.setupWith(text: "", backgroundColor: UIColor.allType.mixed(withColor: .white)) } if let friendLeaderRef = unit.friendLeader.card { friendLeaderSkillLabel.setupWith(text: "\(NSLocalizedString("好友技能", comment: "队伍详情页面")): \(friendLeaderRef.leaderSkill?.name ?? "无")\n\(friendLeaderRef.leaderSkill?.localizedExplain ?? "")", backgroundColor: friendLeaderRef.attColor.mixed(withColor: .white)) } else { friendLeaderSkillLabel.setupWith(text: "", backgroundColor: UIColor.allType.mixed(withColor: .white)) } } func iconClick(_ iv: CGSSIconView) { delegate?.unitInformationUnitCell(self, didClick: iv as! CGSSCardIconView) } }
mit
jboullianne/EndlessTunes
EndlessSoundFeed/NavController.swift
1
985
// // NavController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/2/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit class NavController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
jondwillis/Swinject
Swinject/Container.swift
1
8704
// // Container.swift // Swinject // // Created by Yoichi Tagaya on 7/23/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Foundation /// The `Container` class represents a dependency injection container, which stores registrations of services /// and retrieves registered services with dependencies injected. /// /// **Example to register:** /// /// let container = Container() /// container.register(A.self) { _ in B() } /// container.register(X.self) { r in Y(a: r.resolve(A.self)!) } /// /// **Example to retrieve:** /// /// let x = container.resolve(X.self)! /// /// where `A` and `X` are protocols, `B` is a type conforming `A`, and `Y` is a type conforming `X` and depending on `A`. public final class Container { /// The shared singleton instance of `Container`. It can be used in *the service locator pattern*. public static let defaultContainer = Container() private var services = [ServiceKey: ServiceEntryBase]() private let parent: Container? private var resolutionPool = ResolutionPool() /// Instantiates a `Container`. public init() { self.parent = nil } /// Instantiates a `Container` that is a child container of the `Container` specified with `parent`. /// /// - Parameter parent: The parent `Container`. public init(parent: Container) { self.parent = parent } /// Removes all registrations in the container. public func removeAll() { services.removeAll() } /// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies. /// /// - Parameters: /// - serviceType: The service type to register. /// - name: A registration name, which is used to differenciate from other registrations /// that have the same service and factory types. /// - factory: The closure to specify how the service type is resolved with the dependencies of the type. /// It is invoked when the `Container` needs to instantiate the instance. /// It takes a `Resolvable` to inject dependencies to the instance, /// and returns the instance of the component type for the service. /// /// - Returns: A registered `ServiceEntry` to configure some settings fluently. public func register<Service>( serviceType: Service.Type, name: String? = nil, factory: Resolvable -> Service) -> ServiceEntry<Service> { return registerImpl(serviceType, factory: factory, name: name) } internal func registerImpl<Service, Factory>(serviceType: Service.Type, factory: Factory, name: String?) -> ServiceEntry<Service> { let key = ServiceKey(factoryType: factory.dynamicType, name: name) let entry = ServiceEntry(serviceType: serviceType, factory: factory) services[key] = entry return entry } } // MARK: - Extension for Storyboard extension Container { /// Adds a registration of the specified view or window controller that is configured in a storyboard. /// /// - Parameters: /// - controllerType: The controller type to register as a service type. /// The type is `UIViewController` in iOS, `NSViewController` or `NSWindowController` in OS X. /// - name: A registration name, which is used to differenciate from other registrations /// that have the same view or window controller type. /// - initCompleted: A closure to specifiy how the dependencies of the view or window controller are injected. /// It is invoked by the `Container` when the view or window controller is instantiated by `SwinjectStoryboard`. public func registerForStoryboard<C: Controller>(controllerType: C.Type, name: String? = nil, initCompleted: (Resolvable, C) -> ()) { let key = ServiceKey(factoryType: controllerType, name: name) let entry = ServiceEntry(serviceType: controllerType) entry.initCompleted = initCompleted services[key] = entry } internal func runInitCompleted<C: Controller>(controllerType: C.Type, controller: C, name: String? = nil) { resolutionPool.incrementDepth() defer { resolutionPool.decrementDepth() } let key = ServiceKey(factoryType: controllerType, name: name) if let entry = getEntry(key) { resolutionPool[key] = controller as Any if let completed = entry.initCompleted as? (Resolvable, C) -> () { completed(self, controller) } } } private func getEntry(key: ServiceKey) -> ServiceEntryBase? { return services[key] ?? self.parent?.getEntry(key) } } // MARK: - Resolvable extension Container: Resolvable { /// Retrieves the instance with the specified service type. /// /// - Parameter serviceType: The service type to resolve. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type is found in the `Container`. public func resolve<Service>( serviceType: Service.Type) -> Service? { return resolve(serviceType, name: nil) } /// Retrieves the instance with the specified service type and registration name. /// /// - Parameters: /// - serviceType: The service type to resolve. /// - name: The registration name. /// /// - Returns: The resolved service type instance, or nil if no registration for the service type and name is found in the `Container`. public func resolve<Service>( serviceType: Service.Type, name: String?) -> Service? { typealias FactoryType = Resolvable -> Service return resolveImpl(name) { (factory: FactoryType) in factory(self) } } internal func resolveImpl<Service, Factory>(name: String?, invoker: Factory -> Service) -> Service? { resolutionPool.incrementDepth() defer { resolutionPool.decrementDepth() } var resolvedInstance: Service? let key = ServiceKey(factoryType: Factory.self, name: name) if let (entry, fromParent) = getEntry(key) as (ServiceEntry<Service>, Bool)? { switch (entry.scope) { case .None, .Graph: resolvedInstance = resolveEntry(entry, key: key, invoker: invoker) case .Container: let ownEntry: ServiceEntry<Service> if fromParent { ownEntry = entry.copyExceptInstance() services[key] = ownEntry } else { ownEntry = entry } if ownEntry.instance == nil { ownEntry.instance = resolveEntry(entry, key: key, invoker: invoker) as Any } resolvedInstance = ownEntry.instance as? Service case .Hierarchy: if entry.instance == nil { entry.instance = resolveEntry(entry, key: key, invoker: invoker) as Any } resolvedInstance = entry.instance as? Service } } return resolvedInstance } private func getEntry<Service>(key: ServiceKey) -> (ServiceEntry<Service>, Bool)? { var fromParent = false var entry = services[key] as? ServiceEntry<Service> if entry == nil, let parent = self.parent { if let (parentEntry, _) = parent.getEntry(key) as (ServiceEntry<Service>, Bool)? { entry = parentEntry fromParent = true } } return entry.map { ($0, fromParent) } } private func resolveEntry<Service, Factory>(entry: ServiceEntry<Service>, key: ServiceKey, invoker: Factory -> Service) -> Service { let usesPool = entry.scope != .None if usesPool, let pooledInstance = resolutionPool[key] as? Service { return pooledInstance } let resolvedInstance = invoker(entry.factory as! Factory) if usesPool { if let pooledInstance = resolutionPool[key] as? Service { // An instance for the key might be added by the factory invocation. return pooledInstance } resolutionPool[key] = resolvedInstance as Any } if let completed = entry.initCompleted as? (Resolvable, Service) -> () { completed(self, resolvedInstance) } return resolvedInstance } }
mit
yeziahehe/Gank
Pods/Kingfisher/Sources/Utility/SizeExtensions.swift
1
4631
// // SizeExtensions.swift // Kingfisher // // Created by onevcat on 2018/09/28. // // Copyright (c) 2019 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreGraphics extension CGSize: KingfisherCompatible {} extension KingfisherWrapper where Base == CGSize { /// Returns a size by resizing the `base` size to a target size under a given content mode. /// /// - Parameters: /// - size: The target size to resize to. /// - contentMode: Content mode of the target size should be when resizing. /// - Returns: The resized size under the given `ContentMode`. public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize { switch contentMode { case .aspectFit: return constrained(size) case .aspectFill: return filling(size) case .none: return size } } /// Returns a size by resizing the `base` size by making it aspect fitting the given `size`. /// /// - Parameter size: The size in which the `base` should fit in. /// - Returns: The size fitted in by the input `size`, while keeps `base` aspect. public func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } /// Returns a size by resizing the `base` size by making it aspect filling the given `size`. /// /// - Parameter size: The size in which the `base` should fill. /// - Returns: The size be filled by the input `size`, while keeps `base` aspect. public func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } /// Returns a `CGRect` for which the `base` size is constrained to an input `size` at a given `anchor` point. /// /// - Parameters: /// - size: The size in which the `base` should be constrained to. /// - anchor: An anchor point in which the size constraint should happen. /// - Returns: The result `CGRect` for the constraint operation. public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect { let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0), y: anchor.y.clamped(to: 0.0...1.0)) let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height let r = CGRect(x: x, y: y, width: size.width, height: size.height) let ori = CGRect(origin: .zero, size: base) return ori.intersection(r) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension CGRect { func scaled(_ scale: CGFloat) -> CGRect { return CGRect(x: origin.x * scale, y: origin.y * scale, width: size.width * scale, height: size.height * scale) } } extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } }
gpl-3.0
ouyongyong/swiftPractice
gallery/galleryUITests/galleryUITests.swift
1
1240
// // galleryUITests.swift // galleryUITests // // Created by ouyongyong on 15/10/18. // Copyright © 2015年 kira. All rights reserved. // import XCTest class galleryUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
zcill/SwiftDemoCollection
Project 09- Add Photo Fome Camera Roll/Project9- Add Photo Fome Camera RollTests/Project9__Add_Photo_Fome_Camera_RollTests.swift
1
1089
// // Project9__Add_Photo_Fome_Camera_RollTests.swift // Project9- Add Photo Fome Camera RollTests // // Created by 朱立焜 on 16/4/14. // Copyright © 2016年 朱立焜. All rights reserved. // import XCTest @testable import Project9__Add_Photo_Fome_Camera_Roll class Project9__Add_Photo_Fome_Camera_RollTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
brendonjustin/EtherPlayer
EtherPlayer/AirPlay/StopRequester.swift
1
1361
// // StopRequester.swift // EtherPlayer // // Created by Brendon Justin on 5/5/16. // Copyright © 2016 Brendon Justin. All rights reserved. // import Cocoa class StopRequester: AirplayRequester { let relativeURL = "/stop" weak var delegate: StopRequesterDelegate? weak var requestCustomizer: AirplayRequestCustomizer? private var requestTask: NSURLSessionTask? func performRequest(baseURL: NSURL, sessionID: String, urlSession: NSURLSession) { guard requestTask == nil else { print("\(relativeURL) request already in flight, not performing another one.") return } let url = NSURL(string: relativeURL, relativeToURL: baseURL)! let request = NSMutableURLRequest(URL: url) requestCustomizer?.requester(self, willPerformRequest: request) let task = urlSession.dataTaskWithRequest(request) { [weak self] (data, response, error) in defer { self?.requestTask = nil } self?.delegate?.stoppedWithError(nil) } requestTask = task task.resume() } func cancelRequest() { requestTask?.cancel() requestTask = nil } } protocol StopRequesterDelegate: class { func stoppedWithError(error: NSError?) }
gpl-3.0
xiaoyouPrince/DYLive
DYLive/DYLive/Classes/Main/View/PageTitleView.swift
1
7415
// // PageTitleView.swift // DYLive // // Created by 渠晓友 on 2017/4/1. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // import UIKit /* 1. 封装PageTitileView --> view:scrollview:Label+手势 & lineView 2. 封装PageContentView --> uicollectionView->横向滚动的cell 3. 处理PageTitleView和PageContentView的逻辑 */ // MARK: - 定义自己代理 protocol PageTitleViewDelegate : AnyObject { // 这里只是方法的定义 --selectIndex index :分别是内部和外部属性 func pageTitleView(titleView : PageTitleView , selectIndex index : Int) } // MARK: - 定义常量 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // MARK: - 类的声明 class PageTitleView: UIView { // MARK: - 自定义属性 fileprivate var titles : [String] fileprivate var titleLabels : [UILabel] = [UILabel]() fileprivate var currentIndex : Int = 0 // 设置默认的当前下标为0 weak var delegate : PageTitleViewDelegate? // MARK: - 懒加载属性 fileprivate lazy var scrollView : UIScrollView = {[weak self] in let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.bounces = false scrollView.scrollsToTop = false return scrollView }(); fileprivate lazy var scrollLine : UIView = {[weak self] in let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }(); // MARK: - 自定制PageTitleView的构造方法 init(frame: CGRect, titles:[String]) { // 1.给自己的titles赋值 self.titles = titles // 2.通过frame构造实例变量 super.init(frame:frame) // 3.创建UI setupUI() } // 自定义构造方法必须重写initwithCoder方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI extension PageTitleView{ fileprivate func setupUI(){ // 1.添加对应的scrollview addSubview(scrollView) scrollView.frame = self.bounds // scrollView.backgroundColor = UIColor.yellow // 2.添加lable setupTitleLabels() // 3.添加底边线和可滑动的线 setupBottomLineAndScrollLines() } // MARK: - 添加label private func setupTitleLabels(){ // 0.对于有些只需要设置一遍的东西,放到外面来 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0.0 for (index,title) in titles.enumerated(){ // 1.创建Label let label = UILabel() // 2.设置对应的属性 label.text = title label.font = UIFont.systemFont(ofSize: 16.0) label.tag = index label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center // 3. 设置frame let labelX : CGFloat = CGFloat(index) * labelW label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 4.添加 scrollView.addSubview(label) // 5.添加到Label的数组中 titleLabels.append(label) // 6.给Label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } // MARK: - 设置底线 和 可以滚动的线 private func setupBottomLineAndScrollLines(){ let bottomLine = UIView() let bottomLineH : CGFloat = 0.5 bottomLine.backgroundColor = UIColor.gray bottomLine.frame = CGRect(x: 0, y: frame.height - bottomLineH , width: frame.width, height: bottomLineH) addSubview(bottomLine) guard let label = titleLabels.first else {return} label.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) scrollLine.frame = CGRect(x: label.bounds.origin.x, y: label.frame.origin.y+label.frame.height, width: label.frame.width, height: kScrollLineH) addSubview(scrollLine) } } // MARK: - 监听Label的点击 -- 必须使用@objc extension PageTitleView{ @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer){ // 1.取到当前的label guard let currentLabel = tapGes.view as? UILabel else { return } // 对当前的Index和当前Label的tag值进行对比,如果当前label就是选中的label就不变了,如果是跳到其他的Label就执行后面,修改对应的颜色 if currentLabel.tag == currentIndex { return } // 2.获取之前的label let oldLabel = titleLabels[currentIndex] // 3.设置文字颜色改变 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存新的当前下边值 currentIndex = currentLabel.tag // 5.滚动条的滚动 let scrollLinePosition : CGFloat = currentLabel.frame.origin.x UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLinePosition } // 6.通知代理做事情 delegate?.pageTitleView(titleView: self, selectIndex: currentIndex) } } // MARK: - 暴露给外界的方法 extension PageTitleView{ func setTitleWithProgress( progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
domenicosolazzo/practice-swift
Multipeer/Multipeer/Multipeer/ViewController.swift
1
6201
// // ViewController.swift // Multipeer // // Created by Domenico on 04/05/16. // Copyright © 2016 Domenico Solazzo. All rights reserved. // import UIKit import MultipeerConnectivity class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, MCSessionDelegate, MCBrowserViewControllerDelegate { @IBOutlet weak var collectionView: UICollectionView! var images = [UIImage]() var peerID: MCPeerID! var mcSession: MCSession! var mcAdvertiserAssistant: MCAdvertiserAssistant! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "Selfie Share" navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showConnectionPrompt)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(importPicture)) peerID = MCPeerID(displayName: UIDevice.current.name) mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required) mcSession.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageView", for: indexPath) if let imageView = cell.viewWithTag(1000) as? UIImageView { imageView.image = images[(indexPath as NSIndexPath).item] } return cell } func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) { dismiss(animated: true, completion: nil) } func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) { dismiss(animated: true, completion: nil) } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) { } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { switch state { case MCSessionState.connected: print("Connected: \(peerID.displayName)") case MCSessionState.connecting: print("Connecting: \(peerID.displayName)") case MCSessionState.notConnected: print("Not Connected: \(peerID.displayName)") } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { if let image = UIImage(data: data) { DispatchQueue.main.async { [unowned self] in self.images.insert(image, at: 0) self.collectionView.reloadData() } } } func importPicture() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var newImage: UIImage if let possibleImage = info[UIImagePickerControllerEditedImage] as? UIImage { newImage = possibleImage } else if let possibleImage = info[UIImagePickerControllerOriginalImage] as? UIImage { newImage = possibleImage } else { return } dismiss(animated: true, completion: nil) images.insert(newImage, at: 0) collectionView.reloadData() // 1 if mcSession.connectedPeers.count > 0 { // 2 if let imageData = UIImagePNGRepresentation(newImage) { // 3 do { try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable) } catch let error as NSError { let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(ac, animated: true, completion: nil) } } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func showConnectionPrompt() { let ac = UIAlertController(title: "Connect to others", message: nil, preferredStyle: .actionSheet) ac.addAction(UIAlertAction(title: "Host a session", style: .default, handler: startHosting)) ac.addAction(UIAlertAction(title: "Join a session", style: .default, handler: joinSession)) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(ac, animated: true, completion: nil) } func startHosting(_ action: UIAlertAction!) { mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "TheProject", discoveryInfo: nil, session: mcSession) mcAdvertiserAssistant.start() } func joinSession(_ action: UIAlertAction!) { let mcBrowser = MCBrowserViewController(serviceType: "TheProject", session: mcSession) mcBrowser.delegate = self present(mcBrowser, animated: true, completion: nil) } }
mit
davidgatti/IoT-Home-Automation
GarageOpener/GarageState.swift
3
2524
// // Settings.swift // GarageOpener // // Created by David Gatti on 6/8/15. // Copyright (c) 2015 David Gatti. All rights reserved. // import Foundation import Parse class GarageState { //MARK: Static static let sharedInstance = GarageState() //MARK: Variables var user: PFUser! var isOpen: Int = 0 var useCount: Int = 0 var lastUsed: NSDate = NSDate.distantPast() as NSDate //MARK: Get func get(completition:() -> ()) { var count: Int = 0 getLastUser { (result) -> Void in count++ } getUseCount { (result) -> Void in count++ } while true { if count == 2 { return completition() } } } private func getLastUser(completition:() -> ()) { let qHistory = PFQuery(className: "History") qHistory.orderByDescending("createdAt") qHistory.getFirstObjectInBackgroundWithBlock { (lastEntry: PFObject?, error) -> Void in self.isOpen = (lastEntry?.objectForKey("state") as? Int)! self.lastUsed = lastEntry!.createdAt! self.user = lastEntry?.objectForKey("user") as? PFUser self.user?.fetch() return completition() } } private func getUseCount(completition:() -> ()) { let qGarageDoor = PFQuery(className:"GarageDoor") qGarageDoor.getObjectInBackgroundWithId("eX9QCJGga5") { (garage: PFObject?, error: NSError?) -> Void in self.useCount = (garage!.objectForKey("useCount") as! Int) return completition() } } //MARK: Set func set(completition: (result: String) -> Void) { setHistory { (result) -> Void in } setGarageDoor { (result) -> Void in } } private func setHistory(completition: (result: String) -> Void) { let user = PFUser.currentUser() let history = PFObject(className: "History") history["user"] = user history["applianceID"] = "eX9QCJGga5" history["state"] = self.isOpen history.saveInBackground() } private func setGarageDoor(completition: (result: String) -> Void) { let query = PFObject(withoutDataWithClassName: "GarageDoor", objectId: "eX9QCJGga5") query["useCount"] = self.useCount query.saveInBackground() } }
apache-2.0
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleArrowLeft.swift
1
2057
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Leftwards arrow style: ← struct DynamicButtonStyleArrowLeft: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let rightPoint = CGPoint(x: offset.x + size, y: center.y) let headPoint = CGPoint(x: offset.x + lineWidth, y: center.y) let topPoint = CGPoint(x: offset.x + size / 3.2, y: center.y + size / 3.2) let bottomPoint = CGPoint(x: offset.x + size / 3.2, y: center.y - size / 3.2) let p1 = PathHelper.line(from: rightPoint, to: headPoint) let p2 = PathHelper.line(from: headPoint, to: topPoint) let p3 = PathHelper.line(from: headPoint, to: bottomPoint) pathVector = DynamicButtonPathVector(p1: p1, p2: p2, p3: p3, p4: p1) } /// "Arrow Left" style. static var styleName: String { return "Arrow Left" } }
apache-2.0
hrscy/TodayNews
News/News/Classes/Mine/View/PostCommentView.swift
1
8352
// // PostCommentView.swift // News // // Created by 杨蒙 on 2018/1/4. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import IBAnimatable class PostCommentView: UIView, NibLoadable { private lazy var emojiManger = EmojiManager() @IBOutlet weak var pageControlView: UIView! private lazy var pageControl: UIPageControl = { let pageControl = UIPageControl() pageControl.theme_currentPageIndicatorTintColor = "colors.currentPageIndicatorTintColor" pageControl.theme_pageIndicatorTintColor = "colors.pageIndicatorTintColor" return pageControl }() @IBOutlet weak var emojiView: UIView! @IBOutlet weak var emojiViewBottom: NSLayoutConstraint! @IBOutlet weak var collectionView: UICollectionView! // 包括 emoji 按钮和 pageControl @IBOutlet weak var toolbarHeight: NSLayoutConstraint! @IBOutlet weak var emojiButtonHeight: NSLayoutConstraint! /// 占位符 @IBOutlet weak var placeholderLabel: UILabel! /// 底部 view @IBOutlet weak var bottomView: UIView! /// 底部约束 @IBOutlet weak var bottomViewBottom: NSLayoutConstraint! /// textView @IBOutlet weak var textView: UITextView! /// textView 的高度 @IBOutlet weak var textViewHeight: NSLayoutConstraint! @IBOutlet weak var textViewBackgroundView: AnimatableView! /// 发布按钮 @IBOutlet weak var postButton: UIButton! /// 同时转发 @IBOutlet weak var forwardButton: UIButton! /// @ 按钮 @IBOutlet weak var atButton: UIButton! /// emoji 按钮 @IBOutlet weak var emojiButton: UIButton! /// emoji 按钮是否选中 var isEmojiButtonSelected = false { didSet { if isEmojiButtonSelected { emojiButton.isSelected = isEmojiButtonSelected UIView.animate(withDuration: 0.25, animations: { // 改变约束 self.changeConstraints() self.bottomViewBottom.constant = emojiItemWidth * 3 + self.toolbarHeight.constant + self.emojiViewBottom.constant self.layoutIfNeeded() }) // 判断 pageControlView 的子控件(pageControl)是否为 0 if pageControlView.subviews.count == 0 { pageControl.numberOfPages = emojiManger.emojis.count / 21 pageControl.center = pageControlView.center pageControlView.addSubview(pageControl) } } else { textView.becomeFirstResponder() } } } /// 改变约束 private func changeConstraints() { self.emojiButtonHeight.constant = 44 self.toolbarHeight.constant = self.emojiButtonHeight.constant + 20 self.emojiViewBottom.constant = isIPhoneX ? 34 : 0 } /// 重置约束 private func resetConstraints() { self.emojiButtonHeight.constant = 0 self.toolbarHeight.constant = 0 self.bottomViewBottom.constant = 0 self.emojiViewBottom.constant = 0 layoutIfNeeded() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { endEditing(true) // 如果 emoji 按钮选中了 if isEmojiButtonSelected { UIView.animate(withDuration: 0.25, animations: { // 重置约束 self.resetConstraints() }, completion: { (_) in self.removeFromSuperview() }) } else { removeFromSuperview() } } override func awakeFromNib() { super.awakeFromNib() width = screenWidth height = screenHeight bottomView.theme_backgroundColor = "colors.cellBackgroundColor" textViewBackgroundView.theme_backgroundColor = "colors.grayColor240" forwardButton.theme_setImage("images.loginReadButtonSelected", forState: .normal) atButton.theme_setImage("images.toolbar_icon_at_24x24_", forState: .normal) emojiButton.theme_setImage("images.toolbar_icon_emoji_24x24_", forState: .normal) emojiButton.theme_setImage("images.toolbar_icon_keyboard_24x24_", forState: .selected) /// 添加通知 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil) collectionView.collectionViewLayout = EmojiLayout() collectionView.ym_registerCell(cell: EmojiCollectionCell.self) } /// 键盘将要弹起 @objc private func keyboardWillShow(notification: Notification) { let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval UIView.animate(withDuration: duration) { // 改变约束 self.changeConstraints() self.bottomViewBottom.constant = frame.size.height self.layoutIfNeeded() } } /// 键盘将要隐藏 @objc private func keyboardWillBeHidden(notification: Notification) { let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval UIView.animate(withDuration: duration) { // 重置约束 self.resetConstraints() } } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: - 点击事件 extension PostCommentView { /// 发布按钮点击 @IBAction func postButtonClicked(_ sender: UIButton) { sender.isSelected = !sender.isSelected } /// @ 按钮点击 @IBAction func atButtonClicked(_ sender: UIButton) { } /// emoji 按钮点击 @IBAction func emojiButtonClicked(_ sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { // 说明需要弹起的是表情 textView.resignFirstResponder() isEmojiButtonSelected = true } else { // 说明需要弹起的是键盘 textView.becomeFirstResponder() } } } // MARK: - UITextViewDelegate extension PostCommentView: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { placeholderLabel.isHidden = textView.text.count != 0 postButton.setTitleColor((textView.text.count != 0) ? .blueFontColor() : .grayColor210(), for: .normal) let height = Calculate.attributedTextHeight(text: textView.attributedText, width: textView.width) if height <= 30 { textViewHeight.constant = 30 } else if height >= 80 { textViewHeight.constant = 80 } else { textViewHeight.constant = height } layoutIfNeeded() } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { // 当 textView 将要开始编辑的时候,设置 emoji 按钮不选中 emojiButton.isSelected = false return true } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource extension PostCommentView: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return emojiManger.emojis.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.ym_dequeueReusableCell(indexPath: indexPath) as EmojiCollectionCell cell.emoji = emojiManger.emojis[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { textView.setAttributedText(emoji: emojiManger.emojis[indexPath.item]) placeholderLabel.isHidden = textView.attributedText.length != 0 } func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentPage = scrollView.contentOffset.x / scrollView.width pageControl.currentPage = Int(currentPage + 0.5) } }
mit
nathawes/swift
test/NameLookup/scope_map_lookup_extension_extension.swift
26
247
// Ensure scope construction does not crash on this illegal code // RUN: not %target-swift-frontend -typecheck %s 2> %t.errors // RUN: %FileCheck %s <%t.errors // CHECK-NOT: Program arguments: private extension String { private extension String
apache-2.0
shmidt/ContactsPro
ContactsPro/ContactViewVC.swift
1
7466
// // ContactDetailVC.swift // ContactsPro // // Created by Dmitry Shmidt on 09/04/15. // Copyright (c) 2015 Dmitry Shmidt. All rights reserved. // import UIKit import RealmSwift class ContactViewVC: UITableViewController { private var notificationToken: NotificationToken? var person: Person! private lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .NoStyle return dateFormatter }() deinit{ let realm = Realm() if let notificationToken = notificationToken{ realm.removeNotification(notificationToken) } } override func viewDidLoad() { super.viewDidLoad() tableView.accessibilityLabel = "View Contact" tableView.accessibilityValue = person.fullName tableView.isAccessibilityElement = true tableView.tableFooterView = UIView() title = person.fullName setupTableViewUI() registerFormCells() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editVC") reloadData() notificationToken = Realm().addNotificationBlock {[unowned self] note, realm in println(ContactViewVC.self) println(note) // self.objects = self.array self.reloadData() } } func editVC(){ let vc = storyboard?.instantiateViewControllerWithIdentifier("ContactEditVC") as! ContactEditVC vc.person = person let nc = UINavigationController(rootViewController: vc) presentViewController(nc, animated: true, completion: nil) } func setupTableViewUI(){ tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sectionNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = indexPath.section switch section{ case Section.Notes: let note = person.notes[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.LabelTextTableViewCellID, forIndexPath: indexPath) as! LabelTextTableViewCell cell.label.text = dateFormatter.stringFromDate(note.date) cell.selectionStyle = .None cell.valueTextLabel.text = note.text return cell case Section.WeakPoints: let note = person.weakPoints[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.LabelTextTableViewCellID, forIndexPath: indexPath) as! LabelTextTableViewCell cell.label.text = dateFormatter.stringFromDate(note.date) cell.selectionStyle = .None cell.valueTextLabel.text = note.text return cell case Section.StrongPoints: let note = person.strongPoints[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.LabelTextTableViewCellID, forIndexPath: indexPath) as! LabelTextTableViewCell cell.label.text = dateFormatter.stringFromDate(note.date) cell.selectionStyle = .None cell.valueTextLabel.text = note.text return cell case Section.ToDo: let todo = person.todos[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.ListItemCell, forIndexPath: indexPath) as! ListItemCell cell.textValue = todo.text cell.isComplete = todo.isComplete cell.textField.enabled = false cell.didTapCheckBox({[unowned self] (completed) -> Void in println("didTapCheckBox") let realm = Realm() realm.beginWrite() todo.isComplete = completed realm.commitWrite() }) return cell default:() } let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TableViewCell.DefaultCellID, forIndexPath: indexPath) as! UITableViewCell return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = 0 switch section{ case Section.WeakPoints: rows = person.weakPoints.count case Section.StrongPoints: rows = person.strongPoints.count case Section.Notes: rows = person.notes.count case Section.ToDo: rows = person.todos.count default: rows = 0 } return rows } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("didSelectRowAtIndexPath") let section = indexPath.section if section == Section.ToDo{ let todo = person.todos[indexPath.row] let realm = Realm() realm.beginWrite() todo.isComplete = !todo.isComplete realm.commitWrite() } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if !editing{ switch section{ case Section.Notes: if person.notes.count == 0{ return nil } case Section.StrongPoints: if person.strongPoints.count == 0{ return nil } case Section.WeakPoints: if person.weakPoints.count == 0{ return nil } case Section.ToDo: if person.todos.count == 0{ return nil } default: return sectionNames[section] } } return sectionNames[section] } //MARK: - func reloadData(){ tableView.reloadData() } func registerFormCells(){ tableView.registerNib(UINib(nibName: Constants.TableViewCell.ListItemCell, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.ListItemCell) tableView.registerNib(UINib(nibName: Constants.TableViewCell.LabelTextTableViewCellID, bundle: nil), forCellReuseIdentifier: Constants.TableViewCell.LabelTextTableViewCellID) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: Constants.TableViewCell.DefaultCellID) } }
mit
jklausa/VlKeynr
VlKeynr/AppDelegate.swift
1
2158
// // AppDelegate.swift // VlKeynr // // Created by Michał Kałużny on 15.11.2014. // Copyright (c) 2014 Michał Kałużny. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
wscheper/HealthSurvey
Survey/DBExtensions.swift
1
1461
// // DBExtensions.swift // Survey // // Created by Wesley Scheper on 06/12/15. // Copyright © 2015 Wesley Scheper. All rights reserved. // import UIKit extension NSDate { // Creates and returns an NSDate from a date string in the yyyy-MM-dd'T'HH:mm:ss'Z' format class func dateFromString(dateString: String) -> NSDate { let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" return dateFormatter.dateFromString(dateString)! } // Returns a String in yyyy-MM-dd'T'HH:mm:ss'Z' format from the date func dateString() -> String { let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" return dateFormatter.stringFromDate(self) } // Returns a String in HH:mm:ss format from the date func simpleDateString() -> String { let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm:ss" return dateFormatter.stringFromDate(self) } } extension NSDateComponents { // Returns a string in HH:mm:ss format from the date components func simpleDateString() -> String { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let date = calendar!.dateFromComponents(self) return (date?.simpleDateString())! } }
mit
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/IntroductionSheetViewController/IntroductionSheetViewController.swift
1
2020
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import RxCocoa import RxSwift public final class IntroductionSheetViewController: UIViewController { private typealias AccessibilityIdentifiers = Accessibility.Identifier.IntroductionSheet // MARK: Private Properties private let bag = DisposeBag() private var viewModel: IntroductionSheetViewModel! // MARK: Private IBOutlets @IBOutlet private var thumbnail: UIImageView! @IBOutlet private var titleLabel: UILabel! @IBOutlet private var subtitleLabel: UILabel! @IBOutlet private var button: UIButton! // TICKET: IOS-2520 - Move Storyboardable Protocol to PlatformUIKit public static func make(with viewModel: IntroductionSheetViewModel) -> IntroductionSheetViewController { let storyboard = UIStoryboard(name: String(describing: self), bundle: .module) guard let controller = storyboard.instantiateInitialViewController() as? IntroductionSheetViewController else { fatalError("\(String(describing: self)) not found.") } controller.viewModel = viewModel return controller } override public func viewDidLoad() { super.viewDidLoad() button.setTitle(viewModel.buttonTitle, for: .normal) button.layer.cornerRadius = 4.0 button.rx.tap.bind { [weak self] _ in guard let self = self else { return } self.viewModel.onSelection() self.dismiss(animated: true, completion: nil) } .disposed(by: bag) titleLabel.text = viewModel.title subtitleLabel.text = viewModel.description thumbnail.image = viewModel.thumbnail applyAccessibility() } private func applyAccessibility() { button.accessibility = .id(AccessibilityIdentifiers.doneButton) titleLabel.accessibility = .id(AccessibilityIdentifiers.titleLabel) subtitleLabel.accessibility = .id(AccessibilityIdentifiers.subtitleLabel) } }
lgpl-3.0
modocache/swift
test/IRGen/method_linkage.swift
3
1456
// RUN: %target-swift-frontend -primary-file %s -emit-ir | %FileCheck %s // Test if all methods which go into a vtable have at least the visibility of its class. // Reason: Derived classes from "outside" still have to put the less visible base members // into their vtables. class Base { // CHECK: define hidden void @_TFC14method_linkage4Base{{.*}}3foofT_T_ @inline(never) fileprivate func foo() { } // CHECK: define internal void @_TFC14method_linkage4Base{{.*}}3barfT_T_ @inline(never) fileprivate final func bar() { } // CHECK: define hidden void @_TFC14method_linkage4Base{{.*}}5otherfT_T_ @inline(never) fileprivate func other() { } } class Derived : Base { // CHECK: define hidden void @_TFC14method_linkage7Derived{{.*}}3foofT_T_ @inline(never) fileprivate final override func foo() { } } extension Base { // CHECK: define internal void @_TFC14method_linkage4Base{{.*}}7extfuncfT_T_ @inline(never) fileprivate func extfunc() { } } public class PublicClass { // CHECK: define{{( protected)?}} void @_TFC14method_linkage11PublicClass{{.*}}4pfoofT_T_ @inline(never) fileprivate func pfoo() { } // CHECK: define{{( protected)?}} void @_TFC14method_linkage11PublicClass4pbarfT_T_ @inline(never) internal func pbar() { } } // Just in case anyone wants to delete unused methods... func callit(b: Base, p: PublicClass) { b.foo() b.bar() b.other() b.extfunc() p.pfoo() p.pbar() }
apache-2.0
adi2004/super-memo2-pod
Example/Pods/ADISuperMemo2/Classes/Card.swift
2
1613
// // Card.swift // Pods // // Created by Adrian Florescu on 30/11/2016. // // import Foundation public class Card { public let question: String public let answer: String public var repetition: Int public var eFactor: Double public var repeatOn: Date var interval: Double public init(question q:String, answer a: String, repetition r: Int = 0, eFactor e: Double = 2.5) { self.question = q self.answer = a self.repetition = r self.eFactor = e self.repeatOn = Date() self.interval = 0 } public func update(with assessment:Double) { if (assessment < 3) { repetition = 0 // eFactor remains unchanged interval = 0 repeatOn = Date() } else { repetition += 1 if repetition == 1 { interval = 1 } else if repetition == 2 { interval = 6 } else { interval = interval * eFactor } repeatOn = Date(timeIntervalSinceNow: interval * 24 * 3600) eFactor = eFactor - 0.8 + 0.28 * assessment - 0.02 * assessment * assessment eFactor = setBounds(eFactor) } } private func setBounds(_ element: Double) -> Double { guard element < 1.3 else { return 1.3 } guard element > 2.5 else { return 2.5 } return element } public func repetitionInterval() -> Int { //print(interval) return Int(interval + 0.5) } }
mit
nodes-ios/NStack
Pods/Quick/Sources/Quick/NSString+C99ExtendedIdentifier.swift
17
1517
#if canImport(Darwin) import Foundation extension NSString { private static var invalidCharacters: CharacterSet = { var invalidCharacters = CharacterSet() let invalidCharacterSets: [CharacterSet] = [ .whitespacesAndNewlines, .illegalCharacters, .controlCharacters, .punctuationCharacters, .nonBaseCharacters, .symbols ] for invalidSet in invalidCharacterSets { invalidCharacters.formUnion(invalidSet) } return invalidCharacters }() /// This API is not meant to be used outside Quick, so will be unavailable in /// a next major version. @objc(qck_c99ExtendedIdentifier) public var c99ExtendedIdentifier: String { let validComponents = components(separatedBy: NSString.invalidCharacters) let result = validComponents.joined(separator: "_") return result.isEmpty ? "_" : result } } /// Extension methods or properties for NSObject subclasses are invisible from /// the Objective-C runtime on static linking unless the consumers add `-ObjC` /// linker flag, so let's make a wrapper class to mitigate that situation. /// /// See: https://github.com/Quick/Quick/issues/785 and https://github.com/Quick/Quick/pull/803 @objc class QCKObjCStringUtils: NSObject { override private init() {} @objc static func c99ExtendedIdentifier(from string: String) -> String { return string.c99ExtendedIdentifier } } #endif
mit
lannik/SSImageBrowser
Example/Tests/Tests.swift
2
1190
// https://github.com/Quick/Quick import Quick import Nimble import SSImageBrowser class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
3DprintFIT/octoprint-ios-client
OctoPhoneTests/VIew Related/Slicing Profiles/SlicingProfileCellTests.swift
1
2749
// // SlicingProfileCellTests.swift // OctoPhone // // Created by Josef Dolezal on 01/04/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Nimble import Quick @testable import OctoPhone class SlicingProfileCellTests: QuickSpec { override func spec() { describe("Slicing profile cell") { let contextManger = InMemoryContextManager() var subject: SlicingProfileCellViewModelType! afterEach { subject = nil let realm = try! contextManger.createContext() try! realm.write{ realm.deleteAll() } } context("slicer profile not found") { beforeEach { subject = SlicingProfileCellViewModel(profileID: "", contextManager: contextManger) } it("provides placeholder text for name") { expect(subject.outputs.name.value) == "Unknown slicing profile" } } context("slicer profile is in database") { let profileID = "Profile" var profile: SlicingProfile! beforeEach { profile = SlicingProfile(ID: profileID, name: nil, description: nil, isDefault: true) let realm = try! contextManger.createContext() try! realm.write{ realm.add(profile) } subject = SlicingProfileCellViewModel(profileID: profileID, contextManager: contextManger) } afterEach { profile = nil } it("provides placeholder name if profile name is empty") { expect(subject.outputs.name.value) == "Unknown slicing profile" } it("displays profile name if it's not empty") { let realm = try! contextManger.createContext() try! realm.write { profile.name = "Slicer name" } expect(subject.outputs.name.value).toEventually(equal("Slicer name")) } it("reacts to profile changes") { let realm = try! contextManger.createContext() try! realm.write { profile.name = "Change 1" } expect(subject.outputs.name.value).toEventually(equal("Change 1")) try! realm.write { profile.name = "Change 2" } expect(subject.outputs.name.value).toEventually(equal("Change 2")) try! realm.write { profile.name = "Change 3" } expect(subject.outputs.name.value).toEventually(equal("Change 3")) } } } } }
mit
jshultz/ios9-swift2-core-data-demo
Core Data Demo/ViewController.swift
1
3880
// // ViewController.swift // Core Data Demo // // Created by Jason Shultz on 10/3/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // create an app delegate variable let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // context is a handler for us to be able to access the database. this allows us to access the CoreData database. let context: NSManagedObjectContext = appDel.managedObjectContext // we are describing the Entity we want to insert the new user into. We are doing it for Entity Name Users. Then we tell it the context we want to insert it into, which we described previously. let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) // set the values of the attributes for the newUser we are wanting to set. newUser.setValue("Steve", forKey: "username") newUser.setValue("rogers123", forKey: "password") do { // save the context. try context.save() } catch { print("There was a problem") } // now we are requesting data from the Users Entity. let request = NSFetchRequest(entityName: "Users") // if we want to search for something in particular we can use predicates: request.predicate = NSPredicate(format: "username = %@", "Steve") // search for users where username = Steve // by default, if we do a request and get some data back it returns false for the actual data. if we want to get data back and see it, then we need to set this as false. request.returnsObjectsAsFaults = false do { // save the results of our fetch request to a variable. let results = try context.executeFetchRequest(request) print(results) if (results.count > 0) { for result in results as! [NSManagedObject] { // delete the object that we found. // context.deleteObject(result) do { try context.save() // you have to save after deleting (or anything else) otherwise it won't stick. } catch { print("something went wrong") } if let username = result.valueForKey("username") as? String { // cast username as String so we can use it. print(username) } if let password = result.valueForKey("password") as? String { // cast password as String so we can use it. print(password) // this lets us change a value of the thing we just found and change it to something else. // result.setValue("something", forKey: "password") // change the password to something else. // do { // try context.save() // } catch { // print("something went wrong") // } } } } } catch { print("There was a problem") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
aipeople/PokeIV
PokeIV/PopoverTemplateView.swift
1
4433
// // PopoverTemplateView.swift // PokeIV // // Created by aipeople on 8/15/16. // Github: https://github.com/aipeople/PokeIV // Copyright © 2016 su. All rights reserved. // import UIKit import Cartography typealias PopoverViewSelectionCallBack = (PopoverTemplateView, selectedIndex: Int) -> () class PopoverTemplateView : UIView { // MARK: - Properties let bottomBar = UIView() var buttonData = [BorderButtonData]() {didSet{self.setupButtons()}} private(set) var buttons = [UIButton]() var containerEdgesGroup: ConstraintGroup! private weak var firstButtonLeftConstraint: NSLayoutConstraint? private weak var lastButtonLeftConstraint: NSLayoutConstraint? // MARK: - Data var selectCallback: PopoverViewSelectionCallBack? // MARK: - Life Cycle init() { super.init(frame: CGRect.zero) self.setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { // Setup Constraints self.addSubview(self.bottomBar) constrain(self.bottomBar) { (bar) -> () in bar.left == bar.superview!.left bar.right == bar.superview!.right bar.bottom == bar.superview!.bottom bar.height == 54 } // Setup Constraints self.backgroundColor = UIColor(white: 0.9, alpha: 1.0) self.layer.cornerRadius = 4 self.layer.masksToBounds = true self.bottomBar.backgroundColor = UIColor(white: 0.9, alpha: 1.0).colorWithAlphaComponent(0.95) } override func layoutSubviews() { super.layoutSubviews() self.layoutIfNeeded() let buttonNum = self.buttons.count let buttonsWidth = 150 * buttonNum + 10 * (buttonNum - 1) let spacing = (self.frame.width - CGFloat(buttonsWidth)) * 0.5 if spacing > 10 { self.firstButtonLeftConstraint?.constant = spacing self.lastButtonLeftConstraint?.constant = -spacing } } // MARK: - UI Methods func setupButtons() { // Remove origin buttons for button in self.buttons { button.removeFromSuperview() } self.buttons.removeAll() // Setup new buttons var lastView: UIView? for data in self.buttonData { let button = UIButton.borderButtonWithTitle(data.title, titleColor: data.titleColor) button.layer.borderColor = data.borderColor.CGColor button.addTarget(self, action: #selector(PopoverTemplateView.handleButtonOnTap(_:)), forControlEvents: .TouchUpInside) self.buttons.append(button) self.bottomBar.addSubview(button) if let lastView = lastView { constrain(button, lastView, block: { (button, view) -> () in button.height == 34 button.width == view.width ~ 750 button.centerY == button.superview!.centerY button.left == view.right + 10 }) } else { constrain(button, block: { (button) -> () in button.height == 34 button.width <= 150 button.centerY == button.superview!.centerY button.centerX == button.superview!.centerX ~ 750 self.firstButtonLeftConstraint = button.left == button.superview!.left + 10 ~ 750 }) } lastView = button } if let lastView = lastView { constrain(lastView, block: { (view) -> () in self.lastButtonLeftConstraint = view.right == view.superview!.right - 10 ~ 750 }) } } // MARK: - Events func handleButtonOnTap(sender: UIButton) { if let index = self.buttons.indexOf(sender) { if let callback = self.selectCallback { callback(self, selectedIndex: index) } else { self.popoverView?.dismiss() } } } }
gpl-3.0
Alloc-Studio/Hypnos
Hypnos/Hypnos/Configure/HypnosConfig.swift
1
790
// // HypnosConfig.swift // Hypnos // // Created by Maru on 16/5/18. // Copyright © 2016年 DMT312. All rights reserved. // import Foundation import UIKit struct HypnosConfig { // MARK: - UI Config /// 默认主题颜色,导航栏 static let DefaultThemeColor = UIColor(r: 128, g: 191, b: 232, alpha: 1) /// 主页的背景颜色 static let HomeBgColor = UIColor(r: 249, g: 249, b: 249, alpha: 1) /// 导航栏文字颜色 static let NavTextColor = UIColor.whiteColor() /// Tabbar文字的颜色 static let TabbarTextColor_Normal = UIColor.blackColor() /// 圆角边框的颜色 static let borderColor = UIColor(red: 36/255.0, green: 36/255.0, blue: 36/255.0, alpha: 1) } extension HypnosConfig { // MARK: - API Config }
mit
Ryce/flickrpickr
Carthage/Checkouts/judokit/Source/DateInputField.swift
2
12572
// // DateTextField.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } /** The DateTextField allows two different modes of input. - Picker: Use a custom UIPickerView with month and year fields - Text: Use a common Numpad Keyboard as text input method */ public enum DateInputType { /// DateInputTypePicker using a UIPicker as an input method case picker /// DateInputTypeText using a Keyboard as an input method case text } /** The DateInputField is an input field configured to detect, validate and dates that are set to define a start or end date of various types of credit cards. */ open class DateInputField: JudoPayInputField { /// The datePicker showing months and years to pick from for expiry or start date input let datePicker = UIPickerView() /// The date formatter that shows the date in the same way it is written on a credit card fileprivate let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MM/yy" return formatter }() /// The current year on a Gregorian calendar fileprivate let currentYear = (Calendar.current as NSCalendar).component(.year, from: Date()) /// The current month on a Gregorian calendar fileprivate let currentMonth = (Calendar.current as NSCalendar).component(.month, from: Date()) /// Boolean stating whether input field should identify as a start or end date open var isStartDate: Bool = false { didSet { self.textField.attributedPlaceholder = NSAttributedString(string: self.title(), attributes: [NSForegroundColorAttributeName:self.theme.getPlaceholderTextColor()]) } } /// Boolean stating whether input field should identify as a start or end date open var isVisible: Bool = false /// Variable defining the input type (text or picker) open var dateInputType: DateInputType = .text { didSet { switch dateInputType { case .picker: self.textField.inputView = self.datePicker let month = NSString(format: "%02i", currentMonth) let year = NSString(format: "%02i", currentYear - 2000) // FIXME: not quite happy with this, must be a better way self.textField.text = "\(month)/\(year)" self.datePicker.selectRow(currentMonth - 1, inComponent: 0, animated: false) break case .text: self.textField.inputView = nil self.textField.keyboardType = .numberPad } } } // MARK: Initializers /** Setup the view */ override func setupView() { super.setupView() // Input method should be via date picker self.datePicker.delegate = self self.datePicker.dataSource = self if self.dateInputType == .picker { self.textField.inputView = self.datePicker let month = NSString(format: "%02i", currentMonth) let year = NSString(format: "%02i", currentYear - 2000) self.textField.text = "\(month)/\(year)" self.datePicker.selectRow(currentMonth - 1, inComponent: 0, animated: false) } } // MARK: UITextFieldDelegate /** Delegate method implementation - parameter textField: Text field - parameter range: Range - parameter string: String - returns: boolean to change characters in given range for a textfield */ open func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // Only handle calls if textinput is selected guard self.dateInputType == .text else { return true } // Only handle delegate calls for own textfield guard textField == self.textField else { return false } // Get old and new text let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) if newString.characters.count == 0 { return true } else if newString.characters.count == 1 { return newString == "0" || newString == "1" } else if newString.characters.count == 2 { // if deletion is handled and user is trying to delete the month no slash should be added guard string.characters.count > 0 else { return true } guard Int(newString) > 0 && Int(newString) <= 12 else { return false } self.textField.text = newString + "/" return false } else if newString.characters.count == 3 { return newString.characters.last == "/" } else if newString.characters.count == 4 { // FIXME: need to make sure that number is numeric let deciYear = Int((Double((Calendar.current as NSCalendar).component(.year, from: Date()) - 2000) / 10.0)) let lastChar = Int(String(newString.characters.last!)) if self.isStartDate { return lastChar == deciYear || lastChar == deciYear - 1 } else { return lastChar == deciYear || lastChar == deciYear + 1 } } else if newString.characters.count == 5 { return true } else { self.delegate?.dateInput(self, error: JudoError(.inputLengthMismatchError)) return false } } // MARK: Custom methods /** Check if this inputField is valid - returns: true if valid input */ open override func isValid() -> Bool { guard let dateString = textField.text , dateString.characters.count == 5, let beginningOfMonthDate = self.dateFormatter.date(from: dateString) else { return false } if self.isStartDate { let minimumDate = Date().dateByAddingYears(-10) return beginningOfMonthDate.compare(Date()) == .orderedAscending && beginningOfMonthDate.compare(minimumDate!) == .orderedDescending } else { let endOfMonthDate = beginningOfMonthDate.dateAtTheEndOfMonth() let maximumDate = Date().dateByAddingYears(10) return endOfMonthDate.compare(Date()) == .orderedDescending && endOfMonthDate.compare(maximumDate!) == .orderedAscending } } /** Subclassed method that is called when textField content was changed - parameter textField: the textfield of which the content has changed */ open override func textFieldDidChangeValue(_ textField: UITextField) { super.textFieldDidChangeValue(textField) self.didChangeInputText() guard let text = textField.text , text.characters.count == 5 else { return } if self.dateFormatter.date(from: text) == nil { return } if self.isValid() { self.delegate?.dateInput(self, didFindValidDate: textField.text!) } else { var errorMessage = "Check expiry date" if self.isStartDate { errorMessage = "Check start date" } self.delegate?.dateInput(self, error: JudoError(.invalidEntry, errorMessage)) } } /** The placeholder string for the current inputField - returns: an Attributed String that is the placeholder of the receiver */ open override func placeholder() -> NSAttributedString? { return NSAttributedString(string: self.title(), attributes: [NSForegroundColorAttributeName:self.theme.getPlaceholderTextColor()]) } /** Title of the receiver inputField - returns: a string that is the title of the receiver */ open override func title() -> String { return isStartDate ? "Start date" : "Expiry date" } /** Hint label text - returns: string that is shown as a hint when user resides in a inputField for more than 5 seconds */ open override func hintLabelText() -> String { return "MM/YY" } } // MARK: UIPickerViewDataSource extension DateInputField: UIPickerViewDataSource { /** Datasource method for datePickerView - parameter pickerView: PickerView that calls its delegate - returns: The number of components in the pickerView */ public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } /** Datasource method for datePickerView - parameter pickerView: PickerView that calls its delegate - parameter component: A given component - returns: number of rows in component */ public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? 12 : 11 } } // MARK: UIPickerViewDelegate extension DateInputField: UIPickerViewDelegate { /** Delegate method for datePickerView - parameter pickerView: The caller - parameter row: The row - parameter component: The component - returns: content of a given component and row */ public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return NSString(format: "%02i", row + 1) as String case 1: return NSString(format: "%02i", (self.isStartDate ? currentYear - row : currentYear + row) - 2000) as String default: return nil } } /** Delegate method for datePickerView that had a given row in a component selected - parameter pickerView: The caller - parameter row: The row - parameter component: The component */ public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // Need to use NSString because Precision String Format Specifier is easier this way if component == 0 { let month = NSString(format: "%02i", row + 1) let oldDateString = self.textField.text! let year = oldDateString.substring(from: oldDateString.characters.index(oldDateString.endIndex, offsetBy: -2)) self.textField.text = "\(month)/\(year)" } else if component == 1 { let oldDateString = self.textField.text! let month = oldDateString.substring(to: oldDateString.characters.index(oldDateString.startIndex, offsetBy: 2)) let year = NSString(format: "%02i", (self.isStartDate ? currentYear - row : currentYear + row) - 2000) self.textField.text = "\(month)/\(year)" } } }
mit
quire-io/SwiftyChrono
Sources/Utils/Util.swift
1
2961
// // Util.swift // SwiftyChrono // // Created by Jerry Chen on 1/18/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation let HALF = Int.min let HALF_SECOND_IN_MS = millisecondsToNanoSeconds(500) // unit: nanosecond /// get ascending order from two number. /// ATTENSION: func sortTwoNumbers(_ index1: Int, _ index2: Int) -> (lessNumber: Int, greaterNumber: Int) { if index1 == index2 { return (index1, index2) } let lessNumber = index1 < index2 ? index1 : index2 let greaterNumber = index1 > index2 ? index1 : index2 return (lessNumber, greaterNumber) } extension NSTextCheckingResult { func isNotEmpty(atRangeIndex index: Int) -> Bool { return range(at: index).length != 0 } func isEmpty(atRangeIndex index: Int) -> Bool { return range(at: index).length == 0 } func string(from text: String, atRangeIndex index: Int) -> String { return text.subString(with: range(at: index)) } } extension String { var firstString: String? { return substring(from: 0, to: 1) } func subString(with range: NSRange) -> String { return (self as NSString).substring(with: range) } func substring(from idx: Int) -> String { return String(self[index(startIndex, offsetBy: idx)...]) } func substring(from startIdx: Int, to endIdx: Int? = nil) -> String { if startIdx < 0 || (endIdx != nil && endIdx! < 0) { return "" } let start = index(startIndex, offsetBy: startIdx) let end = endIdx != nil ? index(startIndex, offsetBy: endIdx!) : endIndex return String(self[start..<end]) } func range(ofStartIndex idx: Int, length: Int) -> Range<String.Index> { let startIndex0 = index(startIndex, offsetBy: idx) let endIndex0 = index(startIndex, offsetBy: idx + length) return Range(uncheckedBounds: (lower: startIndex0, upper: endIndex0)) } func range(ofStartIndex startIdx: Int, andEndIndex endIdx: Int) -> Range<String.Index> { let startIndex0 = index(startIndex, offsetBy: startIdx) let endIndex0 = index(startIndex, offsetBy: endIdx) return Range(uncheckedBounds: (lower: startIndex0, upper: endIndex0)) } func trimmed() -> String { return trimmingCharacters(in: .whitespacesAndNewlines) } } extension NSRegularExpression { static func isMatch(forPattern pattern: String, in text: String) -> Bool { return (try? NSRegularExpression(pattern: pattern, options: .caseInsensitive))?.firstMatch(in: text, range: NSRange(location: 0, length: text.count)) != nil } } extension Dictionary { mutating func merge(with dictionary: Dictionary) { dictionary.forEach { updateValue($1, forKey: $0) } } func merged(with dictionary: Dictionary) -> Dictionary { var dict = self dict.merge(with: dictionary) return dict } }
mit
ltcarbonell/deckstravaganza
Deckstravaganza/GenericSwitchView.swift
1
632
// // GenericSwitchView.swift // Deckstravaganza // // Created by Cory Armstrong on 11/23/15. // Copyright © 2015 University of Florida. All rights reserved. // import UIKit class GenericSwitchView: UISwitch, GenericFormElements { func getDefaultFrame() -> CGRect { return UISwitch().frame; } func getResults() -> String { return String(super.isOn); } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/10601-swift-sourcemanager-getmessage.swift
11
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ( { let a { func a { for in { class A { { } class case ,
mit
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Builder/Configurable Dependencies/ConventionStartDateRepository.swift
1
265
import Foundation public protocol ConventionStartDateRepository { func addConsumer(_ consumer: ConventionStartDateConsumer) } public protocol ConventionStartDateConsumer: AnyObject { func conventionStartDateDidChange(to startDate: Date) }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/02356-swift-parser-skipsingle.swift
11
289
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ( ( ) { protocol a { { } var d = [ { class a { class case , var { { { { { ( ( ( ( { [ { { ( ( [ [ { { { { ( ( { ( [ [ x
mit
anicolaspp/rate-my-meetings-ios
Pods/CVCalendar/CVCalendar/CVCalendarMonthContentViewController.swift
3
16595
// // CVCalendarMonthContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthContentViewController: CVCalendarContentViewController { private var monthViews: [Identifier : MonthView] public override init(calendarView: CalendarView, frame: CGRect) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) initialLoad(presentedMonthView.date) } public init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) { monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate) presentedMonthView.updateAppearance(scrollView.bounds) initialLoad(presentedDate) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Load & Reload public func initialLoad(date: NSDate) { insertMonthView(getPreviousMonth(date), withIdentifier: Previous) insertMonthView(presentedMonthView, withIdentifier: Presented) insertMonthView(getFollowingMonth(date), withIdentifier: Following) presentedMonthView.mapDayViews { dayView in if self.calendarView.shouldAutoSelectDayOnMonthChange && self.matchedDays(dayView.date, Date(date: date)) { self.calendarView.coordinator.flush() self.calendarView.touchController.receiveTouchOnDayView(dayView) dayView.circleView?.removeFromSuperview() } } calendarView.presentedDate = CVDate(date: presentedMonthView.date) } public func reloadMonthViews() { for (identifier, monthView) in monthViews { monthView.frame.origin.x = CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width monthView.removeFromSuperview() scrollView.addSubview(monthView) } } // MARK: - Insertion public func insertMonthView(monthView: MonthView, withIdentifier identifier: Identifier) { let index = CGFloat(indexOfIdentifier(identifier)) monthView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0) monthViews[identifier] = monthView scrollView.addSubview(monthView) } public func replaceMonthView(monthView: MonthView, withIdentifier identifier: Identifier, animatable: Bool) { var monthViewFrame = monthView.frame monthViewFrame.origin.x = monthViewFrame.width * CGFloat(indexOfIdentifier(identifier)) monthView.frame = monthViewFrame monthViews[identifier] = monthView if animatable { scrollView.scrollRectToVisible(monthViewFrame, animated: false) } } // MARK: - Load management public func scrolledLeft() { if let presented = monthViews[Presented], let following = monthViews[Following] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[Previous]?.removeFromSuperview() replaceMonthView(presented, withIdentifier: Previous, animatable: false) replaceMonthView(following, withIdentifier: Presented, animatable: true) insertMonthView(getFollowingMonth(following.date), withIdentifier: Following) self.calendarView.delegate?.didShowNextMonthView?(following.date) } } } public func scrolledRight() { if let previous = monthViews[Previous], let presented = monthViews[Presented] { if pageLoadingEnabled { pageLoadingEnabled = false monthViews[Following]?.removeFromSuperview() replaceMonthView(previous, withIdentifier: Presented, animatable: true) replaceMonthView(presented, withIdentifier: Following, animatable: false) insertMonthView(getPreviousMonth(previous.date), withIdentifier: Previous) self.calendarView.delegate?.didShowPreviousMonthView?(previous.date) } } } // MARK: - Override methods public override func updateFrames(rect: CGRect) { super.updateFrames(rect) for monthView in monthViews.values { monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds) } reloadMonthViews() if let presented = monthViews[Presented] { if scrollView.frame.height != presented.potentialSize.height { updateHeight(presented.potentialSize.height, animated: false) } scrollView.scrollRectToVisible(presented.frame, animated: false) } } public override func performedDayViewSelection(dayView: DayView) { if dayView.isOut && calendarView.shouldScrollOnOutDayViewSelection { if dayView.date.day > 20 { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate)) presentPreviousView(dayView) } else { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate)) presentNextView(dayView) } } } public override func presentPreviousView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = monthViews[Following], let presented = monthViews[Presented], let previous = monthViews[Previous] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x += self.scrollView.frame.width presented.frame.origin.x += self.scrollView.frame.width previous.frame.origin.x += self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.Following, animatable: false) self.replaceMonthView(previous, withIdentifier: self.Presented, animatable: false) self.presentedMonthView = previous self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getPreviousMonth(previous.date), withIdentifier: self.Previous) self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } } public override func presentNextView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = monthViews[Previous], let presented = monthViews[Presented], let following = monthViews[Following] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnMonthView(presented, hidden: true) extra.frame.origin.x -= self.scrollView.frame.width presented.frame.origin.x -= self.scrollView.frame.width following.frame.origin.x -= self.scrollView.frame.width self.replaceMonthView(presented, withIdentifier: self.Previous, animatable: false) self.replaceMonthView(following, withIdentifier: self.Presented, animatable: false) self.presentedMonthView = following self.updateLayoutIfNeeded() }) { _ in extra.removeFromSuperview() self.insertMonthView(self.getFollowingMonth(following.date), withIdentifier: self.Following) self.updateSelection() self.presentationEnabled = true for monthView in self.monthViews.values { self.prepareTopMarkersOnMonthView(monthView, hidden: false) } } } } } public override func updateDayViews(hidden: Bool) { setDayOutViewsVisible(hidden) } private var togglingBlocked = false public override func togglePresentedDate(date: NSDate) { let presentedDate = Date(date: date) if let presented = monthViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date { if !matchedDays(selectedDate, presentedDate) && !togglingBlocked { if !matchedMonths(presentedDate, selectedDate) { togglingBlocked = true monthViews[Previous]?.removeFromSuperview() monthViews[Following]?.removeFromSuperview() insertMonthView(getPreviousMonth(date), withIdentifier: Previous) insertMonthView(getFollowingMonth(date), withIdentifier: Following) let currentMonthView = MonthView(calendarView: calendarView, date: date) currentMonthView.updateAppearance(scrollView.bounds) currentMonthView.alpha = 0 insertMonthView(currentMonthView, withIdentifier: Presented) presentedMonthView = currentMonthView calendarView.presentedDate = Date(date: date) UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { presented.alpha = 0 currentMonthView.alpha = 1 }) { _ in presented.removeFromSuperview() self.selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) self.togglingBlocked = false self.updateLayoutIfNeeded() } } else { if let currentMonthView = monthViews[Presented] { selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView) } } } } } } // MARK: - Month management extension CVCalendarMonthContentViewController { public func getFollowingMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month += 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } public func getPreviousMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month -= 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let frame = scrollView.bounds let monthView = MonthView(calendarView: calendarView, date: newDate) monthView.updateAppearance(frame) return monthView } } // MARK: - Visual preparation extension CVCalendarMonthContentViewController { public func prepareTopMarkersOnMonthView(monthView: MonthView, hidden: Bool) { monthView.mapDayViews { dayView in dayView.topMarker?.hidden = hidden } } public func setDayOutViewsVisible(visible: Bool) { for monthView in monthViews.values { monthView.mapDayViews { dayView in if dayView.isOut { if !visible { dayView.alpha = 0 dayView.hidden = false } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { dayView.alpha = visible ? 0 : 1 }) { _ in if visible { dayView.alpha = 1 dayView.hidden = true dayView.userInteractionEnabled = false } else { dayView.userInteractionEnabled = true } } } } } } public func updateSelection() { let coordinator = calendarView.coordinator if let selected = coordinator.selectedDayView { for (index, monthView) in monthViews { if indexOfIdentifier(index) != 1 { monthView.mapDayViews { dayView in if dayView == selected { dayView.setDeselectedWithClearing(true) coordinator.dequeueDayView(dayView) } } } } } if let presentedMonthView = monthViews[Presented] { self.presentedMonthView = presentedMonthView calendarView.presentedDate = Date(date: presentedMonthView.date) if let selected = coordinator.selectedDayView, let selectedMonthView = selected.monthView where !matchedMonths(Date(date: selectedMonthView.date), Date(date: presentedMonthView.date)) && calendarView.shouldAutoSelectDayOnMonthChange { let current = Date(date: NSDate()) let presented = Date(date: presentedMonthView.date) if matchedMonths(current, presented) { selectDayViewWithDay(current.day, inMonthView: presentedMonthView) } else { selectDayViewWithDay(Date(date: calendarView.manager.monthDateRange(presentedMonthView.date).monthStartDate).day, inMonthView: presentedMonthView) } } } } public func selectDayViewWithDay(day: Int, inMonthView monthView: CVCalendarMonthView) { let coordinator = calendarView.coordinator monthView.mapDayViews { dayView in if dayView.date.day == day && !dayView.isOut { if let selected = coordinator.selectedDayView where selected != dayView { self.calendarView.didSelectDayView(dayView) } coordinator.performDayViewSingleSelection(dayView) } } } } // MARK: - UIScrollViewDelegate extension CVCalendarMonthContentViewController { public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y != 0 { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0) } let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1) if currentPage != page { currentPage = page } lastContentOffset = scrollView.contentOffset.x } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if let presented = monthViews[Presented] { prepareTopMarkersOnMonthView(presented, hidden: true) } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if pageChanged { switch direction { case .Left: scrolledLeft() case .Right: scrolledRight() default: break } } updateSelection() updateLayoutIfNeeded() pageLoadingEnabled = true direction = .None } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { let rightBorder = scrollView.frame.width if scrollView.contentOffset.x <= rightBorder { direction = .Right } else { direction = .Left } } for monthView in monthViews.values { prepareTopMarkersOnMonthView(monthView, hidden: false) } } }
mit
liujinlongxa/AnimationTransition
testTransitioning/TableViewController.swift
1
631
// // TableViewController.swift // testTransitioning // // Created by Liujinlong on 8/10/15. // Copyright © 2015 Jaylon. All rights reserved. // import UIKit class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.delegate = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source }
mit
austinzheng/swift-compiler-crashes
fixed/27457-llvm-tinyptrvector-swift-valuedecl-push-back.swift
4
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{{{struct B{let a class a{func b{ class B {func b{ a=B
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/19788-llvm-foldingset-swift-classtype-nodeequals.swift
11
260
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b<d { struct S<T { { } class c { enum b { enum b : A { struct B protocol A { struct B
mit
esttorhe/RxSwift
RxSwift/RxSwift/DataStructures/Queue.swift
1
3173
// // Queue.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public struct Queue<T>: SequenceType { typealias Generator = AnyGenerator<T> let resizeFactor = 2 private var storage: [T?] private var _count: Int private var pushNextIndex: Int private var initialCapacity: Int private var version: Int public init(capacity: Int) { initialCapacity = capacity version = 0 storage = [] _count = 0 pushNextIndex = 0 resizeTo(capacity) } private var dequeueIndex: Int { get { let index = pushNextIndex - count return index < 0 ? index + self.storage.count : index } } public var empty: Bool { get { return count == 0 } } public var count: Int { get { return _count } } public func peek() -> T { contract(count > 0) return storage[dequeueIndex]! } mutating private func resizeTo(size: Int) { var newStorage: [T?] = [] newStorage.reserveCapacity(size) let count = _count for var i = 0; i < count; ++i { // does swift array have some more efficient methods of copying? newStorage.append(dequeue()) } while newStorage.count < size { newStorage.append(nil) } _count = count pushNextIndex = count storage = newStorage } public mutating func enqueue(item: T) { version++ _ = count == storage.count if count == storage.count { resizeTo(storage.count * resizeFactor) } storage[pushNextIndex] = item pushNextIndex++ _count = _count + 1 if pushNextIndex >= storage.count { pushNextIndex -= storage.count } } public mutating func dequeue() -> T { version++ contract(count > 0) let index = dequeueIndex let value = storage[index]! storage[index] = nil _count = _count - 1 let downsizeLimit = storage.count / (resizeFactor * resizeFactor) if _count < downsizeLimit && downsizeLimit >= initialCapacity { resizeTo(storage.count / resizeFactor) } return value } public func generate() -> Generator { var i = dequeueIndex var count = _count let lastVersion = version return anyGenerator { if lastVersion != self.version { rxFatalError("Collection was modified while enumerated") } if count == 0 { return nil } count-- if i >= self.storage.count { i -= self.storage.count } return self.storage[i++] } } }
mit
ra1028/KenBurnsSlideshowView
KenBurnsSlideshowView-Demo/KenBurnsSlideshowView-Demo/ViewController.swift
1
1267
// // ViewController.swift // KenBurnsSlideshowView-Demo // // Created by Ryo Aoyama on 12/1/14. // Copyright (c) 2014 Ryo Aoyama. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var kenBurnsView: KenBurnsView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() let longPress = UILongPressGestureRecognizer(target: self, action: "showWholeImage:") longPress.minimumPressDuration = 0.2 self.kenBurnsView.addGestureRecognizer(longPress) } func showWholeImage(sender: UIGestureRecognizer) { switch sender.state { case .Began: self.kenBurnsView.showWholeImage() case .Cancelled: fallthrough case .Ended: self.kenBurnsView.zoomImageAndRestartMotion() default: break } } @IBAction func buttonHandler(sender: UIButton) { var imageName = "SampleImage" imageName += sender.titleLabel!.text! + ".jpg" self.kenBurnsView.image = UIImage(named: imageName) } @IBAction func removeButtonHandler(sender: UIButton) { self.kenBurnsView.image = nil } }
mit
qvacua/vimr
VimR/VimR/CoreDataStack.swift
1
3318
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Commons import CoreData import Foundation import os final class CoreDataStack { enum Error: Swift.Error { case noCacheFolder case pathDoesNotExit case pathNotFolder case unableToComplete(Swift.Error) } enum StoreLocation { case temp(String) case cache(String) case path(String) } let container: NSPersistentContainer let storeFile: URL var storeLocation: URL { self.storeFile.parent } var deleteOnDeinit: Bool func newBackgroundContext() -> NSManagedObjectContext { let context = self.container.newBackgroundContext() context.undoManager = nil return context } init(modelName: String, storeLocation: StoreLocation, deleteOnDeinit: Bool = false) throws { self.deleteOnDeinit = deleteOnDeinit self.container = NSPersistentContainer(name: modelName) let fileManager = FileManager.default let url: URL switch storeLocation { case let .temp(folderName): let parentUrl = fileManager .temporaryDirectory .appendingPathComponent(folderName) try fileManager.createDirectory(at: parentUrl, withIntermediateDirectories: true) url = parentUrl.appendingPathComponent(modelName) case let .cache(folderName): guard let cacheUrl = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else { throw Error.noCacheFolder } let parentUrl = cacheUrl.appendingPathComponent(folderName) try fileManager.createDirectory(at: parentUrl, withIntermediateDirectories: true) url = parentUrl.appendingPathComponent(modelName) case let .path(path): guard fileManager.fileExists(atPath: path) else { throw Error.pathDoesNotExit } let parentFolder = URL(fileURLWithPath: path) guard parentFolder.hasDirectoryPath else { throw Error.pathNotFolder } url = parentFolder.appendingPathComponent(modelName) } self.container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: url)] self.storeFile = url self.log.info("Created Core Data store in \(self.storeLocation)") let condition = ConditionVariable() var error: Swift.Error? self.container.loadPersistentStores { _, err in error = err condition.broadcast() } condition.wait(for: 5) if let err = error { throw Error.unableToComplete(err) } self.container.viewContext.undoManager = nil } func deleteStore() throws { guard self.deleteOnDeinit else { return } guard let store = self.container.persistentStoreCoordinator.persistentStore( for: self.storeFile ) else { return } try self.container.persistentStoreCoordinator.remove(store) let parentFolder = self.storeLocation let fileManager = FileManager.default guard fileManager.fileExists(atPath: parentFolder.path) else { return } try fileManager.removeItem(at: parentFolder) self.log.info("Deleted store at \(self.storeLocation)") } deinit { guard self.deleteOnDeinit else { return } do { try self.deleteStore() } catch { self.log.error("Could not delete store at \(self.storeLocation): \(error)") } } private let log = OSLog(subsystem: Defs.loggerSubsystem, category: Defs.LoggerCategory.service) }
mit
apple/swift
test/Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
1
1316
@_exported import ObjectiveC @_exported import CoreGraphics public func == (lhs: CGPoint, rhs: CGPoint) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } #if !CGFLOAT_IN_COREFOUNDATION public struct CGFloat { #if arch(i386) || arch(arm) || arch(arm64_32) || arch(powerpc) public typealias UnderlyingType = Float #elseif arch(x86_64) || arch(arm64) || arch(powerpc64le) || arch(s390x) || arch(riscv64) public typealias UnderlyingType = Double #endif public init() { self.value = 0.0 } public init(_ value: Int) { self.value = UnderlyingType(value) } public init(_ value: Float) { self.value = UnderlyingType(value) } public init(_ value: Double) { self.value = UnderlyingType(value) } var value: UnderlyingType } public func ==(lhs: CGFloat, rhs: CGFloat) -> Bool { return lhs.value == rhs.value } extension CGFloat : ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, Equatable { public init(integerLiteral value: UnderlyingType) { self.value = value } public init(floatLiteral value: UnderlyingType) { self.value = value } } public extension Double { init(_ value: CGFloat) { self = Double(value.value) } } #endif import CoreFoundation extension CGFloat: CustomStringConvertible { public var description: String { "" } }
apache-2.0
NoodleOfDeath/PastaParser
runtime/swift/GrammarKit/Classes/model/grammar/scanner/GrammaticalScanner.swift
1
5238
// // The MIT License (MIT) // // Copyright © 2020 NoodleOfDeath. All rights reserved. // NoodleOfDeath // // 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. @objc public protocol GrammaticalScanner: class { typealias CharacterStream = IO.CharacterStream typealias TokenStream = IO.TokenStream typealias Token = Grammar.Token typealias Metadata = Grammar.Metadata typealias MatchChain = Grammar.MatchChain } /// Specifications for a grammatical scanner delegate. public protocol GrammaticalScannerDelegate: class { typealias CharacterStream = IO.CharacterStream typealias TokenStream = IO.TokenStream typealias Token = Grammar.Token typealias Metadata = Grammar.Metadata typealias MatchChain = Grammar.MatchChain /// Called when a grammatical scanner skips a token. /// /// - Parameters: /// - scanner: that called this method. /// - token: that was skipped. /// - characterStream: `scanner` is scanning. func scanner(_ scanner: GrammaticalScanner, didSkip token: Token, characterStream: CharacterStream) /// Called when a grammatical scanner generates a match chain. /// /// - Parameters: /// - scanner: that called this method. /// - matchChain: that was generated. /// - characterStream: `scanner` is scanning. /// - tokenStream: generated, or being parsed, by `scanner`. func scanner(_ scanner: GrammaticalScanner, didGenerate matchChain: MatchChain, characterStream: CharacterStream, tokenStream: TokenStream<Token>?) /// Called when a grammatical scanner finishes a job. /// /// - Parameters: /// - scanner: that called this method. /// - characterStream: `scanner` is scanning. /// - tokenStream: generated, or parsed, by `scanner`. func scanner(_ scanner: GrammaticalScanner, didFinishScanning characterStream: CharacterStream, tokenStream: TokenStream<Token>?) } /// Base abstract class for a grammar scanning. open class BaseGrammaticalScanner: NSObject, GrammaticalScanner { /// Delegate of this grammatical scanner. open weak var delegate: GrammaticalScannerDelegate? /// Handler of this grammartical scanner. open var handler: GrammaticalScannerHandler? open var didSkip: ((_ scanner: GrammaticalScanner, _ token: Grammar.Token, _ characterStream: IO.CharacterStream) -> ())? { get { return handler?.didSkip } set { if handler == nil { handler = GrammaticalScannerHandler() } handler?.didSkip = newValue } } open var didGenerate: ((_ scanner: GrammaticalScanner, _ matchChain: Grammar.MatchChain, _ characterStream: IO.CharacterStream, _ tokenStream: IO.TokenStream<Grammar.Token>?) -> ())? { get { return handler?.didGenerate } set { if handler == nil { handler = GrammaticalScannerHandler() } handler?.didGenerate = newValue } } open var didFinish: ((_ scanner: GrammaticalScanner, _ characterStream: IO.CharacterStream, _ tokenStream: IO.TokenStream<Grammar.Token>?) -> ())? { get { return handler?.didFinish } set { if handler == nil { handler = GrammaticalScannerHandler() } handler?.didFinish = newValue } } /// Grammar of this scanner. public let grammar: Grammar /// Constructs a new grammatical scanner with an initial grammar. /// /// - Parameters: /// - grammar: to initialize this scanner with. public init(grammar: Grammar) { self.grammar = grammar } } /// Data structure representing a grammatical scanner handler alternative /// to a `GrammaticalScannerDelegate`. public struct GrammaticalScannerHandler { var didSkip: ((_ scanner: GrammaticalScanner, _ token: Grammar.Token, _ characterStream: IO.CharacterStream) -> ())? var didGenerate: ((_ scanner: GrammaticalScanner, _ matchChain: Grammar.MatchChain, _ characterStream: IO.CharacterStream, IO.TokenStream<Grammar.Token>?) -> ())? var didFinish: ((_ scanner: GrammaticalScanner, _ characterStream: IO.CharacterStream, _ tokenStream: IO.TokenStream<Grammar.Token>?) -> ())? }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27150-swift-constraints-constraintsystem-gettypeofmemberreference.swift
1
445
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class c{func a{{class B<T where g:C{let:T.B=a{
apache-2.0
raulriera/HuntingKit
HuntingKit/User.swift
1
2579
// // User.swift // HuntingKit // // Created by Raúl Riera on 19/04/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import Foundation public struct User: Model { public let id: Int public let name: String public let headline: String public let username: String public let profileURL: NSURL? public let imagesURL: ImagesURL public let stats: UserStats? // public let followers: [User]? // public let following: [User]? // public let posts: [Post]? public init?(dictionary: NSDictionary) { if let id = dictionary["id"] as? Int, let username = dictionary["username"] as? String, let headline = dictionary["headline"] as? String, let profileURLString = dictionary["profile_url"] as? String, let imagesURLDictionary = dictionary["image_url"] as? NSDictionary, let name = dictionary["name"] as? String { self.id = id self.name = name self.headline = headline self.username = username if let profileURL = NSURL(string: profileURLString) { self.profileURL = profileURL } else { profileURL = .None } if let stats = UserStats(dictionary: dictionary) { self.stats = stats } else { self.stats = .None } imagesURL = ImagesURL(dictionary: imagesURLDictionary) } else { return nil } } } public struct UserStats { public let votes: Int public let posts: Int public let made: Int public let followers: Int public let following: Int public let collections: Int public init?(dictionary: NSDictionary) { if let votes = dictionary["votes_count"] as? Int, let posts = dictionary["posts_count"] as? Int, let made = dictionary["maker_of_count"] as? Int, let followers = dictionary["followers_count"] as? Int, let following = dictionary["followings_count"] as? Int, let collections = dictionary["collections_count"] as? Int { self.votes = votes self.posts = posts self.made = made self.followers = followers self.following = following self.collections = collections } else { return nil } } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/20507-no-stacktrace.swift
11
246
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ( { struct S { class a { func a { for { init { let P { for in { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/17480-no-stacktrace.swift
11
244
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum A { let a = [ { { } { { class A { var d { func b ( = { { class case ,
mit
icanzilb/Retry
Example/Tests/RetryAsyncTests.swift
1
8755
import Foundation import XCTest @testable import Retry class RetryAsyncTests: XCTestCase { enum TestError: Error { case testError } //MARK: - async retries func testAsyncNoThrow() { var output = "" retryAsync { output += "try" } output += "-end" XCTAssertEqual(output, "try-end", "Didn't succed at first try") } func testAsyncDefaults() { let e1 = expectation(description: "retry end") var output = "" retryAsync { output += "try" throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry default(3) times asynchroniously") } } func testSyncMax() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 5 times asynchroniously") } } //MARK: - async retries + final catch func testSyncMaxFinalCatch() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError }.finalCatch {_ in output += "-catch" }.finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry-catch", "Didn't retry 5 times asynchroniously + catch") } } func testSyncMaxFinalCatchErrorMessage() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError }.finalCatch {_ in output += "-\(TestError.testError)" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry-testError", "Didn't retry 5 times asynchroniously + catch") } } //MARK: - sync retries + strategy //TODO: - how to check for the immediate strategy??? func testSyncMaxImmediate() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .immediate) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 0.001, accuracy: 0.01, "Didn't have the expected delay of 0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 2 times asynchroniously") } } func testSyncMaxDelay() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .delay(seconds: 2.0)) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 2.0, accuracy: 0.2, "Didn't have the expected delay of 2.0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 5 times asynchroniously") } } func testSyncMaxCustomRetryRepetitions() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .custom {count,_ in return count == 2 ? nil : 0} ) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 0.0, accuracy: 0.1, "Didn't have the expected delay of 2.0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry 3 times asynchroniously") } } func testSyncMaxCustomRetryDelay() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? var lastTestDelay: TimeInterval = 0.0 retryAsync (max: 3, retryStrategy: .custom {count, lastDelay in return (lastDelay ?? 0.0) + 1.0} ) { if let lastTime = lastTime { lastTestDelay += 1.0 let stopTime = StopWatch.deltaSince(t1: lastTime) //if only XCTAssertEqualWithAccuracy worked ... XCTAssert(stopTime > (lastTestDelay - lastTestDelay/10.0) && stopTime < (lastTestDelay + lastTestDelay/10.0), "Didn't have the correct delay, expected \(lastTestDelay) timed \(stopTime)") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 5.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry 3 times asynchroniously") } } //MARK: - sync successful func testSuccessFirstTry() { let e1 = expectation(description: "retry end") var output = "" retryAsync { output += "try" } .finalCatch {_ in output += "-catch" } .finalDefer { output += "-defer" e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "try-defer", "Didn't succeed") } } func testSuccessSecondTry() { let e1 = expectation(description: "retry end") var output = "" var succeed = false retryAsync (max: 3) { output += "try" if !succeed { succeed = true throw TestError.testError } }.finalCatch {_ in output += "-catch" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytry", "Didn't succeed at second try") } } func testSuccessSecondTryDelayed() { let e1 = expectation(description: "retry end") var output = "" var succeed = false retryAsync (max: 3, retryStrategy: .custom(closure: {_, _ in return 1.0})) { output += "try" if !succeed { succeed = true throw TestError.testError } }.finalCatch {_ in output += "-catch" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 5.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytry", "Didn't succeed at second try") } } func testAsyncFromBackgroundQueue() { let e1 = expectation(description: "final Defer") var output = "" DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { retryAsync (max: 3, retryStrategy: .immediate) { output.append("try") throw TestError.testError }.finalCatch {_ in output.append("-catch") }.finalDefer { e1.fulfill() } } waitForExpectations(timeout: 2.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry-catch", "Didn't succeed at the third try") } } }
mit
steelwheels/Coconut
CoconutData/Source/Value/CNMutablePointer.swift
1
3970
/* * @file CNMutablePointerValue.swift * @brief Define CNMutablePointerValue class * @par Copyright * Copyright (C) 2022 Steel Wheels Project */ import Foundation public class CNMutablePointerValue: CNMutableValue { private var mPointerValue: CNPointerValue private var mContext: CNMutableValue? public init(pointer val: CNPointerValue, sourceDirectory srcdir: URL, cacheDirectory cachedir: URL){ mPointerValue = val mContext = nil super.init(type: .pointer, sourceDirectory: srcdir, cacheDirectory: cachedir) } public var context: CNMutableValue? { get { return mContext }} public override func _value(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> Result<CNMutableValue?, NSError> { let result: Result<CNMutableValue?, NSError> switch pointedValue(in: root) { case .success(let mval): result = mval._value(forPath: path, in: root) case .failure(let err): result = .failure(err) } return result } public override func _set(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? if path.count == 0 { /* Overide this value */ switch val { case .dictionaryValue(let dict): if let ptr = CNPointerValue.fromValue(value: dict) { mPointerValue = ptr root.isDirty = true result = nil } else { result = noPointedValueError(path: path, place: #function) } default: result = noPointedValueError(path: path, place: #function) } } else { switch pointedValue(in: root) { case .success(let mval): result = mval._set(value: val, forPath: path, in: root) case .failure(let err): result = err } } return result } public override func _append(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? if path.count > 0 { switch pointedValue(in: root) { case .success(let mval): result = mval._append(value: val, forPath: path, in: root) case .failure(let err): result = err } } else { result = NSError.parseError(message: "Can not append value to pointer") } return result } public override func _delete(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? { let result: NSError? if path.count > 0 { switch pointedValue(in: root) { case .success(let mval): result = mval._delete(forPath: path, in: root) case .failure(let err): result = err } } else { result = NSError.parseError(message: "Can not delete pointer value") } return result } public override func _search(name nm: String, value val: String, in root: CNMutableValue) -> Result<Array<CNValuePath.Element>?, NSError> { let result: Result<Array<CNValuePath.Element>?, NSError> switch pointedValue(in: root) { case .success(let mval): result = mval._search(name: nm, value: val, in: root) case .failure(let err): result = .failure(err) } return result } private func pointedValue(in root: CNMutableValue) -> Result<CNMutableValue, NSError> { let elms = root.labelTable().pointerToPath(pointer: mPointerValue, in: root) let result: Result<CNMutableValue, NSError> switch root._value(forPath: elms, in: root) { case .success(let mvalp): if let mval = mvalp { result = .success(mval) } else { result = .failure(unmatchedPathError(path: elms, place: #function)) } case .failure(let err): result = .failure(err) } return result } public override func _makeLabelTable(property name: String, path pth: Array<CNValuePath.Element>) -> Dictionary<String, Array<CNValuePath.Element>> { return [:] } public override func clone() -> CNMutableValue { return CNMutablePointerValue(pointer: mPointerValue, sourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory) } public override func toValue() -> CNValue { return .dictionaryValue(mPointerValue.toValue()) } }
lgpl-2.1
yuanziyuer/XLPagerTabStrip
Example/Example/Helpers/PostCell.swift
2
2198
// PostCell.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class PostCell: UITableViewCell { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var postName: UILabel! @IBOutlet weak var postText: UILabel! override func awakeFromNib() { super.awakeFromNib() userImage.layer.cornerRadius = 10.0 } func configureWithData(data: NSDictionary){ postName.text = data["post"]!["user"]!!["name"] as? String postText.text = data["post"]!["text"] as? String userImage.image = UIImage(named: postName.text!.stringByReplacingOccurrencesOfString(" ", withString: "_")) } func changeStylToBlack(){ userImage?.layer.cornerRadius = 30.0 postText.text = nil postName.font = UIFont(name: "HelveticaNeue-Light", size:18) ?? UIFont.systemFontOfSize(18) postName.textColor = .whiteColor() backgroundColor = UIColor(red: 15/255.0, green: 16/255.0, blue: 16/255.0, alpha: 1.0) } }
mit
tuanan94/FRadio-ios
SwiftRadio/NowPlayingViewController.swift
1
4420
import UIKit import AVFoundation import Firebase import FirebaseDatabase import NotificationBannerSwift class NowPlayingViewController: UIViewController { @IBOutlet weak var albumHeightConstraint: NSLayoutConstraint! @IBOutlet weak var albumImageView: SpringImageView! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var songLabel: SpringLabel! @IBOutlet weak var stationDescLabel: UILabel! @IBOutlet weak var volumeParentView: UIView! @IBOutlet weak var recommendSong: UIButton! @objc var iPhone4 = false @objc var nowPlayingImageView: UIImageView! static var radioPlayer: AVPlayer! let streamUrl = "http://fradio.site:8000/default.m3u" var ref: DatabaseReference! static var notification: String! static var isPlaying = false; override func viewDidLoad() { super.viewDidLoad() if (NowPlayingViewController.isPlaying){ self.playButton.setImage(#imageLiteral(resourceName: "btn-pause"), for: UIControlState.normal) }else{ play() } reformButton() self.setupFirebase() } override func viewDidAppear(_ animated: Bool) { self.displayNotification() } private func displayNotification(){ if NowPlayingViewController.notification == nil { return } switch NowPlayingViewController.notification { case "success": let banner = NotificationBanner(title: "Successfully!!", subtitle: "Thank you, your song will be played soon", style: .success) banner.show() NowPlayingViewController.notification = nil break case "fail": let banner = NotificationBanner(title: "Some thing went wrong", subtitle: "I will investigate this case asap", style: .danger) banner.show() NowPlayingViewController.notification = nil break; default: break // Do nothing } } private func setupFirebase(){ if (FirebaseApp.app() == nil){ FirebaseApp.configure() } ref = Database.database().reference(fromURL: "https://fradio-firebase.firebaseio.com/current") ref.removeAllObservers() ref.observe(DataEventType.value, with: { (snapshot) in let postDict = snapshot.value as? [String : AnyObject] ?? [:] let videoTitle = postDict["title"] as? String if (videoTitle == nil){ self.songLabel.text = "waiting new song..." }else{ self.songLabel.text = videoTitle } print("a") }) } private func reformButton(){ recommendSong.layer.cornerRadius = 10; recommendSong.clipsToBounds = true; title = "FRadio" } @IBAction func playPausePress(_ sender: Any) { if (NowPlayingViewController.isPlaying){ pause() } else { play() } } private func play(){ NowPlayingViewController.radioPlayer = AVPlayer(url: URL.init(string: streamUrl)!); if #available(iOS 10.0, *) { NowPlayingViewController.radioPlayer.automaticallyWaitsToMinimizeStalling = true } else { // Fallback on earlier versions } NowPlayingViewController.radioPlayer.play(); self.playButton.setImage(#imageLiteral(resourceName: "btn-pause"), for: UIControlState.normal) NowPlayingViewController.isPlaying = true } private func pause(){ NowPlayingViewController.radioPlayer.pause(); NowPlayingViewController.radioPlayer = nil; self.playButton.setImage(#imageLiteral(resourceName: "btn-play") ,for: UIControlState.normal) NowPlayingViewController.isPlaying = false } @objc func optimizeForDeviceSize() { // Adjust album size to fit iPhone 4s, 6s & 6s+ let deviceHeight = self.view.bounds.height if deviceHeight == 480 { iPhone4 = true albumHeightConstraint.constant = 106 view.updateConstraints() } else if deviceHeight == 667 { albumHeightConstraint.constant = 230 view.updateConstraints() } else if deviceHeight > 667 { albumHeightConstraint.constant = 260 view.updateConstraints() } } }
mit
edx/edx-app-ios
Source/VideoDownloadQualityViewController.swift
1
9105
// // VideoDownloadQualityViewController.swift // edX // // Created by Muhammad Umer on 13/08/2021. // Copyright © 2021 edX. All rights reserved. // import UIKit fileprivate let buttonSize: CGFloat = 20 protocol VideoDownloadQualityDelegate: AnyObject { func didUpdateVideoQuality() } class VideoDownloadQualityViewController: UIViewController { typealias Environment = OEXInterfaceProvider & OEXAnalyticsProvider & OEXConfigProvider private lazy var headerView = VideoDownloadQualityHeaderView() private lazy var tableView: UITableView = { let tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 20 tableView.alwaysBounceVertical = false tableView.separatorInset = .zero tableView.tableFooterView = UIView() tableView.register(VideoQualityCell.self, forCellReuseIdentifier: VideoQualityCell.identifier) tableView.accessibilityIdentifier = "VideoDownloadQualityViewController:table-view" return tableView }() private weak var delegate: VideoDownloadQualityDelegate? private let environment: Environment init(environment: Environment, delegate: VideoDownloadQualityDelegate?) { self.environment = environment self.delegate = delegate super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .never title = Strings.videoDownloadQualityTitle setupViews() addCloseButton() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackScreen(withName: AnalyticsScreenName.VideoDownloadQuality.rawValue) } private func setupViews() { view.addSubview(tableView) tableView.tableHeaderView = headerView headerView.snp.makeConstraints { make in make.leading.equalTo(view) make.trailing.equalTo(view) } tableView.snp.makeConstraints { make in make.edges.equalTo(view) } tableView.setAndLayoutTableHeaderView(header: headerView) tableView.reloadData() } private func addCloseButton() { let closeButton = UIBarButtonItem(image: Icon.Close.imageWithFontSize(size: buttonSize), style: .plain, target: nil, action: nil) closeButton.accessibilityLabel = Strings.Accessibility.closeLabel closeButton.accessibilityHint = Strings.Accessibility.closeHint closeButton.accessibilityIdentifier = "VideoDownloadQualityViewController:close-button" navigationItem.rightBarButtonItem = closeButton closeButton.oex_setAction { [weak self] in self?.dismiss(animated: true, completion: nil) } } } extension VideoDownloadQualityViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return VideoDownloadQuality.allCases.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: VideoQualityCell.identifier, for: indexPath) as! VideoQualityCell let item = VideoDownloadQuality.allCases[indexPath.row] if let quality = environment.interface?.getVideoDownladQuality(), quality == item { cell.update(title: item.title, selected: true) } else { cell.update(title: item.title, selected: false) } return cell } } extension VideoDownloadQualityViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let oldQuality = environment.interface?.getVideoDownladQuality() let quality = VideoDownloadQuality.allCases[indexPath.row] tableView.reloadData() environment.interface?.saveVideoDownloadQuality(quality: quality) environment.analytics.trackVideoDownloadQualityChanged(value: quality.analyticsValue, oldValue: oldQuality?.analyticsValue ?? "") delegate?.didUpdateVideoQuality() } } class VideoDownloadQualityHeaderView: UITableViewHeaderFooterView { private lazy var titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 let textStyle = OEXMutableTextStyle(weight: .normal, size: .small, color: OEXStyles.shared().neutralBlackT()) label.attributedText = textStyle.attributedString(withText: Strings.videoDownloadQualityMessage(platformName: OEXConfig.shared().platformName())) label.accessibilityIdentifier = "VideoDownloadQualityHeaderView:title-view" return label }() private lazy var separator: UIView = { let view = UIView() view.backgroundColor = OEXStyles.shared().neutralXLight() view.accessibilityIdentifier = "VideoDownloadQualityHeaderView:seperator-view" return view }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) accessibilityIdentifier = "VideoDownloadQualityHeaderView" setupViews() setupConstrains() } required init?(coder: NSCoder) { super.init(coder: coder) } private func setupViews() { addSubview(titleLabel) addSubview(separator) } private func setupConstrains() { titleLabel.snp.makeConstraints { make in make.leading.equalTo(self).offset(StandardVerticalMargin * 2) make.trailing.equalTo(self).inset(StandardVerticalMargin * 2) make.top.equalTo(self).offset(StandardVerticalMargin * 2) make.bottom.equalTo(self).inset(StandardVerticalMargin * 2) } separator.snp.makeConstraints { make in make.leading.equalTo(self) make.trailing.equalTo(self) make.bottom.equalTo(self) make.height.equalTo(1) } } } class VideoQualityCell: UITableViewCell { static let identifier = "VideoQualityCell" lazy var titleLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "VideoQualityCell:title-label" return label }() private lazy var checkmarkImageView: UIImageView = { let imageView = UIImageView() imageView.image = Icon.Check.imageWithFontSize(size: buttonSize).image(with: OEXStyles.shared().neutralBlackT()) imageView.accessibilityIdentifier = "VideoQualityCell:checkmark-image-view" return imageView }() private lazy var textStyle = OEXMutableTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryDarkColor()) private lazy var textStyleSelcted = OEXMutableTextStyle(weight: .bold, size: .base, color: OEXStyles.shared().primaryDarkColor()) override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "VideoDownloadQualityViewController:video-quality-cell" setupView() setupConstrains() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupView() { contentView.addSubview(titleLabel) contentView.addSubview(checkmarkImageView) } private func setupConstrains() { titleLabel.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin * 2) make.leading.equalTo(contentView).offset(StandardVerticalMargin * 2) make.trailing.equalTo(contentView).inset(StandardVerticalMargin * 2) make.bottom.equalTo(contentView).inset(StandardVerticalMargin * 2) } checkmarkImageView.snp.makeConstraints { make in make.width.equalTo(buttonSize) make.height.equalTo(buttonSize) make.trailing.equalTo(contentView).inset(StandardVerticalMargin * 2) make.centerY.equalTo(contentView) } checkmarkImageView.isHidden = true } func update(title: String, selected: Bool) { checkmarkImageView.isHidden = !selected if selected { titleLabel.attributedText = textStyleSelcted.attributedString(withText: title) } else { titleLabel.attributedText = textStyle.attributedString(withText: title) } } }
apache-2.0
indragiek/MarkdownTextView
MarkdownTextView/MarkdownSuperscriptHighlighter.swift
1
2376
// // MarkdownSuperscriptHighlighter.swift // MarkdownTextView // // Created by Indragie on 4/29/15. // Copyright (c) 2015 Indragie Karunaratne. All rights reserved. // import UIKit /** * Highlights super^script in Markdown text (unofficial extension) */ public final class MarkdownSuperscriptHighlighter: HighlighterType { private static let SuperscriptRegex = regexFromPattern("(\\^+)(?:(?:[^\\^\\s\\(][^\\^\\s]*)|(?:\\([^\n\r\\)]+\\)))") private let fontSizeRatio: CGFloat /** Creates a new instance of the receiver. :param: fontSizeRatio Ratio to multiply the original font size by to calculate the superscript font size. :returns: An initialized instance of the receiver. */ public init(fontSizeRatio: CGFloat = 0.7) { self.fontSizeRatio = fontSizeRatio } // MARK: HighlighterType public func highlightAttributedString(attributedString: NSMutableAttributedString) { var previousRange: NSRange? var level: Int = 0 enumerateMatches(self.dynamicType.SuperscriptRegex, string: attributedString.string) { level += $0.rangeAtIndex(1).length let textRange = $0.range let attributes = attributedString.attributesAtIndex(textRange.location, effectiveRange: nil) let isConsecutiveRange: Bool = { if let previousRange = previousRange where NSMaxRange(previousRange) == textRange.location { return true } return false }() if isConsecutiveRange { level++ } attributedString.addAttributes(superscriptAttributes(attributes, level: level, ratio: self.fontSizeRatio), range: textRange) previousRange = textRange if !isConsecutiveRange { level = 0 } } } } private func superscriptAttributes(attributes: TextAttributes, level: Int, ratio: CGFloat) -> TextAttributes { if let font = attributes[NSFontAttributeName] as? UIFont { let adjustedFont = UIFont(descriptor: font.fontDescriptor(), size: font.pointSize * ratio) return [ kCTSuperscriptAttributeName as String: level, NSFontAttributeName: adjustedFont ] } return [:] }
mit
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/AutoPan Operation.xcplaygroundpage/Contents.swift
1
1698
//: ## AutoPan Operation //: import AudioKitPlaygrounds import AudioKit //: This first section sets up parameter naming in such a way //: to make the operation code easier to read below. let speedIndex = 0 let depthIndex = 1 extension AKOperationEffect { var speed: Double { get { return self.parameters[speedIndex] } set(newValue) { self.parameters[speedIndex] = newValue } } var depth: Double { get { return self.parameters[depthIndex] } set(newValue) { self.parameters[depthIndex] = newValue } } } //: Use the struct and the extension to refer to the autopan parameters by name let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let effect = AKOperationEffect(player) { input, parameters in let oscillator = AKOperation.sineWave(frequency: parameters[speedIndex], amplitude: parameters[depthIndex]) return input.pan(oscillator) } effect.parameters = [10, 1] AudioKit.output = effect AudioKit.start() player.play() import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("AutoPan") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Speed", value: effect.speed, range: 0.1 ... 25) { sliderValue in effect.speed = sliderValue }) addView(AKSlider(property: "Depth", value: effect.depth) { sliderValue in effect.depth = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
mit