repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Vienta/kuafu
refs/heads/master
CVCalendarKit/CVCalendarKitOperators.swift
mit
2
// // CVCalendarKitOperators.swift // CVCalendarKit // // Created by Eugene Mozharovsky on 05/05/15. // Copyright (c) 2015 Dwive. All rights reserved. // import Foundation /** An operating entity containing content information regarding its owner. It's used in the date management for date construction and comparison. Each enum case is associated with a date and a value. */ public enum DateUnit { case Year(NSDate, Int) case Month(NSDate, Int) case Day(NSDate, Int) /** :returns: An associated value with a particular case. */ func value() -> Int { switch self { case .Year(_, let x): return x case .Month(_, let x): return x case .Day(_, let x): return x } } } /** A structure for marking an offset for a date. Used for date contruction. */ public struct Offset { var year: Int var month: Int var day: Int } // MARK: - Helper functions private typealias DateOffset = (Offset, DateOperation) -> NSDate /** Constructs a date with the offset from the source date. :param: date The given date for applying the offset. :returns: A function for getting the date from the offset and the assignment operation. */ private func dateWithOffset(date: NSDate) -> DateOffset { let comps = NSCalendar.currentCalendar().allComponentsFromDate(date) return { offset, operation in comps.year = offset.year == 0 ? comps.year : operation(comps.year, offset.year) comps.month = offset.month == 0 ? comps.month : operation(comps.month, offset.month) comps.day = offset.day == 0 ? comps.day : operation(comps.day, offset.day) return NSCalendar.currentCalendar().dateFromComponents(comps)! } } private typealias DateOperation = (Int, Int) -> (Int) /** A bridge between construction function and the given options. :param: dateUnit A date unit providing the necessary data. :param: offset An offset for */ private func dateUnitOffset(dateUnit: DateUnit, offset: Int, operation: DateOperation) -> NSDate { let result: NSDate switch dateUnit { case .Year(let date, let value): result = dateWithOffset(date)(Offset(year: offset, month: 0, day: 0), operation) case .Month(let date, let value): result = dateWithOffset(date)(Offset(year: 0, month: offset, day: 0), operation) case .Day(let date, let value): result = dateWithOffset(date)(Offset(year: 0, month: 0, day: offset), operation) } return result } private typealias ComparisonOperation = (Int, Int) -> Bool private typealias ResultMerge = (Bool, Bool, Bool) -> Bool private typealias ComparisonResult = (NSDate, NSDate) -> Bool /** Compares dates via return closure. :param: operation Comparison operation. :param: resultMerge The way of merging the results. :returns: A comparison function. */ private func compareWithOperation(operation: ComparisonOperation, resultMerge: ResultMerge) -> ComparisonResult { return { dateA, dateB in let resultA = operation(dateA.year.value(), dateB.year.value()) let resultB = operation(dateA.month.value(), dateB.month.value()) let resultC = operation(dateA.day.value(), dateB.day.value()) return resultMerge(resultA, resultB, resultC) } } // MARK: - DateUnit operators overload public func + (lhs: DateUnit, rhs: Int) -> NSDate { return dateUnitOffset(lhs, rhs, { x, y in x + y }) } public func - (lhs: DateUnit, rhs: Int) -> NSDate { return dateUnitOffset(lhs, rhs, { x, y in x - y }) } public func * (lhs: DateUnit, rhs: Int) -> NSDate { return dateUnitOffset(lhs, rhs, { x, y in x * y }) } public func / (lhs: DateUnit, rhs: Int) -> NSDate { return dateUnitOffset(lhs, rhs, { x, y in x / y }) } public func == (lhs: DateUnit, rhs: Int) -> NSDate { return dateUnitOffset(lhs, rhs, { _, y in y }) } // MARK: - NSDate operators overload public func == (lhs: NSDate, rhs: NSDate) -> Bool { return compareWithOperation({ $0 == $1 }, { $0 && $1 && $2 })(lhs, rhs) } public func > (lhs: NSDate, rhs: NSDate) -> Bool { return compareWithOperation({ $0 > $1 }, { $0 || $1 || $2 })(lhs, rhs) } public func >= (lhs: NSDate, rhs: NSDate) -> Bool { return compareWithOperation({ $0 > $1 || lhs == rhs }, { $0 || $1 || $2 })(lhs, rhs) } public func < (lhs: NSDate, rhs: NSDate) -> Bool { return compareWithOperation({ $0 < $1 }, { $0 || $1 || $2 })(lhs, rhs) } public func <= (lhs: NSDate, rhs: NSDate) -> Bool { return compareWithOperation({ $0 < $1 || lhs == rhs }, { $0 || $1 || $2 })(lhs, rhs) } public func != (lhs: NSDate, rhs: NSDate) -> Bool { return !(lhs == rhs) }
7c2ba11e349db38d7257d2f3eadcfd04
28.878205
113
0.649356
false
false
false
false
nathan-hekman/Chill
refs/heads/master
Chill/Chill/Utilities/ColorUtil.swift
mit
1
// // Utils.swift // Chill // // Created by Nathan Hekman on 12/20/15. // Copyright © 2015 NTH. All rights reserved. // import UIKit import ChameleonFramework class ColorUtil: NSObject { static let sharedInstance: ColorUtil = { var instance = ColorUtil() return instance }() private override init() { super.init() } var colorArray: NSArray! var color1: UIColor! var color2: UIColor! var color3: UIColor! //base color of palette var color4: UIColor! var color5: UIColor! func setupFlatColorPaletteWithFlatBaseColor(color: UIColor!, colorscheme: ColorScheme!) { //get color scheme colorArray = NSArray(ofColorsWithColorScheme: colorscheme, usingColor: color, withFlatScheme: true) color1 = colorArray[0] as? UIColor color2 = colorArray[1] as? UIColor color3 = colorArray[2] as? UIColor color4 = colorArray[3] as? UIColor color5 = colorArray[4] as? UIColor } }
cb141f4b1162676eb2711a54cab566bb
21.020833
107
0.614948
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
refs/heads/master
ResearchUXFactory/SBAProfileInfoForm.swift
bsd-3-clause
1
// // SBARegistrationForm.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit /** Protocol for extending all the profile info steps (used by the factory to create the appropriate default form items). */ public protocol SBAProfileInfoForm: SBAFormStepProtocol { /** Use the `ORKFormItem` model object when getting/setting */ var formItems:[ORKFormItem]? { get set } /** Used in common initialization to get the default options if the included options are nil. */ func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] } /** Shared factory methods for creating profile form steps. */ extension SBAProfileInfoForm { public var options: [SBAProfileInfoOption]? { return self.formItems?.mapAndFilter({ SBAProfileInfoOption(rawValue: $0.identifier) }) } public func formItemForProfileInfoOption(_ profileInfoOption: SBAProfileInfoOption) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == profileInfoOption.rawValue }) } public func commonInit(inputItem: SBASurveyItem?, factory: SBABaseSurveyFactory?) { self.title = inputItem?.stepTitle self.text = inputItem?.stepText if let formStep = self as? ORKFormStep { formStep.footnote = inputItem?.stepFootnote } let options = SBAProfileInfoOptions(inputItem: inputItem, defaultIncludes: defaultOptions(inputItem)) self.formItems = options.makeFormItems(factory: factory) } }
4633c1c4a66c7e71bdbc40f224aa56f4
40.597403
109
0.739931
false
false
false
false
HongliYu/DPColorfulTags-Swift
refs/heads/master
DPColorfulTagsDemo/DPAppLanguage.swift
mit
1
// // DPAppLanguage.swift // DPColorfulTagsDemo // // Created by Hongli Yu on 12/11/2017. // Copyright © 2017 Hongli Yu. All rights reserved. // import Foundation class DPAppLanguage: Equatable { let code: String let englishName: String let localizedName: String init(code: String) { self.code = code let localeEnglish = Locale(identifier: "en") self.englishName = localeEnglish.localizedString(forIdentifier: code) ?? "" let locale = Locale(identifier: code) self.localizedName = locale.localizedString(forIdentifier: code) ?? "" } } extension DPAppLanguage: CustomStringConvertible { var description: String { return "\(code), \(englishName), \(localizedName)" } } func == (lhs: DPAppLanguage, rhs: DPAppLanguage) -> Bool { return lhs.code == rhs.code }
58014e54d9e3866e5e507908a461e446
21.135135
79
0.686203
false
false
false
false
nessBautista/iOSBackup
refs/heads/master
SwiftSlang/plotTest1/plotTest1/PlotView.swift
cc0-1.0
1
// // PlotView.swift // plotTest1 // // Created by Ness on 1/8/16. // Copyright © 2016 Ness. All rights reserved. // import UIKit class PlotView: UIView { // MARK: Geometric Constants var kGraphHeight = 300 var kDefaultGraphWidth = 600 var kOffsetX = 10 var kStepX = 50 var kGraphBottom = 300 var kGraphTop = 0 // MARK: Init routines required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) CGContextSetLineWidth(context, 10.0) CGContextSetStrokeColorWithColor(context, UIColor.greenColor().CGColor) CGContextMoveToPoint(context, 0.0, 0.0) CGContextAddLineToPoint(context, self.frame.width/2, self.frame.height/2) // let howMany = (kDefaultGraphWidth - kOffsetX) / kStepX // // for i in 0...howMany // { // CGContextMoveToPoint(context, CGFloat(kOffsetX) + CGFloat(i*kStepX), CGFloat(kGraphTop)) // CGContextAddLineToPoint(context, CGFloat(kOffsetX) + CGFloat(i * kStepX), CGFloat(kGraphBottom)) // } CGContextStrokePath(context) CGContextRestoreGState(context) } }
bf77396769cc71375dcf0a2ab1349d3d
23.967213
110
0.625739
false
false
false
false
1er4y/IYSlideView
refs/heads/develop
Carthage/Checkouts/Nimble/Sources/Nimble/Adapters/NMBObjCMatcher.swift
apache-2.0
140
import Foundation #if _runtime(_ObjC) public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool public class NMBObjCMatcher : NSObject, NMBMatcher { let _match: MatcherBlock let _doesNotMatch: MatcherBlock let canMatchNil: Bool public init(canMatchNil: Bool, matcher: @escaping MatcherBlock, notMatcher: @escaping MatcherBlock) { self.canMatchNil = canMatchNil self._match = matcher self._doesNotMatch = notMatcher } public convenience init(matcher: @escaping MatcherBlock) { self.init(canMatchNil: true, matcher: matcher) } public convenience init(canMatchNil: Bool, matcher: @escaping MatcherBlock) { self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in return !matcher(actualExpression, failureMessage) })) } public convenience init(matcher: @escaping FullMatcherBlock) { self.init(canMatchNil: true, matcher: matcher) } public convenience init(canMatchNil: Bool, matcher: @escaping FullMatcherBlock) { self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in return matcher(actualExpression, failureMessage, false) }), notMatcher: ({ actualExpression, failureMessage in return matcher(actualExpression, failureMessage, true) })) } private func canMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { do { if !canMatchNil { if try actualExpression.evaluate() == nil { failureMessage.postfixActual = " (use beNil() to match nils)" return false } } } catch let error { failureMessage.actualValue = "an unexpected error thrown: \(error)" return false } return true } public func matches(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let expr = Expression(expression: actualBlock, location: location) let result = _match( expr, failureMessage) if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { return result } else { return false } } public func doesNotMatch(_ actualBlock: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let expr = Expression(expression: actualBlock, location: location) let result = _doesNotMatch( expr, failureMessage) if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { return result } else { return false } } } #endif
0c601a117d5d85b29494791a6d9e0b60
37.469136
144
0.650513
false
false
false
false
sora0077/iTunesKit
refs/heads/master
iTunesKit/src/Endpoint/Search.swift
mit
1
// // Search.swift // iTunesKit // // Created by 林達也 on 2015/10/04. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation import APIKit public struct Search { /// The URL-encoded text string you want to search for. For example: jack+johnson. /// Any URL-encoded text string. /// /// Note: URL encoding replaces spaces with the plus (+) character and all characters except the following are encoded: letters, numbers, periods (.), dashes (-), underscores (_), and asterisks (*). public var term: String /// The two-letter country code for the store you want to search. The search uses the default store front for the specified country. For example: US. /// /// The default is US. public var country: String /// The media type you want to search for. For example: movie. /// /// The default is all. public var media: String = "all" /// The type of results you want returned, relative to the specified media type. For example: movieArtist for a movie media type search. /// /// The default is the track entity associated with the specified media type. public var entity: String = "allTrack" /// The attribute you want to search for in the stores, relative to the specified media type. For example, if you want to search for an artist by name specify entity=allArtist&attribute=allArtistTerm. /// /// In this example, if you search for term=maroon, iTunes returns "Maroon 5" in the search results, instead of all artists who have ever recorded a song with the word "maroon" in the title. /// /// The default is all attributes associated with the specified media type. public var attribute: String? /// The number of search results you want the iTunes Store to return. For example: 25. /// /// The default is 50. public var limit: Int = 50 /// The language, English or Japanese, you want to use when returning search results. Specify the language using the five-letter codename. For example: en_us. /// /// The default is en_us (English). public var lang: String = "en_us" /// A flag indicating whether or not you want to include explicit content in your search results. /// /// The default is Yes. public var explicit: Bool = true /** <#Description#> - parameter term: Y - parameter country: Y - returns: <#return value description#> */ public init(term: String, country: String = "US") { self.term = term self.country = country } } extension Search: iTunesRequestToken { public typealias Response = [SearchResult] public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .GET } public var path: String { return "https://itunes.apple.com/search" } public var parameters: [String: AnyObject]? { var dict: [String: AnyObject] = [ "term": term, "country": country, "media": media, "entity": entity, "limit": limit, "lang": lang, "explicit": explicit ? "Yes" : "No" ] if let attribute = attribute { dict["attribute"] = attribute } return dict } public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { print(request, object) return (object["results"] as! [[String: AnyObject]]).map { v in guard let wrapperType = SearchResultWrapperType(rawValue: v["wrapperType"] as! String) else { return .Unsupported(v) } switch wrapperType { case .Track: guard let kind = SearchResultKind(rawValue: v["kind"] as! String) else { return .Unsupported(v) } return .Track(SearchResultTrack( kind: kind, artistId: v["artistId"] as! Int, collectionId: v["collectionId"] as! Int, trackId: v["trackId"] as! Int, artistName: v["artistName"] as! String, collectionName: v["collectionName"] as! String, trackName: v["trackName"] as! String, collectionCensoredName: v["collectionCensoredName"] as! String, trackCensoredName: v["trackCensoredName"] as! String, artistViewUrl: v["artistViewUrl"] as! String, collectionViewUrl: v["collectionViewUrl"] as! String, trackViewUrl: v["trackViewUrl"] as! String, previewUrl: v["previewUrl"] as! String, artworkUrl30: v["artworkUrl30"] as! String, artworkUrl60: v["artworkUrl60"] as! String, artworkUrl100: v["artworkUrl100"] as! String, collectionPrice: v["collectionPrice"] as! Float, trackPrice: v["trackPrice"] as! Float, releaseDate: v["releaseDate"] as! String, collectionExplicitness: v["collectionExplicitness"] as! String, trackExplicitness: v["trackExplicitness"] as! String, discCount: v["discCount"] as! Int, discNumber: v["discNumber"] as! Int, trackCount: v["trackCount"] as! Int, trackNumber: v["trackNumber"] as! Int, trackTimeMillis: v["trackTimeMillis"] as! Int, country: v["country"] as! String, currency: v["currency"] as! String, primaryGenreName: v["primaryGenreName"] as! String, radioStationUrl: v["radioStationUrl"] as? String, isStreamable: v["isStreamable"] as! Bool )) case .Artist: return .Artist(SearchResultArtist( artistType: v["artistType"] as! String, artistName: v["artistName"] as! String, artistLinkUrl: v["artistLinkUrl"] as! String, artistId: v["artistId"] as! Int, amgArtistId: v["amgArtistId"] as? Int, primaryGenreName: v["primaryGenreName"] as! String, primaryGenreId: v["primaryGenreId"] as! Int, radioStationUrl: v["radioStationUrl"] as? String )) case .Collection: return .Collection(SearchResultCollection( collectionType: v["collectionType"] as! String, artistId: v["artistId"] as! Int, collectionId: v["collectionId"] as! Int, amgArtistId: v["amgArtistId"] as! Int, artistName: v["artistName"] as! String, collectionName: v["collectionName"] as! String, collectionCensoredName: v["collectionCensoredName"] as! String, artistViewUrl: v["artistViewUrl"] as! String, collectionViewUrl: v["collectionViewUrl"] as! String, artworkUrl30: v["artworkUrl30"] as! String, artworkUrl60: v["artworkUrl60"] as! String, artworkUrl100: v["artworkUrl100"] as! String, collectionPrice: v["collectionPrice"] as! Float, collectionExplicitness: v["collectionExplicitness"] as! String, trackCount: v["trackCount"] as! Int, copyright: v["copyright"] as! String, country: v["country"] as! String, currency: v["currency"] as! String, releaseDate: v["releaseDate"] as! String, primaryGenreName: v["primaryGenreName"] as! String, radioStationUrl: v["radioStationUrl"] as? String )) } } } }
0e980f65015ca173620ae8f4004bba82
40.623188
204
0.528668
false
false
false
false
HongxiangShe/STV
refs/heads/master
STV/STV/Classes/Main/Protocol/Nibloadable.swift
apache-2.0
1
// // Nibloadable.swift // SHXPageView // // Created by 佘红响 on 2017/6/5. // Copyright © 2017年 she. All rights reserved. // import UIKit protocol Nibloadable { } // 表明该协议只能被UIView实现 extension Nibloadable where Self: UIView { // 协议,结构体都用static static func loadFromNib(_ nibname: String? = nil) -> Self { // let nib = nibname == nil ? "\(self)" : nibname! let nib = nibname ?? "\(self)"; return Bundle.main.loadNibNamed(nib, owner: nil, options: nil)?.first as! Self } }
b95cda00c498ea7f1379a093071136e3
18.962963
86
0.593692
false
false
false
false
treasure-data/td-ios-sdk
refs/heads/master
TreasureDataExample/TreasureDataExample/IAPViewController.swift
apache-2.0
1
// // IAPViewController.swift // TreasureDataExample // // Created by huylenq on 3/7/19. // Copyright © 2019 Arm Treasure Data. All rights reserved. // import UIKit import StoreKit class IAPViewController : UITableViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver { var products: [SKProduct] = [] let indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) override func viewDidLoad() { indicator.center = CGPoint(x: self.view.center.x, y: self.view.center.y * 0.3) indicator.color = .gray indicator.hidesWhenStopped = true indicator.startAnimating() self.view.addSubview(indicator) requestProducts() } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { if (transaction.transactionState != .purchasing) { queue.finishTransaction(transaction) } } } @IBAction func purchase(_ sender: UIButton) { (self.parent as! iOSViewController).updateClientIfFormChanged() let product = products[sender.tag] SKPaymentQueue.default().add(SKPayment(product: product)) } public func requestProducts() { let request = SKProductsRequest(productIdentifiers: TreasureDataExample.productIds()) request.delegate = self request.start() SKPaymentQueue.default().add(self) } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { self.products = response.products (self.view as? UITableView)?.separatorStyle = .singleLine indicator.stopAnimating() self.tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "IAPItemCell") as! IAPItemCell cell.itemName.text = products[indexPath.row].localizedTitle cell.purchaseButton.tag = indexPath.row return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let product = products[indexPath.row] let payment = SKMutablePayment(product: product) payment.quantity = 1 SKPaymentQueue.default().add(payment) } } class IAPItemCell : UITableViewCell { @IBOutlet weak var itemName: UILabel! @IBOutlet weak var purchaseButton: UIButton! }
52d38264613f5a847f5a007c903dab41
29.731183
107
0.6655
false
false
false
false
bromas/ActivityViewController
refs/heads/master
ActivityViewController/ActivityTransitionManager.swift
mit
1
// // ApplicationTransitionManager.swift // ApplicationVCSample // // Created by Brian Thomas on 3/1/15. // Copyright (c) 2015 Brian Thomas. All rights reserved. // import Foundation import UIKit internal class ActivityTransitionManager { fileprivate weak var managedContainer : ActivityViewController? internal var activeVC : UIViewController? lazy internal var typeAnimator: AnimateByTypeManager = { return AnimateByTypeManager(containerController: self.managedContainer) }() lazy internal var noninteractiveTransitionManager: AnimateNonInteractiveTransitionManager = { return AnimateNonInteractiveTransitionManager(containerController: self.managedContainer) }() init (containerController: ActivityViewController) { managedContainer = containerController } var containerView: UIView? = .none /** An 'active controller's view should be contained in a UIView subview of the container controller to operate correctly with all transition types. */ internal func transitionToVC(_ controller: UIViewController, withOperation operation: ActivityOperation) { guard let managedContainer = managedContainer else { return } if let activeVCUnwrapped = activeVC { switch operation.type { case .animationOption: managedContainer.animating = true typeAnimator.animate(operation.animationOption, fromVC: activeVCUnwrapped, toVC: controller, withDuration: operation.animationDuration, completion: completionGen(operation)) case .nonInteractiveTransition: managedContainer.animating = true noninteractiveTransitionManager.animate(operation.nonInteractiveTranstionanimator, fromVC: activeVCUnwrapped, toVC: controller, completion: completionGen(operation)) case .none: _ = swapToControllerUnanimated(controller, fromController: activeVCUnwrapped) default: assert(false, "You called for a transition with an invalid operation... How did you even do that!?") } activeVC = controller } else { _ = initializeDisplayWithController(controller) } } fileprivate func completionGen(_ operation: ActivityOperation) -> (() -> Void) { return { [weak self] _ in operation.completionBlock() self?.managedContainer?.animating = false } } fileprivate func swapToControllerUnanimated(_ controller: UIViewController, fromController: UIViewController) -> Bool { guard let container = containerView else { return false } removeController(fromController) self.activeVC = .none prepareContainmentFor(controller, inController: managedContainer) container.addSubview(controller.view) constrainEdgesOf(controller.view, toEdgesOf: container) controller.didMove(toParentViewController: managedContainer); self.activeVC = controller return true } func initializeDisplayWithController(_ controller: UIViewController) -> Bool { guard let managedContainer = managedContainer else { return false } let container = UIView(frame: CGRect.zero) container.translatesAutoresizingMaskIntoConstraints = false managedContainer.view.addSubview(container) constrainEdgesOf(container, toEdgesOf: managedContainer.view) containerView = container managedContainer.configureContainerView(container) prepareContainmentFor(controller, inController: managedContainer) container.addSubview(controller.view) constrainEdgesOf(controller.view, toEdgesOf: container) controller.didMove(toParentViewController: managedContainer); self.activeVC = controller return true } fileprivate func removeController(_ controller: UIViewController) { controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.didMove(toParentViewController: nil) } }
66a976623e6135026a158a1cb3ec5702
34.225225
181
0.74578
false
false
false
false
hhsolar/MemoryMaster-iOS
refs/heads/master
MemoryMaster/View/EditNoteCollectionViewCell.swift
mit
1
// // EditNoteCollectionViewCell.swift // MemoryMaster // // Created by apple on 23/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import UIKit protocol EditNoteCollectionViewCellDelegate: class { func noteTitleEdit(for cell: EditNoteCollectionViewCell) func noteTextContentChange(cardIndex: Int, textViewType: String, textContent: NSAttributedString) func noteAddPhoto() } class EditNoteCollectionViewCell: UICollectionViewCell { @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var titleEditButton: UIButton! @IBOutlet weak var titleLable: UILabel! @IBOutlet weak var bodyTextView: UITextView! let titleTextView = UITextView() let titleKeyboardAddPhotoButton = UIButton() let bodyKeyboardAddPhotoButton = UIButton() var cardIndex: Int? var currentStatus: CardStatus? var editingTextView: UITextView? weak var delegate: EditNoteCollectionViewCellDelegate? var titleText: NSAttributedString? { get { return titleTextView.attributedText } } var bodyText: NSAttributedString? { get { return bodyTextView.attributedText } } override func awakeFromNib() { super.awakeFromNib() setupUI() } private func setupUI() { contentView.backgroundColor = CustomColor.paperColor titleEditButton.setTitleColor(CustomColor.medianBlue, for: .normal) // titleTextView titleTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge) titleTextView.backgroundColor = CustomColor.paperColor titleTextView.tag = OutletTag.titleTextView.rawValue titleTextView.showsVerticalScrollIndicator = false titleTextView.delegate = self contentView.addSubview(titleTextView) let titleAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) titleKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight) titleKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal) titleKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside) titleAccessoryView.addSubview(titleKeyboardAddPhotoButton) titleTextView.inputAccessoryView = titleAccessoryView // bodyTextView bodyTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge) bodyTextView.backgroundColor = CustomColor.paperColor bodyTextView.tag = OutletTag.bodyTextView.rawValue bodyTextView.showsVerticalScrollIndicator = false bodyTextView.delegate = self let bodyAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) bodyKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight) bodyKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal) bodyKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside) bodyAccessoryView.addSubview(bodyKeyboardAddPhotoButton) bodyTextView.inputAccessoryView = bodyAccessoryView } override func layoutSubviews() { super.layoutSubviews() titleTextView.frame = bodyTextView.frame } func updateCell(with cardContent: CardContent, at index: Int, total: Int, cellStatus: CardStatus, noteType: NoteType) { cardIndex = index currentStatus = cellStatus indexLabel.text = String.init(format: "%d / %d", index + 1, total) bodyTextView.attributedText = cardContent.body.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.body.length)) if noteType == NoteType.single { titleEditButton.isHidden = false } else { titleEditButton.isHidden = true } switch cellStatus { case .titleFront: titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length)) showTitle(noteType: noteType) case .bodyFrontWithTitle: titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length)) showBody(noteType: noteType) default: showBody(noteType: noteType) titleTextView.attributedText = NSAttributedString() } } func showTitle(noteType: NoteType) { UIView.animateKeyframes(withDuration: 0.5, delay: 0.3, options: [], animations: { if noteType == NoteType.single { self.titleEditButton.setTitle("Remove Title", for: .normal) self.titleLable.text = "Title" } else { self.titleLable.text = "Question" } self.titleTextView.alpha = 1.0 self.bodyTextView.alpha = 0.0 }, completion: nil) titleTextView.isHidden = false bodyTextView.isHidden = true bodyTextView.resignFirstResponder() editingTextView = titleTextView } func showBody(noteType: NoteType) { UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: { if noteType == NoteType.single { self.titleLable.text = "" if self.currentStatus == CardStatus.bodyFrontWithTitle { self.titleEditButton.setTitle("Remove Title", for: .normal) } else { self.titleEditButton.setTitle("Add Title", for: .normal) } } else { self.titleLable.text = "Answer" } self.titleTextView.alpha = 0.0 self.bodyTextView.alpha = 1.0 }, completion: nil) titleTextView.isHidden = true bodyTextView.isHidden = false titleTextView.resignFirstResponder() editingTextView = bodyTextView } @IBAction func titleEditAction(_ sender: UIButton) { delegate?.noteTitleEdit(for: self) } @objc func addPhotoAction() { delegate?.noteAddPhoto() } func cutTextView(KBHeight: CGFloat) { editingTextView?.frame.size.height = contentView.bounds.height + CustomSize.barHeight - KBHeight - CustomSize.buttonHeight } func extendTextView() { editingTextView?.frame.size.height = contentView.bounds.height - CustomSize.buttonHeight } } extension EditNoteCollectionViewCell: UITextViewDelegate { func textViewDidChangeSelection(_ textView: UITextView) { if textView.tag == OutletTag.titleTextView.rawValue { delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "title", textContent: titleText!) } else if textView.tag == OutletTag.bodyTextView.rawValue { delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "body", textContent: bodyText!) } } func textViewDidChange(_ textView: UITextView) { if textView.markedTextRange == nil { let range = textView.selectedRange let attrubuteStr = NSMutableAttributedString(attributedString: textView.attributedText) attrubuteStr.addAttributes(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: textView.text.count)) textView.attributedText = attrubuteStr textView.selectedRange = range } } }
d9626437e5ecc96716308f0d33c6d733
40.8125
209
0.670279
false
false
false
false
tensorflow/swift-models
refs/heads/main
Examples/ResNet50-ImageNet/main.swift
apache-2.0
1
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // 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 Datasets import ImageClassificationModels import TensorBoard import TensorFlow import TrainingLoop // XLA mode can't load Imagenet, need to use eager mode to limit memory use let device = Device.defaultTFEager let dataset = ImageNet(batchSize: 32, outputSize: 224, on: device) var model = ResNet(classCount: 1000, depth: .resNet50) // https://github.com/mlcommons/training/blob/4f97c909f3aeaa3351da473d12eba461ace0be76/image_classification/tensorflow/official/resnet/imagenet_main.py#L286 let optimizer = SGD(for: model, learningRate: 0.1, momentum: 0.9) public func scheduleLearningRate<L: TrainingLoopProtocol>( _ loop: inout L, event: TrainingLoopEvent ) throws where L.Opt.Scalar == Float { if event == .epochStart { guard let epoch = loop.epochIndex else { return } if epoch > 30 { loop.optimizer.learningRate = 0.01 } if epoch > 60 { loop.optimizer.learningRate = 0.001 } if epoch > 80 { loop.optimizer.learningRate = 0.0001 } } } var trainingLoop = TrainingLoop( training: dataset.training, validation: dataset.validation, optimizer: optimizer, lossFunction: softmaxCrossEntropy, metrics: [.accuracy], callbacks: [scheduleLearningRate, tensorBoardStatisticsLogger()]) try! trainingLoop.fit(&model, epochs: 90, on: device)
1c133d014403c1aea4af1dac032a49cb
39.361702
156
0.756458
false
false
false
false
uber/rides-ios-sdk
refs/heads/master
source/UberCoreTests/LoginManagerTests.swift
mit
1
// // LoginManagerTests.swift // UberRides // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import CoreLocation import WebKit @testable import UberCore class LoginManagerTests: XCTestCase { private let timeout: Double = 2 override func setUp() { super.setUp() Configuration.plistName = "testInfo" Configuration.restoreDefaults() Configuration.shared.isSandbox = true } override func tearDown() { Configuration.restoreDefaults() super.tearDown() } func testRidesAppDelegateContainsManager_afterNativeLogin() { let loginManager = LoginManager(loginType: .native) loginManager.login(requestedScopes: [.profile], presentingViewController: nil, completion: nil) XCTAssert(UberAppDelegate.shared.loginManager is LoginManager, "Expected RidesAppDelegate to have loginManager instance") } func testAuthentictorIsImplicit_whenLoginWithImplicitType() { let loginManager = LoginManager(loginType: .implicit) let presentingViewController = UIViewController() loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil) XCTAssert(loginManager.authenticator is ImplicitGrantAuthenticator) XCTAssertTrue(loginManager.loggingIn) } func testAuthentictorIsAuthorizationCode_whenLoginWithAuthorizationCodeType() { let loginManager = LoginManager(loginType: .authorizationCode) let presentingViewController = UIViewController() loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil) XCTAssert(loginManager.authenticator is AuthorizationCodeGrantAuthenticator) XCTAssertTrue(loginManager.loggingIn) } func testLoginFails_whenLoggingIn() { let expectation = self.expectation(description: "loginCompletion called") let loginCompletion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void) = { token, error in guard let error = error else { XCTFail() return } XCTAssertEqual(error.code, UberAuthenticationErrorType.unavailable.rawValue) expectation.fulfill() } let loginManagerMock = LoginManagerPartialMock() loginManagerMock.executeLoginClosure = { completionHandler in completionHandler?(nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) } loginManagerMock.login(requestedScopes: [.profile], presentingViewController: nil, completion: loginCompletion) waitForExpectations(timeout: 0.2, handler: nil) } func testOpenURLFails_whenInvalidSource() { let loginManager = LoginManager(loginType: .native) let testApp = UIApplication.shared guard let testURL = URL(string: "http://www.google.com") else { XCTFail() return } let testSourceApplication = "com.not.uber.app" let testAnnotation = "annotation" XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) } func testOpenURLFails_whenNotNativeType() { let loginManager = LoginManager(loginType: .implicit) let testApp = UIApplication.shared guard let testURL = URL(string: "http://www.google.com") else { XCTFail() return } let testSourceApplication = "com.ubercab.foo" let testAnnotation = "annotation" XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) } func testOpenURLSuccess_rides() { let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) let testApp = UIApplication.shared guard let testURL = URL(string: "http://www.google.com") else { XCTFail() return } let testSourceApplication = "com.ubercab.foo" let testAnnotation = "annotation" let authenticatorMock = RidesNativeAuthenticatorPartialStub(scopes: [.profile]) authenticatorMock.consumeResponseCompletionValue = (nil, nil) loginManager.authenticator = authenticatorMock loginManager.loggingIn = true XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) XCTAssertFalse(loginManager.loggingIn) XCTAssertNil(loginManager.authenticator) } func testOpenURLSuccess_eats() { let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) let testApp = UIApplication.shared guard let testURL = URL(string: "http://www.google.com") else { XCTFail() return } let testSourceApplication = "com.ubercab.UberEats" let testAnnotation = "annotation" let authenticatorMock = EatsNativeAuthenticatorPartialStub(scopes: [.profile]) authenticatorMock.consumeResponseCompletionValue = (nil, nil) loginManager.authenticator = authenticatorMock loginManager.loggingIn = true XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) XCTAssertFalse(loginManager.loggingIn) XCTAssertNil(loginManager.authenticator) } func testCancelLoginNotCalled_whenNotEnteringForeground() { let loginManager = LoginManager(loginType: .native) loginManager.loggingIn = true loginManager.applicationDidBecomeActive() XCTAssertNil(loginManager.authenticator) XCTAssertTrue(loginManager.loggingIn) } func testCancelLoginCalled_whenDidBecomeActive() { let loginManager = LoginManager(loginType: .native) loginManager.loggingIn = true loginManager.applicationWillEnterForeground() loginManager.applicationDidBecomeActive() XCTAssertNil(loginManager.authenticator) XCTAssertFalse(loginManager.loggingIn) } func testNativeLoginCompletionDoesFallback_whenUnavailableError_withConfiguration_alwaysUseAuthCodeFallback() { Configuration.shared.alwaysUseAuthCodeFallback = true let scopes = [UberScope.historyLite] let loginManager = LoginManager(loginType: .native) let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) loginManager.authenticator = nativeAuthenticatorStub let viewController = UIViewController() loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) } func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_rides() { Configuration.shared.useFallback = true let scopes = [UberScope.request] let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) loginManager.authenticator = nativeAuthenticatorStub let viewController = UIViewController() loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) } func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_eats() { Configuration.shared.useFallback = true let scopes = [UberScope.request] let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: []) nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) loginManager.authenticator = nativeAuthenticatorStub let viewController = UIViewController() loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) } func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_rides() { let scopes = [UberScope.profile] let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) loginManager.authenticator = nativeAuthenticatorStub let viewController = UIViewController() loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) XCTAssertEqual(loginManager.loginType, LoginType.implicit) } func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_eats() { let scopes = [UberScope.profile] let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: []) nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) loginManager.authenticator = nativeAuthenticatorStub let viewController = UIViewController() loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) XCTAssertEqual(loginManager.loginType, LoginType.implicit) } }
6f5fdceeb5d4d63f55605470448ef872
41.386029
159
0.737618
false
true
false
false
rferrerme/malaga-scala-user-group-meetup
refs/heads/master
2015-06-18_Scala_y_programacion_funcional_101/Functional_Programming.playground/Contents.swift
mit
1
/*: # Functional Programming in Swift ### Based on the Malaga Scala User Group meetup on 2015-06-08: * [Slides](https://docs.google.com/presentation/d/1JYhcSe3JcWdNQkz9oquX3vU5I8gKA-KWuzVPkaQbopk/edit?usp=sharing) * [Code](https://gist.github.com/jserranohidalgo/31e7ea8efecfb36276cf) Pure function: */ let sumPure1 = { (x: Int, y: Int) in x+y } sumPure1(4, 5) //: Function with side effect: let sumPureWithLogging1 = { (x: Int, y: Int) -> Int in println("I'm a side effect") return x+y } sumPureWithLogging1(4, 5) /*: That is not a pure function: * It does not declare everything it does * Pure functions can only do internal things Impure functions are _evil_: * Side effects make things difficult to understand * Testing is also difficult (you need mocks, etc) * Modularity and reusability are also a problem if there are side effects * Efficiency and scalability: pure functions can be executed in any order But we cannot only have pure functions because someone has to do the job: database, web services, log, etc. How do we purify functions? * E.g. logging has to be part of the result * It has to be declared in the signature, as a new data type New type to take care of the logging information: */ enum LoggingInstruction1 { case Info(msg: String) case Warn(msg: String) case Debug(msg: String) var description: String { switch self { case let .Info(msg: msg): return "Info(\(msg))" case let .Warn(msg: msg): return "Warn(\(msg))" case let .Debug(msg: msg): return "Debug(\(msg))" } } } //: New type to combine logging information and value: struct Logging1<T> { var log: LoggingInstruction1 var result: T var description: String { return "(\(log.description), \(result)" } } //: New implementations without side effects: let sumPureWithLogging2 = { (x: Int, y: Int) -> Logging1<Int> in return Logging1<Int>(log: LoggingInstruction1.Info(msg: "\(x) + \(y)"), result: x+y) } let operation = sumPureWithLogging2(4, 5) operation.description let negPureWithLogging2 = { (x: Int) -> Logging1<Int> in return Logging1<Int>(log: LoggingInstruction1.Warn(msg: "Neg \(x)"), result: -x) } negPureWithLogging2(7).description //: Simple test (asserts are not nice in Playgrounds): operation.log.description == "Info(4 + 5)" operation.result == 9 /*: That helps to understand it conceptually. The function returns an integer but decorated with logging instructions. In practice every side effect should have its own type. We will have two separare parts: pure and impure. Programs have the interpreter also to be able to deal with the side effects. What is the gain? * Most part of the code can be tested, it is modular, it can be composed * But the other part has to exist also... * Our logging instructions can be implemented with println or log4j, etc * The business logic of my application will remain unaffected by that * The instructions set that I designed is not going to change * I have designed a language to define my effects My interpreter will remove the decoration and return the pure value: */ func runIO(logging: Logging1<Int>) -> Int { switch logging.log { case let LoggingInstruction1.Info(msg): println("INFO: " + msg) case let LoggingInstruction1.Warn(msg): println("WARN: " + msg) case let LoggingInstruction1.Debug(msg): println("DEBUG: " + msg) } return logging.result } //: See above (Quicklook of each `println`) for the side effects: runIO(sumPureWithLogging2(4, 5)) runIO(sumPureWithLogging2(2, 3)) runIO(negPureWithLogging2(8)) /*: But now it is not possible to do composition because types do not match. This will not compile: negPureWithLogging2(sumPureWithLogging2(4, 5)) We will have to define a special compose operator to solve the problem (`bind`/`flatMap`). LoggingInstruction needs to be able to combine multiple logs: */ enum LoggingInstruction2 { case Info(msg: String) case Warn(msg: String) case Debug(msg: String) // Added to be able to do composition case MultiLog(logs: [LoggingInstruction2]) var description: String { switch self { case let .Info(msg: msg): return "Info(\(msg))" case let .Warn(msg: msg): return "Warn(\(msg))" case let .Debug(msg: msg): return "Debug(\(msg))" case let .MultiLog(logs: logs): return "Multi(\(logs.map({ $0.description })))" } } } LoggingInstruction2.MultiLog(logs: [LoggingInstruction2.Info(msg: "info1"), LoggingInstruction2.Warn(msg: "warn1")]).description //: Implementation of the `bind`/`flatMap` operator: struct Logging2<T> { var log: LoggingInstruction2 var result: T func bind<U>(f: T -> Logging2<U>) -> Logging2<U> { let logging = f(result) return Logging2<U>(log: LoggingInstruction2.MultiLog(logs: [log, logging.log]), result: logging.result) } var description: String { return "(\(log.description), \(result)" } } let sumPureWithLogging3 = { (x: Int, y: Int) -> Logging2<Int> in return Logging2<Int>(log: LoggingInstruction2.Info(msg: "\(x) + \(y)"), result: x+y) } let negPureWithLogging3 = { (x: Int) -> Logging2<Int> in return Logging2<Int>(log: LoggingInstruction2.Warn(msg: "Neg \(x)"), result: -x) } //: Now we can do composition and it will contain all the information (result of the operation and composition of the logging effects): sumPureWithLogging3(4, 5).bind(negPureWithLogging3).description /*: There are other composition operators: * E.g. `pure` will encapsulate a value into something with effects, but the effect will be empty: */ func pure<T>(t: T) -> Logging2<T> { return Logging2<T>(log: LoggingInstruction2.MultiLog(logs: []), result: t) } pure(10).description
de189d6c23a25e1ee0be24ff1f5a98dd
28.348259
135
0.686218
false
false
false
false
TribeMedia/firefox-ios
refs/heads/master
Client/Frontend/Home/TopSitesPanel.swift
mpl-2.0
6
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import XCGLogger import Storage private let log = Logger.browserLogger private let ThumbnailIdentifier = "Thumbnail" extension UIView { public class func viewOrientationForSize(size: CGSize) -> UIInterfaceOrientation { return size.width > size.height ? UIInterfaceOrientation.LandscapeRight : UIInterfaceOrientation.Portrait } } class TopSitesPanel: UIViewController { weak var homePanelDelegate: HomePanelDelegate? private var collection: TopSitesCollectionView? = nil private lazy var dataSource: TopSitesDataSource = { return TopSitesDataSource(profile: self.profile, data: Cursor(status: .Failure, msg: "Nothing loaded yet")) }() private lazy var layout: TopSitesLayout = { return TopSitesLayout() }() var editingThumbnails: Bool = false { didSet { if editingThumbnails != oldValue { dataSource.editingThumbnails = editingThumbnails if editingThumbnails { homePanelDelegate?.homePanelWillEnterEditingMode?(self) } updateRemoveButtonStates() } } } let profile: Profile override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) self.refreshHistory(self.layout.thumbnailCount) self.layout.setupForOrientation(UIView.viewOrientationForSize(size)) } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.AllButUpsideDown } init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationPrivateDataCleared, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let collection = TopSitesCollectionView(frame: self.view.frame, collectionViewLayout: layout) collection.backgroundColor = UIConstants.PanelBackgroundColor collection.delegate = self collection.dataSource = dataSource collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier) collection.keyboardDismissMode = .OnDrag view.addSubview(collection) collection.snp_makeConstraints { make in make.edges.equalTo(self.view) } self.collection = collection self.refreshHistory(layout.thumbnailCount) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataCleared, object: nil) } func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationPrivateDataCleared: refreshHistory(self.layout.thumbnailCount) break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } //MARK: Private Helpers private func updateDataSourceWithSites(result: Maybe<Cursor<Site>>) { if let data = result.successValue { self.dataSource.data = data self.dataSource.profile = self.profile // redraw now we've udpated our sources self.collection?.collectionViewLayout.invalidateLayout() self.collection?.setNeedsLayout() } } private func updateRemoveButtonStates() { for i in 0..<layout.thumbnailCount { if let cell = collection?.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as? ThumbnailCell { //TODO: Only toggle the remove button for non-suggested tiles for now if i < dataSource.data.count { cell.toggleRemoveButton(editingThumbnails) } else { cell.toggleRemoveButton(false) } } } } private func deleteHistoryTileForSite(site: Site, atIndexPath indexPath: NSIndexPath) { profile.history.removeSiteFromTopSites(site) >>== { self.profile.history.getSitesByFrecencyWithLimit(self.layout.thumbnailCount).uponQueue(dispatch_get_main_queue(), block: { result in self.updateDataSourceWithSites(result) self.deleteOrUpdateSites(result, indexPath: indexPath) }) } } private func refreshHistory(frequencyLimit: Int) { self.profile.history.getSitesByFrecencyWithLimit(frequencyLimit).uponQueue(dispatch_get_main_queue(), block: { result in self.updateDataSourceWithSites(result) self.collection?.reloadData() }) } private func deleteOrUpdateSites(result: Maybe<Cursor<Site>>, indexPath: NSIndexPath) { if let data = result.successValue { let numOfThumbnails = self.layout.thumbnailCount collection?.performBatchUpdates({ // If we have enough data to fill the tiles after the deletion, then delete and insert the next one from data if (data.count + SuggestedSites.count >= numOfThumbnails) { self.collection?.deleteItemsAtIndexPaths([indexPath]) self.collection?.insertItemsAtIndexPaths([NSIndexPath(forItem: numOfThumbnails - 1, inSection: 0)]) } // If we don't have enough to fill the thumbnail tile area even with suggested tiles, just delete else if (data.count + SuggestedSites.count) < numOfThumbnails { self.collection?.deleteItemsAtIndexPaths([indexPath]) } }, completion: { _ in self.updateRemoveButtonStates() }) } } } extension TopSitesPanel: HomePanel { func endEditing() { editingThumbnails = false } } extension TopSitesPanel: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if editingThumbnails { return } if let site = dataSource[indexPath.item] { // We're gonna call Top Sites bookmarks for now. let visitType = VisitType.Bookmark let destination = NSURL(string: site.url)?.domainURL() ?? NSURL(string: "about:blank")! homePanelDelegate?.homePanel(self, didSelectURL: destination, visitType: visitType) } } func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if let thumbnailCell = cell as? ThumbnailCell { thumbnailCell.delegate = self if editingThumbnails && indexPath.item < dataSource.data.count && thumbnailCell.removeButton.hidden { thumbnailCell.removeButton.hidden = false } } } } extension TopSitesPanel: ThumbnailCellDelegate { func didRemoveThumbnail(thumbnailCell: ThumbnailCell) { if let indexPath = collection?.indexPathForCell(thumbnailCell) { if let site = dataSource[indexPath.item] { self.deleteHistoryTileForSite(site, atIndexPath: indexPath) } } } func didLongPressThumbnail(thumbnailCell: ThumbnailCell) { editingThumbnails = true } } private class TopSitesCollectionView: UICollectionView { private override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // Hide the keyboard if this view is touched. window?.rootViewController?.view.endEditing(true) super.touchesBegan(touches, withEvent: event) } } private class TopSitesLayout: UICollectionViewLayout { private var thumbnailRows: Int { return max(2, Int((self.collectionView?.frame.height ?? self.thumbnailHeight) / self.thumbnailHeight)) } private var thumbnailCols = 2 private var thumbnailCount: Int { return thumbnailRows * thumbnailCols } private var width: CGFloat { return self.collectionView?.frame.width ?? 0 } // The width and height of the thumbnail here are the width and height of the tile itself, not the image inside the tile. private var thumbnailWidth: CGFloat { let insets = ThumbnailCellUX.Insets return (width - insets.left - insets.right) / CGFloat(thumbnailCols) } // The tile's height is determined the aspect ratio of the thumbnails width. We also take into account // some padding between the title and the image. private var thumbnailHeight: CGFloat { return thumbnailWidth / CGFloat(ThumbnailCellUX.ImageAspectRatio) } // Used to calculate the height of the list. private var count: Int { if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource { return dataSource.collectionView(self.collectionView!, numberOfItemsInSection: 0) } return 0 } private var topSectionHeight: CGFloat { let maxRows = ceil(Float(count) / Float(thumbnailCols)) let rows = min(Int(maxRows), thumbnailRows) let insets = ThumbnailCellUX.Insets return thumbnailHeight * CGFloat(rows) + insets.top + insets.bottom } override init() { super.init() setupForOrientation(UIApplication.sharedApplication().statusBarOrientation) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupForOrientation(orientation: UIInterfaceOrientation) { if orientation.isLandscape { thumbnailCols = 5 } else if UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact { thumbnailCols = 3 } else { thumbnailCols = 4 } } private func getIndexAtPosition(y: CGFloat) -> Int { if y < topSectionHeight { let row = Int(y / thumbnailHeight) return min(count - 1, max(0, row * thumbnailCols)) } return min(count - 1, max(0, Int((y - topSectionHeight) / UIConstants.DefaultRowHeight + CGFloat(thumbnailCount)))) } override func collectionViewContentSize() -> CGSize { if count <= thumbnailCount { return CGSize(width: width, height: topSectionHeight) } let bottomSectionHeight = CGFloat(count - thumbnailCount) * UIConstants.DefaultRowHeight return CGSize(width: width, height: topSectionHeight + bottomSectionHeight) } private var layoutAttributes:[UICollectionViewLayoutAttributes]? private override func prepareLayout() { var layoutAttributes = [UICollectionViewLayoutAttributes]() for section in 0..<(self.collectionView?.numberOfSections() ?? 0) { for item in 0..<(self.collectionView?.numberOfItemsInSection(section) ?? 0) { let indexPath = NSIndexPath(forItem: item, inSection: section) guard let attrs = self.layoutAttributesForItemAtIndexPath(indexPath) else { continue } layoutAttributes.append(attrs) } } self.layoutAttributes = layoutAttributes } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attrs = [UICollectionViewLayoutAttributes]() if let layoutAttributes = self.layoutAttributes { for attr in layoutAttributes { if CGRectIntersectsRect(rect, attr.frame) { attrs.append(attr) } } } return attrs } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) // Set the top thumbnail frames. let row = floor(Double(indexPath.item / thumbnailCols)) let col = indexPath.item % thumbnailCols let insets = ThumbnailCellUX.Insets let x = insets.left + thumbnailWidth * CGFloat(col) let y = insets.top + CGFloat(row) * thumbnailHeight attr.frame = CGRectMake(ceil(x), ceil(y), thumbnailWidth, thumbnailHeight) return attr } } private class TopSitesDataSource: NSObject, UICollectionViewDataSource { var data: Cursor<Site> var profile: Profile var editingThumbnails: Bool = false init(profile: Profile, data: Cursor<Site>) { self.data = data self.profile = profile } @objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if data.status != .Success { return 0 } // If there aren't enough data items to fill the grid, look for items in suggested sites. if let layout = collectionView.collectionViewLayout as? TopSitesLayout { return min(data.count + SuggestedSites.count, layout.thumbnailCount) } return 0 } private func setDefaultThumbnailBackground(cell: ThumbnailCell) { cell.imageView.image = UIImage(named: "defaultTopSiteIcon")! cell.imageView.contentMode = UIViewContentMode.Center } private func getFavicon(cell: ThumbnailCell, site: Site) { self.setDefaultThumbnailBackground(cell) if let url = site.url.asURL { FaviconFetcher.getForURL(url, profile: profile) >>== { icons in if (icons.count > 0) { cell.imageView.sd_setImageWithURL(icons[0].url.asURL!) { (img, err, type, url) -> Void in if let img = img { cell.backgroundImage.image = img cell.image = img } else { let icon = Favicon(url: "", date: NSDate(), type: IconType.NoneFound) self.profile.favicons.addFavicon(icon, forSite: site) self.setDefaultThumbnailBackground(cell) } } } } } } private func createTileForSite(cell: ThumbnailCell, site: Site) -> ThumbnailCell { // We always want to show the domain URL, not the title. // // Eventually we can do something more sophisticated — e.g., if the site only consists of one // history item, show it, and otherwise use the longest common sub-URL (and take its title // if you visited that exact URL), etc. etc. — but not yet. // // The obvious solution here and in collectionView:didSelectItemAtIndexPath: is for the cursor // to return domain sites, not history sites -- that is, with the right icon, title, and URL -- // and for this code to just use what it gets. // // Instead we'll painstakingly re-extract those things here. let domainURL = NSURL(string: site.url)?.normalizedHost() ?? site.url cell.textLabel.text = domainURL cell.imageWrapper.backgroundColor = UIColor.clearColor() // Resets used cell's background image so that it doesn't get recycled when a tile doesn't update its background image. cell.backgroundImage.image = nil if let icon = site.icon { // We've looked before recently and didn't find a favicon switch icon.type { case .NoneFound where NSDate().timeIntervalSinceDate(icon.date) < FaviconFetcher.ExpirationTime: self.setDefaultThumbnailBackground(cell) default: cell.imageView.sd_setImageWithURL(icon.url.asURL, completed: { (img, err, type, url) -> Void in if let img = img { cell.backgroundImage.image = img cell.image = img } else { self.getFavicon(cell, site: site) } }) } } else { getFavicon(cell, site: site) } cell.isAccessibilityElement = true cell.accessibilityLabel = cell.textLabel.text cell.removeButton.hidden = !editingThumbnails return cell } private func createTileForSuggestedSite(cell: ThumbnailCell, site: SuggestedSite) -> ThumbnailCell { cell.textLabel.text = site.title.isEmpty ? NSURL(string: site.url)?.normalizedHostAndPath() : site.title cell.imageWrapper.backgroundColor = site.backgroundColor cell.backgroundImage.image = nil if let icon = site.wordmark.url.asURL, let host = icon.host { if icon.scheme == "asset" { cell.imageView.image = UIImage(named: host) } else { cell.imageView.sd_setImageWithURL(icon, completed: { img, err, type, key in if img == nil { self.setDefaultThumbnailBackground(cell) } }) } } else { self.setDefaultThumbnailBackground(cell) } cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit cell.isAccessibilityElement = true cell.accessibilityLabel = cell.textLabel.text cell.removeButton.hidden = true return cell } subscript(index: Int) -> Site? { if data.status != .Success { return nil } if index >= data.count { return SuggestedSites[index - data.count] } return data[index] as Site? } @objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Cells for the top site thumbnails. let site = self[indexPath.item]! let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell if indexPath.item >= data.count { return createTileForSuggestedSite(cell, site: site as! SuggestedSite) } return createTileForSite(cell, site: site) } }
cabee1cacf913bcdefa8ea5456723cbe
39.18259
151
0.644827
false
false
false
false
corchwll/amos-ss15-proj5_ios
refs/heads/master
MobileTimeAccounting/Model/Profile.swift
agpl-3.0
1
/* Mobile Time Accounting Copyright (C) 2015 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation class Profile { var firstname: String var lastname: String var employeeId: String var weeklyWorkingTime: Int var totalVacationTime: Int var currentVacationTime: Int var currentOvertime: Int var registrationDate: NSDate /* Constructor for model class, representing a profile. @methodtype Constructor @pre - @post Initialized profile */ init(firstname: String, lastname: String, employeeId: String, weeklyWorkingTime: Int, totalVacationTime: Int, currentVacationTime: Int, currentOvertime: Int) { self.firstname = firstname self.lastname = lastname self.employeeId = employeeId self.weeklyWorkingTime = weeklyWorkingTime self.totalVacationTime = totalVacationTime self.currentVacationTime = currentVacationTime self.currentOvertime = currentOvertime self.registrationDate = NSDate() } /* Constructor for model class, representing a profile. @methodtype Constructor @pre - @post Initialized profile */ convenience init(firstname: String, lastname: String, employeeId: String, weeklyWorkingTime: Int, totalVacationTime: Int, currentVacationTime: Int, currentOvertime: Int, registrationDate: NSDate) { self.init(firstname: firstname, lastname: lastname, employeeId: employeeId, weeklyWorkingTime: weeklyWorkingTime, totalVacationTime: totalVacationTime, currentVacationTime: currentVacationTime, currentOvertime: currentOvertime) self.registrationDate = registrationDate } /* Asserts wether id is valid or not(consists only of digits of length 5). @methodtype Assertion @pre - @post - */ static func isValidId(id: String)->Bool { return id.toInt() != nil && count(id) == 5 } /* Asserts wether weekly working time is valid or not(must be a number between 10 and 50). @methodtype Assertion @pre - @post - */ static func isValidWeeklyWorkingTime(weeklyWorkingTime: String)->Bool { if let time = weeklyWorkingTime.toInt() { return time >= 10 && time <= 50 } return false } /* Asserts wether total vacation time is valid or not(must be a number between 0 and 40). @methodtype Assertion @pre - @post - */ static func isValidTotalVacationTime(totalVacationTime: String)->Bool { if let time = totalVacationTime.toInt() { return time >= 0 && time <= 40 } return false } /* Asserts wether current vacation time is valid or not(must be a number greater or equals 0). @methodtype Assertion @pre - @post - */ static func isValidCurrentVacationTime(currentVacationTime: String)->Bool { if let time = currentVacationTime.toInt() { return time >= 0 } return false } /* Asserts wether current over time is valid or not(must be a number). @methodtype Assertion @pre - @post - */ static func isValidCurrentOvertime(currentOvertime: String)->Bool { if let time = currentOvertime.toInt() { return true } return false } /* Returns string representation of user profile @methodtype Convertion @pre - @post String representation of user profile */ func asString()->String { return "\(firstname) \(lastname); \(employeeId); \(weeklyWorkingTime); \(totalVacationTime); \(currentVacationTime); \(currentOvertime)" } }
945ae2096d3759366c31ab8c8a55df10
27.8
235
0.624484
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Distortion/Complex Distortion/AKDistortion.swift
mit
2
// // AKDistortion.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// AudioKit version of Apple's Distortion Audio Unit /// /// - Parameters: /// - input: Input node to process /// - delay: Delay (Milliseconds) ranges from 0.1 to 500 (Default: 0.1) /// - decay: Decay (Rate) ranges from 0.1 to 50 (Default: 1.0) /// - delayMix: Delay Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0.0) /// - decimationMix: Decimation Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - linearTerm: Linear Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - squaredTerm: Squared Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - cubicTerm: Cubic Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - polynomialMix: Polynomial Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - ringModFreq1: Ring Mod Freq1 (Hertz) ranges from 0.5 to 8000 (Default: 100) /// - ringModFreq2: Ring Mod Freq2 (Hertz) ranges from 0.5 to 8000 (Default: 100) /// - ringModBalance: Ring Mod Balance (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - ringModMix: Ring Mod Mix (Normalized Value) ranges from 0 to 1 (Default: 0.0) /// - softClipGain: Soft Clip Gain (dB) ranges from -80 to 20 (Default: -6) /// - finalMix: Final Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// public class AKDistortion: AKNode, AKToggleable { // MARK: - Properties private let cd = AudioComponentDescription( componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_Distortion, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) internal var internalEffect = AVAudioUnitEffect() internal var internalAU: AudioUnit = nil private var lastKnownMix: Double = 0.5 /// Delay (Milliseconds) ranges from 0.1 to 500 (Default: 0.1) public var delay: Double = 0.1 { didSet { if delay < 0.1 { delay = 0.1 } if delay > 500 { delay = 500 } AudioUnitSetParameter( internalAU, kDistortionParam_Delay, kAudioUnitScope_Global, 0, Float(delay), 0) } } /// Decay (Rate) ranges from 0.1 to 50 (Default: 1.0) public var decay: Double = 1.0 { didSet { if decay < 0.1 { decay = 0.1 } if decay > 50 { decay = 50 } AudioUnitSetParameter( internalAU, kDistortionParam_Decay, kAudioUnitScope_Global, 0, Float(decay), 0) } } /// Delay Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var delayMix: Double = 0.5 { didSet { if delayMix < 0 { delayMix = 0 } if delayMix > 1 { delayMix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_DelayMix, kAudioUnitScope_Global, 0, Float(delayMix) * 100.0, 0) } } /// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var decimation: Double = 0.5 { didSet { if decimation < 0 { decimation = 0 } if decimation > 1 { decimation = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_Decimation, kAudioUnitScope_Global, 0, Float(decimation) * 100.0, 0) } } /// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0.0) public var rounding: Double = 0.0 { didSet { if rounding < 0 { rounding = 0 } if rounding > 1 { rounding = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_Rounding, kAudioUnitScope_Global, 0, Float(rounding) * 100.0, 0) } } /// Decimation Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var decimationMix: Double = 0.5 { didSet { if decimationMix < 0 { decimationMix = 0 } if decimationMix > 1 { decimationMix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_DecimationMix, kAudioUnitScope_Global, 0, Float(decimationMix) * 100.0, 0) } } /// Linear Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var linearTerm: Double = 0.5 { didSet { if linearTerm < 0 { linearTerm = 0 } if linearTerm > 1 { linearTerm = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_LinearTerm, kAudioUnitScope_Global, 0, Float(linearTerm) * 100.0, 0) } } /// Squared Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var squaredTerm: Double = 0.5 { didSet { if squaredTerm < 0 { squaredTerm = 0 } if squaredTerm > 1 { squaredTerm = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_SquaredTerm, kAudioUnitScope_Global, 0, Float(squaredTerm) * 100.0, 0) } } /// Cubic Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var cubicTerm: Double = 0.5 { didSet { if cubicTerm < 0 { cubicTerm = 0 } if cubicTerm > 1 { cubicTerm = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_CubicTerm, kAudioUnitScope_Global, 0, Float(cubicTerm) * 100.0, 0) } } /// Polynomial Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var polynomialMix: Double = 0.5 { didSet { if polynomialMix < 0 { polynomialMix = 0 } if polynomialMix > 1 { polynomialMix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_PolynomialMix, kAudioUnitScope_Global, 0, Float(polynomialMix * 100.0), 0) } } /// Ring Mod Freq1 (Hertz) ranges from 0.5 to 8000 (Default: 100) public var ringModFreq1: Double = 100 { didSet { if ringModFreq1 < 0.5 { ringModFreq1 = 0.5 } if ringModFreq1 > 8000 { ringModFreq1 = 8000 } AudioUnitSetParameter( internalAU, kDistortionParam_RingModFreq1, kAudioUnitScope_Global, 0, Float(ringModFreq1), 0) } } /// Ring Mod Freq2 (Hertz) ranges from 0.5 to 8000 (Default: 100) public var ringModFreq2: Double = 100 { didSet { if ringModFreq2 < 0.5 { ringModFreq2 = 0.5 } if ringModFreq2 > 8000 { ringModFreq2 = 8000 } AudioUnitSetParameter( internalAU, kDistortionParam_RingModFreq2, kAudioUnitScope_Global, 0, Float(ringModFreq2), 0) } } /// Ring Mod Balance (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var ringModBalance: Double = 0.5 { didSet { if ringModBalance < 0 { ringModBalance = 0 } if ringModBalance > 1 { ringModBalance = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_RingModBalance, kAudioUnitScope_Global, 0, Float(ringModBalance * 100.0), 0) } } /// Ring Mod Mix (Normalized Value) ranges from 0 to 1 (Default: 0.0) public var ringModMix: Double = 0.0 { didSet { if ringModMix < 0 { ringModMix = 0 } if ringModMix > 1 { ringModMix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_RingModMix, kAudioUnitScope_Global, 0, Float(ringModMix * 100.0), 0) } } /// Soft Clip Gain (dB) ranges from -80 to 20 (Default: -6) public var softClipGain: Double = -6 { didSet { if softClipGain < -80 { softClipGain = -80 } if softClipGain > 20 { softClipGain = 20 } AudioUnitSetParameter( internalAU, kDistortionParam_SoftClipGain, kAudioUnitScope_Global, 0, Float(softClipGain), 0) } } /// Final Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var finalMix: Double = 0.5 { didSet { if finalMix < 0 { finalMix = 0 } if finalMix > 1 { finalMix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_FinalMix, kAudioUnitScope_Global, 0, Float(finalMix * 100.0), 0) } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted = true // MARK: - Initialization /// Initialize the distortion node /// /// - Parameters: /// - input: Input node to process /// - delay: Delay (Milliseconds) ranges from 0.1 to 500 (Default: 0.1) /// - decay: Decay (Rate) ranges from 0.1 to 50 (Default: 1.0) /// - delayMix: Delay Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0.0) /// - decimationMix: Decimation Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - linearTerm: Linear Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - squaredTerm: Squared Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - cubicTerm: Cubic Term (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - polynomialMix: Polynomial Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - ringModFreq1: Ring Mod Freq1 (Hertz) ranges from 0.5 to 8000 (Default: 100) /// - ringModFreq2: Ring Mod Freq2 (Hertz) ranges from 0.5 to 8000 (Default: 100) /// - ringModBalance: Ring Mod Balance (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - ringModMix: Ring Mod Mix (Normalized Value) ranges from 0 to 1 (Default: 0.0) /// - softClipGain: Soft Clip Gain (dB) ranges from -80 to 20 (Default: -6) /// - finalMix: Final Mix (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// public init( _ input: AKNode, delay: Double = 0.1, decay: Double = 1.0, delayMix: Double = 0.5, decimation: Double = 0.5, rounding: Double = 0.0, decimationMix: Double = 0.5, linearTerm: Double = 0.5, squaredTerm: Double = 0.5, cubicTerm: Double = 0.5, polynomialMix: Double = 0.5, ringModFreq1: Double = 100, ringModFreq2: Double = 100, ringModBalance: Double = 0.5, ringModMix: Double = 0.0, softClipGain: Double = -6, finalMix: Double = 0.5) { self.delay = delay self.decay = decay self.delayMix = delayMix self.decimation = decimation self.rounding = rounding self.decimationMix = decimationMix self.linearTerm = linearTerm self.squaredTerm = squaredTerm self.cubicTerm = cubicTerm self.polynomialMix = polynomialMix self.ringModFreq1 = ringModFreq1 self.ringModFreq2 = ringModFreq2 self.ringModBalance = ringModBalance self.ringModMix = ringModMix self.softClipGain = softClipGain self.finalMix = finalMix internalEffect = AVAudioUnitEffect(audioComponentDescription: cd) super.init() avAudioNode = internalEffect AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) internalAU = internalEffect.audioUnit AudioUnitSetParameter(internalAU, kDistortionParam_Delay, kAudioUnitScope_Global, 0, Float(delay), 0) AudioUnitSetParameter(internalAU, kDistortionParam_Decay, kAudioUnitScope_Global, 0, Float(decay), 0) AudioUnitSetParameter(internalAU, kDistortionParam_DelayMix, kAudioUnitScope_Global, 0, Float(delayMix) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_Decimation, kAudioUnitScope_Global, 0, Float(decimation) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_Rounding, kAudioUnitScope_Global, 0, Float(rounding) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_DecimationMix, kAudioUnitScope_Global, 0, Float(decimationMix) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_LinearTerm, kAudioUnitScope_Global, 0, Float(linearTerm) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_SquaredTerm, kAudioUnitScope_Global, 0, Float(squaredTerm) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_CubicTerm, kAudioUnitScope_Global, 0, Float(cubicTerm) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_PolynomialMix, kAudioUnitScope_Global, 0, Float(polynomialMix) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_RingModFreq1, kAudioUnitScope_Global, 0, Float(ringModFreq1), 0) AudioUnitSetParameter(internalAU, kDistortionParam_RingModFreq2, kAudioUnitScope_Global, 0, Float(ringModFreq2), 0) AudioUnitSetParameter(internalAU, kDistortionParam_RingModBalance, kAudioUnitScope_Global, 0, Float(ringModBalance) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_RingModMix, kAudioUnitScope_Global, 0, Float(ringModMix) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_SoftClipGain, kAudioUnitScope_Global, 0, Float(softClipGain), 0) AudioUnitSetParameter(internalAU, kDistortionParam_FinalMix, kAudioUnitScope_Global, 0, Float(finalMix) * 100.0, 0) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { finalMix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownMix = finalMix finalMix = 0 isStarted = false } } }
7470d033575850755605fb2b03786319
36.147887
139
0.558167
false
false
false
false
RyanTech/cannonball-ios
refs/heads/master
Cannonball/SignInViewController.swift
apache-2.0
3
// // Copyright (C) 2014 Twitter, Inc. and other contributors. // // 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 UIKit import TwitterKit import DigitsKit import Crashlytics class SignInViewController: UIViewController, UIAlertViewDelegate { // MARK: Properties @IBOutlet weak var logoView: UIImageView! @IBOutlet weak var signInTwitterButton: UIButton! @IBOutlet weak var signInPhoneButton: UIButton! // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Color the logo. logoView.image = logoView.image?.imageWithRenderingMode(.AlwaysTemplate) logoView.tintColor = UIColor(red: 0, green: 167/255, blue: 155/255, alpha: 1) // Decorate the Sign In with Twitter and Phone buttons. let defaultColor = signInPhoneButton.titleLabel?.textColor decorateButton(signInTwitterButton, color: UIColor(red: 0.333, green: 0.675, blue: 0.933, alpha: 1)) decorateButton(signInPhoneButton, color: defaultColor!) // Add custom image to the Sign In with Phone button. let image = UIImage(named: "Phone")?.imageWithRenderingMode(.AlwaysTemplate) signInPhoneButton.setImage(image, forState: .Normal) } private func navigateToMainAppScreen() { performSegueWithIdentifier("ShowThemeChooser", sender: self) } // MARK: IBActions @IBAction func signInWithTwitter(sender: UIButton) { Twitter.sharedInstance().logInWithCompletion { session, error in if session != nil { // Navigate to the main app screen to select a theme. self.navigateToMainAppScreen() // Tie crashes to a Twitter user ID and username in Crashlytics. Crashlytics.sharedInstance().setUserIdentifier(session.userID) Crashlytics.sharedInstance().setUserName(session.userName) // Log Answers Custom Event. Answers.logLoginWithMethod("Twitter", success: true, customAttributes: ["User ID": session.userID]) } else { // Log Answers Custom Event. Answers.logLoginWithMethod("Twitter", success: false, customAttributes: ["Error": error.localizedDescription]) } } } @IBAction func signInWithPhone(sender: UIButton) { // Create a Digits appearance with Cannonball colors. let appearance = DGTAppearance() appearance.backgroundColor = UIColor.cannonballBeigeColor() appearance.accentColor = UIColor.cannonballGreenColor() // Start the Digits authentication flow with the custom appearance. Digits.sharedInstance().authenticateWithDigitsAppearance(appearance, viewController: nil, title: nil) { session, error in if session != nil { // Navigate to the main app screen to select a theme. self.navigateToMainAppScreen() // Tie crashes to a Digits user ID in Crashlytics. Crashlytics.sharedInstance().setUserIdentifier(session.userID) // Log Answers Custom Event. Answers.logLoginWithMethod("Digits", success: true, customAttributes: ["User ID": session.userID]) } else { // Log Answers Custom Event. Answers.logLoginWithMethod("Digits", success: false, customAttributes: ["Error": error.localizedDescription]) } } } @IBAction func skipSignIn(sender: AnyObject) { // Log Answers Custom Event. Answers.logCustomEventWithName("Skipped Sign In", customAttributes: nil) } // MARK: Utilities private func decorateButton(button: UIButton, color: UIColor) { // Draw the border around a button. button.layer.masksToBounds = false button.layer.borderColor = color.CGColor button.layer.borderWidth = 2 button.layer.cornerRadius = 6 } }
770dee94ff6d5105e9e21277d7f7295c
37.826087
129
0.665174
false
false
false
false
timd/Flashcardr
refs/heads/master
Flashcards/Card.swift
mit
1
// // Card.swift // Flashcards // // Created by Tim on 22/07/15. // Copyright (c) 2015 Tim Duckett. All rights reserved. // import RealmSwift class Card: Object { dynamic var uid: Int = 0 dynamic var sortOrder: Int = 0 dynamic var deutsch: String = "" dynamic var englisch: String = "" dynamic var score: Int = 0 let sections = List<Section>() }
c73281e15289e74d0d00d9bdf2d09ef9
17.47619
56
0.615979
false
false
false
false
GrouponChina/groupon-up
refs/heads/master
Groupon UP/Groupon UP/UPConstants.swift
apache-2.0
1
// // UPConstants.swift // Groupon UP // // Created by Robert Xue on 11/21/15. // Copyright © 2015 Chang Liu. All rights reserved. // import UIKit let UPBackgroundColor = UIColor.whiteColor() let UPTintColor = UIColor(rgba: "#82b548") let UPSpanSize = 15 let UPPrimaryTextColor = UIColor(rgba: "#333333") let UPSecondaryTextColor = UIColor(rgba: "#666666") let UPDangerZoneColor = UIColor(rgba: "#df3e3e") let UPTextColorOnDardBackground = UIColor(rgba: "#f2f2f2") let UPContentFont = UIFont(name: "Avenir", size: 17)! let UPBorderRadius: CGFloat = 5 let UPBorderWidth: CGFloat = 1.0 let UPContainerMargin = 8 //Groupon Color let UPBackgroundGrayColor = UIColor(rgba: "#f2f2f2") let UPDarkGray = UIColor(rgba: "#666666") let UPUrgencyOrange = UIColor(rgba: "#e35205") //font let UPFontBold = "HelveticaNeue-Bold" let UPFont = "HelveticaNeue"
e751d088e8484324d16aa4d6a9227639
26.451613
58
0.737955
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Extensions/ShareTo/ShareViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage struct ShareDestination { let code: String let name: String let image: String } // TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values. let ShareDestinationBookmarks: String = "Bookmarks" let ShareDestinationReadingList: String = "ReadingList" let ShareDestinations = [ ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"), ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks") ] protocol ShareControllerDelegate { func shareControllerDidCancel(shareController: ShareDialogController) -> Void func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void } private struct ShareDialogControllerUX { static let CornerRadius: CGFloat = 4 // Corner radius of the dialog static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize()) // System default static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize()) // System default static let NavigationBarIconSize = 38 // Width and height of the icon static let NavigationBarBottomPadding = 12 static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium) static let ItemTitleFont = UIFont.systemFontOfSize(15) static let ItemTitleMaxNumberOfLines = 2 static let ItemTitleLeftPadding = 44 static let ItemTitleRightPadding = 44 static let ItemTitleBottomPadding = 12 static let ItemLinkFont = UIFont.systemFontOfSize(12) static let ItemLinkMaxNumberOfLines = 3 static let ItemLinkLeftPadding = 44 static let ItemLinkRightPadding = 44 static let ItemLinkBottomPadding = 14 static let DividerColor = UIColor.lightGrayColor() // Divider between the item and the table with destinations static let DividerHeight = 0.5 static let TableRowHeight: CGFloat = 44 // System default static let TableRowFont = UIFont.systemFontOfSize(14) static let TableRowFontMinScale: CGFloat = 0.8 static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark static let TableRowTextColor = UIColor(rgb: 0x555555) static let TableHeight = 88 // Height of 2 standard 44px cells } class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate { var delegate: ShareControllerDelegate! var item: ShareItem! var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks) var selectedShareDestinations: NSMutableSet = NSMutableSet() var navBar: UINavigationBar! var navItem: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() selectedShareDestinations = NSMutableSet(set: initialShareDestinations) self.view.backgroundColor = UIColor.whiteColor() self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius self.view.clipsToBounds = true // Setup the NavigationBar navBar = UINavigationBar() navBar.translatesAutoresizingMaskIntoConstraints = false navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor navBar.translucent = false self.view.addSubview(navBar) // Setup the NavigationItem navItem = UINavigationItem() navItem.leftBarButtonItem = UIBarButtonItem( title: Strings.ShareToCancelButton, style: .Plain, target: self, action: #selector(ShareDialogController.cancel) ) navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal) navItem.leftBarButtonItem?.accessibilityIdentifier = "ShareDialogController.navigationItem.leftBarButtonItem" navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(ShareDialogController.add)) navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal) let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize)) logo.image = UIImage(named: "Icon-Small") logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size navItem.titleView = logo navBar.pushNavigationItem(navItem, animated: false) // Setup the title view let titleView = UILabel() titleView.translatesAutoresizingMaskIntoConstraints = false titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail titleView.text = item.title titleView.font = ShareDialogControllerUX.ItemTitleFontMedium view.addSubview(titleView) // Setup the link view let linkView = UILabel() linkView.translatesAutoresizingMaskIntoConstraints = false linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail linkView.text = item.url linkView.font = ShareDialogControllerUX.ItemLinkFont view.addSubview(linkView) // Setup the icon let iconView = UIImageView() iconView.translatesAutoresizingMaskIntoConstraints = false iconView.image = UIImage(named: "defaultFavicon") view.addSubview(iconView) // Setup the divider let dividerView = UIView() dividerView.translatesAutoresizingMaskIntoConstraints = false dividerView.backgroundColor = ShareDialogControllerUX.DividerColor view.addSubview(dividerView) // Setup the table with destinations let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.userInteractionEnabled = true tableView.delegate = self tableView.allowsSelection = true tableView.dataSource = self tableView.scrollEnabled = false view.addSubview(tableView) // Setup constraints let views = [ "nav": navBar, "title": titleView, "link": linkView, "icon": iconView, "divider": dividerView, "table": tableView ] // TODO See Bug 1102516 - Use Snappy to define share extension layout constraints let constraints = [ "H:|[nav]|", "V:|[nav]", "H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|", "V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]", "H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|", "V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]", "H:|[divider]|", "V:[divider(\(ShareDialogControllerUX.DividerHeight))]", "V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]", "H:|[table]|", "V:[divider][table]", "V:[table(\(ShareDialogControllerUX.TableHeight))]|" ] for constraint in constraints { view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views)) } } // UITabBarItem Actions that map to our delegate methods func cancel() { delegate?.shareControllerDidCancel(self) } func add() { delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations)) } // UITableView Delegate and DataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ShareDestinations.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ShareDialogControllerUX.TableRowHeight } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor cell.textLabel?.font = ShareDialogControllerUX.TableRowFont cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None cell.tintColor = ShareDialogControllerUX.TableRowTintColor cell.layoutMargins = UIEdgeInsetsZero cell.textLabel?.text = ShareDestinations[indexPath.row].name cell.textLabel?.adjustsFontSizeToFitWidth = true cell.textLabel?.minimumScaleFactor = ShareDialogControllerUX.TableRowFontMinScale cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let code = ShareDestinations[indexPath.row].code if selectedShareDestinations.containsObject(code) { selectedShareDestinations.removeObject(code) } else { selectedShareDestinations.addObject(code) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0) } }
8481a876f5e78660192381dbeaaea7a1
44.821138
244
0.702981
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Reports/Generators/ReportGenerator.swift
agpl-3.0
2
// // ReportGenerator.swift // SmartReceipts // // Created by Bogdan Evsenev on 03/12/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Foundation typealias CategoryReceipts = (category: WBCategory, receipts: [WBReceipt]) @objcMembers class ReportGenerator: NSObject { private(set) var trip: WBTrip! private(set) var database: Database! init(trip: WBTrip, database: Database) { self.trip = trip self.database = database } func generateTo(path: String) -> Bool { abstractMethodError() return false } func receiptColumns() -> [ReceiptColumn] { abstractMethodError() return [] } func categoryColumns() -> [CategoryColumn] { return CategoryColumn.allColumns() } func distanceColumns() -> [DistanceColumn] { return DistanceColumn.allColumns() as! [DistanceColumn] } func receipts() -> [WBReceipt] { var receipts = database.allReceipts(for: trip, ascending: true) as! [WBReceipt] receipts = receipts.filter { !$0.isMarkedForDeletion } return ReceiptIndexer.indexReceipts(receipts, filter: { WBReportUtils.filterOutReceipt($0) }) } func distances() -> [Distance] { let distances = database.fetchedAdapterForDistances(in: trip, ascending: true) return distances?.allObjects() as! [Distance] } func receiptsByCategories() -> [CategoryReceipts] { var result = [WBCategory: [WBReceipt]]() let receipts = self.receipts() receipts.forEach { guard let category = $0.category else { return } if result[category] == nil { result[category] = [] } result[category]?.append($0) } if WBPreferences.printDailyDistanceValues() { let dReceipts = DistancesToReceiptsConverter.convertDistances(distances()) as! [WBReceipt] if let category = dReceipts.first?.category { result[category] = dReceipts } } return result .filter { !$0.value.isEmpty } .sorted { $0.key.customOrderId < $1.key.customOrderId } .map { ($0.key, $0.value) } } } fileprivate func abstractMethodError() { fatalError("Abstract Method") }
c9d4341478e067d06e78f1a363dfc366
29.230769
102
0.603478
false
false
false
false
onebytecode/krugozor-iOSVisitors
refs/heads/develop
krugozor-visitorsApp/OnboardPageVC.swift
apache-2.0
1
// // OnboardPageVC.swift // krugozor-visitorsApp // // Created by Stanly Shiyanovskiy on 27.09.17. // Copyright © 2017 oneByteCode. All rights reserved. // import UIKit class OnboardPageVC: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { static func storyboardInstance() -> OnboardPageVC? { let storyboard = UIStoryboard(name: String(describing: self), bundle: nil) return storyboard.instantiateInitialViewController() as? OnboardPageVC } // MARK: - Properties - let contentImages = [("Onboard_1", "Landing Page #1."), ("Onboard_2", "Landing Page #2.")] // MARK: - Outlets - override func viewDidLoad() { self.delegate = self self.dataSource = self if contentImages.count > 0 { let firstController = getItemController(0)! let startingViewControllers = [firstController] self.setViewControllers(startingViewControllers, direction: .forward, animated: false, completion: nil) } setupPageControl() } func setupPageControl() { self.view.backgroundColor = UIColor.white let appearance = UIPageControl.appearance() appearance.pageIndicatorTintColor = UIColor.CustomColors.second appearance.currentPageIndicatorTintColor = UIColor.CustomColors.first appearance.backgroundColor = UIColor.white } // MARK: - UIPageViewControllerDataSource methods - func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let itemController = viewController as! OnboardTemplateVC if itemController.itemIndex > 0 { return getItemController(itemController.itemIndex - 1) } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let itemController = viewController as? OnboardTemplateVC { if itemController.itemIndex + 1 < contentImages.count { return getItemController(itemController.itemIndex + 1) } else if itemController.itemIndex + 1 == contentImages.count { let itemController2 = LogInVC.storyboardInstance()! return getItemController(itemController2.itemIndex + contentImages.count) } } return nil } func getItemController(_ itemIndex: Int) -> UIViewController? { if itemIndex < contentImages.count { if let pageVC = OnboardTemplateVC.storyboardInstance() { pageVC.itemIndex = itemIndex pageVC.contentModel = contentImages[itemIndex] return pageVC } } else if itemIndex == contentImages.count { if let loginVC = LogInVC.storyboardInstance() { return loginVC } } return nil } // MARK: - Page Indicator - func presentationCount(for pageViewController: UIPageViewController) -> Int { return contentImages.count + 1 } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return 0 } // MARK: - Additions - func currentControllerIndex() -> Int { let pageItemController = self.currentController() if let controller = pageItemController as? OnboardTemplateVC { return controller.itemIndex } return -1 } func currentController() -> UIViewController? { if (self.viewControllers?.count)! > 0 { return self.viewControllers![0] } return nil } }
bdbe542509681fe1e3cecbdaa3d6ee5e
35.171429
149
0.64218
false
false
false
false
wftllc/hahastream
refs/heads/master
Haha Stream/HahaService/Models/ContentItem.swift
mit
1
import Foundation class ContentItem: NSObject, FromDictable { public var game: Game? public var channel: Channel? static func fromDictionary(_ dict:[String: Any]?) throws -> Self { guard let dict = dict else { throw FromDictableError.keyError(key: "\(self).<root>") } let kind: String = try dict.value("kind") if kind == "channel" { return self.init(channel: try Channel.fromDictionary(dict)) } else if kind == "game" { return self.init(game: try Game.fromDictionary(dict)) } else { throw FromDictableError.keyError(key: "kind unrecognized \(kind)") } } required init(game: Game? = nil, channel: Channel? = nil) { self.game = game self.channel = channel } override var description: String { if let g = game { return g.description } else { return channel!.description } } override func isEqual(_ object: Any?) -> Bool { guard let item = object as? ContentItem else { return false } if self.game != nil { return item.game?.uuid == self.game?.uuid } else if self.channel != nil { return item.channel?.uuid == self.channel?.uuid } else { return false } } }
564918f63b476f7a5225b8d32a393353
22.346939
88
0.656469
false
false
false
false
SteveRohrlack/CitySimCore
refs/heads/master
src/Model/City/City.swift
mit
1
// // City.swift // CitySimCore // // Created by Steve Rohrlack on 24.05.16. // Copyright © 2016 Steve Rohrlack. All rights reserved. // import Foundation /// the simulation's main data container public class City: EventEmitting, ActorStageable { typealias EventNameType = CityEvent /// Container holding event subscribers var eventSubscribers: [EventNameType: [EventSubscribing]] = [:] /// CityMap, regards all layers of the map public var map: CityMap /// current population count public var population: Int { didSet { emitPopulationThresholdEvents(oldValue: oldValue) } } /// list of population thresholds that trigger events private var populationThresholds: [Int] = [] /// City budget public var budget: Budget /// City Ressources public var ressources: Ressources /** initializer - parameter map: CityMap - parameter budget: city budget - parameter population: city population - parameter populationThresholds: population thresholds that trigger events */ init(map: CityMap, budget: Budget, ressources: Ressources, population: Int, populationThresholds: [Int]) { self.map = map self.budget = budget self.ressources = ressources self.population = population self.populationThresholds = populationThresholds } /** convenience initializer - parameter map: CityMap - parameter startingBudget: starting budget - parameter populationThresholds: population thresholds that trigger events */ convenience init(map: CityMap, startingBudget: Int) { let budget = Budget(amount: startingBudget, runningCost: 0) let ressources = Ressources(electricityDemand: 0, electricitySupply: 0, electricityNeedsRecalculation: false) self.init(map: map, budget: budget, ressources: ressources, population: 0, populationThresholds: []) } /** convenience initializer - parameter map: CityMap - parameter startingBudget: starting budget */ convenience init(map: CityMap, startingBudget: Int, populationThresholds: [Int]) { let budget = Budget(amount: startingBudget, runningCost: 0) let ressources = Ressources(electricityDemand: 0, electricitySupply: 0, electricityNeedsRecalculation: false) self.init(map: map, budget: budget, ressources: ressources, population: 0, populationThresholds: populationThresholds) } /** determines if city population threshold event should be triggered - parameter oldValue: value before population-value was changed */ private func emitPopulationThresholdEvents(oldValue oldValue: Int) { for threshold in populationThresholds { if oldValue < threshold && population >= threshold { do { try emit(event: .PopulationReachedThreshold, payload: threshold) } catch {} } } } }
bc4b4438103cdd5a9a3330a7222e4ed3
31.104167
126
0.657903
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/IRGen/dynamic_self_metadata.swift
apache-2.0
1
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir -parse-as-library | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: Not a SIL test because we can't parse dynamic Self in SIL. // <rdar://problem/16931299> // CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }> @inline(never) func id<T>(_ t: T) -> T { return t } // CHECK-LABEL: define hidden swiftcc void @_TF21dynamic_self_metadata2idurFxx class C { class func fromMetatype() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_TZFC21dynamic_self_metadata1C12fromMetatypefT_GSqDS0__(%swift.type* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func fromInstance() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @_TFC21dynamic_self_metadata1C12fromInstancefT_GSqDS0__(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8 // CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: store i64 0, i64* [[CAST1]], align 8 // CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64* // CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8 // CHECK: ret i64 [[LOAD]] func dynamicSelfArgument() -> Self? { return id(nil) } // CHECK-LABEL: define hidden swiftcc i64 @_TFC21dynamic_self_metadata1C19dynamicSelfArgumentfT_GSqDS0__(%T21dynamic_self_metadata1CC* swiftself) // CHECK: [[CAST1:%.+]] = bitcast %T21dynamic_self_metadata1CC* %0 to [[METATYPE:%.+]] // CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]]) // CHECK: [[TYPE2:%.+]] = call %swift.type* @_TMaSq(%swift.type* [[TYPE1]]) // CHECK: call swiftcc void @_TF21dynamic_self_metadata2idurFxx({{.*}}, %swift.type* [[TYPE2]]) }
74cf741834a1992e1b485f87c9d7fd9b
46.97619
147
0.628288
false
false
false
false
fanyinan/ImagePickerProject
refs/heads/master
ImagePicker/Tool/Extension.swift
bsd-2-clause
1
// // MuColor.swift // ImagePickerProject // // Created by 范祎楠 on 15/4/9. // Copyright (c) 2015年 范祎楠. All rights reserved. // import UIKit extension UIColor { class var jx_main: UIColor { return UIColor(hex: 0x333333) } class var separatorColor: UIColor { return UIColor(hex: 0xe5e5e5) } convenience init(hex: Int, alpha: CGFloat = 1) { let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0x00FF00) >> 8) / 255.0 let blue = CGFloat((hex & 0x0000FF)) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } /** 随机颜色 - returns: 颜色 */ class func randomColor() -> UIColor{ let hue = CGFloat(arc4random() % 256) / 256.0 let saturation = CGFloat(arc4random() % 128) / 256.0 + 0.5 let brightness : CGFloat = CGFloat(arc4random() % 128) / 256.0 + 0.5 return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) } } extension UIImage { //旋转rect func transformOrientationRect(_ rect: CGRect) -> CGRect { var rectTransform: CGAffineTransform = CGAffineTransform.identity switch imageOrientation { case .left: rectTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)).translatedBy(x: 0, y: -size.height) case .right: rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: 0) case .down: rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: -size.height) default: break } let orientationRect = rect.applying(rectTransform.scaledBy(x: scale, y: scale)) return orientationRect } }
df54ea0719e9fc2b609a5751e955fd18
26.0625
125
0.646651
false
false
false
false
brentdax/swift
refs/heads/master
validation-test/Reflection/reflect_NSNumber.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_NSNumber // RUN: %target-codesign %t/reflect_NSNumber // RUN: %target-run %target-swift-reflection-test %t/reflect_NSNumber | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest import Foundation class TestClass { var t: NSNumber init(t: NSNumber) { self.t = t } } var obj = TestClass(t: 123) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_NSNumber.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0 // CHECK-64: (field name=t offset=16 // CHECK-64: (reference kind=strong refcounting=unknown))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_NSNumber.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 // CHECK-32: (field name=t offset=8 // CHECK-32: (reference kind=strong refcounting=unknown))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
4859ed99855c91643503d5dac31b071a
27.5625
122
0.69876
false
true
false
false
crossroadlabs/ExpressCommandLine
refs/heads/master
swift-express/Commands/Run/RunSPM.swift
gpl-3.0
1
//===--- RunSPM.swift ----------------------------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line 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. // //Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===---------------------------------------------------------------------------===// import Foundation import Result infix operator ++ {} func ++ <K,V> (left: Dictionary<K,V>, right: Dictionary<K,V>?) -> Dictionary<K,V> { guard let right = right else { return left } return left.reduce(right) { var new = $0 as [K:V] new.updateValue($1.1, forKey: $1.0) return new } } struct RunSPMStep : RunSubtaskStep { let dependsOn:[Step] = [] func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] { guard let path = params["path"] as? String else { throw SwiftExpressError.BadOptions(message: "RunSPM: No path option.") } guard let buildType = params["buildType"] as? BuildType else { throw SwiftExpressError.BadOptions(message: "RunSPM: No buildType option.") } print ("Running app...") let binaryPath = path.addPathComponent(".build").addPathComponent(buildType.spmValue).addPathComponent("app") try executeSubtaskAndWait(SubTask(task: binaryPath, arguments: nil, workingDirectory: path, environment: nil, useAppOutput: true)) return [String:Any]() } func cleanup(params: [String : Any], output: StepResponse) throws { } // func callParams(ownParams: [String : Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String : Any] { // return ownParams ++ ["force": false, "dispatch": DEFAULTS_BUILD_DISPATCH] // } }
ab58a59e3f08e8a36658380f9e50013a
38.435484
138
0.625205
false
false
false
false
vedantb/WatchkitMusic
refs/heads/master
PlayThatSong/ViewController.swift
mit
1
// // ViewController.swift // PlayThatSong // // Created by Vedant Bhatt on 1/29/15. // Copyright (c) 2015 Vedant. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var playButton: UIButton! @IBOutlet weak var currentSongLabel: UILabel! var audioSession: AVAudioSession! //var audioPlayer: AVAudioPlayer! var audioQueuePlayer: AVQueuePlayer! var currentSongIndex: Int! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureAudioSession() //self.configureAudioPlayer() self.configureAudioQueuePlayer() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleRequest:"), name: "WatchKitDidMakeRequest", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Mark - IBActions @IBAction func playButtonPressed(sender: UIButton) { self.playMusic() self.updateUI() } @IBAction func playPreviousButtonPressed(sender: UIButton) { if currentSongIndex > 0 { self.audioQueuePlayer.pause() self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) let temporaryNowPlayingIndex = currentSongIndex let temporaryPlaylist = self.createSongs() self.audioQueuePlayer.removeAllItems() for var index = temporaryNowPlayingIndex - 1; index < temporaryPlaylist.count; index++ { self.audioQueuePlayer.insertItem(temporaryPlaylist[index] as AVPlayerItem, afterItem: nil) } self.currentSongIndex = temporaryNowPlayingIndex - 1; self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) self.audioQueuePlayer.play() } self.updateUI() } @IBAction func playNextButtonPressed(sender: UIButton) { self.audioQueuePlayer.advanceToNextItem() self.currentSongIndex = self.currentSongIndex + 1 self.updateUI() } //Mark - Audio func configureAudioSession() { self.audioSession = AVAudioSession.sharedInstance() var categoryError:NSError? var activeError:NSError? self.audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) println("error \(categoryError)") var success = self.audioSession.setActive(true, error: &activeError) if !success { println("Error making audio session active \(activeError)") } } // func configureAudioPlayer() { // var songPath = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3") // var songURL = NSURL.fileURLWithPath(songPath!) // println("songURL: \(songURL)") // var songError: NSError? // self.audioPlayer = AVAudioPlayer(contentsOfURL: songURL, error: &songError) // println("song error: \(songError)") // self.audioPlayer.numberOfLoops = 0 // } func configureAudioQueuePlayer() { let songs = createSongs() self.audioQueuePlayer = AVQueuePlayer(items: songs) for var songIndex = 0; songIndex < songs.count; songIndex++ { NSNotificationCenter.defaultCenter().addObserver(self, selector: "songEnded:", name: AVPlayerItemDidPlayToEndTimeNotification, object: songs[songIndex]) } } func playMusic() { //was used to implement audio player. Later replaced with AudioQueuePlayer // self.audioPlayer.prepareToPlay() // self.audioPlayer.play() if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil { self.audioQueuePlayer.pause() } else if currentSongIndex == nil { self.audioQueuePlayer.play() self.currentSongIndex = 0 } else { self.audioQueuePlayer.play() } } func createSongs () -> [AnyObject] { let firstSongPath = NSBundle.mainBundle().pathForResource("CLASSICAL SOLITUDE", ofType: "wav") let secondSongPath = NSBundle.mainBundle().pathForResource("Timothy Pinkham - The Knolls of Doldesh", ofType: "mp3") let thirdSongPath = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3") let firstSongURL = NSURL.fileURLWithPath(firstSongPath!) let secondSongURL = NSURL.fileURLWithPath(secondSongPath!) let thirdSongURL = NSURL.fileURLWithPath(thirdSongPath!) let firstPlayItem = AVPlayerItem(URL: firstSongURL) let secondPlayItem = AVPlayerItem(URL: secondSongURL) let thirdPlayItem = AVPlayerItem(URL: thirdSongURL) let songs: [AnyObject] = [firstPlayItem, secondPlayItem, thirdPlayItem] return songs } //Mark: Audio Notification func songEnded (notification: NSNotification){ self.currentSongIndex = self.currentSongIndex + 1 self.updateUI() } //Mark: UI Update Helpers func updateUI () { self.currentSongLabel.text = currentSongName() if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil { self.playButton.setTitle("Pause", forState: UIControlState.Normal) } else { self.playButton.setTitle("Play", forState: UIControlState.Normal) } } func currentSongName () -> String { var currentSong: String if currentSongIndex == 0{ currentSong = "Classical Solitude" } else if currentSongIndex == 1 { currentSong = "The Knolls of Doldesh" } else if currentSongIndex == 2 { currentSong = "Sending my Signal" } else { currentSong = "No Song Playing" println("Someting went wrong!") } return currentSong } //Mark - WatchKit Notification func handleRequest(notification: NSNotification) { let watchKitInfo = notification.object! as? WatchKitInfo if watchKitInfo.playerRequest != nil { let requestedAction: String = watchKitInfo.playerRequest! self.playMusic() } } }
5f4385c047732fd1d767873cb4ca540e
33.533679
164
0.626707
false
false
false
false
ZwxWhite/V2EX
refs/heads/master
V2EX/V2EX/Class/Model/V2Reply.swift
mit
1
// // V2Replies.swift // V2EX // // Created by wenxuan.zhang on 16/2/24. // Copyright © 2016年 张文轩. All rights reserved. // import Foundation import SwiftyJSON class V2Reply { var id: Int? var thanks: Int? var content: String? var content_rendered: String? var member: V2Member? var created: Int? var last_modified: Int? init(json: JSON) { self.id = json["id"].int self.thanks = json["thanks"].int self.content = json["content"].string self.content_rendered = json["content_rendered"].string self.created = json["created"].int self.last_modified = json["last_modified"].int self.member = V2Member(json: json["member"]) } }
65419c86eee9abac4dd550a350b8ef2f
22.09375
63
0.603518
false
false
false
false
msn0w/bgsights
refs/heads/master
bgSights/ViewController.swift
mit
1
// // ViewController.swift // bgSights // // Created by Deyan Marinov on 1/8/16. // Copyright © 2016 Deyan Marinov. All rights reserved. // import UIKit class ViewController: UITableViewController, MenuTransitionManagerDelegate { let menuTransitionManager = MenuTransitionManager() var introModalDidDisplay = NSUserDefaults.standardUserDefaults().boolForKey("introModalDidDisplay") override func viewDidLoad() { super.viewDidLoad() if NSUserDefaults.standardUserDefaults().isFirstLaunch() { let walkVC = self.storyboard?.instantiateViewControllerWithIdentifier("walk0") as! WalkthroughVC walkVC.modalPresentationStyle = UIModalPresentationStyle.FormSheet self.presentViewController(walkVC, animated: true, completion: nil) } self.title = "Начало" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } // MARK: - Navigation @IBAction func unwindToHome(segue: UIStoryboardSegue) { let sourceController = segue.sourceViewController as! MenuTableViewController self.title = sourceController.currentItem } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let menuTableViewController = segue.destinationViewController as! MenuTableViewController menuTableViewController.currentItem = self.title! menuTableViewController.transitioningDelegate = menuTransitionManager menuTransitionManager.delegate = self } } extension NSUserDefaults { func isFirstLaunch() -> Bool { if !NSUserDefaults.standardUserDefaults().boolForKey("LaunchedOnce") { NSUserDefaults.standardUserDefaults().setBool(true, forKey: "LaunchedOnce") NSUserDefaults.standardUserDefaults().synchronize() return true } return false } }
4ade880d968f7a543a92b070d2819afc
33.081967
108
0.698268
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/partial_apply_generic.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s protocol Foo { static func staticFunc() func instanceFunc() } // CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc1{{[_0-9a-zA-Z]*}}F func getStaticFunc1<T: Foo>(t: T.Type) -> () -> () { // CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ // CHECK-NEXT: apply [[REF]]<T>(%0) return t.staticFunc // CHECK-NEXT: return } // CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ // CHECK: [[REF:%.*]] = witness_method $Self, #Foo.staticFunc!1 // CHECK-NEXT: partial_apply [[REF]]<Self>(%0) // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc2{{[_0-9a-zA-Z]*}}F func getStaticFunc2<T: Foo>(t: T) -> () -> () { // CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ // CHECK: apply [[REF]]<T> return T.staticFunc // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc1{{[_0-9a-zA-Z]*}}F func getInstanceFunc1<T: Foo>(t: T) -> () -> () { // CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] // CHECK-NEXT: apply [[REF]]<T> return t.instanceFunc // CHECK-NEXT: dealloc_stack // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: return } // CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F // CHECK: [[REF:%.*]] = witness_method $Self, #Foo.instanceFunc!1 // CHECK-NEXT: partial_apply [[REF]]<Self>(%0) // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc2{{[_0-9a-zA-Z]*}}F func getInstanceFunc2<T: Foo>(t: T) -> (T) -> () -> () { // CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: partial_apply [[REF]]<T>( return T.instanceFunc // CHECK-NEXT: destroy_addr %0 : $* // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc3{{[_0-9a-zA-Z]*}}F func getInstanceFunc3<T: Foo>(t: T.Type) -> (T) -> () -> () { // CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: partial_apply [[REF]]<T>( return t.instanceFunc // CHECK-NEXT: return }
a42683a26f82318a6450f637900f8a09
38.111111
101
0.655438
false
false
false
false
fulldecent/8-ball
refs/heads/master
8 Ball/SceneDelegate.swift
mit
1
// // SceneDelegate.swift // 8 Ball // // Created by William Entriken on 2020-01-01. // Copyright © 2020 William Entriken. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
c5b8bd02793a1832e2e318c538188c07
42.25
147
0.704118
false
false
false
false
i-schuetz/SwiftCharts
refs/heads/master
SwiftCharts/Views/ChartPointViewBar.swift
apache-2.0
1
// // ChartPointViewBar.swift // Examples // // Created by ischuetz on 14/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public struct ChartBarViewSettings { let animDuration: Float let animDelay: Float let selectionViewUpdater: ChartViewSelector? let cornerRadius: CGFloat let roundedCorners: UIRectCorner let delayInit: Bool public init(animDuration: Float = 0.5, animDelay: Float = 0, cornerRadius: CGFloat = 0, roundedCorners: UIRectCorner = .allCorners, selectionViewUpdater: ChartViewSelector? = nil, delayInit: Bool = false) { self.animDuration = animDuration self.animDelay = animDelay self.cornerRadius = cornerRadius self.roundedCorners = roundedCorners self.selectionViewUpdater = selectionViewUpdater self.delayInit = delayInit } public func copy(animDuration: Float? = nil, animDelay: Float? = nil, cornerRadius: CGFloat? = nil, roundedCorners: UIRectCorner? = nil, selectionViewUpdater: ChartViewSelector? = nil) -> ChartBarViewSettings { return ChartBarViewSettings( animDuration: animDuration ?? self.animDuration, animDelay: animDelay ?? self.animDelay, cornerRadius: cornerRadius ?? self.cornerRadius, roundedCorners: roundedCorners ?? self.roundedCorners, selectionViewUpdater: selectionViewUpdater ?? self.selectionViewUpdater ) } } open class ChartPointViewBar: UIView { let targetFrame: CGRect var isSelected: Bool = false var tapHandler: ((ChartPointViewBar) -> Void)? { didSet { if tapHandler != nil && gestureRecognizers?.isEmpty ?? true { enableTap() } } } public let isHorizontal: Bool public let settings: ChartBarViewSettings public required init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor?, settings: ChartBarViewSettings) { let targetFrame = ChartPointViewBar.frame(p1, p2: p2, width: width) let firstFrame: CGRect = { if p1.y - p2.y =~ 0 { // horizontal return CGRect(x: targetFrame.origin.x, y: targetFrame.origin.y, width: 0, height: targetFrame.size.height) } else { // vertical return CGRect(x: targetFrame.origin.x, y: targetFrame.origin.y, width: targetFrame.size.width, height: 0) } }() self.targetFrame = targetFrame self.settings = settings isHorizontal = p1.y == p2.y super.init(frame: firstFrame) backgroundColor = bgColor if settings.cornerRadius > 0 { layer.cornerRadius = settings.cornerRadius } } static func frame(_ p1: CGPoint, p2: CGPoint, width: CGFloat) -> CGRect { if p1.y - p2.y =~ 0 { // horizontal return CGRect(x: p1.x, y: p1.y - width / 2, width: p2.x - p1.x, height: width) } else { // vertical return CGRect(x: p1.x - width / 2, y: p1.y, width: width, height: p2.y - p1.y) } } func updateFrame(_ p1: CGPoint, p2: CGPoint) { frame = ChartPointViewBar.frame(p1, p2: p2, width: isHorizontal ? frame.height : frame.width) } func enableTap() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTap)) addGestureRecognizer(tapRecognizer) } @objc func onTap(_ sender: UITapGestureRecognizer) { toggleSelection() tapHandler?(self) } func toggleSelection() { isSelected = !isSelected settings.selectionViewUpdater?.displaySelected(self, selected: isSelected) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func didMoveToSuperview() { func targetState() { frame = targetFrame layoutIfNeeded() } if settings.animDuration =~ 0 { targetState() } else { UIView.animate(withDuration: CFTimeInterval(settings.animDuration), delay: CFTimeInterval(settings.animDelay), options: .curveEaseOut, animations: { targetState() }, completion: nil) } } }
65a0ce4129979755662d64635b54ba38
31.211268
160
0.5892
false
false
false
false
Vazzi/VJAutocomplete
refs/heads/master
VJAutocompleteSwiftDemo/VJAutocompleteSwiftDemo/VJAutocomplete.swift
mit
2
// // VJAutocomplete.m // // Created by Jakub Vlasák on 14/09/14. // Copyright (c) 2014 Jakub Vlasak ( http://vlasakjakub.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 /*! Protocol for manipulation with data */ protocol VJAutocompleteDataSource { /*! Set the text of cell with given data. Data can be any object not only string. Always return the parameter cell. Only set text. ([cell.textLabel setText:]) /param cell /param item Source data. Data can be any object not only string that is why you have to define the cell text. /return cell that has been given and modified */ func setCell(cell:UITableViewCell, withItem item:AnyObject) -> UITableViewCell /*! Define data that should by shown by autocomplete on substring. Can be any object. Not only NSString. /param substring /return array of objects for substring */ func getItemsArrayWithSubstring(substring:String) -> [AnyObject] } /*! Protocol for manipulation with VJAutocomplete */ protocol VJAutocompleteDelegate { /*! This is called when row was selected and autocomplete add text to text field. /param rowIndex Selected row number */ func autocompleteWasSelectedRow(rowIndex: Int) } /*! VJAutocomplete table for text field is pinned to the text field that must be given. User starts writing to the text field and VJAutocomplete show if has any suggestion. If there is no suggestion then hide. User can choose suggestion by clicking on it. If user choose any suggestion then it diseppeared and add text to text field. If user continues adding text then VJAutocomplete start showing another suggestions or diseppead if has no. */ class VJAutocomplete: UITableView, UITableViewDelegate, UITableViewDataSource { // ------------------------------------------------------------------------------- // MARK: - Public properties // ------------------------------------------------------------------------------- // Set by init var textField: UITextField! //!< Given text field. To this text field is autocomplete pinned to. var parentView: UIView? //!< Parent view of text field (Change only if the current view is not what you want) // Actions properties var doNotShow = false //!< Do not show autocomplete // Other properties var maxVisibleRowsCount:UInt = 2 //!< Maximum height of autocomplete based on max visible rows var cellHeight:CGFloat = 44.0 //!< Cell height var minCountOfCharsToShow:UInt = 3 //!< Minimum count of characters needed to show autocomplete var autocompleteDataSource:VJAutocompleteDataSource? //!< Manipulation with data var autocompleteDelegate:VJAutocompleteDelegate? //!< Manipulation with autocomplete // ------------------------------------------------------------------------------- // MARK: - Private properties // ------------------------------------------------------------------------------- private let cellIdentifier = "VJAutocompleteCellIdentifier" private var lastSubstring:String = "" //!< Last given substring private var autocompleteItemsArray = [AnyObject]() //!< Current suggestions private var autocompleteSearchQueue = dispatch_queue_create("VJAutocompleteQueue", DISPATCH_QUEUE_SERIAL); //!< Queue for searching suggestions private var isVisible = false //<! Is autocomplete visible // ------------------------------------------------------------------------------- // MARK: - Init methods // ------------------------------------------------------------------------------- init(textField: UITextField) { super.init(frame: textField.frame, style: UITableViewStyle.Plain); // Text field self.textField = textField; // Set parent view as text field super view self.parentView = textField.superview; // Setup table view setupTableView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } // ------------------------------------------------------------------------------- // MARK: - Setups // ------------------------------------------------------------------------------- private func setupTableView() { // Protocols dataSource = self; delegate = self; // Properties scrollEnabled = true; // Visual properties backgroundColor = UIColor.whiteColor(); rowHeight = cellHeight; // Empty footer tableFooterView = UIView(frame: CGRectZero); } // ------------------------------------------------------------------------------- // MARK: - Public methods // ------------------------------------------------------------------------------- func setBorder(width: CGFloat, cornerRadius: CGFloat, color: UIColor) { self.layer.borderWidth = width; self.layer.cornerRadius = cornerRadius; self.layer.borderColor = color.CGColor; } func searchAutocompleteEntries(WithSubstring substring: NSString) { let lastCount = autocompleteItemsArray.count; autocompleteItemsArray.removeAll(keepCapacity: false); // If substring has less than min. characters then hide and return if (UInt(substring.length) < minCountOfCharsToShow) { hideAutocomplete(); return; } let substringBefore = lastSubstring; lastSubstring = substring as String; // If substring is the same as before and before it has no suggestions then // do not search for suggestions if (substringBefore == substring.substringToIndex(substring.length - 1) && lastCount == 0 && !substringBefore.isEmpty) { return; } dispatch_async(autocompleteSearchQueue) { () // Save new suggestions if let dataArray = self.autocompleteDataSource?.getItemsArrayWithSubstring(substring as String) { self.autocompleteItemsArray = dataArray; } // Call show or hide autocomplete and reload data on main thread dispatch_async(dispatch_get_main_queue()) { () if (self.autocompleteItemsArray.count != 0) { self.showAutocomplete(); } else { self.hideAutocomplete(); } self.reloadData(); } } } func hideAutocomplete() { if (!isVisible) { return; } removeFromSuperview(); isVisible = false; } func showAutocomplete() { if (doNotShow) { return; } if (isVisible) { removeFromSuperview(); } self.isVisible = true; var origin = getTextViewOrigin(); setFrame(origin, height: computeHeight()); layer.zPosition = CGFloat(FLT_MAX); parentView?.addSubview(self); } func shouldChangeCharacters(InRange range: NSRange, replacementString string: String) { var substring = NSString(string: textField.text); substring = substring.stringByReplacingCharactersInRange(range, withString: string); searchAutocompleteEntries(WithSubstring: substring); } func isAutocompleteVisible() -> Bool { return isVisible; } // ------------------------------------------------------------------------------- // MARK: - UITableView data source // ------------------------------------------------------------------------------- func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return autocompleteItemsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell!; if let oldCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell { cell = oldCell; } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier); } var newCell = autocompleteDataSource?.setCell(cell, withItem: autocompleteItemsArray[indexPath.row]) return cell } // ------------------------------------------------------------------------------- // MARK: - UITableView delegate // ------------------------------------------------------------------------------- func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Get the cell let selectedCell = tableView.cellForRowAtIndexPath(indexPath) // Set text to textField.text = selectedCell?.textLabel!.text // Call delegate method autocompleteDelegate?.autocompleteWasSelectedRow(indexPath.row) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return cellHeight } // ------------------------------------------------------------------------------- // MARK: - Private // ------------------------------------------------------------------------------- private func computeHeight() -> CGFloat { // Set number of cells (do not show more than maxSuggestions) var visibleRowsCount = autocompleteItemsArray.count as NSInteger; if (visibleRowsCount > NSInteger(maxVisibleRowsCount)) { visibleRowsCount = NSInteger(maxVisibleRowsCount); } // Calculate autocomplete height let height = cellHeight * CGFloat(visibleRowsCount); return height; } private func getTextViewOrigin() -> CGPoint { var textViewOrigin: CGPoint; if (parentView?.isEqual(textField.superview) != nil) { textViewOrigin = textField.frame.origin; } else { textViewOrigin = textField.convertPoint(textField.frame.origin, toView: parentView); } return textViewOrigin; } private func setFrame(textViewOrigin: CGPoint, height: CGFloat) { var newFrame = CGRectMake(textViewOrigin.x, textViewOrigin.y + CGRectGetHeight(textField.bounds), CGRectGetWidth(textField.bounds), height); frame = newFrame; } }
2482806afa067449cfe79a8105c746c6
37.220395
123
0.577933
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/BeeFun/View/BaseViewController/BFBaseViewController.swift
mit
1
// // BFBaseViewController.swift // BeeFun // // Created by wenghengcong on 15/12/30. // Copyright © 2015年 JungleSong. All rights reserved. // import UIKit import MJRefresh protocol BFViewControllerNetworkProtocol: class { func networkSuccssful() func networkFailure() } class BFBaseViewController: UIViewController, UIGestureRecognizerDelegate { typealias PlaceHolderAction = ((Bool) -> Void) // MARK: - 视图 var topOffset: CGFloat = uiTopBarHeight /// 是否需要登录态 var needLogin = true // MARK: - 各种占位图:网络 > 未登录 > 无数据 //Reload View var needShowReloadView = true var placeReloadView: BFPlaceHolderView? var reloadTip = "Wake up your connection!".localized { didSet { } } var reloadImage = "network_error_1" { didSet { } } var reloadActionTitle = "Try Again".localized { didSet { } } var reloadViewClosure: PlaceHolderAction? //Empty View var needShowEmptyView = true var placeEmptyView: BFPlaceHolderView? var emptyTip = "Empty now".localized { didSet { } } var emptyImage = "empty_data" { didSet { } } var emptyActionTitle = "Go".localized { didSet { } } var emptyViewClosure: PlaceHolderAction? //Login View var needShowLoginView = true var placeLoginView: BFPlaceHolderView? var loginTip = "Please login first".localized { didSet { } } var loginImage = "github_signin_logo" { didSet { } } var loginActionTitle = "Sign in".localized { didSet { } } var loginViewClosure: PlaceHolderAction? // MARK: - 刷新控件 var refreshHidden: RefreshHidderType = .all { didSet { setRefreshHiddenOrShow() } } var refreshManager = MJRefreshManager() var header: MJRefreshNormalHeader! var footer: MJRefreshAutoNormalFooter! lazy var tableView: UITableView = { return self.getBaseTableView() }() // MARK: - 导航栏左右按钮 var leftItem: UIButton? { didSet { if let left = leftItem { setLeftBarItem(left) } } } var rightItem: UIButton? { didSet { if let right = rightItem { setRightBarItem(right) } } } var leftItemImage: UIImage? { didSet { leftItem!.setImage(leftItemImage, for: .normal) layoutLeftItem() } } var leftItemSelImage: UIImage? { didSet { leftItem!.setImage(leftItemSelImage, for: .selected) layoutLeftItem() } } var rightItemImage: UIImage? { didSet { rightItem!.setImage(rightItemImage, for: .normal) layoutRightItem() } } var rightItemSelImage: UIImage? { didSet { rightItem!.setImage(rightItemSelImage, for: .selected) layoutRightItem() } } // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() customView() gatherUserActivityInViewDidload() registerNoti() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) gatherUserActivityInViewWillAppear() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) gatherUserActivityInViewWillDisAppear() } }
4f85879a414a14d686b81167698266ce
20.755952
75
0.563338
false
false
false
false
cocoaheadsru/server
refs/heads/develop
Sources/App/Models/Speaker/Speaker.swift
mit
1
import Vapor import FluentProvider // sourcery: AutoModelGeneratable // sourcery: Preparation final class Speaker: Model { let storage = Storage() var userId: Identifier var speechId: Identifier init(userId: Identifier, speechId: Identifier) { self.userId = userId self.speechId = speechId } // sourcery:inline:auto:Speaker.AutoModelGeneratable init(row: Row) throws { userId = try row.get(Keys.userId) speechId = try row.get(Keys.speechId) } func makeRow() throws -> Row { var row = Row() try row.set(Keys.userId, userId) try row.set(Keys.speechId, speechId) return row } // sourcery:end } extension Speaker { func user() throws -> User? { return try parent(id: userId).get() } func speech() throws -> Speech? { return try parent(id: speechId).get() } } /// Custom implementation because of this exceptional case extension Speaker: JSONRepresentable { func makeJSON() throws -> JSON { guard let userJSON = try user()?.makeJSON(), let userId = userJSON[Keys.id]?.int else { throw Abort(.internalServerError, reason: "Speaker doesn't have associated User") } var json = JSON(json: userJSON) json.removeKey(Session.Keys.token) json.removeKey(Keys.id) try json.set(Keys.userId, userId) return json } }
f2ccbef313b4c74495b7785cedabb30e
21.466667
87
0.664688
false
false
false
false
gewill/Feeyue
refs/heads/develop
Feeyue/Main/Lists/Lists/ListModel.swift
mit
1
// // ListModel.swift // Feeyue // // Created by Will on 2018/7/15. // Copyright © 2018 Will. All rights reserved. // import Foundation import RealmSwift import IGListKit import SwiftyJSON import Moya_SwiftyJSONMapper @objcMembers class TwitterList: BaseModel, ALSwiftyJSONAble { enum Property: String { case idStr, name, uri, memberCount, subscriberCount, mode, des, slug, fullName, createdAt, following, user } dynamic var idStr: String = "-1" dynamic var name: String = "" dynamic var uri: String = "" dynamic var subscriberCount: Int = 0 dynamic var memberCount: Int = 0 dynamic var _mode: String = "priavate" dynamic var des: String = "" dynamic var slug: String = "" dynamic var fullName: String = "" dynamic var createdAt: Date = Date.distantPast dynamic var following: Bool = false dynamic var user: TwitterUser? enum Mode: String { case `private`, `public` } var mode: Mode { get { return Mode(rawValue: _mode) ?? Mode.private } set { _mode = mode.rawValue } } override class func primaryKey() -> String? { return Property.idStr.rawValue } // MARK: - Object Mapper convenience required init(jsonData json: JSON) { self.init() self.idStr = json["id_str"].string ?? UUID().uuidString self.name = json["name"].stringValue self.uri = json["uri"].stringValue self.subscriberCount = json["subscriber_count"].intValue self.memberCount = json["member_count"].intValue self._mode = json["mode"].stringValue self.des = json["description"].stringValue self.slug = json["slug"].stringValue self.fullName = json["full_name"].stringValue self.createdAt = DateHelper.convert(json["created_at"]) self.following = json["following"].boolValue if json["user"] != JSON.null { self.user = TwitterUser(jsonData: json["user"]) } } }
09b252470a8341248a85d22d46515c48
30.222222
114
0.641586
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/UI/PXCard/DefaultCards/TemplateCard.swift
mit
1
import Foundation import MLCardDrawer // TemplateCard class TemplateCard: NSObject, CardUI { var placeholderName = "" var placeholderExpiration = "" var bankImage: UIImage? var cardPattern = [4, 4, 4, 4] var cardFontColor: UIColor = .white var cardLogoImage: UIImage? var cardBackgroundColor: UIColor = UIColor(red: 0.23, green: 0.31, blue: 0.39, alpha: 1.0) var securityCodeLocation: MLCardSecurityCodeLocation = .back var defaultUI = true var securityCodePattern = 3 var fontType: String = "light" var cardLogoImageUrl: String? var bankImageUrl: String? } class TemplatePIX: NSObject, GenericCardUI { var titleName = "" var titleWeight = "" var titleTextColor = "" var subtitleName = "" var subtitleWeight = "" var subtitleTextColor = "" var labelName = "" var labelTextColor = "" var labelBackgroundColor = "" var labelWeight = "" var cardBackgroundColor = UIColor.white var logoImageURL = "" var securityCodeLocation = MLCardSecurityCodeLocation.none var placeholderName = "" var placeholderExpiration = "" var cardPattern = [4, 4, 4, 4] var cardFontColor: UIColor = .white var defaultUI = true var securityCodePattern = 3 var gradientColors = [""] } class TemplateDebin: NSObject, GenericCardUI { var gradientColors: [String] = [""] var descriptionName = "" var descriptionTextColor = "" var descriptionWeight = "" var bla: String = "" var labelName: String = "" var labelTextColor: String = "" var labelBackgroundColor: String = "" var labelWeight: String = "" var titleName: String = "" var titleTextColor: String = "" var titleWeight: String = "" var subtitleName: String = "" var subtitleTextColor: String = "" var subtitleWeight: String = "" var logoImageURL: String = "" var cardPattern: [Int] = [] var cardBackgroundColor: UIColor = .red var securityCodeLocation: MLCardSecurityCodeLocation = .none var placeholderName: String = "" var placeholderExpiration: String = "" var cardFontColor: UIColor = .white var defaultUI: Bool = true var securityCodePattern: Int = 0 // averiguar }
7d2357bca105faf6efa4fadeb603ca02
31.405797
94
0.666816
false
false
false
false
fakerabbit/LucasBot
refs/heads/master
AutoBot/PopOver.swift
gpl-3.0
2
// // PopOverView.swift // LucasBot // // Created by Mirko Justiniano on 2/20/17. // Copyright © 2017 LB. All rights reserved. // import Foundation import UIKit class PopOver: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { typealias PopOverOnCell = (MenuButton?) -> Void var onCell: PopOverOnCell = { button in } var parentRect: CGRect = CGRect.zero lazy var loading: UIActivityIndicatorView! = { let load = UIActivityIndicatorView(activityIndicatorStyle: .gray) load.hidesWhenStopped = true load.startAnimating() return load }() private let backgroundImg: UIImageView! = { let view = UIImageView(image: UIImage(named: Utils.kPopBg)) view.contentMode = .scaleToFill return view }() lazy var collectionView: UICollectionView! = { let frame = self.frame let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 1 let cv: UICollectionView = UICollectionView(frame: frame, collectionViewLayout: layout) cv.backgroundColor = UIColor.clear cv.alwaysBounceVertical = true cv.showsVerticalScrollIndicator = false cv.dataSource = self cv.delegate = self cv.register(PopCell.classForCoder(), forCellWithReuseIdentifier: "PopCell") return cv }() var menuItems: [MenuButton?] = [] // MARK:- Init override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear ///self.layer.cornerRadius = 6.0; //self.layer.masksToBounds = false; //self.clipsToBounds = true self.addSubview(backgroundImg) self.addSubview(collectionView) self.addSubview(loading) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Layout override func layoutSubviews() { super.layoutSubviews() let w = self.frame.size.width let h = self.frame.size.height backgroundImg.frame = CGRect(x: 0, y: 0, width: w, height: h) collectionView.frame = CGRect(x: 0, y: 10, width: w - 10, height: h - 30) loading.frame = CGRect(x: w/2 - loading.frame.size.width/2, y: h/2 - loading.frame.size.height/2, width: loading.frame.size.width, height: loading.frame.size.height) } // MARK:- Data Provider func fetchMenu() { NetworkMgr.sharedInstance.fetchMenu() { [weak self] buttons in self?.menuItems = buttons DispatchQueue.main.async { self?.growAnimation() } } } /* * MARK:- CollectionView Datasource & Delegate */ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return menuItems.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let button = self.menuItems[indexPath.row] let cell:PopCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PopCell", for: indexPath) as! PopCell cell.title = button?.title cell.imgUrl = button?.imgUrl return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = CGSize(width: collectionView.frame.size.width - 20, height: CGFloat((Utils.menuItemHeight as NSString).floatValue)) return size } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let button = self.menuItems[indexPath.row] self.onCell(button) } // MARK:- Animations func growAnimation() { self.isHidden = true let h:CGFloat = UIScreen.main.bounds.size.height/3 + 10 self.frame = CGRect(x: self.frame.origin.x, y: self.parentRect.minY - (h - 10), width: UIScreen.main.bounds.size.width - 20, height: h) UIView.animate(withDuration: 2, animations: { self.isHidden = false }, completion: { [weak self] finished in self?.loading.stopAnimating() self?.layoutIfNeeded() self?.collectionView.reloadData() }) } }
9747a15a0aaf9c06a15cdafde20e771a
32.846715
173
0.633815
false
false
false
false
Kushki/kushki-ios
refs/heads/master
Example/kushki-ios/CardTokenView.swift
mit
1
import SwiftUI import Kushki struct CardTokenView: View { @State var name: String = "" @State var cardNumber: String = "" @State var cvv: String = "" @State var expiryMonth: String = "" @State var expiryYear: String = "" @State var totalAmount: String = "" @State var currency: String = "USD" @State var showResponse: Bool = false @State var responseMsg: String = "" @State var isSubscription: Bool = false @State var merchantId: String = "" @State var loading: Bool = false let currencies = ["CRC", "USD", "GTQ", "HNL", "NIO"] func getCard() -> Card { return Card(name: self.name,number: self.cardNumber, cvv: self.cvv,expiryMonth: self.expiryMonth,expiryYear: self.expiryYear) } func requestToken() { self.loading.toggle() let card = getCard(); let totalAmount = Double(self.totalAmount) ?? 0.0 let kushki = Kushki(publicMerchantId: self.merchantId, currency: self.currency, environment: KushkiEnvironment.testing_qa) if(self.isSubscription){ kushki.requestSubscriptionToken(card: card, isTest: true){ transaction in self.responseMsg = transaction.isSuccessful() ? transaction.token : transaction.code + ": " + transaction.message self.showResponse = true self.loading.toggle() } } else{ kushki.requestToken(card: card, totalAmount: totalAmount, isTest: true){ transaction in self.responseMsg = transaction.isSuccessful() ? transaction.token : transaction.code + ": " + transaction.message self.showResponse = true self.loading.toggle() } } } var body: some View { NavigationView { Form { Section(header: Text("MerchantId")){ TextField("merchantId", text: $merchantId) } Section(header: Text("data")){ TextField("Name", text: $name) TextField("Card Number", text: $cardNumber) TextField("CVV", text: $cvv) HStack{ TextField("Expiry Month", text: $expiryMonth) TextField("Expiry Year", text: $expiryYear) } TextField("Total amount", text: $totalAmount) Picker("Currency", selection: $currency){ ForEach(currencies, id: \.self){ Text($0) } } } Section(header:Text("Subscrition")){ Toggle(isOn: $isSubscription ){ Text("Subscription") } } Section { Button(action: {self.requestToken()}, label: { Text("Request token") }).alert(isPresented: $showResponse) { Alert(title: Text("Token Response"), message: Text(self.responseMsg), dismissButton: .default(Text("Got it!"))) } } }.navigationBarTitle("Card Token").disabled(self.loading) } } } struct CardTokenView_Previews: PreviewProvider { static var previews: some View { CardTokenView() } }
951244ebb335e7722ebe5916c390f532
34.88
135
0.498606
false
false
false
false
xdkoooo/LiveDemo
refs/heads/master
LiveDemo/LiveDemo/Classes/Home/Controller/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // LiveDemo // // Created by BillBear on 2017/1/25. // Copyright © 2017年 xdkoo. All rights reserved. // import UIKit fileprivate let kItemMargin : CGFloat = 10 fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2 fileprivate let kNormalItemH = kItemW * 3 / 4 fileprivate let kPrettyItemH = kItemW * 4 / 3 fileprivate let kHeaderViewH : CGFloat = 50 fileprivate let kCycleViewH = kScreenW * 3 / 8 fileprivate let kNormalCellID = "kNormalCellID" fileprivate let kPrettyCellID = "kPrettyCellID" fileprivate let kHeaderViewID = "kHeaderViewID" class RecommendViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) // MARK:- 配合minimumLineSpacing使用 layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) // MARK:- 控制collectionView 随父控件伸缩 collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self // collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionViewNormalCell",bundle:nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell",bundle:nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView",bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -kCycleViewH, width: kScreenW, height: kCycleViewH) return cycleView }() override func viewDidLoad() { super.viewDidLoad() // 1.设置UI界面 setupUI() // 发送网络请求 loadData() } } // MARK:- 设置UI界面内容 extension RecommendViewController { fileprivate func setupUI() { // 1.添加collection view.addSubview(collectionView) // 2.将cycleView添加到UICollectionView中 collectionView.addSubview(cycleView) // 3.设置collectionView的内边距 collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH, 0, 0, 0) } } // MARK:- 请求数据 extension RecommendViewController { fileprivate func loadData() { // 1.请求推荐数据 recommendVM.requestData { self.collectionView.reloadData() } // 2.请求轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModels = self.recommendVM.cycleModels } } } // MARK:- UICollectionViewDataSource extension RecommendViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return recommendVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendVM.anchorGroups[section] return group.anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.定义cell // var cell : UICollectionViewCell! let group = recommendVM.anchorGroups[indexPath.section] let anchor = group.anchors[indexPath.item] // 2.定义cell var cell : CollectionViewBaseCell! // 3.取出cell if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell } // 4.将模型赋值给Cell cell.anchor = anchor return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出section的headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.取出模型 headerView.group = recommendVM.anchorGroups[indexPath.section] return headerView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } }
d82b97db372c282b2ec4c5779fb116d9
35.148387
195
0.686596
false
false
false
false
lanit-tercom-school/grouplock
refs/heads/master
GroupLockiOS/GroupLockTests/UIViewControllerTests.swift
apache-2.0
1
// // UIViewControllerTests.swift // GroupLock // // Created by Sergej Jaskiewicz on 27.05.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // import XCTest @testable import GroupLock class UIViewControllerTests: XCTestCase { var window: UIWindow! var sut: UIViewController! override func setUp() { super.setUp() window = UIWindow() sut = UIViewController() // Load the view _ = sut.view // Add the main view to the view hierarchy window.addSubview(sut.view) RunLoop.current.run(until: Date()) } override func tearDown() { sut = nil window = nil super.tearDown() } func testHideKeyboardWhenTappedAround() { sut.hideKeyboardWhenTappedAround() XCTAssertEqual(sut.view.gestureRecognizers?.count, 1, "View should be able to recognize gestures") let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 10)) sut.view.addSubview(textField) textField.becomeFirstResponder() sut.dismissKeyboard() XCTAssertFalse(textField.isFirstResponder, "Text field should lose keyboard focus") } }
cc503a9603d6516e5a4f0a0b9b4d95dd
23.08
106
0.645349
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewModel/RegisterDomainDetailsViewModel+RowList.swift
gpl-2.0
1
import Foundation // MARK: - Row list extension RegisterDomainDetailsViewModel { enum RowType: Equatable { case checkMark(Row.CheckMarkRow) case inlineEditable(Row.EditableKeyValueRow) case addAddressLine(title: String?) var editableRow: Row.EditableKeyValueRow? { switch self { case .inlineEditable(let row): return row default: return nil } } } static var privacyProtectionRows: [RowType] { return [ .checkMark(.init( isSelected: true, title: Localized.PrivacySection.registerPrivatelyRowText )), .checkMark(.init( isSelected: false, title: Localized.PrivacySection.registerPubliclyRowText )) ] } static var nonEmptyRule: ValidationRule { return ValidationRule(context: .clientSide, validationBlock: ValidationBlock.nonEmpty, errorMessage: nil) } static var emailRule: ValidationRule { return ValidationRule(context: .clientSide, validationBlock: ValidationBlock.validEmail, errorMessage: "not email") } static func serverSideRule(with key: String, hasErrorMessage: Bool = true) -> ValidationRule { let errorMessage: String? if !hasErrorMessage { errorMessage = nil } else { switch key { case Localized.ContactInformation.firstName: errorMessage = Localized.validationErrorFirstName case Localized.ContactInformation.lastName: errorMessage = Localized.validationErrorLastName case Localized.ContactInformation.email: errorMessage = Localized.validationErrorEmail case Localized.ContactInformation.country: errorMessage = Localized.validationErrorCountry case Localized.ContactInformation.phone: errorMessage = Localized.validationErrorPhone case Localized.Address.addressLine: errorMessage = Localized.validationErrorAddress case Localized.Address.city: errorMessage = Localized.validationErrorCity case Localized.Address.state: errorMessage = Localized.validationErrorState case Localized.Address.postalCode: errorMessage = Localized.validationErrorPostalCode default: errorMessage = nil } } return ValidationRule(context: .serverSide, validationBlock: nil, //validation is handled on serverside errorMessage: errorMessage) } static func transformToLatinASCII(value: String?) -> String? { let toLatinASCII = StringTransform(rawValue: "Latin-ASCII") // See http://userguide.icu-project.org/transforms/general for more options. return value?.applyingTransform(toLatinASCII, reverse: false) } // MARK: - Rows static var contactInformationRows: [RowType] { return [ .inlineEditable(.init( key: Localized.ContactInformation.firstName, jsonKey: "first_name", value: nil, placeholder: Localized.ContactInformation.firstName, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.ContactInformation.firstName)], valueSanitizer: transformToLatinASCII )), .inlineEditable(.init( key: Localized.ContactInformation.lastName, jsonKey: "last_name", value: nil, placeholder: Localized.ContactInformation.lastName, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.ContactInformation.lastName)], valueSanitizer: transformToLatinASCII )), .inlineEditable(.init( key: Localized.ContactInformation.organization, jsonKey: "organization", value: nil, placeholder: Localized.ContactInformation.organizationPlaceholder, editingStyle: .inline, valueSanitizer: transformToLatinASCII )), .inlineEditable(.init( key: Localized.ContactInformation.email, jsonKey: "email", value: nil, placeholder: Localized.ContactInformation.email, editingStyle: .inline, validationRules: [emailRule, nonEmptyRule, serverSideRule(with: Localized.ContactInformation.email)] )), .inlineEditable(.init( key: Localized.ContactInformation.country, jsonKey: "country_code", value: nil, placeholder: Localized.ContactInformation.countryPlaceholder, editingStyle: .multipleChoice, validationRules: [nonEmptyRule, serverSideRule(with: Localized.ContactInformation.country)] ))] } static var phoneNumberRows: [RowType] { return [ .inlineEditable(.init( key: Localized.PhoneNumber.countryCode, jsonKey: "phone", value: nil, placeholder: Localized.PhoneNumber.countryCodePlaceholder, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.ContactInformation.phone, hasErrorMessage: false)] )), .inlineEditable(.init( key: Localized.PhoneNumber.number, jsonKey: "phone", value: nil, placeholder: Localized.PhoneNumber.numberPlaceholder, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.ContactInformation.phone)] )) ] } static func addressLine(row: Int, optional: Bool = true) -> RowType { let key = String(format: Localized.Address.addressLine, "\(row + 1)") return .inlineEditable(.init( key: key, jsonKey: String(format: "address_%@", "\(row + 1)"), value: nil, placeholder: Localized.Address.addressPlaceholder, editingStyle: .inline, validationRules: optional ? [serverSideRule(with: Localized.Address.addressLine)] : [nonEmptyRule, serverSideRule(with: Localized.Address.addressLine)], valueSanitizer: transformToLatinASCII )) } static var addressRows: [RowType] { return [ addressLine(row: 0, optional: false), .inlineEditable(.init( key: Localized.Address.city, jsonKey: "city", value: nil, placeholder: Localized.Address.city, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.Address.city)], valueSanitizer: transformToLatinASCII )), .inlineEditable(.init( key: Localized.Address.state, jsonKey: "state", value: nil, placeholder: Localized.Address.statePlaceHolder, editingStyle: .multipleChoice, validationRules: [serverSideRule(with: Localized.Address.state)], valueSanitizer: transformToLatinASCII )), .inlineEditable(.init( key: Localized.Address.postalCode, jsonKey: "postal_code", value: nil, placeholder: Localized.Address.postalCode, editingStyle: .inline, validationRules: [nonEmptyRule, serverSideRule(with: Localized.Address.postalCode)], valueSanitizer: transformToLatinASCII )) ] } }
487b0cb647459a6caf26ef1c5bfd3031
39.725962
164
0.558494
false
false
false
false
GJJDD/gjjinSwift
refs/heads/master
gjjinswift/gjjinswift/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // gjjinswift // // Created by apple on 16/6/28. // Copyright © 2016年 QiaTu HangZhou. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate,UITabBarControllerDelegate { var window: UIWindow? lazy var takePhotoViewController:GJJTakePhotoViewController = { GJJTakePhotoViewController() }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow.init(frame: UIScreen.main().bounds) if false { // 直接进入主页 let inTabBarController: UITabBarController = GJJTabBarConfig().setuptabBarController() inTabBarController.delegate = self; self.window?.rootViewController = inTabBarController } else { // 开启广告页面 self.window?.rootViewController = GJJLaunchAdViewController() } self.window?.makeKeyAndVisible() return true } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { if viewController.classForCoder.isSubclass(of: GJJTakePhotoTabbarViewController.classForCoder()) { debugPrint("点我了") viewController.present(takePhotoViewController, animated: true, completion: { }) return false } return true } }
f2dfa7a461daf25c0992413c38cba153
24.967213
129
0.624369
false
false
false
false
Sutto/Dollar.swift
refs/heads/master
Cent/Cent/Date.swift
mit
16
// // Date.swift // Cent // // Created by Ankur Patel on 6/30/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation extension NSDate { /// Returns a new Date given the year month and day /// /// :param year /// :param month /// :param day /// :return Date public class func from(#year: Int, month: Int, day: Int) -> NSDate? { var c = NSDateComponents() c.year = year c.month = month c.day = day if let gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian) { return gregorian.dateFromComponents(c) } else { return .None } } /// Returns a new Date given the unix timestamp /// /// :param unix timestamp /// :return Date public class func from(#unix: Double) -> NSDate { return NSDate(timeIntervalSince1970: unix) } /// Parses the date based on the format and return a new Date /// /// :param dateStr String version of the date /// :param format By default it is year month day /// :return Date public class func parse(dateStr: String, format: String = "yyyy-MM-dd") -> NSDate { var dateFmt = NSDateFormatter() dateFmt.timeZone = NSTimeZone.defaultTimeZone() dateFmt.dateFormat = format return dateFmt.dateFromString(dateStr)! } /// Returns the unix timestamp of the date passed in or /// the current unix timestamp /// /// :param date /// :return Double public class func unix(_ date: NSDate = NSDate()) -> Double { return date.timeIntervalSince1970 as Double } } public typealias Date = NSDate
12ea0e70b1b8531ea330c6fc604b44c8
26.532258
87
0.603398
false
false
false
false
mono0926/MonoGenerator
refs/heads/master
Sources/Generator.swift
mit
1
// // Generator.swift // MonoGenerator // // Created by mono on 2016/11/16. // // import Foundation class Generator { let value: String init(value: String) { self.value = value } func generate(suffix: String = "( ´・‿・`)", maxLength: Int? = nil) -> String { let r = value + suffix guard let maxLength = maxLength else { return r } // こうも書けるけどprefixの方がベター // return r[r.startIndex..<r.index(r.startIndex, offsetBy: min(maxLength, r.characters.count))] return String(r.characters.prefix(maxLength)) } }
1ca2cbbe7700e2ddfc7c1420f7b6244e
21.807692
102
0.588533
false
false
false
false
appfoundry/DRYLogging
refs/heads/master
Pod/Classes/BackupRoller.swift
mit
1
// // BackupRoller.swift // Pods // // Created by Michael Seghers on 29/10/2016. // // import Foundation /// File roller which moves log files, augmenting their index and limiting them to the maximumNumberOfFiles. /// The naming of the file follows the format [fileName][index].[extension] bassed on the file being rolled. /// /// The following list shows an example of how rolling happens for a file named "default.log" and a maximum of 4 files /// /// * 1st roll /// - default.log becomes default1.log /// * 2nd roll /// - default1.log becomes default2.log /// - default.log becomes default1.log /// * 3rd roll /// - default2.log becomes default3.log /// - default1.log becomes default2.log /// - default.log becomes default1.log /// * 4th roll /// - default3.log is deleted /// - default2.log becomes default3.log /// - default1.log becomes default2.log /// - default.log becomes default1.log /// /// - since: 3.0 public struct BackupRoller : LoggingRoller { /// The number of files that should be kept before starting to delete te oldest ones. public let maximumNumberOfFiles: UInt /// Designated initializer, initializing a backup roller with the given maximumNumberOfFiles. The default is a maximum of 5 files. /// /// - parameter maximumNumberOfFiles: the maximum number of files that will be used to roll over public init(maximumNumberOfFiles: UInt = 5) { self.maximumNumberOfFiles = maximumNumberOfFiles } public func rollFile(atPath path: String) { objc_sync_enter(self) let fileName = path.lastPathComponent.stringByDeletingPathExtension let ext = path.pathExtension let directory = path.stringByDeletingLastPathComponent let operation = BackupRollerOperation(fileName: fileName, ext: ext, directory: directory, lastIndex: self.maximumNumberOfFiles - 1) operation.performRolling() objc_sync_exit(self) } } /// Private helper class to perform the actual rolling private struct BackupRollerOperation { let fileName: String let ext: String let directory: String let lastIndex: UInt let fileManager: FileManager = FileManager.default func performRolling() { self.deleteLastFileIfNeeded() for index in stride(from: Int(lastIndex), to: -1, by: -1) { self.moveFileToNextIndex(from: index) } } private func deleteLastFileIfNeeded() { let lastFile = self.file(at: Int(self.lastIndex)) if self.fileManager.fileExists(atPath: lastFile) { do { try self.fileManager.removeItem(atPath: lastFile) } catch { print("Unable to delete last file: \(error)") } } } private func moveFileToNextIndex(from index: Int) { let potentialExistingRolledFile = self.file(at: index) if self.fileManager.fileExists(atPath: potentialExistingRolledFile) { let newPath = self.file(at: index + 1) self.moveFile(fromPath: potentialExistingRolledFile, toPath: newPath) } } private func moveFile(fromPath: String, toPath: String) { do { try self.fileManager.moveItem(atPath: fromPath, toPath: toPath) } catch { print("Couldn't move file from \(fromPath) to \(toPath): \(error)") } } private func file(at index: Int) -> String { return self.directory.stringByAppendingPathComponent(path: "\(self.fileName)\(index <= 0 ? "" : String(index)).\(self.ext)") } }
661a1f58c6841f9c362b6afbfa358f99
33.695238
139
0.648092
false
false
false
false
jianghongbing/APIReferenceDemo
refs/heads/master
UIKit/UIProgressView/UIProgressView/ViewController.swift
mit
1
// // ViewController.swift // UIProgressView // // Created by jianghongbing on 2017/6/1. // Copyright © 2017年 jianghongbing. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var barProgressView: UIProgressView! @IBOutlet weak var defaultProgressView: UIProgressView! @IBOutlet weak var progressView: UIProgressView! let progress = Progress(totalUnitCount: 10) override func viewDidLoad() { super.viewDidLoad() setupProgressView() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() print(barProgressView.frame, defaultProgressView.frame) // barProgressView.subviews.forEach { // print($0.frame) // } // defaultProgressView.subviews.forEach { // print($0.frame) // } } private func setupProgressView() { //1.设置已经加载的进度的颜色 barProgressView.progressTintColor = UIColor.red //2.设置没有被进度填充部分的颜色 barProgressView.trackTintColor = UIColor.blue //3.设置progress view的进度,默认为0.5 // barProgressView.setProgress(0.0, animated: false) barProgressView.progress = 0.0 //设置进度条的图片和非填充区域的图片 defaultProgressView.progressImage = createImage(UIColor.orange) defaultProgressView.trackImage = createImage(UIColor.black) // defaultProgressView.progressTintColor = UIColor.yellow // defaultProgressView.trackTintColor = UIColor.brown if #available(iOS 9.0, *) { //iOS 9.0之后,可以通过UIProgress来改变UIProgressView的进度 progressView.observedProgress = progress } } private func createImage(_ color: UIColor) -> UIImage? { UIGraphicsBeginImageContext(CGSize(width: 1.0, height: 1.0)) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0))) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } @IBAction func start(_ sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { barProgressView.setProgress(1.0, animated: true) defaultProgressView.setProgress(0.0, animated: true) progress.completedUnitCount = 10 }else { barProgressView.setProgress(0.0, animated: true) defaultProgressView.setProgress(1.0, animated: true) progress.completedUnitCount = 0 } } }
0aeec084bf8daeb2d7813acb6ac39e54
31.074074
83
0.658968
false
false
false
false
incetro/NIO
refs/heads/master
Tests/DAOTests/Realm/Translators/MessagesTranslator.swift
mit
1
// // MessagesTranslator.swift // SDAO // // Created by incetro on 07/10/2019. // import SDAO import Monreau // MARK: - MessagesTranslator final class MessagesTranslator { // MARK: - Aliases typealias PlainModel = MessagePlainObject typealias DatabaseModel = MessageModelObject private lazy var messageStorage = RealmStorage<MessageModelObject>( configuration: RealmConfiguration(inMemoryIdentifier: "DAO") ) } // MARK: - Translator extension MessagesTranslator: Translator { func translate(model: DatabaseModel) throws -> PlainModel { MessagePlainObject( id: Int(model.uniqueId) ?? 0, date: model.date, text: model.text, senderId: model.senderId, receiverId: model.receiverId, type: model.type, isIncoming: model.isIncoming, isRead: model.isRead ) } func translate(plain: PlainModel) throws -> DatabaseModel { let model = try messageStorage.read(byPrimaryKey: plain.uniqueId.rawValue) ?? MessageModelObject() try translate(from: plain, to: model) return model } func translate(from plain: PlainModel, to databaseModel: DatabaseModel) throws { if databaseModel.uniqueId.isEmpty { databaseModel.uniqueId = plain.uniqueId.rawValue } databaseModel.date = plain.date databaseModel.isIncoming = plain.isIncoming databaseModel.isRead = plain.isRead databaseModel.senderId = plain.senderId databaseModel.text = plain.text databaseModel.type = plain.type databaseModel.receiverId = plain.receiverId } }
7f9f40cead60a3020f71de9694f0f8b0
27.083333
106
0.657567
false
false
false
false
pawrsccouk/Stereogram
refs/heads/master
Stereogram-iPad/Stereogram.swift
mit
1
// // Stereogram.swift // Stereogram-iPad // // Created by Patrick Wallace on 19/04/2015. // Copyright (c) 2015 Patrick Wallace. All rights reserved. // import UIKit /// How the stereogram should be viewed. /// /// - Crosseyed: Adjacent pictures, view crosseyed. /// - Walleyed: Adjacent pictures, view wall-eyed /// - RedGreen: Superimposed pictures, use red green glasses. /// - RandomDot: "Magic Eye" format. /// - AnimatedGIF: As a cycling animation. /// public enum ViewMode: Int { case Crosseyed, Walleyed, RedGreen, RandomDot, AnimatedGIF } private let kViewingMethod = "ViewingMethod" private let leftPhotoFileName = "LeftPhoto.jpg" , rightPhotoFileName = "RightPhoto.jpg" , propertyListFileName = "Properties.plist" /// Save the property list into it's appointed place. /// /// :returns: .Success or .Error(NSError) on failure. private func savePropertyList(propertyList: Stereogram.PropertyDict, toURL url: NSURL) -> Result { var error: NSError? if let data = NSPropertyListSerialization.dataWithPropertyList(propertyList , format: .XMLFormat_v1_0 , options: 0 , error: &error) { if data.writeToURL(url, options: .allZeros, error: &error) { return .Success() } } return returnError("Stereogram.savePropertyList()" , "NSData.writeToURL(_, options:, error:)") } /// A Stereogram contains URLs to a left and a right image /// and composites these according to a viewing method. /// /// The stereogram assumes you have created a new directory with three files in it: /// LeftPhoto.jpg, RightPhoto.jpg and Properties.plist. /// There are class methods to create this directory structure /// and to search a directory for stereogram objects. /// /// The stereogram normally contains just three URLs to find these resources. /// When needed, it will load and cache the images. /// It will also respond to memory-full notifications and clear the images, /// which can be re-calculated or reloaded later. /// /// Calculating the main stereogram image can take time, so you can use /// the reset method, which will clear all the loaded images and then explicitly reload them all. /// This can be done in a background thread. public class Stereogram: NSObject { // MARK: Properties /// The type of the property dictionary. typealias PropertyDict = [String : AnyObject] /// How to view this stereogram. /// This affects how the image returned by stereogramImage is computed. var viewingMethod: ViewMode { get { var viewMode: ViewMode? = nil if let viewingMethodNumber = propertyList[kViewingMethod] as? NSNumber { viewMode = ViewMode(rawValue: viewingMethodNumber.integerValue) assert(viewMode != nil, "Invalid value \(viewingMethodNumber)") } return viewMode ?? .Crosseyed } set { if self.viewingMethod != newValue { propertyList[kViewingMethod] = newValue.rawValue savePropertyList(propertyList, toURL: propertiesURL) // Delete any cached images so they are recreated with the new viewing method. stereogramImg = nil thumbnailImg = nil } } } override public var description: String { return "\(super.description) <BaseURL: \(baseURL), Properties: \(propertyList)>" } /// URLs to the base directory containing the images. Used to load the images when needed. let baseURL: NSURL //MARK: Private Data /// Properties file for each stereogram. /// Probably not cached, just load them when we open the object. private var propertyList: PropertyDict /// Cached images in memory. Free these if needed. private var stereogramImg: UIImage? private var thumbnailImg: UIImage? //MARK: Initializers /// Initilizes the stereogram from two already-existing images. /// /// Save the images provided to the disk under a specified directory. /// /// :param: leftImage - The left image in the stereogram. /// :param: rightImage - The right image in the stereogram. /// :param: baseURL - The URL to save the stereogram under. /// :returns: A Stereogram object on success, nil on failure. public convenience init?(leftImage: UIImage , rightImage: UIImage , baseURL: NSURL , inout error: NSError?) { let newStereogramURL = Stereogram.getUniqueStereogramURL(baseURL) let propertyList = [String : AnyObject]() self.init( baseURL: newStereogramURL , propertyList: propertyList) switch writeToURL(newStereogramURL, propertyList, leftImage, rightImage) { case .Success: break case .Error(let e): error = e return nil } } /// Designated Initializer. /// Creates a new stereogram object from a URL and a property list. /// /// :param: baseImageURL File URL pointing to the directory under which the images are stored. /// :param: propertyList A dictionary of default properties for this stereogram private init(baseURL url: NSURL, propertyList propList: PropertyDict) { baseURL = url propertyList = propList super.init() thumbnailImg = nil stereogramImg = nil // Notify when memory is low, so I can delete this cache. let centre = NSNotificationCenter.defaultCenter() centre.addObserver(self , selector: "lowMemoryNotification:" , name: UIApplicationDidReceiveMemoryWarningNotification , object :nil) } deinit { let centre = NSNotificationCenter.defaultCenter() centre.removeObserver(self) } } //MARK: - Public class functions. /// Checks if a file exists given a base directory URL and filename. /// /// :param: baseURL The Base URL to look in. /// :param: fileName The name of the file to check for. /// :returns: .Success if the file was present, .Error(NSError) if it was not. private func fileExists(baseURL: NSURL, fileName: String) -> Result { let fullURLPath = baseURL.URLByAppendingPathComponent(fileName).path if let fullPath = fullURLPath { if NSFileManager.defaultManager().fileExistsAtPath(fullPath) { return .Success() } } let userInfo = [NSFilePathErrorKey : NSString(string: fullURLPath ?? "<no path>")] return .Error(NSError(errorCode:.FileNotFound, userInfo: userInfo)) } /// Initialize this object by loading image data from the specified URL. /// /// :param: url - A File URL pointing to the root directory of a stereogram object /// :returns: A Stereogram object on success or an NSError object on failure. private func stereogramFromURL(url: NSURL) -> ResultOf<Stereogram> { // URL should be pointing to a directory. // Inside this there should be 3 files: LeftImage.jpg, RightImage.jpg, Properties.plist. // Return an error if any of these are missing. Also load the properties file. let defaultPropertyDict: Stereogram.PropertyDict = [ kViewingMethod : ViewMode.Crosseyed.rawValue] // if any of the files don't exist, then return an error. let result = and([ fileExists(url, leftPhotoFileName), fileExists(url, rightPhotoFileName), fileExists(url, propertyListFileName)]) if let err = result.error { return .Error(err) } // Load the property list at the given URL. var propertyList = defaultPropertyDict switch loadPropertyList(url.URLByAppendingPathComponent(propertyListFileName)) { case .Success(let propList): propertyList = propList.value case .Error(let error): return .Error(error) } return ResultOf(Stereogram(baseURL: url, propertyList: propertyList)) } /// Load a property list stored at URL and return it. /// /// :param: url - File URL describing a path to a .plist file. /// :returns: A PropertyDict on success, an NSError on failure. private func loadPropertyList(url: NSURL) -> ResultOf<Stereogram.PropertyDict> { var error: NSError? var formatPtr: UnsafeMutablePointer<NSPropertyListFormat> = nil let options = Int(NSPropertyListMutabilityOptions.MutableContainersAndLeaves.rawValue) if let propertyData = NSData(contentsOfURL:url, options:.allZeros, error:&error) , propObject: AnyObject = NSPropertyListSerialization.propertyListWithData(propertyData , options: options , format: formatPtr , error: &error) , propDict = propObject as? Stereogram.PropertyDict { return ResultOf(propDict) } else { assert(false, "Property list object cannot be converted to a dictionary") } return .Error(error!) } extension Stereogram { /// Find all the stereograms found in the given directory /// /// :param: url - A File URL pointing to the directory to search. /// :returns: An array of Stereogram objects on success or an NSError on failure. class func allStereogramsUnderURL(url: NSURL) -> ResultOf<[Stereogram]> { let fileManager = NSFileManager.defaultManager() var stereogramArray = [Stereogram]() var error: NSError? if let fileArray = fileManager.contentsOfDirectoryAtURL(url , includingPropertiesForKeys: nil , options: .SkipsHiddenFiles , error: &error), fileNames = fileArray as? [NSURL] { for stereogramURL in fileNames { switch stereogramFromURL(stereogramURL) { case .Success(let result): stereogramArray.append(result.value) case .Error(let err): return .Error(err) } } } return ResultOf(stereogramArray) } } // MARK: - Methods extension Stereogram { /// Combine leftImage and rightImage according to viewingMethod, /// loading the images if they are not already available. /// /// :returns: The new image on success or an NSError object on failure. func stereogramImage() -> ResultOf<UIImage> { // The image is cached. Just return the cached image. if stereogramImg != nil { return ResultOf(stereogramImg!) } // Get the left and right images, loading them if they are not in cache. let leftImage: UIImage, rightImage: UIImage switch and(loadImage(.Left), loadImage(.Right)) { case .Error(let error): return .Error(error) case .Success(let result): (leftImage, rightImage) = result.value } // Create the stereogram image, cache it and return it. switch (self.viewingMethod) { case .Crosseyed: switch ImageManager.makeStereogramWithLeftPhoto(leftImage, rightPhoto:rightImage) { case .Error(let error): return .Error(error) case .Success(let result): stereogramImg = result.value } case .Walleyed: switch ImageManager.makeStereogramWithLeftPhoto(rightImage, rightPhoto:leftImage) { case .Error(let error): return .Error(error) case .Success(let result): stereogramImg = result.value } case .AnimatedGIF: stereogramImg = UIImage.animatedImageWithImages([leftImage, rightImage], duration: 0.25) default: let reason = "Viewing method \(self.viewingMethod) is not implemented yet." let e = NSException(name: "Not implemented" , reason: reason , userInfo: nil) e.raise() break } return ResultOf(stereogramImg!) } /// Return a thumbnail image, caching it if necessary. /// /// :returns: The thumbnail image on success or an NSError object on failure. func thumbnailImage() -> ResultOf<UIImage> { let options = NSDataReadingOptions.allZeros var error: NSError? if thumbnailImg == nil { // Get either the left or the right image file URL to use as the thumbnail. var data: NSData? = NSData(contentsOfURL:leftImageURL, options:options, error:&error) if data == nil { data = NSData(contentsOfURL:rightImageURL, options:options, error:&error) } if data == nil { return .Error(error!) } if let d = data, image = UIImage(data: d) { // Create the image, and then return a thumbnail-sized copy. thumbnailImg = image.thumbnailImage(thumbnailSize: Int(thumbnailSize.width) , transparentBorderSize: 0 , cornerRadius: 0 , interpolationQuality: kCGInterpolationLow) } else { let userInfo: [String : AnyObject] = [ NSLocalizedDescriptionKey : "Invalid image format in file", NSFilePathErrorKey : leftImageURL.path!] let err = NSError(errorCode:.InvalidFileFormat, userInfo:userInfo) return .Error(err) } } return ResultOf(thumbnailImg!) } } // MARK: Exporting extension Stereogram { /// Alias for a string representing a MIME Type (e.g. "image/jpeg") typealias MIMEType = String /// The MIME type for the image that stereogramImage will generate. /// /// This is based on the viewing method. Use to represent the image when saving. var mimeType: MIMEType { return viewingMethod == ViewMode.AnimatedGIF ? "image/gif" : "image/jpeg" } /// Data format when returning data for exporting a stereogram typealias ExportData = (NSData, MIMEType) /// Returns the stereogram image in a format for sending outside this application. /// /// :returns: .Success(ExportData) or .Error(NSError) /// /// ExportData is a tuple: The data representing the image, /// and a MIME type indicating the format of the data. func exportData() -> ResultOf<ExportData> { return stereogramImage().map { (image) -> ResultOf<ExportData> in let data: NSData let mimeType: MIMEType if self.viewingMethod == .AnimatedGIF { mimeType = "image/gif" data = image.asGIFData } else { mimeType = "image/jpeg" data = image.asJPEGData } return ResultOf((data, mimeType)) } } } // MARK: - Convenience Properties extension Stereogram { /// Update the stereogram and thumbnail, replacing the cached images. /// Usually called from a background thread just after some property has been changed. /// /// :returns: Success or an NSError object on failure. func refresh() -> Result { thumbnailImg = nil stereogramImg = nil return and(thumbnailImage().result, stereogramImage().result) } /// Delete the folder representing this stereogram from the disk. /// After this, the stereogram will be invalid. /// /// :returns: Success or an NSError object on failure. func deleteFromDisk() -> Result { var error: NSError? let fileManager = NSFileManager.defaultManager() let success = fileManager.removeItemAtURL(baseURL, error:&error) if success { thumbnailImg = nil stereogramImg = nil return .Success() } return .Error(error!) } } //MARK: Private data /// Saves the specified image into a file provided by the given URL /// /// :param: image - The image to save. /// :param: url - File URL of the location to save the image. /// :returns: Success on success, or an NSError on failure. /// /// Currently this saves as a JPEG file, but it doesn't check the extension in the URL /// so it is possible it could save JPEG data into a file ending in .png for example. private func saveImageIntoURL(image: UIImage, url: NSURL) -> Result { let fileData = UIImageJPEGRepresentation(image, 1.0) var error: NSError? if fileData.writeToURL(url, options:.AtomicWrite, error:&error) { return .Success() } return .Error(error!) } /// Save the left and right images and the property list into the directory specified by url. /// /// :param: url - A File URL to the directory to store the images in. /// :param: propertyList - The property list to output /// :param: leftImage - The left image to save. /// :param: rightImage - The right image to save. /// :returns: Success or .Error(NSError) on failure. private func writeToURL(url: NSURL , propertyList: [String : AnyObject] , leftImage: UIImage , rightImage: UIImage) -> Result { assert(url.path != nil, "URL \(url) has an invalid path") let fileManager = NSFileManager.defaultManager() let leftImageURL = url.URLByAppendingPathComponent(leftPhotoFileName) let rightImageURL = url.URLByAppendingPathComponent(rightPhotoFileName) // Create the directory (ignoring any errors about it already existing) // and then write the left and right images and properties data into it. return and( [ fileManager.createDirectoryAtURL(url) , saveImageIntoURL(leftImage , leftImageURL ) , saveImageIntoURL(rightImage, rightImageURL) , savePropertyList(propertyList, toURL: url) ]) } /// Serialize the property dict given and write it out to the given URL. /// /// :param: propertyList /// :param: toURL /// :param: format /// :returns: .Success() on success, .Error() on error. private func savePropertyList(propertyList: Stereogram.PropertyDict , toURL url: NSURL , format: NSPropertyListFormat = .XMLFormat_v1_0) -> Result { var error: NSError? if let propertyListData = NSPropertyListSerialization.dataWithPropertyList( propertyList , format: format , options: .allZeros , error: &error) { let propertyListURL = url.URLByAppendingPathComponent(propertyListFileName) if !propertyListData.writeToURL(propertyListURL , options: .AtomicWrite , error: &error) { return .Error(error!) } return .Success() } return returnError("writeToURL(_propertyList:toURL:format:)" , "calling NSPropertyListSerialization.dataWithPropertyList") } extension Stereogram { /// URL of the left image file (computed from the base URL) private var leftImageURL: NSURL { return baseURL.URLByAppendingPathComponent(leftPhotoFileName) } /// URL of the right image file (computed from the base URL) private var rightImageURL: NSURL { return baseURL.URLByAppendingPathComponent(rightPhotoFileName) } /// URL of the property list file (computed from the base URL) private var propertiesURL: NSURL { return baseURL.URLByAppendingPathComponent(propertyListFileName) } /// Create a new unique URL which will not already reference a stereogram. /// This URL is relative to photoDir. /// /// :param: photoDir - The base directory with all the stereograms in it. /// :returns: A file URL pointing to a new directory under photoDir. private class func getUniqueStereogramURL(photoDir: NSURL) -> NSURL { // Create a CF GUID, then turn it into a string, which we will return. // Add the object into the backing store using this key. let newUID = CFUUIDCreate(kCFAllocatorDefault); let newUIDString = CFUUIDCreateString(kCFAllocatorDefault, newUID) let uid = newUIDString as String let newURL = photoDir.URLByAppendingPathComponent(uid, isDirectory:true) // Name should be unique so no photo should exist yet. assert(newURL.path != nil, "URL \(newURL) has no path.") assert(!NSFileManager.defaultManager().fileExistsAtPath(newURL.path!) , "'Unique' file URL \(newURL) already exists") return newURL; } private enum WhichImage { case Left, Right } /// Loads one of the two images, caching it if necessary. /// /// :param: whichImage - Left or Right specifying which image to load. /// :returns: The UIImage object on success or NSError on failure. private func loadImage(whichImage: WhichImage) -> ResultOf<UIImage> { func loadData(url: NSURL) -> ResultOf<UIImage> { var error: NSError? if let imageData = NSData(contentsOfURL:url, options:.allZeros, error:&error), image = UIImage(data: imageData) { return ResultOf(image) } else { return ResultOf.Error(error!) } } switch whichImage { case .Left: return loadData(leftImageURL) case .Right: return loadData(rightImageURL) } } /// Searches a given directory and returns all the entries under it. /// /// :param: url - A file URL pointing to the directory to search. /// :returns: An array of URL objects, one each for each file in the directory /// /// This does not include hidden files in the search. private class func contentsUnderURL(url: NSURL) -> ResultOf<[NSURL]> { let fileManager = NSFileManager.defaultManager() var error: NSError? if let fileArray = fileManager.contentsOfDirectoryAtURL(url , includingPropertiesForKeys: nil , options: .SkipsHiddenFiles , error: &error), urlArray = fileArray as? [NSURL] { return ResultOf(urlArray) } return .Error(error!) } }
84957159afece8b5807d0f7a6a844c65
32.292763
98
0.696176
false
false
false
false
hooman/swift
refs/heads/main
test/Generics/redundant_protocol_refinement.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s protocol Base {} protocol Middle : Base {} protocol Derived : Middle, Base {} // expected-note@-1 {{conformance constraint 'Self' : 'Base' implied here}} // expected-warning@-2 {{redundant conformance constraint 'Self' : 'Base'}} protocol P1 {} protocol P2 { associatedtype Assoc: P1 } // no warning here protocol Good: P2, P1 where Assoc == Self {} // CHECK-LABEL: Requirement signature: <Self where Self : P1, Self : P2, Self == Self.Assoc> // missing refinement of 'P1' protocol Bad: P2 where Assoc == Self {} // expected-warning@-1 {{protocol 'Bad' should be declared to refine 'P1' due to a same-type constraint on 'Self'}} // expected-note@-2 {{conformance constraint 'Self' : 'P1' implied here}} // CHECK-LABEL: Requirement signature: <Self where Self : P2, Self == Self.Assoc>
3f10b561ceee4aa3cbfa506decbb6f15
37.458333
115
0.699566
false
false
false
false
5calls/ios
refs/heads/main
FiveCalls/FiveCalls/ContactsManager.swift
mit
1
// // ContactsManager.swift // FiveCalls // // Created by Ben Scheirman on 1/9/19. // Copyright © 2019 5calls. All rights reserved. // import Foundation enum ContactLoadResult { case success([Contact]) case failed(Error) } class ContactsManager { private let queue: OperationQueue // contactCache stores a list of contacts for a string-serialized location private var contactCache: [String: [Contact]] init() { queue = .main contactCache = [:] } func fetchContacts(location: UserLocation, completion: @escaping (ContactLoadResult) -> Void) { // if we already have contacts for this userlocation, return that if let contacts = self.contactCache[location.description] { completion(.success(contacts)) return } let operation = FetchContactsOperation(location: location) operation.completionBlock = { [weak operation] in if var contacts = operation?.contacts, !contacts.isEmpty { // if we get more than one house rep here, select the first one. // this is a split district situation and we should let the user // pick which one is correct in the future let houseReps = contacts.filter({ $0.area == "US House" }) if houseReps.count > 1 { contacts = contacts.filter({ $0.area != "US House" }) contacts.append(houseReps[0]) } self.contactCache[location.description] = contacts DispatchQueue.main.async { completion(.success(contacts)) } } else if let error = operation?.error { DispatchQueue.main.async { completion(.failed(error)) } } } queue.addOperation(operation) } }
ce8b191ac5d7e519d2c039223d91da9d
32.186441
99
0.562819
false
false
false
false
DianQK/rx-sample-code
refs/heads/master
Stopwatch/BasicViewModel.swift
mit
1
// // BasicViewModel.swift // Stopwatch // // Created by DianQK on 12/09/2016. // Copyright © 2016 T. All rights reserved. // import UIKit import RxSwift import RxCocoa //import RxExtensions struct BasicViewModel: StopwatchViewModelProtocol { let startAStopStyle: Observable<Style.Button> let resetALapStyle: Observable<Style.Button> let displayTime: Observable<String> let displayElements: Observable<[(title: Observable<String>, displayTime: Observable<String>, color: Observable<UIColor>)]> private enum State { case timing, stopped } init(input: (startAStopTrigger: Observable<Void>, resetALapTrigger: Observable<Void>)) { let state = input.startAStopTrigger .scan(State.stopped) { switch $0.0 { case .stopped: return State.timing case .timing: return State.stopped } } .shareReplay(1) displayTime = state .flatMapLatest { state -> Observable<TimeInterval> in switch state { case .stopped: return Observable.empty() case .timing: return Observable<Int>.interval(0.01, scheduler: MainScheduler.instance).map { _ in 0.01 } } } .scan(0, accumulator: +) .startWith(0) .map(Tool.convertToTimeInfo) startAStopStyle = state .map { state in switch state { case .stopped: return Style.Button(title: "Start", titleColor: Tool.Color.green, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "green")) case .timing: return Style.Button(title: "Stop", titleColor: Tool.Color.red, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "red")) } } resetALapStyle = Observable.just(Style.Button(title: "", titleColor: UIColor.white, isEnabled: false, backgroungImage: #imageLiteral(resourceName: "gray"))) displayElements = Observable.empty() } }
7e6786f9749815ed3fe7b51ae3799ce6
34.145161
164
0.582836
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Components/UserImageView.swift
gpl-3.0
1
// // 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 WireSyncEngine /** * A view that displays the avatar for a remote user. */ class UserImageView: AvatarImageView, ZMUserObserver { /** * The different sizes for the avatar image. */ enum Size: Int { case tiny = 16 case badge = 24 case small = 32 case normal = 64 case big = 320 } // MARK: - Interface Properties /// The size of the avatar. var size: Size { didSet { updateUserImage() } } /// Whether the image should be desaturated, e.g. for unconnected users. var shouldDesaturate: Bool = true /// Whether the badge indicator is enabled. var indicatorEnabled: Bool = false { didSet { badgeIndicator.isHidden = !indicatorEnabled } } private let badgeIndicator = RoundedView() // MARK: - Remote User /// The user session to use to download images. var userSession: ZMUserSessionInterface? { didSet { updateUser() } } /// The user to display the avatar of. var user: UserType? { didSet { updateUser() } } private var userObserverToken: Any? // MARK: - Initialization override init(frame: CGRect) { self.size = .small super.init(frame: .zero) configureSubviews() configureConstraints() } init(size: Size = .small) { self.size = size super.init(frame: .zero) configureSubviews() configureConstraints() } deinit { userObserverToken = nil } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return CGSize(width: size.rawValue, height: size.rawValue) } private func configureSubviews() { accessibilityElementsHidden = true badgeIndicator.backgroundColor = .red badgeIndicator.isHidden = true badgeIndicator.shape = .circle addSubview(badgeIndicator) } private func configureConstraints() { badgeIndicator.translatesAutoresizingMaskIntoConstraints = false setContentHuggingPriority(.required, for: .vertical) setContentHuggingPriority(.required, for: .horizontal) NSLayoutConstraint.activate([ badgeIndicator.topAnchor.constraint(equalTo: topAnchor), badgeIndicator.trailingAnchor.constraint(equalTo: trailingAnchor), badgeIndicator.heightAnchor.constraint(equalTo: badgeIndicator.widthAnchor), badgeIndicator.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/3) ]) } // MARK: - Interface /// Returns the appropriate border width for the user. private func borderWidth(for user: UserType) -> CGFloat { return user.isServiceUser ? 0.5 : 0 } /// Returns the appropriate border color for the user. private func borderColor(for user: UserType) -> CGColor? { return user.isServiceUser ? UIColor.black.withAlphaComponent(0.08).cgColor : nil } /// Returns the placeholder background color for the user. private func containerBackgroundColor(for user: UserType) -> UIColor? { switch self.avatar { case .image?, nil: return user.isServiceUser ? .white : .clear case .text?: if user.isConnected || user.isSelfUser || user.isTeamMember || user.isWirelessUser { return user.accentColor } else { return UIColor(white: 0.8, alpha: 1) } } } /// Returns the appropriate avatar shape for the user. private func shape(for user: UserType) -> AvatarImageView.Shape { return user.isServiceUser ? .relative : .circle } // MARK: - Changing the Content /** * Sets the avatar for the user with an optional animation. * - parameter avatar: The avatar of the user. * - parameter user: The currently displayed user. * - parameter animated: Whether to animate the change. */ func setAvatar(_ avatar: Avatar, user: UserType, animated: Bool) { let updateBlock = { self.avatar = avatar self.container.backgroundColor = self.containerBackgroundColor(for: user) } if animated && !ProcessInfo.processInfo.isRunningTests { UIView.transition(with: self, duration: 0.15, options: .transitionCrossDissolve, animations: updateBlock, completion: nil) } else { updateBlock() } } /// Updates the image for the user. fileprivate func updateUserImage() { guard let user = user, let userSession = userSession else { return } var desaturate = false if shouldDesaturate { desaturate = !user.isConnected && !user.isSelfUser && !user.isTeamMember && !user.isServiceUser } user.fetchProfileImage(session: userSession, imageCache: UIImage.defaultUserImageCache, sizeLimit: size.rawValue, isDesaturated: desaturate, completion: { [weak self] (image, cacheHit) in // Don't set image if nil or if user has changed during fetch guard let image = image, user.isEqual(self?.user) else { return } self?.setAvatar(.image(image), user: user, animated: !cacheHit) }) } // MARK: - Updates func userDidChange(_ changeInfo: UserChangeInfo) { // Check for potential image changes if size == .big { if changeInfo.imageMediumDataChanged || changeInfo.connectionStateChanged { updateUserImage() } } else { if changeInfo.imageSmallProfileDataChanged || changeInfo.connectionStateChanged || changeInfo.teamsChanged { updateUserImage() } } // Change for accent color changes if changeInfo.accentColorValueChanged { updateIndicatorColor() } } /// Called when the user or user session changes. func updateUser() { guard let user = self.user, let initials = user.initials else { return } let defaultAvatar = Avatar.text(initials.localizedUppercase) setAvatar(defaultAvatar, user: user, animated: false) if !ProcessInfo.processInfo.isRunningTests, let userSession = userSession as? ZMUserSession { userObserverToken = UserChangeInfo.add(observer: self, for: user, in: userSession) } updateForServiceUserIfNeeded(user) updateIndicatorColor() updateUserImage() } /// Updates the color of the badge indicator. private func updateIndicatorColor() { self.badgeIndicator.backgroundColor = user?.accentColor } /// Updates the interface to reflect if the user is a service user or not. private func updateForServiceUserIfNeeded(_ user: UserType) { let oldValue = shape shape = shape(for: user) if oldValue != shape { container.layer.borderColor = borderColor(for: user) container.layer.borderWidth = borderWidth(for: user) container.backgroundColor = containerBackgroundColor(for: user) } } }
d459a0e784cf78d1b598d81802068887
30.237548
134
0.621489
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/CoreAnimation/Animations/CombinedShapeAnimation.swift
apache-2.0
3
// Created by Cal Stephens on 1/28/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import QuartzCore extension CAShapeLayer { /// Adds animations for the given `CombinedShapeItem` to this `CALayer` @nonobjc func addAnimations( for combinedShapes: CombinedShapeItem, context: LayerAnimationContext, pathMultiplier: PathMultiplier) throws { try addAnimation( for: .path, keyframes: combinedShapes.shapes.keyframes, value: { paths in let combinedPath = CGMutablePath() for path in paths { combinedPath.addPath(path.cgPath().duplicated(times: pathMultiplier)) } return combinedPath }, context: context) } } // MARK: - CombinedShapeItem /// A custom `ShapeItem` subclass that combines multiple `Shape`s into a single `KeyframeGroup` final class CombinedShapeItem: ShapeItem { // MARK: Lifecycle init(shapes: KeyframeGroup<[BezierPath]>, name: String) { self.shapes = shapes super.init(name: name, type: .shape, hidden: false) } required init(from _: Decoder) throws { fatalError("init(from:) has not been implemented") } required init(dictionary _: [String: Any]) throws { fatalError("init(dictionary:) has not been implemented") } // MARK: Internal let shapes: KeyframeGroup<[BezierPath]> } extension CombinedShapeItem { /// Manually combines the given shape keyframes by manually interpolating at each frame static func manuallyInterpolating( shapes: [KeyframeGroup<BezierPath>], name: String) -> CombinedShapeItem { let interpolators = shapes.map { shape in KeyframeInterpolator(keyframes: shape.keyframes) } let times = shapes.flatMap { $0.keyframes.map { $0.time } } let minimumTime = times.min() ?? 0 let maximumTime = times.max() ?? 0 let animationLocalTimeRange = Int(minimumTime)...Int(maximumTime) let interpolatedKeyframes = animationLocalTimeRange.map { localTime in Keyframe( value: interpolators.compactMap { interpolator in interpolator.value(frame: AnimationFrameTime(localTime)) as? BezierPath }, time: AnimationFrameTime(localTime)) } return CombinedShapeItem( shapes: KeyframeGroup(keyframes: ContiguousArray(interpolatedKeyframes)), name: name) } }
c411d2c82bf966f76fcd6a56806af462
26.845238
95
0.689611
false
false
false
false
Jnosh/swift
refs/heads/master
test/ClangImporter/foreign_errors.swift
apache-2.0
22
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -parse-as-library -verify %s // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -O -parse-as-library -DEMIT_SIL %s // REQUIRES: objc_interop import Foundation import errors #if !EMIT_SIL func test0() { try ErrorProne.fail() // expected-error {{errors thrown from here are not handled}} } #endif // Test "AndReturnError" stripping. // rdar://20722195 func testAndReturnError() throws { try ErrorProne.fail() try ErrorProne.go() try ErrorProne.tryAndReturnError() // collides with 'try' keyword ErrorProne.messUpSignatureAndReturnError(nil) // wrong signature } func testInheritedInit() throws { try ReallyErrorProne(one: nil) // expected-warning{{unused}} } func testInheritedFactory() throws { try ReallyErrorProne(two: nil) // expected-warning{{unused}} } // Resolve a conflict between -foo and -foo: by just not // importing the latter as throwing. func testConflict1(_ obj: ErrorProne) throws { try obj.conflict1() // expected-warning {{no calls to throwing functions occur within 'try'}} } func testConflict1_error(_ obj: ErrorProne) throws { var error: NSError? obj.conflict1(&error) } // Resolve a conflict between -foo and -fooAndReturnError: // by not changing the name of the latter. func testConflict2(_ obj: ErrorProne) throws { try obj.conflict2() // expected-warning {{no calls to throwing functions occur within 'try'}} } func testConflict2_error(_ obj: ErrorProne) throws { try obj.conflict2AndReturnError() } // Resolve a conflict between -foo: and -foo:error: by not // changing the name of the latter. func testConflict3(_ obj: ErrorProne) throws { try obj.conflict3(nil) // expected-warning {{no calls to throwing functions occur within 'try'}} } func testConflict3_error(_ obj: ErrorProne) throws { try obj.conflict3(nil, error: ()) } // Same as above but with an initializer. // <rdar://problem/20922973> func testConflict4() throws { try ErrorProne(newtonMessagePad: "Dilbert") // expected-warning {{no calls to throwing functions occur within 'try'}} // expected-warning{{unused}} } func testConflict4_error() throws { try ErrorProne(newtonMessagePad: "Eat Up Martha", error: ()) // expected-warning{{unused}} } func testBlockFinal() throws { try ErrorProne.run(callback: {}) try ErrorProne.runWithAnError(callback: {}) try ErrorProne.runSwiftly(5000, callback: {}) } #if !EMIT_SIL func testNonBlockFinal() throws { ErrorProne.runWithError(count: 0) // expected-error {{missing argument for parameter #1 in call}} ErrorProne.run(count: 0) // expected-error {{incorrect argument label in call (have 'count:', expected 'callback:')}} } #endif class VeryErrorProne : ErrorProne { override class func fail() throws {} } func testConflictWithUnavailable() throws { try ErrorProne.doTheThing(42) } // rdar://21715350 func testSwiftError() throws { var err: NSError? let _: Bool = try ErrorProne.bound() let _: Float = try ErrorProne.bounce() let _: () = try ErrorProne.flounce() let _: CInt = try ErrorProne.ounce() let _: () = try ErrorProne.once() let _: () = try ErrorProne.sconce() let _: () = try ErrorProne.scotch() let _: Bool = ErrorProne.scout(&err) } // rdar://21074857 func needsNonThrowing(_ fn: () -> Void) {} func testNSErrorExhaustive() { needsNonThrowing { do { try ErrorProne.fail() } catch let e as NSError { e // expected-warning {{expression of type 'NSError' is unused}} } } } func testBadOverrides(obj: FoolishErrorSub) throws { try obj.performRiskyOperation() let _: FoolishErrorSub = try obj.produceRiskyOutput() let _: String = try obj.produceRiskyString() let _: NSObject = try obj.badNullResult() let _: CInt = try obj.badNullResult2() // This is unfortunate but consistent. let _: CInt = try obj.badZeroResult() try obj.badNonzeroResult() as Void let base = obj as SensibleErrorBase try base.performRiskyOperation() let _: NSObject = try base.produceRiskyOutput() let _: String = try base.produceRiskyString() let _: NSObject = try base.badNullResult() let _: NSObject = try base.badNullResult2() let _: CInt = try base.badZeroResult() try base.badNonzeroResult() as Void }
acd29055cfa74be56a850e675a62acb0
30.316176
149
0.712139
false
true
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Generators/Oscillators/Phase Distortion Oscillator Bank/AKPhaseDistortionOscillatorBank.swift
mit
1
// // AKPhaseDistortionOscillatorBank.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Phase Distortion Oscillator Bank /// open class AKPhaseDistortionOscillatorBank: AKPolyphonicNode, AKComponent { public typealias AKAudioUnitType = AKPhaseDistortionOscillatorBankAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(instrument: "phdb") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var waveform: AKTable? fileprivate var phaseDistortionParameter: AUParameter? fileprivate var attackDurationParameter: AUParameter? fileprivate var decayDurationParameter: AUParameter? fileprivate var sustainLevelParameter: AUParameter? fileprivate var releaseDurationParameter: AUParameter? fileprivate var pitchBendParameter: AUParameter? fileprivate var vibratoDepthParameter: AUParameter? fileprivate var vibratoRateParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Duty cycle width (range -1 - 1). @objc open dynamic var phaseDistortion: Double = 0.0 { willSet { if phaseDistortion != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { phaseDistortionParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.phaseDistortion = Float(newValue) } } } } /// Attack time @objc open dynamic var attackDuration: Double = 0.1 { willSet { if attackDuration != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { attackDurationParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.attackDuration = Float(newValue) } } } } /// Decay time @objc open dynamic var decayDuration: Double = 0.1 { willSet { if decayDuration != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { decayDurationParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.decayDuration = Float(newValue) } } } } /// Sustain Level @objc open dynamic var sustainLevel: Double = 1.0 { willSet { if sustainLevel != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { sustainLevelParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.sustainLevel = Float(newValue) } } } } /// Release time @objc open dynamic var releaseDuration: Double = 0.1 { willSet { if releaseDuration != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { releaseDurationParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.releaseDuration = Float(newValue) } } } } /// Pitch Bend as number of semitones @objc open dynamic var pitchBend: Double = 0 { willSet { if pitchBend != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { pitchBendParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.pitchBend = Float(newValue) } } } } /// Vibrato Depth in semitones @objc open dynamic var vibratoDepth: Double = 0 { willSet { if vibratoDepth != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { vibratoDepthParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.vibratoDepth = Float(newValue) } } } } /// Vibrato Rate in Hz @objc open dynamic var vibratoRate: Double = 0 { willSet { if vibratoRate != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { vibratoRateParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.vibratoRate = Float(newValue) } } } } // MARK: - Initialization /// Initialize the oscillator with defaults public convenience override init() { self.init(waveform: AKTable(.sine)) } /// Initialize this oscillator node /// /// - Parameters: /// - waveform: The waveform of oscillation /// - phaseDistortion: Phase distortion amount (range -1 - 1). /// - attackDuration: Attack time /// - decayDuration: Decay time /// - sustainLevel: Sustain Level /// - releaseDuration: Release time /// - pitchBend: Change of pitch in semitones /// - vibratoDepth: Vibrato size in semitones /// - vibratoRate: Frequency of vibrato in Hz /// @objc public init( waveform: AKTable, phaseDistortion: Double = 0.0, attackDuration: Double = 0.1, decayDuration: Double = 0.1, sustainLevel: Double = 1.0, releaseDuration: Double = 0.1, pitchBend: Double = 0, vibratoDepth: Double = 0, vibratoRate: Double = 0) { self.waveform = waveform self.phaseDistortion = phaseDistortion self.attackDuration = attackDuration self.decayDuration = decayDuration self.sustainLevel = sustainLevel self.releaseDuration = releaseDuration self.pitchBend = pitchBend self.vibratoDepth = vibratoDepth self.vibratoRate = vibratoRate _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.midiInstrument = avAudioUnit as? AVAudioUnitMIDIInstrument self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType self?.internalAU?.setupWaveform(Int32(waveform.count)) for (i, sample) in waveform.enumerated() { self?.internalAU?.setWaveformValue(sample, at: UInt32(i)) } } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } phaseDistortionParameter = tree["phaseDistortion"] attackDurationParameter = tree["attackDuration"] decayDurationParameter = tree["decayDuration"] sustainLevelParameter = tree["sustainLevel"] releaseDurationParameter = tree["releaseDuration"] pitchBendParameter = tree["pitchBend"] vibratoDepthParameter = tree["vibratoDepth"] vibratoRateParameter = tree["vibratoRate"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.phaseDistortion = Float(phaseDistortion) internalAU?.attackDuration = Float(attackDuration) internalAU?.decayDuration = Float(decayDuration) internalAU?.sustainLevel = Float(sustainLevel) internalAU?.releaseDuration = Float(releaseDuration) internalAU?.pitchBend = Float(pitchBend) internalAU?.vibratoDepth = Float(vibratoDepth) internalAU?.vibratoRate = Float(vibratoRate) } // MARK: - AKPolyphonic // Function to start, play, or activate the node at frequency open override func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, frequency: Double) { internalAU?.startNote(noteNumber, velocity: velocity, frequency: Float(frequency)) } /// Function to stop or bypass the node, both are equivalent open override func stop(noteNumber: MIDINoteNumber) { internalAU?.stopNote(noteNumber) } }
94e6e3483f468cafa839c4436a7b6ac6
34.767176
102
0.579554
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/PhysicsBody+Internal.swift
apache-2.0
1
// // PhysicsBody+Internal.swift // Fiber2D // // Created by Andrey Volodin on 20.09.16. // Copyright © 2016 s1ddok. All rights reserved. // internal func internalBodySetMass(_ body: UnsafeMutablePointer<cpBody>, _ mass: cpFloat) { cpBodyActivate(body); body.pointee.m = mass; body.pointee.m_inv = 1.0 / mass //cpAssertSaneBody(body); } internal func internalBodyUpdateVelocity(_ body: UnsafeMutablePointer<cpBody>?, _ gravity: cpVect, _ damping: cpFloat, _ dt: cpFloat) { cpBodyUpdateVelocity(body, cpvzero, damping, dt) // Skip kinematic bodies. guard cpBodyGetType(body) != CP_BODY_TYPE_KINEMATIC else { return } let physicsBody = Unmanaged<PhysicsBody>.fromOpaque(cpBodyGetUserData(body)).takeUnretainedValue() if physicsBody.isGravityEnabled { body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvadd(gravity, cpvmult(body!.pointee.f, body!.pointee.m_inv)), dt)), cpFloat(physicsBody.velocityLimit)) } else { body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvmult(body!.pointee.f, body!.pointee.m_inv), dt)), cpFloat(physicsBody.velocityLimit)) } let w_limit = cpFloat(physicsBody.angularVelocityLimit) body!.pointee.w = cpfclamp(body!.pointee.w * damping + body!.pointee.t * body!.pointee.i_inv * dt, -w_limit, w_limit) // Reset forces. body!.pointee.f = cpvzero //to check body sanity cpBodySetTorque(body, 0.0) }
998a4979ad73cae65d1c0dcecda5117d
38.236842
190
0.694165
false
false
false
false
KHPhoneTeam/connect-ios
refs/heads/master
simpleVoIP/KHPSettingsViewController.swift
gpl-3.0
1
// // KHPSettingsViewController.swift // KHPhoneConnect // // Created by armand on 07-01-17. // Copyright © 2017 KHPhone. All rights reserved. // import UIKit @objc class KHPSettingsViewController: UIViewController { @IBOutlet var chooseEndpointButton: UIButton! @IBOutlet weak var qrButton: UIButton! @IBOutlet weak var sipAdressTextField: UITextField! @IBOutlet weak var portNumberTextField: UITextField! @IBOutlet weak var userPhoneNumberTextField: UITextField! @IBOutlet var chooseEndpointTextField: UITextField! let reachability = Reachability() let pickerFeeder = PickerViewFeeder() @objc var focusOnUserPhoneNeeded : Bool = false var cameFromQR : Bool = false fileprivate let pickerView = ToolbarPickerView() var endpoints: [Endpoint]? fileprivate func setupUI() { sipAdressTextField.text = "" chooseEndpointTextField.inputView = pickerView chooseEndpointTextField.inputAccessoryView = pickerView.toolbar pickerView.delegate = pickerFeeder pickerView.toolbarDelegate = self if let sip = KHPhonePrefUtil.returnSipURL() { pickerView.selectRow(pickerFeeder.rowForSip(sip: sip), inComponent: 0, animated: false) } sipAdressTextField.delegate = self portNumberTextField.delegate = self userPhoneNumberTextField.delegate = self let toolBar = UIToolbar() toolBar.barStyle = .default toolBar.isTranslucent = true toolBar.tintColor = UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1) let doneButton = UIBarButtonItem(title: "Sluit", style: .done, target: self, action: #selector(donePressedOnKeyboard)) let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true toolBar.sizeToFit() userPhoneNumberTextField.inputAccessoryView = toolBar } override func viewDidLoad() { super.viewDidLoad() setupUI() if focusOnUserPhoneNeeded { // this is used when the user has tapped on a setup link focusOnUserPhoneNumber() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateTextFields() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if cameFromQR { focusOnUserPhoneNumber() cameFromQR = false } } @IBAction func closeButtonPressed(sender: UIButton){ self.dismiss(animated: true) { } } @IBAction func doneButtonPressed(sender: UIButton){ view.endEditing(true) } @objc func donePressedOnKeyboard(){ view.endEditing(true) } func focusOnUserPhoneNumber (){ userPhoneNumberTextField?.becomeFirstResponder() } func updateTextFields(){ if let congregationName = KHPhonePrefUtil.returnCongregationName() { chooseEndpointTextField.text = congregationName } else { chooseEndpointTextField.text = "-- kies een gemeente --" } let sipPort = KHPhonePrefUtil.returnSipPort() if (sipPort != 0) { portNumberTextField.text = String(sipPort); } else { portNumberTextField.text = "5011"; // default } if let sipAddress = KHPhonePrefUtil.returnSipURL() { sipAdressTextField.text = sipAddress; } else { sipAdressTextField.text = ""; // default } if let userPhoneNumber = KHPhonePrefUtil.returnUserPhoneNumber() { userPhoneNumberTextField.text = userPhoneNumber; } else { userPhoneNumberTextField.text = ""; // default } } func updatePreferences(){ let sipPort = Int(portNumberTextField.text!) let sipAddress = sipAdressTextField.text! let userPhoneNumber = userPhoneNumberTextField.text! KHPhonePrefUtil.save(sipPort: sipPort!) KHPhonePrefUtil.save(sipAddress: sipAddress) KHPhonePrefUtil.save(userPhoneNumber: userPhoneNumber) // register account! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "GQSegue" { cameFromQR = true } } } extension KHPSettingsViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { updatePreferences() } } extension KHPSettingsViewController: ToolbarPickerViewDelegate { func didTapDone() { let selectedRow = pickerView.selectedRow(inComponent: 0) print("Selected row: \(selectedRow)") pickerFeeder.didSelect(row: selectedRow) chooseEndpointTextField.resignFirstResponder() // updateUI updateTextFields() } func didTapCancel() { chooseEndpointTextField.resignFirstResponder() } }
f51b93e1edc302d71a58e2773ad94ced
29.011765
122
0.712858
false
false
false
false
SwiftKit/Cuckoo
refs/heads/master
Generator/Source/CuckooGeneratorFramework/Generator.swift
mit
1
// // Generator.swift // CuckooGenerator // // Created by Tadeas Kriz on 13/01/16. // Copyright © 2016 Brightify. All rights reserved. // import Foundation import Stencil public struct Generator { private static let reservedKeywordsNotAllowedAsMethodName: Set = [ // Keywords used in declarations: "associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import", "init", "inout", "internal", "let", "operator", "private", "precedencegroup", "protocol", "public", "rethrows", "static", "struct", "subscript", "typealias", "var", // Keywords used in statements: "break", "case", "catch", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "throw", "switch", "where", "while", // Keywords used in expressions and types: "Any", "as", "catch", "false", "is", "nil", "rethrows", "self", "super", "throw", "throws", "true", "try", // Keywords used in patterns: "_", ] private let declarations: [Token] private let code = CodeBuilder() public init(file: FileRepresentation) { declarations = file.declarations } public func generate(debug: Bool = false) throws -> String { code.clear() let ext = Extension() ext.registerFilter("genericSafe") { (value: Any?) in guard let string = value as? String else { return value } return self.genericSafeType(from: string) } ext.registerFilter("matchableGenericNames") { (value: Any?) in guard let method = value as? Method else { return value } return self.matchableGenericTypes(from: method) } ext.registerFilter("matchableGenericWhereClause") { (value: Any?) in guard let method = value as? Method else { return value } return self.matchableGenericsWhereClause(from: method) } ext.registerFilter("matchableParameterSignature") { (value: Any?) in guard let parameters = value as? [MethodParameter] else { return value } return self.matchableParameterSignature(with: parameters) } ext.registerFilter("parameterMatchers") { (value: Any?) in guard let parameters = value as? [MethodParameter] else { return value } return self.parameterMatchers(for: parameters) } ext.registerFilter("openNestedClosure") { (value: Any?) in guard let method = value as? Method else { return value } return self.openNestedClosure(for: method) } ext.registerFilter("closeNestedClosure") { (value: Any?) in guard let parameters = value as? [MethodParameter] else { return value } return self.closeNestedClosure(for: parameters) } ext.registerFilter("escapeReservedKeywords") { (value: Any?) in guard let name = value as? String else { return value } return self.escapeReservedKeywords(for: name) } let environment = Environment(extensions: [ext]) let containers = declarations.compactMap { $0 as? ContainerToken } .filter { $0.accessibility.isAccessible } .map { $0.serializeWithType() } return try environment.renderTemplate(string: Templates.mock, context: ["containers": containers, "debug": debug]) } private func matchableGenericTypes(from method: Method) -> String { guard !method.parameters.isEmpty || !method.genericParameters.isEmpty else { return "" } let matchableGenericParameters = method.parameters.enumerated().map { index, parameter -> String in let type = parameter.isOptional ? "OptionalMatchable" : "Matchable" return "M\(index + 1): Cuckoo.\(type)" } let methodGenericParameters = method.genericParameters.map { $0.description } return "<\((matchableGenericParameters + methodGenericParameters).joined(separator: ", "))>" } private func matchableGenericsWhereClause(from method: Method) -> String { guard method.parameters.isEmpty == false else { return "" } let matchableWhereConstraints = method.parameters.enumerated().map { index, parameter -> String in let type = parameter.isOptional ? "OptionalMatchedType" : "MatchedType" return "M\(index + 1).\(type) == \(genericSafeType(from: parameter.type.withoutAttributes.unoptionaled.sugarized))" } let methodWhereConstraints = method.returnSignature.whereConstraints return " where \((matchableWhereConstraints + methodWhereConstraints).joined(separator: ", "))" } private func matchableParameterSignature(with parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "" } return parameters.enumerated().map { "\($1.labelAndName): M\($0 + 1)" }.joined(separator: ", ") } private func parameterMatchers(for parameters: [MethodParameter]) -> String { guard parameters.isEmpty == false else { return "let matchers: [Cuckoo.ParameterMatcher<Void>] = []" } let tupleType = parameters.map { $0.typeWithoutAttributes }.joined(separator: ", ") let matchers = parameters.enumerated().map { "wrap(matchable: \($1.name)) { $0\(parameters.count > 1 ? ".\($0)" : "") }" }.joined(separator: ", ") return "let matchers: [Cuckoo.ParameterMatcher<(\(genericSafeType(from: tupleType)))>] = [\(matchers)]" } private func genericSafeType(from type: String) -> String { return type.replacingOccurrences(of: "!", with: "?") } private func openNestedClosure(for method: Method) -> String { var fullString = "" for (index, parameter) in method.parameters.enumerated() { if parameter.isClosure && !parameter.isEscaping { let indents = String(repeating: "\t", count: index) let tries = method.isThrowing ? "try " : "" let awaits = method.isAsync ? "await " : "" let sugarizedReturnType = method.returnType.sugarized let returnSignature: String if sugarizedReturnType.isEmpty { returnSignature = sugarizedReturnType } else { returnSignature = " -> \(sugarizedReturnType)" } fullString += "\(indents)return \(tries)\(awaits)withoutActuallyEscaping(\(parameter.name), do: { (\(parameter.name): @escaping \(parameter.type))\(returnSignature) in\n" } } return fullString } private func closeNestedClosure(for parameters: [MethodParameter]) -> String { var fullString = "" for (index, parameter) in parameters.enumerated() { if parameter.isClosure && !parameter.isEscaping { let indents = String(repeating: "\t", count: index) fullString += "\(indents)})\n" } } return fullString } private func escapeReservedKeywords(for name: String) -> String { Self.reservedKeywordsNotAllowedAsMethodName.contains(name) ? "`\(name)`" : name } }
a724cda75b83f0ec86804607b2868868
43.561728
263
0.620862
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Client/Frontend/AuthenticationManager/SensitiveViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import SwiftKeychainWrapper enum AuthenticationState { case NotAuthenticating case Presenting } class SensitiveViewController: UIViewController { var promptingForTouchID: Bool = false var backgroundedBlur: UIImageView? var authState: AuthenticationState = .NotAuthenticating override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(SensitiveViewController.checkIfUserRequiresValidation), name: UIApplicationWillEnterForegroundNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(SensitiveViewController.checkIfUserRequiresValidation), name: UIApplicationDidBecomeActiveNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(SensitiveViewController.blurContents), name: UIApplicationWillResignActiveNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(SensitiveViewController.hideLogins), name: UIApplicationDidEnterBackgroundNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) notificationCenter.removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) notificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) notificationCenter.removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil) } func checkIfUserRequiresValidation() { guard authState != .Presenting else { return } presentedViewController?.dismissViewControllerAnimated(false, completion: nil) guard let authInfo = KeychainWrapper.defaultKeychainWrapper().authenticationInfo() where authInfo.requiresValidation() else { removeBackgroundedBlur() return } promptingForTouchID = true AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { self.promptingForTouchID = false self.authState = .NotAuthenticating self.removeBackgroundedBlur() }, cancel: { self.promptingForTouchID = false self.authState = .NotAuthenticating self.navigationController?.popToRootViewControllerAnimated(true) }, fallback: { self.promptingForTouchID = false AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) } ) authState = .Presenting } func hideLogins() { self.navigationController?.popToRootViewControllerAnimated(true) } func blurContents() { if backgroundedBlur == nil { backgroundedBlur = addBlurredContent() } } func removeBackgroundedBlur() { if !promptingForTouchID { backgroundedBlur?.removeFromSuperview() backgroundedBlur = nil } } private func addBlurredContent() -> UIImageView? { guard let snapshot = view.screenshot() else { return nil } let blurredSnapshot = snapshot.applyBlurWithRadius(10, blurType: BOXFILTER, tintColor: UIColor.init(white: 1, alpha: 0.3), saturationDeltaFactor: 1.8, maskImage: nil) let blurView = UIImageView(image: blurredSnapshot) view.addSubview(blurView) blurView.snp_makeConstraints { $0.edges.equalTo(self.view) } view.layoutIfNeeded() return blurView } } // MARK: - PasscodeEntryDelegate extension SensitiveViewController: PasscodeEntryDelegate { func passcodeValidationDidSucceed() { removeBackgroundedBlur() self.navigationController?.dismissViewControllerAnimated(true, completion: nil) self.authState = .NotAuthenticating } func userDidCancelValidation() { self.navigationController?.popToRootViewControllerAnimated(false) self.authState = .NotAuthenticating } }
c592aa2c5f88ae1227cd0eab9be5ad70
39.582609
185
0.708378
false
false
false
false
Performador/Pickery
refs/heads/master
Pickery/PhotosAsset.swift
mit
1
// // PhotosAsset.swift // Pickery // // Created by Okan Arikan on 8/1/16. // // import Foundation import Photos import AVFoundation import ReactiveSwift /// Represents a photo image request in flight /// /// It will cancel the request when deallocated class PhotosRequest { /// The request identifier to cancellation let requestId : PHImageRequestID /// Ctor init(requestId: PHImageRequestID) { self.requestId = requestId } /// Cancel the request deinit { PhotoLibrary.sharedInstance.cachingImageManager.cancelImageRequest(requestId) } } /// Represents an asset in the photo library class PhotosAsset : Asset { /// The unique identifier var identifier : String { return localIdentifier } /// The pixel resolution var pixelSize : CGSize { return CGSize(width: CGFloat(phAsset.pixelWidth), height: CGFloat(phAsset.pixelHeight)) } /// The duration var durationSeconds : TimeInterval { return phAsset.duration } /// Where? var location : CLLocation? { return phAsset.location } /// When var dateCreated : Date? { return phAsset.creationDate } /// Return the associated resource types var resourceTypes : [ ResourceType ] { return PHAssetResource.assetResources(for: phAsset).flatMap { ResourceType(resourceType: $0.type) } } /// Is this a live photo? var isLivePhoto : Bool { return phAsset.mediaSubtypes.contains(.photoLive) } /// Is this a video? var isVideo : Bool { return phAsset.mediaType == .video } /// The photos asset let phAsset : PHAsset /// The local identifier in case we need it var localIdentifier : String { return phAsset.localIdentifier } /// If we have this asset already uploaded, here it is var remoteAsset : RemoteAsset? /// Ctor init(phAsset: PHAsset) { // Save the class members self.phAsset = phAsset } /// Request an image func requestImage(for view: AssetImageView) -> AnyObject? { assertMainQueue() // We must be the active asset being displayed assert(view.asset?.identifier == identifier) let desiredPixelSize = view.pixelSize let cacheKey = "\(phAsset.localIdentifier)_\(desiredPixelSize)" // Already exists in the image cache? if let image = ImageCache.sharedInstance.imageForAsset(key: cacheKey) { view.image = image } else { let placeholderKey = phAsset.localIdentifier // Got a placeholder image? if let placeholder = ImageCache.sharedInstance.imageForAsset(key: placeholderKey) { view.image = placeholder } // We will have to request this image let myIdentifier = identifier let options = PHImageRequestOptions() options.resizeMode = .exact options.deliveryMode = .highQualityFormat options.isSynchronous = false options.isNetworkAccessAllowed = true // Fire off the request return PhotosRequest(requestId: PhotoLibrary .sharedInstance .cachingImageManager .requestImage(for: phAsset, targetSize: desiredPixelSize, contentMode: .default, options: options, resultHandler: { (image: UIImage?, info: [AnyHashable : Any]?) in assertMainQueue() // Were able to get an image? if let image = image { // Add the image to cache ImageCache.sharedInstance.addImageForAsset(key: cacheKey, image: image) // Have existing placeholder already larger than this? if let placeholder = ImageCache.sharedInstance.imageForAsset(key: placeholderKey), placeholder.size.width > image.size.width { // Nothing to do, existing placeholder is already good } else { // No placeholder or it's size is smaller than this, record it in the cache ImageCache.sharedInstance.addImageForAsset(key: placeholderKey, image: image) } // Set the image if this is still relevant if view.asset?.identifier == myIdentifier { view.image = image } } }) ) } return nil } /// Request a player item /// /// see Asset func requestPlayerItem(pixelSize: CGSize) -> SignalProducer<AVPlayerItem,NSError> { // Capture the asset let phAsset = self.phAsset return SignalProducer<AVPlayerItem,NSError> { sink, disposible in // The request options let options = PHVideoRequestOptions() options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true // Let's see if we can create a player item directly PhotoLibrary .sharedInstance .cachingImageManager .requestPlayerItem(forVideo: phAsset, options: options, resultHandler: { (playerItem: AVPlayerItem?, info: [AnyHashable : Any]?) in // Success? if let playerItem = playerItem { sink.send(value: playerItem) sink.sendCompleted() } else { var foundVideo = false // No player found, request the file for resource in PHAssetResource.assetResources(for: phAsset) { if resource.type == .video { let fileURL = FileManager.tmpURL.appendingPathComponent(UUID().uuidString) // Configure the resource access options let options = PHAssetResourceRequestOptions() options.isNetworkAccessAllowed = true // Write the data PHAssetResourceManager .default() .writeData(for: resource, toFile: fileURL, options: options, completionHandler: { (error: Swift.Error?) in // Got an error? if let error = error { sink.send(error: error as NSError) } else { sink.send(value: AVPlayerItem(asset: AVURLAsset(url: fileURL))) sink.sendCompleted() } }) foundVideo = true } } if foundVideo == false { sink.send(error: PickeryError.internalAssetNotFound as NSError) } } }) } } /// Request a live photo /// /// see Asset func requestLivePhoto(pixelSize: CGSize) -> SignalProducer<PHLivePhoto,NSError> { // Capture asset let phAsset = self.phAsset // Fire off the request in a signal producer return SignalProducer<PHLivePhoto,NSError> { sink, disposible in let options = PHLivePhotoRequestOptions() options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true PhotoLibrary .sharedInstance .cachingImageManager .requestLivePhoto(for: phAsset, targetSize: pixelSize, contentMode: PHImageContentMode.aspectFit, options: options, resultHandler: { (photo: PHLivePhoto?, info: [AnyHashable : Any]?) in // Success? if let photo = photo { sink.send(value: photo) } // Done sink.sendCompleted() }) } } }
10223ffbb55050017f4eab2e42b4ec31
38.012195
150
0.467021
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/Controller/Personal/PersonalMainViewController.swift
mit
1
// // PersonalMainViewController.swift // Whereami // // Created by WuQifei on 16/2/16. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import FBSDKLoginKit import Kingfisher //import SDWebImage class PersonalMainViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var tableView:UITableView? = nil var items:[String]? = nil var logos:[String]? = nil var currentUser:UserModel? = nil override func viewDidLoad() { super.viewDidLoad() self.setConfig() // Do any additional setup after loading the view. self.title = NSLocalizedString("Personal",tableName:"Localizable", comment: "") self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.customFontWithStyle("Bold", size:18.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()] self.items = ["Shop","Achievements","Settings","Help","Published"] self.logos = ["shop","achievements","setting","help","published"] self.setUI() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor() self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default) self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor() currentUser = UserModel.getCurrentUser() self.tableView?.reloadData() } func setUI(){ self.tableView = UITableView(frame: self.view.bounds) self.tableView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.tableFooterView = UIView() self.view.addSubview(tableView!) self.tableView?.registerClass(PersonalHeadTableViewCell.self, forCellReuseIdentifier: "PersonalHeadTableViewCell") self.tableView?.registerClass(PersonalMainViewCell.self, forCellReuseIdentifier: "PersonalMainViewCell") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else{ return (self.items?.count)! } } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 2 } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 0 || section == 1 { return 13 } else{ return 0 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return 90 } else{ return 50 } } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = UIColor.clearColor() return view } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("PersonalHeadTableViewCell", forIndexPath: indexPath) as! PersonalHeadTableViewCell cell.accessoryType = .DisclosureIndicator cell.userNicknameLabel?.text = currentUser?.nickname let avatarUrl = currentUser?.headPortraitUrl != nil ? currentUser?.headPortraitUrl : "" // cell.userImageView?.setImageWithString(avatarUrl!, placeholderImage: UIImage(named: "avator.png")!) cell.userImageView?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.selectionStyle = .None return cell } else{ let cell = tableView.dequeueReusableCellWithIdentifier("PersonalMainViewCell", forIndexPath: indexPath) as! PersonalMainViewCell cell.itemNameLabel?.text = self.items![indexPath.row] cell.logoView?.image = UIImage(named: self.logos![indexPath.row]) cell.accessoryType = .DisclosureIndicator cell.selectionStyle = .None return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { let viewController = TourRecordsViewController() viewController.userId = UserModel.getCurrentUser()?.id viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) } else{ if indexPath.row == 0 { let viewController = PersonalShopViewController() viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: false) } else if indexPath.row == 1 { let viewController = PersonalAchievementsViewController() viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) } else if indexPath.row == 2 { let viewController = PersonalSettingsViewController() viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
a19a1deb5e580770d80e4ec9e91d61c8
38.816456
191
0.657129
false
false
false
false
DukeLenny/Weibo
refs/heads/master
Weibo/Weibo/Class/View(视图和控制器)/Main/Controller/WBNavigationController.swift
mit
1
// // WBNavigationController.swift // Weibo // // Created by LiDinggui on 2017/9/1. // Copyright © 2017年 DAQSoft. All rights reserved. // import UIKit class WBNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationBar.isHidden = true } @objc fileprivate func popVC() { popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension WBNavigationController { override func pushViewController(_ viewController: UIViewController, animated: Bool) { if childViewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true var title = BarButtonItemTitle if childViewControllers.count == 1 { if let rootViewController = childViewControllers.first as? WBBaseViewController { title = rootViewController.navItem.title ?? BarButtonItemTitle } } if let viewController = viewController as? WBBaseViewController { viewController.navItem.leftBarButtonItem = UIBarButtonItem(title: title, target: self, action: #selector(popVC)) } } super.pushViewController(viewController, animated: animated) } } // MARK: - Rotation extension WBNavigationController { override var shouldAutorotate: Bool { if let topViewController = topViewController { return topViewController.shouldAutorotate } return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let topViewController = topViewController { return topViewController.supportedInterfaceOrientations } return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if let topViewController = topViewController { return topViewController.preferredInterfaceOrientationForPresentation } return .portrait } }
bb9249e039f6998eddb5ecefd41f1033
30.626506
128
0.665524
false
false
false
false
kykim/SwiftCheck
refs/heads/master
Sources/Random.swift
mit
1
// // Random.swift // SwiftCheck // // Created by Robert Widmann on 8/3/14. // Copyright (c) 2015 TypeLift. All rights reserved. // /// Provides a standard interface to an underlying Random Value Generator of any /// type. It is analogous to `GeneratorType`, but rather than consume a /// sequence it uses sources of randomness to generate values indefinitely. public protocol RandomGeneneratorType { /// The next operation returns an Int that is uniformly distributed in the /// range returned by `genRange` (including both end points), and a new /// generator. var next : (Int, Self) { get } /// The genRange operation yields the range of values returned by the /// generator. /// /// This property must return integers in ascending order. var genRange : (Int, Int) { get } /// Splits the receiver into two distinct random value generators. var split : (Self, Self) { get } } /// `StdGen` represents a pseudo-random number generator. The library makes it /// possible to generate repeatable results, by starting with a specified /// initial random number generator, or to get different results on each run by /// using the system-initialised generator or by supplying a seed from some /// other source. public struct StdGen : RandomGeneneratorType { let seed1 : Int let seed2 : Int /// Creates a `StdGen` initialized at the given seeds that is suitable for /// replaying of tests. public init(_ replaySeed1 : Int, _ replaySeed2 : Int) { self.seed1 = replaySeed1 self.seed2 = replaySeed2 } /// Convenience to create a `StdGen` from a given integer. public init(_ o : Int) { func mkStdGen32(_ sMaybeNegative : Int) -> StdGen { let s = sMaybeNegative & Int.max let (q, s1) = (s / 2147483562, s % 2147483562) let s2 = q % 2147483398 return StdGen((s1 + 1), (s2 + 1)) } self = mkStdGen32(o) } /// Returns an `Int` generated uniformly within the bounds of the generator /// and a new distinct random number generator. public var next : (Int, StdGen) { let s1 = self.seed1 let s2 = self.seed2 let k = s1 / 53668 let s1_ = 40014 * (s1 - k * 53668) - k * 12211 let s1__ = s1_ < 0 ? s1_ + 2147483563 : s1_ let k_ = s2 / 52774 let s2_ = 40692 * (s2 - k_ * 52774) - k_ * 3791 let s2__ = s2_ < 0 ? s2_ + 2147483399 : s2_ let z = s1__ - s2__ let z_ = z < 1 ? z + 2147483562 : z return (z_, StdGen(s1__, s2__)) } /// Splits the receiver and returns two distinct random number generators. public var split : (StdGen, StdGen) { let s1 = self.seed1 let s2 = self.seed2 let std = self.next.1 return (StdGen(s1 == 2147483562 ? 1 : s1 + 1, std.seed2), StdGen(std.seed1, s2 == 1 ? 2147483398 : s2 - 1)) } public var genRange : (Int, Int) { return (Int.min, Int.max) } } extension StdGen : Equatable, CustomStringConvertible { public var description : String { return "\(self.seed1) \(self.seed2)" } } /// Equality over random number generators. /// /// Two `StdGen`s are equal iff their seeds match. public func == (l : StdGen, r : StdGen) -> Bool { return l.seed1 == r.seed1 && l.seed2 == r.seed2 } private var theStdGen : StdGen = mkStdRNG(0) /// A library-provided standard random number generator. public func newStdGen() -> StdGen { let (left, right) = theStdGen.split theStdGen = left return right } /// Types that can generate random versions of themselves. public protocol RandomType { /// Takes a range `(lo, hi)` and a random number generator `G`, and returns /// a random value uniformly distributed in the closed interval `[lo,hi]`, /// together with a new generator. It is unspecified what happens if lo>hi. /// /// For continuous types there is no requirement that the values `lo` and /// `hi` are ever produced, but they may be, depending on the implementation /// and the interval. static func randomInRange<G : RandomGeneneratorType>(_ range : (Self, Self), gen : G) -> (Self, G) } /// Generates a random value from a LatticeType random type. public func randomBound<A : LatticeType & RandomType, G : RandomGeneneratorType>(_ gen : G) -> (A, G) { return A.randomInRange((A.min, A.max), gen: gen) } extension Bool : RandomType { /// Returns a random `Bool`ean value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Bool, Bool), gen: G) -> (Bool, G) { let (x, gg) = Int.randomInRange((range.0 ? 1 : 0, range.1 ? 1 : 0), gen: gen) return (x == 1, gg) } } extension Character : RandomType { /// Returns a random `Character` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Character, Character), gen : G) -> (Character, G) { let (min, max) = range let minc = String(min).unicodeScalars.first! let maxc = String(max).unicodeScalars.first! let (val, gg) = UnicodeScalar.randomInRange((minc, maxc), gen: gen) return (Character(val), gg) } } extension UnicodeScalar : RandomType { /// Returns a random `UnicodeScalar` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UnicodeScalar, UnicodeScalar), gen : G) -> (UnicodeScalar, G) { let (val, gg) = UInt32.randomInRange((range.0.value, range.1.value), gen: gen) return (UnicodeScalar(val)!, gg) } } extension Int : RandomType { /// Returns a random `Int` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int, Int), gen : G) -> (Int, G) { let (minl, maxl) = range let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen) return (Int(truncatingBitPattern: bb), gg) } } extension Int8 : RandomType { /// Returns a random `Int8` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int8, Int8), gen : G) -> (Int8, G) { let (minl, maxl) = range let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen) return (Int8(truncatingBitPattern: bb), gg) } } extension Int16 : RandomType { /// Returns a random `Int16` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int16, Int16), gen : G) -> (Int16, G) { let (minl, maxl) = range let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen) return (Int16(truncatingBitPattern: bb), gg) } } extension Int32 : RandomType { /// Returns a random `Int32` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int32, Int32), gen : G) -> (Int32, G) { let (minl, maxl) = range let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen) return (Int32(truncatingBitPattern: bb), gg) } } extension Int64 : RandomType { /// Returns a random `Int64` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int64, Int64), gen : G) -> (Int64, G) { let (l, h) = range if l > h { return Int64.randomInRange((h, l), gen: gen) } else { let (genlo, genhi) : (Int64, Int64) = (1, 2147483562) let b = Double(genhi - genlo + 1) let q : Double = 1000 let k = Double(h) - Double(l) + 1 let magtgt = k * q func entropize(_ mag : Double, _ v : Double, _ g : G) -> (Double, G) { if mag >= magtgt { return (v, g) } else { let (x, g_) = g.next let v_ = (v * b + (Double(x) - Double(genlo))) return entropize(mag * b, v_, g_) } } let (v, rng_) = entropize(1, 0, gen) return (Int64(Double(l) + (v.truncatingRemainder(dividingBy: k))), rng_) } } } extension UInt : RandomType { /// Returns a random `UInt` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt, UInt), gen : G) -> (UInt, G) { let (minl, maxl) = range let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen) return (UInt(truncatingBitPattern: bb), gg) } } extension UInt8 : RandomType { /// Returns a random `UInt8` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt8, UInt8), gen : G) -> (UInt8, G) { let (minl, maxl) = range let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen) return (UInt8(truncatingBitPattern: bb), gg) } } extension UInt16 : RandomType { /// Returns a random `UInt16` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt16, UInt16), gen : G) -> (UInt16, G) { let (minl, maxl) = range let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen) return (UInt16(truncatingBitPattern: bb), gg) } } extension UInt32 : RandomType { /// Returns a random `UInt32` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt32, UInt32), gen : G) -> (UInt32, G) { let (minl, maxl) = range let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen) return (UInt32(truncatingBitPattern: bb), gg) } } extension UInt64 : RandomType { /// Returns a random `UInt64` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt64, UInt64), gen : G) -> (UInt64, G) { let (l, h) = range if l > h { return UInt64.randomInRange((h, l), gen: gen) } else { let (genlo, genhi) : (Int64, Int64) = (1, 2147483562) let b = Double(genhi - genlo + 1) let q : Double = 1000 let k = Double(h) - Double(l) + 1 let magtgt = k * q func entropize(_ mag : Double, _ v : Double, _ g : G) -> (Double, G) { if mag >= magtgt { return (v, g) } else { let (x, g_) = g.next let v_ = (v * b + (Double(x) - Double(genlo))) return entropize(mag * b, v_, g_) } } let (v, rng_) = entropize(1, 0, gen) return (UInt64(Double(l) + (v.truncatingRemainder(dividingBy: k))), rng_) } } } extension Float : RandomType { /// Produces a random `Float` value in the range `[Float.min, Float.max]`. public static func random<G : RandomGeneneratorType>(_ rng : G) -> (Float, G) { let (x, rng_) : (Int32, G) = randomBound(rng) let twoto24 = Int32(2) ^ Int32(24) let mask24 = twoto24 - 1 return (Float(mask24 & (x)) / Float(twoto24), rng_) } /// Returns a random `Float` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Float, Float), gen : G) -> (Float, G) { let (l, h) = range if l > h { return Float.randomInRange((h , l), gen: gen) } else { let (coef, g_) = Float.random(gen) return (2.0 * (0.5 * l + coef * (0.5 * h - 0.5 * l)), g_) } } } extension Double : RandomType { /// Produces a random `Float` value in the range `[Double.min, Double.max]`. public static func random<G : RandomGeneneratorType>(_ rng : G) -> (Double, G) { let (x, rng_) : (Int64, G) = randomBound(rng) let twoto53 = Int64(2) ^ Int64(53) let mask53 = twoto53 - 1 return (Double(mask53 & (x)) / Double(twoto53), rng_) } /// Returns a random `Double` value using the given range and generator. public static func randomInRange<G : RandomGeneneratorType>(_ range : (Double, Double), gen : G) -> (Double, G) { let (l, h) = range if l > h { return Double.randomInRange((h , l), gen: gen) } else { let (coef, g_) = Double.random(gen) return (2.0 * (0.5 * l + coef * (0.5 * h - 0.5 * l)), g_) } } } /// Implementation Details Follow private enum ClockTimeResult { case success case failure(Int) } private func mkStdRNG(_ o : Int) -> StdGen { func mkStdGen32(_ sMaybeNegative : Int) -> StdGen { let s = sMaybeNegative & Int.max let (q, s1) = (s / 2147483562, s % 2147483562) let s2 = q % 2147483398 return StdGen(s1 + 1, s2 + 1) } let ct = Int(clock()) var tt = timespec() switch clock_gettime(0, &tt) { case .success: break case let .failure(error): fatalError("call to `clock_gettime` failed. error: \(error)") } let (sec, psec) = (tt.tv_sec, tt.tv_nsec) let (ll, _) = Int.multiplyWithOverflow(Int(sec), 12345) return mkStdGen32(Int.addWithOverflow(ll, Int.addWithOverflow(psec, Int.addWithOverflow(ct, o).0).0).0) } private func clock_gettime(_ : Int, _ t : UnsafeMutablePointer<timespec>) -> ClockTimeResult { var now : timeval = timeval() let rv = gettimeofday(&now, nil) if rv != 0 { return .failure(Int(rv)) } t.pointee.tv_sec = now.tv_sec t.pointee.tv_nsec = Int(now.tv_usec) * 1000 return .success } #if os(Linux) import Glibc #else import Darwin #endif
529b6f5606dae1658ac0902938ce28e4
33.186486
135
0.654992
false
false
false
false
tinypass/piano-sdk-for-ios
refs/heads/master
PianoAPI/Models/UserDto.swift
apache-2.0
1
import Foundation @objc(PianoAPIUserDto) public class UserDto: NSObject, Codable { /// User&#39;s UID @objc public var uid: String? = nil /// User&#39;s email address @objc public var email: String? = nil /// User&#39;s first name @objc public var firstName: String? = nil /// User&#39;s last name @objc public var lastName: String? = nil /// User&#39;s personal name @objc public var personalName: String? = nil /// User creation date @objc public var createDate: Date? = nil public enum CodingKeys: String, CodingKey { case uid = "uid" case email = "email" case firstName = "first_name" case lastName = "last_name" case personalName = "personal_name" case createDate = "create_date" } }
7a1ea764f251012f04acefc7c4b80799
24.03125
48
0.615481
false
false
false
false
CartoDB/mobile-ios-samples
refs/heads/master
AdvancedMap.Objective-C/AdvancedMap/Device.swift
bsd-2-clause
1
// // Device.swift // AdvancedMap.Swift // // Created by Aare Undo on 20/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit @objc class Device : NSObject { @objc static func isLandscape() -> Bool { return UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight } @objc static func isTablet() -> Bool { return UIDevice.current.userInterfaceIdiom == .pad } @objc static func navigationbarHeight() -> CGFloat { return ((UIApplication.shared.delegate as! AppDelegate).navigationController?.navigationBar.frame.height)! } @objc static func statusBarHeight() -> CGFloat { return UIApplication.shared.statusBarFrame.height } @objc static func trueY0() -> CGFloat { return navigationbarHeight() + statusBarHeight() } }
659fc6db1754ebe4759fa893ee6281ea
26.393939
114
0.662611
false
false
false
false
vimask/ClientCodeGen
refs/heads/master
ClientCodeGen/Misc/ApiClient.swift
mit
1
// // ApiClient.swift // JSONExport // // Created by Vinh Vo on 4/19/17. // Copyright © 2017 Vinh Vo. All rights reserved. // import Foundation typealias ServiceResponse = (_ success: Bool, _ jsonString: String?) -> () enum HttpMethod:String { case get = "GET" case post = "POST" case put = "PUT" case detele = "DELETE" } class ApiClient{ static let shared = ApiClient() // MARK: - Perform a GET Request func makeGetRequest(strURL:String, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) { let urlRequest = clientURLRequest(urlString: strURL, headers: headers) get(request: urlRequest) { (result, jsonString) in runOnUiThread{ onCompletion(result, jsonString) } } } // MARK: - Perform a POST Request func makePostRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) { let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers) post(request: urlRequest) { (result, jsonString) in runOnUiThread{ onCompletion(result, jsonString) } } } // MARK: - Perform a PUST Request func makePutRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) { let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers) put(request: urlRequest) { (result, jsonString) in runOnUiThread{ onCompletion(result, jsonString) } } } // MARK: - Perform a DELETE Request func makeDeleteRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) { let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers) delete(request: urlRequest) { (result, jsonString) in runOnUiThread{ onCompletion(result, jsonString) } } } // MARK: - private func clientURLRequest(urlString: String, params:[String:Any]? = nil, headers:[String:Any]? = nil) -> NSMutableURLRequest { let request = NSMutableURLRequest(url: URL(string: urlString)!) //set params if let params = params { // var paramString = "" // for (key, value) in params { // let escapedKey = key.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) // let escapedValue = (value as AnyObject).addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) // paramString += "\(String(describing: escapedKey))=\(String(describing: escapedValue))&" // } do{ request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) // request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") } catch let error as NSError { print(error) } } //set headers if let headers = headers { for (key,value) in headers { request.setValue("\(value)", forHTTPHeaderField: key) } } return request } // MARK: - private func post(request: NSMutableURLRequest, completion: @escaping ServiceResponse) { dataTask(request: request, method: "POST", completion: completion) } private func put(request: NSMutableURLRequest, completion: @escaping ServiceResponse) { dataTask(request: request, method: "PUT", completion: completion) } private func get(request: NSMutableURLRequest, completion: @escaping ServiceResponse) { dataTask(request: request, method: "GET", completion: completion) } private func delete(request: NSMutableURLRequest, completion: @escaping ServiceResponse) { dataTask(request: request, method: "DELETE", completion: completion) } // MARK: - Data task private func dataTask(request: NSMutableURLRequest, method: String, completion: @escaping ServiceResponse) { request.httpMethod = method let session = URLSession(configuration: URLSessionConfiguration.default) session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in if let data = data { var jsonString = String(data: data, encoding: String.Encoding.utf8) do { let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: []) let data1 = try JSONSerialization.data(withJSONObject: jsonData, options: JSONSerialization.WritingOptions.prettyPrinted) jsonString = String(data: data1, encoding: String.Encoding.utf8) } catch let error as NSError { print(error) } if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode { completion(true, jsonString ) } else { completion(false, jsonString) } } }.resume() } }
39b181ecf173b14202dc9dba37eb56af
36.096154
142
0.577328
false
false
false
false
1170197998/STVideoPlayer
refs/heads/dev
02-FontChange/Pods/SnapKit/Source/LayoutConstraintItem.swift
apache-2.0
261
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public protocol LayoutConstraintItem: class { } @available(iOS 9.0, OSX 10.11, *) extension ConstraintLayoutGuide : LayoutConstraintItem { } extension ConstraintView : LayoutConstraintItem { } extension LayoutConstraintItem { internal func prepare() { if let view = self as? ConstraintView { view.translatesAutoresizingMaskIntoConstraints = false } } internal var superview: ConstraintView? { if let view = self as? ConstraintView { return view.superview } if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { return guide.owningView } return nil } internal var constraints: [Constraint] { return self.constraintsSet.allObjects as! [Constraint] } internal func add(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.add(constraint) } } internal func remove(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.remove(constraint) } } private var constraintsSet: NSMutableSet { let constraintsSet: NSMutableSet if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { constraintsSet = existing } else { constraintsSet = NSMutableSet() objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraintsSet } } private var constraintsKey: UInt8 = 0
8a8d45aad301c240318a319bf1726936
31.354839
111
0.67564
false
false
false
false
sivakumarscorpian/INTPushnotification1
refs/heads/master
REIOSSDK/REiosViews.swift
mit
1
// // ResulticksViews.swift // INTPushNotification // // Created by Sivakumar on 14/9/17. // Copyright © 2017 Interakt. All rights reserved. // import UIKit class REiosViews: NSObject { // MARK: Show quick survey class func addQuickSurvey() { let podBundle = Bundle(for: REiosRatingVc.self) let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle") let bundle = Bundle(url: bundleURL!) let storyboard = UIStoryboard(name: "INTMain", bundle: bundle) let childView = storyboard.instantiateViewController(withIdentifier: "SIDQuickSurvey") as! REiosQuickSurveyVc if let topVc:UIViewController = UIApplication.topViewController() { topVc.addChildViewController(childView) childView.view.frame = topVc.view.bounds topVc.view.addSubview(childView.view) topVc.navigationController?.isNavigationBarHidden = true childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childView.didMove(toParentViewController: topVc) topVc.navigationController?.isNavigationBarHidden = true } } // MARK: Show rating class func addRatingChildView() { let podBundle = Bundle(for: REiosRatingVc.self) let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle") let bundle = Bundle(url: bundleURL!) let storyboard = UIStoryboard(name: "INTMain", bundle: bundle) let childView = storyboard.instantiateViewController(withIdentifier: "SIDRating") as! REiosRatingVc if let topVc:UIViewController = UIApplication.topViewController() { topVc.addChildViewController(childView) childView.view.frame = topVc.view.bounds topVc.view.addSubview(childView.view) topVc.navigationController?.isNavigationBarHidden = true childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childView.didMove(toParentViewController: topVc) topVc.navigationController?.isNavigationBarHidden = true } } // MARK: Show rich image class func addRichImage() { let podBundle = Bundle(for: REiosRatingVc.self) let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle") let bundle = Bundle(url: bundleURL!) let storyboard = UIStoryboard(name: "INTMain", bundle: bundle) let childView = storyboard.instantiateViewController(withIdentifier: "SIDRichImage") as! REiosRichImageVc if let topVc:UIViewController = UIApplication.topViewController() { topVc.addChildViewController(childView) childView.view.frame = topVc.view.bounds topVc.view.addSubview(childView.view) topVc.navigationController?.isNavigationBarHidden = true childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] childView.didMove(toParentViewController: topVc) topVc.navigationController?.isNavigationBarHidden = true } } }
274e11265225d25bf61c3b0644cc3e73
39.075
117
0.661572
false
false
false
false
HeartOfCarefreeHeavens/TestKitchen_pww
refs/heads/master
TestKitchen/TestKitchen/classes/cookbook/homePage/controller/CookbookViewController.swift
mit
1
// // CookbookViewController.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class CookbookViewController: BaseViewController { //滚动视图 var scrollView:UIScrollView? //食材首页推荐视图 private var recommendView:CBRecommendView? //首页食材视图 private var foodView:CBMaterialView? //首页分类视图 private var categoryView:CBMaterialView? //导航的标题视图 private var segCtrl:KTCSegmentCtrl? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createMyNav() self.createHomePageView() downloadRecommendData() downloadFoodData() downloadCategoryData() } //下载分类的数据 func downloadCategoryData(){ let params = ["methodName":"CategoryIndex"] let downloader = KTCDownloder() downloader.delegate = self downloader.type = .Category downloader.postWithUrl(kHostUrl, params: params) } //下载食材的数据 func downloadFoodData(){ //参数 let dict = ["methodName":"MaterialSubtype"] let downloader = KTCDownloder() downloader.delegate = self downloader.type = .FoodMaterial downloader.postWithUrl(kHostUrl, params: dict) } //初始化视图 func createHomePageView(){ self.automaticallyAdjustsScrollViewInsets = false //1.创建滚动视图 scrollView = UIScrollView() scrollView!.pagingEnabled = true scrollView!.showsHorizontalScrollIndicator = false scrollView?.delegate = self view.addSubview(scrollView!) //给滚动视图添加约束 scrollView!.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0)) } //2.创建容器视图 let containerView = UIView.createView() scrollView!.addSubview(containerView) containerView.snp_makeConstraints { (make) in make.edges.equalTo(self.scrollView!) make.height.equalTo(self.scrollView!) } //推荐 recommendView = CBRecommendView() containerView.addSubview(recommendView!) recommendView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo(containerView) }) //食材 foodView = CBMaterialView() foodView?.backgroundColor = UIColor.redColor() containerView.addSubview(foodView!) foodView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((recommendView?.snp_right)!) }) //分类 categoryView = CBMaterialView() categoryView?.backgroundColor = UIColor.purpleColor() containerView.addSubview(categoryView!) categoryView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((foodView?.snp_right)!) }) //修改容器视图的大小 containerView.snp_makeConstraints { (make) in make.right.equalTo(categoryView!) } } //下载推荐数据 func downloadRecommendData(){ let dict = ["methodName":"SceneHome"] let downloader = KTCDownloder() downloader.type = .Recommend downloader.delegate = self downloader.postWithUrl(kHostUrl, params: dict) } //导航视图 func createMyNav(){ //标题位置 segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"]) navigationItem.titleView = segCtrl //设置代理 segCtrl?.delegate = self //扫一扫功能 addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true) //搜索功能 addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false) } func scanAction(){ } func searchAction(){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //首页推荐的部分的方法 //食材课程分集显示 func gotoFoodCoursePage(link:String){ let startRange = NSString(string: link).rangeOfString("#") let endRange = NSString(string: link).rangeOfString("#", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, link.characters.count),locale:nil) let id = NSString(string: link).substringWithRange(NSMakeRange(startRange.location+1, endRange.location-startRange.location-1)) //跳转界面 let foodCourseCtrl = FoodCourseController() foodCourseCtrl.serialId = id navigationController?.pushViewController(foodCourseCtrl, animated: true) } //显示首页推荐的数据 func showRecommendData(model:CBRecommendModel){ recommendView?.model = model //点击事件 recommendView?.clickClosure = { (title:String?,link:String) in if link.hasPrefix("app://food_course_series") == true { //食材课程分集显示 //第一个# self.gotoFoodCoursePage(link) } } } /* // 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. } */ } extension CookbookViewController:KTCDownloaderDelegate{ func downloader(downloader: KTCDownloder, didFailWithError error: NSError) { } func downloader(downloader: KTCDownloder, didFinishWithData data: NSData?) { if downloader.type == .Recommend { if let jsonData = data { let model = CBRecommendModel.parseModel(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self?.showRecommendData(model) }) } }else if downloader.type == .FoodMaterial{ // let str = NSString(data: data!, encoding: NSUTF8StringEncoding) // print(str!) if let jsonData = data { let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self?.foodView?.model = model }) } }else if downloader.type == .Category{ if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) //会主线程刷新 dispatch_async(dispatch_get_main_queue(), { [weak self] in self?.categoryView?.model = model }) } } } } //KTCSegCtrl的代理 extension CookbookViewController:KTCSegmentCtrlDelegate{ func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) { // scrollView?.contentOffset = CGPointMake(kScreenWidth*CGFloat(index), 0) //点击按钮切换视图(有动画效果) scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true) } } //UIScrollView的代理 extension CookbookViewController:UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width) segCtrl?.selectIndex = index } }
8604bf95c5de143e8ab1db948cc8a4aa
26.268371
170
0.561687
false
false
false
false
saku/PixivLTSample
refs/heads/master
PixivLTSample/base/BaseSwiftViewController.swift
mit
1
// // BaseSwiftViewController.swift // PixivLTSample // // Created by saku on 2014/09/28. // Copyright (c) 2014 Yoichiro Sakurai. All rights reserved. // import UIKit class BaseSwiftViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() var button : UIButton; button = UIButton(frame: CGRectMake(0, 0, 200, 40)) button.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 - 100); button.setTitle("showObjcAlert", forState: .Normal) button.setTitleColor(UIColor.blackColor(), forState: .Normal) button.addTarget(self, action: "showObjcAlert", forControlEvents: .TouchUpInside) self.view.addSubview(button) button = UIButton(frame: CGRectMake(0, 0, 200, 40)) button.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 + 100); button.setTitle("showSwiftAlert", forState: .Normal) button.setTitleColor(UIColor.blackColor(), forState: .Normal) button.addTarget(self, action: "showSwiftAlert", forControlEvents: .TouchUpInside) self.view.addSubview(button) } func showObjcAlert() { showObjcAlertView() } func showSwiftAlert() { showSwiftAlertView(self) } }
434cf09ae8882b69adcfaacaf339a325
33.35
109
0.671761
false
false
false
false
ioramashvili/BeforeAfterSlider
refs/heads/master
BeforeAfterSlider/BeforeAfterView.swift
mit
1
import UIKit import Foundation @IBDesignable public class BeforeAfterView: UIView { fileprivate var leading: NSLayoutConstraint! fileprivate var originRect: CGRect! @IBInspectable public var image1: UIImage = UIImage() { didSet { imageView1.image = image1 } } @IBInspectable public var image2: UIImage = UIImage() { didSet { imageView2.image = image2 } } @IBInspectable public var thumbColor: UIColor = UIColor.white { didSet { thumb.backgroundColor = thumbColor } } fileprivate lazy var imageView2: UIImageView = { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false iv.contentMode = .scaleAspectFill iv.clipsToBounds = true return iv }() fileprivate lazy var imageView1: UIImageView = { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false iv.contentMode = .scaleAspectFill iv.clipsToBounds = true return iv }() fileprivate lazy var image1Wrapper: UIView = { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false v.clipsToBounds = true return v }() fileprivate lazy var thumbWrapper: UIView = { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false v.clipsToBounds = true return v }() fileprivate lazy var thumb: UIView = { let v = UIView() v.backgroundColor = UIColor.white v.translatesAutoresizingMaskIntoConstraints = false v.clipsToBounds = true return v }() lazy fileprivate var setupLeadingAndOriginRect: Void = { self.leading.constant = self.frame.width / 2 self.layoutIfNeeded() self.originRect = self.image1Wrapper.frame }() override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override public func layoutSubviews() { super.layoutSubviews() _ = setupLeadingAndOriginRect } } extension BeforeAfterView { fileprivate func initialize() { image1Wrapper.addSubview(imageView1) addSubview(imageView2) addSubview(image1Wrapper) thumbWrapper.addSubview(thumb) addSubview(thumbWrapper) NSLayoutConstraint.activate([ imageView2.topAnchor.constraint(equalTo: topAnchor, constant: 0), imageView2.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0), imageView2.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0), imageView2.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0) ]) leading = image1Wrapper.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0) NSLayoutConstraint.activate([ image1Wrapper.topAnchor.constraint(equalTo: topAnchor, constant: 0), image1Wrapper.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0), image1Wrapper.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0), leading ]) NSLayoutConstraint.activate([ imageView1.topAnchor.constraint(equalTo: image1Wrapper.topAnchor, constant: 0), imageView1.bottomAnchor.constraint(equalTo: image1Wrapper.bottomAnchor, constant: 0), imageView1.trailingAnchor.constraint(equalTo: image1Wrapper.trailingAnchor, constant: 0) ]) NSLayoutConstraint.activate([ thumbWrapper.topAnchor.constraint(equalTo: image1Wrapper.topAnchor, constant: 0), thumbWrapper.bottomAnchor.constraint(equalTo: image1Wrapper.bottomAnchor, constant: 0), thumbWrapper.leadingAnchor.constraint(equalTo: image1Wrapper.leadingAnchor, constant: -20), thumbWrapper.widthAnchor.constraint(equalToConstant: 40) ]) NSLayoutConstraint.activate([ thumb.centerXAnchor.constraint(equalTo: thumbWrapper.centerXAnchor, constant: 0), thumb.centerYAnchor.constraint(equalTo: thumbWrapper.centerYAnchor, constant: 0), thumb.widthAnchor.constraint(equalTo: thumbWrapper.widthAnchor, multiplier: 1), thumb.heightAnchor.constraint(equalTo: thumbWrapper.widthAnchor, multiplier: 1) ]) leading.constant = frame.width / 2 thumb.layer.cornerRadius = 20 imageView1.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true let tap = UIPanGestureRecognizer(target: self, action: #selector(gesture(sender:))) thumbWrapper.isUserInteractionEnabled = true thumbWrapper.addGestureRecognizer(tap) } @objc func gesture(sender: UIPanGestureRecognizer) { let translation = sender.translation(in: self) switch sender.state { case .began, .changed: var newLeading = originRect.origin.x + translation.x newLeading = max(newLeading, 20) newLeading = min(frame.width - 20, newLeading) leading.constant = newLeading layoutIfNeeded() case .ended, .cancelled: originRect = image1Wrapper.frame default: break } } }
dea8eb4a315164cac9b6589ca06eb8b5
32.107784
103
0.639537
false
false
false
false
kouky/Algorithms
refs/heads/master
Algorithms.playground/Pages/List Abstract Data Type.xcplaygroundpage/Contents.swift
mit
1
// List Abstract Data Type // https://en.wikipedia.org/wiki/List_(abstract_data_type) // // The MIT License (MIT) // // Copyright (c) 2015 Michael Koukoullis <http://github.com/kouky> indirect enum List<T> { case Cons(T, List<T>) case Nil } extension List { func head() -> T { switch self { case .Cons(let head, _): return head case .Nil: fatalError("Invalid") } } func tail() -> List { switch self { case .Cons(_, let tail): return tail case .Nil: return List.Nil } } func foldl<U>(start: U, _ f: (U, T) -> U) -> U { switch self { case let .Cons(head, tail): return tail.foldl(f(start, head), f) case .Nil: return start } } func size() -> Int { return self.foldl(0) { (acc, _) -> Int in return acc + 1 } } func reverse() -> List { return self.foldl(List.Nil) { (acc, item) -> List in return List.Cons(item, acc) } } func filter(f: T -> Bool) -> List { let x = self.foldl(List.Nil) { (acc, item) -> List in if f(item) { return List.Cons(item, acc) } else { return acc } } return x.reverse() } func map<U>(f: T -> U) -> List<U> { let x = self.foldl(List<U>.Nil) { (acc: List<U>, item: T) -> List<U> in return List<U>.Cons(f(item), acc) } return x.reverse() } } extension List : CustomStringConvertible { var description: String { switch self { case let .Cons(value, list): return "\(value)," + list.description case .Nil: return "" } } } // Shorthand list construction infix operator ~ { associativity right } func ~ <T> (left: T, right: List<T>) -> List<T> { return List.Cons(left, right) } // Create lists of Int let z = 1 ~ 2 ~ 3 ~ 4 ~ 5 ~ List.Nil z // Create lists of tuples let x = ("grapes", 5) ~ ("apple", 8) ~ List.Nil x // Head and Tail z.head() z.tail() // Foldl z.foldl(0, +) z.foldl(1, *) z.foldl(List.Nil) { (acc, x) in (x * 3) ~ acc } // Functions implemeted with foldl z.size() z.reverse() z.filter { (item) -> Bool in item % 2 == 0 } z.map { (item) -> Int in item * 2 } z.map { (item) -> String in "$\(item).00" }
37f17e6d29ef3896f28f46632c203e91
19.675
79
0.483676
false
false
false
false
librerose/iAdSample
refs/heads/master
src/iAdSample/ViewController.swift
mit
1
// // ViewController.swift // iAdSample // // Created by Meng on 15/11/4. // Copyright © 2015年 Libre Rose. All rights reserved. // import UIKit import iAd class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.edgesForExtendedLayout = .None view.addSubview(tableView) _ = iAdView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var tableView: UITableView { if nil == _tableView { _tableView = UITableView(frame: view.bounds, style: .Plain) } return _tableView! } var _tableView: UITableView? var iAdView: ADBannerView { if nil == _iAdView { _iAdView = ADBannerView(frame: CGRect.zero) _iAdView?.delegate = self } return _iAdView! } var _iAdView: ADBannerView? } extension ViewController: ADBannerViewDelegate { func bannerViewDidLoadAd(banner: ADBannerView!) { tableView.tableHeaderView = banner } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { tableView.tableHeaderView = nil } func bannerViewWillLoadAd(banner: ADBannerView!) { } }
53536dc33e0d6b8ba82b76f7672e7c22
22.836066
89
0.616231
false
false
false
false
StartAppsPe/StartAppsKitExtensions
refs/heads/master
Sources/TableViewExtensions.swift
mit
1
// // TableViewExtensions.swift // StartAppsKitExtensionsPackageDescription // // Created by Gabriel Lanata on 16/10/17. // #if os(iOS) import UIKit extension UITableView { public func updateHeaderViewFrame() { guard let headerView = self.tableHeaderView else { return } headerView.setNeedsLayout() headerView.layoutIfNeeded() let fitSize = CGSize(width: self.frame.size.width, height: 3000) let height = headerView.systemLayoutSizeFitting(fitSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow).height var headerViewFrame = headerView.frame headerViewFrame.size.height = height headerView.frame = headerViewFrame self.tableHeaderView = headerView } public func updateFooterViewFrame() { guard let footerView = self.tableFooterView else { return } footerView.setNeedsLayout() footerView.layoutIfNeeded() let fitSize = CGSize(width: self.frame.size.width, height: 3000) let height = footerView.systemLayoutSizeFitting(fitSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow).height var footerViewFrame = footerView.frame footerViewFrame.size.height = height footerView.frame = footerViewFrame self.tableFooterView = footerView } } extension UITableViewCell { public func autoLayoutHeight(_ tableView: UITableView? = nil) -> CGFloat { if let tableView = tableView { // where frame.size.width == 0 { frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width-13, height: 9999) contentView.frame = frame } layoutIfNeeded() let targetSize = CGSize(width: tableView!.frame.size.width-13, height: 10) let size = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority(rawValue: 999)) return size.height+1 } } extension UITableView { public func hideBottomSeparator(showLast: Bool = false) { let inset = separatorInset.left tableFooterView = UIView(frame: CGRect(x: inset, y: 0, width: frame.size.width-inset, height: 0.5)) tableFooterView!.backgroundColor = showLast ? separatorColor : UIColor.clear } public func showBottomSeparator() { tableFooterView = nil } } extension UITableView { public func scrollToTop(animated: Bool) { self.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: animated) } } #endif
8586fb2da43ce38d6fa2738a5d449e0d
36.880952
186
0.570082
false
false
false
false
DrGo/LearningSwift
refs/heads/master
PLAYGROUNDS/APPLE/Patterns.playground/section-19.swift
gpl-3.0
2
let trainOne = Train() let trainTwo = Train() let trainThree = Train() trainTwo.status = .Delayed(minutes: 2) trainThree.status = .Delayed(minutes: 8)
876b6d2c9849d60804651e7ff224aa18
24.333333
40
0.728477
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/ServiceTerms/Modal/Modal/ServiceTermsModalScreenViewModel.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh Modal/Show ServiceTermsModalScreen /* Copyright 2019 New Vector Ltd 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 final class ServiceTermsModalScreenViewModel: ServiceTermsModalScreenViewModelType { // MARK: - Properties // MARK: Private private let serviceTerms: MXServiceTerms // MARK: Public var serviceUrl: String { return serviceTerms.baseUrl } var serviceType: MXServiceType { return serviceTerms.serviceType } var policies: [MXLoginPolicyData]? var alreadyAcceptedPoliciesUrls: [String] = [] weak var viewDelegate: ServiceTermsModalScreenViewModelViewDelegate? weak var coordinatorDelegate: ServiceTermsModalScreenViewModelCoordinatorDelegate? // MARK: - Setup init(serviceTerms: MXServiceTerms) { self.serviceTerms = serviceTerms } // MARK: - Public func process(viewAction: ServiceTermsModalScreenViewAction) { switch viewAction { case .load: self.loadTerms() case .display(let policy): self.coordinatorDelegate?.serviceTermsModalScreenViewModel(self, displayPolicy: policy) case .accept: self.acceptTerms() case .decline: self.coordinatorDelegate?.serviceTermsModalScreenViewModelDidDecline(self) } } // MARK: - Private private func loadTerms() { self.update(viewState: .loading) self.serviceTerms.terms({ [weak self] (terms, alreadyAcceptedTermsUrls) in guard let self = self else { return } let policies = self.processTerms(terms: terms) self.policies = policies self.alreadyAcceptedPoliciesUrls = alreadyAcceptedTermsUrls ?? [] self.update(viewState: .loaded(policies: policies, alreadyAcceptedPoliciesUrls: self.alreadyAcceptedPoliciesUrls)) }, failure: { [weak self] error in guard let self = self else { return } self.update(viewState: .error(error)) }) } private func acceptTerms() { self.update(viewState: .loading) self.serviceTerms.agree(toTerms: self.termsUrls, success: { [weak self] in guard let self = self else { return } self.update(viewState: .accepted) // Send a notification to update the identity service immediately. if self.serviceTerms.serviceType == MXServiceTypeIdentityService { let userInfo = [MXIdentityServiceNotificationIdentityServerKey: self.serviceTerms.baseUrl] NotificationCenter.default.post(name: .MXIdentityServiceTermsAccepted, object: nil, userInfo: userInfo) } // Notify the delegate. self.coordinatorDelegate?.serviceTermsModalScreenViewModelDidAccept(self) }, failure: { [weak self] (error) in guard let self = self else { return } self.update(viewState: .error(error)) }) } private func processTerms(terms: MXLoginTerms?) -> [MXLoginPolicyData] { if let policies = terms?.policiesData(forLanguage: Bundle.mxk_language(), defaultLanguage: Bundle.mxk_fallbackLanguage()) { return policies } else { MXLog.debug("[ServiceTermsModalScreenViewModel] processTerms: Error: No terms for \(String(describing: terms))") return [] } } private var termsUrls: [String] { guard let policies = self.policies else { return [] } return policies.map({ return $0.url }) } private func update(viewState: ServiceTermsModalScreenViewState) { self.viewDelegate?.serviceTermsModalScreenViewModel(self, didUpdateViewState: viewState) } }
35b2526d634f4ba2562457981a1da9ca
32.014706
131
0.642094
false
false
false
false
007HelloWorld/DouYuZhiBo
refs/heads/1.0.0
06-Touch ID /Pods/Alamofire/Source/Response.swift
agpl-3.0
359
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
19165cfb394207e9605c62d35fd4d9c8
37.32043
119
0.65823
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
test/SILGen/external_definitions.swift
apache-2.0
4
// RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen | FileCheck %s // REQUIRES: objc_interop import ansible var a = NSAnse(Ansible(bellsOn: NSObject())) var anse = NSAnse hasNoPrototype() // CHECK-LABEL: sil @main // -- Foreign function is referenced with C calling conv and ownership semantics // CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible> // CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @_TFCSo7AnsibleC // CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject // CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]] // CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]]) // CHECK: release_value [[ANSIBLE]] : $ImplicitlyUnwrappedOptional<Ansible> // -- Referencing unapplied C function goes through a thunk // CHECK: [[NSANSE:%.*]] = function_ref @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible> // -- Referencing unprototyped C function passes no parameters // CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> () // CHECK: apply [[NOPROTO]]() // -- Constructors for imported Ansible // CHECK-LABEL: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<AnyObject>, @thick Ansible.Type) -> @owned ImplicitlyUnwrappedOptional<Ansible> // -- Constructors for imported NSObject // CHECK-LABEL: sil shared @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject // -- Native Swift thunk for NSAnse // CHECK: sil shared @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible> { // CHECK: bb0(%0 : $ImplicitlyUnwrappedOptional<Ansible>): // CHECK: %1 = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible> // CHECK: %2 = apply %1(%0) : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible> // CHECK: release_value %0 : $ImplicitlyUnwrappedOptional<Ansible> // CHECK: return %2 : $ImplicitlyUnwrappedOptional<Ansible> // CHECK: } // -- Constructor for imported Ansible was unused, should not be emitted. // CHECK-NOT: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@thick Ansible.Type) -> @owned Ansible
f52b0bd35c09b7ae911b4a4254551861
56.377778
193
0.711851
false
false
false
false
thecb4/SwiftCRUD
refs/heads/master
Example/Tests/ModelSpec.swift
mit
1
// // ModelSpec.swift // KanoMapp // // Created by Cavelle Benjamin on 28/2/15. // Copyright (c) 2015 The CB4. All rights reserved. // import Quick import Nimble import SwiftCRUD_Example import SwiftCRUD import CoreData class CRUDHelper { var name:String! var type:NSManagedObject.Type var count = 0 init(type:NSManagedObject.Type, name:String!) { self.type = type self.name = name } func crudClass<T>() -> T { return type as! T } func params() -> Dictionary<String,AnyObject> { var _params:[String:AnyObject] = [:] switch name { case "SuperHero": _params["name"] = "Scarlet Witch" _params["name"] = "Hex" return _params default: () } return Dictionary() } } class SharedCRUDSpecConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("CRUD class") { (sharedExampleContext: SharedExampleContext) in let helper = sharedExampleContext()["crud-class"] as! CRUDHelper let sut = helper.type let sutName = helper.name it("should should have an entity name = \(sutName)") { let expectedName = sutName let actualName = sut.entityName() expect(expectedName).to(equal(actualName)) } it("should have initial count of 0 for entity type as \(sutName)") { sut.deleteAll() let expectedValue = 0 let actualValue = sut.count() expect(actualValue).to(equal(expectedValue)) } it("should create a new entity type with parameters as \(sutName)") { let expectedID = NSNumber(integer: 1) let params = helper.params() let actualID = sut.createWithParameters(params); expect(actualID).to(equal(actualID)) let entity:NSManagedObject = sut.readOne(actualID!)! let paramKey:String = params.keys.first! let actualValue:String = params[paramKey]! as! String let expectedValue:String = entity.valueForKey(paramKey)! as! String expect(expectedValue).to(equal(actualValue)) } it("should create a new entity") { let expectedID = NSNumber(integer: 1) let actualID = sut.create() expect(actualID).to(equal(actualID)) } it("should read an entity of type \(sutName)") { let crudID = sut.create()! let entity:NSManagedObject? = sut.readOne(crudID) expect(entity!).toNot(beNil()) } it("should update an entity of type \(sutName)") { let crudID = sut.create()! let params = helper.params() let updated = sut.updateOne(crudID, params) expect(updated).to(beTrue()) } it("should delete entity of type \(sutName)") { let crudID = sut.create()! let deleted = sut.deleteOne(crudID) expect(deleted).to(beTrue()) let deletedEntity:NSManagedObject? = sut.readOne(crudID) expect(deletedEntity).to(beNil()) } } } } class ProductSpec: QuickSpec { override func spec() { let manager = CoreDataManager.sharedInstance beforeEach { manager.resetContext(); } itBehavesLike("CRUD class") { [ "crud-class" : CRUDHelper(type: SuperHero.self, name: "SuperHero") ] } } }
b914e721b46f224ab6779a067da4b556
22.037736
106
0.56047
false
false
false
false
fhchina/firefox-ios
refs/heads/master
Client/Frontend/Browser/URLBarView.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit private struct URLBarViewUX { static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB) static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2) static let TextFieldContentInset = UIOffsetMake(9, 5) static let LocationLeftPadding = 5 static let LocationHeight = 28 static let LocationContentOffset: CGFloat = 8 static let TextFieldCornerRadius: CGFloat = 3 static let TextFieldBorderWidth: CGFloat = 1 // offset from edge of tabs button static let URLBarCurveOffset: CGFloat = 14 static let URLBarCurveOffsetLeft: CGFloat = -10 // buffer so we dont see edges when animation overshoots with spring static let URLBarCurveBounceBuffer: CGFloat = 8 static let TabsButtonRotationOffset: CGFloat = 1.5 static let TabsButtonHeight: CGFloat = 18.0 static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor { return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha) } } protocol URLBarDelegate: class { func urlBarDidPressTabs(urlBar: URLBarView) func urlBarDidPressReaderMode(urlBar: URLBarView) /// :returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool func urlBarDidPressStop(urlBar: URLBarView) func urlBarDidPressReload(urlBar: URLBarView) func urlBarDidEnterOverlayMode(urlBar: URLBarView) func urlBarDidLeaveOverlayMode(urlBar: URLBarView) func urlBarDidLongPressLocation(urlBar: URLBarView) func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? func urlBarDidPressScrollToTop(urlBar: URLBarView) func urlBar(urlBar: URLBarView, didEnterText text: String) func urlBar(urlBar: URLBarView, didSubmitText text: String) } class URLBarView: UIView { weak var delegate: URLBarDelegate? weak var browserToolbarDelegate: BrowserToolbarDelegate? var helper: BrowserToolbarHelper? var toolbarIsShowing = false /// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown, /// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode /// is *not* tied to the location text field's editing state; for instance, when selecting /// a panel, the first responder will be resigned, yet the overlay mode UI is still active. var inOverlayMode = false lazy var locationView: BrowserLocationView = { let locationView = BrowserLocationView() locationView.setTranslatesAutoresizingMaskIntoConstraints(false) locationView.readerModeState = ReaderModeState.Unavailable locationView.delegate = self return locationView }() private lazy var locationTextField: ToolbarTextField = { let locationTextField = ToolbarTextField() locationTextField.setTranslatesAutoresizingMaskIntoConstraints(false) locationTextField.autocompleteDelegate = self locationTextField.keyboardType = UIKeyboardType.WebSearch locationTextField.autocorrectionType = UITextAutocorrectionType.No locationTextField.autocapitalizationType = UITextAutocapitalizationType.None locationTextField.returnKeyType = UIReturnKeyType.Go locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing locationTextField.backgroundColor = UIColor.whiteColor() locationTextField.font = UIConstants.DefaultMediumFont locationTextField.accessibilityIdentifier = "address" locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.") locationTextField.attributedPlaceholder = self.locationView.placeholder return locationTextField }() private lazy var locationContainer: UIView = { let locationContainer = UIView() locationContainer.setTranslatesAutoresizingMaskIntoConstraints(false) // Enable clipping to apply the rounded edges to subviews. locationContainer.clipsToBounds = true locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth return locationContainer }() private lazy var tabsButton: UIButton = { let tabsButton = InsetButton() tabsButton.setTranslatesAutoresizingMaskIntoConstraints(false) tabsButton.setTitle("0", forState: UIControlState.Normal) tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal) tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor tabsButton.titleLabel?.layer.cornerRadius = 2 tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside) tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar") return tabsButton }() private lazy var progressBar: UIProgressView = { let progressBar = UIProgressView() progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1) progressBar.alpha = 0 progressBar.hidden = true return progressBar }() private lazy var cancelButton: UIButton = { let cancelButton = InsetButton() cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query") cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal) cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside) cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12) cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal) return cancelButton }() private lazy var curveShape: CurveView = { return CurveView() }() private lazy var scrollToTopButton: UIButton = { let button = UIButton() button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside) return button }() lazy var shareButton: UIButton = { return UIButton() }() lazy var bookmarkButton: UIButton = { return UIButton() }() lazy var forwardButton: UIButton = { return UIButton() }() lazy var backButton: UIButton = { return UIButton() }() lazy var stopReloadButton: UIButton = { return UIButton() }() lazy var actionButtons: [UIButton] = { return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton] }() // Used to temporarily store the cloned button so we can respond to layout changes during animation private weak var clonedTabsButton: InsetButton? private var rightBarConstraint: Constraint? private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer var currentURL: NSURL? { get { return locationView.url } set(newURL) { locationView.url = newURL } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0) addSubview(curveShape) addSubview(scrollToTopButton) locationContainer.addSubview(locationView) locationContainer.addSubview(locationTextField) addSubview(locationContainer) addSubview(progressBar) addSubview(tabsButton) addSubview(cancelButton) addSubview(shareButton) addSubview(bookmarkButton) addSubview(forwardButton) addSubview(backButton) addSubview(stopReloadButton) helper = BrowserToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForOverlayModeAndToolbarChanges() } private func setupConstraints() { scrollToTopButton.snp_makeConstraints { make in make.top.equalTo(self) make.left.right.equalTo(self.locationContainer) } progressBar.snp_makeConstraints { make in make.top.equalTo(self.snp_bottom) make.width.equalTo(self) } locationView.snp_makeConstraints { make in make.edges.equalTo(self.locationContainer) } cancelButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) } tabsButton.titleLabel?.snp_makeConstraints { make in make.size.equalTo(URLBarViewUX.TabsButtonHeight) } tabsButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.width.height.equalTo(UIConstants.ToolbarHeight) } curveShape.snp_makeConstraints { make in make.top.left.bottom.equalTo(self) self.rightBarConstraint = make.right.equalTo(self).constraint self.rightBarConstraint?.updateOffset(defaultRightOffset) } locationTextField.snp_makeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } backButton.snp_makeConstraints { make in make.left.centerY.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } forwardButton.snp_makeConstraints { make in make.left.equalTo(self.backButton.snp_right) make.centerY.equalTo(self) make.size.equalTo(backButton) } stopReloadButton.snp_makeConstraints { make in make.left.equalTo(self.forwardButton.snp_right) make.centerY.equalTo(self) make.size.equalTo(backButton) } shareButton.snp_makeConstraints { make in make.right.equalTo(self.bookmarkButton.snp_left) make.centerY.equalTo(self) make.size.equalTo(backButton) } bookmarkButton.snp_makeConstraints { make in make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft) make.centerY.equalTo(self) make.size.equalTo(backButton) } } override func updateConstraints() { super.updateConstraints() if inOverlayMode { // In overlay mode, we always show the location view full width self.locationContainer.snp_remakeConstraints { make in make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding) make.trailing.equalTo(self.cancelButton.snp_leading) make.height.equalTo(URLBarViewUX.LocationHeight) make.centerY.equalTo(self) } } else { self.locationContainer.snp_remakeConstraints { make in if self.toolbarIsShowing { // If we are showing a toolbar, show the text field next to the forward button make.leading.equalTo(self.stopReloadButton.snp_trailing) make.trailing.equalTo(self.shareButton.snp_leading) } else { // Otherwise, left align the location view make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding) make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14) } make.height.equalTo(URLBarViewUX.LocationHeight) make.centerY.equalTo(self) } } } // Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without // However, switching views dynamically at runtime is a difficult. For now, we just use one view // that can show in either mode. func setShowToolbar(shouldShow: Bool) { toolbarIsShowing = shouldShow setNeedsUpdateConstraints() // when we transition from portrait to landscape, calling this here causes // the constraints to be calculated too early and there are constraint errors if !toolbarIsShowing { updateConstraintsIfNeeded() } updateViewsForOverlayModeAndToolbarChanges() } func updateAlphaForSubviews(alpha: CGFloat) { self.tabsButton.alpha = alpha self.locationContainer.alpha = alpha self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha) self.actionButtons.map { $0.alpha = alpha } } func updateTabCount(count: Int) { // make a 'clone' of the tabs button let newTabsButton = InsetButton() self.clonedTabsButton = newTabsButton newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside) newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal) newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor newTabsButton.titleLabel?.layer.cornerRadius = 2 newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center newTabsButton.setTitle(count.description, forState: .Normal) addSubview(newTabsButton) newTabsButton.titleLabel?.snp_makeConstraints { make in make.size.equalTo(URLBarViewUX.TabsButtonHeight) } newTabsButton.snp_makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.trailing.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } newTabsButton.frame = tabsButton.frame // Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be // a rotation around a non-origin point if let labelFrame = newTabsButton.titleLabel?.frame { let halfTitleHeight = CGRectGetHeight(labelFrame) / 2 var newFlipTransform = CATransform3DIdentity newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0) newFlipTransform.m34 = -1.0 / 200.0 // add some perspective newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0) newTabsButton.titleLabel?.layer.transform = newFlipTransform var oldFlipTransform = CATransform3DIdentity oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0) oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0) UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { _ in newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity self.tabsButton.titleLabel?.layer.transform = oldFlipTransform self.tabsButton.titleLabel?.layer.opacity = 0 }, completion: { _ in // remove the clone and setup the actual tab button newTabsButton.removeFromSuperview() self.tabsButton.titleLabel?.layer.opacity = 1 self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity self.tabsButton.setTitle(count.description, forState: UIControlState.Normal) self.tabsButton.accessibilityValue = count.description self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar") }) } } func updateProgressBar(progress: Float) { if progress == 1.0 { self.progressBar.setProgress(progress, animated: true) UIView.animateWithDuration(1.5, animations: { self.progressBar.alpha = 0.0 }, completion: { _ in self.progressBar.setProgress(0.0, animated: false) }) } else { self.progressBar.alpha = 1.0 self.progressBar.setProgress(progress, animated: (progress > progressBar.progress)) } } func updateReaderModeState(state: ReaderModeState) { locationView.readerModeState = state } func setAutocompleteSuggestion(suggestion: String?) { locationTextField.setAutocompleteSuggestion(suggestion) } func enterOverlayMode(locationText: String?, pasted: Bool) { if pasted { // Clear any existing text, focus the field, then set the actual pasted text. // This avoids highlighting all of the text. locationTextField.text = "" locationTextField.becomeFirstResponder() locationTextField.text = locationText } else { // Copy the current URL to the editable text field, then activate it. locationTextField.text = locationText locationTextField.becomeFirstResponder() } // Show the overlay mode UI, which includes hiding the locationView and replacing it // with the editable locationTextField. animateToOverlayState(true) delegate?.urlBarDidEnterOverlayMode(self) } func leaveOverlayMode() { locationTextField.resignFirstResponder() animateToOverlayState(false) delegate?.urlBarDidLeaveOverlayMode(self) } func prepareOverlayAnimation() { // Make sure everything is showing during the transition (we'll hide it afterwards). self.cancelButton.hidden = false self.progressBar.hidden = false self.locationTextField.hidden = false self.shareButton.hidden = !self.toolbarIsShowing self.bookmarkButton.hidden = !self.toolbarIsShowing self.forwardButton.hidden = !self.toolbarIsShowing self.backButton.hidden = !self.toolbarIsShowing self.stopReloadButton.hidden = !self.toolbarIsShowing } func transitionToOverlay() { self.cancelButton.alpha = inOverlayMode ? 1 : 0 self.progressBar.alpha = inOverlayMode ? 0 : 1 self.locationTextField.alpha = inOverlayMode ? 1 : 0 self.shareButton.alpha = inOverlayMode ? 0 : 1 self.bookmarkButton.alpha = inOverlayMode ? 0 : 1 self.forwardButton.alpha = inOverlayMode ? 0 : 1 self.backButton.alpha = inOverlayMode ? 0 : 1 self.stopReloadButton.alpha = inOverlayMode ? 0 : 1 let borderColor = inOverlayMode ? URLBarViewUX.TextFieldActiveBorderColor : URLBarViewUX.TextFieldBorderColor locationContainer.layer.borderColor = borderColor.CGColor if inOverlayMode { self.cancelButton.transform = CGAffineTransformIdentity let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0) self.tabsButton.transform = tabsButtonTransform self.clonedTabsButton?.transform = tabsButtonTransform self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width) // Make the editable text field span the entire URL bar, covering the lock and reader icons. self.locationTextField.snp_remakeConstraints { make in make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset) make.top.bottom.trailing.equalTo(self.locationContainer) } } else { self.tabsButton.transform = CGAffineTransformIdentity self.clonedTabsButton?.transform = CGAffineTransformIdentity self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0) self.rightBarConstraint?.updateOffset(defaultRightOffset) // Shrink the editable text field back to the size of the location view before hiding it. self.locationTextField.snp_remakeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } } } func updateViewsForOverlayModeAndToolbarChanges() { self.cancelButton.hidden = !inOverlayMode self.progressBar.hidden = inOverlayMode self.locationTextField.hidden = !inOverlayMode self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode } func animateToOverlayState(overlay: Bool) { prepareOverlayAnimation() layoutIfNeeded() inOverlayMode = overlay UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: nil, animations: { _ in self.transitionToOverlay() self.setNeedsUpdateConstraints() self.layoutIfNeeded() }, completion: { _ in self.updateViewsForOverlayModeAndToolbarChanges() }) } func SELdidClickAddTab() { delegate?.urlBarDidPressTabs(self) } func SELdidClickCancel() { leaveOverlayMode() } func SELtappedScrollToTopArea() { delegate?.urlBarDidPressScrollToTop(self) } } extension URLBarView: BrowserToolbarProtocol { func updateBackStatus(canGoBack: Bool) { backButton.enabled = canGoBack } func updateForwardStatus(canGoForward: Bool) { forwardButton.enabled = canGoForward } func updateBookmarkStatus(isBookmarked: Bool) { bookmarkButton.selected = isBookmarked } func updateReloadStatus(isLoading: Bool) { if isLoading { stopReloadButton.setImage(helper?.ImageStop, forState: .Normal) stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted) } else { stopReloadButton.setImage(helper?.ImageReload, forState: .Normal) stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted) } } func updatePageStatus(#isWebPage: Bool) { bookmarkButton.enabled = isWebPage stopReloadButton.enabled = isWebPage shareButton.enabled = isWebPage } override var accessibilityElements: [AnyObject]! { get { if inOverlayMode { return [locationTextField, cancelButton] } else { if toolbarIsShowing { return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar] } else { return [locationView, tabsButton, progressBar] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: BrowserLocationViewDelegate { func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) { enterOverlayMode(locationView.url?.absoluteString, pasted: false) } func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) { delegate?.urlBarDidLongPressLocation(self) } func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReload(self) } func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressStop(self) } func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReaderMode(self) } func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didSubmitText: locationTextField.text) return true } func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) { delegate?.urlBar(self, didEnterText: text) } func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) { autocompleteTextField.highlightAll() } func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didEnterText: "") return true } } /* Code for drawing the urlbar curve */ // Curve's aspect ratio private let ASPECT_RATIO = 0.729 // Width multipliers private let W_M1 = 0.343 private let W_M2 = 0.514 private let W_M3 = 0.49 private let W_M4 = 0.545 private let W_M5 = 0.723 // Height multipliers private let H_M1 = 0.25 private let H_M2 = 0.5 private let H_M3 = 0.72 private let H_M4 = 0.961 /* Code for drawing the urlbar curve */ private class CurveView: UIView { private lazy var leftCurvePath: UIBezierPath = { var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true) leftArc.addLineToPoint(CGPoint(x: 0, y: 0)) leftArc.addLineToPoint(CGPoint(x: 0, y: 5)) leftArc.closePath() return leftArc }() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.opaque = false self.contentMode = .Redraw } private func getWidthForHeight(height: Double) -> Double { return height * ASPECT_RATIO } private func drawFromTop(path: UIBezierPath) { let height: Double = Double(UIConstants.ToolbarHeight) let width = getWidthForHeight(height) var from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0)) path.moveToPoint(CGPoint(x: from.0, y: from.1)) path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2), controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1), controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1)) path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height), controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3), controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4)) } private func getPath() -> UIBezierPath { let path = UIBezierPath() self.drawFromTop(path) path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight)) path.addLineToPoint(CGPoint(x: self.frame.width, y: 0)) path.addLineToPoint(CGPoint(x: 0, y: 0)) path.closePath() return path } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) CGContextClearRect(context, rect) CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor) getPath().fill() leftCurvePath.fill() CGContextDrawPath(context, kCGPathFill) CGContextRestoreGState(context) } } private class ToolbarTextField: AutocompleteTextField { override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
e41ac7e2845657c0a77831a76827dbba
40.691877
198
0.687483
false
false
false
false
magi82/MGUtils
refs/heads/master
Sources/Commons/etc/CommonReactive.swift
mit
1
// // CommonReactive.swift // Common // // Created by Byung Kook Hwang on 2017. 9. 21.. // Copyright © 2017년 apptube. All rights reserved. // import Foundation import RxSwift import RxCocoa extension Reactive where Base: UIImageView { public var isHighlight: Binder<Bool> { return Binder(self.base) { view, highlight in view.isHighlighted = highlight } } } extension Reactive where Base: UIControl { public var tap: ControlEvent<Void> { return controlEvent(.touchUpInside) } } extension Reactive where Base: UICollectionViewFlowLayout { public var footerSize: Binder<CGSize> { return Binder(self.base) { view, size in view.footerReferenceSize = size } } } extension Reactive where Base: UIButton { public var selectedTitle: Binder<(title: String, selectedText: String)> { return Binder(self.base) { view, value in view.setTitle(value.title, for: .normal) view.isSelected = (value.title != value.selectedText) } } } extension Reactive where Base: UIViewController { public func popVC(animated: Bool = true) -> Binder<Void> { return Binder(self.base) { (view, _) -> () in view.navigationController?.popViewController(animated: animated) } } public func pushVC(animated: Bool = true) -> Binder<ProvideObjectProtocol> { return Binder(self.base) { (view, object) -> () in view.navigationController?.pushViewController(object.viewController, animated: animated) } } public func dismiss(animated: Bool = true, completion: (() -> Void)? = nil) -> Binder<Void> { return Binder(self.base) { (view, _) -> () in view.dismiss(animated: animated, completion: completion) } } public func present(animated: Bool = true, completion: (() -> Void)? = nil) -> Binder<ProvideObjectProtocol> { return Binder(self.base) { (view, object) -> () in view.present(object.viewController, animated: animated, completion: completion) } } }
35bddde0c7e0d256d4c5505471482686
26.873239
112
0.675594
false
false
false
false
SpiciedCrab/MGRxKitchen
refs/heads/master
Example/MGRxKitchen/TableViewTestViewModel.swift
mit
1
// // TableViewTestViewModel.swift // RxMogo // // Created by Harly on 2017/8/7. // Copyright © 2017年 Harly. All rights reserved. // import UIKit import RxCocoa import RxSwift import MGRxActivityIndicator import MGRxKitchen import MGBricks import Result internal class MGItem { var name: String = "" init(str: String) { name = str } } internal class TableViewTestViewModel: HaveRequestRx, PageableJSONRequest, PageExtensible { var pageOutputer: PublishSubject<MGPage> = PublishSubject<MGPage>() typealias PageJSONType = SuperDemo var jsonOutputer: PublishSubject<SuperDemo> = PublishSubject<SuperDemo>() var loadingActivity: ActivityIndicator = ActivityIndicator() var errorProvider: PublishSubject<RxMGError> = PublishSubject<RxMGError>() var firstPage: PublishSubject<Void> = PublishSubject() var nextPage: PublishSubject<Void> = PublishSubject() //Output var finalPageReached: PublishSubject<Void> = PublishSubject() let disposeBag: DisposeBag = DisposeBag() let service: MockService = MockService() var serviceDriver: Observable<[Demo]>! init() { } func initial() { // pagedRequest(request: <#T##(MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>#>) // let requestObser: Observable<Result<([Demo], MGPage), MGAPIError>> = interuptPage(origin: self.service.providePageJSONMock(on: 1)) { json -> [Demo] in // return json.demos // } // // serviceDriver = pagedRequest(request: { _ in requestObser }) serviceDriver = pagedRequest(request: { page -> Observable<Result<([String : Any], MGPage), MGAPIError>> in return self.service.providePageJSONMock(on: page.currentPage) }) { json -> [Demo] in return json.demos } } func sectionableData() -> Observable<[MGSection<MGItem>]> { let item1 = MGItem(str: "1") let item2 = MGItem(str: "2") let item3 = MGItem(str: "4") let item4 = MGItem(str: "5") let section1 = MGSection(header: "header1", items: [item1, item2]) let section2 = MGSection(header: "header2", items: [item3, item4]) return Observable.of([section1, section2]) } }
4a9f280c1f2c21398da83ec2b4335414
26.108434
160
0.660444
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
06-Daily/code/Daily/IBAnimatable/ActivityIndicatorAnimationLineScaleParty.swift
gpl-3.0
5
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationLineScaleParty: ActivityIndicatorAnimating { // MARK: Properties fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 7 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations: [CFTimeInterval] = [1.26, 0.43, 1.01, 0.73] let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0.77, 0.29, 0.28, 0.74] // Animation let animation = self.animation for i in 0..<4 { let line = ActivityIndicatorShape.line.makeLayer(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] animation.duration = durations[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } } // MARK: - Setup private extension ActivityIndicatorAnimationLineScaleParty { var animation: CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath:"transform.scale") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.5, 1] animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } }
ce2aaebf8bddc1ae3ffe774f0b8ec474
31.673077
120
0.701001
false
false
false
false
Automattic/Automattic-Tracks-iOS
refs/heads/trunk
Sources/Remote Logging/Crash Logging/TestHelpers.swift
gpl-2.0
1
import Foundation import ObjectiveC import Sentry typealias EventLoggingCallback = (Event) -> () typealias ShouldSendEventCallback = (Event?, Bool) -> () private var errorLoggingCallback: EventLoggingCallback? = nil private var messageLoggingCallback: EventLoggingCallback? = nil private var eventSendCallback: ShouldSendEventCallback? = nil internal extension CrashLoggingDataProvider { var didLogErrorCallback: EventLoggingCallback? { get { return errorLoggingCallback } set { errorLoggingCallback = newValue } } var didLogMessageCallback: EventLoggingCallback? { get { return messageLoggingCallback } set { messageLoggingCallback = newValue } } }
3b46783acbf5bcc6363b77a93cf9cd31
29.565217
63
0.755334
false
false
false
false
ubi-naist/SenStick
refs/heads/master
SenStickSDK/SenStickSDK/UVSensorService.swift
mit
1
// // UVSensorService.swift // SenStickSDK // // Created by AkihiroUehara on 2016/05/24. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import Foundation public enum UVSensorRange : UInt16, CustomStringConvertible { case uvRangeDefault = 0x00 public var description : String { switch self { case .uvRangeDefault: return "uvRangeDefault" } } } struct UVRawData { var rawValue : UInt16 init(rawValue:UInt16) { self.rawValue = rawValue } // 物理センサーの1uW/cm^2あたりのLBSの値 static func getLSBperuWcm2(_ range: UVSensorRange) -> Double { switch range { case .uvRangeDefault: return (1.0 / 5.0) } } static func unpack(_ data: [Byte]) -> UVRawData { let value = UInt16.unpack(data[0..<2]) return UVRawData(rawValue: value!) } } public struct UVSensorData : SensorDataPackableType { public var uv: Double public init(uv: Double) { self.uv = uv } public typealias RangeType = UVSensorRange public static func unpack(_ range:UVSensorRange, value: [UInt8]) -> UVSensorData? { guard value.count >= 2 else { return nil } let rawData = UVRawData.unpack(value) let LSBperuWcm = UVRawData.getLSBperuWcm2(range) //debugPrint("\(rawData), LSBperuWcm:\(LSBperuWcm)") return UVSensorData(uv: (Double(rawData.rawValue) / LSBperuWcm)); } } // センサー各種のベースタイプ, Tはセンサデータ独自のデータ型, Sはサンプリングの型、 open class UVSensorService: SenStickSensorService<UVSensorData, UVSensorRange> { required public init?(device:SenStickDevice) { super.init(device: device, sensorType: SenStickSensorType.ultraVioletSensor) } }
028d71a2612d09c8d51beffdd983f92a
22.381579
85
0.633089
false
false
false
false
neotron/SwiftBot-Discord
refs/heads/master
SwiftBot/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // SwiftBot // // Created by David Hedbor on 2/20/16. // Copyright © 2016 NeoTron. All rights reserved. // import Foundation import AppKit import DiscordAPI import Fabric import Crashlytics private class CrashlyticsLogger : Logger { override init() { UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true]) Fabric.with([Crashlytics.self]) super.init() } override func log(_ message: String, args: CVaListPointer) { CLSNSLogv(message, args) } } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { fileprivate var main: SwiftBotMain? @IBOutlet weak var window: NSWindow! func launchWatchDog() { guard let watcherPath = Bundle.main.path(forResource: "SwiftBotKeeperAliver", ofType: nil, inDirectory: "../MacOS"), let selfPath = Bundle.main.path(forResource: "SwiftBot", ofType: nil, inDirectory: "../MacOS") else { LOG_ERROR("Can't find the watcher.") return } let task = Process() task.launchPath = watcherPath task.arguments = [selfPath, "\(getpid())"] task.launch() } func applicationDidFinishLaunching(_ aNotification: Notification) { Logger.instance = CrashlyticsLogger(); let args = ProcessInfo.processInfo.arguments Config.development = args.contains("--development") #if false if !Config.development { launchWatchDog() } #endif self.main = SwiftBotMain() main?.runWithDoneCallback({ LOG_INFO("Exiting gracefully.") NSApp.terminate(self.main!) }) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
4aa588a5f361a177267c3812ecbf1b85
25.463768
124
0.646221
false
false
false
false
SEMT2Group1/CASPER_IOS_Client
refs/heads/master
Pods/Socket.IO-Client-Swift/Source/SocketEnginePollable.swift
mit
2
// // SocketEnginePollable.swift // Socket.IO-Client-Swift // // Created by Erik Little on 1/15/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Protocol that is used to implement socket.io polling support public protocol SocketEnginePollable: SocketEngineSpec { var invalidated: Bool { get } /// Holds strings waiting to be sent over polling. /// You shouldn't need to mess with this. var postWait: [String] { get set } var session: NSURLSession? { get } /// Because socket.io doesn't let you send two polling request at the same time /// we have to keep track if there's an outstanding poll var waitingForPoll: Bool { get set } /// Because socket.io doesn't let you send two post request at the same time /// we have to keep track if there's an outstanding post var waitingForPost: Bool { get set } func doPoll() func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) func stopPolling() } // Default polling methods extension SocketEnginePollable { private func addHeaders(req: NSMutableURLRequest) { if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) req.allHTTPHeaderFields = headers } if extraHeaders != nil { for (headerName, value) in extraHeaders! { req.setValue(value, forHTTPHeaderField: headerName) } } } func createRequestForPostWithPostWait() -> NSURLRequest { var postStr = "" for packet in postWait { let len = packet.characters.count postStr += "\(len):\(packet)" } DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr) postWait.removeAll(keepCapacity: false) let req = NSMutableURLRequest(URL: urlPollingWithSid) addHeaders(req) req.HTTPMethod = "POST" req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type") let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! req.HTTPBody = postData req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length") return req } public func doPoll() { if websocket || waitingForPoll || !connected || closed { return } waitingForPoll = true let req = NSMutableURLRequest(URL: urlPollingWithSid) addHeaders(req) doLongPoll(req) } func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) { if !polling || closed || invalidated { DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling") return } DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling") session?.dataTaskWithRequest(req, completionHandler: callback).resume() } func doLongPoll(req: NSURLRequest) { doRequest(req) {[weak self] data, res, err in guard let this = self else { return } if err != nil || data == nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling") if this.polling { this.didError(err?.localizedDescription ?? "Error") } return } DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling") if let str = String(data: data!, encoding: NSUTF8StringEncoding) { dispatch_async(this.parseQueue) { this.parsePollingMessage(str) } } this.waitingForPoll = false if this.fastUpgrade { this.doFastUpgrade() } else if !this.closed && this.polling { this.doPoll() } } } private func flushWaitingForPost() { if postWait.count == 0 || !connected { return } else if websocket { flushWaitingForPostToWebSocket() return } let req = createRequestForPostWithPostWait() waitingForPost = true DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling") doRequest(req) {[weak self] data, res, err in guard let this = self else { return } if err != nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling") if this.polling { this.didError(err?.localizedDescription ?? "Error") } return } this.waitingForPost = false dispatch_async(this.emitQueue) { if !this.fastUpgrade { this.flushWaitingForPost() this.doPoll() } } } } func parsePollingMessage(str: String) { guard str.characters.count != 1 else { return } var reader = SocketStringReader(message: str) while reader.hasNext { if let n = Int(reader.readUntilStringOccurence(":")) { let str = reader.read(n) dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } } else { dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } break } } } /// Send polling message. /// Only call on emitQueue public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) { DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue) let fixedMessage: String if doubleEncodeUTF8 { fixedMessage = doubleEncodeUTF8(message) } else { fixedMessage = message } let strMsg = "\(type.rawValue)\(fixedMessage)" postWait.append(strMsg) for data in datas { if case let .Right(bin) = createBinaryDataForSend(data) { postWait.append(bin) } } if !waitingForPost { flushWaitingForPost() } } public func stopPolling() { waitingForPoll = false waitingForPost = false session?.finishTasksAndInvalidate() } }
83a18fd355450fa6b2c215354943671e
33.726891
129
0.574229
false
false
false
false
KagasiraBunJee/TryHard
refs/heads/master
TryHard/QExpandVC.swift
mit
1
// // QExpandVC.swift // TryHard // // Created by Sergey on 5/13/16. // Copyright © 2016 Sergey Polishchuk. All rights reserved. // import UIKit class QExpandVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let tableViewContent:[Array<String>] = [ [ "Value 1", "Value 2", "Value 3" ], [ "Value 4", "Value 5", "Value 6" ] ] var hiddenSections = NSMutableDictionary() var hiddenSection = false override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } //MARK:- UITapGestureRecognizer func sectionTapped(gesture:UIGestureRecognizer) { if let view = gesture.view { let section = view.tag if hiddenSections.objectForKey(section) != nil { hiddenSections.removeObjectForKey(section) } else { hiddenSections.setObject(section, forKey: section) } let set = NSMutableIndexSet() set.addIndex(section) tableView.reloadSections(set, withRowAnimation: UITableViewRowAnimation.None) } } //MARK:- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if hiddenSections.objectForKey(section) != nil { return 0 } return tableViewContent[section].count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return tableViewContent.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("expandCell")! cell.textLabel!.text = tableViewContent[indexPath.section][indexPath.row] return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRectMake(0, 0, self.tableView.frame.width, 50)) view.backgroundColor = UIColor.whiteColor() view.tag = section let label = UILabel(frame: view.frame) let gesture = UITapGestureRecognizer(target: self, action: #selector(self.sectionTapped(_:))) view.addGestureRecognizer(gesture) var isHidden = "" if hiddenSections.objectForKey(section) != nil { isHidden = " hidden" } let title = "Section \(section+1)"+isHidden label.text = title view.addSubview(label) return view } }
26f62c23f4c8103ef3109aa8c8716ff4
26.731481
109
0.584307
false
false
false
false
wattson12/Moya-ObjectMapper
refs/heads/master
Source/RxSwift/Single+ObjectMapper.swift
mit
1
// // Single+MoyaObjectMapper.swift // // Created by Ivan Bruel on 09/12/15. // Copyright © 2015 Ivan Bruel. All rights reserved. // import Foundation import RxSwift import Moya import ObjectMapper /// Extension for processing Responses into Mappable objects through ObjectMapper public extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response { /// Maps data received from the signal into an object /// which implements the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<T> { return flatMap { response -> Single<T> in return Single.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<[T]> { return flatMap { response -> Single<[T]> in return Single.just(try response.mapArray(type, context: context)) } } } // MARK: - ImmutableMappable public extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response { /// Maps data received from the signal into an object /// which implements the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<T> { return flatMap { response -> Single<T> in return Single.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<[T]> { return flatMap { response -> Single<[T]> in return Single.just(try response.mapArray(type, context: context)) } } }
c05fd6fb62656e840dd6c45b966f04c1
41
107
0.667092
false
false
false
false
AngryLi/Onmyouji
refs/heads/master
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchResultViewModel.swift
mit
8
// // SearchResultViewModel.swift // RxExample // // Created by Krunoslav Zaher on 4/3/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class SearchResultViewModel { let searchResult: WikipediaSearchResult var title: Driver<String> var imageURLs: Driver<[URL]> let API = DefaultWikipediaAPI.sharedAPI let $: Dependencies = Dependencies.sharedDependencies init(searchResult: WikipediaSearchResult) { self.searchResult = searchResult self.title = Driver.never() self.imageURLs = Driver.never() let URLs = configureImageURLs() self.imageURLs = URLs.asDriver(onErrorJustReturn: []) self.title = configureTitle(URLs).asDriver(onErrorJustReturn: "Error during fetching") } // private methods func configureTitle(_ imageURLs: Observable<[URL]>) -> Observable<String> { let searchResult = self.searchResult let loadingValue: [URL]? = nil return imageURLs .map(Optional.init) .startWith(loadingValue) .map { URLs in if let URLs = URLs { return "\(searchResult.title) (\(URLs.count) pictures)" } else { return "\(searchResult.title) (loading…)" } } .retryOnBecomesReachable("⚠️ Service offline ⚠️", reachabilityService: $.reachabilityService) } func configureImageURLs() -> Observable<[URL]> { let searchResult = self.searchResult return API.articleContent(searchResult) .observeOn($.backgroundWorkScheduler) .map { page in do { return try parseImageURLsfromHTMLSuitableForDisplay(page.text as NSString) } catch { return [] } } .shareReplayLatestWhileConnected() } }
044c3c2e6b62f64e7b5be59147635017
27.710145
105
0.594144
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Tools/SettingsListEditorViewController.swift
gpl-2.0
1
import Foundation import WordPressShared /// The purpose of this class is to render an interface that allows the user to Insert / Edit / Delete /// a set of strings. /// open class SettingsListEditorViewController: UITableViewController { // MARK: - Public Properties @objc open var footerText: String? @objc open var emptyText: String? @objc open var insertTitle: String? @objc open var editTitle: String? @objc open var onChange: ((Set<String>) -> Void)? // MARK: - Initialiers @objc public convenience init(collection: Set<String>?) { self.init(style: .grouped) emptyText = NSLocalizedString("No Items", comment: "List Editor Empty State Message") if let unwrappedCollection = collection?.sorted() as [String]? { rows.addObjects(from: unwrappedCollection) } } // MARK: - View Lifecycle open override func viewDidLoad() { super.viewDidLoad() setupNavBar() setupTableView() } // MARK: - Helpers fileprivate func notifyDidChange() { let orderedRows = Set<String>(rows.array as! [String]) onChange?(orderedRows) } // MARK: - Setup Helpers fileprivate func setupNavBar() { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SettingsListEditorViewController.addItemPressed(_:))) } fileprivate func setupTableView() { tableView.register(WPTableViewCell.self, forCellReuseIdentifier: reuseIdentifier) WPStyleGuide.configureColors(view: view, tableView: tableView) } // MARK: - Button Handlers @IBAction func addItemPressed(_ sender: AnyObject?) { let settingsViewController = SettingsTextViewController(text: nil, placeholder: nil, hint: nil) settingsViewController.title = insertTitle settingsViewController.onValueChanged = { (updatedValue: String!) in self.insertString(updatedValue) self.notifyDidChange() self.tableView.reloadData() } navigationController?.pushViewController(settingsViewController, animated: true) } // MARK: - UITableViewDataSoutce Methods open override func numberOfSections(in tableView: UITableView) -> Int { return 1 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Note: // We'll always render, at least, one row, with the Empty State text return max(rows.count, 1) } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)! WPStyleGuide.configureTableViewCell(cell) cell.accessoryType = isEmpty() ? .none : .disclosureIndicator cell.textLabel?.text = isEmpty() ? emptyText : stringAtIndexPath(indexPath) cell.textLabel?.textColor = isEmpty() ? .neutral(.shade10) : .neutral(.shade70) return cell } open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return footerText } open override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionFooter(view) } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectSelectedRowWithAnimation(true) // Empty State if isEmpty() { addItemPressed(nil) return } // Edit! let oldText = stringAtIndexPath(indexPath) let settingsViewController = SettingsTextViewController(text: oldText, placeholder: nil, hint: nil) settingsViewController.title = editTitle settingsViewController.onValueChanged = { (newText: String!) in self.replaceString(oldText, newText: newText) self.notifyDidChange() self.tableView.reloadData() } navigationController?.pushViewController(settingsViewController, animated: true) } open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return isEmpty() == false } open override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete } open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Nuke it from the collection removeAtIndexPath(indexPath) notifyDidChange() // Empty State: We'll always render a single row, indicating that there are no items if isEmpty() { tableView.reloadRows(at: [indexPath], with: .fade) } else { tableView.deleteRows(at: [indexPath], with: .fade) } } // MARK: - Helpers fileprivate func stringAtIndexPath(_ indexPath: IndexPath) -> String { return rows.object(at: indexPath.row) as! String } fileprivate func removeAtIndexPath(_ indexPath: IndexPath) { rows.removeObject(at: indexPath.row) } fileprivate func insertString(_ newText: String) { if newText.isEmpty { return } rows.add(newText) sortStrings() } fileprivate func replaceString(_ oldText: String, newText: String) { if oldText == newText { return } insertString(newText) rows.remove(oldText) } fileprivate func sortStrings() { self.rows.sort (comparator: { ($0 as! String).compare($1 as! String) }) } fileprivate func isEmpty() -> Bool { return rows.count == 0 } // MARK: - Constants fileprivate let reuseIdentifier = "WPTableViewCell" // MARK: - Properties fileprivate var rows = NSMutableOrderedSet() }
ffac5e5b29366841fa304dfb760c9202
30.085427
121
0.649208
false
false
false
false
IngmarStein/swift
refs/heads/master
test/Driver/options-interpreter.swift
apache-2.0
24
// RUN: not %swift_driver -deprecated-integrated-repl -emit-module 2>&1 | %FileCheck -check-prefix=IMMEDIATE_NO_MODULE %s // RUN: not %swift_driver -emit-module 2>&1 | %FileCheck -check-prefix=IMMEDIATE_NO_MODULE %s // REQUIRES: swift_interpreter // IMMEDIATE_NO_MODULE: error: unsupported option '-emit-module' // RUN: %swift_driver -### %s | %FileCheck -check-prefix INTERPRET %s // INTERPRET: -interpret // RUN: %swift_driver -### %s a b c | %FileCheck -check-prefix ARGS %s // ARGS: -- a b c // RUN: %swift_driver -### -parse-stdlib %s | %FileCheck -check-prefix PARSE_STDLIB %s // RUN: %swift_driver -### -parse-stdlib | %FileCheck -check-prefix PARSE_STDLIB %s // PARSE_STDLIB: -parse-stdlib // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -resource-dir /RSRC/ %s | %FileCheck -check-prefix=CHECK-RESOURCE-DIR-ONLY %s // CHECK-RESOURCE-DIR-ONLY: # DYLD_LIBRARY_PATH=/RSRC/macosx{{$}} // RUN: %swift_driver -### -target x86_64-unknown-linux-gnu -resource-dir /RSRC/ %s | %FileCheck -check-prefix=CHECK-RESOURCE-DIR-ONLY-LINUX${LD_LIBRARY_PATH+_LAX} %s // CHECK-RESOURCE-DIR-ONLY-LINUX: # LD_LIBRARY_PATH=/RSRC/linux{{$}} // CHECK-RESOURCE-DIR-ONLY-LINUX_LAX: # LD_LIBRARY_PATH=/RSRC/linux{{$|:}} // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -L/foo/ %s | %FileCheck -check-prefix=CHECK-L %s // CHECK-L: # DYLD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/macosx$}} // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-L2 %s // CHECK-L2: # DYLD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/macosx$}} // RUN: env DYLD_LIBRARY_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-L2-ENV %s // CHECK-L2-ENV: # DYLD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/macosx:/abc/$}} // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 %s | %FileCheck -check-prefix=CHECK-NO-FRAMEWORKS %s // RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 %s | %FileCheck -check-prefix=CHECK-NO-FRAMEWORKS %s // CHECK-NO-FRAMEWORKS-NOT: DYLD_FRAMEWORK_PATH // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -F/foo/ %s | %FileCheck -check-prefix=CHECK-F %s // CHECK-F: -F /foo/ // CHECK-F: # // CHECK-F: DYLD_FRAMEWORK_PATH=/foo/{{$}} // RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ %s | %FileCheck -check-prefix=CHECK-F2 %s // CHECK-F2: -F /foo/ // CHECK-F2: -F /bar/ // CHECK-F2: # // CHECK-F2: DYLD_FRAMEWORK_PATH=/foo/:/bar/{{$}} // RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ %s | %FileCheck -check-prefix=CHECK-F2-ENV %s // CHECK-F2-ENV: -F /foo/ // CHECK-F2-ENV: -F /bar/ // CHECK-F2-ENV: # // CHECK-F2-ENV: DYLD_FRAMEWORK_PATH=/foo/:/bar/:/abc/{{$}} // RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ -L/foo2/ -L/bar2/ %s | %FileCheck -check-prefix=CHECK-COMPLEX %s // CHECK-COMPLEX: -F /foo/ // CHECK-COMPLEX: -F /bar/ // CHECK-COMPLEX: # // CHECK-COMPLEX-DAG: DYLD_FRAMEWORK_PATH=/foo/:/bar/:/abc/{{$| }} // CHECK-COMPLEX-DAG: DYLD_LIBRARY_PATH={{/foo2/:/bar2/:[^:]+/lib/swift/macosx($| )}} // RUN: %swift_driver -### -target x86_64-unknown-linux-gnu -L/foo/ %s | %FileCheck -check-prefix=CHECK-L-LINUX${LD_LIBRARY_PATH+_LAX} %s // CHECK-L-LINUX: # LD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/linux$}} // CHECK-L-LINUX_LAX: # LD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/linux($|:)}} // RUN: env LD_LIBRARY_PATH=/abc/ %swift_driver_plain -### -target x86_64-unknown-linux-gnu -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-LINUX-COMPLEX${LD_LIBRARY_PATH+_LAX} %s // CHECK-LINUX-COMPLEX: # LD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/linux:/abc/$}} // CHECK-LINUX-COMPLEX_LAX: # LD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/linux:/abc/($|:)}}
0ba8089d1544e5daf4bfbb4f08530fdd
57.074627
183
0.650989
false
false
true
false
digipost/ios
refs/heads/master
Digipost/Constants.swift
apache-2.0
1
// // Copyright (C) Posten Norge AS // // 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 struct Constants { struct APIClient { static let taskCounter = "taskCounter" static var baseURL : String { return k__SERVER_URI__ } struct AttributeKey { static let location = "location" static let subject = "subject" static let folderId = "folderId" static let identifier = "id" static let name = "name" static let icon = "icon" static let folder = "folder" static let token = "token" static let device = "device" } } struct FolderName { static let inbox = "INBOX" static let folder = "FOLDER" } struct HTTPHeaderKeys { static let accept = "Accept" static let contentType = "Content-Type" } struct Error { static let apiErrorDomainOAuthUnauthorized = "oAuthUnauthorized" static let apiClientErrorDomain = "APIManagerErrorDomain" static let noOAuthTokenPresent = "APInoOAuthTokenPresent" enum Code : Int { case oAuthUnathorized = 4001 case uploadFileDoesNotExist = 4002 case uploadFileTooBig = 4003 case uploadLinkNotFoundInRootResource = 4004 case uploadFailed = 4005 case needHigherAuthenticationLevel = 4006 case unknownError = 4007 case noOAuthTokenPresent = 4008 } static let apiClientErrorScopeKey = "scope" } struct Account { static let viewControllerIdentifier = "accountViewController" static let refreshContentNotification = "refreshContentNotificiation" static let accountCellIdentifier = "accountCellIdentifier" static let mainAccountCellIdentifier = "mainAccountCellIdentifier" static let accountCellNibName = "AccountTableViewCell" static let mainAccountCellNibName = "MainAccountTableViewCell" } struct Invoice { static let InvoiceBankTableViewNibName = "InvoiceBankTableView" static let InvoiceBankTableViewCellNibName = "InvoiceBankTableViewCell" } struct Composer { static let imageModuleCellIdentifier = "ImageModuleCell" static let textModuleCellIdentifier = "TextModuleCell" } struct Recipient { static let name = "name" static let recipient = "recipient" static let address = "address" static let mobileNumber = "mobile-number" static let organizationNumber = "organisation-number" static let uri = "uri" static let digipostAddress = "digipost-address" } } func == (left:Int, right:Constants.Error.Code) -> Bool { return left == right.rawValue } func == (left:Constants.Error.Code, right:Int) -> Bool { return left.rawValue == right }
58fdbb2ccbac35dc3d175e6b7973e576
30.303571
79
0.640616
false
false
false
false
nzaghini/b-viper
refs/heads/master
Weather/Modules/WeatherDetail/Core/Presenter/WeatherDetailPresenter.swift
mit
2
import Foundation struct WeatherDetailViewModel { let cityName: String let temperature: String let forecasts: [WeatherDetailForecastViewModel] } struct WeatherDetailForecastViewModel { let day: String let temp: String } protocol WeatherDetailPresenter: class { func loadContent() } class WeatherDetailDefaultPresenter: WeatherDetailPresenter { let interactor: WeatherDetailInteractor weak var view: WeatherDetailView? required init(interactor: WeatherDetailInteractor, view: WeatherDetailView) { self.interactor = interactor self.view = view } // MARK: - WeatherDetailPresenter func loadContent() { self.view?.displayLoading() self.interactor.fetchWeather {(result) in switch result { case .success(let weather): let vm = self.buildViewModel(weather) self.view?.displayWeatherDetail(vm) break case .failure(let reason): self.view?.displayError(reason.localizedDescription) } } } fileprivate func buildViewModel(_ data: Weather) -> WeatherDetailViewModel { var forecasts = [WeatherDetailForecastViewModel]() let df = DateFormatter() df.dateFormat = "EEEE" var date = Date() for temp in data.forecastInDays { let day = df.string(from: date) let forecast = WeatherDetailForecastViewModel(day: day, temp: temp + data.temperatureUnit) forecasts.append(forecast) date = date.addingTimeInterval(24 * 60 * 60) } return WeatherDetailViewModel(cityName: data.locationName, temperature: data.temperature + data.temperatureUnit, forecasts: forecasts) } }
63507a2a7c5811afc107cfd4d460f702
28.569231
102
0.603018
false
false
false
false
vandadnp/chorizo
refs/heads/master
Chorizo/ChorizoUrlConnection.swift
mit
1
// // ChorizoUrlConnection.swift // Chorizo // // Created by Vandad Nahavandipoor on 06/11/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // import Foundation class ChorizoAsyncUrlConnection{ typealias ChorizoUrlConnectionSuccessBlock = (data: NSData) -> () typealias ChorizoUrlConnectionFailureBlock = (error: NSError) -> () private var request = NSMutableURLRequest() var timeout: NSTimeInterval = 20.0 var successBlock: ChorizoUrlConnectionSuccessBlock? var failureBlock: ChorizoUrlConnectionFailureBlock? var url: NSURL{ set{ self.request.URL = newValue } get{ return self.request.URL! } } init(url: String){ self.url = NSURL(string: url)! } func setBody(data: NSData) -> Self{ self.request.HTTPBody = data return self } func setHeaders(headers: [NSObject : AnyObject]) -> Self{ self.request.allHTTPHeaderFields = headers return self } func onSuccess(successBlock: ChorizoUrlConnectionSuccessBlock) -> Self{ self.successBlock = successBlock return self } func onFailure(failureBlock: ChorizoUrlConnectionFailureBlock) -> Self{ self.failureBlock = failureBlock return self } func start() -> Self{ NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in if error != nil{ self.failureBlock?(error: error) } else { self.successBlock?(data: data) } } return self } }
7b1ea38f7acf2cb914418ecef3179d1d
24.811594
164
0.598876
false
false
false
false
RoverPlatform/rover-ios
refs/heads/master
Sources/Experiences/Models/WebViewBlock.swift
apache-2.0
2
// // WebViewBlock.swift // Rover // // Created by Sean Rucker on 2018-04-24. // Copyright © 2018 Rover Labs Inc. All rights reserved. // public struct WebViewBlock: Block { public var background: Background public var border: Border public var id: String public var name: String public var insets: Insets public var opacity: Double public var position: Position public var tapBehavior: BlockTapBehavior public var webView: WebView public var keys: [String: String] public var tags: [String] public var conversion: Conversion? public init(background: Background, border: Border, id: String, name: String, insets: Insets, opacity: Double, position: Position, tapBehavior: BlockTapBehavior, webView: WebView, keys: [String: String], tags: [String], conversion: Conversion?) { self.background = background self.border = border self.id = id self.name = name self.insets = insets self.opacity = opacity self.position = position self.tapBehavior = tapBehavior self.webView = webView self.keys = keys self.tags = tags self.conversion = conversion } }
6c4b47d2c83c03fbb26abb2166d53fca
29.974359
250
0.663907
false
false
false
false