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
dcutting/Syft
Package.swift
1
406
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "Syft", products: [ .library(name: "Syft", targets: ["Syft"]) ], targets: [ .target( name: "Sample", dependencies: ["Syft"]), .target( name: "Syft"), .testTarget( name: "SyftTests", dependencies: ["Syft"]) ] )
mit
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
12
7470
// // Bag.swift // Rx // // Created by Krunoslav Zaher on 2/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Swift let arrayDictionaryMaxSize = 30 /** Class that enables using memory allocations as a means to uniquely identify objects. */ class Identity { // weird things have known to happen with Swift var _forceAllocation: Int32 = 0 } func hash(_ _x: Int) -> Int { var x = _x x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) return x; } /** Unique identifier for object added to `Bag`. */ public struct BagKey : Hashable { let uniqueIdentity: Identity? let key: Int public var hashValue: Int { if let uniqueIdentity = uniqueIdentity { return hash(key) ^ (ObjectIdentifier(uniqueIdentity).hashValue) } else { return hash(key) } } } /** Compares two `BagKey`s. */ public func == (lhs: BagKey, rhs: BagKey) -> Bool { return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity } /** Data structure that represents a bag of elements typed `T`. Single element can be stored multiple times. Time and space complexity of insertion an deletion is O(n). It is suitable for storing small number of elements. */ public struct Bag<T> : CustomDebugStringConvertible { /** Type of identifier for inserted elements. */ public typealias KeyType = BagKey fileprivate typealias ScopeUniqueTokenType = Int typealias Entry = (key: BagKey, value: T) fileprivate var _uniqueIdentity: Identity? fileprivate var _nextKey: ScopeUniqueTokenType = 0 // data // first fill inline variables fileprivate var _key0: BagKey? = nil fileprivate var _value0: T? = nil fileprivate var _key1: BagKey? = nil fileprivate var _value1: T? = nil // then fill "array dictionary" fileprivate var _pairs = ContiguousArray<Entry>() // last is sparse dictionary fileprivate var _dictionary: [BagKey : T]? = nil fileprivate var _onlyFastPath = true /** Creates new empty `Bag`. */ public init() { } /** Inserts `value` into bag. - parameter element: Element to insert. - returns: Key that can be used to remove element from bag. */ public mutating func insert(_ element: T) -> BagKey { _nextKey = _nextKey &+ 1 #if DEBUG _nextKey = _nextKey % 20 #endif if _nextKey == 0 { _uniqueIdentity = Identity() } let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) if _key0 == nil { _key0 = key _value0 = element return key } _onlyFastPath = false if _key1 == nil { _key1 = key _value1 = element return key } if _dictionary != nil { _dictionary![key] = element return key } if _pairs.count < arrayDictionaryMaxSize { _pairs.append(key: key, value: element) return key } if _dictionary == nil { _dictionary = [:] } _dictionary![key] = element return key } /** - returns: Number of elements in bag. */ public var count: Int { let dictionaryCount: Int = _dictionary?.count ?? 0 return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount } /** Removes all elements from bag and clears capacity. */ public mutating func removeAll() { _key0 = nil _value0 = nil _key1 = nil _value1 = nil _pairs.removeAll(keepingCapacity: false) _dictionary?.removeAll(keepingCapacity: false) } /** Removes element with a specific `key` from bag. - parameter key: Key that identifies element to remove from bag. - returns: Element that bag contained, or nil in case element was already removed. */ public mutating func removeKey(_ key: BagKey) -> T? { if _key0 == key { _key0 = nil let value = _value0! _value0 = nil return value } if _key1 == key { _key1 = nil let value = _value1! _value1 = nil return value } if let existingObject = _dictionary?.removeValue(forKey: key) { return existingObject } for i in 0 ..< _pairs.count { if _pairs[i].key == key { let value = _pairs[i].value _pairs.remove(at: i) return value } } return nil } } extension Bag { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription : String { return "\(self.count) elements in Bag" } } // MARK: forEach extension Bag { /** Enumerates elements inside the bag. - parameter action: Enumeration closure. */ public func forEach(_ action: (T) -> Void) { if _onlyFastPath { if let value0 = _value0 { action(value0) } return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { action(value0) } if let value1 = value1 { action(value1) } for i in 0 ..< pairs.count { action(pairs[i].value) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { action(element) } } } } extension Bag where T: ObserverType { /** Dispatches `event` to app observers contained inside bag. - parameter action: Enumeration closure. */ public func on(_ event: Event<T.E>) { if _onlyFastPath { _value0?.on(event) return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { value0.on(event) } if let value1 = value1 { value1.on(event) } for i in 0 ..< pairs.count { pairs[i].value.on(event) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.on(event) } } } } /** Dispatches `dispose` to all disposables contained inside bag. */ @available(*, deprecated, renamed: "disposeAll(in:)") public func disposeAllIn(_ bag: Bag<Disposable>) { disposeAll(in: bag) } /** Dispatches `dispose` to all disposables contained inside bag. */ public func disposeAll(in bag: Bag<Disposable>) { if bag._onlyFastPath { bag._value0?.dispose() return } let pairs = bag._pairs let value0 = bag._value0 let value1 = bag._value1 let dictionary = bag._dictionary if let value0 = value0 { value0.dispose() } if let value1 = value1 { value1.dispose() } for i in 0 ..< pairs.count { pairs[i].value.dispose() } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.dispose() } } }
mit
Q42/NoticeWindow
Pod/Classes/NoticeView.swift
1
2780
// // NoticeView.swift // Pods // // Created by Tim van Steenis on 09/12/15. // // import Foundation import UIKit class NoticeView: UIView { @IBOutlet weak var horizontalStackView: UIStackView! @IBOutlet weak var leftImage: UIImageView! @IBOutlet weak var rightImage: UIImageView! @IBOutlet weak var leftImageWidth: NSLayoutConstraint! @IBOutlet weak var rightImageWidth: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! var style: NoticeViewStyle = NoticeViewStyle() { didSet { backgroundColor = style.backgroundColor titleLabel.textColor = style.textColor messageLabel.textColor = style.textColor titleLabel.numberOfLines = style.titleNumberOfLines messageLabel.numberOfLines = style.messageNumberOfLines horizontalStackView.spacing = style.imageSpacing layoutMargins = style.insets if let image = style.leftImage { leftImage.isHidden = false leftImageWidth.constant = image.width leftImage.image = image.image leftImage.tintColor = image.tintColor leftImage.contentMode = image.contentMode } else { leftImage.isHidden = true } if let image = style.rightImage { rightImage.isHidden = false rightImageWidth.constant = image.width rightImage.image = image.image rightImage.tintColor = image.tintColor rightImage.contentMode = image.contentMode } else { rightImage.isHidden = true } } } public override init(frame: CGRect) { super.init(frame: frame) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } @objc fileprivate func adjustForStatusBarFrameChanges() { guard style.position == .top else { return } // For some reason, statusBarFrame hasn't been updated yet when rotating, but it is in next event loop DispatchQueue.main.async { self.updateLayoutMarginsWithStatusBarHeight() } } override func didMoveToWindow() { super.didMoveToWindow() updateLayoutMarginsWithStatusBarHeight() } private func updateLayoutMarginsWithStatusBarHeight() { guard style.position == .top else { return } let additionalHeight = (window as? NoticeWindow)?.additionalStatusBarHeight() ?? 0 layoutMargins.top = style.insets.top + additionalHeight } }
mit
Brightify/ReactantUI
Sources/Tokenizer/Properties/AssignableProperty.swift
1
3261
// // AssignablePropertyDescription.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif /** * Standard typed property obtained from an XML attribute. */ public struct AssignableProperty<T: AttributeSupportedPropertyType>: TypedProperty { public var namespace: [PropertyContainer.Namespace] public var name: String public var description: AssignablePropertyDescription<T> public var value: T public var attributeName: String { return namespace.resolvedAttributeName(name: name) } /** * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(context: PropertyContext) -> String { return value.generate(context: context.child(for: value)) } /** * - parameter target: UI element to be targetted with the property * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(on target: String, context: PropertyContext) -> String { let namespacedTarget = namespace.resolvedSwiftName(target: target) return "\(namespacedTarget).\(description.swiftName) = \(application(context: context))" } #if SanAndreas public func dematerialize(context: PropertyContext) -> XMLSerializableAttribute { return XMLSerializableAttribute(name: attributeName, value: value.dematerialize(context: context.child(for: value))) } #endif #if canImport(UIKit) /** * Try to apply the property on an object using the passed property context. * - parameter object: UI element to apply the property to * - parameter context: property context to use */ public func apply(on object: AnyObject, context: PropertyContext) throws { let key = description.key let selector = Selector("set\(key.capitalizingFirstLetter()):") let target = try resolveTarget(for: object) guard target.responds(to: selector) else { throw LiveUIError(message: "!! Object `\(target)` doesn't respond to selector `\(key)` to set value `\(value)`") } guard let resolvedValue = value.runtimeValue(context: context.child(for: value)) else { throw LiveUIError(message: "!! Value `\(value)` couldn't be resolved in runtime for key `\(key)`") } do { try catchException { _ = target.setValue(resolvedValue, forKey: key) } } catch { _ = target.perform(selector, with: resolvedValue) } } private func resolveTarget(for object: AnyObject) throws -> AnyObject { if namespace.isEmpty { return object } else { let keyPath = namespace.resolvedKeyPath guard let target = object.value(forKeyPath: keyPath) else { throw LiveUIError(message: "!! Object \(object) doesn't have keyPath \(keyPath) to resolve real target") } return target as AnyObject } } #endif }
mit
Zewo/TrieRouteMatcher
Package.swift
1
299
import PackageDescription let package = Package( name: "TrieRouteMatcher", dependencies: [ .Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 7), .Package(url: "https://github.com/Zewo/PathParameterMiddleware.git", majorVersion: 0, minor: 7), ] )
mit
brentsimmons/Frontier
BeforeTheRename/Frontier/DB/DBViewController.swift
1
250
// // DBViewController.swift // // // Created by Brent Simmons on 4/19/17. // // import Cocoa class DBViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
gpl-2.0
mownier/pyrobase
Pyrobase/Pyrobase.swift
1
2029
// // Pyrobase.swift // Pyrobase // // Created by Mounir Ybanez on 01/05/2017. // Copyright © 2017 Ner. All rights reserved. // public class Pyrobase { internal var path: RequestPathProtocol internal var request: RequestProtocol public var baseURL: String { return path.baseURL } public init(request: RequestProtocol, path: RequestPathProtocol) { self.request = request self.path = path } public func get(path relativePath: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.read(path: path.build(relativePath), query: query) { result in completion(result) } } public func put(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .put, data: value) { result in completion(result) } } public func post(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .post, data: value) { result in completion(result) } } public func patch(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .patch, data: value) { result in completion(result) } } public func delete(path relativePath: String, completion: @escaping (RequestResult) -> Void) { request.delete(path: path.build(relativePath), completion: completion) } } extension Pyrobase { public class func create(baseURL: String, accessToken: String) -> Pyrobase { let path = RequestPath(baseURL: baseURL, accessToken: accessToken) let request = Request.create() let pyrobase = Pyrobase(request: request, path: path) return pyrobase } }
mit
Quick/Spry
Source/Spry/Core/Helpers.swift
1
327
// // Helpers.swift // Spry // // Created by Shahpour Benkau on 22/02/2017. // // import Foundation extension Sequence { func all(_ fn: (Iterator.Element) -> Bool) -> Bool { for item in self { if !fn(item) { return false } } return true } }
apache-2.0
Diego5529/tcc-swift3
tcc-swift3/src/controllers/view/form/Commons/Login.swift
2
272
// // Login.swift // Former-Demo // // Created by Ryo Aoyama on 11/8/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit final class Login { static let sharedInstance = Login() var username: String? var password: String? }
mit
lukejmann/FBLA2017
Pods/Instructions/Sources/Helpers/CoachMarkLayoutHelper.swift
1
9860
// CoachMarkLayoutHelper.swift // // Copyright (c) 2016 Frédéric Maquin <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // swiftlint:disable line_length class CoachMarkLayoutHelper { var layoutDirection: UIUserInterfaceLayoutDirection = .leftToRight // TODO: Improve the layout system. Make it smarter. func constraints(for coachMarkView: CoachMarkView, coachMark: CoachMark, parentView: UIView, layoutDirection: UIUserInterfaceLayoutDirection? = nil) -> [NSLayoutConstraint] { if coachMarkView.superview != parentView { print("coachMarkView was not added to parentView, returned constraints will be empty") return [] } if layoutDirection == nil { if #available(iOS 9, *) { self.layoutDirection = UIView.userInterfaceLayoutDirection( for: parentView.semanticContentAttribute) } } else { self.layoutDirection = layoutDirection! } let computedProperties = computeProperties(for: coachMark, inParentView: parentView) let offset = arrowOffset(for: coachMark, withProperties: computedProperties, inParentView: parentView) switch computedProperties.segmentIndex { case 1: coachMarkView.changeArrowPosition(to: .leading, offset: offset) return leadingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 2: coachMarkView.changeArrowPosition(to: .center, offset: offset) return middleConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 3: coachMarkView.changeArrowPosition(to: .trailing, offset: offset) return trailingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) default: return [NSLayoutConstraint]() } } private func leadingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } private func middleConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth)@1000)]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) constraints.append(NSLayoutConstraint( item: coachMarkView, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0 )) return constraints } private func trailingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(==\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } /// Returns the arrow offset, based on the layout and the /// segment in which the coach mark will be. /// /// - Parameter coachMark: coachmark data. /// - Parameter properties: precomputed properties. /// - Parameter parentView: view showing the coachmarks. private func arrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { var arrowOffset: CGFloat switch properties.segmentIndex { case 1: arrowOffset = leadingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 2: arrowOffset = middleArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 3: arrowOffset = trailingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) default: arrowOffset = 0 break } return arrowOffset } private func leadingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return pointOfInterest.x - coachMark.horizontalMargin } else { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } } private func middleArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.center.x - pointOfInterest.x } else { return pointOfInterest.x - parentView.center.x } } private func trailingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } else { return pointOfInterest.x - coachMark.horizontalMargin } } /// Compute the segment index (for now the screen is separated /// in three horizontal areas and depending in which one the coach /// mark stand, it will be layed out in a different way. /// /// - Parameter coachMark: coachmark data. /// - Parameter layoutDirection: the layout direction (LTR or RTL) /// - Parameter frame: frame of the parent view /// /// - Returns: the segment index (either 1, 2 or 3) private func computeSegmentIndex( of coachMark: CoachMark, forLayoutDirection layoutDirection: UIUserInterfaceLayoutDirection, inFrame frame: CGRect ) -> Int { if let pointOfInterest = coachMark.pointOfInterest { var segmentIndex = 3 * pointOfInterest.x / frame.size.width if layoutDirection == .rightToLeft { segmentIndex = 3 - segmentIndex } return Int(ceil(segmentIndex)) } else { print("The point of interest was found nil. Fallbacking to middle segment.") return 1 } } private func computeProperties(for coachMark: CoachMark, inParentView parentView: UIView) -> CoachMarkComputedProperties { let segmentIndex = computeSegmentIndex(of: coachMark, forLayoutDirection: layoutDirection, inFrame: parentView.frame) return CoachMarkComputedProperties( layoutDirection: layoutDirection, segmentIndex: segmentIndex ) } } struct CoachMarkComputedProperties { let layoutDirection: UIUserInterfaceLayoutDirection let segmentIndex: Int }
mit
keyeMyria/edx-app-ios
Source/OEXStyles+Swift.swift
4
3515
// // OEXStyles+Swift.swift // edX // // Created by Ehmad Zubair Chughtai on 25/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit extension OEXStyles { var navigationTitleTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .Base, color : navigationItemTintColor()) } var navigationButtonTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .XSmall, color: nil) } public func applyGlobalAppearance() { if (OEXConfig.sharedConfig().shouldEnableNewCourseNavigation()) { //Probably want to set the tintColor of UIWindow but it didn't seem necessary right now UINavigationBar.appearance().barTintColor = navigationBarColor() UINavigationBar.appearance().barStyle = UIBarStyle.Black UINavigationBar.appearance().tintColor = navigationItemTintColor() UINavigationBar.appearance().titleTextAttributes = navigationTitleTextStyle.attributes UIBarButtonItem.appearance().setTitleTextAttributes(navigationButtonTextStyle.attributes, forState: .Normal) UIToolbar.appearance().tintColor = navigationBarColor() let styleAttributes = OEXTextStyle(weight: .Normal, size : .Small, color : self.neutralBlack()).attributes UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Selected) UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Normal) UISegmentedControl.appearance().tintColor = self.neutralLight() } if UIDevice.currentDevice().isOSVersionAtLeast8() { UINavigationBar.appearance().translucent = false } } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTintColor : UIColor { return UIColor(red: CGFloat(126.0/255.0), green: CGFloat(199.0/255.0), blue: CGFloat(143.0/255.0), alpha: CGFloat(1.00)) } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTrackTintColor : UIColor { return UIColor(red: CGFloat(223.0/255.0), green: CGFloat(242.0/255.0), blue: CGFloat(228.0/255.0), alpha: CGFloat(1.00)) } var standardTextViewInsets : UIEdgeInsets { return UIEdgeInsetsMake(8, 8, 8, 8) } var standardFooterHeight : CGFloat { return 50 } // Standard text Styles var textAreaBodyStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: OEXTextWeight.Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) style.lineBreakMode = .ByWordWrapping return style } // Standard button styles var filledPrimaryButtonStyle : ButtonStyle { let buttonMargins : CGFloat = 8 let borderStyle = BorderStyle() let textStyle = OEXTextStyle(weight: .Normal, size: .Small, color: self.neutralWhite()) return ButtonStyle(textStyle: textStyle, backgroundColor: OEXStyles.sharedStyles().primaryBaseColor(), borderStyle: borderStyle, contentInsets : UIEdgeInsetsMake(buttonMargins, buttonMargins, buttonMargins, buttonMargins)) } // Standard border styles var entryFieldBorderStyle : BorderStyle { return BorderStyle(width: .Size(1), color: OEXStyles.sharedStyles().neutralLight()) } }
apache-2.0
relayr/apple-sdk
Sources/common/services/API/APIUsers.swift
1
7530
import ReactiveSwift import Result import Foundation internal extension API { /// User entity as represented on the relayr API platform. struct User: JSONable { let identifier: String var email: String? var nickname: String? var name: (first: String?, last: String?) var companyName: String? var industryArea: String? } } /// Instances of conforming type can request OAuth codes from the cloud servers. /// /// An OAuth code is the first step on an OAuth login process. Arm with the code, you can request an OAuth token. internal protocol OAuthCodeRetrievable { /// It request an OAuth code to the instance of the conforming type. /// The OAuth process won't start till a `start()` message is send to the `SignalProducer`. static func requestOAuthCode(toURL url: String, withRedirectURI redirectURI: String, willAnimate: Bool, cancellableButton: Bool) -> SignalProducer<String,API.Error> } // HTTP APIs for user related endpoints. internal extension API { /// Requests information about the user currently logged in which owns this API instance. func currentUserInfo() -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/user-info") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.User(fromJSON: json) } } } /// Updates the user with the arguments passed. /// /// If no arguments are given, no HTTP call is performed and an error is returned. /// - parameter firstName: Modify the user's first name. /// - parameter lastName: Modify the user's last name. /// - parameter companyName: Modify the user's company name. /// - parameter industryArea: Modify the user's company area. func setUserInfo(withID userID: String, firstName: String?=nil, lastName: String?=nil, companyName: String?=nil, industryArea: String?=nil) -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)") var body: [String:String] = [:] if let firstName = firstName { body[User.Keys.firstName] = firstName } if let lastName = lastName { body[User.Keys.lastName] = lastName } if let company = companyName { body[User.Keys.companyName] = company } if let industry = industryArea { body[User.Keys.industryArea] = industry } guard !body.isEmpty else { return SignalProducer(error: .insufficientInformation) } return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Patch, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json: [String:Any]) in Result { guard let data = json["data"] as? [String:Any] else { throw API.Error.invalidResponseBody(body: json) } return try API.User(fromJSON: data) } } } // MARK: Login & Tokens #if os(macOS) || os(iOS) /// It requests the temporal access OAuth code needed to ask for a 100 year OAuth access token. /// - parameter clientID: `String` representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: `String` representing the redirect URI you chosed when creating an app in the relayr developer platform. func oauthCode(withProjectID projectID: String, oauthRedirectURI redirectURI: String, willAnimate: Bool=false, cancellableButton: Bool=true) -> SignalProducer<String,API.Error> { let scope = "access-own-user-info+configure-devices+read-device-history" let relativePath = "oauth2/auth?client_id=\(projectID)&redirect_uri=\(redirectURI)&response_type=code&scope=\(scope)" let url = Addresses.build(withHostURL: urls.root, relativeURL: relativePath) return WebOAuthController.requestOAuthCode(toURL: url, withRedirectURI: redirectURI, willAnimate: willAnimate, cancellableButton: cancellableButton) } #endif /// It request a valid OAuth token from an OAuth code, clientID, clientSecret, and redirectURI. /// - parameter tmpCode: Temporal OAuth code (usually valid for 5 minutes) that it is required to retrieve a token. /// - parameter projectID: String representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter oauthSecret: String representing the Oauth client secret. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: String representing the redirect URI you chosed when creating an app in the Relayr developer platform. func oauthToken(withTemporalCode tmpCode: String, projectID: String, oauthSecret: String, redirectURI: String) -> SignalProducer<String,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/token") let body = ["code": tmpCode, "client_id": projectID, "redirect_uri": redirectURI, "scope": "", "client_secret": oauthSecret, "grant_type": "authorization_code"] return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Post, contentType: .Xform, body: body, expectedCodes: [200]).attemptMap { (json : [String:Any]) in let token = json["access_token"] as? String return Result(token, failWith: .invalidResponseBody(body: json)) } } } internal extension API.User { typealias JSONType = [String:Any] init(fromJSON json: JSONType) throws { guard let identifier = json[Keys.identifier] as? String else { throw API.Error.invalidResponseBody(body: json) } self.identifier = identifier self.email = json[Keys.email] as? String self.nickname = json[Keys.name] as? String self.name = (json[Keys.firstName] as? String, json[Keys.lastName] as? String) self.companyName = json[Keys.companyName] as? String self.industryArea = json[Keys.industryArea] as? String } var json: JSONType { var result: JSONType = [Keys.identifier: self.identifier] if let email = self.email { result[Keys.email] = email } if let nickname = self.nickname { result[Keys.name] = nickname } if let firstName = self.name.first { result[Keys.firstName] = firstName } if let lastName = self.name.last { result[Keys.lastName] = lastName } if let company = self.companyName { result[Keys.companyName] = company } if let industry = self.industryArea { result[Keys.industryArea] = industry } return result } fileprivate init(withIdentifier identifier: String, email: String?=nil, nickname: String?=nil, firstName: String?=nil, lastName: String?=nil, company: String?=nil, industry: String?=nil) { self.identifier = identifier self.email = email self.nickname = nickname self.name = (firstName, lastName) self.companyName = company self.industryArea = industry } fileprivate struct Keys { static let identifier = "id" static let email = "email" static let name = "name" fileprivate static let firstName = "firstName" static let lastName = "lastName" static let companyName = "companyName" static let industryArea = "industryArea" } }
mit
tomas789/JustLog
JustLog/Extensions/Data+Representation.swift
1
304
// // Data+Representation.swift // JustLog // // Created by Alberto De Bortoli on 15/12/2016. // Copyright © 2017 Just Eat. All rights reserved. // import Foundation extension Data { func stringRepresentation() -> String { return String(data: self, encoding: .utf8) ?? "" } }
apache-2.0
dnosk/Explore
Example/Explore/ViewController.swift
1
1164
// // ViewController.swift // Explore // // Created by dnosk on 04/26/2017. // Copyright (c) 2017 dnosk. All rights reserved. // import Explore import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var appsDownloaded = [String]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self appsDownloaded = exploreAppsDownloaded() tableView.reloadData() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appsDownloaded.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let app = appsDownloaded[indexPath.row] cell.textLabel?.text = app return cell } }
mit
bm842/TradingLibrary
Sources/OandaRestV1Instrument.swift
2
9009
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import Foundation public final class OandaInstrument: GenericInstrument, Instrument { weak var oandaAccount: OandaRestAccount! { return account as! OandaRestAccount } weak var oanda: OandaRestBroker! init(account: OandaRestAccount, instrumentData: OandaRestV1Instrument) { self.oanda = account.oanda let instrument = instrumentData.instrument let elements = instrument.components(separatedBy: "_") super.init(instrument: instrument, displayName: instrumentData.displayName, pip: instrumentData.pip, minTradeUnits: 1, maxTradeUnits: instrumentData.maxTradeUnits, precision: instrumentData.precision, marginRate: instrumentData.marginRate, base: Currency(rawValue: elements[0]), quote: Currency(rawValue: elements[1])!) self.account = account } public override func stopRateEventsStreaming() { oanda.ratesStreamingConnection.stopStreaming() } public override func startRateEventsStreaming(_ queue: DispatchQueue, handler: @escaping (RatesEvent) -> ()) -> RequestStatus { var query = "prices?" query += "accountId=\(oandaAccount.id)" query += "&instruments=" + instrument return oanda.ratesStreamingConnection.startStreaming(query) { (status, json) in guard let json = json else { queue.async { handler(.status(time: Timestamp.now, status: status)) } return } if let price: OandaRestV1Price = try? json.value(for: "tick") { queue.async { handler(.tickEvent(tick: Tick(fromOanda: price))) } return } if let heartbeat: OandaRestV1Heartbeat = try? json.value(for: "heartbeat") { queue.async { handler(.heartBeat(time: Timestamp(microSeconds: heartbeat.time))) } return } log.error("%f: unexpected json = \(json)") } } public override func submitOrder(_ info: OrderCreation, completion: @escaping (RequestStatus, _ execution: OrderExecution) -> ()) { var params: String = "type=\(info.type.oandaValue)" params += "&side=\(info.side.oandaValue)" params += "&units=\(info.units)" params += "&instrument=\(instrument)" params += "&stopLoss=\(info.stopLoss ?? 0)" params += "&takeProfit=\(info.takeProfit ?? 0)" params += "&price=\(info.entry ?? 0)" params += "&expiry=\(info.expiry?.oandaRestV1Value ?? 0)" /*params += "&lowerBound=\(lowerBound)" params += "&upperBound=\(upperBound)" params += "&trailingStop=\(trailingStop)"*/ oanda.restConnection.fetchJson("accounts/\(oandaAccount.id)/orders", method: "POST", data: params) { (status, json) in var execution: OrderExecution = .none guard let json = json else { log.error("no json, status = \(status) creation=\(info)") return } do { let response = try OandaRestV1CreateOrderResponse(object: json) let time = Timestamp(microSeconds: response.time) if let orderOpened = response.orderOpened { let openedOrder = OrderInfo(orderId: "\(orderOpened.id)", time: time, type: info.type, side: info.side, units: info.units, entry: response.price, stopLoss: nilIfZero(orderOpened.stopLoss), takeProfit: nilIfZero(orderOpened.takeProfit), expiry: Timestamp(microSeconds: orderOpened.expiry)) let order = OandaOrder(instrument: self, info: openedOrder) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenOrders.append(order) } self.notify(tradeEvent: .orderCreated(info: openedOrder)) execution = .orderCreated(orderId: openedOrder.orderId) } if let tradeOpened = response.tradeOpened { let createdTrade = TradeInfo(tradeId: "\(tradeOpened.id)", time: time, side: info.side, units: tradeOpened.units, entry: response.price, stopLoss: nilIfZero(tradeOpened.stopLoss), takeProfit: nilIfZero(tradeOpened.takeProfit)) let trade = OandaTrade(instrument: self, info: createdTrade) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenTrades.append(trade) } self.notify(tradeEvent: .tradeCreated(info: createdTrade)) execution = .orderFilled(tradeId: createdTrade.tradeId) } if let tradesClosed = response.tradesClosed { for tradeClosed in tradesClosed { self.reduceTrade(withId: "\(tradeClosed.id)", atTime: time, units: tradeClosed.units, atPrice: response.price, reason: .reverseOrder) } } if let tradeReduced = response.tradeReduced { self.reduceTrade(withId: "\(tradeReduced.id)", atTime: time, units: tradeReduced.units, atPrice: response.price, reason: .reverseOrder) } completion(status, execution) } catch { completion(OandaStatus.jsonParsingError(error), execution) } } } public override func quote(_ completion: @escaping (RequestStatus, _ tick: Tick?) -> ()) { oanda.restConnection.fetchArray("prices", query: "instruments=" + instrument) { (status, prices: [OandaRestV1Price]?) in if let setPrices = prices { for price in setPrices where price.instrument == self.instrument { completion(status, Tick(fromOanda: price)) break } } else { completion(status, nil) } } } }
mit
pocketworks/Dollar.swift
Cent/Cent/Int.swift
1
2807
// // Int.swift // Cent // // Created by Ankur Patel on 6/30/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation extension Int { /// Invoke a callback n times /// /// :param callback The function to invoke that accepts the index public func times(callback: (Int) -> ()) { (0..<self).eachWithIndex { callback($0) } } /// Invoke a callback n times /// /// :param callback The function to invoke public func times(function: () -> ()) { self.times { (index: Int) -> () in function() } } /// Check if it is even /// /// :return Bool whether int is even public var isEven: Bool { get { return self % 2 == 0 } } /// Check if it is odd /// /// :return Bool whether int is odd public var isOdd: Bool { get { return self % 2 == 1 } } /// Splits the int into array of digits /// /// :return Bool whether int is odd public func digits() -> [Int] { var digits: [Int] = [] var selfCopy = self while selfCopy > 0 { digits << (selfCopy % 10) selfCopy = (selfCopy / 10) } return Array(digits.reverse()) } /// Get the next int /// /// :return next int public func next() -> Int { return self + 1 } /// Get the previous int /// /// :return previous int public func prev() -> Int { return self - 1 } /// Invoke the callback from int up to and including limit /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: () -> ()) { (self...limit).each { callback() } } /// Invoke the callback from int up to and including limit passing the index /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: (Int) -> ()) { (self...limit).eachWithIndex { callback($0) } } /// Invoke the callback from int down to and including limit /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: () -> ()) { var selfCopy = self while selfCopy-- >= limit { callback() } } /// Invoke the callback from int down to and including limit passing the index /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: (Int) -> ()) { var selfCopy = self while selfCopy >= limit { callback(selfCopy--) } } }
mit
natecook1000/swift
test/PlaygroundTransform/high_performance.swift
7
1253
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main2 %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] __builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='5'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var b = true for i in 0..<3 { i continue } // CHECK-NEXT: [{{.*}}] __builtin_log[b='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var c = true for i in 0..<3 { i break } // CHECK-NEXT: [{{.*}}] __builtin_log[c='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0']
apache-2.0
danfsd/FolioReaderKit
Example/Example/ViewController.swift
1
1987
// // ViewController.swift // Example // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import FolioReaderKit class ViewController: UIViewController { @IBOutlet var bookOne: UIButton! @IBOutlet var bookTwo: UIButton! let epubSampleFiles = [ "The Silver Chair", // standard eBook // "Medcel", "The Adventures Of Sherlock Holmes - Adventure I", // audio-eBook ] override func viewDidLoad() { super.viewDidLoad() setCover(bookOne, index: 0) setCover(bookTwo, index: 1) } @IBAction func didOpen(sender: AnyObject) { openEpub(sender.tag); } func openEpub(sampleNum: Int) { let config = FolioReaderConfig() config.shouldHideNavigationOnTap = sampleNum == 1 ? true : false config.scrollDirection = sampleNum == 1 ? .horizontal : .vertical // See more at FolioReaderConfig.swift // config.enableTTS = false // config.allowSharing = false // config.tintColor = UIColor.blueColor() // config.toolBarTintColor = UIColor.redColor() // config.toolBarBackgroundColor = UIColor.purpleColor() // config.menuTextColor = UIColor.brownColor() // config.menuBackgroundColor = UIColor.lightGrayColor() let epubName = epubSampleFiles[sampleNum-1]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") FolioReader.presentReader(parentViewController: self, withEpubPath: bookPath!, andConfig: config, shouldRemoveEpub: false) } func setCover(button: UIButton, index: Int) { let epubName = epubSampleFiles[index]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") if let image = FolioReader.getCoverImage(bookPath!) { button.setBackgroundImage(image, forState: .Normal) } } }
bsd-3-clause
coodly/TalkToCloud
Sources/TalkToCloud/APIKeyConsumer.swift
1
683
/* * Copyright 2016 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public protocol APIKeyConsumer { var apiKeyID: String! { get set } }
apache-2.0
codercd/DPlayer
DPlayer/Model.swift
1
1721
// // Model.swift // DPlayer // // Created by LiChendi on 16/4/19. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit class Model: NSObject { } enum LiveBaseURL:String { case rtmp = "rtmp://live.quanmin.tv/live/1456011" case hls = "http://hls.quanmin.tv/live/1456011/playlist.m3u8" case flv = "http://flv.quanmin.tv/live/1456011.flv" } //struct HomepageModel { // var homepageCategories = Array<HomepageCategory>() // // // var list = Array<AnyObject>() { // willSet { //// print("will - list---- \(newValue)") // } // } // var homepageItems = Dictionary<String, AnyObject>() { // willSet { // for categories in newValue { // var homepageCategory = HomepageCategory() // homepageCategory.name = categories.0 // homepageCategory.detail = categories.1 as! Array<AnyObject> // homepageCategories.append(homepageCategory) // } // } // } //} //struct HomepageCategory { // var name = "" { // willSet { // print("name----\(newValue)") // } // } // var detail = Array<AnyObject>() { // willSet { // print("detail----\(newValue)") //// RoomDetail(). // } // } //} struct recommendList { // var } struct RoomDetail { var stateus = 0 var follow = 0 var avatar = "" var view = 0 var intro = "" var slug = "" var category_id = 0 var category_name = "" var category_slug = "" var recommend_image = "" var nick = "" var play_at = "" var announcement = "" var title = "" var uid = "" var thumb = "" }
mit
wunshine/FoodStyle
FoodStyle/FoodStyle/Classes/View/WXTextField.swift
1
845
// // WXTextField.swift // FoodStyle // // Created by Woz Wong on 16/3/5. // Copyright © 2016年 code4Fun. All rights reserved. // import UIKit class WXTextField: UITextField { override func textRectForBounds(bounds: CGRect) -> CGRect { super.textRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { super.placeholderRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } override func editingRectForBounds(bounds: CGRect) -> CGRect { super.editingRectForBounds(bounds) return CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width, bounds.size.height) } }
mit
ociata/OCIKeyboardAdjuster
OCIKeyboardAdjuster.swift
1
7643
// // KeyboardAdjuster.swift // // // Created by Hristo Todorov - Oci on 6/5/15. // Copyright (c) 2015 // import UIKit class OCIKeyboardAdjuster: NSObject { static let sharedKeyboardAdjuster = OCIKeyboardAdjuster() weak var focusedControl: UIView? private override init() { //this way users will always use singleton instance } private(set) weak var scrollView: UIScrollView? private(set) weak var view: UIView! private var originalScrollOffset: CGPoint? private var originalScrollSize: CGSize? func startObserving(scrollableView: UIScrollView, holderView: UIView) { scrollView = scrollableView view = holderView //remove old observers stopObserving() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func stopObserving() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: scrollview ajust when keyboard present @objc private func keyboardWillShow(notification: NSNotification) { if nil == self.view || self.view.window == nil { return } if let scrollView = scrollView, let userInfo = notification.userInfo, let keyboardFrameInWindow = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let keyboardFrameInWindowBegin = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { // the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view let keyboardFrameInView = self.view.convertRect(keyboardFrameInWindow.CGRectValue(), fromView: nil) let scrollViewKeyboardIntersection = CGRectIntersection(scrollView.frame, keyboardFrameInView) UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { [weak self] in if let strongSelf = self, let scrollView = strongSelf.scrollView { if let focusedControl = strongSelf.focusedControl { // if the control is a deep in the hierarchy below the scroll view, this will calculate the frame as if it were a direct subview var controlFrameInScrollView = scrollView.convertRect(focusedControl.bounds, fromView: focusedControl) controlFrameInScrollView = CGRectInset(controlFrameInScrollView, 0, -10) let controlVisualOffsetToTopOfScrollview = controlFrameInScrollView.origin.y - scrollView.contentOffset.y let controlVisualBottom = controlVisualOffsetToTopOfScrollview + controlFrameInScrollView.size.height // this is the visible part of the scroll view that is not hidden by the keyboard let scrollViewVisibleHeight = scrollView.frame.size.height - scrollViewKeyboardIntersection.size.height var newContentOffset = scrollView.contentOffset //store it to better update latter strongSelf.originalScrollOffset = newContentOffset if controlVisualBottom > scrollViewVisibleHeight // check if the keyboard will hide the control in question { newContentOffset.y += (controlVisualBottom - scrollViewVisibleHeight) //check for impossible offset newContentOffset.y = min(newContentOffset.y, scrollView.contentSize.height - scrollViewVisibleHeight) } else if controlFrameInScrollView.origin.y < scrollView.contentOffset.y // if the control is not fully visible, make it so (useful if the user taps on a partially visible input field { newContentOffset.y = controlFrameInScrollView.origin.y } //no animation as we had own animation already going scrollView.setContentOffset(newContentOffset, animated: false) } var scrollSize = scrollView.contentSize if let _ = strongSelf.originalScrollSize { //subtract old keyboard value scrollSize.height -= strongSelf.view.convertRect(keyboardFrameInWindowBegin.CGRectValue(), fromView: nil).size.height } strongSelf.originalScrollSize = scrollSize scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollSize.height + keyboardFrameInView.height) } }, completion: nil) } } @objc private func keyboardWillHide(notification: NSNotification) { if self.view == nil || self.view.window == nil { return } if let _ = scrollView, let userInfo = notification.userInfo, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { if let scrollView = self.scrollView { if let originalContentSize = self.originalScrollSize { scrollView.contentSize = originalContentSize } if let originalScrollOffset = self.originalScrollOffset { scrollView.setContentOffset( originalScrollOffset, animated: false) } } }, completion: { success in self.originalScrollOffset = nil self.originalScrollSize = nil }) } } }
mit
RCacheaux/BitbucketKit
Carthage/Checkouts/Swinject/Sources/SwinjectStoryboard/Container+SwinjectStoryboard.swift
1
2302
// // Container+SwinjectStoryboard.swift // Swinject // // Created by Yoichi Tagaya on 11/28/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // #if os(iOS) || os(OSX) || os(tvOS) extension Container { /// Adds a registration of the specified view or window controller that is configured in a storyboard. /// /// - Note: Do NOT explicitly resolve the controller registered by this method. /// The controller is intended to be resolved by `SwinjectStoryboard` implicitly. /// /// - 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: (ResolverType, C) -> ()) { // Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7. // The actual controller type is distinguished by the dynamic type name in `nameWithActualType`. let nameWithActualType = String(reflecting: controllerType) + ":" + (name ?? "") let wrappingClosure: (ResolverType, Controller) -> () = { r, c in initCompleted(r, c as! C) } self.register(Controller.self, name: nameWithActualType) { (_: ResolverType, controller: Controller) in controller } .initCompleted(wrappingClosure) } } #endif extension Container { #if os(iOS) || os(tvOS) /// The typealias to UIViewController. public typealias Controller = UIViewController #elseif os(OSX) /// The typealias to AnyObject, which should be actually NSViewController or NSWindowController. /// See the reference of NSStoryboard.instantiateInitialController method. public typealias Controller = AnyObject #endif }
apache-2.0
adamnemecek/SortedArray.swift
Cmdline/main.swift
1
931
// // main.swift // Cmdline // // Created by Adam Nemecek on 5/6/17. // // import Foundation import SortedArray let s = SortedSet([5,2,1,2,3,6,7,8]) let a = [1,2,3,4,5,6] let b = [1, 2, 2, 3, 3, 5, 6] print(b) //var u = UnionIterator(a: a, b: b) { $0 < $1 } //print(s.contains(1)) //while let n = u.next() { // print(n) //} // //struct UniqueSequence<Element : Equatable> : IteratorProtocol { // private var i: AnyIterator<Element> //// // private var last : Element? // // init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element { // self.i = AnyIterator(sequence.makeIterator()) // last = i.next() // } // // func next() -> Element? { // return nil //// while let n = i.next() { //// //// } // } //} let c = SortedSet(b) //let ii = s.intersection(c) //print(s.intersection(c)) for e in s.symmetricDifference(c) { print(e) }
mit
KBryan/SwiftFoundation
Darwin Support/NSUUID.swift
1
1268
// // NSUUID.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/4/15. // Copyright © 2015 PureSwift. All rights reserved. // import Foundation public extension NSUUID { convenience init(byteValue: uuid_t) { var value = byteValue let buffer = withUnsafeMutablePointer(&value, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> UnsafeMutablePointer<UInt8> in let bufferType = UnsafeMutablePointer<UInt8>.self return unsafeBitCast(valuePointer, bufferType) }) self.init(UUIDBytes: buffer) } var byteValue: uuid_t { var uuid = uuid_t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) withUnsafeMutablePointer(&uuid, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> Void in let bufferType = UnsafeMutablePointer<UInt8>.self let buffer = unsafeBitCast(valuePointer, bufferType) self.getUUIDBytes(buffer) }) return uuid } var rawValue: String { return UUIDString } convenience init?(rawValue: String) { self.init(UUIDString: rawValue) } }
mit
chizcake/ReplayKitExample
ReplayKitExampleStarter/Carthage/Checkouts/CleanroomLogger/Tests/CleanroomLoggerTests/LogSeverityTests.swift
2
974
// // LogSeverityTests.swift // Cleanroom Project // // Created by Claudio Romandini on 5/19/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import XCTest import CleanroomLogger class LogSeverityTests: XCTestCase { func testLogSeverityEquality() { XCTAssertTrue(LogSeverity.debug == LogSeverity.debug, "Debug should be equal to itself.") XCTAssertTrue(LogSeverity.info != LogSeverity.warning, "Info should be not equal to Warning.") } func testLogSeverityComparableImplementation() { XCTAssertTrue(LogSeverity.verbose < LogSeverity.debug, "Verbose should be less than Debug.") XCTAssertTrue(LogSeverity.info >= LogSeverity.debug, "Info should be greater than or equal to Debug.") XCTAssertTrue(LogSeverity.warning > LogSeverity.info, "Warning should be greater than Info.") XCTAssertTrue(LogSeverity.warning <= LogSeverity.error, "Warning should be less than or equal to Error.") } }
mit
EstebanVallejo/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/MercadoPago.swift
1
17199
// // MercadoPago.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class MercadoPago : NSObject { public class var PUBLIC_KEY : String { return "public_key" } public class var PRIVATE_KEY : String { return "private_key" } public class var ERROR_KEY_CODE : Int { return -1 } public class var ERROR_API_CODE : Int { return -2 } public class var ERROR_UNKNOWN_CODE : Int { return -3 } public class var ERROR_NOT_INSTALLMENTS_FOUND : Int { return -4 } public class var ERROR_PAYMENT : Int { return -4 } let BIN_LENGTH : Int = 6 let MP_API_BASE_URL : String = "https://api.mercadopago.com" public var privateKey : String? public var publicKey : String? public var paymentMethodId : String? public var paymentTypeId : String? public init (publicKey: String) { self.publicKey = publicKey } public init (keyType: String?, key: String?) { if keyType != nil && key != nil { if keyType != MercadoPago.PUBLIC_KEY && keyType != MercadoPago.PRIVATE_KEY { fatalError("keyType must be 'public_key' or 'private_key'.") } else { if keyType == MercadoPago.PUBLIC_KEY { self.publicKey = key } else if keyType == MercadoPago.PUBLIC_KEY { self.privateKey = key } } } else { fatalError("keyType and key cannot be nil.") } } public class func startCustomerCardsViewController(cards: [Card], callback: (selectedCard: Card?) -> Void) -> CustomerCardsViewController { return CustomerCardsViewController(cards: cards, callback: callback) } public class func startNewCardViewController(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: (cardToken: CardToken) -> Void) -> NewCardViewController { return NewCardViewController(keyType: keyType, key: key, paymentMethod: paymentMethod, requireSecurityCode: requireSecurityCode, callback: callback) } public class func startPaymentMethodsViewController(merchantPublicKey: String, supportedPaymentTypes: [String], callback:(paymentMethod: PaymentMethod) -> Void) -> PaymentMethodsViewController { return PaymentMethodsViewController(merchantPublicKey: merchantPublicKey, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public class func startIssuersViewController(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (issuer: Issuer) -> Void) -> IssuersViewController { return IssuersViewController(merchantPublicKey: merchantPublicKey, paymentMethod: paymentMethod, callback: callback) } public class func startInstallmentsViewController(payerCosts: [PayerCost], amount: Double, callback: (payerCost: PayerCost?) -> Void) -> InstallmentsViewController { return InstallmentsViewController(payerCosts: payerCosts, amount: amount, callback: callback) } public class func startCongratsViewController(payment: Payment, paymentMethod: PaymentMethod) -> CongratsViewController { return CongratsViewController(payment: payment, paymentMethod: paymentMethod) } public class func startPromosViewController(merchantPublicKey: String) -> PromoViewController { return PromoViewController(publicKey: merchantPublicKey) } public class func startVaultViewController(merchantPublicKey: String, merchantBaseUrl: String?, merchantGetCustomerUri: String?, merchantAccessToken: String?, amount: Double, supportedPaymentTypes: [String], callback: (paymentMethod: PaymentMethod, tokenId: String?, issuerId: Int64?, installments: Int) -> Void) -> VaultViewController { return VaultViewController(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, amount: amount, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public func createNewCardToken(cardToken : CardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { cardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, cardToken: cardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func createToken(savedCardToken : SavedCardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { savedCardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, savedCardToken: savedCardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPaymentMethods(success: (paymentMethods: [PaymentMethod]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getPaymentMethods(public_key: self.publicKey!, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var pms : [PaymentMethod] = [PaymentMethod]() if paymentMethods != nil { for i in 0..<paymentMethods!.count { if let pmDic = paymentMethods![i] as? NSDictionary { pms.append(PaymentMethod.fromJSON(pmDic)) } } } success(paymentMethods: pms) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIdentificationTypes(success: (identificationTypes: [IdentificationType]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : IdentificationService = IdentificationService(baseURL: MP_API_BASE_URL) service.getIdentificationTypes(public_key: self.publicKey, privateKey: self.privateKey, success: {(jsonResult: AnyObject?) -> Void in if let error = jsonResult as? NSDictionary { if (error["status"]! as? Int) == 404 { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_API_CODE, userInfo: error as [NSObject : AnyObject])) } } } else { var identificationTypesResult = jsonResult as? NSArray? var identificationTypes : [IdentificationType] = [IdentificationType]() if identificationTypesResult != nil { for var i = 0; i < identificationTypesResult!!.count; i++ { if let identificationTypeDic = identificationTypesResult!![i] as? NSDictionary { identificationTypes.append(IdentificationType.fromJSON(identificationTypeDic)) } } } success(identificationTypes: identificationTypes) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getInstallments(bin: String, amount: Double, issuerId: Int64?, paymentTypeId: String, success: (installments: [Installment]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getInstallments(public_key: self.publicKey!, bin: bin, amount: amount, issuer_id: issuerId, payment_type_id: paymentTypeId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var installments : [Installment] = [Installment]() if paymentMethods != nil && paymentMethods?.count > 0 { if let dic = paymentMethods![0] as? NSDictionary { installments.append(Installment.fromJSON(dic)) } success(installments: installments) } else { var error : NSError = NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_NOT_INSTALLMENTS_FOUND, userInfo: ["message": "NOT_INSTALLMENTS_FOUND".localized + "\(amount)"]) failure?(error: error) } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIssuers(paymentMethodId : String, success: (issuers: [Issuer]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getIssuers(public_key: self.publicKey!, payment_method_id: paymentMethodId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var issuersArray = jsonResult as? NSArray var issuers : [Issuer] = [Issuer]() if issuersArray != nil { for i in 0..<issuersArray!.count { if let issuerDic = issuersArray![i] as? NSDictionary { issuers.append(Issuer.fromJSON(issuerDic)) } } } success(issuers: issuers) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPromos(success: (promos: [Promo]?) -> Void, failure: ((error: NSError) -> Void)?) { // TODO: Está hecho para MLA fijo porque va a cambiar la URL para que dependa de una API y una public key let service : PromosService = PromosService(baseURL: MP_API_BASE_URL) service.getPromos(public_key: self.publicKey!, success: { (jsonResult) -> Void in var promosArray = jsonResult as? NSArray? var promos : [Promo] = [Promo]() if promosArray != nil { for var i = 0; i < promosArray!!.count; i++ { if let promoDic = promosArray!![i] as? NSDictionary { promos.append(Promo.fromJSON(promoDic)) } } } success(promos: promos) }, failure: failure) } public class func isCardPaymentType(paymentTypeId: String) -> Bool { if paymentTypeId == "credit_card" || paymentTypeId == "debit_card" || paymentTypeId == "prepaid_card" { return true } return false } public class func getBundle() -> NSBundle? { var bundle : NSBundle? = nil var privatePath = NSBundle.mainBundle().privateFrameworksPath if privatePath != nil { var path = privatePath!.stringByAppendingPathComponent("MercadoPagoSDK.framework") return NSBundle(path: path) } return nil } public class func getImage(name: String) -> UIImage? { var bundle = getBundle() if (UIDevice.currentDevice().systemVersion as NSString).compare("8.0", options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending { var nameArr = split(name) {$0 == "."} var imageExtension : String = nameArr[1] var imageName : String = nameArr[0] var filePath = bundle?.pathForResource(name, ofType: imageExtension) if filePath != nil { return UIImage(contentsOfFile: filePath!) } else { return nil } } return UIImage(named:name, inBundle: bundle, compatibleWithTraitCollection:nil) } public class func screenBoundsFixedToPortraitOrientation() -> CGRect { var screenSize : CGRect = UIScreen.mainScreen().bounds if NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 && UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { return CGRectMake(0.0, 0.0, screenSize.height, screenSize.width) } return screenSize } public class func showAlertViewWithError(error: NSError?, nav: UINavigationController?) { let msgDefault = "An error occurred while processing your request. Please try again." var msg : String? = msgDefault if error != nil { msg = error!.userInfo!["message"] as? String } let alert = UIAlertController() alert.title = "MercadoPago Error" alert.message = "Error = \(msg != nil ? msg! : msgDefault)" alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in switch action.style{ case .Default: nav!.popViewControllerAnimated(true) case .Cancel: println("cancel") case .Destructive: println("destructive") } })) nav!.presentViewController(alert, animated: true, completion: nil) } }
mit
xmartlabs/XLSlidingContainer
Example/Example/ScrollViewController.swift
1
1800
// // ScrollViewController.swift // // Copyright (c) 2017 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 import SlidingContainer class ScrollViewController: UIViewController, ContainedViewController { private var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: UIImage(named: "stonehenge")!) let scrollView = UIScrollView() scrollView.addSubview(imageView) scrollView.contentSize = imageView.bounds.size view = scrollView } func didMinimizeControllerWith(diff: CGFloat) { view.alpha = 0.3 } func didMaximizeControllerWith(diff: CGFloat) { view.alpha = 1.0 } }
mit
abdullahselek/SwiftyNotifications
Sample/Sample/ViewController.swift
1
2983
// // ViewController.swift // Sample // // Created by Abdullah Selek on 03/04/2017. // Copyright © 2017 Abdullah Selek. All rights reserved. // import UIKit import SwiftyNotifications class ViewController: UIViewController, SwiftyNotificationsDelegate { private var notification: SwiftyNotifications! private var customNotification: SwiftyNotifications! override func viewDidLoad() { super.viewDidLoad() notification = SwiftyNotifications.withStyle(style: .info, title: "Swifty Notifications", subtitle: "Highly configurable iOS UIView for presenting notifications that doesn't block the UI", direction: .bottom) notification.delegate = self notification.addTouchHandler { } notification.addSwipeGestureRecognizer(direction: .down) view.addSubview(notification) customNotification = SwiftyNotifications.withStyle(style: .custom, title: "Custom", subtitle: "Custom notification with custom image and colors", direction: .top) customNotification.leftAccessoryView.image = UIImage(named: "apple_logo")! customNotification.setCustomColors(backgroundColor: UIColor.cyan, textColor: UIColor.white) view.addSubview(customNotification) } @IBAction func show(_ sender: Any) { notification.show() } @IBAction func dismiss(_ sender: Any) { if customNotification != nil { customNotification.dismiss() } notification.dismiss() } @IBAction func changeStyle(_ sender: Any) { let style = (sender as! UIButton).tag switch style { case 0: notification.customize(style: .normal) break case 1: notification.customize(style: .error) break case 2: notification.customize(style: .success) break case 3: notification.customize(style: .info) break case 4: notification.customize(style: .warning) break case 5: notification.dismiss() customNotification.show() break default: break } } // MARK: SwiftyNotifications Delegates func willShowNotification(notification: UIView) { } func didShowNotification(notification: UIView) { } func willDismissNotification(notification: UIView) { } func didDismissNotification(notification: UIView) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
tarun-talentica/TalNet
Source/Request/NetworkService.swift
2
1023
// // NetworkService.swift // GSignIn // // Created by Tarun Sharma on 07/05/16. // Copyright © 2016 Appcoda. All rights reserved. // import Foundation public protocol NetworkService { var host: String { get } var port: Int? {get} var scheme: String { get } var serviceType: NSURLRequestNetworkServiceType { get } func refreshAccessToken(request request: NSMutableURLRequest,completionHandler:(NSMutableURLRequest,Bool)->Void) func authorizeRequest(request: NSMutableURLRequest) -> NSMutableURLRequest } public extension NetworkService { var port: Int? { return nil } /// Network service has network service type as default var serviceType: NSURLRequestNetworkServiceType { return .NetworkServiceTypeDefault } func refreshAccessToken(request request: NSMutableURLRequest,completionHandler:(NSMutableURLRequest,Bool)->Void){ completionHandler(request,true) } func authorizeRequest(request: NSMutableURLRequest) -> NSMutableURLRequest { return request } }
mit
agrippa1994/iOS-PLC
PLC/CoreData/Entities/StaticData+CoreDataProperties.swift
1
374
// // StaticData+CoreDataProperties.swift // PLC // // Created by Manuel Stampfl on 08.09.15. // Copyright © 2015 mani1337. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension StaticData { }
mit
kallahir/MarvelFinder
MarvelFinder/CharacterDetailCollectionCell.swift
1
359
// // CharacterDetailCollectionCell.swift // MarvelFinder // // Created by Itallo Rossi Lucas on 10/01/17. // Copyright © 2017 Kallahir Labs. All rights reserved. // import UIKit class CharacterDetailCollectionCell: UICollectionViewCell { @IBOutlet weak var collectionImage: UIImageView! @IBOutlet weak var collectionName: UILabel! }
mit
wireapp/wire-ios
Wire-iOS Tests/DeviceManagement/CoreDataFixture+MockUserClient.swift
1
1530
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire extension CoreDataFixture { func mockUserClient(fingerprintString: String = "102030405060708090102030405060708090102030405060708090") -> UserClient! { let client = UserClient.insertNewObject(in: uiMOC) client.remoteIdentifier = "102030405060708090" client.user = ZMUser.insertNewObject(in: uiMOC) client.deviceClass = .tablet client.model = "Simulator" client.label = "Bill's MacBook Pro" let fingerprint: Data? = fingerprintString.data(using: .utf8) client.fingerprint = fingerprint let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm" let activationDate = formatter.date(from: "2016/05/01 14:31") client.activationDate = activationDate return client } }
gpl-3.0
wireapp/wire-ios
Wire-iOS Tests/ConversationCell/ConversationCellBurstTimestampViewSnapshotTests.swift
1
1759
// // Wire // Copyright (C) 2021 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire final class ConversationCellBurstTimestampViewSnapshotTests: XCTestCase { var sut: ConversationCellBurstTimestampView! override func setUp() { super.setUp() sut = ConversationCellBurstTimestampView() sut.frame = CGRect(origin: .zero, size: CGSize(width: 320, height: 40)) sut.unreadDot.backgroundColor = .red sut.backgroundColor = .lightGray } override func tearDown() { sut = nil super.tearDown() } func testForInitState() { verify(matching: sut) } func testForIncludeDayOfWeekAndDot() { // GIVEN & WHEN sut.configure(with: Date(timeIntervalSinceReferenceDate: 0), includeDayOfWeek: true, showUnreadDot: true) // THEN verify(matching: sut) } func testForNotIncludeDayOfWeekAndDot() { // GIVEN & WHEN sut.configure(with: Date(timeIntervalSinceReferenceDate: 0), includeDayOfWeek: false, showUnreadDot: false) // THEN verify(matching: sut) } }
gpl-3.0
derrh/CanvasKit
CanvasKitTests/Model Tests/CKIActivityStreamCollaborationItemTests.swift
3
1036
// // CKIActivityStreamCollaborationItemTests.swift // CanvasKit // // Created by Nathan Lambson on 7/17/14. // Copyright (c) 2014 Instructure. All rights reserved. // import UIKit import XCTest class CKIActivityStreamCollaborationItemTests: 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 testJSONModelConversion() { let activityStreamCollaborationItemDictionary = Helpers.loadJSONFixture("activity_stream_collaboration_item") as NSDictionary let streamItem = CKIActivityStreamCollaborationItem(fromJSONDictionary: activityStreamCollaborationItemDictionary) XCTAssertEqual(streamItem.collaborationID!, "1234", "Stream Collaboration Item id was not parsed correctly") } }
mit
terhechte/SourceKittenDaemon
Tests/SourceKittenDaemonTests/Fixtures/Sources/CompleteMethodFromFrameworkFixture.swift
2
70
import Foundation import AVFoundation let devices = AVCaptureDevice.
mit
novi/i2c-swift-example
Sources/I2CDeviceModule/SHT21.swift
1
1397
// // SHT21.swift // I2CDeviceModule // // Created by Yusuke Ito on 3/1/17. // Copyright © 2017 Yusuke Ito. All rights reserved. // import Foundation import I2C public final class SHT21 { public let address: UInt8 public let device: I2CDevice public init(device: I2CDevice, address: UInt8 = 0x40) { self.device = device self.address = address } } fileprivate extension SHT21 { enum Command: UInt8 { case mesureHoldT = 0xe3 case mesureHoldRH = 0xe5 case reset = 0xfe } func sendAndRead(command: Command, readByte: UInt32) throws -> [UInt8] { return try device.write(toAddress: address, data: [command.rawValue], readBytes: readByte) } func send(command: Command) throws -> UInt16 { let data = try sendAndRead(command: command, readByte: 3) let value: UInt16 = (UInt16(data[0]) << 8) | UInt16(data[1] & 0xfc) return value } } public extension SHT21 { func reset() throws { _ = try sendAndRead(command: .reset, readByte: 0) } func mesureTemperature() throws -> Double { let val = Double(try send(command: .mesureHoldT)) return -46.85 + (175.72 * val / 65536) } func mesureRH() throws -> Double { let val = Double(try send(command: .mesureHoldRH)) return -6 + (125 * val / 65536) } }
mit
HasanEdain/NPCColorPicker
NPCColorPicker/NPCPaleteUtility.swift
1
4578
// // NPCPaleteUtility.swift // NPCColorPicker // // Created by Hasan D Edain and Andrew Bush on 12/6/15. // Copyright © 2015-2017 NPC Unlimited. All rights reserved. // import UIKit open class NPCPaleteUtility { open static func twelveColorWheel()->[UIColor] { let colorArray = [NPCColorUtility.colorWithHex("fe7923"), NPCColorUtility.colorWithHex("fd0d1b"), NPCColorUtility.colorWithHex("bf1698"), NPCColorUtility.colorWithHex("941abe"), NPCColorUtility.colorWithHex("6819bd"), NPCColorUtility.colorWithHex("1024fc"), NPCColorUtility.colorWithHex("1ec0a8"), NPCColorUtility.colorWithHex("1dbb20"), NPCColorUtility.colorWithHex("c7f131"), NPCColorUtility.colorWithHex("e8ea34"), NPCColorUtility.colorWithHex("fad931"), NPCColorUtility.colorWithHex("feb92b")] return colorArray } open static func colorArrayWithRGBAStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithRGBA(hexString) colorArray.append(color) } return colorArray } open static func colorArrayWithHexStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithHex(hexString) colorArray.append(color) } return colorArray } // These colors are specified in #ffffffff Hexidecimal form open static func colorArrayWithGradient(_ startColor: String, endColor: String, steps: Int) -> [UIColor] { var colorArray = [UIColor]() let startRed = NPCColorUtility.redPercentForHexString(startColor as NSString) let startGreen = NPCColorUtility.greenPercentForHexString(startColor as NSString) let startBlue = NPCColorUtility.bluePercentForHexString(startColor as NSString) let startAlpha = NPCColorUtility.alphaPercentForHexString(startColor as NSString) let endRed = NPCColorUtility.redPercentForHexString(endColor as NSString) let endGreen = NPCColorUtility.greenPercentForHexString(endColor as NSString) let endBlue = NPCColorUtility.bluePercentForHexString(endColor as NSString) let endAlpha = NPCColorUtility.alphaPercentForHexString(endColor as NSString) let redDelta = -1 * (startRed - endRed) let greenDelta = -1 * (startGreen - endGreen) let blueDelta = -1 * (startBlue - endBlue) let alphaDelta = -1 * (startAlpha - endAlpha) var redIncrement:CGFloat = 0.0 if steps > 0 && redDelta != 0 { redIncrement = redDelta / CGFloat(steps) } var greenIncrement: CGFloat = 0.0 if steps > 0 && greenDelta != 0 { greenIncrement = greenDelta / CGFloat(steps) } var blueIncrement: CGFloat = 0.0 if steps > 0 && blueDelta != 0 { blueIncrement = blueDelta / CGFloat(steps) } var alphaIncrement: CGFloat = 0.0 if steps > 0 && alphaDelta != 0 { alphaIncrement = alphaDelta / CGFloat(steps) } for step in 1...steps { let red = startRed + (redIncrement * CGFloat(step)) let green = startGreen + (greenIncrement * CGFloat(step)) let blue = startBlue + (blueIncrement * CGFloat(step)) let alpha = startAlpha + (alphaIncrement * CGFloat(step)) let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) colorArray.append(color) } return colorArray } open static func colorArrayWithColorStringArray(_ colorStrings: [String], steps: Int)->[UIColor] { if colorStrings.count <= 0 { return [UIColor.white] } else if colorStrings.count == 1 { return NPCPaleteUtility.colorArrayWithGradient(colorStrings[0], endColor: "ffffff", steps: steps) } else { var gradients = [UIColor]() for index in 1...(colorStrings.count - 1){ let start = colorStrings[index - 1] let end = colorStrings[index] var gradient = NPCPaleteUtility.colorArrayWithGradient(start, endColor: end, steps: steps) if index > 1 { gradient.removeFirst() } gradients.append(contentsOf: gradient) } return gradients } } }
mit
ByteriX/BxInputController
BxInputController/Sources/Rows/Boolean/View/BxInputCheckRowBinder.swift
1
1126
/** * @file BxInputCheckRowBinder.swift * @namespace BxInputController * * @details Binder for check box row subclasses * @date 17.03.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Binder for check box Row subclasses open class BxInputCheckRowBinder<Row : BxInputCheckRow, Cell>: BxInputStandartTextRowBinder<Row, Cell> where Cell : UITableViewCell, Cell : BxInputFieldCell { /// call when user selected this cell override open func didSelected() { super.didSelected() owner?.dissmissAllRows() row.value = !row.value didChangeValue() update() } /// call after common update for text attributes updating override open func updateCell() { cell?.valueTextField.isEnabled = false cell?.valueTextField.text = "" cell?.accessoryType = row.value ? .checkmark : .none cell?.selectionStyle = .default } }
mit
LunaGao/cnblogs-Mac-Swift
CNBlogsForMac/WebApi/BaseWebApi.swift
1
1904
// // BaseWebApi.swift // CNBlogsForMac // // Created by Luna Gao on 15/11/16. // Copyright © 2015年 gao.luna.com. All rights reserved. // import Foundation class BaseWebApi : NSObject { func basicRequest(callback:(String?)->Void){ let basicAuth = "Basic 这个值是根据ClientId和ClientSercret计算得来,这里隐藏" let urlstr = "https://api.cnblogs.com/token" let url = NSURL(string: urlstr) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.addValue(basicAuth, forHTTPHeaderField: "Authorization") let op:NSOperationQueue = NSOperationQueue.mainQueue() request.HTTPBody = "grant_type=client_credentials".dataUsingEncoding(NSUTF8StringEncoding) //通过NSURLConnection发送请求 NSURLConnection.sendAsynchronousRequest(request, queue: op) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in //异步处理 dispatch_async(dispatch_get_main_queue(), { () -> Void in do { let jsonValue: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) if let statusesArray = jsonValue as? NSDictionary{ // NSLog("%@",statusesArray) if let aStatus = statusesArray["access_token"] as? String{ callback(aStatus) } else { callback(nil) } } } catch { callback(nil) } // NSLog("%@", String.init(data: data!, encoding: NSUTF8StringEncoding)!) }) } } } //同步处理 // dispatch_sync(dispatch_get_main_queue(), { () -> Void in // // })
mit
therealglazou/quaxe-for-swift
quaxe/protocols/core/DOMString.swift
1
226
/** * Quaxe for Swift * * Copyright 2016-2017 Disruptive Innovations * * Original author: * Daniel Glazman <[email protected]> * * Contributors: * */ public typealias DOMString = String
mpl-2.0
noppoMan/SwiftJNChatApp
Package.swift
1
655
import PackageDescription let package = Package( name: "SwiftJNChatApp", targets: [ Target(name: "Config"), Target(name: "Migration", dependencies: ["Config"]), Target(name: "SwiftJNChatApp", dependencies: ["Config"]) ], dependencies: [ .Package(url: "https://github.com/noppoMan/WebAppKit.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/noppoMan/SwiftKnex.git", majorVersion: 0, minor: 2), .Package(url: "https://github.com/apple/swift-protobuf.git", Version(0,9,27)), .Package(url: "https://github.com/noppoMan/JSONWebToken.swift.git", Version(2,1,1)) ] )
mit
q231950/appwatch
AppWatch/ViewControllers/TimeTableViewController.swift
1
1268
// // TimeTableViewController.swift // AppWatch // // Created by Martin Kim Dung-Pham on 25.08.15. // Copyright © 2015 Martin Kim Dung-Pham. All rights reserved. // import AppKit class TimeTableViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // collectionView.content = ["hu", "lu"] // collectionView.itemPrototype = storyboard!.instantiateControllerWithIdentifier("collectionViewItem") as? NSCollectionViewItem } // func numberOfSectionsInCollectionView(collectionView: NSCollectionView) -> Int { // return 1 // } // // func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { // return 4 // } // // func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem { // // let item: NSCollectionViewItem // if let i = collectionView.itemAtIndexPath(indexPath) { // item = i // } else { // item = collectionView.newItemForRepresentedObject("hulu") // } // // return item // } // // }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/18378-swift-lexer-leximpl.swift
11
308
// 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 d { deinit { protocol e { let b = { case { func c { if true { class a { class case , let { { { [ { { [ [ { { { { { { { { { { { { c " "
mit
praca-japao/156
PMC156Inteligente/MyProfileTableViewController.swift
1
3269
// // MyProfileTableViewController.swift // PMC156Inteligente // // Created by Giovanni Pietrangelo on 11/29/15. // Copyright © 2015 Sigma Apps. All rights reserved. // import UIKit class MyProfileTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
albertinopadin/SwiftBreakout
Breakout/AppDelegate.swift
1
2153
// // AppDelegate.swift // Breakout // // Created by Albertino Padin on 10/26/14. // Copyright (c) 2014 Albertino Padin. 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:. } }
gpl-2.0
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
1
5571
// // ImageDataProvider.swift // Kingfisher // // Created by onevcat on 2018/11/13. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents a data provider to provide image data to Kingfisher when setting with /// `Source.provider` source. Compared to `Source.network` member, it gives a chance /// to load some image data in your own way, as long as you can provide the data /// representation for the image. public protocol ImageDataProvider { /// The key used in cache. var cacheKey: String { get } /// Provides the data which represents image. Kingfisher uses the data you pass in the /// handler to process images and caches it for later use. /// /// - Parameter handler: The handler you should call when you prepared your data. /// If the data is loaded successfully, call the handler with /// a `.success` with the data associated. Otherwise, call it /// with a `.failure` and pass the error. /// /// - Note: /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError` /// from the framework. func data(handler: @escaping (Result<Data, Error>) -> Void) } /// Represents an image data provider for loading from a local file URL on disk. /// Uses this type for adding a disk image to Kingfisher. Compared to loading it /// directly, you can get benefit of using Kingfisher's extension methods, as well /// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher. public struct LocalFileImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The file URL from which the image be loaded. public let fileURL: URL // MARK: Initializers /// Creates an image data provider by supplying the target local file URL. /// /// - Parameters: /// - fileURL: The file URL from which the image be loaded. /// - cacheKey: The key is used for caching the image data. By default, /// the `absoluteString` of `fileURL` is used. public init(fileURL: URL, cacheKey: String? = nil) { self.fileURL = fileURL self.cacheKey = cacheKey ?? fileURL.absoluteString } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { handler( Result { try Data(contentsOf: fileURL) } ) } } /// Represents an image data provider for loading image from a given Base64 encoded string. public struct Base64ImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The encoded Base64 string for the image. public let base64String: String // MARK: Initializers /// Creates an image data provider by supplying the Base64 encoded string. /// /// - Parameters: /// - base64String: The Base64 encoded string for an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(base64String: String, cacheKey: String) { self.base64String = base64String self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { let data = Data(base64Encoded: base64String)! handler(.success(data)) } } /// Represents an image data provider for a raw data object. public struct RawImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The raw data object to provide to Kingfisher image loader. public let data: Data // MARK: Initializers /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache. /// /// - Parameters: /// - data: The raw data reprensents an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(data: Data, cacheKey: String) { self.data = data self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: @escaping (Result<Data, Error>) -> Void) { handler(.success(data)) } }
mit
therealbnut/swift
stdlib/public/SDK/Foundation/NSString.swift
9
4420
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
apache-2.0
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Dealer Detail/Presenter Tests/WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould.swift
1
1348
@testable import Eurofurence import EurofurenceModel import XCTest class WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould: XCTestCase { func testBindTheArtistDescriptionOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.artistDescription, context.boundAboutTheArtistComponent?.capturedArtistDescription) } func testBindTheTitleOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.title, context.boundAboutTheArtistComponent?.capturedTitle) } }
mit
grandiere/box
box/Metal/Texture/MetalTexture.swift
1
1392
import UIKit import MetalKit class MetalTexture { let totalFrames:Int var currentFrame:Int private var frameTick:Int private let frames:[MTLTexture] private let ticksPerFrame:Int init( ticksPerFrame:Int, images:[UIImage], textureLoader:MTKTextureLoader) { self.ticksPerFrame = ticksPerFrame currentFrame = 0 frameTick = 0 var frames:[MTLTexture] = [] for image:UIImage in images { guard let texture:MTLTexture = textureLoader.loadImage(image:image) else { continue } frames.append(texture) } self.frames = frames totalFrames = frames.count } //MARK: public func changeFrame() { } //MARK final final func current() -> MTLTexture? { if totalFrames < 1 { return nil } frameTick += 1 if frameTick >= ticksPerFrame { frameTick = 0 changeFrame() } let texture:MTLTexture = frames[currentFrame] return texture } final func restart() { currentFrame = 0 frameTick = 0 } }
mit
serieuxchat/SwiftySRP
SwiftySRP/SRPData+BigIntType.swift
1
9367
// // SRPData+BigIntType.swift // SwiftySRP // // Created by Sergey A. Novitsky on 20/03/2017. // Copyright © 2017 Flock of Files. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// Internal extension to short-circuit conversions between Data and BigIntType extension SRPData { // Client specific data /// Password hash 'x' (see SRP spec. in SRPProtocol.swift) func bigInt_x<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._x } return BigIntType(passwordHash) } /// Client private value 'a' (see SRP spec. in SRPProtocol.swift) func bigInt_a<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._a } return BigIntType(clientPrivateValue) } /// Client public value 'A' (see SRP spec. in SRPProtocol.swift) func bigInt_A<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._A } return BigIntType(clientPublicValue) } /// Client evidence message, computed as: M = H( pA | pB | pS), where pA, pB, and pS - padded values of A, B, and S (see SRP spec. in SRPProtocol.swift) func bigInt_clientM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientM } return BigIntType(clientEvidenceMessage) } mutating func setBigInt_clientM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientM = newValue self = impl as! Self } else { clientEvidenceMessage = newValue.serialize() } } /// Server evidence message, computed as: M = H( pA | pMc | pS), where pA is the padded A value; pMc is the padded client evidence message, and pS is the padded shared secret. (see SRP spec. in SRPProtocol.swift) func bigInt_serverM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverM } return BigIntType(serverEvidenceMessage) } mutating func setBigInt_serverM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverM = newValue self = impl as! Self } else { serverEvidenceMessage = newValue.serialize() } } // Common data: /// SRP Verifier 'v' (see SRP spec. in SRPProtocol.swift) func bigInt_v<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._v } return BigIntType(verifier) } mutating func setBigInt_v<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._v = newValue self = impl as! Self } else { self.verifier = newValue.serialize() } } // Scrambler parameter 'u'. u = H(A, B) (see SRP spec. in SRPProtocol.swift) func bigInt_u<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._u } return BigIntType(scrambler) } mutating func setBigInt_u<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._u = newValue self = impl as! Self } else { self.scrambler = newValue.serialize() } } /// Shared secret 'S' . Computed on the client as: S = (B - kg^x) ^ (a + ux) (see SRP spec. in SRPProtocol.swift) func bigInt_clientS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientS } return BigIntType(clientSecret) } mutating func setBigInt_clientS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientS = newValue self = impl as! Self } else { self.clientSecret = newValue.serialize() } } /// Shared secret 'S'. Computed on the server as: S = (Av^u) ^ b (see SRP spec. in SRPProtocol.swift) func bigInt_serverS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverS } return BigIntType(serverSecret) } mutating func setBigInt_serverS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverS = newValue self = impl as! Self } else { self.serverSecret = newValue.serialize() } } // Server specific data /// Multiplier parameter 'k'. Computed as: k = H(N, g) (see SRP spec. in SRPProtocol.swift) func bigInt_k<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._k } return BigIntType(multiplier) } mutating func setBigInt_k<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._k = newValue self = impl as! Self } else { self.multiplier = newValue.serialize() } } /// Server private value 'b' (see SRP spec. in SRPProtocol.swift) func bigInt_b<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._b } return BigIntType(serverPrivateValue) } /// Server public value 'B' (see SRP spec. in SRPProtocol.swift) func bigInt_B<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._B } return BigIntType(serverPublicValue) } }
mit
jatiwn/geocore-tutorial-1
Carthage/Checkouts/PromiseKit/Categories/Foundation/NSNotificationCenter+Promise.swift
1
986
import Foundation.NSNotification import PromiseKit /** To import the `NSNotificationCenter` category: use_frameworks! pod "PromiseKit/Foundation" Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: use_frameworks! pod "PromiseKit" And then in your sources: import PromiseKit */ extension NSNotificationCenter { public class func once(name: String) -> Promise<[NSObject: AnyObject]> { return once(name).then(on: zalgo) { (note: NSNotification) -> [NSObject: AnyObject] in return note.userInfo ?? [:] } } public class func once(name: String) -> Promise<NSNotification> { return Promise { fulfill, _ in var id: AnyObject? id = NSNotificationCenter.defaultCenter().addObserverForName(name, object: nil, queue: nil){ note in fulfill(note) NSNotificationCenter.defaultCenter().removeObserver(id!) } } } }
apache-2.0
tokyovigilante/CesiumKit
CesiumKit/Core/EllipsoidGeodesic.swift
1
14805
// // EllipsoidGeodesic.swift // CesiumKit // // Created by Ryan Walklin on 2/11/2015. // Copyright © 2015 Test Toast. All rights reserved. // import Foundation /** * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points. * * @alias EllipsoidGeodesic * @constructor * * @param {Cartographic} [start] The initial planetodetic point on the path. * @param {Cartographic} [end] The final planetodetic point on the path. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies. */ class EllipsoidGeodesic { /** * Gets the ellipsoid. * @memberof EllipsoidGeodesic.prototype * @type {Ellipsoid} * @readonly */ let ellipsoid: Ellipsoid /** * Gets the initial planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var start: Cartographic? = nil /** * Gets the final planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var end: Cartographic? = nil /** * Gets the heading at the initial point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var startHeading: Double { assert(_distance != nil, "set end positions before getting startHeading") return _startHeading! } fileprivate var _startHeading: Double? = nil /** * Gets the heading at the final point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var endHeading: Double { assert(_distance != nil, "set end positions before getting endHeading") return _endHeading! } fileprivate var _endHeading: Double? = nil /** * Gets the surface distance between the start and end point * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var surfaceDistance: Double { assert(_distance != nil, "set end positions before getting surfaceDistance") return _distance! } fileprivate var _distance: Double? = nil fileprivate var _uSquared: Double? = nil fileprivate var _constants = EllipsoidGeodesicConstants() init (start: Cartographic? = nil, end: Cartographic? = nil, ellipsoid: Ellipsoid = Ellipsoid.wgs84) { self.ellipsoid = ellipsoid if start != nil && end != nil { computeProperties(start: start!, end: end!) } } /** * Sets the start and end points of the geodesic * * @param {Cartographic} start The initial planetodetic point on the path. * @param {Cartographic} end The final planetodetic point on the path. */ func setEndPoints (start: Cartographic, end: Cartographic) { computeProperties(start: start, end: end) } fileprivate func computeProperties(start: Cartographic, end: Cartographic) { let firstCartesian = ellipsoid.cartographicToCartesian(start).normalize() let lastCartesian = ellipsoid.cartographicToCartesian(end).normalize() assert(abs(abs(firstCartesian.angle(between: lastCartesian)) - .pi) >= 0.0125, "geodesic position is not unique") vincentyInverseFormula(major: ellipsoid.maximumRadius, minor: ellipsoid.minimumRadius, firstLongitude: start.longitude, firstLatitude: start.latitude, secondLongitude: end.longitude, secondLatitude: end.latitude) var surfaceStart = start var surfaceEnd = end surfaceStart.height = 0 surfaceEnd.height = 0 self.start = surfaceStart self.end = surfaceEnd setConstants() } fileprivate func vincentyInverseFormula(major: Double, minor: Double, firstLongitude: Double, firstLatitude: Double, secondLongitude: Double, secondLatitude: Double) { let eff = (major - minor) / major let l = secondLongitude - firstLongitude let u1 = atan((1 - eff) * tan(firstLatitude)) let u2 = atan((1 - eff) * tan(secondLatitude)) let cosineU1 = cos(u1) let sineU1 = sin(u1) let cosineU2 = cos(u2) let sineU2 = sin(u2) let cc = cosineU1 * cosineU2 let cs = cosineU1 * sineU2 let ss = sineU1 * sineU2 let sc = sineU1 * cosineU2 var lambda = l var lambdaDot = M_2_PI var cosineLambda = cos(lambda) var sineLambda = sin(lambda) var sigma: Double var cosineSigma: Double var sineSigma: Double var cosineSquaredAlpha: Double var cosineTwiceSigmaMidpoint: Double repeat { cosineLambda = cos(lambda) sineLambda = sin(lambda) let temp = cs - sc * cosineLambda sineSigma = sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp) cosineSigma = ss + cc * cosineLambda sigma = atan2(sineSigma, cosineSigma) let sineAlpha: Double if sineSigma == 0.0 { sineAlpha = 0.0 cosineSquaredAlpha = 1.0 } else { sineAlpha = cc * sineLambda / sineSigma cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha } lambdaDot = lambda cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha; if cosineTwiceSigmaMidpoint.isNaN { cosineTwiceSigmaMidpoint = 0.0 } lambda = l + computeDeltaLambda(eff, sineAlpha: sineAlpha, cosineSquaredAlpha: cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) } while (abs(lambda - lambdaDot) > Math.Epsilon12) let uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor) let A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0 let B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0 let cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint; let deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint * (4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0); _distance = minor * A * (sigma - deltaSigma) _startHeading = atan2(cosineU2 * sineLambda, cs - sc * cosineLambda) _endHeading = atan2(cosineU1 * sineLambda, cs * cosineLambda - sc) _uSquared = uSquared } fileprivate func setConstants() { let a = ellipsoid.maximumRadius let b = ellipsoid.minimumRadius let f = (a - b) / a let cosineHeading = cos(startHeading) let sineHeading = sin(startHeading) let tanU = (1 - f) * tan(start!.latitude) let cosineU = 1.0 / sqrt(1.0 + tanU * tanU) let sineU = cosineU * tanU let sigma = atan2(tanU, cosineHeading) let sineAlpha = cosineU * sineHeading let sineSquaredAlpha = sineAlpha * sineAlpha let cosineSquaredAlpha = 1.0 - sineSquaredAlpha let cosineAlpha = sqrt(cosineSquaredAlpha) let u2Over4 = _uSquared! / 4.0 let u4Over16 = u2Over4 * u2Over4 let u6Over64 = u4Over16 * u2Over4 let u8Over256 = u4Over16 * u4Over16 let a0: Double = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0) let a1: Double = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0) let a2: Double = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0) let a3: Double = (1.0 - 5.0 * u2Over4) // FIXME: Compiler //let distanceRatio0 = a0 * sigma - a1 * sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * sin(4.0 * sigma) * u4Over16 / 16.0 - a3 * sin(6.0 * sigma) * u6Over64 / 48.0 - sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let dr0 = a0 * sigma let dr1 = a1 * sin(2.0 * sigma) * u2Over4 / 2.0 let dr2 = a2 * sin(4.0 * sigma) * u4Over16 / 16.0 let dr3 = a3 * sin(6.0 * sigma) * u6Over64 / 48.0 let dr4 = sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let distanceRatio = dr0 - dr1 - dr2 - dr3 - dr4 _constants.a = a _constants.b = b _constants.f = f _constants.cosineHeading = cosineHeading _constants.sineHeading = sineHeading _constants.tanU = tanU _constants.cosineU = cosineU _constants.sineU = sineU _constants.sigma = sigma _constants.sineAlpha = sineAlpha _constants.sineSquaredAlpha = sineSquaredAlpha _constants.cosineSquaredAlpha = cosineSquaredAlpha _constants.cosineAlpha = cosineAlpha _constants.u2Over4 = u2Over4 _constants.u4Over16 = u4Over16 _constants.u6Over64 = u6Over64 _constants.u8Over256 = u8Over256 _constants.a0 = a0 _constants.a1 = a1 _constants.a2 = a2 _constants.a3 = a3 _constants.distanceRatio = distanceRatio } fileprivate func computeDeltaLambda(_ f: Double, sineAlpha: Double, cosineSquaredAlpha: Double, sigma: Double, sineSigma: Double, cosineSigma: Double, cosineTwiceSigmaMidpoint: Double) -> Double { let C = computeC(f, cosineSquaredAlpha: cosineSquaredAlpha) return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint + C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0))) } fileprivate func computeC(_ f: Double, cosineSquaredAlpha: Double) -> Double { return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0 } /** * Provides the location of a point at the indicated portion along the geodesic. * * @param {Number} fraction The portion of the distance between the initial and final points. * @returns {Cartographic} The location of the point along the geodesic. */ func interpolate (fraction: Double) -> Cartographic { assert(fraction >= 0.0 && fraction <= 1.0, "fraction out of bounds") assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") return interpolate(surfaceDistance: _distance! * fraction) } /** * Provides the location of a point at the indicated distance along the geodesic. * * @param {Number} distance The distance from the inital point to the point of interest along the geodesic * @returns {Cartographic} The location of the point along the geodesic. * * @exception {DeveloperError} start and end must be set before calling funciton interpolateUsingSurfaceDistance */ func interpolate (surfaceDistance distance: Double) -> Cartographic { assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") let constants = _constants let s = constants.distanceRatio + distance / constants.b let cosine2S = cos(2.0 * s) let cosine4S = cos(4.0 * s) let cosine6S = cos(6.0 * s) let sine2S = sin(2.0 * s) let sine4S = sin(4.0 * s) let sine6S = sin(6.0 * s) let sine8S = sin(8.0 * s) let s2 = s * s; let s3 = s * s2; let u8Over256 = constants.u8Over256 let u2Over4 = constants.u2Over4 let u6Over64 = constants.u6Over64 let u4Over16 = constants.u4Over16 var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 + s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 - (u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S - (5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S - 29.0 * u8Over256 * cosine6S / 16.0) + (u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S + (5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S - s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) + (29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S + 539.0 * u8Over256 * sine8S / 1536.0; let theta = asin(sin(sigma) * constants.cosineAlpha) let latitude = atan(constants.a / constants.b * tan(theta)) // Redefine in terms of relative argument of latitude. sigma = sigma - constants.sigma let cosineTwiceSigmaMidpoint = cos(2.0 * constants.sigma + sigma) let sineSigma = sin(sigma) let cosineSigma = cos(sigma) let cc = constants.cosineU * cosineSigma; let ss = constants.sineU * sineSigma; let lambda = atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading) let l = lambda - computeDeltaLambda(constants.f, sineAlpha: constants.sineAlpha, cosineSquaredAlpha: constants.cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) return Cartographic(longitude: start!.longitude + l, latitude: latitude, height: 0.0) } fileprivate struct EllipsoidGeodesicConstants { var a = Double.nan var b = Double.nan var f = Double.nan var cosineHeading = Double.nan var sineHeading = Double.nan var tanU = Double.nan var cosineU = Double.nan var sineU = Double.nan var sigma = Double.nan var sineAlpha = Double.nan var sineSquaredAlpha = Double.nan var cosineSquaredAlpha = Double.nan var cosineAlpha = Double.nan var u2Over4 = Double.nan var u4Over16 = Double.nan var u6Over64 = Double.nan var u8Over256 = Double.nan var a0 = Double.nan var a1 = Double.nan var a2 = Double.nan var a3 = Double.nan var distanceRatio = Double.nan } }
apache-2.0
sarahspins/Loop
Loop/Extensions/NSBundle.swift
1
683
// // NSBundle.swift // Loop // // Created by Nate Racklyeft on 7/28/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation extension NSBundle { var shortVersionString: String { return objectForInfoDictionaryKey("CFBundleShortVersionString") as! String } var bundleDisplayName: String { return objectForInfoDictionaryKey("CFBundleDisplayName") as! String } var localizedNameAndVersion: String { return String(format: NSLocalizedString("%1$@ v%2$@", comment: "The format string for the app name and version number. (1: bundle name)(2: bundle version)"), bundleDisplayName, shortVersionString) } }
apache-2.0
3drobotics/SwiftIO
Sources/UDPChannel.swift
1
9242
// // UDPMavlinkReceiver.swift // SwiftIO // // Created by Jonathan Wight on 4/22/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Darwin import Dispatch import SwiftUtilities /** * A GCD based UDP listener. */ public class UDPChannel { public enum PreconditionError: ErrorType { case QueueSuspended case QueueNotExist } public let label: String? public let address: Address public var readHandler: (Datagram -> Void)? = loggingReadHandler public var errorHandler: (ErrorType -> Void)? = loggingErrorHandler private var resumed: Bool = false private let receiveQueue: dispatch_queue_t! private let sendQueue: dispatch_queue_t! private var source: dispatch_source_t! public private(set) var socket: Socket! public var configureSocket: (Socket -> Void)? // MARK: - Initialization public init(label: String? = nil, address: Address, qos: dispatch_qos_class_t = QOS_CLASS_DEFAULT, readHandler: (Datagram -> Void)? = nil) { self.label = label self.address = address assert(address.port != nil) if let readHandler = readHandler { self.readHandler = readHandler } let queueAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos, 0) receiveQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.receiveQueue", queueAttribute) guard receiveQueue != nil else { fatalError("dispatch_queue_create() failed") } sendQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.sendQueue", queueAttribute) guard sendQueue != nil else { fatalError("dispatch_queue_create() failed") } } // MARK: - Actions public func resume() throws { do { socket = try Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) } catch let error { cleanup() errorHandler?(error) } configureSocket?(socket) source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, UInt(socket.descriptor), 0, receiveQueue) guard source != nil else { cleanup() throw Error.Generic("dispatch_source_create() failed") } dispatch_source_set_cancel_handler(source) { [weak self] in guard let strong_self = self else { return } strong_self.cleanup() strong_self.resumed = false } dispatch_source_set_event_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.read() } catch let error { strong_self.errorHandler?(error) } } dispatch_source_set_registration_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.socket.bind(strong_self.address) strong_self.resumed = true } catch let error { strong_self.errorHandler?(error) tryElseFatalError() { try strong_self.cancel() } return } } dispatch_resume(source) } public func cancel() throws { if resumed == true { assert(source != nil, "Cancel called with source = nil.") dispatch_source_cancel(source) } } public func send(data: DispatchData <Void>, address: Address? = nil, callback: Result <Void> -> Void) { guard sendQueue != nil else { callback(.Failure(PreconditionError.QueueNotExist)) return } guard resumed else { callback(.Failure(PreconditionError.QueueSuspended)) return } dispatch_async(sendQueue) { [weak self] in guard let strong_self = self else { return } do { // use default address if address parameter is not set let address = address ?? strong_self.address if address.family != strong_self.address.family { throw Error.Generic("Cannot send UDP data down a IPV6 socket with a IPV4 address or vice versa.") } try strong_self.socket.sendto(data, address: address) } catch let error { strong_self.errorHandler?(error) callback(.Failure(error)) return } callback(.Success()) } } public static func send(data: DispatchData <Void>, address: Address, queue: dispatch_queue_t, writeHandler: Result <Void> -> Void) { let socket = try! Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) dispatch_async(queue) { do { try socket.sendto(data, address: address) } catch let error { writeHandler(.Failure(error)) return } writeHandler(.Success()) } } } // MARK: - extension UDPChannel: CustomStringConvertible { public var description: String { return "\(self.dynamicType)(\"\(label ?? "")\")" } } // MARK: - private extension UDPChannel { func read() throws { let data: NSMutableData! = NSMutableData(length: 4096) var addressData = Array <Int8> (count: Int(SOCK_MAXADDRLEN), repeatedValue: 0) let (result, address) = addressData.withUnsafeMutableBufferPointer() { (inout ptr: UnsafeMutableBufferPointer <Int8>) -> (Int, Address?) in var addrlen: socklen_t = socklen_t(SOCK_MAXADDRLEN) let result = Darwin.recvfrom(socket.descriptor, data.mutableBytes, data.length, 0, UnsafeMutablePointer<sockaddr> (ptr.baseAddress), &addrlen) guard result >= 0 else { return (result, nil) } let addr = UnsafeMutablePointer <sockaddr_storage> (ptr.baseAddress) let address = Address(sockaddr: addr.memory) return (result, address) } guard result >= 0 else { let error = Error.Generic("recvfrom() failed") errorHandler?(error) throw error } data.length = result let datagram = Datagram(from: address!, timestamp: Timestamp(), data: DispatchData <Void> (buffer: data.toUnsafeBufferPointer())) readHandler?(datagram) } func cleanup() { defer { socket = nil source = nil } do { try socket.close() } catch let error { errorHandler?(error) } } } // MARK: - public extension UDPChannel { public func send(data: NSData, address: Address? = nil, callback: Result <Void> -> Void) { let data = DispatchData <Void> (start: data.bytes, count: data.length) send(data, address: address ?? self.address, callback: callback) } } // Private for now - make public soon? private extension Socket { func sendto(data: DispatchData <Void>, address: Address) throws { var addr = sockaddr_storage(address: address) let result = withUnsafePointer(&addr) { ptr in return data.createMap() { (_, buffer) in return Darwin.sendto(descriptor, buffer.baseAddress, buffer.count, 0, UnsafePointer <sockaddr> (ptr), socklen_t(addr.ss_len)) } } // TODO: what about "partial" sends. if result < data.length { throw Errno(rawValue: errno) ?? Error.Unknown } } }
mit
jisudong/study
MyPlayground.playground/Pages/可选链式调用.xcplaygroundpage/Contents.swift
1
1812
//: [Previous](@previous) import Foundation class Person { var residence: Residence? } class Residence { var rooms = [Room]() var address: Address? var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room{ get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } } class Room { var name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName != nil { return buildingName } else if buildingNumber != nil && street != nil { return "\(String(describing: buildingNumber))\(String(describing: street))" } else { return nil } } } let john = Person() if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" john.residence?.address = someAddress // residence 为nil if john.residence?.printNumberOfRooms() != nil { print("It was possible to print the number of rooms.") } else { print("It was not possible to print the number of rooms.") } if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } var dict = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]] dict["Dave"]?[0] = 91 dict["Bev"]?[0] += 1 dict["Brian"]?[0] = 72
mit
STShenZhaoliang/Swift2Guide
Swift2Guide/Swift100Tips/Swift100Tips/ErrorController.swift
1
3869
// // ErrorController.swift // Swift100Tips // // Created by 沈兆良 on 16/5/30. // Copyright © 2016年 ST. All rights reserved. // import UIKit class ErrorController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("", ofType: "")! let file = NSFileManager.defaultManager().contentsAtPath(path)! do { try file.writeToFile("Hello", options: []) } catch let error as NSError { print ("Error: \(error.domain)") } do { try login("onevcat", password: "123") } catch LoginError.UserNotFound { print("UserNotFound") } catch LoginError.UserPasswordNotMatch { print("UserPasswordNotMatch") } catch { } let result = doSomethingParam(path) switch result { case let .Success(ok): let serverResponse = ok case let .Error(error): let serverResponse = error.description } do { try methodRethrows(1, f: methodThrows) } catch _ { } // 输出: // Int } enum LoginError: ErrorType { case UserNotFound, UserPasswordNotMatch } var users:[String: String]! func login(user: String, password: String) throws { //users 是 [String: String],存储[用户名:密码] if !users.keys.contains(user) { throw LoginError.UserNotFound } if users[user] != password { throw LoginError.UserPasswordNotMatch } print("Login successfully.") } enum Result { case Success(String) case Error(NSError) } func doSomethingParam(param:AnyObject) -> Result { //...做某些操作,成功结果放在 success 中 let success = true if success { return Result.Success("成功完成") } else { let error = NSError(domain: "errorDomain", code: 1, userInfo: nil) return Result.Error(error) } } func methodThrows(num: Int) throws { if num < 0 { print("Throwing!") // throw Error.Negative } print("Executed!") } func methodRethrows(num: Int, f: Int throws -> ()) rethrows { try f(num) } } //在 Swift 2.0 中,我们甚至可以在 enum 中指定泛型,这样就使结果统一化了。 enum Result<T> { case Success(T) case Failure(NSError) } //在 Swift 2 时代中的错误处理,现在一般的最佳实践是对于同步 API 使用异常机制,对于异步 API 使用泛型枚举。 //首先,try 可以接 ! 表示强制执行,这代表你确定知道这次调用不会抛出异常。如果在调用中出现了异常的话,你的程序将会崩溃,这和我们在对 Optional 值用 ! 进行强制解包时的行为是一致的。另外,我们也可以在 try 后面加上 ? 来进行尝试性的运行。try? 会返回一个 Optional 值:如果运行成功,没有抛出错误的话,它会包含这条语句的返回值,否则将为 nil。和其他返回 Optional 的方法类似,一个典型的 try? 的应用场景是和 if let 这样的语句搭配使用,不过如果你用了 try? 的话,就意味着你无视了错误的具体类型 /* 简单理解的话你可以将 rethrows 看做是 throws 的“子类”,rethrows 的方法可以用来重载那些被标为 throws 的方法或者参数,或者用来满足被标为 throws 的接口,但是反过来不行。如果你拿不准要怎么使用的话,就先记住你在要 throws 另一个 throws 时,应该将前者改为 rethrows。这样在不失灵活性的同时保证了代码的可读性和准确性。 */
mit
AaronMT/firefox-ios
Client/Frontend/AuthenticationManager/PagingPasscodeViewController.swift
9
3110
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation private let PaneSwipeDuration: TimeInterval = 0.3 /// Base class for implementing a Passcode configuration screen with multiple 'panes'. class PagingPasscodeViewController: BasePasscodeViewController { fileprivate lazy var pager: UIScrollView = { let scrollView = UIScrollView() scrollView.isPagingEnabled = true scrollView.isUserInteractionEnabled = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() var panes = [PasscodePane]() var currentPaneIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() view.addSubview(pager) panes.forEach { pager.addSubview($0) } pager.snp.makeConstraints { make in make.bottom.left.right.equalTo(self.view) make.top.equalTo(self.view.safeArea.top) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() panes.enumerated().forEach { index, pane in pane.frame = CGRect(origin: CGPoint(x: CGFloat(index) * pager.frame.width, y: 0), size: pager.frame.size) } pager.contentSize = CGSize(width: CGFloat(panes.count) * pager.frame.width, height: pager.frame.height) scrollToPaneAtIndex(currentPaneIndex) if self.authenticationInfo?.isLocked() ?? false { return } panes[currentPaneIndex].codeInputView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } } extension PagingPasscodeViewController { @discardableResult func scrollToNextAndSelect() -> PasscodePane { scrollToNextPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } @discardableResult func scrollToPreviousAndSelect() -> PasscodePane { scrollToPreviousPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } func resetAllInputFields() { panes.forEach { $0.codeInputView.resetCode() } } func scrollToNextPane() { guard (currentPaneIndex + 1) < panes.count else { return } currentPaneIndex += 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPreviousPane() { guard (currentPaneIndex - 1) >= 0 else { return } currentPaneIndex -= 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPaneAtIndex(_ index: Int) { UIView.animate(withDuration: PaneSwipeDuration, delay: 0, options: [], animations: { self.pager.contentOffset = CGPoint(x: CGFloat(self.currentPaneIndex) * self.pager.frame.width, y: 0) }, completion: nil) } }
mpl-2.0
heitorgcosta/Quiver
Quiver/Validating/Extensions/Validator+Misc.swift
1
696
// // Validator+Misc.swift // Quiver // // Created by Heitor Costa on 20/10/17. // Copyright © 2017 Heitor Costa. All rights reserved. // import Foundation // Misc Validators public extension Validator { static func required(message: String? = nil) -> Validator { return RequiredValidator().with(message: message) } static func not(_ validator: Validator, message: String? = nil) -> Validator { return NegateValidator(validator: validator).with(message: message) } static func when(_ condition: @escaping () -> Bool, use validator: Validator) -> Validator { return ConditionalValidator(conditionClosure: condition, validator: validator) } }
mit
rnystrom/GitHawk
Classes/Repository/RepositoryIssueSummaryModel+Filterable.swift
1
699
// // RepositoryIssueSummaryModel+Filterable.swift // Freetime // // Created by Ryan Nystrom on 10/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation extension RepositoryIssueSummaryModel: Filterable { func match(query: String) -> Bool { if query.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil { let ticketNumber = String(number) return ticketNumber.contains(query) } let lowerQuery = query.lowercased() if title.string.allText.lowercased().contains(lowerQuery) { return true } if author.lowercased().contains(lowerQuery) { return true } return false } }
mit
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Main/Controller/BaseViewController.swift
1
2249
// // BaseViewController.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/25. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK: 定义属性 var contentView : UIView? var baseVM : BaseViewModel! // MARK: 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: #imageLiteral(resourceName: "daipingjia")) imageView.center = self.view.center imageView.animationImages = [#imageLiteral(resourceName: "daipingjia"),#imageLiteral(resourceName: "daishouhuo")] imageView.animationDuration = 2 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // extension BaseViewController { func setupUI() { // 1.隐藏内容的View contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(animImageView) // 3.给animImageView执行动画 animImageView.startAnimating() // 4.设置view的背景颜色 view.backgroundColor = UIColor.ColorHexString(hexStr: "#f0f0f0") //5.设置返回按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(backImage: #imageLiteral(resourceName: "back"), title: nil, parentVc: self, action: #selector(self.popAction)) navigationController?.navigationBar.tintColor = UIColor.gray } func loadDataFinished() { // 1.停止动画 animImageView.stopAnimating() // 2.隐藏animImageView animImageView.isHidden = true // 3.显示内容的View contentView?.isHidden = false } func popAction(){ navigationController?.popViewController(animated: true) } } // MARK:- 请求数据 extension BaseViewController { func loadData() { } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/25512-swift-genericsignature-get.swift
13
240
// RUN: not %target-swift-frontend %s -parse // 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 c{{let c{class case,
apache-2.0
frootloops/swift
validation-test/Sema/type_checker_perf/slow/rdar35213699.swift
1
359
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts func test() { let x: UInt = 1 * 2 + 3 * 4 + 5 * 6 + 7 * 8 + 9 * 10 + 11 * 12 + 13 * 14 // expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}} }
apache-2.0

IVA Swift GitHub Code Dataset

Dataset Description

This is the raw IVA Swift dataset extracted from GitHub. It contains uncurated Swift files gathered with the purpose to train a code generation model.

The dataset consists of 753693 swift code files from GitHub totaling ~700MB of data. The dataset was created from the public GitHub dataset on Google BiqQuery.

How to use it

To download the full dataset:

from datasets import load_dataset
dataset = load_dataset('mvasiliniuc/iva-swift-codeint', split='train')

from datasets import load_dataset
dataset = load_dataset('mvasiliniuc/iva-swift-codeint', split='train')
print(dataset[77723])

#OUTPUT:
{
   "repo_name":"simpleandpretty/decider-ios",
   "path":"MessagesExtension/MediaResources.swift",
   "copies":"1",
   "size":"1232",
   "content":"import Foundation\nimport UIKit\n\nclass MediaResources {\n\n    static func mediaURL(forGameOption option:FightMove) -> URL {\n        let bundle = Bundle.main\n        guard\n            let mediaURL = bundle.url(forResource: option.rawValue, withExtension: \"mp4\")\n ...",
   "license":"gpl-3.0"
}

Data Structure

Data Fields

Field Type Description
repo_name string name of the GitHub repository
path string path of the file in GitHub repository
copies string number of occurrences in dataset
code string content of source file
size string size of the source file in bytes
license string license of GitHub repository

Instance

{
   "repo_name":"simpleandpretty/decider-ios",
   "path":"MessagesExtension/MediaResources.swift",
   "copies":"1",
   "size":"1232",
   "content":"import Foundation\nimport UIKit\n\nclass MediaResources {\n\n    static func mediaURL(forGameOption option:FightMove) -> URL {\n        let bundle = Bundle.main\n        guard\n            let mediaURL = bundle.url(forResource: option.rawValue, withExtension: \"mp4\")\n ...",
   "license":"gpl-3.0"
}

Languages

The dataset contains only Swift files.

{
    "Swift": [".swift"]
}

Licenses

Each entry in the dataset contains the associated license. The following is a list of licenses involved and their occurrences.

{
    "agpl-3.0": 2775,
    "apache-2.0": 180178,
    "artistic-2.0": 314,
    "bsd-2-clause": 5342,
    "bsd-3-clause": 11429,
    "cc0-1.0": 2718,
    "epl-1.0": 980,
    "gpl-2.0": 15751,
    "gpl-3.0": 33074,
    "isc": 1647,
    "lgpl-2.1": 1741,
    "lgpl-3.0": 6150,
    "mit": 476518,
    "mpl-2.0": 11799,
    "unlicense": 3277
}

Dataset Statistics

{
    "Total size": "~712 MB",
    "Number of files": 753693,
    "Number of files under 500 bytes": 129827,
    "Average file size in bytes": 4245,
}

Dataset Creation

The dataset was created using Google Query for Github: https://cloud.google.com/blog/topics/public-datasets/github-on-bigquery-analyze-all-the-open-source-code

The following steps were pursued for data gathering:

  1. Creation of a dataset and a table in Google Big Query Project.
  2. Creation of a bucket in Google Cloud Storage.
  3. Creation of a query in Google Big Query Project.
  4. Running the query with the setting to output the results in the dataset and table created at step one.
  5. Exporting the resulting dataset into the bucket created in step 2. Export format of JSON with gzip compression.

The result of these steps leads to the following results:

  • 2.7 TB Processed,
  • number of extracted rows/Swift files was 464,215
  • total logical bytes 1.46 GB.
  • The result amounts to 7 json.gz files in a total of 700 MB

The SQL Query used is:

SELECT
  f.repo_name, f.path, c.copies, c.size, c.content, l.license
FROM
 (select f.*, row_number() over (partition by id order by path desc) as seqnum from `bigquery-public-data.github_repos.files` AS f) f
JOIN
  `bigquery-public-data.github_repos.contents` AS c
ON
  f.id = c.id AND seqnum=1
JOIN
  `bigquery-public-data.github_repos.licenses` AS l
ON
  f.repo_name = l.repo_name
WHERE
  NOT c.binary AND ((f.path LIKE '%.swift') AND (c.size BETWEEN 0 AND 1048575))

Data Splits

The dataset only contains a train split.

Using the curated version of this dataset, a split was made into multiple repositories:

Considerations for Using the Data

The dataset comprises source code from various repositories, potentially containing harmful or biased code, along with sensitive information such as passwords or usernames.

Additional Information

Dataset Curators

[email protected]

Licensing Information

  • The license of this open-source dataset is: other.
  • The dataset is gathered from open-source repositories on GitHub using BigQuery.
  • Find the license of each entry in the dataset in the corresponding license column.

Citation Information

@misc {mircea_vasiliniuc_2023,
    author       = { {Mircea Vasiliniuc} },
    title        = { iva-swift-codeint (Revision c09ebf8) },
    year         = 2023,
    url          = { https://huggingface.co/datasets/mvasiliniuc/iva-swift-codeint },
    doi          = { 10.57967/hf/0778 },
    publisher    = { Hugging Face }
}
Downloads last month
53
Edit dataset card