repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
RevenueCat/purchases-ios
Tests/APITesters/SwiftAPITester/SwiftAPITester/CustomerInfoAPI.swift
1
2128
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // CustomerInfoAPI.swift // // Created by Madeline Beyl on 8/25/21. import Foundation import RevenueCat var customerInfo: CustomerInfo! func checkCustomerInfoAPI() { let entitlementInfo: EntitlementInfos = customerInfo.entitlements let asubs: Set<String> = customerInfo.activeSubscriptions let appis: Set<String> = customerInfo.allPurchasedProductIdentifiers let led: Date? = customerInfo.latestExpirationDate let nst: [NonSubscriptionTransaction] = customerInfo.nonSubscriptions let oav: String? = customerInfo.originalApplicationVersion let opd: Date? = customerInfo.originalPurchaseDate let rDate: Date? = customerInfo.requestDate let fSeen: Date = customerInfo.firstSeen let oaud: String? = customerInfo.originalAppUserId let murl: URL? = customerInfo.managementURL let edfpi: Date? = customerInfo.expirationDate(forProductIdentifier: "") let pdfpi: Date? = customerInfo.purchaseDate(forProductIdentifier: "") let exdf: Date? = customerInfo.expirationDate(forEntitlement: "") let pdfe: Date? = customerInfo.purchaseDate(forEntitlement: "") let desc: String = customerInfo.description let rawData: [String: Any] = customerInfo.rawData print(customerInfo!, entitlementInfo, asubs, appis, led!, nst, oav!, opd!, rDate!, fSeen, oaud!, murl!, edfpi!, pdfpi!, exdf!, pdfe!, desc, rawData) } func checkCacheFetchPolicyEnum(_ policy: CacheFetchPolicy) { switch policy { case .fromCacheOnly: break case .fetchCurrent: break case .cachedOrFetched: break case .notStaleCachedOrFetched: break @unknown default: break } } @available(*, deprecated) // Ignore deprecation warnings func checkDeprecatedAPI() { let _: Set<String> = customerInfo.nonConsumablePurchases let _: [StoreTransaction] = customerInfo.nonSubscriptionTransactions }
mit
1fae748b299876c73bc7f506d43bb112
34.466667
107
0.734023
4.172549
false
false
false
false
domenicosolazzo/practice-swift
File Management/Saving Objects to File/Saving Objects to File/AppDelegate.swift
1
1073
// // AppDelegate.swift // Saving Objects to File // // Created by Domenico on 27/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let path = NSTemporaryDirectory() + "person" let firstPerson = Person() NSKeyedArchiver.archiveRootObject(firstPerson, toFile: path) let secondPerson = NSKeyedUnarchiver.unarchiveObject(withFile: path) as! Person! if firstPerson == secondPerson{ print("Both persons are the same") } else { print("Could not read the archive") } self.window = UIWindow(frame: UIScreen.main.bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.white self.window!.makeKeyAndVisible() return true } }
mit
a777fa435a3dadc2cb011c5767895b3d
28.805556
144
0.653308
5.208738
false
false
false
false
eramdam/BetterTweetDeck
safari/Better TweetDeck for Safari/Better TweetDeck for Safari Extension/SafariWebExtensionHandler.swift
1
787
// // SafariWebExtensionHandler.swift // Better TweetDeck for Safari Extension // // Created by Damien Erambert on 1/16/21. // import SafariServices import os.log let SFExtensionMessageKey = "message" class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { let item = context.inputItems[0] as! NSExtensionItem let message = item.userInfo?[SFExtensionMessageKey] os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg) let response = NSExtensionItem() response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ] context.completeRequest(returningItems: [response], completionHandler: nil) } }
mit
4b3f73fa6a540d0ec7be064f20744a7f
29.269231
108
0.72554
4.324176
false
false
false
false
codingpotato/SpriteWidget
Pod/Classes/SWFrame.swift
1
1782
// // SWFrame.swift // Pods // // Created by wangyw on 1/13/16. // // import Foundation import SpriteKit public class SWFrame: SKNode { private var buttons: [SWButtonController] = [] public override init() { super.init() userInteractionEnabled = true } public convenience init(fileNamed: String) { self.init() let scene = SKScene(fileNamed: fileNamed)! for node in scene.children { node.removeFromParent() addChild(node) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func addActionForButtonWithName(buttonName: String, action: SKAction, block: () -> Void) { let buttonNode = childNodeWithName(".//\(buttonName)")! buttons.append(SWButtonController(buttonNode: buttonNode, action: action, block: block)) } public func addActionForButton(buttonNode: SKNode, action: SKAction, block: () -> Void) { buttonNode.removeFromParent() addChild(buttonNode) buttons.append(SWButtonController(buttonNode: buttonNode, action: action, block: block)) } public func dismiss() { removeFromParent() } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { for node in nodesAtPoint(touch.locationInNode(self)) { for buttonController in buttons { if node == buttonController.buttonNode { node.runAction(buttonController.action) buttonController.block() } } } } } }
mit
4f771f30779c73e59b2011ba4dd9af83
26.84375
101
0.583614
4.868852
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/EmailLogin/RemoteDeviceAuthorization/AuthorizationResultView.swift
1
3862
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import FeatureAuthenticationDomain import Localization import SwiftUI public struct AuthorizationResultView: View { private enum Layout { static let bottomPadding: CGFloat = 34 static let leadingPadding: CGFloat = 24 static let trailingPadding: CGFloat = 24 static let imageSideLength: CGFloat = 72 static let imageBottomPadding: CGFloat = 16 static let descriptionFontSize: CGFloat = 16 static let descriptionLineSpacing: CGFloat = 4 static let buttonSpacing: CGFloat = 10 } public var okButtonPressed: (() -> Void)? private let iconImage: Image private let title: String private let description: String public init( iconImage: Image, title: String, description: String ) { self.iconImage = iconImage self.title = title self.description = description } public var body: some View { VStack { Spacer() iconImage .frame(width: Layout.imageSideLength, height: Layout.imageSideLength) .padding(.bottom, Layout.imageBottomPadding) .accessibility(identifier: AccessibilityIdentifiers.AuthorizationResultScreen.image) Text(title) .textStyle(.title) .accessibility(identifier: AccessibilityIdentifiers.AuthorizationResultScreen.title) Text(description) .font(Font(weight: .medium, size: Layout.descriptionFontSize)) .foregroundColor(.textSubheading) .lineSpacing(Layout.descriptionLineSpacing) .accessibility(identifier: AccessibilityIdentifiers.AuthorizationResultScreen.message) Spacer() PrimaryButton(title: LocalizationConstants.okString) { okButtonPressed?() } .accessibility(identifier: AccessibilityIdentifiers.AuthorizationResultScreen.button) } .multilineTextAlignment(.center) .padding( EdgeInsets( top: 0, leading: Layout.leadingPadding, bottom: Layout.bottomPadding, trailing: Layout.trailingPadding ) ) .navigationBarHidden(true) } } extension AuthorizationResultView { private typealias LocalizedString = LocalizationConstants.FeatureAuthentication.AuthorizationResult public static let success: AuthorizationResultView = .init( iconImage: Image("icon_authorized"), title: LocalizedString.Success.title, description: LocalizedString.Success.message ) public static let linkExpired: AuthorizationResultView = .init( iconImage: Image("icon_link_expired"), title: LocalizedString.LinkExpired.title, description: LocalizedString.LinkExpired.message ) public static let rejected: AuthorizationResultView = .init( iconImage: Image("icon_rejected"), title: LocalizedString.DeviceRejected.title, description: LocalizedString.DeviceRejected.message ) public static let unknown: AuthorizationResultView = .init( iconImage: Image("icon_unknown_error"), title: LocalizedString.Unknown.title, description: LocalizedString.Unknown.message ) } #if DEBUG private struct AuthorizationResultView_Previews: PreviewProvider { private typealias LocalizedString = LocalizationConstants.FeatureAuthentication.AuthorizationResult static var previews: some View { AuthorizationResultView( iconImage: Image("icon_authorized"), title: LocalizedString.Success.title, description: LocalizedString.Success.message ) } } #endif
lgpl-3.0
76c352fa34c5b89e09fe88ddf1f2f670
32.868421
103
0.665372
5.686303
false
false
false
false
marty-suzuki/QiitaWithFluxSample
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/UITextField+RxTests.swift
2
1963
// // UITextField+RxTests.swift // Tests // // Created by Krunoslav Zaher on 5/13/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import UIKit import RxSwift import RxCocoa import XCTest // UITextField final class UITextFieldTests : RxTest { func test_completesOnDealloc() { ensurePropertyDeallocated({ UITextField() }, "a", comparer: { $0 == $1 }) { (view: UITextField) in view.rx.text } ensurePropertyDeallocated({ UITextField() }, "a", comparer: { $0 == $1 }) { (view: UITextField) in view.rx.value } ensurePropertyDeallocated({ UITextField() }, "a".enrichedWithTextFieldAttributes, comparer: { $0 == $1 }) { (view: UITextField) in view.rx.attributedText } } func test_settingTextDoesntClearMarkedText() { let textField = UITextFieldSubclass(frame: CGRect.zero) textField.text = "Text1" textField.didSetText = false textField.rx.text.on(.next("Text1")) XCTAssertTrue(!textField.didSetText) textField.rx.text.on(.next("Text2")) XCTAssertTrue(textField.didSetText) } func test_attributedTextObserver() { let textField = UITextField() XCTAssertEqual(textField.attributedText, "".enrichedWithTextFieldAttributes) let attributedText = "Hello!".enrichedWithTextFieldAttributes textField.rx.attributedText.onNext(attributedText) XCTAssertEqual(textField.attributedText!, attributedText) } } private extension String { var enrichedWithTextFieldAttributes: NSAttributedString { let tf = UITextField() tf.attributedText = NSAttributedString(string: self) return tf.attributedText! } } final class UITextFieldSubclass : UITextField { var didSetText = false override var text: String? { get { return super.text } set { didSetText = true super.text = newValue } } }
mit
d069d5cca1dc90c9bc0320bd7e40a09c
30.142857
163
0.654944
4.573427
false
true
false
false
the-grid/Portal
Portal/Models/CoverPreferences.swift
1
1184
import Argo import Curry import Foundation import Ogra /// Cover preferences. public struct CoverPreferences { public var crop: Bool public var filter: Bool public var overlay: Bool public init( crop: Bool = false, filter: Bool = false, overlay: Bool = false ) { self.crop = crop self.filter = filter self.overlay = overlay } } // MARK: - Decodable extension CoverPreferences: Decodable { public static func decode(json: JSON) -> Decoded<CoverPreferences> { return curry(self.init) <^> json <| "crop" <*> json <| "filter" <*> json <| "overlay" } } // MARK: - Encodable extension CoverPreferences: Encodable { public func encode() -> JSON { return .Object([ "crop": crop.encode(), "filter": filter.encode(), "overlay": overlay.encode() ]) } } // MARK: - Equatable extension CoverPreferences: Equatable {} public func == (lhs: CoverPreferences, rhs: CoverPreferences) -> Bool { return lhs.crop == rhs.crop && lhs.filter == rhs.filter && lhs.overlay == rhs.overlay }
mit
b73b172aee1e0b19526412aaba62be0a
19.77193
72
0.576858
4.274368
false
false
false
false
frankcjw/CJWUtilsS
CJWUtilsS/QPLib/UI/QPColumnsView.swift
1
6399
// // QPColumnsView.swift // CJWUtilsS // // Created by Frank on 19/03/2017. // Copyright © 2017 cen. All rights reserved. // import UIKit public class QPColumnsView: UIControl { public var count = 2 public var labels: [UILabel] = [] public var lines: [UIView] = [] public var indicatorLines: [UIView] = [] public var currentIndex = 0 public var selectable = false public var identifier = "" public func hideLines(flag: Bool = true) { for line in lines { line.hidden = flag } } public typealias QPColumnsViewCustomBlock = (label: UILabel) -> () var onSelectedBlock: QPColumnsViewCustomBlock? var onDeselectedBlock: QPColumnsViewCustomBlock? public func clearCornor() { for label in self.labels { label.cornorRadius(0) } } public func setupOnSelected(block: QPColumnsViewCustomBlock) { self.onSelectedBlock = block } public func setupOnDeselected(block: QPColumnsViewCustomBlock) { self.onDeselectedBlock = block } public typealias QPColumnsViewBlock = (index: Int) -> () public var block: QPColumnsViewBlock? public func onIndexChanged(block: QPColumnsViewBlock) { self.block = block } public func labelAt(index: Int) -> UILabel { return labels[index] } public convenience init (count: Int) { self.init(frame: CGRect.zero) self.count = count setup(self) setupData(self) setupLine(self) } convenience init (count: Int, frame: CGRect) { self.init(frame: frame) self.count = count setup(self) setupData(self) setupLine(self) } public convenience init () { self.init(frame: CGRect.zero) setup(self) } public override init(frame: CGRect) { super.init(frame: frame) setup(self) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup(self) } public override func updateConstraints() { super.updateConstraints() } public func setupLabel(label: UILabel) { label.numberOfLines = 0 label.cornorRadius(15) } public func setupLine(view: UIView) { if count == 1 { // let xPredicate = UIView.predicate(1, count: 1) // let line = UIView() // view.addSubview(line) // line.widthConstrain("1") // line.height(view, predicate: "*0.6") // line.centerY(view) // line.centerX(view, predicate: "*\(xPredicate)") // line.backgroundColorWhite() // lines.append(line) return } for index in 1 ... count - 1 { let xPredicate = Float(2) * Float(index) / Float(count) let line = UIView() view.addSubview(line) line.widthConstrain("1") line.height(view, predicate: "*0.6") line.centerY(view) line.centerX(view, predicate: "*\(xPredicate)") line.backgroundColorWhite() lines.append(line) } } public func setupData(view: UIView) { for index in 1...count { let indexFloat = NSNumber(integer: index).floatValue let countFloat = NSNumber(integer: count).floatValue let aaa: Float = indexFloat * 2 - 1 let bbb: Float = (countFloat * 1) let xPredicate: Float = aaa / bbb let label = UILabel() label.tag = index - 1 labels.append(label) view.addSubview(label) label.centerY(view) label.heightConstrain(">=30") label.centerX(view, predicate: "*\(xPredicate)") label.widthConstrain(">=80") label.leadingAlign(view, predicate: ">=0") label.trailingAlign(view, predicate: "<=0") label.topAlign(view, predicate: ">=0") label.bottomAlign(view, predicate: "<=0") label.textAlignmentCenter() label.text = "label \(index)" label.textColor = UIColor.whiteColor() label.font = FONT_NORMAL label.addTapGesture(self, action: "onTap:") setupLabel(label) let line = UIView() view.addSubview(line) line.bottomAlign(view, predicate: "0") line.width(label) line.heightConstrain("2") line.centerX(label) line.backgroundColor = UIColor.mainColor() line.hidden = true indicatorLines.append(line) } } func onTap(gesture: UIGestureRecognizer) { if let tag = gesture.view?.tag { selectIndex(tag) if let block = block { block(index: tag) } else { self.sendActionsForControlEvents(UIControlEvents.ValueChanged) } } } public func onSelected(label: UILabel) { label.backgroundColor = UIColor.mainColor() label.textColor = UIColor.whiteColor() } public func onDeselected(label: UILabel) { label.backgroundColor = UIColor.whiteColor() label.textColor = UIColor.darkGrayColor() } public func setup(view: UIView) { } public func selectIndex(index: Int) { if !selectable { return } if index < labels.count { for label in labels { onDeselected(label) onDeselectedBlock?(label: label) } for line in indicatorLines { line.hidden = true } indicatorLines[index].hidden = false self.currentIndex = index let label = labelAt(index) onSelected(label) onSelectedBlock?(label: label) } } public func custom(block: (label: UILabel, index: Int) -> ()) { var index = 0 for label in labels { block(label: label, index: index) index += 1 } } } //public class QPColumnsView2: QPColumnsView { // public let imageView = UIImageView() // // public override func setupData(view: UIView) { // super.setupData(view) // view.addSubview(imageView) // let label = labelAt(labels.count - 1) // label.hidden = true // imageView.centerX(label) // imageView.centerY(label) // // imageView.aspectRatio() // imageView.height(label) // imageView.scaleAspectFit() // imageView.image("w_unit") // } //} public extension UILabel { func setTitle(title: String, subtitle: String, titleColor: UIColor, subtitleColor: UIColor) { let label = self label.numberOfLines = 0 let titleLen = title.length() label.text = "\(title)\n\(subtitle)" label.textColor = subtitleColor label.font = FONT_NORMAL label.textAlignmentCenter() let range = NSMakeRange(0, titleLen) label.setTextColor(titleColor, atRange: range) label.setTextFont(FONT_BIG, atRange: range) } } public extension QPColumnsView { public func setTitle(title: String, subtitle: String, index: Int, titleColor: UIColor, subtitleColor: UIColor) { let label = labelAt(index) label.setTitle(title, subtitle: subtitle, titleColor: titleColor, subtitleColor: subtitleColor) } public func setTitle(title: String, subtitle: String, index: Int) { setTitle(title, subtitle: subtitle, index: index, titleColor: UIColor.lightGrayColor(), subtitleColor: UIColor.whiteColor()) } }
mit
9697a79c3021c2fbe75e72babce81a6e
22.696296
126
0.692404
3.270961
false
false
false
false
white-rabbit-apps/white-rabbit-common-ios
WhiteRabbitCommon/GiFHUD.swift
1
14484
// // GiFHUD.swift // GiFHUD-Swift // // Created by Cem Olcay on 07/11/14. // Copyright (c) 2014 Cem Olcay. All rights reserved. // import ImageIO import MobileCoreServices class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? } // MARK: - UIImageView Extension extension UIImageView { // MARK: Computed Properties var animatableImage: AnimatedImage? { if image is AnimatedImage { return image as? AnimatedImage } else { return nil } } var isAnimatingGif: Bool { return animatableImage?.isAnimating() ?? false } var animatable: Bool { return animatableImage != nil } // MARK: Method Overrides override public func displayLayer(layer: CALayer) { if let image = animatableImage { if let frame = image.currentFrame { layer.contents = frame.CGImage } } } // MARK: Setter Methods func setAnimatableImage(named name: String) { image = AnimatedImage.imageWithName(name, delegate: self) layer.setNeedsDisplay() } func setAnimatableImage(data data: NSData) { image = AnimatedImage.imageWithData(data, delegate: self) layer.setNeedsDisplay() } // MARK: Animation func startAnimatingGif() { if animatable { animatableImage!.resumeAnimation() } } func stopAnimatingGif() { if animatable { animatableImage!.pauseAnimation() } } } // MARK: - UIImage Extension class AnimatedImage: UIImage { func CGImageSourceContainsAnimatedGIF(imageSource: CGImageSource) -> Bool { let isTypeGIF = UTTypeConformsTo(CGImageSourceGetType(imageSource)!, kUTTypeGIF) let imageCount = CGImageSourceGetCount(imageSource) return isTypeGIF != false && imageCount > 1 } func CGImageSourceGIFFrameDuration(imageSource: CGImageSource, index: Int) -> NSTimeInterval { let containsAnimatedGIF = CGImageSourceContainsAnimatedGIF(imageSource) if !containsAnimatedGIF { return 0.0 } var duration = 0.0 let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, Int(index), nil)! as Dictionary let GIFProperties: NSDictionary? = imageProperties[String(kCGImagePropertyGIFDictionary)] as? NSDictionary if let properties = GIFProperties { duration = properties[String(kCGImagePropertyGIFUnclampedDelayTime)] as! Double if duration <= 0 { duration = properties[String(kCGImagePropertyGIFDelayTime)] as! Double } } let threshold = 0.02 - Double(FLT_EPSILON) if duration > 0 && duration < threshold { duration = 0.1 } return duration } // MARK: Constants let framesToPreload = 10 let maxTimeStep = 1.0 // MARK: Public Properties var delegate: UIImageView? var frameDurations = [NSTimeInterval]() var frames = [UIImage?]() var totalDuration: NSTimeInterval = 0.0 // MARK: Private Properties private lazy var displayLink: CADisplayLink = CADisplayLink(target: self, selector: #selector(AnimatedImage.updateCurrentFrame)) private lazy var preloadFrameQueue: dispatch_queue_t! = dispatch_queue_create("co.kaishin.GIFPreloadImages", DISPATCH_QUEUE_SERIAL) private var currentFrameIndex = 0 private var imageSource: CGImageSource? private var timeSinceLastFrameChange: NSTimeInterval = 0.0 // MARK: Computed Properties var currentFrame: UIImage? { return frameAtIndex(currentFrameIndex) } private var isAnimated: Bool { return imageSource != nil } // MARK: Initializers required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } required init(data: NSData, delegate: UIImageView?) { let imageSource = CGImageSourceCreateWithData(data, nil) self.delegate = delegate super.init() attachDisplayLink() prepareFrames(imageSource) pauseAnimation() } required convenience init(imageLiteral name: String) { fatalError("init(imageLiteral:) has not been implemented") } // MARK: Factories class func imageWithName(name: String, delegate: UIImageView?) -> Self? { let path = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent(name) let data = NSData (contentsOfFile: path) return (data != nil) ? imageWithData(data!, delegate: delegate) : nil } class func imageWithData(data: NSData, delegate: UIImageView?) -> Self? { return self.init(data: data, delegate: delegate) } // MARK: Display Link Helpers func attachDisplayLink() { displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } // MARK: Frame Methods private func prepareFrames(source: CGImageSource!) { imageSource = source let numberOfFrames = Int(CGImageSourceGetCount(self.imageSource!)) frameDurations.reserveCapacity(numberOfFrames) frames.reserveCapacity(numberOfFrames) for index in 0..<numberOfFrames { let frameDuration = CGImageSourceGIFFrameDuration(source, index: index) frameDurations.append(frameDuration) totalDuration += frameDuration if index < framesToPreload { let frameImageRef = CGImageSourceCreateImageAtIndex(self.imageSource!, Int(index), nil) let frame = UIImage(CGImage: frameImageRef!, scale: 0.0, orientation: UIImageOrientation.Up) frames.append(frame) } else { frames.append(nil) } } } func frameAtIndex(index: Int) -> UIImage? { if Int(index) >= self.frames.count { return nil } let image: UIImage? = self.frames[Int(index)] updatePreloadedFramesAtIndex(index) return image } private func updatePreloadedFramesAtIndex(index: Int) { if frames.count <= framesToPreload { return } if index != 0 { frames[index] = nil } for internalIndex in (index + 1)...(index + framesToPreload) { let adjustedIndex = internalIndex % frames.count if frames[adjustedIndex] == nil { dispatch_async(preloadFrameQueue) { let frameImageRef = CGImageSourceCreateImageAtIndex(self.imageSource!, Int(adjustedIndex), nil) self.frames[adjustedIndex] = UIImage(CGImage: frameImageRef!) } } } } func updateCurrentFrame() { if !isAnimated { return } timeSinceLastFrameChange += min(maxTimeStep, displayLink.duration) let frameDuration = frameDurations[currentFrameIndex] while timeSinceLastFrameChange >= frameDuration { timeSinceLastFrameChange -= frameDuration currentFrameIndex += 1 if currentFrameIndex >= frames.count { currentFrameIndex = 0 } delegate?.layer.setNeedsDisplay() } } // MARK: Animation func pauseAnimation() { displayLink.paused = true } func resumeAnimation() { displayLink.paused = false } func isAnimating() -> Bool { return !displayLink.paused } } // MARK: - GiFHUD class GiFHUD: UIView { // MARK: Constants var Height : CGFloat = 300 var Width : CGFloat = 300 let FadeDuration : NSTimeInterval = 0.3 let GifSpeed : CGFloat = 0.3 let OverlayAlpha : CGFloat = 0.3 let Window : UIWindow = (UIApplication.sharedApplication().delegate as! AppDelegate).window! // MARK: Variables var overlayView : UIView? var imageView : UIImageView? var shown : Bool private var tapGesture: UITapGestureRecognizer? private var didTapClosure: (() -> Void)? private var swipeGesture: UISwipeGestureRecognizer? private var didSwipeClosure: (() -> Void)? // MARK: Singleton class var instance : GiFHUD { struct Static { static let inst : GiFHUD = GiFHUD () } return Static.inst } // MARK: Init init () { self.shown = false super.init(frame: CGRect (x: 0, y: 0, width: Width, height: Height)) alpha = 0 center = Window.center clipsToBounds = false layer.backgroundColor = UIColor (white: 0, alpha: 0.5).CGColor layer.cornerRadius = 10 layer.masksToBounds = true imageView = UIImageView (frame: CGRectInset(bounds, 20, 20)) addSubview(imageView!) Window.addSubview(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reframe() { // self.frame = CGRectMake(0, 0, Width, Height) } // MARK: HUD class func showWithOverlay () { dismiss ({ self.instance.Window.addSubview(self.instance.overlay()) self.show() }) } class func show () { if (!self.instance.shown) { dismiss({ if let _ = self.instance.imageView?.animationImages { self.instance.imageView?.startAnimating() } else { self.instance.imageView?.startAnimatingGif() } self.instance.Window.bringSubviewToFront(self.instance) self.instance.shown = true self.instance.fadeIn() }) } } class func showForSeconds (seconds: Double) { show() let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue(), { GiFHUD.dismiss() }) } class func dismissOnTap (didTap: (() -> Void)? = nil) { self.instance.tapGesture = UITapGestureRecognizer(target: self, action: #selector(GiFHUD.userTapped)) self.instance.addGestureRecognizer(self.instance.tapGesture!) self.instance.didTapClosure = didTap } @objc private class func userTapped () { GiFHUD.dismiss() self.instance.tapGesture = nil self.instance.didTapClosure?() self.instance.didTapClosure = nil } class func dismissOnSwipe (didTap: (() -> Void)? = nil) { self.instance.swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(GiFHUD.userSwiped)) self.instance.addGestureRecognizer(self.instance.swipeGesture!) } @objc private class func userSwiped () { GiFHUD.dismiss() self.instance.swipeGesture = nil self.instance.didSwipeClosure?() self.instance.didSwipeClosure = nil } class func dismiss () { if (!self.instance.shown) { return } self.instance.overlay().removeFromSuperview() self.instance.fadeOut() if let _ = self.instance.imageView?.animationImages { self.instance.imageView?.stopAnimating() } else { self.instance.imageView?.stopAnimatingGif() } } class func dismiss (complete: ()->Void) { if (!self.instance.shown) { return complete() } self.instance.fadeOut({ self.instance.overlay().removeFromSuperview() complete() }) if let _ = self.instance.imageView?.animationImages { self.instance.imageView?.stopAnimating() } else { self.instance.imageView?.stopAnimatingGif() } } // MARK: Effects func fadeIn () { imageView?.startAnimatingGif() UIView.animateWithDuration(FadeDuration, animations: { self.alpha = 1 }) } func fadeOut () { UIView.animateWithDuration(FadeDuration, animations: { self.alpha = 0 }, completion: { (complate) in self.shown = false self.imageView?.stopAnimatingGif() }) } func fadeOut (complated: ()->Void) { UIView.animateWithDuration(FadeDuration, animations: { self.alpha = 0 }, completion: { (complate) in self.shown = false self.imageView?.stopAnimatingGif() complated () }) } func overlay () -> UIView { if (overlayView == nil) { overlayView = UIView (frame: Window.frame) overlayView?.backgroundColor = UIColor.blackColor() overlayView?.alpha = 0 UIView.animateWithDuration(0.3, animations: { () -> Void in self.overlayView!.alpha = self.OverlayAlpha }) } return overlayView! } // MARK: Gif class func setGif (name: String) { self.instance.imageView?.animationImages = nil self.instance.imageView?.stopAnimating() self.instance.imageView?.image = AnimatedImage.imageWithName(name, delegate: self.instance.imageView) } class func setGifBundle (bundle: NSBundle) { self.instance.imageView?.animationImages = nil self.instance.imageView?.stopAnimating() self.instance.imageView?.image = AnimatedImage (data: NSData(contentsOfURL: bundle.resourceURL!)!, delegate: nil) } class func setGifImages (images: [UIImage]) { self.instance.imageView?.stopAnimatingGif() self.instance.imageView?.animationImages = images self.instance.imageView?.animationDuration = NSTimeInterval(self.instance.GifSpeed) } }
mit
cbba21cc3610b934b59388b80039a847
28.026052
135
0.582436
5.249728
false
false
false
false
cscalcucci/Swift_Life
Swift_Life/AppDelegate.swift
1
6114
// // AppDelegate.swift // Swift_Life // // Created by Christopher Scalcucci on 2/11/16. // Copyright © 2016 Christopher Scalcucci. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "Aphelion.Swift_Life" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Swift_Life", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
973514e67b1c8d7dd6382b0456bef434
54.072072
291
0.720105
5.88921
false
false
false
false
quire-io/SwiftyChrono
Sources/Utils/JPUtil.swift
1
1515
// // JPUtil.swift // SwiftyChrono // // Created by Jerry Chen on 2/6/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation // source: https://gist.github.com/sgr-ksmt/2dcf11a64cdb22d44517 extension String { private func convertFullWidthToHalfWidth(reverse: Bool) -> String { let str = NSMutableString(string: self) as CFMutableString CFStringTransform(str, nil, kCFStringTransformFullwidthHalfwidth, reverse) return str as String } var hankaku: String { return convertFullWidthToHalfWidth(reverse: false) } var zenkaku: String { return convertFullWidthToHalfWidth(reverse: true) } var hankakuOnlyNumber: String { return convertFullWidthToHalfWidthOnlyNumber(fullWidth: false) } var zenkakuOnlyNumber: String { return convertFullWidthToHalfWidthOnlyNumber(fullWidth: true) } private func convertFullWidthToHalfWidthOnlyNumber(fullWidth: Bool) -> String { var str = self let pattern = fullWidth ? "[0-9]+" : "[0-9]+" let regex = try! NSRegularExpression(pattern: pattern, options: []) let results = regex.matches(in: str, options: [], range: NSMakeRange(0, str.count)) results.reversed().forEach { let subStr = (str as NSString).substring(with: $0.range) str = str.replacingOccurrences(of: subStr, with: (fullWidth ? subStr.zenkaku : subStr.hankaku)) } return str } }
mit
ab9288bf6519177d623f1065c67e9e8f
31.12766
107
0.656291
4.136986
false
false
false
false
someoneAnyone/Nightscouter
Common/Protocols/Chartable.swift
1
2206
// // Chartable.swift // Nightscouter // // Created by Peter Ina on 1/15/16. // Copyright © 2016 Nothingonline. All rights reserved. // import Foundation public protocol Chartable { var chartDictionary: String { get } var chartColor: String { get } var chartDateFormatter: DateFormatter { get } var jsonForChart: String { get } } struct ChartPoint: Codable { let color: String let date: Date let filtered: Double let noise: Noise let sgv: MgdlValue let type: String let unfiltered: Double let y: Double let direction: Direction } extension Chartable { public var chartColor: String { return "grey" } public var chartDateFormatter: DateFormatter { let nsDateFormatter = DateFormatter() nsDateFormatter.dateFormat = "EEE MMM d HH:mm:ss zzz yyy" nsDateFormatter.timeZone = TimeZone.autoupdatingCurrent nsDateFormatter.locale = Locale(identifier: "en_US") return nsDateFormatter } public var jsonForChart: String { // do { // let jsObj = try JSONSerialization.data(withJSONObject: chartDictionary, options:[]) // guard let str = String(bytes: jsObj, encoding: .utf8) else { // return "" // } // // return str // } catch { // print(error) // return "" // } return chartDictionary } } extension SensorGlucoseValue: Chartable { public var chartDictionary: String { get{ let entry: SensorGlucoseValue = self // let dateForJson = chartDateFormatter.string(from: entry.date) let chartObject = ChartPoint(color: chartColor, date: entry.date, filtered: entry.filtered ?? 0, noise: entry.noise ?? .none, sgv: entry.mgdl, type: "sgv", unfiltered: entry.unfiltered ?? 0, y: entry.mgdl, direction: entry.direction ?? .none) let jsonEncorder = JSONEncoder() jsonEncorder.dateEncodingStrategy = .formatted(chartDateFormatter) let item = try! jsonEncorder.encode(chartObject.self) return String(data: item, encoding: .utf8) ?? "[{}]" } } }
mit
4493f471a6512f6470706e354606a90c
29.205479
254
0.61678
4.216061
false
false
false
false
yangligeryang/codepath
labs/ParseDemo/ParseDemo/LoginViewController.swift
1
3071
// // LoginViewController.swift // ParseDemo // // Created by Yang Yang on 11/29/16. // Copyright © 2016 Yang Yang. All rights reserved. // import Parse import UIKit class LoginViewController: UIViewController { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapSignup(_ sender: UIButton) { let user = PFUser() user.username = emailField.text! user.password = passwordField.text! user.email = emailField.text! if user.username != "" && user.password != "" { user.signUpInBackground { (success: Bool, error: Error?) in if error != nil { let alertController = UIAlertController(title: "Signup error", message: error?.localizedDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in }) alertController.addAction(okAction) self.present(alertController, animated: true) { } } else { print("Yay") self.performSegue(withIdentifier: "loginSegue", sender: nil) } } } else if user.username != "" { let alertController = UIAlertController(title: "Password required", message: "", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in }) alertController.addAction(okAction) present(alertController, animated: true) { } } else { let alertController = UIAlertController(title: "Email and password required", message: "", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in }) alertController.addAction(okAction) present(alertController, animated: true) { } } } @IBAction func didTapLogin(_ sender: UIButton) { PFUser.logInWithUsername(inBackground: emailField.text!, password: passwordField.text!) { (user: PFUser?, error: Error?) in if user == nil { let alertController = UIAlertController(title: "Login error", message: error?.localizedDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in }) alertController.addAction(okAction) self.present(alertController, animated: true) { } } else { self.performSegue(withIdentifier: "loginSegue", sender: nil) } } } }
apache-2.0
e43ae6e252819b0e31a8298e211700aa
35.987952
144
0.567101
5.293103
false
false
false
false
arslanbilal/cryptology-project
Cryptology Project/Cryptology Project/Classes/Views/Messages List Cell/MessagesListTableViewCell.swift
1
3085
// // MessageListTableViewCell.swift // Cryptology Project // // Created by Bilal Arslan on 15/03/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import UIKit class MessagesListTableViewCell: UITableViewCell { private let profileImageView = UIImageView.newAutoLayoutView() private let profileNameLabel = UILabel.newAutoLayoutView() private let profileLastMessageLabel = UILabel.newAutoLayoutView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.layer.borderColor = UIColor.grayColor().CGColor self.layer.borderWidth = 0.5 self.selectionStyle = .None profileImageView.layer.cornerRadius = 27.5 self.addSubview(profileImageView) profileImageView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10.0, 10.0, 10.0, 0), excludingEdge: .Right) profileImageView.autoSetDimension(.Width, toSize: 55) let profileInfoView = UIView.newAutoLayoutView() self.addSubview(profileInfoView) profileInfoView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10.0, 0, 10.0, 10.0), excludingEdge: .Left) profileInfoView.autoPinEdge(.Left, toEdge: .Right, ofView: profileImageView, withOffset: 10.0) profileNameLabel.textColor = UIColor.blackColor() profileNameLabel.textAlignment = .Left profileNameLabel.numberOfLines = 1 profileNameLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 16) profileInfoView.addSubview(profileNameLabel) profileNameLabel.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom) profileNameLabel.autoSetDimension(.Height, toSize: 20) profileLastMessageLabel.textColor = UIColor.grayColor() profileLastMessageLabel.textAlignment = .Left profileLastMessageLabel.numberOfLines = 2 profileLastMessageLabel.font = UIFont(name: "HelveticaNeue", size: 12) profileInfoView.addSubview(profileLastMessageLabel) profileLastMessageLabel.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top) profileLastMessageLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: profileNameLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setContent(messageList: MessageList) { self.profileNameLabel.text = "\(messageList.otherUser.name) \(messageList.otherUser.lastname)" if messageList.messages.last?.message.isImageMassage == true { self.profileLastMessageLabel.text = "Image message" } else { self.profileLastMessageLabel.text = FBEncryptorAES.decryptBase64String(messageList.messages.last?.message.text, keyString: messageList.messageKey!.key) } self.profileImageView.image = UIImage(named: "profile") } }
mit
b272b7bcd3b37aa357d60e08cfbd1e98
40.675676
164
0.700389
5.317241
false
false
false
false
seungprk/PenguinJump
PenguinJump/PenguinJump/AboutScene.swift
1
2974
// // AboutScene.swift // PenguinJump // // Created by Seung Park on 6/6/16. // Copyright © 2016 De Anza. All rights reserved. // import SpriteKit class AboutScene: SKScene { override func didMoveToView(view: SKView) { backgroundColor = UIColor.whiteColor() let logo = SKSpriteNode(texture: SKTexture(image: UIImage(named: "logo")!)) logo.name = "logo" logo.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5 + logo.frame.height - 25) addChild(logo) let teamName = SKLabelNode(text: "TEAM PENGUIN") teamName.fontName = "Helvetica Neue Condensed Black" teamName.fontSize = 24 teamName.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5) teamName.fontColor = SKColor.blackColor() addChild(teamName) let memberOne = SKLabelNode(text: "David Park") memberOne.fontName = "Helvetica Neue" memberOne.fontSize = 19 memberOne.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5 - 50) memberOne.fontColor = SKColor.blackColor() addChild(memberOne) let memberOneDescript = SKLabelNode(text: "@seungprk") memberOneDescript.fontName = "Helvetica Neue" memberOneDescript.fontSize = 19 memberOneDescript.position = memberOne.position memberOneDescript.position.y -= memberOne.frame.height + 5 memberOneDescript.fontColor = SKColor(red: 14/255, green: 122/255, blue: 254/255, alpha: 1.0) addChild(memberOneDescript) let plusSign = SKLabelNode(text: "+") plusSign.fontName = "Helvetica Neue" plusSign.fontSize = 19 plusSign.position = memberOneDescript.position plusSign.position.y -= 25 plusSign.fontColor = SKColor.blackColor() addChild(plusSign) let memberTwo = SKLabelNode(text: "Matthew Tso") memberTwo.fontName = "Helvetica Neue" memberTwo.fontSize = 19 memberTwo.position = plusSign.position memberTwo.position.y -= 25 memberTwo.fontColor = SKColor.blackColor() addChild(memberTwo) let memberTwoDescript = SKLabelNode(text: "@matthewtso") memberTwoDescript.fontName = "Helvetica Neue" memberTwoDescript.fontSize = 19 memberTwoDescript.position = memberTwo.position memberTwoDescript.position.y -= memberTwo.frame.height + 5 memberTwoDescript.fontColor = SKColor(red: 14/255, green: 122/255, blue: 254/255, alpha: 1.0) addChild(memberTwoDescript) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let gameScene = GameScene(size: self.size) let transition = SKTransition.pushWithDirection(.Up, duration: 0.5) gameScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(gameScene, transition: transition) } }
bsd-2-clause
ae9e2c94bb669c5203f49cd66e11f1c0
38.64
101
0.645812
4.140669
false
false
false
false
AlexChekanov/Gestalt
Gestalt/ModelLayer/Data/DataLayer.swift
1
2160
import Foundation import CoreData typealias TasksBlock = ([Task])->Void protocol DataLayer { func loadFromDB(finished: TasksBlock) func save(dtos: [TaskDTO], translationLayer: TranslationLayer, finished: @escaping () -> Void) } class DataLayerImpl: DataLayer { lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores(completionHandler: { storeDescription, error in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() var mainContext: NSManagedObjectContext { return persistentContainer.viewContext } func save(dtos: [TaskDTO], translationLayer: TranslationLayer, finished: @escaping () -> Void) { clearOldResults() _ = translationLayer.toUnsavedCoreData(from: dtos, with: mainContext) try! mainContext.save() finished() } func loadFromDB(finished: TasksBlock) { print("loading data locally") let tasks = loadTasksFromDB() finished(tasks) } } extension DataLayerImpl { fileprivate func loadTasksFromDB() -> [Task] { let sortOn = NSSortDescriptor(key: "brief", ascending: true) let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest() fetchRequest.sortDescriptors = [sortOn] let tasks = try! persistentContainer.viewContext.fetch(fetchRequest) return tasks } //MARK: - Helper Methods fileprivate func clearOldResults() { print("clearing old results") let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Task.fetchRequest() let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) try! persistentContainer.persistentStoreCoordinator.execute(deleteRequest, with: persistentContainer.viewContext) persistentContainer.viewContext.reset() } }
apache-2.0
c95fd2ba6ef60bbb19cf3dcb2e0b4e7d
31.238806
121
0.659259
5.359801
false
false
false
false
ijaureguialzo/GooglePlacesRow
Sources/GooglePlacesTableCell.swift
1
3447
// // GooglePlacesTableCell.swift // GooglePlacesRow // // Created by Mathias Claassen on 4/14/16. // // import Foundation import UIKit open class GooglePlacesTableCell<TableViewCell: UITableViewCell>: GooglePlacesCell, UITableViewDelegate, UITableViewDataSource where TableViewCell: EurekaGooglePlacesTableViewCell { /// callback that can be used to cuustomize the appearance of the UICollectionViewCell in the inputAccessoryView public var customizeTableViewCell: ((TableViewCell) -> Void)? /// UICollectionView that acts as inputAccessoryView. public var tableView: UITableView? /// Maximum number of candidates to be shown public var numberOfCandidates: Int = 5 required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func setup() { super.setup() tableView = UITableView(frame: CGRect.zero, style: .plain) tableView?.autoresizingMask = .flexibleHeight tableView?.isHidden = true tableView?.delegate = self tableView?.dataSource = self tableView?.backgroundColor = UIColor.white tableView?.register(TableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) } open func showTableView() { if let controller = formViewController() { if tableView?.superview == nil { controller.view.addSubview(tableView!) } let frame = controller.tableView?.convert(self.frame, to: controller.view) ?? self.frame tableView?.frame = CGRect(x: 0, y: frame.origin.y + frame.height, width: contentView.frame.width, height: 44 * CGFloat(numberOfCandidates)) tableView?.isHidden = false } } open func hideTableView() { tableView?.isHidden = true } override func reload() { tableView?.reloadData() } open override func textFieldDidChange(_ textField: UITextField) { super.textFieldDidChange(textField) if textField.text?.isEmpty == false { showTableView() } } open override func textFieldDidEndEditing(_ textField: UITextField) { super.textFieldDidEndEditing(textField) hideTableView() } //MARK: UITableViewDelegate and Datasource open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return predictions?.count ?? 0 } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell if let prediction = predictions?[(indexPath as NSIndexPath).row] { cell.setTitle(prediction) } customizeTableViewCell?(cell) return cell } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let prediction = predictions?[(indexPath as NSIndexPath).row] { row.value = GooglePlace.prediction(prediction: prediction) _ = cellResignFirstResponder() } } open func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
mit
faf1e740f47f5f91898b257d8781b083
33.818182
181
0.665506
5.488854
false
false
false
false
kamawshuang/iOS---Animation
3D动画(八)/3DSlideMenu/3DSlideMenu/ContainerViewController.swift
1
6703
// // ContainerViewController.swift // 3DSlideMenu // // Created by 51Testing on 15/12/9. // Copyright © 2015年 HHW. All rights reserved. // import UIKit import QuartzCore class ContainerViewController: UIViewController { let menuWidth: CGFloat = 80.0 let animationTime: NSTimeInterval = 0.5 let menuViewController: UIViewController! let centerViewController: UIViewController! var isOpening = false //自定义初始化 init(sideMenu: UIViewController, center: UIViewController) { //先赋值再调父类 menuViewController = sideMenu centerViewController = center //调用父类初始化,否则报错 super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() //setNeedsStatusBarAppearanceUpdate,更新status bar的显示。 setNeedsStatusBarAppearanceUpdate() /** View Controller中可以添加多个sub view,在需要的时候显示出来; 可以通过viewController(parent)中可以添加多个child viewController;来控制页面中的sub view,降低代码耦合度; 通过切换,可以显示不同的view;,替代之前的addSubView的管理 */ addChildViewController(centerViewController) view.addSubview(centerViewController.view) /// addChildViewController回调用[child willMoveToParentViewController:self] ,但是不会调用didMoveToParentViewController,所以需要显示调用 centerViewController.didMoveToParentViewController(self) addChildViewController(menuViewController) view.addSubview(menuViewController.view) menuViewController.didMoveToParentViewController(self) //设置锚点,旋转动画使用,详见文档,需要在设置Frame之前 menuViewController.view.layer.anchorPoint.x = 1.0 menuViewController.view.frame = CGRect(x: -menuWidth, y: 0, width: menuWidth, height: view.frame.height) let panGesture = UIPanGestureRecognizer(target: self, action: Selector("handleGesture:")) view.addGestureRecognizer(panGesture) setToPercent(0.0) } func handleGesture(recognizer: UIPanGestureRecognizer) { //利用拖动手势的translationInView:方法取得在相对指定视图(这里是控制器根视图)的移动 ---> CGPoint let translation = recognizer.translationInView(recognizer.view!.superview) print("translation-++++++++++++++++-----\(translation.x)") var progress = translation.x / menuWidth * (isOpening ? 1.0 : -1.0) print("translation-000000000-------\(progress) \n") progress = min(max(progress, 0.0), 1.0) switch recognizer.state { case .Began: //floor 向下取整,去掉小数部分 let isOpen = floor(centerViewController.view.frame.origin.x / menuWidth) isOpening = isOpen == 1.0 ? false : true // Improve the look of the opening menu menuViewController.view.layer.shouldRasterize = true menuViewController.view.layer.rasterizationScale = UIScreen.mainScreen().scale case .Changed: self.setToPercent(isOpening ? progress: (1.0 - progress)) case .Ended: fallthrough case .Cancelled: fallthrough case .Failed: var tagetProgress: CGFloat if (isOpening) { tagetProgress = progress < 0.5 ? 0.0 : 1.0 }else { tagetProgress = progress < 0.5 ? 1.0 : 0.0 } UIView.animateWithDuration(animationTime, animations: { self.setToPercent(tagetProgress) }, completion: {_ in self.menuViewController.view.layer.shouldRasterize = false }) default: break } } func toggleSideMenu() { let isOpen = floor(centerViewController.view.frame.origin.x/menuWidth) let targetProgress: CGFloat = isOpen == 1.0 ? 0.0: 1.0 UIView.animateWithDuration(animationTime, animations: { self.setToPercent(targetProgress) }, completion: { _ in self.menuViewController.view.layer.shouldRasterize = false }) } func setToPercent(percent: CGFloat) { print("percent----------------\(percent)") centerViewController.view.frame.origin.x = menuWidth * CGFloat(percent) // menuViewController.view.frame.origin.x = menuWidth * CGFloat(percent) - menuWidth menuViewController.view.layer.transform = menuTransformForPercent(percent) //设置透明度 menuViewController.view.alpha = CGFloat(max(0.2, percent)) } func menuTransformForPercent(percent: CGFloat) -> CATransform3D { var identity = CATransform3DIdentity //为什么这个属性被称为m34 ?视图和层变换数学表示为二维矩阵。在一层的情况下变换矩阵,第三行第四列中的元素集你的z轴的角度。你可以设置这个元素直接应用所需的透视变换。 identity.m34 = -1.0/1000 let remainingPercent = 1.0 - percent let angle = remainingPercent * CGFloat(-M_PI_2) let rotationTransform = CATransform3DRotate(identity, angle, 0.0, 1.0, 0.0) let translationTransform = CATransform3DMakeTranslation(menuWidth * percent, 0, 0) return CATransform3DConcat(rotationTransform, translationTransform) } 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. } */ }
apache-2.0
d8d24639dfd77b72add75c39237315f1
29.984925
118
0.617742
4.948636
false
false
false
false
leotao2014/RTPhotoBrowser
RTPhotoBrowser/ImageCell.swift
1
978
// // ImageCell.swift // PtBrowser // // Created by leotao on 2017/2/14. // Copyright © 2017年 leotao. All rights reserved. // import UIKit import Kingfisher class ImageCell: UICollectionViewCell { let imageView = UIImageView(); var imageUrl:String = "" { didSet { imageView.kf.setImage(with: URL(string:imageUrl)) } } override init(frame: CGRect) { super.init(frame: frame); self.contentView.addSubview(imageView); self.contentView.backgroundColor = UIColor(red: 92 / 255.0, green: 105 / 255.0, blue: 111 / 255.0, alpha: 1.0); imageView.clipsToBounds = true; imageView.contentMode = .scaleAspectFill; } override func layoutSubviews() { super.layoutSubviews(); imageView.frame = self.contentView.bounds; } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
6e48fc7adc86c7929e8531a2cf7d1ea6
24
119
0.611282
4.202586
false
false
false
false
thanhcuong1990/swift-sample-code
SampleCode/Utilities/Constants.swift
1
873
// // Constants.swift // SampleCode // // Created by Cuong Lam on 11/9/15. // Copyright © 2015 Cuong Lam. All rights reserved. // import Foundation import UIKit // MARK: Storyboard struct Storyboard { static let Featured = "Featured" static let Categories = "Categories" static let Search = "Search" static let Wishlist = "Wishlist" static let Account = "Account" static let Checkout = "Checkout" static let Product = "Product" } struct ScreenSize { static let WIDTH = UIScreen.mainScreen().bounds.size.width static let HEIGHT = UIScreen.mainScreen().bounds.size.height static let MAX_LENGTH = max(ScreenSize.WIDTH, ScreenSize.HEIGHT) static let MIN_LENGTH = min(ScreenSize.WIDTH, ScreenSize.HEIGHT) } struct Url { static let images = "https://api.flickr.com/services/rest/" }
unlicense
0e9983ab3e7b0b4b5af42d0536b32bea
26.25
68
0.668578
3.824561
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/LockerRental/controller/LockerRentalMyLockersViewController.swift
1
5140
// // LockerRentalMyLockersViewController.swift // byuSuite // // Created by Erik Brady on 7/19/17. // Copyright © 2017 Brigham Young University. All rights reserved. // protocol LockerRentalDelegate { func loadLockers() } class LockerRentalMyLockersViewController: ByuViewController2, UITableViewDataSource, LockerRentalDelegate { //MARK: Outlets @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var spinner: UIActivityIndicatorView! @IBOutlet private weak var button: UIBarButtonItem! //MARK: Properties private var agreements = [LockerRentalAgreement]() private var loadedLockerCount: Int = 0 override func viewDidLoad() { super.viewDidLoad() loadLockers() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRow() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "myLockerDetail", let vc = segue.destination as? LockerRentalMyLockersDetailViewController, let sender = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: sender) { vc.agreement = agreements[indexPath.row] vc.delegate = self } else if segue.identifier == "toBrowseLockers", let vc = segue.destination as? LockerRentalBuildingsViewController { vc.delegate = self } } //MARK: UITableViewDelegate/DataSource Methods func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if loadedLockerCount > 0 { return "My Lockers" } return nil } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return loadedLockerCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) let agreement = agreements[indexPath.row] if let building = agreement.locker?.building, let floor = agreement.locker?.floor, let number = agreement.locker?.displayedLockerNumber { cell.textLabel?.text = "\(building) Floor \(floor) - \(number)" } cell.detailTextLabel?.text = "Expires on: \(agreement.expirationDateString())" return cell } //MARK: IBAction Methods @IBAction func browseAvailableLockersClicked(_ sender: Any) { if agreements.count >= 3 { super.displayAlert(error: nil, title: "Unable to Browse Lockers", message: "You have reached the maximum number of lockers you can rent.", alertHandler: nil) } else { self.performSegue(withIdentifier: "toBrowseLockers", sender: sender) } } //MARK: LockerRental Delegate Methods func loadLockers() { //loadedLockerCount tracks the number of lockers loaded. It must be reset here because this method can be called later in the feature to reload lockers. loadedLockerCount = 0 //Remove current rows from tableView tableView.reloadData() spinner.startAnimating() LockerRentalClient.getAgreements { (agreements, error) in if let agreements = agreements { self.agreements = agreements if self.agreements.count == 0 { self.stopSpinnerIfReady() self.tableView.tableFooterView?.isHidden = false } else { //Reset footer in the case that they just rented a first locker self.tableView.tableFooterView?.isHidden = true //Sort locker agreements by Expiration Date self.agreements.sort() //Load lockers for each agreement for agreement in self.agreements { if let lockerId = agreement.lockerId { LockerRentalClient.getLocker(lockerId: lockerId, callback: { (locker, error) in if let locker = locker { agreement.locker = locker self.loadedLockerCount += 1 self.tableView.reloadData() self.stopSpinnerIfReady() } else { self.spinner.stopAnimating() super.displayAlert(error: error) } }) } } } } else { super.displayAlert(error: error) } } } //MARK: Custom Methods private func stopSpinnerIfReady() { if agreements.count == loadedLockerCount { spinner.stopAnimating() button.isEnabled = true } } }
apache-2.0
63bc57152d04b7c1f292d8cf1ad16220
36.23913
169
0.578906
5.443856
false
false
false
false
michalciurus/KatanaRouter
Pods/Katana/Katana/Plastic/PlasticView.swift
1
10249
// // PlasticView.swift // Katana // // Copyright © 2016 Bending Spoons. // Distributed under the MIT License. // See the LICENSE file for more information. import CoreGraphics /// Enum that represents a constraint in the X axis private enum ConstraintX { case none, left, right, centerX, width } /// Enum that represents a constraint in the Y axis private enum ConstraintY { case none, top, bottom, centerY, height } /** This class basically acts as an abstraction over views created through Katana. The idea is that Plastic will create a `PlasticView` for each node description returned by `childrenDescriptions(props:state:update:dispatch:)`. You can then apply Plastic methods over the instances of `PlasticView` and achieve the desidered layout. This abstraction has been introduced to avoid to deal directly with `UIView` or 'NSView' instances in the Katana world. This allows us to implement some optimizations behinde the scenes (e.g., caching). */ public class PlasticView { /** Key of the instance, this is the same defined in the corresponded node description properties */ public let key: String /// The current frame of the instance. It can be changed by applying Plastic methods public private(set) var frame: CGRect /// The plastic multiplier that will be used to scale the values private let multiplier: CGFloat /// The frame of the instance in the native view coordinate system private(set) var absoluteOrigin: CGPoint /** A manager that can be used to emulate UIKit/AppKit capabilities - seeAlso: `CoordinateConvertible` */ private unowned let hierarchyManager: CoordinateConvertible /// The X constraint related to the previous plastic method private var oldestConstraintX = ConstraintX.none /// The X constraint related to the last plastic method private var newestConstraintX = ConstraintX.none /// The Y constraint related to the previous plastic method private var oldestConstraintY = ConstraintY.none /// The Y constraint related to the last plastic method private var newestConstraintY = ConstraintY.none /// The current X constraint private var constraintX: ConstraintX { get { return newestConstraintX } set(newValue) { oldestConstraintX = newestConstraintX newestConstraintX = newValue } } /// The current Y constraint private var constraintY: ConstraintY { get { return newestConstraintY } set(newValue) { oldestConstraintY = newestConstraintY newestConstraintY = newValue } } /** Creates an instance of `PlasticView` with the given parameters - parameter hierarchyManager: the hierarchy manager to use to emulate UIKit/AppKit capabilities - parameter key: the key of the node description with which the instance will be associated to - parameter multiplier: the plastic multiplier to use - parameter frame: the initial frame of the instance - returns: a valid instance of `PlasticView` */ init(hierarchyManager: CoordinateConvertible, key: String, multiplier: CGFloat, frame: CGRect) { self.key = key self.frame = frame self.absoluteOrigin = frame.origin self.multiplier = multiplier self.hierarchyManager = hierarchyManager } /** Scales a value by using the multiplier defined in the `init(hierarchyManager:key:multiplier:frame:)` method - parameter value: the value to scale - returns: the scaled value */ public func scaleValue(_ value: Value) -> CGFloat { return value.scale(by: multiplier) } /** Updates the `frame` height value - parameter newValue: the new value to assig */ private func updateHeight(_ newValue: CGFloat) { self.frame.size.height = newValue } /** Updates the `frame` width value - parameter newValue: the new value to assig */ private func updateWidth(_ newValue: CGFloat) { self.frame.size.width = newValue } /** Updates the `frame` X origin value - parameter newValue: the new value to assig */ private func updateX(_ newValue: CGFloat) { let relativeValue = self.hierarchyManager.getXCoordinate(newValue, inCoordinateSystemOfParentOfKey: self.key) self.frame.origin.x = relativeValue self.absoluteOrigin.x = newValue } /** Updates the `frame` Y origin value - parameter newValue: the new value to assig */ private func updateY(_ newValue: CGFloat) { let relativeValue = self.hierarchyManager.getYCoordinate(newValue, inCoordinateSystemOfParentOfKey: self.key) self.frame.origin.y = relativeValue self.absoluteOrigin.y = newValue } /// The height of the instance public var height: Value { get { return .fixed(self.frame.size.height) } set(newValue) { self.constraintY = .height let newHeight = max(scaleValue(newValue), 0) var newTop = self.top.coordinate if oldestConstraintY == .bottom { newTop = self.bottom.coordinate - newHeight } else if oldestConstraintY == .centerY { newTop = self.centerY.coordinate - newHeight / 2.0 } self.updateY(newTop) self.updateHeight(newHeight) } } /// The width of the instance public var width: Value { get { return .fixed(self.frame.size.width) } set(newValue) { self.constraintX = .width let newWidth = max(scaleValue(newValue), 0) var newLeft = self.left.coordinate if self.oldestConstraintX == .right { newLeft = self.right.coordinate - newWidth } else if self.oldestConstraintX == .centerX { newLeft = self.centerX.coordinate - newWidth / 2.0 } self.updateX(newLeft) self.updateWidth(newWidth) } } /** The bottom anchor of the instance. Setting its value sets the view's bottom edge position equal to the given anchor */ public var bottom: Anchor { get { return Anchor(kind: .bottom, view: self) } set(newValue) { self.constraintY = .bottom let newBottom = newValue.coordinate var newHeight = scaleValue(self.height) if oldestConstraintY == .top { newHeight = max(newBottom - self.top.coordinate, 0) } else if oldestConstraintY == .centerY { newHeight = max(2 * (newBottom - self.centerY.coordinate), 0) } self.updateY(newBottom - newHeight) self.updateHeight(newHeight) } } /** The top anchor of the instance. Setting its value sets the view's top edge position equal to the given anchor */ public var top: Anchor { get { return Anchor(kind: .top, view: self) } set(newValue) { self.constraintY = .top let newTop = newValue.coordinate var newHeight = scaleValue(self.height) if self.constraintY == .bottom { newHeight = max(self.bottom.coordinate - newTop, 0) } else if self.constraintY == .centerY { newHeight = max(2.0 * (self.centerY.coordinate - newTop), 0.0) } self.updateY(newTop) self.updateHeight(newHeight) } } /** The right anchor of the instance. Setting its value sets the view's right edge position equal to the given anchor */ public var right: Anchor { get { return Anchor(kind: .right, view: self) } set(newValue) { self.constraintX = .right let newRight = newValue.coordinate var newWidth = scaleValue(self.width) if self.oldestConstraintX == .left { newWidth = max(newRight - self.left.coordinate, 0.0) } else if self.oldestConstraintX == .centerX { newWidth = max(2.0 * (newRight - self.centerX.coordinate), 0.0) } self.updateX(newRight - newWidth) self.updateWidth(newWidth) } } /** The left anchor of the instance. Setting its value sets the view's left edge position equal to the given anchor */ public var left: Anchor { get { return Anchor(kind: .left, view: self) } set(newValue) { self.constraintX = .left let newLeft = newValue.coordinate var newWidth = scaleValue(self.width) if self.oldestConstraintX == .right { newWidth = max(self.right.coordinate - newLeft, 0) } else if self.oldestConstraintX == .centerX { newWidth = max(2.0 * (self.centerX.coordinate - newLeft), 0.0) } // update coords self.updateX(newLeft) self.updateWidth(newWidth) } } /** The horizontal center anchor of the instance. Setting its value sets the view's horizontal center position equal to the given anchor */ public var centerX: Anchor { get { return Anchor(kind: .centerX, view: self) } set(newValue) { self.constraintX = .centerX let newCenterX = newValue.coordinate var newWidth = scaleValue(self.width) if self.oldestConstraintX == .left { newWidth = max(2.0 * (newCenterX - self.left.coordinate), 0.0) } else if self.oldestConstraintX == .right { newWidth = max(2.0 * (self.right.coordinate - newCenterX), 0.0) } // update coords self.updateX(newCenterX - newWidth / 2.0) self.updateWidth(newWidth) } } /** The vertical center anchor of the instance. Setting its value sets the view's vertical center position equal to the given anchor */ public var centerY: Anchor { get { return Anchor(kind: .centerY, view: self) } set(newValue) { self.constraintY = .centerY let newCenterY = newValue.coordinate var newHeight = scaleValue(self.height) if self.oldestConstraintY == .top { newHeight = max(2.0 * (newCenterY - self.top.coordinate), 0.0) } else if self.oldestConstraintY == .bottom { newHeight = max(2.0 * (self.bottom.coordinate - newCenterY), 0.0) } // update coords self.updateY(newCenterY - newHeight / 2.0) self.updateHeight(newHeight) } } /// The size of the instance public var size: Size { get { return .fixed(self.frame.width, self.frame.height) } set(newValue) { self.height = newValue.height self.width = newValue.width } } }
mit
81e9eba7028dbcb393b7f850ac6a1af2
25.549223
113
0.664325
4.186275
false
false
false
false
rhcad/SwiftGraphics
SwiftGraphics/GenericGeometryTypes.swift
1
3585
// // IntGeometry.swift // SwiftGraphics // // Created by Jonathan Wight on 1/16/15. // Copyright (c) 2015 schwa.io. All rights reserved. // // MARK: A generic arithmetic type. /* Note this seems to cause the compiler to get very unhappy when inferring types and complain about. You'll see errors like: "error: expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions" To fix this specify the type explicitly so the compiler no longer needs to infer. Look for this comment to see places where I've had to do this: "(Unnecessarily specify CGFloat to prevent compiler from complaining about complexity while inferring type)" */ import CoreGraphics public protocol ArithmeticType: Comparable { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } extension Int: ArithmeticType { } extension UInt: ArithmeticType { } extension CGFloat: ArithmeticType { } // MARK: Protocols with associated types /* Due to a bug with Swift (http://openradar.appspot.com/myradars/edit?id=5241213351362560) we cannot make CG types conform to these protocols. Ideally instead of using CGPoint and friends we could just use PointType and our code would work with all types. */ public protocol PointType { typealias ScalarType var x:ScalarType { get } var y:ScalarType { get } } public protocol SizeType { typealias ScalarType var width:ScalarType { get } var height:ScalarType { get } } public protocol RectType { typealias OriginType typealias SizeType var origin:OriginType { get } var size:SizeType { get } } // MARK: Generic Points public struct GenericPoint <T:ArithmeticType> { public let x:T public let y:T public init(x:T, y:T) { self.x = x self.y = y } } extension GenericPoint: PointType { typealias ScalarType = T } // MARK: Generic Sizes public struct GenericSize <T:ArithmeticType> { public let width:T public let height:T public init(width:T, height:T) { self.width = width self.height = height } } extension GenericSize: SizeType { typealias ScalarType = T } // MARK: Generic Rects public struct GenericRect <T:PointType, U:SizeType> { public let origin:T public let size:U public init(origin:T, size:U) { self.origin = origin self.size = size } } extension GenericRect: RectType { typealias OriginType = T typealias SizeType = U } // MARK: Specialisations of Generic geometric types for Integers. public typealias IntPoint = GenericPoint<Int> public typealias IntSize = GenericSize<Int> public typealias IntRect = GenericRect<IntPoint, IntSize> public typealias UIntPoint = GenericPoint <UInt> public typealias UIntSize = GenericSize <UInt> public typealias UIntRect = GenericRect<UIntPoint, UIntSize> // MARK: Extensions extension GenericPoint: Equatable { } public func == <T> (lhs:GenericPoint <T>, rhs:GenericPoint <T>) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } extension GenericSize: Equatable { } public func == <T> (lhs:GenericSize <T>, rhs:GenericSize <T>) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } // TODO: Need more generic magic //extension GenericRect: Equatable { //} //public func == <T,U> (lhs:GenericRect <T,U>, rhs:GenericRect <T,U>) -> Bool { // return lhs.origin == rhs.origin && lhs.size == rhs.size //}
bsd-2-clause
96c730e89c6fd8b0dd711596273990bf
23.222973
175
0.690098
3.734375
false
false
false
false
rsmoz/swift-corelibs-foundation
TestFoundation/TestNSJSONSerialization.swift
1
21098
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSJSONSerialization : XCTestCase { let supportedEncodings = [ NSUTF8StringEncoding, NSUTF16LittleEndianStringEncoding, NSUTF16BigEndianStringEncoding, NSUTF32LittleEndianStringEncoding, NSUTF32BigEndianStringEncoding ] var allTests : [(String, () throws -> Void)] { return JSONObjectWithDataTests + deserializationTests + isValidJSONObjectTests } } //MARK: - JSONObjectWithData extension TestNSJSONSerialization { var JSONObjectWithDataTests: [(String, () throws -> Void)] { return [ ("test_JSONObjectWithData_emptyObject", test_JSONObjectWithData_emptyObject), ("test_JSONObjectWithData_encodingDetection", test_JSONObjectWithData_encodingDetection), ] } func test_JSONObjectWithData_emptyObject() { let subject = NSData(bytes: UnsafePointer<Void>([UInt8]([0x7B, 0x7D])), length: 2) let object = try! NSJSONSerialization.JSONObjectWithData(subject, options: []) as? [String:Any] XCTAssertEqual(object?.count, 0) } //MARK: - Encoding Detection func test_JSONObjectWithData_encodingDetection() { let subjects: [(String, [UInt8])] = [ // BOM Detection ("{} UTF-8 w/BOM", [0xEF, 0xBB, 0xBF, 0x7B, 0x7D]), ("{} UTF-16BE w/BOM", [0xFE, 0xFF, 0x0, 0x7B, 0x0, 0x7D]), ("{} UTF-16LE w/BOM", [0xFF, 0xFE, 0x7B, 0x0, 0x7D, 0x0]), ("{} UTF-32BE w/BOM", [0x00, 0x00, 0xFE, 0xFF, 0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]), ("{} UTF-32LE w/BOM", [0xFF, 0xFE, 0x00, 0x00, 0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]), // RFC4627 Detection ("{} UTF-8", [0x7B, 0x7D]), ("{} UTF-16BE", [0x0, 0x7B, 0x0, 0x7D]), ("{} UTF-16LE", [0x7B, 0x0, 0x7D, 0x0]), ("{} UTF-32BE", [0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]), ("{} UTF-32LE", [0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]), // // Single Characters // ("'3' UTF-8", [0x33]), // ("'3' UTF-16BE", [0x0, 0x33]), // ("'3' UTF-16LE", [0x33, 0x0]), ] for (description, encoded) in subjects { let result = try? NSJSONSerialization.JSONObjectWithData(NSData(bytes:UnsafePointer<Void>(encoded), length: encoded.count), options: []) XCTAssertNotNil(result, description) } } } //MARK: - JSONDeserialization extension TestNSJSONSerialization { var deserializationTests: [(String, () throws -> Void)] { return [ ("test_deserialize_emptyObject", test_deserialize_emptyObject), ("test_deserialize_multiStringObject", test_deserialize_multiStringObject), ("test_deserialize_emptyArray", test_deserialize_emptyArray), ("test_deserialize_multiStringArray", test_deserialize_multiStringArray), ("test_deserialize_unicodeString", test_deserialize_unicodeString), ("test_deserialize_values", test_deserialize_values), ("test_deserialize_numbers", test_deserialize_numbers), ("test_deserialize_simpleEscapeSequences", test_deserialize_simpleEscapeSequences), ("test_deserialize_unicodeEscapeSequence", test_deserialize_unicodeEscapeSequence), ("test_deserialize_unicodeSurrogatePairEscapeSequence", test_deserialize_unicodeSurrogatePairEscapeSequence), // Disabled due to uninitialized memory SR-606 // ("test_deserialize_allowFragments", test_deserialize_allowFragments), ("test_deserialize_unterminatedObjectString", test_deserialize_unterminatedObjectString), ("test_deserialize_missingObjectKey", test_deserialize_missingObjectKey), ("test_deserialize_unexpectedEndOfFile", test_deserialize_unexpectedEndOfFile), ("test_deserialize_invalidValueInObject", test_deserialize_invalidValueInObject), ("test_deserialize_invalidValueIncorrectSeparatorInObject", test_deserialize_invalidValueIncorrectSeparatorInObject), ("test_deserialize_invalidValueInArray", test_deserialize_invalidValueInArray), ("test_deserialize_badlyFormedArray", test_deserialize_badlyFormedArray), ("test_deserialize_invalidEscapeSequence", test_deserialize_invalidEscapeSequence), ("test_deserialize_unicodeMissingTrailingSurrogate", test_deserialize_unicodeMissingTrailingSurrogate), ] } //MARK: - Object Deserialization func test_deserialize_emptyObject() { let subject = "{}" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } let t = try NSJSONSerialization.JSONObjectWithData(data, options: []) let result = t as? [String: Any] XCTAssertEqual(result?.count, 0) } catch { XCTFail("Error thrown: \(error)") } } func test_deserialize_multiStringObject() { let subject = "{ \"hello\": \"world\", \"swift\": \"rocks\" }" do { for encoding in [NSUTF8StringEncoding, NSUTF16BigEndianStringEncoding] { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any] XCTAssertEqual(result?["hello"] as? String, "world") XCTAssertEqual(result?["swift"] as? String, "rocks") } } catch { XCTFail("Error thrown: \(error)") } } //MARK: - Array Deserialization func test_deserialize_emptyArray() { let subject = "[]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?.count, 0) } catch { XCTFail("Unexpected error: \(error)") } } func test_deserialize_multiStringArray() { let subject = "[\"hello\", \"swift⚡️\"]" do { for encoding in [NSUTF8StringEncoding, NSUTF16BigEndianStringEncoding] { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? String, "hello") XCTAssertEqual(result?[1] as? String, "swift⚡️") } } catch { XCTFail("Unexpected error: \(error)") } } func test_deserialize_unicodeString() { /// Ģ has the same LSB as quotation mark " (U+0022) so test guarding against this case let subject = "[\"unicode\", \"Ģ\", \"😢\"]" do { for encoding in [NSUTF16LittleEndianStringEncoding, NSUTF16BigEndianStringEncoding, NSUTF32LittleEndianStringEncoding, NSUTF32BigEndianStringEncoding] { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? String, "unicode") XCTAssertEqual(result?[1] as? String, "Ģ") XCTAssertEqual(result?[2] as? String, "😢") } } catch { XCTFail("Unexpected error: \(error)") } } //MARK: - Value parsing func test_deserialize_values() { let subject = "[true, false, \"hello\", null, {}, []]" do { for encoding in supportedEncodings { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? Bool, true) XCTAssertEqual(result?[1] as? Bool, false) XCTAssertEqual(result?[2] as? String, "hello") XCTAssertNotNil(result?[3] as? NSNull) XCTAssertNotNil(result?[4] as? [String:Any]) XCTAssertNotNil(result?[5] as? [Any]) } } catch { XCTFail("Unexpected error: \(error)") } } //MARK: - Number parsing func test_deserialize_numbers() { let subject = "[1, -1, 1.3, -1.3, 1e3, 1E-3]" do { for encoding in supportedEncodings { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? Double, 1) XCTAssertEqual(result?[1] as? Double, -1) XCTAssertEqual(result?[2] as? Double, 1.3) XCTAssertEqual(result?[3] as? Double, -1.3) XCTAssertEqual(result?[4] as? Double, 1000) XCTAssertEqual(result?[5] as? Double, 0.001) } } catch { XCTFail("Unexpected error: \(error)") } } //MARK: - Escape Sequences func test_deserialize_simpleEscapeSequences() { let subject = "[\"\\\"\", \"\\\\\", \"\\/\", \"\\b\", \"\\f\", \"\\n\", \"\\r\", \"\\t\"]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } let res = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] let result = res?.flatMap { $0 as? String } XCTAssertEqual(result?[0], "\"") XCTAssertEqual(result?[1], "\\") XCTAssertEqual(result?[2], "/") XCTAssertEqual(result?[3], "\u{08}") XCTAssertEqual(result?[4], "\u{0C}") XCTAssertEqual(result?[5], "\u{0A}") XCTAssertEqual(result?[6], "\u{0D}") XCTAssertEqual(result?[7], "\u{09}") } catch { XCTFail("Unexpected error: \(error)") } } func test_deserialize_unicodeEscapeSequence() { let subject = "[\"\\u2728\"]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? String, "✨") } catch { XCTFail("Unexpected error: \(error)") } } func test_deserialize_unicodeSurrogatePairEscapeSequence() { let subject = "[\"\\uD834\\udd1E\"]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Any] XCTAssertEqual(result?[0] as? String, "\u{1D11E}") } catch { XCTFail("Unexpected error: \(error)") } } func test_deserialize_allowFragments() { let subject = "3" do { for encoding in supportedEncodings { guard let data = subject.bridge().dataUsingEncoding(encoding) else { XCTFail("Unable to convert string to data") return } let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? Double XCTAssertEqual(result, 3) } } catch { XCTFail("Unexpected error: \(error)") } } //MARK: - Parsing Errors func test_deserialize_unterminatedObjectString() { let subject = "{\"}" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: UnterminatedString") } catch { // Passing case; the object as unterminated } } func test_deserialize_missingObjectKey() { let subject = "{3}" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Missing key for value") } catch { // Passing case; the key was missing for a value } } func test_deserialize_unexpectedEndOfFile() { let subject = "{" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Unexpected end of file") } catch { // Success } } func test_deserialize_invalidValueInObject() { let subject = "{\"error\":}" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Invalid value") } catch { // Passing case; the value is invalid } } func test_deserialize_invalidValueIncorrectSeparatorInObject() { let subject = "{\"missing\";}" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Invalid value") } catch { // passing case the value is invalid } } func test_deserialize_invalidValueInArray() { let subject = "[," do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Invalid value") } catch { // Passing case; the element in the array is missing } } func test_deserialize_badlyFormedArray() { let subject = "[2b4]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Badly formed array") } catch { // Passing case; the array is malformed } } func test_deserialize_invalidEscapeSequence() { let subject = "[\"\\e\"]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) XCTFail("Expected error: Invalid escape sequence") } catch { // Passing case; the escape sequence is invalid } } func test_deserialize_unicodeMissingTrailingSurrogate() { let subject = "[\"\\uD834\"]" do { guard let data = subject.bridge().dataUsingEncoding(NSUTF8StringEncoding) else { XCTFail("Unable to convert string to data") return } try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] XCTFail("Expected error: Missing Trailing Surrogate") } catch { // Passing case; the unicode character is malformed } } } // MARK: - isValidJSONObjectTests extension TestNSJSONSerialization { var isValidJSONObjectTests: [(String, () throws -> Void)] { return [ ("test_isValidJSONObjectTrue", test_isValidJSONObjectTrue), ("test_isValidJSONObjectFalse", test_isValidJSONObjectFalse), ] } func test_isValidJSONObjectTrue() { let trueJSON: [Any] = [ // [] Array<Any>(), // [1, ["string", [[]]]] Array<Any>(arrayLiteral: NSNumber(int: 1), Array<Any>(arrayLiteral: "string", Array<Any>(arrayLiteral: Array<Any>() ) ) ), // [NSNull(), ["1" : ["string", 1], "2" : NSNull()]] Array<Any>(arrayLiteral: NSNull(), Dictionary<String, Any>(dictionaryLiteral: ( "1", Array<Any>(arrayLiteral: "string", NSNumber(int: 1) ) ), ( "2", NSNull() ) ) ), // ["0" : 0] Dictionary<String, Any>(dictionaryLiteral: ( "0", NSNumber(int: 0) ) ) ] for testCase in trueJSON { XCTAssertTrue(NSJSONSerialization.isValidJSONObject(testCase)) } } func test_isValidJSONObjectFalse() { let falseJSON: [Any] = [ // 0 NSNumber(int: 0), // NSNull() NSNull(), // "string" "string", // [1, 2, 3, [4 : 5]] Array<Any>(arrayLiteral: NSNumber(int: 1), NSNumber(int: 2), NSNumber(int: 3), Dictionary<NSNumber, Any>(dictionaryLiteral: ( NSNumber(int: 4), NSNumber(int: 5) ) ) ), // [1, 2, Infinity] [NSNumber(int: 1), NSNumber(int: 2), NSNumber(double: 1 / 0)], // [NSNull() : 1] [NSNull() : NSNumber(int: 1)], // [[[[1 : 2]]]] Array<Any>(arrayLiteral: Array<Any>(arrayLiteral: Array<Any>(arrayLiteral: Dictionary<NSNumber, Any>(dictionaryLiteral: ( NSNumber(int: 1), NSNumber(int: 2) ) ) ) ) ) ] for testCase in falseJSON { XCTAssertFalse(NSJSONSerialization.isValidJSONObject(testCase)) } } }
apache-2.0
d3a86d56a0b19ab060da5f931ae6669d
36.507117
164
0.532331
5.030788
false
true
false
false
livio/HelloTrello
Pod/Classes/Card.swift
1
744
// // Card.swift // Pods // // Created by Joel Fischer on 4/8/16. // // import Foundation public struct Card: Codable { public let id: String public let name: String public let description: String? public let closed: Bool? public let position: Int? public let dueDate: Date? public let listId: String? public let memberIds: [String]? public let boardId: String? public let shortURL: String? public let labels: [Label]? enum CodingKeys: String, CodingKey { case id, name, description, closed, position, labels case listId = "idList" case memberIds = "idMembers" case boardId = "idBoard" case shortURL = "shortUrl" case dueDate = "due" } }
bsd-3-clause
ca8b7e222d256a20daf0c6b7e49b8263
22.25
60
0.630376
3.915789
false
false
false
false
ZwxWhite/V2EX
V2EX/V2EX/Class/Controller/Node(节点)/NodeViewController.swift
1
2213
// // NodeViewController.swift // V2EX // // Created by wenxuan.zhang on 15/11/12. // Copyright © 2015年 张文轩. All rights reserved. // 节点 import UIKit import Alamofire import RealmSwift import SwiftyJSON class NodeViewController: UICollectionViewController { var nodes = [V2NodeModel]() override func viewDidLoad() { super.viewDidLoad() self.loadNodes() if let flowLayout = self.collectionView!.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSizeMake(1, 1) flowLayout.minimumLineSpacing = 5 } self.collectionView?.contentInset = UIEdgeInsetsMake(0, 10, 10, 10) } } // MARK: - extension NodeViewController { private func loadNodes() { request(.GET, v2exBaseUrl+"/api/nodes/all.json", parameters: nil, encoding: .URL, headers: nil).responseJSON { (response) -> Void in switch response.result { case .Success(let responseResult): if let responseArray = responseResult as? NSArray { for dictionary in responseArray { let node = V2NodeModel(json: JSON(dictionary)) self.nodes.append(node) } } let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil) NSURLCache.setSharedURLCache(cache) self.collectionView?.reloadData() case .Failure(let error): printLog(error) } } } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.nodes.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("NodeCollectionCell", forIndexPath: indexPath) let label = cell.viewWithTag(1001) as! UILabel label.text = self.nodes[indexPath.row].title return cell } }
mit
cb821ccc3c4991ba9bd8cffe9674ab5a
28.72973
140
0.620455
5.188679
false
false
false
false
yonaskolb/XcodeGen
Sources/ProjectSpec/SpecOptions.swift
1
10166
import Foundation import JSONUtilities import Version public struct SpecOptions: Equatable { public static let settingPresetsDefault = SettingPresets.all public static let createIntermediateGroupsDefault = false public static let transitivelyLinkDependenciesDefault = false public static let groupSortPositionDefault = GroupSortPosition.bottom public static let generateEmptyDirectoriesDefault = false public static let findCarthageFrameworksDefault = false public static let useBaseInternationalizationDefault = true public static let schemePathPrefixDefault = "../../" public var minimumXcodeGenVersion: Version? public var carthageBuildPath: String? public var carthageExecutablePath: String? public var createIntermediateGroups: Bool public var bundleIdPrefix: String? public var settingPresets: SettingPresets public var disabledValidations: [ValidationType] public var developmentLanguage: String? public var usesTabs: Bool? public var tabWidth: UInt? public var indentWidth: UInt? public var xcodeVersion: String? public var deploymentTarget: DeploymentTarget public var defaultConfig: String? public var transitivelyLinkDependencies: Bool public var groupSortPosition: GroupSortPosition public var groupOrdering: [GroupOrdering] public var fileTypes: [String: FileType] public var generateEmptyDirectories: Bool public var findCarthageFrameworks: Bool public var localPackagesGroup: String? public var preGenCommand: String? public var postGenCommand: String? public var useBaseInternationalization: Bool public var schemePathPrefix: String public enum ValidationType: String { case missingConfigs case missingConfigFiles case missingTestPlans } public enum SettingPresets: String { case all case none case project case targets public var applyTarget: Bool { switch self { case .all, .targets: return true default: return false } } public var applyProject: Bool { switch self { case .all, .project: return true default: return false } } } /// Where groups are sorted in relation to other files public enum GroupSortPosition: String { /// groups are at the top case top /// groups are at the bottom case bottom /// groups are sorted with the rest of the files case none } public init( minimumXcodeGenVersion: Version? = nil, carthageBuildPath: String? = nil, carthageExecutablePath: String? = nil, createIntermediateGroups: Bool = createIntermediateGroupsDefault, bundleIdPrefix: String? = nil, settingPresets: SettingPresets = settingPresetsDefault, developmentLanguage: String? = nil, indentWidth: UInt? = nil, tabWidth: UInt? = nil, usesTabs: Bool? = nil, xcodeVersion: String? = nil, deploymentTarget: DeploymentTarget = .init(), disabledValidations: [ValidationType] = [], defaultConfig: String? = nil, transitivelyLinkDependencies: Bool = transitivelyLinkDependenciesDefault, groupSortPosition: GroupSortPosition = groupSortPositionDefault, groupOrdering: [GroupOrdering] = [], fileTypes: [String: FileType] = [:], generateEmptyDirectories: Bool = generateEmptyDirectoriesDefault, findCarthageFrameworks: Bool = findCarthageFrameworksDefault, localPackagesGroup: String? = nil, preGenCommand: String? = nil, postGenCommand: String? = nil, useBaseInternationalization: Bool = useBaseInternationalizationDefault, schemePathPrefix: String = schemePathPrefixDefault ) { self.minimumXcodeGenVersion = minimumXcodeGenVersion self.carthageBuildPath = carthageBuildPath self.carthageExecutablePath = carthageExecutablePath self.createIntermediateGroups = createIntermediateGroups self.bundleIdPrefix = bundleIdPrefix self.settingPresets = settingPresets self.developmentLanguage = developmentLanguage self.tabWidth = tabWidth self.indentWidth = indentWidth self.usesTabs = usesTabs self.xcodeVersion = xcodeVersion self.deploymentTarget = deploymentTarget self.disabledValidations = disabledValidations self.defaultConfig = defaultConfig self.transitivelyLinkDependencies = transitivelyLinkDependencies self.groupSortPosition = groupSortPosition self.groupOrdering = groupOrdering self.fileTypes = fileTypes self.generateEmptyDirectories = generateEmptyDirectories self.findCarthageFrameworks = findCarthageFrameworks self.localPackagesGroup = localPackagesGroup self.preGenCommand = preGenCommand self.postGenCommand = postGenCommand self.useBaseInternationalization = useBaseInternationalization self.schemePathPrefix = schemePathPrefix } } extension SpecOptions: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { if let string: String = jsonDictionary.json(atKeyPath: "minimumXcodeGenVersion") { minimumXcodeGenVersion = try Version.parse(string) } carthageBuildPath = jsonDictionary.json(atKeyPath: "carthageBuildPath") carthageExecutablePath = jsonDictionary.json(atKeyPath: "carthageExecutablePath") bundleIdPrefix = jsonDictionary.json(atKeyPath: "bundleIdPrefix") settingPresets = jsonDictionary.json(atKeyPath: "settingPresets") ?? SpecOptions.settingPresetsDefault createIntermediateGroups = jsonDictionary.json(atKeyPath: "createIntermediateGroups") ?? SpecOptions.createIntermediateGroupsDefault developmentLanguage = jsonDictionary.json(atKeyPath: "developmentLanguage") usesTabs = jsonDictionary.json(atKeyPath: "usesTabs") xcodeVersion = jsonDictionary.json(atKeyPath: "xcodeVersion") indentWidth = (jsonDictionary.json(atKeyPath: "indentWidth") as Int?).flatMap(UInt.init) tabWidth = (jsonDictionary.json(atKeyPath: "tabWidth") as Int?).flatMap(UInt.init) deploymentTarget = jsonDictionary.json(atKeyPath: "deploymentTarget") ?? DeploymentTarget() disabledValidations = jsonDictionary.json(atKeyPath: "disabledValidations") ?? [] defaultConfig = jsonDictionary.json(atKeyPath: "defaultConfig") transitivelyLinkDependencies = jsonDictionary.json(atKeyPath: "transitivelyLinkDependencies") ?? SpecOptions.transitivelyLinkDependenciesDefault groupSortPosition = jsonDictionary.json(atKeyPath: "groupSortPosition") ?? SpecOptions.groupSortPositionDefault groupOrdering = jsonDictionary.json(atKeyPath: "groupOrdering") ?? [] generateEmptyDirectories = jsonDictionary.json(atKeyPath: "generateEmptyDirectories") ?? SpecOptions.generateEmptyDirectoriesDefault findCarthageFrameworks = jsonDictionary.json(atKeyPath: "findCarthageFrameworks") ?? SpecOptions.findCarthageFrameworksDefault localPackagesGroup = jsonDictionary.json(atKeyPath: "localPackagesGroup") preGenCommand = jsonDictionary.json(atKeyPath: "preGenCommand") postGenCommand = jsonDictionary.json(atKeyPath: "postGenCommand") useBaseInternationalization = jsonDictionary.json(atKeyPath: "useBaseInternationalization") ?? SpecOptions.useBaseInternationalizationDefault schemePathPrefix = jsonDictionary.json(atKeyPath: "schemePathPrefix") ?? SpecOptions.schemePathPrefixDefault if jsonDictionary["fileTypes"] != nil { fileTypes = try jsonDictionary.json(atKeyPath: "fileTypes") } else { fileTypes = [:] } } } extension SpecOptions: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "deploymentTarget": deploymentTarget.toJSONValue(), "transitivelyLinkDependencies": transitivelyLinkDependencies, "groupSortPosition": groupSortPosition.rawValue, "disabledValidations": disabledValidations.map { $0.rawValue }, "minimumXcodeGenVersion": minimumXcodeGenVersion?.description, "carthageBuildPath": carthageBuildPath, "carthageExecutablePath": carthageExecutablePath, "bundleIdPrefix": bundleIdPrefix, "developmentLanguage": developmentLanguage, "usesTabs": usesTabs, "xcodeVersion": xcodeVersion, "indentWidth": indentWidth.flatMap { Int($0) }, "tabWidth": tabWidth.flatMap { Int($0) }, "defaultConfig": defaultConfig, "localPackagesGroup": localPackagesGroup, "preGenCommand": preGenCommand, "postGenCommand": postGenCommand, "fileTypes": fileTypes.mapValues { $0.toJSONValue() } ] if settingPresets != SpecOptions.settingPresetsDefault { dict["settingPresets"] = settingPresets.rawValue } if createIntermediateGroups != SpecOptions.createIntermediateGroupsDefault { dict["createIntermediateGroups"] = createIntermediateGroups } if generateEmptyDirectories != SpecOptions.generateEmptyDirectoriesDefault { dict["generateEmptyDirectories"] = generateEmptyDirectories } if findCarthageFrameworks != SpecOptions.findCarthageFrameworksDefault { dict["findCarthageFrameworks"] = findCarthageFrameworks } if useBaseInternationalization != SpecOptions.useBaseInternationalizationDefault { dict["useBaseInternationalization"] = useBaseInternationalization } if schemePathPrefix != SpecOptions.schemePathPrefixDefault { dict["schemePathPrefix"] = schemePathPrefix } return dict } } extension SpecOptions: PathContainer { static var pathProperties: [PathProperty] { [ .string("carthageBuildPath"), ] } }
mit
bcfcf83df87325d5126765d0422b907f
44.383929
152
0.705095
5.297551
false
false
false
false
avaidyam/Parrot
MochaUI/BlockTrampoline.swift
1
2705
import AppKit import Mocha public protocol BlockTrampolineSupporting: NSObjectProtocol { /*weak*/ var target: AnyObject? { get set } var action: Selector? { get set } } extension NSControl: BlockTrampolineSupporting {} extension NSMenuItem: BlockTrampolineSupporting {} public extension BlockTrampolineSupporting { var performedAction: (() -> ())? { get { guard let trampoline = BlockTrampoline.handlerProp[self] else { return nil } return trampoline.action } set { if let trampoline = BlockTrampoline.handlerProp[self], let update = newValue { trampoline.action = update } else if let update = newValue { let trampoline = BlockTrampoline(action: update) BlockTrampoline.handlerProp[self] = trampoline self.target = trampoline self.action = #selector(BlockTrampoline.performAction(_:)) } else { BlockTrampoline.handlerProp[self] = nil self.target = nil self.action = nil } } } } // // // public extension NSMenu { @discardableResult public func addItem(title: String, keyEquivalent: String = "", handler: @escaping () -> ()) -> NSMenuItem { let item = NSMenuItem(title: title, action: nil, keyEquivalent: keyEquivalent) item.performedAction = handler self.addItem(item) return item } } public extension NSMenuItem { public convenience init(title: String, isEnabled: Bool = true, target: AnyObject? = nil, action: String? = nil, keyEquivalent: String = "", modifierMask: NSEvent.ModifierFlags = [], _ submenuItems: [NSMenuItem]? = nil) { self.init(title: title, action: action != nil ? Selector(action!) : nil, keyEquivalent: keyEquivalent) self.isEnabled = isEnabled self.target = target self.keyEquivalentModifierMask = modifierMask if let submenuItems = submenuItems { let m = NSMenu(title: title) for x in submenuItems { m.addItem(x) } self.submenu = m } } } // // // @objc fileprivate class BlockTrampoline: NSObject { fileprivate typealias Action = () -> () fileprivate fileprivate(set) var action: Action fileprivate init(action: @escaping Action) { self.action = action } @objc dynamic fileprivate func performAction(_ sender: Any!) { self.action() } fileprivate static var handlerProp = AssociatedProperty<BlockTrampolineSupporting, BlockTrampoline>(.strong) }
mpl-2.0
d0d06681e419147d9cee2386167b65af
30.091954
224
0.606654
5
false
false
false
false
wibosco/CoreDataMigration-Example
CoreDataMigration-Example/CoreData/CoreDataManager.swift
1
2534
// // CoreDataManager.swift // CoreDataMigration-Example // // Created by William Boles on 11/09/2017. // Copyright © 2017 William Boles. All rights reserved. // import Foundation import CoreData class CoreDataManager { let migrator: CoreDataMigrator lazy var persistentContainer: NSPersistentContainer! = { let persistentContainer = NSPersistentContainer(name: "CoreDataMigration_Example") let description = persistentContainer.persistentStoreDescriptions.first description?.shouldInferMappingModelAutomatically = false //inferred mapping will be handled else where return persistentContainer }() lazy var backgroundContext: NSManagedObjectContext = { let context = self.persistentContainer.newBackgroundContext() context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return context }() lazy var mainContext: NSManagedObjectContext = { let context = self.persistentContainer.viewContext context.automaticallyMergesChangesFromParent = true return context }() // MARK: - Singleton static let shared = CoreDataManager() // MARK: - Init init(migrator: CoreDataMigrator = CoreDataMigrator()) { self.migrator = migrator } // MARK: - SetUp func setup(completion: @escaping () -> Void) { loadPersistentStore { completion() } } // MARK: - Loading private func loadPersistentStore(completion: @escaping () -> Void) { migrateStoreIfNeeded { self.persistentContainer.loadPersistentStores { description, error in guard error == nil else { fatalError("was unable to load store \(error!)") } completion() } } } private func migrateStoreIfNeeded(completion: @escaping () -> Void) { guard let storeURL = persistentContainer.persistentStoreDescriptions.first?.url else { fatalError("persistentContainer was not set up properly") } if migrator.requiresMigration(at: storeURL) { DispatchQueue.global(qos: .userInitiated).async { self.migrator.migrateStore(at: storeURL) DispatchQueue.main.async { completion() } } } else { completion() } } }
mit
3b572b5b4a59940139ba89e52651f344
27.784091
111
0.602448
6.045346
false
false
false
false
quickthyme/PUTcat
Tests/iOS/Project/ProjectSceneMock.swift
1
1886
import UIKit class ProjectSceneMock: ProjectScene { var sceneData: ProjectSceneData = ProjectSceneData(section: []) var projectID: String? var parentSceneDataItem: SceneDataItem = ProjectSceneDataItem() var resetSceneWasCalled = false var refreshSceneWasCalled = false var navigateWasCalled = false var navigateSegueID: String? var presentExportPickerWasCalled = false var presentSendEmailWithAttachmentWasCalled = false var presentSendEmailSubject: String? var presentSendEmailAttachment: Data? var presentSendEmailFilename: String? var presentSendEmailMimeType: String? var presentBasicAlertWasCalled = false var presentBasicAlertTitle: String? var presentBasicAlertMessage: String? var presentBasicAlertButton: String? var presentBasicAlertHandler: ((Any)->Void)? func set(parentSceneDataItem: SceneDataItem) { self.parentSceneDataItem = parentSceneDataItem } func resetScene() { resetSceneWasCalled = true } func refreshScene() { refreshSceneWasCalled = true } func navigate(segueID: String) { navigateWasCalled = true; navigateSegueID = segueID } func presentExportPicker() { presentExportPickerWasCalled = true } func presentSendEmailWithAttachment(subject: String, attachment: Data, filename: String, mimeType: String) { presentSendEmailWithAttachmentWasCalled = true presentSendEmailSubject = subject presentSendEmailAttachment = attachment presentSendEmailFilename = filename presentSendEmailMimeType = mimeType } func presentBasicAlert(title:String?, message:String?, button:String, handler: ((Any) -> Void)?) { presentBasicAlertWasCalled = false presentBasicAlertTitle = title presentBasicAlertMessage = message presentBasicAlertButton = button presentBasicAlertHandler = handler } }
apache-2.0
66a9376faf73e7cb93004855a7652801
42.860465
112
0.750265
5.253482
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Core/_Extensions/_Foundation/Error+Utils.swift
1
973
// // Error+Utils.swift // APExtensions // // Created by Anton Plebanovich on 6/28/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import Foundation public extension Error { /// Checks if cancelled error var isCancelledError: Bool { guard _domain == NSURLErrorDomain else { return false } return _code == NSURLErrorCancelled } /// Checks if error is related to connection problems. Usual flow is to retry on those errors. var isConnectionError: Bool { guard _domain == NSURLErrorDomain else { return false } return _code == NSURLErrorNotConnectedToInternet || _code == NSURLErrorCannotFindHost || _code == NSURLErrorCannotConnectToHost || _code == NSURLErrorInternationalRoamingOff || _code == NSURLErrorNetworkConnectionLost || _code == NSURLErrorDNSLookupFailed || _code == NSURLErrorTimedOut } }
mit
a96a4985a12bdc72837c3386b008eaad
29.375
98
0.639918
5.554286
false
false
false
false
honghaoz/2048-Solver-AI
2048 AI/AI/GameBoardAssistant.swift
1
8012
// Copyright © 2019 ChouTi. All rights reserved. import Foundation class GameboardAssistant: CustomStringConvertible { private let _goal: Int = 2048 private var _won: Bool = false // Size of the board private var _size: Int // Cells of the board private var _cell: [[Int]] // MARK: public properties var size: Int { return _size } var won: Bool { return _won } var cell: [[Int]] { return _cell } /// The max value of the game board var max: Int { var maxVal: Int = Int.min for i in 0..<_size { for j in 0..<_size { if _cell[i][j] > maxVal { maxVal = _cell[i][j] } } } return maxVal } // MARK: Printable var description: String { var board: String = String() for i in 0..<_size { for j in 0..<_size { board += String(format: "%d\t", _cell[i][j]) } board += "\n" } return board } subscript(x: Int, y: Int) -> Int { return _cell[y][x] } // MARK: Initializer init(size: Int = 4, won: Bool = false) { // Initialize the game board and add two new tiles self._cell = [[Int]](repeating: [Int](repeating: 0, count: size), count: size) self._size = size self._won = won addNewTile() addNewTile() } init(cells: [[Int]], won: Bool = false) { // Initialize the game board with a given board state self._cell = cells self._size = _cell[0].count self._won = won } // MARK: Deep copy func copy() -> GameboardAssistant { return GameboardAssistant(cells: _cell) } /// Get the location of all empty cells func getAllEmptyCells() -> [(x: Int, y: Int)] { var emptyCells: [(x: Int, y: Int)] = [] for i in 0..<_size { for j in 0..<_size { if _cell[j][i] == 0 { emptyCells.append((x: i, y: j)) } } } return emptyCells } // MARK: Public methods /// Test if a move to certain directino is valid func isMoveValid(_ dir: MoveDirection) -> Bool { for i in 0..<_size { for j in 0..<_size { switch dir { case .up: if j > 0, _cell[j][i] == _cell[j - 1][i] && _cell[j][i] != 0 || _cell[j][i] != 0 && _cell[j - 1][i] == 0 { return true } case .down: if j < _size - 1, _cell[j][i] == _cell[j + 1][i] && _cell[j][i] != 0 || _cell[j][i] != 0 && _cell[j + 1][i] == 0 { return true } case .left: if i > 0, _cell[j][i] == _cell[j][i - 1] && _cell[j][i] != 0 || _cell[j][i] != 0 && _cell[j][i - 1] == 0 { return true } case .right: if i < _size - 1, _cell[j][i] == _cell[j][i + 1] && _cell[j][i] != 0 || _cell[j][i] != 0 && _cell[j][i + 1] == 0 { return true } } } } return false } /// Make a move in certain direction, the precondition must be met that the move to this direction is valid. /// Return the score of such move @discardableResult func makeMove(_ dir: MoveDirection, toAddNewTile: Bool = true) -> Int { var hasMoved = false var score: Int = 0 // var setFun = dir == .up || dir == .down ? setRow : setCol // var getFun = dir == .up || dir == .down ? getRow : getRow // Move col if dir == .left || dir == .right { for j in 0..<_size { var oriRow = getRow(j) moveRowToDirection(&oriRow, dir: dir) let points = mergeRow(&oriRow, dir: dir) moveRowToDirection(&oriRow, dir: dir) setRow(j, vals: oriRow, moved: &hasMoved) score += points } } // Move row else { for i in 0..<_size { var oriCol = getCol(i) moveColToDirection(&oriCol, dir: dir) let points = mergeCol(&oriCol, dir: dir) moveColToDirection(&oriCol, dir: dir) setCol(i, vals: oriCol, moved: &hasMoved) score += points } } if hasMoved, toAddNewTile { addNewTile() } return score } /// Assign a value to a specific cell func setCell(_ x: Int, y: Int, val: Int) { _cell[y][x] = val } // MARK: Private methods /// Randomly assign a value to an empty cell private func addNewTile(_ valueSpecified: Int = 2) { var newTiles: [Int] = [Int](repeating: valueSpecified, count: 10) // If the tile value is not specified, then give a array of choices consisted of [2,2,2,2,2,2,2,2,2,4] if valueSpecified == 2 { newTiles[9] = 4 } // Get a random choice let randomChoice = newTiles[Int(arc4random_uniform(10))] var emptyCells = getAllEmptyCells() // If there exists some empty cell(s) if !emptyCells.isEmpty { let randomCellLoc = emptyCells[Int(arc4random_uniform(UInt32(emptyCells.count)))] setCell(randomCellLoc.x, y: randomCellLoc.y, val: randomChoice) } } /// See if every cell has a value private func allCellFull() -> Bool { return getAllEmptyCells().isEmpty } /// Get a copy of certain row private func getRow(_ x: Int) -> [Int] { return _cell[x] } /// Get a copy of certain col private func getCol(_ y: Int) -> [Int] { var col = [Int](repeating: -1, count: _size) for i in 0..<_size { col[i] = _cell[i][y] } return col } /// Assign values to an entire row private func setRow(_ row: Int, vals: [Int], moved: inout Bool) { for i in 0..<vals.count { if _cell[row][i] != vals[i] { moved = true } _cell[row][i] = vals[i] } } /// Assign values to an entire col private func setCol(_ col: Int, vals: [Int], moved: inout Bool) { for i in 0..<vals.count { if _cell[i][col] != vals[i] { moved = true } _cell[i][col] = vals[i] } } /// Merge row private func mergeRow(_ row: inout [Int], dir: MoveDirection) -> Int { assert(dir == .left || dir == .right, "The direction is not valid!") var points: Int = 0 var offset = 0 var range: [Int]? if dir == .left { range = (0..._size - 2).map { $0 } offset = 1 } else { range = Array((1..._size - 1).map { $0 }.reversed()) offset = -1 } for j in range! { if row[j] == 0 { continue } if row[j] == row[j + offset] { points += row[j] * 2 row[j] = row[j] * 2 row[j + offset] = 0 // Has reached the goal, win if row[j] == _goal { _won = true } } } return points } /// Merge col private func mergeCol(_ col: inout [Int], dir: MoveDirection) -> Int { assert(dir == .up || dir == .down, "The direction is not valid!") var points: Int = 0 var offset = 0 var range: [Int]? if dir == .up { range = (0..._size - 2).map { $0 } offset = 1 } else { range = Array((1..._size - 1).map { $0 }.reversed()) offset = -1 } for i in range! { if col[i] == 0 { continue } if col[i] == col[i + offset] { points += col[i] * 2 col[i] = col[i] * 2 col[i + offset] = 0 if col[i] == _goal { _won = true } } } return points } /// Move a row to a certain direction private func moveColToDirection(_ col: inout [Int], dir: MoveDirection) { assert(dir == .up || dir == .down, "The direction is not valid!") col = col.filter { element -> Bool in element != 0 } if dir == .up { col += [Int](repeating: 0, count: _size - col.count) } else { col = [Int](repeating: 0, count: _size - col.count) + col } } /// Move a col to a certain direction private func moveRowToDirection(_ row: inout [Int], dir: MoveDirection) { assert(dir == .left || dir == .right, "The direction is not valid!") row = row.filter { element -> Bool in element != 0 } if dir == .left { row += [Int](repeating: 0, count: _size - row.count) } else { row = [Int](repeating: 0, count: _size - row.count) + row } } }
gpl-2.0
8b51607265fadc433c1a8077bc4f9946
24.034375
124
0.524154
3.36314
false
false
false
false
remirobert/Dotzu-Objective-c
Pods/Dotzu/Dotzu/Log.swift
3
1561
// // Log.swift // exampleWindow // // Created by Remi Robert on 17/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class Log: NSObject, NSCoding { let level: LogLevel let id: String let fileInfo: String? let content: String let date: Date? init(content: String, fileInfo: String? = nil, level: LogLevel = .verbose) { id = NSUUID().uuidString self.fileInfo = fileInfo self.content = content self.level = level date = Date() } func encode(with aCoder: NSCoder) { aCoder.encode(fileInfo, forKey: "fileInfo") aCoder.encode(level.rawValue, forKey: "level") aCoder.encode(id, forKey: "id") aCoder.encode(content, forKey: "content") aCoder.encode(date, forKey: "date") } required init?(coder aDecoder: NSCoder) { fileInfo = aDecoder.decodeObject(forKey: "fileInfo") as? String level = LogLevel(rawValue: aDecoder.decodeInteger(forKey: "level")) ?? .error id = aDecoder.decodeObject(forKey: "id") as? String ?? "" content = aDecoder.decodeObject(forKey: "content") as? String ?? "" date = aDecoder.decodeObject(forKey: "date") as? Date } } extension Log: LogProtocol { var cell: UITableViewCell.Type { return LogTableViewCell.self } class func source() -> [LogProtocol] { let store = StoreManager<Log>(store: .log) return store.logs().filter({ LogLevelFilter.shared.enabled.contains($0.level) }) } }
mit
0e7c1e25eca0757e87a787a5d8fb3c22
27.363636
85
0.61859
4.0625
false
false
false
false
damicreabox/Git2Swift
Sources/Git2Swift/repository/Repository+Open.swift
1
4580
// // Repository+Init.swift // Git2Swift // // Created by Damien Giron on 31/07/2016. // Copyright © 2016 Creabox. All rights reserved. // import Foundation import CLibgit2 // MARK: - Repository extension for openning extension Repository { /// Constructor with URL and manager /// /// - parameter url: Repository URL /// - parameter manager: Repository manager /// /// - throws: GitError /// /// - returns: Repository convenience init(openAt url: URL, manager: RepositoryManager) throws { // Repository pointer let repository = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Init repo let error = git_repository_open(repository, url.path) if (error != 0) { repository.deinitialize() repository.deallocate(capacity: 1) throw gitUnknownError("Unable to open repository, url: \(url)", code: error) } self.init(at: url, manager: manager, repository: repository) } /// Init new repository at URL /// /// - parameter url: Repository URL /// - parameter manager: Repository manager /// - parameter signature: Initial commiter /// - parameter bare: Create bare repository /// - parameter shared: Share repository from users /// /// - throws: GitError /// /// - returns: Repository convenience init(initAt url: URL, manager: RepositoryManager, signature: Signature, bare: Bool, shared : Bool) throws { // Repository pointer let repository = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) // Options var options = git_repository_init_options() options.version = 1 if bare { // Set bare options.flags = GIT_REPOSITORY_INIT_BARE.rawValue } if shared { // Used shared options.mode = GIT_REPOSITORY_INIT_SHARED_ALL.rawValue } // Init repo let error = git_repository_init_ext(repository, url.path, &options) //let error = git_repository_init(repository, url.path, bare ? 1 : 0) if (error != 0) { repository.deinitialize() repository.deallocate(capacity: 1) throw gitUnknownError("Unable to init repository, url: \(url) (bare \(bare))", code: error) } self.init(at: url, manager: manager, repository: repository) } /// Clone a repository at URL /// /// - parameter url: URL to remote git /// - parameter at: URL to local respository /// - parameter manager: Repository manager /// - parameter authentication: Authentication /// - parameter progress: Object containing progress callbacks /// /// - throws: GitError wrapping libgit2 error /// /// - returns: Repository convenience init(cloneFrom url: URL, at: URL, manager: RepositoryManager, authentication: AuthenticationHandler? = nil, progress: Progress? = nil) throws { // Repository pointer let repository = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1) var opts = git_clone_options() opts.version = 1 // General checkouts opts.checkout_opts.version = 1 opts.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE.rawValue // General fetchs opts.fetch_opts.version = 1 opts.fetch_opts.prune = GIT_FETCH_PRUNE_UNSPECIFIED opts.fetch_opts.update_fetchhead = 1 opts.fetch_opts.callbacks.version = 1 // Set fetch progress setTransfertProgressHandler(options: &opts.fetch_opts.callbacks, progress: progress) // Check handler if (authentication != nil) { setAuthenticationCallback(&opts.fetch_opts.callbacks, authentication: authentication!) } // Clone repository let error = git_clone(repository, url.absoluteString, at.path, &opts) if (error != 0) { repository.deinitialize() repository.deallocate(capacity: 1) throw gitUnknownError("Unable to clone repository, from \(url) to: \(at)", code: error) } self.init(at: at, manager: manager, repository: repository) } }
apache-2.0
88ad5bc89b5e7d9fda2416cb23b43ea7
32.669118
103
0.574798
4.8661
false
false
false
false
MailOnline/ImageViewer
ImageViewer/Source/Extensions/CAShapeLayer.swift
2
4369
// // UIImage.swift // ImageViewer // // Created by Kristian Angyal on 28/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit extension CAShapeLayer { static func replayShape(_ fillColor: UIColor, triangleEdgeLength: CGFloat) -> CAShapeLayer { let triangle = CAShapeLayer() let altitude = (sqrt(3) / 2) * triangleEdgeLength triangle.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: altitude, height: triangleEdgeLength)) triangle.path = UIBezierPath.equilateralTriangle(triangleEdgeLength).cgPath triangle.fillColor = fillColor.cgColor return triangle } static func playShape(_ fillColor: UIColor, triangleEdgeLength: CGFloat) -> CAShapeLayer { let triangle = CAShapeLayer() let altitude = (sqrt(3) / 2) * triangleEdgeLength triangle.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: altitude, height: triangleEdgeLength)) triangle.path = UIBezierPath.equilateralTriangle(triangleEdgeLength).cgPath triangle.fillColor = fillColor.cgColor return triangle } static func pauseShape(_ fillColor: UIColor, elementSize: CGSize, elementDistance: CGFloat) -> CAShapeLayer { let element = CALayer() element.bounds.size = elementSize element.frame.origin = CGPoint.zero let secondElement = CALayer() secondElement.bounds.size = elementSize secondElement.frame.origin = CGPoint(x: elementSize.width + elementDistance, y: 0) [element, secondElement].forEach { $0.backgroundColor = fillColor.cgColor } let container = CAShapeLayer() container.bounds.size = CGSize(width: 2 * elementSize.width + elementDistance, height: elementSize.height) container.frame.origin = CGPoint.zero container.addSublayer(element) container.addSublayer(secondElement) return container } static func circle(_ fillColor: UIColor, diameter: CGFloat) -> CAShapeLayer { let circle = CAShapeLayer() let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: diameter * 2, height: diameter * 2)) circle.frame = frame circle.path = UIBezierPath(ovalIn: frame).cgPath circle.fillColor = fillColor.cgColor return circle } static func circlePlayShape(_ fillColor: UIColor, diameter: CGFloat) -> CAShapeLayer { let circle = CAShapeLayer() let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: diameter, height: diameter)) circle.frame = frame let circlePath = UIBezierPath(ovalIn: frame) let trianglePath = UIBezierPath.equilateralTriangle(diameter / 2, shiftBy: CGPoint(x: diameter / 3, y: diameter / 4)) circlePath.append(trianglePath) circle.path = circlePath.cgPath circle.fillColor = fillColor.cgColor return circle } static func closeShape(edgeLength: CGFloat) -> CAShapeLayer { let container = CAShapeLayer() container.bounds.size = CGSize(width: edgeLength + 4, height: edgeLength + 4) container.frame.origin = CGPoint.zero let linePath = UIBezierPath() linePath.move(to: CGPoint(x: 0, y: 0)) linePath.addLine(to: CGPoint(x: edgeLength, y: edgeLength)) linePath.move(to: CGPoint(x: 0, y: edgeLength)) linePath.addLine(to: CGPoint(x: edgeLength, y: 0)) let elementBorder = CAShapeLayer() elementBorder.bounds.size = CGSize(width: edgeLength, height: edgeLength) elementBorder.position = CGPoint(x: container.bounds.midX, y: container.bounds.midY) elementBorder.lineCap = CAShapeLayerLineCap.round elementBorder.path = linePath.cgPath elementBorder.strokeColor = UIColor.darkGray.cgColor elementBorder.lineWidth = 2.5 let elementFill = CAShapeLayer() elementFill.bounds.size = CGSize(width: edgeLength, height: edgeLength) elementFill.position = CGPoint(x: container.bounds.midX, y: container.bounds.midY) elementFill.lineCap = CAShapeLayerLineCap.round elementFill.path = linePath.cgPath elementFill.strokeColor = UIColor.white.cgColor elementFill.lineWidth = 2 container.addSublayer(elementBorder) container.addSublayer(elementFill) return container } }
mit
ddcee5d3862cf53aefb7fddb4b9958d5
36.655172
125
0.680861
4.70183
false
false
false
false
TinyCrayon/TinyCrayon-iOS-SDK
TCMask/CanvasView.swift
1
2008
// // CanvasView.swift // TinyCrayon // // Created by Xin Zeng on 2/16/16. // // import UIKit class CanvasView : UIView { let scaleFactor = UIScreen.main.scale var cacheContext: CGContext! var _data = [UInt8]() var data: [UInt8] { get {return _data} } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initCacheContext() } override init(frame: CGRect) { super.init(frame: frame) self.initCacheContext() } // http://www.effectiveui.com/blog/2011/12/02/how-to-build-a-simple-painting-app-for-ios/ // How to build a Simple Painting App for iOS override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext()! ctx.setBlendMode(CGBlendMode.copy) // Draw cache image to ctx let width = CGFloat(cacheContext.width) let height = CGFloat(cacheContext.height) let scaleX = width / self.bounds.size.width let scaleY = height / self.bounds.size.height let scaledRect = CGRect(x: round(rect.origin.x * scaleX), y: round(height - rect.origin.y * scaleY - rect.size.height * scaleY), width: round(rect.size.width * scaleX), height: round(rect.size.height * scaleY)) let cacheImage = cacheContext.makeImage()!.cropping(to: scaledRect) ctx.draw(cacheImage!, in: rect) } func initCacheContext() { let width = Int(round(self.width * scaleFactor)) let height = Int(round(self.height * scaleFactor)) self._data = [UInt8](repeating: 0, count: width * height * 4) self.cacheContext = CGContext(data: &_data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! cacheContext.setLineCap(CGLineCap.round) cacheContext.setLineJoin(CGLineJoin.round) cacheContext.setShouldAntialias(false) } deinit { } }
mit
88d86651c9475b4c3815a670821c093e
34.857143
222
0.64741
3.992048
false
false
false
false
benlangmuir/swift
test/attr/Inputs/PackageDescription.swift
19
1399
public enum SwiftVersion { // CHECK: @available(_PackageDescription, introduced: 3.0, deprecated: 4.2, obsoleted: 5.0) @available(_PackageDescription, introduced: 3.0, deprecated: 4.2, obsoleted: 5.0) case v3 case v4 // CHECK: @available(_PackageDescription 5.0) // CHECK-NEXT: @available(macOS 10.1, *) // CHECK-NEXT: v5 @available(_PackageDescription, introduced: 5.0) @available(macOS, introduced: 10.1) case v5 } public class Package { public var swiftVersion: [SwiftVersion] @available(_PackageDescription 4.3) public var buildSettings: [String: String] { get { return _buildSettings } set { _buildSettings = newValue } } private var _buildSettings: [String: String] @available(_PackageDescription 5) public init( swiftVersion: [SwiftVersion] = [], buildSettings: [String: String] = [:] ) { self._buildSettings = buildSettings self.swiftVersion = swiftVersion } @available(_PackageDescription, introduced: 3.0, obsoleted: 5.0) public init( swiftVersion: [SwiftVersion] = [] ) { self._buildSettings = [:] self.swiftVersion = swiftVersion } public func serialize() { for version in swiftVersion { print(version) } print(_buildSettings) } }
apache-2.0
cdb3e18073d420361a7168baebbd827d
24.907407
95
0.606147
4.331269
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/Detail/Views/ReaderDetailCommentsTableViewDelegate.swift
1
6928
import UIKit /// Table View delegate to handle the Comments table displayed in Reader Post details. /// class ReaderDetailCommentsTableViewDelegate: NSObject, UITableViewDataSource, UITableViewDelegate { // MARK: - Private Properties private(set) var totalComments = 0 private var post: ReaderPost? private var presentingViewController: UIViewController? private weak var buttonDelegate: BorderedButtonTableViewCellDelegate? private(set) var headerView: ReaderDetailCommentsHeader? var followButtonTappedClosure: (() ->Void)? private var totalRows = 0 private var hideButton = true private var comments: [Comment] = [] { didSet { totalRows = { // If there are no comments and commenting is closed, 1 empty cell. if hideButton { return 1 } // If there are no comments, 1 empty cell + 1 button. if comments.count == 0 { return 2 } // Otherwise add 1 for the button. return comments.count + 1 }() } } private var commentsEnabled: Bool { return post?.commentsOpen ?? false } // MARK: - Public Methods func updateWith(post: ReaderPost, comments: [Comment] = [], totalComments: Int = 0, presentingViewController: UIViewController, buttonDelegate: BorderedButtonTableViewCellDelegate? = nil) { self.post = post hideButton = (comments.count == 0 && !commentsEnabled) self.comments = comments self.totalComments = totalComments self.presentingViewController = presentingViewController self.buttonDelegate = buttonDelegate } func updateFollowButtonState(post: ReaderPost) { self.post = post headerView?.updateFollowButtonState(post: post) } func followButtonMidPoint() -> CGPoint? { headerView?.followButtonMidPoint() } // MARK: - Table Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return totalRows } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == (totalRows - 1) && !hideButton { return showCommentsButtonCell() } if let comment = comments[safe: indexPath.row] { guard let cell = tableView.dequeueReusableCell(withIdentifier: CommentContentTableViewCell.defaultReuseID) as? CommentContentTableViewCell else { return UITableViewCell() } cell.configureForPostDetails(with: comment) { _ in tableView.performBatchUpdates({}) } return cell } guard let cell = tableView.dequeueReusableCell(withIdentifier: ReaderDetailNoCommentCell.defaultReuseID) as? ReaderDetailNoCommentCell else { return UITableViewCell() } cell.titleLabel.text = commentsEnabled ? Constants.noComments : Constants.closedComments return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: ReaderDetailCommentsHeader.defaultReuseID) as? ReaderDetailCommentsHeader, let post = post, let presentingViewController = presentingViewController else { return nil } header.configure( post: post, totalComments: totalComments, presentingViewController: presentingViewController, followButtonTappedClosure: followButtonTappedClosure ) headerView = header return header } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { /// We used this method to show the Jetpack badge rather than setting `tableFooterView` because it scaled better with Dynamic type. guard section == 0, JetpackBrandingVisibility.all.enabled else { return nil } return JetpackButton.makeBadgeView(bottomPadding: Constants.jetpackBadgeBottomPadding, target: self, selector: #selector(jetpackButtonTapped)) } func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return ReaderDetailCommentsHeader.estimatedHeight } func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { return ReaderDetailCommentsHeader.estimatedHeight } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { guard section == 0, JetpackBrandingVisibility.all.enabled else { return 0 } return UITableView.automaticDimension } } private extension ReaderDetailCommentsTableViewDelegate { func showCommentsButtonCell() -> BorderedButtonTableViewCell { let cell = BorderedButtonTableViewCell() let title = totalComments == 0 ? Constants.leaveCommentButtonTitle : Constants.viewAllButtonTitle cell.configure(buttonTitle: title, borderColor: .textTertiary, buttonInsets: Constants.buttonInsets) cell.delegate = buttonDelegate return cell } @objc func jetpackButtonTapped() { guard let presentingViewController = presentingViewController else { return } JetpackBrandingCoordinator.presentOverlay(from: presentingViewController) JetpackBrandingAnalyticsHelper.trackJetpackPoweredBadgeTapped(screen: .readerDetail) } struct Constants { static let noComments = NSLocalizedString("No comments yet", comment: "Displayed on the post details page when there are no post comments.") static let closedComments = NSLocalizedString("Comments are closed", comment: "Displayed on the post details page when there are no post comments and commenting is closed.") static let viewAllButtonTitle = NSLocalizedString("View all comments", comment: "Title for button on the post details page to show all comments when tapped.") static let leaveCommentButtonTitle = NSLocalizedString("Be the first to comment", comment: "Title for button on the post details page when there are no comments.") static let buttonInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) static let jetpackBadgeBottomPadding: CGFloat = 10 } }
gpl-2.0
75acf34e085581337cfca5e96b2993b8
39.046243
181
0.664261
5.802345
false
false
false
false
kellanburket/Passenger
Example/Pods/Wildcard/Pod/Classes/Wildcard.swift
1
22728
// // Wildcard.swift // Wildcard // // Created by Kellan Cummings on 6/6/15. // Copyright (c) 2015 Kellan Cummings. All rights reserved. // import UIKit private let consonant = "[b-df-hj-np-tv-z]" private let vowel = "[aeiou]" let plurals: [(String, String)] = [ ("(?<=f)oo(?=t)$|(?<=t)oo(?=th)$|(?<=g)oo(?=se)$", "ee"), ("(?<=i)fe$|(?<=[eao]l)f$|(?<=(l|sh)ea)f$", "ves"), ("(\\w{2,})[ie]x", "$1ices"), ("(?<=[ml])ouse$", "ice"), ("man$", "men"), ("child$", "children"), ("person$", "people"), ("eau$", "eaux"), ("(?<=-by)$", "s"), ("(?<=[^q]\(vowel)y)$", "s"), ("y$", "ies"), ("(?<=s|sh|tch)$", "es"), ("(?<=\(vowel)\(consonant)i)um", "a"), ("(?<=\\w)$", "s") //"a$": "ae", //"us$": "i" //"us$": "ora", //"us$": "era", ] let singulars: [(String, String)] = [ ("(?<=f)ee(?=t)$|(?<=t)ee(?=th)$|(?<=g)ee(?=se)$", "oo"), ("(?<=i)ves$", "fe"), ("(?<=[eao]l)ves$|(?<=(l|sh)ea)ves$", "f"), ("(?<=[ml])ice$", "ouse"), ("men$", "man"), ("children$", "child"), ("people$", "person"), ("eaux$", "eau"), ("(?<=-by)s$", ""), ("(?<=[^q]\(vowel)y)s$", ""), ("ies$", "y"), ("(?<=s|sh|tch)es$", ""), ("(?<=\(vowel)\(consonant)i)a", "um"), ("(?<=\\w)s$", "") ] private let irregulars: [String:String] = [ "potato": "potatoes", "di": "dice", "appendix": "appendices", "index": "indices", "matrix": "matrices", "radix": "radices", "vertex": "vertices", "radius": "radii", "goose": "geese" ] infix operator =~ { associativity left precedence 140 } /** Checks if the input matches the pattern :param: left the input string :param: right the pattern :returns: returns true if pattern exists in the input string */ public func =~(left: String, right: String) -> Bool { return left.match(right) != nil } public extension String { /** Convert a string into an NSDate object. Currently supports both backslashes and hyphens in the following formats: * Y-m-d * m-d-Y * Y-n-j * n-j-Y :returns: a date */ public func toDate() -> NSDate? { //println("to Date: \(self)") var patterns = [ "\\w+ (\\w+) (\\d+) (\\d{1,2}):(\\d{1,2}):(\\d{1,2}) \\+\\d{4} (\\d{4})": ["month", "day", "hour", "minute", "second", "year"], "(\\d{4})[-\\/](\\d{1,2})[-\\/](\\d{1,2})(?: (\\d{1,2}):(\\d{1,2}):(\\d{1,2}))?": ["year", "month", "day", "hour", "minute", "second"], "(\\d{1,2})[-\\/](\\d{1,2})[-\\/](\\d{4})(?: (\\d{1,2}):(\\d{1,2}):(\\d{1,2}))?": ["month", "day", "year", "hour", "minute", "second"] ] for (pattern, map) in patterns { if let matches = self.match(pattern) { //println("Matches \(matches)") if(matches.count >= 4) { var dictionary = [String:String]() for (i, item) in enumerate(map) { if i + 1 < matches.count { dictionary[item] = matches[i + 1] } else { break } } let calendar = NSCalendar.currentCalendar() let comp = NSDateComponents() comp.year = 0 if let year = dictionary["year"]?.toInt() { comp.year = year } comp.month = 0 if let month = dictionary["month"] { if let month = month.toInt() { comp.month = month } else { var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] for (i, m) in enumerate(months) { if month =~ m { comp.month = i break } } } } comp.day = 0 if let day = dictionary["day"]?.toInt() { comp.day = day } comp.hour = 0 if let hour = dictionary["hour"]?.toInt() { comp.hour = hour } comp.minute = 0 if let minute = dictionary["minute"]?.toInt() { comp.minute = minute } comp.second = 0 if let second = dictionary["second"]?.toInt() { comp.second = second } return calendar.dateFromComponents(comp) } } } return nil } /** Split a string into an array of strings by slicing at delimiter :param: delimiter character(s) to split string at :returns: an array of strings if delimiter matches, or an array with the original string as its only component */ public func split(delimiter: String) -> [String] { var parsedDelimiter: String = NSRegularExpression.escapedPatternForString(delimiter) if let matches = self.scan("(.+?)(?:\(parsedDelimiter)|$)") { var arr = [String]() for match in matches { arr.append(match[1]) } return arr } else { return [self] } } /** Substitute result of callback function for all occurences of pattern :param: pattern a regular expression string to match against :param: callback a callback function to call on pattern match success :returns: modified string */ public func gsub(pattern: String, callback: ((String) -> (String))) -> String { var regex = RegExp(pattern) return regex.gsub(self, callback: callback) } /** Substitute result of callback function for all occurences of pattern. The following flags are permitted: * i: case-insenstive match * x: ignore #-prefixed comments and whitespace in this pattern * s: `.` matches `\n` * m: `^`, `$` match the beginning and end of lines, respectively (set by default) * w: use unicode word boundaries * c: ignore metacharacters when matching (e.g, `\w`, `\d`, `\s`, etc..) * l: use only `\n` as a line separator :param: pattern an ICU-style regular expression :param: options a string containing option flags :param: callback a callback function to call on pattern match success :returns: modified string */ public func gsub(pattern: String, options: String, callback: ((String) -> (String))) -> String { var regex = RegExp(pattern, options) return regex.gsub(self, callback: callback) } /** Convenience wrapper for gsub with options */ public func gsub(pattern: String, _ replacement: String, options: String = "") -> String { var regex = RegExp(pattern, options) return regex.gsub(self, replacement) } /** Convenience wrapper for case-insenstive gsub */ public func gsubi(pattern: String, _ replacement: String, options: String = "") -> String { var regex = RegExp(pattern, "\(options)i") return regex.gsub(self, replacement) } /** Convenience wrapper for case-insensitive gsub with callback */ public func gsubi(pattern: String, callback: ((String) -> (String))) -> String { var regex = RegExp(pattern, "i") return regex.gsub(self, callback: callback) } /** Convenience wrapper for case-insensitive gsub with callback and options */ public func gsubi(pattern: String, options: String, callback: ((String) -> (String))) -> String { var regex = RegExp(pattern, "\(options)i") return regex.gsub(self, callback: callback) } /** Conveneience wrapper for first-match-only substitution */ public func sub(pattern: String, _ replacement: String, options: String = "") -> String { var regex = RegExp(pattern, options) return regex.sub(self, replacement) } /** Conveneience wrapper for case-insensitive first-match-only substitution */ public func subi(pattern: String, _ replacement: String, options: String = "") -> String { var regex = RegExp(pattern, "\(options)i") return regex.sub(self, replacement) } /** Scans and matches only the first pattern :param: pattern the pattern to search against :param: (not-required) options for matching--see documentation for `gsub`; defaults to "" :returns: an array of all matches to the first pattern */ public func match(pattern: String, _ options: String = "") -> [String]? { return RegExp(pattern, options).match(self) } /** Scans and matches all patterns :param: pattern the pattern to search against :param: (not-required) options for matching--see documentation for `gsub`; defaults to "" :returns: an array of arrays of each matched pattern */ public func scan(pattern: String, _ options: String = "") -> [[String]]? { return RegExp(pattern, options).scan(self) } /** Slices out the parts of the string that match the pattern :param: pattern the pattern to search against :returns: an array of the slices */ public mutating func slice(pattern: String) -> [[String]]? { var matches = self.scan(pattern) self = self.gsub(pattern, "") return matches } /** Strip white space or aditional specified characters from beginning or end of string :param: a string of any characters additional characters to strip off beginning/end of string :returns: trimmed string */ public func trim(_ characters: String = "") -> String { var parsedCharacters = NSRegularExpression.escapedPatternForString(characters) return self.gsub("^[\\s\(parsedCharacters)]+|[\\s\(parsedCharacters)]+$", "") } /** Strip white space or aditional specified characters from end of string :param: a string of any characters additional characters to strip off end of string :returns: trimmed string */ public func rtrim(_ characters: String = "") -> String { var parsedCharacters = NSRegularExpression.escapedPatternForString(characters) return self.gsub("[\\s\(parsedCharacters)]+$", "") } /** Strip white space or aditional specified characters from beginning of string :param: a string of any characters additional characters to strip off beginning of string :returns: trimmed string */ public func ltrim(_ characters: String = "") -> String { var parsedCharacters = NSRegularExpression.escapedPatternForString(characters) return self.gsub("^[\\s\(parsedCharacters)]+", "") } /** Converts Html special characters (e.g. '&#169;' => '©') :returns: converted string */ public func decodeHtmlSpecialCharacters() -> String { var regex = RegExp("&#[a-fA-F\\d]+;") return regex.gsub(self) { pattern in var hex = RegExp("[a-fA-F\\d]+") if let matches = hex.match(pattern) { if let sint = matches[0].toInt() { var character = Character(UnicodeScalar(UInt32(sint))) return "\(character)" } } println("There was an issue while trying to decode character '\(pattern)'") return "" } } /** Converts a string to camelcase. e.g.: 'hello_world' -> 'HelloWorld' :returns: a formatted string */ public func toCamelcase() -> String { return gsub("[_\\-\\s]\\w") { match in return match[advance(match.startIndex, 1)..<match.endIndex].uppercaseString } } /** Converts a string to snakecase. e.g.: 'HelloWorld' -> 'hello_world' :param: language (Reserved for future use) :returns: a formatted string */ public func toSnakecase() -> String { return gsub("[\\s-]\\w") { match in return "_" + match[advance(match.startIndex, 1)..<match.endIndex].lowercaseString }.gsub("(?<!^)\\p{Lu}") { match in return "_\(match.lowercaseString)" }.lowercaseString } /** DEVELOPMENTAL METHOD: Change String from singular to plural. :param: language (Reserved for future use) :returns: a plural string */ public func pluralize(language: String = "en/us") -> String { if let plural = irregulars[self] { return plural } for (regex, mod) in plurals { var replacement = self.gsubi(regex, mod) if replacement != self { return replacement } } return self } /** DEVELOPMENTAL METHOD: Change String from plural to singular. :returns: a singular string */ public func singularize(language: String = "en/us") -> String { if let plurals = irregulars.flip(), plural = plurals[self] { return plural } for (regex, mod) in singulars { var replacement = self.gsubi(regex, mod) if replacement != self { return replacement } } return self } /** Set the first letter to lowercase :returns: formatted string */ public func decapitalize() -> String { var prefix = self[startIndex..<advance(startIndex, 1)].lowercaseString var body = self[advance(startIndex, 1)..<endIndex] return "\(prefix)\(body)" } /** Set the first letter to uppercase :returns: formatted string */ public func capitalize() -> String { var prefix = self[startIndex..<advance(startIndex, 1)].uppercaseString var body = self[advance(startIndex, 1)..<endIndex] return "\(prefix)\(body)" } /** Repeat String x times. :param: the number of times to repeat :returns: formatted string */ public func repeat(times: Int) -> String { var rstring = "" if times > 0 { for i in 0...times { rstring = "\(rstring)\(self)" } } return rstring } /** Attribute matched subpatterns and trim. The following attributes are permitted: * UIFont set the font * NSParagraphStyle set paragraph styling * UIColor set font color :param: attributes a dictionary with the pattern as the key and an array of style attributes as values. :param: font (optional) default font :returns: an attributed string with styles applied */ public func attribute(attributes: [String: [AnyObject]], font: UIFont? = nil) -> NSAttributedString { var textAttrs = [TextAttribute]() for (pattern, attrs) in attributes { var map = [NSObject: AnyObject]() for attr in attrs { if attr is UIFont { map[NSFontAttributeName] = attr } else if attr is NSParagraphStyle { map[NSParagraphStyleAttributeName] = attr } else if attr is UIColor { map[NSForegroundColorAttributeName] = attr } } textAttrs.append(TextAttribute(pattern: pattern, attribute: map)) } return RegExp(attributes: textAttrs).attribute(self, font: font) } /** Attribute matched subpatterns and trim :param: attributes an array of TextAttribute objects :param: font default font :returns: an attributed string with styles applied */ public func attribute(attributes: [TextAttribute], font: UIFont? = nil) -> NSAttributedString { return RegExp(attributes: attributes).attribute(self, font: font) } /** Helper method that parses an Html string and converts it to an attributed string. Currently the default styles are as follows: * p, ul, ol, div, section, main: * paragraph style: * firstLineHeadIndent: 17 * headIndent: 20 * paragraphSpacing: 12 * li * paragraph style: * firstLineHeadIndent: 20 * headIndent: 30 * paragraphSpacing: 7 * b, bold, strong: boldSystemFontOfSize(12) * i, em: italicSystemFontOfSize(12) * h1: boldSystemFontOfSize(24) * h2: boldSystemFontOfSize(20) * h3: italicSystemFontOfSize(18) * h4: boldSystemFontOfSize(16) * h5: systemFontOfSize(15) To ovverride the defaults do something like this: var str = "Hello World" var style = NSParagraphStyle() style.setValue(CGFloat(16), forKey: "paragraphSpacing") var font = UIFont.systemFontOfSize(16) var attrStr = str.attributeHtml(map: ["p": [style, font]]) :param: map override default html properties passing in an array of variables which can be either NSParagraphStyle, UIFont, or UIColor variables. :returns: an attributed strings without html tags */ public func attributeHtml(map: [String:[AnyObject]] = [String:[AnyObject]]()) -> NSAttributedString { var str = self.decodeHtmlSpecialCharacters().gsub("\\<.*br>", "\n") var paragraphStyle = NSParagraphStyle() paragraphStyle.setValue(CGFloat(17), forKey: "firstLineHeadIndent") paragraphStyle.setValue(CGFloat(20), forKey: "headIndent") paragraphStyle.setValue(CGFloat(12), forKey: "paragraphSpacing") var listStyle = NSParagraphStyle() listStyle.setValue(CGFloat(20), forKey: "firstLineHeadIndent") listStyle.setValue(CGFloat(30), forKey: "headIndent") listStyle.setValue(CGFloat(7), forKey: "paragraphSpacing") var attributes: [String:[AnyObject]] = [ "li": [listStyle], "b": [UIFont.boldSystemFontOfSize(12)], "bold": [UIFont.boldSystemFontOfSize(12)], "strong": [UIFont.boldSystemFontOfSize(12)], "i": [UIFont.italicSystemFontOfSize(12)], "em": [UIFont.italicSystemFontOfSize(12)], "a": [UIFont.systemFontOfSize(12)], "p": [paragraphStyle], "ul": [paragraphStyle], "ol": [paragraphStyle], "div": [paragraphStyle], "section": [paragraphStyle], "main": [paragraphStyle], "h1": [UIFont.boldSystemFontOfSize(24)], "h2": [UIFont.boldSystemFontOfSize(20)], "h3": [UIFont.italicSystemFontOfSize(18)], "h4": [UIFont.boldSystemFontOfSize(16)], "h5": [UIFont.systemFontOfSize(15)], ] for (k, v) in map { attributes[k] = v } var parsedAttributes = [String:[AnyObject]]() for (el, attr) in attributes { parsedAttributes["\\<\(el).*?>(.+?)\\<\\/\(el)>"] = attr } return str.attribute(parsedAttributes) } internal func substringWithNSRange(range: NSRange) -> String { return substringWithRange(range.toStringIndexRange(self)) } internal func substringRanges(pattern: String, _ options: String = "") -> [RegExpMatch]? { return RegExp(pattern, options).getSubstringRanges(self) } internal func toMutable() -> NSMutableString { var capacity = Swift.count(self.utf16) var mutable = NSMutableString(capacity: capacity) mutable.appendString(self) return mutable } internal func toRange() -> NSRange { let capacity = Swift.count(self.utf16) return NSMakeRange(0, capacity) } } internal extension NSMutableString { internal func gsub(pattern: String, _ replacement: String) -> NSMutableString { var regex = RegExp(pattern) return regex.gsub(self, replacement) } internal func substringRanges(pattern: String, _ options: String = "") -> [RegExpMatch]? { return RegExp(pattern, options).getSubstringRanges(self as String) } } internal extension NSMutableAttributedString { internal func substringRanges(pattern: String, _ options: String = "") -> [RegExpMatch]? { return RegExp(pattern, options).getSubstringRanges(self) } } internal extension NSRange { internal func toStringIndexRange(input: String) -> Range<String.Index> { if location < count(input.utf16) { var startIndex = advance(input.startIndex, location) var endIndex = advance(input.startIndex, location + length) var range = Range(start: startIndex, end: endIndex) //println(input.substringWithRange(range)) return range } //println("Count: \(count(input.utf16))") //println("Location: \(location)") return Range(start: input.startIndex, end: input.endIndex) } } internal extension Dictionary { internal func flip() -> Dictionary<Key, Value>? { if Key.self is Value.Type { var out = Dictionary<Key, Value>() for key in self.keys { if let value = self[key] as? Key, key = key as? Value { out[value] = key } } return out.count > 0 ? out : nil } return nil } }
mit
f8f46d775b7914e4c726a4e8599e5d8f
32.522124
153
0.526906
4.554509
false
false
false
false
tomtclai/swift-algorithm-club
Set Cover (Unweighted)/SetCover.playground/Sources/RandomArrayOfSets.swift
7
1171
import Foundation public func randomArrayOfSets<T>(covering universe: Set<T>, minArraySizeFactor: Double = 0.8, maxSetSizeFactor: Double = 0.6) -> Array<Set<T>> { var result = [Set<T>]() var ongoingUnion = Set<T>() let minArraySize = Int(Double(universe.count) * minArraySizeFactor) var maxSetSize = Int(Double(universe.count) * maxSetSizeFactor) if maxSetSize > universe.count { maxSetSize = universe.count } while true { var generatedSet = Set<T>() let targetSetSize = Int(arc4random_uniform(UInt32(maxSetSize)) + 1) while true { let randomUniverseIndex = Int(arc4random_uniform(UInt32(universe.count))) for (setIndex, value) in universe.enumerated() { if setIndex == randomUniverseIndex { generatedSet.insert(value) break } } if generatedSet.count == targetSetSize { result.append(generatedSet) ongoingUnion = ongoingUnion.union(generatedSet) break } } if result.count >= minArraySize { if ongoingUnion == universe { break } } } return result }
mit
3737f0a8aa2b0b549f94a6bd4677dbd0
26.232558
80
0.614005
3.956081
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/MediaViewController.swift
1
6024
// // MediaViewController.swift // Slide for Reddit // // Created by Carlos Crane on 12/28/16. // Copyright © 2016 Haptic Apps. All rights reserved. // import UIKit import reddift import SDWebImage import ImageViewer import MaterialComponents.MaterialProgressView class MediaViewController: UIViewController, UIViewControllerTransitioningDelegate { var subChanged = false var link:RSubmission! public func setLink(lnk: RSubmission, shownURL: URL?, lq: Bool, saveHistory: Bool){ //lq is should load lq and did load lq if(saveHistory){ History.addSeen(s: lnk) } self.link = lnk if(lq){ doShow(url: link.url!, lq: shownURL) } else { doShow(url: link.url!) } } func getControllerForUrl(baseUrl: URL, lq: URL? = nil) -> UIViewController? { print(baseUrl ) contentUrl = baseUrl var url = contentUrl?.absoluteString if(shouldTruncate(url: contentUrl!)){ let content = contentUrl?.absoluteString contentUrl = URL.init(string: (content?.substring(to: (content?.characters.index(of: "."))!))!) } let type = ContentType.getContentType(baseUrl: contentUrl!) if(type == ContentType.CType.ALBUM && SettingValues.internalAlbumView){ print("Showing album") return AlbumViewController.init(urlB: contentUrl!) } else if (contentUrl != nil && ContentType.displayImage(t: type) && SettingValues.internalImageView || (type == .GIF && SettingValues.internalGifView) || type == .STREAMABLE || type == .VID_ME || (type == ContentType.CType.VIDEO && SettingValues.internalYouTube)) { return SingleContentViewController.init(url: contentUrl!, lq: lq) } else if(type == ContentType.CType.LINK || type == ContentType.CType.NONE){ let web = WebsiteViewController(url: baseUrl, subreddit: link == nil ? "" : link.subreddit) return web } else if(type == ContentType.CType.REDDIT){ return RedditLink.getViewControllerForURL(urlS: contentUrl!) } return WebsiteViewController(url: baseUrl, subreddit: link == nil ? "" : link.subreddit) } var contentUrl:URL? public func shouldTruncate(url: URL) -> Bool { let path = url.path return !ContentType.isGif(uri: url) && !ContentType.isImage(uri: url) && path.contains("."); } func doShow(url: URL, lq: URL? = nil){ print(url) contentUrl = url let controller = getControllerForUrl(baseUrl: url, lq: lq)! if( controller is YouTubeViewController){ controller.modalPresentationStyle = .overFullScreen present(controller, animated: false, completion: nil) } else if( controller is AlbumViewController){ controller.modalPresentationStyle = .overFullScreen present(controller, animated: true, completion: nil) } else if(controller is SingleContentViewController){ controller.modalPresentationStyle = .overFullScreen present(controller, animated: true, completion: nil) } else { if(controller is CommentViewController){ if(UIScreen.main.traitCollection.userInterfaceIdiom == .pad && Int(round(view.bounds.width / CGFloat(320))) > 1){ let navigationController = UINavigationController(rootViewController: controller) navigationController.modalPresentationStyle = .formSheet navigationController.modalTransitionStyle = .crossDissolve present(navigationController, animated: true, completion: nil) } else { show(controller, sender: self) } } else { show(controller, sender: self) } } navigationController?.setNavigationBarHidden(false, animated: true) } var color: UIColor? func setBarColors(color: UIColor){ self.color = color setNavColors() } let overlayTransitioningDelegate = OverlayTransitioningDelegate() public func prepareOverlayVC(overlayVC: UIViewController) { overlayVC.transitioningDelegate = overlayTransitioningDelegate overlayVC.modalPresentationStyle = .custom overlayVC.view.layer.cornerRadius = 5 overlayVC.view.layer.masksToBounds = true } func setNavColors(){ if(navigationController != nil){ navigationController?.setNavigationBarHidden(false, animated: true) self.navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.barTintColor = color navigationController?.navigationBar.tintColor = .white } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.shadowImage = UIImage() setNavColors() navigationController?.isToolbarHidden = true } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return LeftTransition() } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let leftTransiton = LeftTransition() leftTransiton.dismiss = true return leftTransiton } } extension URL { var queryDictionary: [String: String] { var queryDictionary = [String: String]() guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else { return queryDictionary } queryItems.forEach { queryDictionary[$0.name] = $0.value } return queryDictionary } }
apache-2.0
9cdd8643b263e0bee14aa874d306c32a
38.887417
274
0.649676
5.283333
false
false
false
false
codingrhythm/traffic_lights
Traffic Lights/Traffic Lights/Modules/Views/TrafficLightsView.swift
1
767
// // TrafficLightsView.swift // Traffic Lights // // Created by Zack Zhu on 04/03/2017. // // import UIKit class TrafficLightsView: UIView { @IBOutlet var greenLight: LightView? @IBOutlet var yellowLight: LightView? @IBOutlet var redLight: LightView? var trafficLights: TrafficLight? { didSet { updateUI() } } override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 5 layer.borderColor = UIColor.white.cgColor layer.borderWidth = 1 } private func updateUI() { greenLight?.light = trafficLights?.greenLight yellowLight?.light = trafficLights?.yellowLight redLight?.light = trafficLights?.redLight } }
mit
80b99e2170cc74475dd68fea115178e6
20.914286
55
0.616688
4.408046
false
false
false
false
dautermann/500pxDemoBrowser
LevelMoney500pxBrowser/CircleImageView.swift
1
1230
// // CircleImageView.swift // LevelMoney500pxBrowser // // Created by Michael Dautermann on 2/18/16. // Copyright © 2016 Michael Dautermann. All rights reserved. // import UIKit class LMImageView: UIImageView { // keep track of this image view's URL, super useful in case we want // to cancel setting (or assigning) an image that doesn't match the view's current URL var imageURL : URL? } class CircleImageView: LMImageView { // handy code found at http://stackoverflow.com/questions/7399343/making-a-uiimage-to-a-circle-form override var image: UIImage? { didSet { if let image = image { let newImage = image.copy() as! UIImage let cornerRadius = image.size.height/2 UIGraphicsBeginImageContextWithOptions(image.size, false, 1.0) let bounds = CGRect(origin: CGPoint.zero, size: image.size) UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip() newImage.draw(in: bounds) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() super.image = finalImage } } } }
mit
3b40277c0d0fbb2db04ff6352a98fb7e
34.114286
103
0.637103
4.708812
false
false
false
false
YoungFuRui/douyu
douyuTV/douyuTV/Classes/Main/View/PageTitleView.swift
1
6260
// // PageTitleView.swift // douyuTV // // Created by free on 17/2/19. // Copyright © 2017年 free. All rights reserved. // import UIKit // MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } // MARK:- 定义常量 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // MARK:- 定义PageTitleView类 class PageTitleView: UIView { // MARK:- 定义属性 var titles : [String] var currentIndex : Int = 0 weak var delegate : PageTitleViewDelegate? // MARK:- 懒加载属性 lazy var titleLabels : [UILabel] = [UILabel]() lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() // MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) // 设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension PageTitleView { func setupUI() { // 1.添加UIScrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加title对应的label setupTitleLabels() // 3.设置底线和滚动的滑块 setupBottomLineAndScrollLine() } private func setupTitleLabels() { // 0.确定label的一些frame值 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0 for (index, title) in titles.enumerated() { // 1.创建UILabel let label = UILabel() // 2.设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center // 3.设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 4.将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) // 5.给label添加手势 label.isUserInteractionEnabled = true let tapGeS = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGeS) } } private func setupBottomLineAndScrollLine() { // 1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1 获取第一个label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) // 2.2 设置 scrollLine 的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK:- 监听Label的点击 extension PageTitleView { @objc func titleLabelClick(tapGes : UITapGestureRecognizer) { // 1.获取当前Label guard let currentLabel = tapGes.view as? UILabel else {return} // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6.通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1 取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2 变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.3 变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
131755842110acdae5e431c28cd545f6
31.646409
174
0.609071
4.663773
false
false
false
false
michael-lehew/swift-corelibs-foundation
Foundation/Measurement.swift
2
12525
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import CoreFoundation /// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`. /// /// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators. public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable, CustomStringConvertible { public typealias ReferenceType = NSMeasurement /// The unit component of the `Measurement`. public let unit: UnitType /// The value component of the `Measurement`. public var value: Double /// Create a `Measurement` given a specified value and unit. public init(value: Double, unit: UnitType) { self.value = value self.unit = unit } public var hashValue: Int { return Int(bitPattern: _CFHashDouble(value)) } public var description: String { return "\(value) \(unit.symbol)" } public var debugDescription: String { return "\(value) \(unit.symbol)" } } /// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension. extension Measurement where UnitType : Dimension { /// Returns a new measurement created by converting to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. /// - returns: A converted measurement. public func converted(to otherUnit: UnitType) -> Measurement<UnitType> { if unit.isEqual(otherUnit) { return Measurement(value: value, unit: otherUnit) } else { let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value) if otherUnit.isEqual(type(of: unit).baseUnit()) { return Measurement(value: valueInTermsOfBase, unit: otherUnit) } else { let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase) return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit) } } } /// Converts the measurement to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. public mutating func convert(to otherUnit: UnitType) { self = converted(to: otherUnit) } } /// Add two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`. public func +<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { fatalError("Attempt to add measurements with non-equal units") } } /// Add two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public func +<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } /// Subtract two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`. public func -<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { fatalError("Attempt to subtract measurements with non-equal units") } } /// Subtract two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public func -<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit == rhs.unit { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } /// Multiply a measurement by a scalar value. /// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`. public func *<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value * rhs, unit: lhs.unit) } /// Multiply a scalar value by a measurement. /// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`. public func *<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs * rhs.value, unit: rhs.unit) } /// Divide a measurement by a scalar value. /// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`. public func /<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value / rhs, unit: lhs.unit) } /// Divide a scalar value by a measurement. /// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`. public func /<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs / rhs.value, unit: rhs.unit) } /// Compare two measurements of the same `Unit`. /// - returns: `true` if `lhs.value == rhs.value && lhs.unit == rhs.unit`. public func ==<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value == rhs.value && lhs.unit == rhs.unit } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if the measurements are equal. public func ==<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value == rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value == rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value < rhs.value` public func <<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value < rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is less than `rhs`. public func <<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value < rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value < rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value > rhs.value` public func ><UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value > rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value > rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is greater than `rhs`. public func ><UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value > rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value > rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value <= rhs.value` public func <=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value <= rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is less than or equal to `rhs`. public func <=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value <= rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value <= rhsInLhs.value } } /// Compare two measurements of the same `Unit`. /// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`. /// - returns: `lhs.value >= rhs.value` public func >=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { return lhs.value >= rhs.value } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value >= rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if `lhs` is greater or equal to `rhs`. public func >=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value >= rhs.value } else { let rhsInLhs = rhs.converted(to: lhs.unit) return lhs.value >= rhsInLhs.value } } // Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types. extension Measurement : _ObjectTypeBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSMeasurement { return NSMeasurement(doubleValue: value, unit: unit) } public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) { result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType) } public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool { if let u = source.unit as? UnitType { result = Measurement(value: source.doubleValue, unit: u) return true } else { return false } } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement { let u = source!.unit as! UnitType return Measurement(value: source!.doubleValue, unit: u) } }
apache-2.0
ef4701f1f86cbb4797f362d7e632af88
44.216606
276
0.66515
4.20161
false
false
false
false
natecook1000/swift
stdlib/public/core/ContiguousArrayBuffer.swift
1
23459
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _sanityCheckFailure("creating instance of _EmptyArrayStorage") } #if _runtime(_ObjC) @inlinable override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { return 0 } @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { return _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, 0, 0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage : _EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline internal final class _ContiguousArrayStorage< Element > : _ContiguousArrayStorageBase { @inlinable // FIXME(sil-serialize-all) deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. @inlinable internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. @inlinable internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable @nonobjc override internal func _getNonVerbatimBridgedCount() -> Int { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. @inlinable override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, count, count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @usableFromInline @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: _ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _sanityCheck(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _sanityCheck(newValue >= 0) _sanityCheck( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _sanityCheck(bounds.lowerBound >= 0) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @inlinable internal func _asCocoaArray() -> _NSArrayCore { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return _SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _sanityCheck(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @usableFromInline internal var _storage: _ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } internal typealias Indices = Range<Int> } extension Sequence { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) let p = UnsafeMutableBufferPointer(start: result.firstElementAddress, count: count) var (itr, end) = source._copyContents(initializing: p) _debugPrecondition(itr.next() == nil, "invalid Collection: more than 'count' elements in collection") // We also have to check the evil shrink case in release builds, because // it can result in uninitialized array elements and therefore undefined // behavior. _precondition(end == p.endIndex, "invalid Collection: less than 'count' elements in collection") return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writting to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _sanityCheck(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable // FIXME(sil-serialize-all) @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _sanityCheck(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
14c4783b00216044b6290572e1369b8d
30.570659
110
0.697148
4.748381
false
false
false
false
GeoThings/LakestoneGeometry
Source/BoundingBox.swift
1
5834
// // BoundingBox.swift // LakestoneGeometry // // Created by Volodymyr Andriychenko on 20/10/2016. // Copyright © 2016 GeoThings. 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. // #if COOPER import lakestonecore.android #else import LakestoneCore import Foundation #endif //MARK: - BoundingBox rectangle with Coordinates using Double type /// Structure to store two Coordinates defining a region public class BoundingBox { public var ll: Coordinate public var ur: Coordinate public init(ll: Coordinate, ur: Coordinate) throws { if (ll.x > ur.x) || (ll.y > ur.y) { throw Error.InvalidCoordinates } self.ll = ll self.ur = ur } /// Checks if Coordinate is within or on the borders of given BoundingBox public func contains(coordinate: Coordinate) -> Bool { if (self.ll.x <= coordinate.x && coordinate.x <= self.ur.x && self.ll.y <= coordinate.y && coordinate.y <= self.ur.y){ return true } else { return false } } /// List of sides of the BoundingBox (clockwise from left to bottom) public var sides: [Line] { let ul = Coordinate(x: self.ll.x, y: self.ur.y) let lr = Coordinate(x: self.ur.x, y: self.ll.y) var sides = [Line]() let leftSide = Line(endpointA: self.ll, endpointB: ul) sides.append(leftSide) let topSide = Line(endpointA: ul, endpointB: self.ur) sides.append(topSide) let rightSide = Line(endpointA: self.ur, endpointB: lr) sides.append(rightSide) let bottomSide = Line(endpointA: lr, endpointB: self.ll) sides.append(bottomSide) return sides } } ///Checks if the Coordinate lies on the borders of given BoundingBox public func does(boundingBox: BoundingBox, edgesContain coordinate: Coordinate) -> Bool { if ((boundingBox.ll.x == coordinate.x || boundingBox.ur.x == coordinate.x) && (boundingBox.ll.y <= coordinate.y && coordinate.y <= boundingBox.ur.y)) || ((boundingBox.ll.y == coordinate.y || boundingBox.ur.y == coordinate.y) && (boundingBox.ll.x < coordinate.x && coordinate.x < boundingBox.ur.x)){ return true } else { return false } } //MARK: CustomStringConvertable extension BoundingBox: CustomStringConvertible { public var description: String { return "BoundingBox: { left: \(self.ll.x), bottom: \(self.ll.y), right: \(self.ur.x), top: \(self.ur.y) }" } #if COOPER public override func toString() -> String { return self.description } #endif } //MARK: Java's Equatable analogue extension BoundingBox: Equatable { #if COOPER public override func equals(_ o: Object!) -> Bool { guard let other = o as? Self else { return false } return (self == other) } #endif } public func ==(lhs: BoundingBox, rhs: BoundingBox) -> Bool { return (lhs.ll == rhs.ll && lhs.ur == rhs.ur) } //MARK: Errors extension BoundingBox { public class Error { public static let InvalidCoordinates = LakestoneError.with(stringRepresentation: "BoundingBox creation failed. Please check the order of coordinates") } } //----------------------------------------------------------------------------------- //MARK: - BoundingBox rectangle with Coordinates using Int type /// Structure to store two Int Coordinates defining a region public class BoundingBoxInt { public var ll: CoordinateInt public var ur: CoordinateInt public init(ll: CoordinateInt, ur: CoordinateInt) throws { if (ll.x > ur.x) || (ll.y > ur.y) { throw Error.InvalidIntCoordinates } self.ll = ll self.ur = ur } public func contains(coordinate: CoordinateInt) -> Bool { if (self.ll.x <= coordinate.x && coordinate.x <= self.ur.x && self.ll.y <= coordinate.y && coordinate.y <= self.ur.y){ return true } else { return false } } } /// checks if the CoordinateInt lies on the borders if given BoundingBoxInt public func does(boundingBox: BoundingBoxInt, edgesContain coordinate: CoordinateInt) -> Bool { if ((boundingBox.ll.x == coordinate.x || boundingBox.ur.x == coordinate.x) && (boundingBox.ll.y <= coordinate.y && coordinate.y <= boundingBox.ur.y)) || ((boundingBox.ll.y == coordinate.y || boundingBox.ur.y == coordinate.y) && (boundingBox.ll.x < coordinate.x && coordinate.x < boundingBox.ur.x)){ return true } else { return false } } //MARK: CustomStringConvertable extension BoundingBoxInt: CustomStringConvertible { public var description: String { return "BoundingBoxInt: { left: \(self.ll.x), bottom: \(self.ll.y), right: \(self.ur.x), top: \(self.ur.y) }" } #if COOPER public override func toString() -> String { return self.description } #endif } //MARK: Java's Equatable analogue extension BoundingBoxInt: Equatable { #if COOPER public override func equals(_ o: Object!) -> Bool { guard let other = o as? Self else { return false } return (self == other) } #endif } public func ==(lhs: BoundingBoxInt, rhs: BoundingBoxInt) -> Bool { return (lhs.ll == rhs.ll && lhs.ur == rhs.ur) } //MARK: Errors extension BoundingBoxInt { public class Error { public static let InvalidIntCoordinates = LakestoneError.with(stringRepresentation: "BoundingBoxInt creation failed. Please check the order of coordinates") } }
apache-2.0
398f633b5d12381dedff031fd482a7cb
25.625571
158
0.664037
3.635287
false
false
false
false
elysiumd/ios-wallet
BreadWallet/BRAPIProxy.swift
1
5391
// // BRAPIProxy.swift // BreadWallet // // Created by Samuel Sutch on 2/8/16. // Copyright (c) 2016 breadwallet LLC // // 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 // Add this middleware to a BRHTTPServer to expose a proxy to the breadwallet HTTP api // It has all the capabilities of the real API but with the ability to authenticate // requests using the users private keys stored on device. // // Clients should set the "X-Should-Verify" to enable response verification and can set // "X-Should-Authenticate" to sign requests with the users private authentication key @objc open class BRAPIProxy: NSObject, BRHTTPMiddleware { var mountPoint: String var apiInstance: BRAPIClient var shouldVerifyHeader: String = "x-should-verify" var shouldAuthHeader: String = "x-should-authenticate" var bannedSendHeaders: [String] { return [ shouldVerifyHeader, shouldAuthHeader, "connection", "authorization", "host", "user-agent" ] } var bannedReceiveHeaders: [String] = ["content-length", "content-encoding", "connection"] init(mountAt: String, client: BRAPIClient) { mountPoint = mountAt if mountPoint.hasSuffix("/") { mountPoint = mountPoint.substring(to: mountPoint.characters.index(mountPoint.endIndex, offsetBy: -1)) } apiInstance = client super.init() } open func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) { if request.path.hasPrefix(mountPoint) { let idx = request.path.characters.index(request.path.startIndex, offsetBy: mountPoint.characters.count) var path = request.path.substring(from: idx) if request.queryString.utf8.count > 0 { path += "?\(request.queryString)" } var nsReq = URLRequest(url: apiInstance.url(path)) nsReq.httpMethod = request.method // copy body if request.hasBody { nsReq.httpBody = request.body() } // copy headers for (hdrName, hdrs) in request.headers { if bannedSendHeaders.contains(hdrName) { continue } for hdr in hdrs { nsReq.setValue(hdr, forHTTPHeaderField: hdrName) } } var auth = false if let authHeader = request.headers[shouldAuthHeader] , authHeader.count > 0 { if authHeader[0].lowercased() == "yes" { auth = true } } apiInstance.dataTaskWithRequest(nsReq, authenticated: auth, retryCount: 0, handler: { (nsData, nsHttpResponse, nsError) -> Void in if let httpResp = nsHttpResponse { var hdrs = [String: [String]]() for (k, v) in httpResp.allHeaderFields { if self.bannedReceiveHeaders.contains((k as! String).lowercased()) { continue } hdrs[k as! String] = [v as! String] } var body: [UInt8]? = nil if let bod = nsData { let bp = (bod as NSData).bytes.bindMemory(to: UInt8.self, capacity: bod.count) let b = UnsafeBufferPointer<UInt8>(start: bp, count: bod.count) body = Array(b) } let resp = BRHTTPResponse( request: request, statusCode: httpResp.statusCode, statusReason: HTTPURLResponse.localizedString(forStatusCode: httpResp.statusCode), headers: hdrs, body: body) return next(BRHTTPMiddlewareResponse(request: request, response: resp)) } else { print("[BRAPIProxy] error getting response from backend: \(nsError)") return next(BRHTTPMiddlewareResponse(request: request, response: nil)) } }).resume() } else { return next(BRHTTPMiddlewareResponse(request: request, response: nil)) } } }
mit
b645e6416a89ec480d5c4f398b892c6a
45.076923
115
0.595251
4.896458
false
false
false
false
a736220388/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendModel.swift
1
3838
// // CBRecommendModel.swift // TestKitchen // // Created by qianfeng on 16/8/16. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit import SwiftyJSON class CBRecommendModel: NSObject { var code:NSNumber? var msg:Bool? var version:String? var timestamp:NSNumber? var data:CBRecommendDataModel? class func parseModel(data:NSData)->CBRecommendModel{ let model = CBRecommendModel() let jsonData = JSON(data:data) model.code = jsonData["code"].number model.msg = jsonData["msg"].bool model.version = jsonData["version"].string model.timestamp = jsonData["timestamp"].number let dataDict = jsonData["data"] model.data = CBRecommendDataModel.parseModel(dataDict) return model } } class CBRecommendDataModel:NSObject{ var banner:Array<CBRecommendBannerModel>? var widgetList:Array<CBRecommendWidgetListModel>? class func parseModel(jsonData:JSON) -> CBRecommendDataModel{ let model = CBRecommendDataModel() let bannerArray = jsonData["banner"] var array = Array<CBRecommendBannerModel>() for (_,subjson) in bannerArray{ let bannerModel = CBRecommendBannerModel.parseModel(subjson) array.append(bannerModel) } model.banner = array let listArray = jsonData["widgetList"] var wlArray = Array<CBRecommendWidgetListModel>() for (_,subjson) in listArray{ let model = CBRecommendWidgetListModel.parseModel(subjson) wlArray.append(model) } model.widgetList = wlArray return model } } class CBRecommendBannerModel:NSObject{ var banner_id:NSNumber? var banner_title:String? var banner_picture:String? var banner_link:String? var is_link:NSNumber? var refer_key:NSNumber? var type_id:NSNumber? class func parseModel(jsonData:JSON)->CBRecommendBannerModel{ let model = CBRecommendBannerModel() model.banner_id = jsonData["banner_id"].number model.banner_title = jsonData["banner_title"].string model.banner_picture = jsonData["banner_picture"].string model.banner_link = jsonData["banner_link"].string model.is_link = jsonData["is_link"].number model.refer_key = jsonData["refer_key"].number model.type_id = jsonData["type_id"].number return model } } class CBRecommendWidgetListModel:NSObject{ var widget_id:NSNumber? var widget_type:NSNumber? var title:String? var title_link:String? var desc:String? var widget_data:Array<CBRecommendWidgetDataModel>? class func parseModel(jsonData:JSON)->CBRecommendWidgetListModel{ let model = CBRecommendWidgetListModel() model.widget_id = jsonData["widget_id"].number model.widget_type = jsonData["widget_type"].number model.title = jsonData["title"].string model.title_link = jsonData["title_link"].string model.desc = jsonData["desc"].string let dataArray = jsonData["widget_data"] var wdArray = Array<CBRecommendWidgetDataModel>() for (_,subjson) in dataArray{ let wdModel = CBRecommendWidgetDataModel.parseModel(subjson) wdArray.append(wdModel) } model.widget_data = wdArray return model } } class CBRecommendWidgetDataModel:NSObject{ var id:NSNumber? var type:String? var content:String? var link:String? class func parseModel(jsonData:JSON)->CBRecommendWidgetDataModel{ let model = CBRecommendWidgetDataModel() model.id = jsonData["id"].number model.type = jsonData["type"].string model.content = jsonData["content"].string model.link = jsonData["link"].string return model } }
mit
2924e6870def24841816b1d873977b4a
33.241071
72
0.663364
4.454123
false
false
false
false
mightydeveloper/swift
test/DebugInfo/linetable-cleanups.swift
10
868
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(t: T) {} class Person { var name = "No Name" var age = 0 } func main() { var person = Person() var b = [0,1,13] for element in b { markUsed("element = \(element)") } markUsed("Done with the for loop") // CHECK: call void @_TF4main8markUsedurFxT_ // CHECK: br label // CHECK: <label>: // CHECK: , !dbg ![[LOOPHEADER_LOC:.*]] // CHECK: call void {{.*}}elease({{.*}}) {{#[0-9]+}}, !dbg ![[LOOPHEADER_LOC]] // CHECK: call void @_TF4main8markUsedurFxT_ // The cleanups should share the line number with the ret stmt. // CHECK: call void {{.*}}elease({{.*}}) {{#[0-9]+}}, !dbg ![[CLEANUPS:.*]] // CHECK-NEXT: !dbg ![[CLEANUPS]] // CHECK-NEXT: ret void, !dbg ![[CLEANUPS]] // CHECK: ![[CLEANUPS]] = !DILocation(line: [[@LINE+1]], column: 1, } main()
apache-2.0
83778a3dee4633d14020fa6b975b4e53
28.931034
78
0.573733
3.167883
false
false
false
false
Limon-O-O/Medusa
MED/Views/RingControl.swift
1
4973
// // RingControl.swift // VideoRecorderExample // // Created by Limon on 6/15/16. // Copyright © 2016 VideoRecorder. All rights reserved. // import UIKit @IBDesignable class RingControl: UIControl { enum TouchStatus { case began case press case end } var toucheActions: ((_ status: TouchStatus) -> Void)? var touchStatus: TouchStatus = .end { willSet { guard touchStatus != newValue else { return } toucheActions?(newValue) } } fileprivate let innerRing = UIView() fileprivate var previousTimestamp: TimeInterval = 0.0 override init(frame: CGRect) { super.init(frame: frame) addViews() addTargetForAnimation() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addViews() addTargetForAnimation() } fileprivate func addViews() { backgroundColor = UIColor.clear let circlePath = UIBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: frame.size)) let outerRing = CAShapeLayer() outerRing.path = circlePath.cgPath outerRing.fillColor = UIColor.clear.cgColor outerRing.strokeColor = UIColor.white.cgColor outerRing.lineWidth = 4.0 let ringSpace: CGFloat = 12.0 let innerRingWH: CGFloat = frame.width - ringSpace innerRing.isUserInteractionEnabled = false innerRing.frame.size = CGSize(width: innerRingWH, height: innerRingWH) innerRing.center = CGPoint(x: frame.width/2, y: frame.width/2) innerRing.backgroundColor = UIColor.red innerRing.layer.masksToBounds = true innerRing.layer.cornerRadius = innerRingWH / 2.0 layer.addSublayer(outerRing) addSubview(innerRing) } } // MARK: - Add Targets extension RingControl { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let touch = touches.first else { return } // touchStatus = .began previousTimestamp = touch.timestamp } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) guard let touch = touches.first else { return } let currentTimestamp = touch.timestamp let validFrame = CGRect(x: -frame.size.width/2, y: -frame.size.height/2, width: frame.size.width*2, height: frame.size.width*2) let location = touch.location(in: self) if validFrame.contains(location) { if currentTimestamp - previousTimestamp > 0.14 { // touchStatus = .press } } else { // touchStatus = .end } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) // touchStatus = .end } override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { super.touchesCancelled(touches!, with: event) // touchStatus = .end } } extension RingControl { @nonobjc static let eye_scaleToSmall = "scaleToSmall" @nonobjc static let eye_scaleAnimationWithSpring = "scaleAnimationWithSpring" @nonobjc static let eye_scaleToDefault = "scaleToDefault" func removeAnimatedTarget() { removeTarget(self, action: Selector(RingControl.eye_scaleToSmall), for: .touchDown) removeTarget(self, action: Selector(RingControl.eye_scaleAnimationWithSpring), for: .touchUpInside) removeTarget(self, action: Selector(RingControl.eye_scaleToDefault), for: .touchDragExit) } func addTargetForAnimation() { addTarget(self, action: Selector(RingControl.eye_scaleToSmall), for: .touchDown) addTarget(self, action: Selector(RingControl.eye_scaleAnimationWithSpring), for: .touchUpInside) addTarget(self, action: Selector(RingControl.eye_scaleToDefault), for: .touchDragExit) } @objc fileprivate func scaleToSmall() { UIView.animate(withDuration: 0.2, animations: { self.innerRing.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }) } @objc fileprivate func scaleAnimationWithSpring() { if touchStatus == .began { touchStatus = .end } else { touchStatus = .began } UIView.animate(withDuration: 0.26, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: UIView.AnimationOptions(), animations: { self.innerRing.transform = CGAffineTransform.identity }, completion: nil) } @objc fileprivate func scaleToDefault() { UIView.animate(withDuration: 0.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: UIView.AnimationOptions(), animations: { self.innerRing.transform = CGAffineTransform.identity }, completion: nil) } }
mit
26709a20719586718d2aa8c58f71201a
28.772455
160
0.651247
4.447227
false
false
false
false
ffried/FFUIKit
Sources/FFUIKit/ViewControllers/Notifications/NotificationAnimationController.swift
1
4113
// // NotificationAnimationController.swift // FFUIKit // // Copyright 2016 Florian Friedrich // // 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. // #if !os(watchOS) import Foundation import UIKit import FFFoundation final class NotificationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { private var topConstraint: NSLayoutConstraint! private var bottomConstraint: NSLayoutConstraint! private var originalVCContainer: UIView! private final func setupTopBottomConstraints(for view: UIView) { topConstraint = view.superview?.topAnchor.constraint(equalTo: view.topAnchor) bottomConstraint = view.superview?.topAnchor.constraint(equalTo: view.bottomAnchor) } @objc(transitionDuration:) dynamic internal func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { 0.3 } @objc(animateTransition:) dynamic internal func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) else { return } let presenting = toVC.isBeingPresented guard let vcView = presenting ? fromVC.view : toVC.view, let noteView = presenting ? toVC.view : fromVC.view, let noteVC = (presenting ? toVC : fromVC) as? NotificationControllerProtocol else { return } let container = transitionContext.containerView if presenting { originalVCContainer = vcView.superview container.addSubview(vcView) container.addSubview(noteView) setupTopBottomConstraints(for: noteView) noteVC.noteView.contentViewTopConstraint.isActive = false let views: [String: UIView] = ["note": noteView] ([bottomConstraint] + ["H:|[note]|"].constraints(with: views)).activate() container.layoutIfNeeded() } let curveOption: UIView.AnimationOptions = presenting ? .curveEaseOut : .curveEaseIn let options: UIView.AnimationOptions = [.beginFromCurrentState, .allowAnimatedContent, .allowUserInteraction, curveOption] let duration = transitionDuration(using: transitionContext) let animations = { if presenting { self.bottomConstraint.isActive = false self.topConstraint.isActive = true noteVC.noteView.contentViewTopConstraint.isActive = true } else { noteVC.noteView.contentViewTopConstraint.isActive = false self.topConstraint.isActive = false self.bottomConstraint.isActive = true } container.layoutIfNeeded() } let completion = { (pos: UIViewAnimatingPosition) in if !presenting { self.originalVCContainer.addSubview(vcView) } transitionContext.completeTransition(pos == .end) } if transitionContext.isAnimated { UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration, delay: 0, options: options, animations: animations, completion: completion) } else { animations() completion(.end) } } } #endif
apache-2.0
0b21f4052565e9a3b09859bb63dc5b2c
41.84375
132
0.640165
5.626539
false
false
false
false
marwen86/NHtest
NHTest/NHTest/Model/NHResultImagesParser.swift
1
910
// // NHResultImagesParser.swift // NHTest // // Created by Mohamed Marouane YOUSSEF on 07/10/2017. // Copyright © 2017 Mohamed Marouane YOUSSEF. All rights reserved. // import UIKit extension NHResultImages { static func fromJson(_ data : Dictionary<String,AnyObject>)-> NHResultImages? { guard let total = data["total"] as? Int, let totalHits = data["totalHits"] as? Int, let hitsArray = data["hits"] as? Array<AnyObject> else { return nil } var hits = [NHImageModel]() for item in hitsArray { guard let item = item as? Dictionary<String,AnyObject> , let hit = NHImageModel.fromJson(item) else { break } hits.append(hit) } return NHResultImages(total: total, totalHits: totalHits, hits: hits) } }
mit
35268e817828e8ffdce1b1d47234cf01
26.545455
114
0.564356
4.169725
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/data types/enumerable/XGType.swift
1
2651
// // XGTypeData.swift // XG Tool // // Created by StarsMmd on 19/05/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation let kCategoryOffset = 0x0 let kTypeIconBigIDOffset = 0x02 let kTypeIconSmallIDOffset = 0x04 let kTypeNameIDOffset = 0x8 let kFirstEffectivenessOffset = 0xD let kSizeOfTypeData = 0x30 let kNumberOfTypes = CommonIndexes.NumberOfTypes.value final class XGType: NSObject, Codable { var index = 0 var nameID = 0 var category = XGMoveCategories.none var effectivenessTable = [XGEffectivenessValues]() var iconBigID = 0 var iconSmallID = 0 var name : XGString { get { return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID) } } var startOffset = 0 init(index: Int) { super.init() let rel = XGFiles.common_rel.data! self.index = index startOffset = CommonIndexes.Types.startOffset + (index * kSizeOfTypeData) self.nameID = rel.getWordAtOffset(startOffset + kTypeNameIDOffset).int self.category = XGMoveCategories(rawValue: rel.getByteAtOffset(startOffset + kCategoryOffset))! self.iconBigID = rel.get2BytesAtOffset(startOffset + kTypeIconBigIDOffset) self.iconSmallID = rel.get2BytesAtOffset(startOffset + kTypeIconSmallIDOffset) var offset = startOffset + kFirstEffectivenessOffset for _ in 0 ..< kNumberOfTypes { let value = rel.getByteAtOffset(offset) let effectiveness = XGEffectivenessValues(rawValue: value)! effectivenessTable.append(effectiveness) offset += 2 } } func save() { let rel = XGFiles.common_rel.data! rel.replaceByteAtOffset(startOffset + kCategoryOffset, withByte: self.category.rawValue) rel.replaceWordAtOffset(startOffset + kTypeNameIDOffset, withBytes: UInt32(self.nameID)) rel.replace2BytesAtOffset(startOffset + kTypeIconBigIDOffset, withBytes: self.iconBigID) rel.replace2BytesAtOffset(startOffset + kTypeIconSmallIDOffset, withBytes: self.iconSmallID) for i in 0 ..< self.effectivenessTable.count { let value = effectivenessTable[i].rawValue rel.replaceByteAtOffset(startOffset + kFirstEffectivenessOffset + (i * 2), withByte: value) // i*2 because each value is 2 bytes apart } rel.save() } } extension XGType: XGEnumerable { var enumerableName: String { return name.string } var enumerableValue: String? { return String(format: "%02d", index) } static var className: String { return "Types" } static var allValues: [XGType] { var values = [XGType]() for i in 0 ..< CommonIndexes.NumberOfTypes.value { values.append(XGType(index: i)) } return values } }
gpl-2.0
a6468b54df3171ac2906e22181f7f169
21.65812
97
0.723878
3.368488
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Requests/Request+Picture.swift
1
2250
// // Request+Picture.swift // Pods // // Created by King, Gavin on 10/24/16. // // public extension Request { /// `Request` that returns a single `VIMPicture` typealias PictureRequest = Request<VIMPicture> /** Create a `Request` to create a picture for a user - parameter userURI: the URI of the user - returns: a new `Request` */ static func createPictureRequest(forUserURI userURI: String) -> Request { let uri = "\(userURI)/pictures" return Request(method: .post, path: uri) } /** Create a `Request` to create a picture for a video. Note that if `time` is not specified then `active` will have no effect. - parameter videoURI: the URI of the video - parameter time: the timestamp (in seconds) of the point in the video that the thumbnail should reflect - parameter active: whether the newly created thumbnail should be activated - returns: a new `Request` */ static func createPictureRequest( forVideoURI videoURI: String, time: TimeInterval? = nil, active: Bool? = nil) -> Request { let uri = "\(videoURI)/pictures" var parameters: VimeoClient.RequestParametersDictionary = [:] parameters[.timeKey] = time parameters[.activeKey] = active return Request(method: .post, path: uri, parameters: parameters) } /** Create a `Request` to delete a picture - parameter pictureURI: the URI of the picture - returns: a new `Request` */ static func deletePictureRequest(forPictureURI pictureURI: String) -> Request { return Request(method: .delete, path: pictureURI) } /** Create a `Request` to activate a picture - parameter pictureURI: the URI of the picture - returns: a new `Request` */ static func activatePictureRequest(forPictureURI pictureURI: String) -> Request { let parameters = ["active": "true"] return Request(method: .patch, path: pictureURI, parameters: parameters) } } private extension String { // Request & response keys static let timeKey = "time" static let activeKey = "active" }
mit
c0ea10ddcd8908011c99ca0879fe1864
27.481013
117
0.625778
4.420432
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/ViewControllers/ProfileShotsViewController.swift
1
12188
// // ProfileShotsViewController.swift // Inbbbox // // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import ZFDragableModalTransition import PromiseKit import PeekPop fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class ProfileShotsViewController: TwoLayoutsCollectionViewController, Support3DTouch, ContainingScrollableView { var dismissClosure: (() -> Void)? var modalTransitionAnimator: ZFModalTransitionAnimator? var scrollableView: UIScrollView { return collectionView! } var scrollContentOffset: (() -> CGPoint)? var didLayoutSubviews = false internal var peekPop: PeekPop? internal var didCheckedSupport3DForOlderDevices = false override var containsHeader: Bool { return false } fileprivate var viewModel: ProfileShotsViewModel! fileprivate var indexPathsNeededImageUpdate = [IndexPath]() /// Initialize view controller to show user's shots. /// /// - Note: According to Dribbble API - Team is a particular case of User, /// so if you want to show team's shots - pass it as `UserType` with `accountType = .Team`. /// /// - parameter user: User to initialize view controller with. convenience init(user: UserType) { self.init(oneColumnLayoutCellHeightToWidthRatio: SimpleShotCollectionViewCell.heightToWidthRatio, twoColumnsLayoutCellHeightToWidthRatio: SimpleShotCollectionViewCell.heightToWidthRatio) viewModel = ProfileShotsViewModel(user: user) viewModel.delegate = self } override func viewDidLoad() { super.viewDidLoad() guard let collectionView = collectionView else { return } collectionView.delegate = self collectionView.dataSource = self collectionView.registerClass(SimpleShotCollectionViewCell.self, type: .cell) collectionView.registerClass(SmallUserCollectionViewCell.self, type: .cell) collectionView.registerClass(LargeUserCollectionViewCell.self, type: .cell) collectionView.registerClass(ProfileHeaderView.self, type: .header) collectionView.updateInsets(top: ProfileView.headerInitialHeight) viewModel.downloadInitialItems() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() didLayoutSubviews = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let collectionView = collectionView else { return } if viewModel.itemsCount == 0 { collectionView.updateInsets(bottom: collectionView.frame.height) } if let offset = scrollContentOffset?() { collectionView.contentOffset = offset } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let collectionView = collectionView { addSupport3DForOlderDevicesIfNeeded(with: self, viewController: self, sourceView: collectionView) } } } // MARK: UICollectionViewDataSource extension ProfileShotsViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.itemsCount } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return prepareUserCell(at: indexPath, in: collectionView) } } // MARK: UICollectionViewDelegate extension ProfileShotsViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let detailsViewController = ShotDetailsViewController(shot: viewModel.shotWithSwappedUser(viewModel.userShots[indexPath.item])) detailsViewController.shotIndex = indexPath.item let shotDetailsPageDataSource = ShotDetailsPageViewControllerDataSource(shots: viewModel.userShots, initialViewController: detailsViewController) let pageViewController = ShotDetailsPageViewController(shotDetailsPageDataSource: shotDetailsPageDataSource) modalTransitionAnimator = CustomTransitions.pullDownToCloseTransitionForModalViewController(pageViewController) pageViewController.transitioningDelegate = modalTransitionAnimator pageViewController.modalPresentationStyle = .custom present(pageViewController, animated: true, completion: nil) } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == viewModel.itemsCount - 1 { viewModel.downloadItemsForNextPage() } } override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let index = indexPathsNeededImageUpdate.index(of: indexPath) { indexPathsNeededImageUpdate.remove(at: index) } } } // MARK: BaseCollectionViewViewModelDelegate extension ProfileShotsViewController: BaseCollectionViewViewModelDelegate { func viewModelDidLoadInitialItems() { collectionView?.reloadData() collectionView?.layoutIfNeeded() self.adjustCollectionView() } func viewModelDidFailToLoadInitialItems(_ error: Error) { collectionView?.reloadData() collectionView?.layoutIfNeeded() if let offset = self.scrollContentOffset?() { self.collectionView?.contentOffset = offset } if viewModel.collectionIsEmpty { guard let visibleViewController = navigationController?.visibleViewController else { return } FlashMessage.sharedInstance.showNotification(inViewController: visibleViewController, title: FlashMessageTitles.tryAgain, canBeDismissedByUser: true) } } func viewModelDidFailToLoadItems(_ error: Error) { guard let visibleViewController = navigationController?.visibleViewController else { return } FlashMessage.sharedInstance.showNotification(inViewController: visibleViewController, title: FlashMessageTitles.downloadingShotsFailed, canBeDismissedByUser: true) } func viewModel(_ viewModel: BaseCollectionViewViewModel, didLoadItemsAtIndexPaths indexPaths: [IndexPath]) { collectionView?.insertItems(at: indexPaths) } func viewModel(_ viewModel: BaseCollectionViewViewModel, didLoadShotsForItemAtIndexPath indexPath: IndexPath) { collectionView?.reloadItems(at: [indexPath]) } } // MARK: Private extension private extension ProfileShotsViewController { func lazyLoadImage(_ shotImage: ShotImageType, forCell cell: SimpleShotCollectionViewCell, atIndexPath indexPath: IndexPath) { let imageLoadingCompletion: (UIImage) -> Void = { [weak self] image in guard let certainSelf = self, certainSelf.indexPathsNeededImageUpdate.contains(indexPath) else { return } cell.shotImageView.image = image } LazyImageProvider.lazyLoadImageFromURLs( (shotImage.teaserURL, isCurrentLayoutOneColumn ? shotImage.normalURL : nil, nil), teaserImageCompletion: imageLoadingCompletion, normalImageCompletion: imageLoadingCompletion ) } func prepareUserCell(at indexPath: IndexPath, in collectionView: UICollectionView) -> UICollectionViewCell { let cell = collectionView.dequeueReusableClass(SimpleShotCollectionViewCell.self, forIndexPath: indexPath, type: .cell) cell.contentView.backgroundColor = ColorModeProvider.current().shotViewCellBackground cell.shotImageView.image = nil let cellData = viewModel.shotCollectionViewCellViewData(indexPath) indexPathsNeededImageUpdate.append(indexPath) lazyLoadImage(cellData.shotImage, forCell: cell, atIndexPath: indexPath) cell.gifLabel.isHidden = !cellData.animated if !cell.isRegisteredTo3DTouch { cell.isRegisteredTo3DTouch = registerTo3DTouch(cell.contentView) } return cell } func adjustCollectionView() { guard let collectionView = collectionView else { return } if viewModel.itemsCount == 0 { collectionView.updateInsets(bottom: collectionView.frame.height) } else { if collectionView.contentSize.height < collectionView.frame.height { collectionView.updateInsets(bottom: collectionView.frame.height - collectionView.contentSize.height) } else { collectionView.updateInsets(bottom: 0) } } guard let offset = self.scrollContentOffset?() else { return } collectionView.contentOffset = offset } } // MARK: UIViewControllerPreviewingDelegate extension ProfileShotsViewController: UIViewControllerPreviewingDelegate { fileprivate func peekPopPresent(viewController: UIViewController) { if let detailsViewController = viewController as? ShotDetailsViewController { detailsViewController.customizeFor3DTouch(false) let shotDetailsPageDataSource = ShotDetailsPageViewControllerDataSource(shots: viewModel.userShots, initialViewController: detailsViewController) let pageViewController = ShotDetailsPageViewController(shotDetailsPageDataSource: shotDetailsPageDataSource) modalTransitionAnimator = CustomTransitions.pullDownToCloseTransitionForModalViewController(pageViewController) modalTransitionAnimator?.behindViewScale = 1 pageViewController.transitioningDelegate = modalTransitionAnimator pageViewController.modalPresentationStyle = .custom present(pageViewController, animated: true, completion: nil) } } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let collectionView = collectionView, let indexPath = collectionView.indexPathForItem(at: previewingContext.sourceView.convert(location, to: collectionView)), let cell = collectionView.cellForItem(at: indexPath) else { return nil } previewingContext.sourceRect = cell.contentView.bounds let controller = ShotDetailsViewController(shot: viewModel.shotWithSwappedUser(viewModel.userShots[indexPath.item])) controller.customizeFor3DTouch(true) controller.shotIndex = indexPath.item return controller } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { peekPopPresent(viewController: viewControllerToCommit) } } // MARK: PeekPopPreviewingDelegate extension ProfileShotsViewController: PeekPopPreviewingDelegate { func previewingContext(_ previewingContext: PreviewingContext, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let collectionView = collectionView, let indexPath = collectionView.indexPathForItem(at: previewingContext.sourceView.convert(location, to: collectionView)), let cell = collectionView.cellForItem(at: indexPath) else { return nil } let controller = ShotDetailsViewController(shot: viewModel.shotWithSwappedUser(viewModel.userShots[indexPath.item])) controller.customizeFor3DTouch(true) controller.shotIndex = indexPath.item previewingContext.sourceRect = cell.frame return controller } func previewingContext(_ previewingContext: PreviewingContext, commit viewControllerToCommit: UIViewController) { peekPopPresent(viewController: viewControllerToCommit) } }
gpl-3.0
12ae0972509afff283e06b4fa9771695
37.444795
171
0.721178
5.775829
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/Routers/SettingsBuilder.swift
1
2582
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import FeatureCardPaymentDomain import Localization import PlatformKit import UIKit public protocol SettingsBuilding: AnyObject { func removeCardPaymentMethodViewController(cardData: CardData) -> UIViewController func removeBankPaymentMethodViewController(beneficiary: Beneficiary) -> UIViewController } public final class SettingsBuilder: SettingsBuilding { private let cardDeletionService: PaymentMethodDeletionServiceAPI private let beneficiariesService: BeneficiariesServiceAPI public init( cardDeletionService: PaymentMethodDeletionServiceAPI = resolve(), beneficiariesService: BeneficiariesServiceAPI = resolve() ) { self.cardDeletionService = cardDeletionService self.beneficiariesService = beneficiariesService } /// Generate remove card payment method view controller /// - Parameter cardData: CC data /// - Returns: The view controller public func removeCardPaymentMethodViewController(cardData: CardData) -> UIViewController { let data = PaymentMethodRemovalData(cardData: cardData) return removePaymentMethodViewController( buttonLocalizedString: LocalizationConstants.Settings.Card.remove, removalData: data, deletionService: cardDeletionService ) } /// Generate remove bank payment method view controller /// - Parameter cardData: Bank data /// - Returns: The view controller public func removeBankPaymentMethodViewController(beneficiary: Beneficiary) -> UIViewController { let data = PaymentMethodRemovalData(beneficiary: beneficiary) return removePaymentMethodViewController( buttonLocalizedString: LocalizationConstants.Settings.Bank.remove, removalData: data, deletionService: beneficiariesService ) } private func removePaymentMethodViewController( buttonLocalizedString: String, removalData: PaymentMethodRemovalData, deletionService: PaymentMethodDeletionServiceAPI ) -> UIViewController { let interactor = RemovePaymentMethodScreenInteractor( data: removalData, deletionService: deletionService ) let presenter = RemovePaymentMethodScreenPresenter( buttonLocalizedString: buttonLocalizedString, interactor: interactor ) let viewController = RemovePaymentMethodViewController(presenter: presenter) return viewController } }
lgpl-3.0
1e5c576ccf5dbe377632966654d74e97
37.522388
101
0.733437
5.960739
false
false
false
false
zhugejunwei/LeetCode
375. Guess Number Higher or Lower II.swift
1
1112
import Darwin // dp solution, 884 ms //func getMoneyAmount(n: Int) -> Int { // var num = Array(count: n+1, repeatedValue: Array(count: n+1, repeatedValue: 0)) // return dp(&num, 1, n) //} // //func dp(inout num: [[Int]], _ s: Int, _ e: Int) -> Int { // if s >= e { // return 0 // } // if num[s][e] != 0 { // return num[s][e] // } // var res = Int.max // for x in s...e { // let tmp = x + max(dp(&num, s, x-1), dp(&num, x+1, e)) // res = min(res, tmp) // } // num[s][e] = res // return res //} // bottom up, iteration solution, 468 ms func getMoneyAmount(n: Int) -> Int { if n == 1 { return 0 } var num = Array(count: n+1, repeatedValue: Array(count: n+1, repeatedValue: 0)) for j in 2...n { var i = j - 1 while i > 0 { var res = Int.max for k in i+1..<j { let tmp = k + max(num[i][k-1],num[k+1][j]) res = min(res,tmp) } num[i][j] = i+1 == j ? i : res i -= 1 } } return num[1][n] } getMoneyAmount(1)
mit
88a907c6c2e1880b475cd15551400ab9
22.680851
85
0.444245
2.79397
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/Main/BaseTableViewController.swift
1
1871
// // BaseTableViewController.swift // LSYWeiBo // // Created by 李世洋 on 16/5/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { var visitorView: VisitorView? let login = UserAccount.userLogin() override func loadView() { // 未登录显示 访客界面 login ? super.loadView() : createVisitorView() } //MARK: - 初始化 未登录 界面 private func createVisitorView() { let customView = NSBundle.mainBundle().loadNibNamed("VisitorView", owner: self, options: nil).last as! VisitorView view = customView visitorView = customView visitorView?.delegate = self navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: .registerBtnClick) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: .loginBtnClick) } override func viewDidLoad() { super.viewDidLoad() } //注册(导航栏) func registerBtnWillClick() { print(#function) } // 登录(导航栏) func loginBtnWillClick() { presentViewController("OAuthViewController".storyBoard(), animated: true, completion: nil) } } extension BaseTableViewController: VisitorViewDelegate { func registerClick() { } func loginClick() { presentViewController("OAuthViewController".storyBoard(), animated: true, completion: nil) } } private extension Selector { static let registerBtnClick = #selector(BaseTableViewController.registerBtnWillClick) static let loginBtnClick = #selector(BaseTableViewController.loginBtnWillClick) }
artistic-2.0
8f42f030369088390dcd23ff8f9adbf4
25.716418
147
0.664804
5.014006
false
false
false
false
Antondomashnev/FBSnapshotsViewer
FBSnapshotsViewerTests/ApplicationTestLogFilesListenerSpec.swift
1
4588
// // ApplicationTestLogFilesListenerSpec.swift // FBSnapshotsViewer // // Created by Anton Domashnev on 26.04.17. // Copyright © 2017 Anton Domashnev. All rights reserved. // import Quick import Nimble @testable import FBSnapshotsViewer class ApplicationTestLogFilesListener_MockFolderEventsListenerFactory: FolderEventsListenerFactory { var mockApplicationTestLogsEventsListener: FolderEventsListener! var givenDerivedDataFolder: DerivedDataFolder! override func applicationTestLogsEventsListener(at derivedDataFolder: DerivedDataFolder) -> FolderEventsListener { givenDerivedDataFolder = derivedDataFolder return mockApplicationTestLogsEventsListener } } class ApplicationTestLogFilesListenerSpec: QuickSpec { override func spec() { let derivedDataFolder = DerivedDataFolder.xcodeCustom(path: "Users/Antondomashnev/Library/Xcode/DerivedData/") var folderEventsListenerFactory: ApplicationTestLogFilesListener_MockFolderEventsListenerFactory! var applicationTestLogsEventsListener: FolderEventsListenerMock! var applicationTestLogFilesListener: ApplicationTestLogFilesListener! var applicationTestLogFilesListenerOutput: ApplicationTestLogFilesListenerOutput! var outputPath: String? beforeEach { applicationTestLogFilesListenerOutput = { path in outputPath = path } applicationTestLogsEventsListener = FolderEventsListenerMock(folderPath: "", filter: nil, fileWatcherFactory: FileWatcherFactory()) folderEventsListenerFactory = ApplicationTestLogFilesListener_MockFolderEventsListenerFactory() folderEventsListenerFactory.mockApplicationTestLogsEventsListener = applicationTestLogsEventsListener applicationTestLogFilesListener = ApplicationTestLogFilesListener(folderEventsListenerFactory: folderEventsListenerFactory) } describe(".stopListening") { beforeEach { applicationTestLogFilesListener.listen(derivedDataFolder: derivedDataFolder, outputTo: applicationTestLogFilesListenerOutput) applicationTestLogFilesListener.stopListening() applicationTestLogFilesListener.folderEventsListener(applicationTestLogsEventsListener, didReceive: FolderEvent.created(path: "createdPath.log", object: .folder)) } it("stops current listening") { expect(outputPath).to(beNil()) } } describe(".folderEventsListener(didReceive:)") { beforeEach { applicationTestLogFilesListener.listen(derivedDataFolder: derivedDataFolder, outputTo: applicationTestLogFilesListenerOutput) } context("when event without path") { beforeEach { applicationTestLogFilesListener.folderEventsListener(applicationTestLogsEventsListener, didReceive: FolderEvent.unknown) } it("doesnt output it") { expect(outputPath).to(beNil()) } } context("when event with path") { let eventPath = "Users/Antondomashnev/Library/Xcode/DerivedData/Application.log" beforeEach { applicationTestLogFilesListener.folderEventsListener(applicationTestLogsEventsListener, didReceive: FolderEvent.modified(path: eventPath, object: .folder)) } it("outputs it") { expect(outputPath).to(equal(eventPath)) } } } describe(".listen") { beforeEach { applicationTestLogFilesListener.listen(derivedDataFolder: derivedDataFolder, outputTo: applicationTestLogFilesListenerOutput) } context("when already listening") { beforeEach { applicationTestLogFilesListener.listen(derivedDataFolder: derivedDataFolder, outputTo: applicationTestLogFilesListenerOutput) } it("stops current listening") { expect(applicationTestLogsEventsListener.stopListeningCalled).to(beTrue()) } } it("starts listening the given derived data folder") { expect(folderEventsListenerFactory.givenDerivedDataFolder).to(equal(derivedDataFolder)) } it("starts listening") { expect(applicationTestLogsEventsListener.startListeningCalled).to(beTrue()) } } } }
mit
518336c4ed67c228b33065764494bb75
41.869159
178
0.679965
5.972656
false
true
false
false
Incipia/Goalie
PaintCode/BizeeBeeCharacterKit.swift
1
12681
// // BizeeBeeCharacterKit.swift // Goalie // // Created by Gregory Klein on 2/9/16. // Copyright © 2016 Incipia. All rights reserved. // import UIKit class BizeeBeeCharacterKit { class func drawAccessoriesForPriority(_ priority: TaskPriority) { switch priority { case .ages: //// Sunglasses Drawing let sunglassesPath = UIBezierPath() sunglassesPath.move(to: CGPoint(x: 61.54, y: 19.78)) sunglassesPath.addCurve(to: CGPoint(x: 57.07, y: 21.28), controlPoint1: CGPoint(x: 60.05, y: 19.04), controlPoint2: CGPoint(x: 58.21, y: 19.73)) sunglassesPath.addCurve(to: CGPoint(x: 52.59, y: 19.78), controlPoint1: CGPoint(x: 55.97, y: 19.73), controlPoint2: CGPoint(x: 54.09, y: 19.04)) sunglassesPath.addCurve(to: CGPoint(x: 50.85, y: 22.72), controlPoint1: CGPoint(x: 51.5, y: 20.33), controlPoint2: CGPoint(x: 50.9, y: 21.42)) sunglassesPath.addCurve(to: CGPoint(x: 43.35, y: 22.57), controlPoint1: CGPoint(x: 47.62, y: 21.57), controlPoint2: CGPoint(x: 45.09, y: 21.92)) sunglassesPath.addCurve(to: CGPoint(x: 41.61, y: 19.78), controlPoint1: CGPoint(x: 43.25, y: 21.37), controlPoint2: CGPoint(x: 42.65, y: 20.28)) sunglassesPath.addCurve(to: CGPoint(x: 37.13, y: 21.28), controlPoint1: CGPoint(x: 40.11, y: 19.04), controlPoint2: CGPoint(x: 38.27, y: 19.73)) sunglassesPath.addCurve(to: CGPoint(x: 32.66, y: 19.78), controlPoint1: CGPoint(x: 36.04, y: 19.73), controlPoint2: CGPoint(x: 34.15, y: 19.04)) sunglassesPath.addCurve(to: CGPoint(x: 31.41, y: 25), controlPoint1: CGPoint(x: 30.97, y: 20.63), controlPoint2: CGPoint(x: 30.37, y: 22.97)) sunglassesPath.addCurve(to: CGPoint(x: 36.68, y: 30.13), controlPoint1: CGPoint(x: 32.31, y: 26.84), controlPoint2: CGPoint(x: 34.64, y: 29.63)) sunglassesPath.addCurve(to: CGPoint(x: 42.4, y: 25.75), controlPoint1: CGPoint(x: 38.77, y: 30.62), controlPoint2: CGPoint(x: 41.21, y: 27.74)) sunglassesPath.addCurve(to: CGPoint(x: 51.8, y: 25.8), controlPoint1: CGPoint(x: 42.55, y: 25.65), controlPoint2: CGPoint(x: 46.03, y: 22.82)) sunglassesPath.addCurve(to: CGPoint(x: 56.62, y: 30.08), controlPoint1: CGPoint(x: 52.89, y: 27.54), controlPoint2: CGPoint(x: 54.83, y: 29.68)) sunglassesPath.addCurve(to: CGPoint(x: 62.79, y: 24.95), controlPoint1: CGPoint(x: 58.96, y: 30.62), controlPoint2: CGPoint(x: 61.84, y: 26.84)) sunglassesPath.addCurve(to: CGPoint(x: 61.54, y: 19.78), controlPoint1: CGPoint(x: 63.83, y: 22.97), controlPoint2: CGPoint(x: 63.23, y: 20.63)) sunglassesPath.close() sunglassesPath.miterLimit = 4; UIColor(priority: priority, headComponent: .stripe).setFill() sunglassesPath.fill() case .unknown: _drawSleepingFace() default: break } } class func _drawSleepingFace() { let fillColor12 = UIColor.eyeColorForPriority(.unknown) //// Group 9 //// Oval 3 Drawing let oval3Path = UIBezierPath(ovalIn: CGRect(x: 43.49, y: 32.66, width: 7.56, height: 7.56)) fillColor12.setFill() oval3Path.fill() //// Group 10 //// Bezier 6 Drawing let bezier6Path = UIBezierPath() bezier6Path.move(to: CGPoint(x: 39.62, y: 24.31)) bezier6Path.addLine(to: CGPoint(x: 35.29, y: 24.31)) bezier6Path.addCurve(to: CGPoint(x: 34.35, y: 24.81), controlPoint1: CGPoint(x: 34.89, y: 24.31), controlPoint2: CGPoint(x: 34.54, y: 24.51)) bezier6Path.addCurve(to: CGPoint(x: 34.15, y: 25.8), controlPoint1: CGPoint(x: 34.15, y: 25.1), controlPoint2: CGPoint(x: 34.05, y: 25.45)) bezier6Path.addCurve(to: CGPoint(x: 37.43, y: 28.24), controlPoint1: CGPoint(x: 34.59, y: 27.24), controlPoint2: CGPoint(x: 35.94, y: 28.24)) bezier6Path.addCurve(to: CGPoint(x: 40.71, y: 25.8), controlPoint1: CGPoint(x: 38.92, y: 28.24), controlPoint2: CGPoint(x: 40.26, y: 27.24)) bezier6Path.addCurve(to: CGPoint(x: 40.51, y: 24.81), controlPoint1: CGPoint(x: 40.81, y: 25.45), controlPoint2: CGPoint(x: 40.76, y: 25.1)) bezier6Path.addCurve(to: CGPoint(x: 39.62, y: 24.31), controlPoint1: CGPoint(x: 40.36, y: 24.51), controlPoint2: CGPoint(x: 40.01, y: 24.31)) bezier6Path.close() bezier6Path.miterLimit = 4; fillColor12.setFill() bezier6Path.fill() //// Group 11 //// Bezier 7 Drawing let bezier7Path = UIBezierPath() bezier7Path.move(to: CGPoint(x: 60.1, y: 24.81)) bezier7Path.addCurve(to: CGPoint(x: 59.16, y: 24.31), controlPoint1: CGPoint(x: 59.85, y: 24.51), controlPoint2: CGPoint(x: 59.5, y: 24.31)) bezier7Path.addLine(to: CGPoint(x: 54.88, y: 24.31)) bezier7Path.addCurve(to: CGPoint(x: 53.94, y: 24.81), controlPoint1: CGPoint(x: 54.48, y: 24.31), controlPoint2: CGPoint(x: 54.13, y: 24.51)) bezier7Path.addCurve(to: CGPoint(x: 53.74, y: 25.8), controlPoint1: CGPoint(x: 53.74, y: 25.1), controlPoint2: CGPoint(x: 53.64, y: 25.45)) bezier7Path.addCurve(to: CGPoint(x: 57.02, y: 28.24), controlPoint1: CGPoint(x: 54.18, y: 27.24), controlPoint2: CGPoint(x: 55.53, y: 28.24)) bezier7Path.addCurve(to: CGPoint(x: 60.3, y: 25.8), controlPoint1: CGPoint(x: 58.56, y: 28.24), controlPoint2: CGPoint(x: 59.85, y: 27.24)) bezier7Path.addCurve(to: CGPoint(x: 60.1, y: 24.81), controlPoint1: CGPoint(x: 60.35, y: 25.45), controlPoint2: CGPoint(x: 60.3, y: 25.1)) bezier7Path.close() bezier7Path.miterLimit = 4; fillColor12.setFill() bezier7Path.fill() } class func drawBody(_ bodyColor: UIColor, cheekColor: UIColor, stripeColor: UIColor, bowtieColor: UIColor) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Shadow Declarations let shadow = NSShadow() shadow.shadowColor = UIColor.black.withAlphaComponent(0.2) shadow.shadowOffset = CGSize(width: -1.1, height: 4.1) shadow.shadowBlurRadius = 8 //// Group 2 //// BodyOutline Drawing let bodyOutlinePath = UIBezierPath() bodyOutlinePath.move(to: CGPoint(x: 69.65, y: 18.54)) bodyOutlinePath.addCurve(to: CGPoint(x: 76.56, y: 37.24), controlPoint1: CGPoint(x: 73.97, y: 23.66), controlPoint2: CGPoint(x: 76.56, y: 30.18)) bodyOutlinePath.addCurve(to: CGPoint(x: 76.56, y: 37.43), controlPoint1: CGPoint(x: 76.56, y: 37.29), controlPoint2: CGPoint(x: 76.56, y: 37.38)) bodyOutlinePath.addCurve(to: CGPoint(x: 74.82, y: 47.48), controlPoint1: CGPoint(x: 76.56, y: 40.82), controlPoint2: CGPoint(x: 76.01, y: 44.25)) bodyOutlinePath.addCurve(to: CGPoint(x: 56.87, y: 87.1), controlPoint1: CGPoint(x: 69.75, y: 61.15), controlPoint2: CGPoint(x: 57.22, y: 71.74)) bodyOutlinePath.addCurve(to: CGPoint(x: 53.39, y: 88.99), controlPoint1: CGPoint(x: 56.82, y: 88.85), controlPoint2: CGPoint(x: 54.88, y: 89.94)) bodyOutlinePath.addCurve(to: CGPoint(x: 20.67, y: 55.09), controlPoint1: CGPoint(x: 40.11, y: 80.99), controlPoint2: CGPoint(x: 26.99, y: 69.55)) bodyOutlinePath.addCurve(to: CGPoint(x: 32.26, y: 12.18), controlPoint1: CGPoint(x: 14.26, y: 40.37), controlPoint2: CGPoint(x: 17.94, y: 20.83)) bodyOutlinePath.addCurve(to: CGPoint(x: 47.37, y: 8), controlPoint1: CGPoint(x: 36.78, y: 9.44), controlPoint2: CGPoint(x: 42.05, y: 8)) bodyOutlinePath.addCurve(to: CGPoint(x: 69.65, y: 18.54), controlPoint1: CGPoint(x: 56.22, y: 8), controlPoint2: CGPoint(x: 64.23, y: 12.13)) bodyOutlinePath.close() bodyOutlinePath.miterLimit = 4; context!.saveGState() context!.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: (shadow.shadowColor as! UIColor).cgColor) bodyColor.setFill() bodyOutlinePath.fill() context!.restoreGState() //// Left Cheek Drawing let leftCheekPath = UIBezierPath(ovalIn: CGRect(x: 27.88, y: 30.18, width: 5.47, height: 5.47)) cheekColor.setFill() leftCheekPath.fill() //// Right Cheek Drawing let rightCheekPath = UIBezierPath(ovalIn: CGRect(x: 60.85, y: 30.18, width: 5.47, height: 5.47)) cheekColor.setFill() rightCheekPath.fill() //// Bottom Stripe Drawing let bottomStripePath = UIBezierPath() bottomStripePath.move(to: CGPoint(x: 56.87, y: 87.15)) bottomStripePath.addCurve(to: CGPoint(x: 57.57, y: 81.44), controlPoint1: CGPoint(x: 56.92, y: 85.17), controlPoint2: CGPoint(x: 57.17, y: 83.28)) bottomStripePath.addLine(to: CGPoint(x: 42.4, y: 81.44)) bottomStripePath.addCurve(to: CGPoint(x: 53.34, y: 89.04), controlPoint1: CGPoint(x: 46.08, y: 84.37), controlPoint2: CGPoint(x: 49.81, y: 86.96)) bottomStripePath.addCurve(to: CGPoint(x: 56.87, y: 87.15), controlPoint1: CGPoint(x: 54.88, y: 89.94), controlPoint2: CGPoint(x: 56.87, y: 88.89)) bottomStripePath.close() bottomStripePath.miterLimit = 4; stripeColor.setFill() bottomStripePath.fill() //// Middle Stripe Drawing let middleStripePath = UIBezierPath() middleStripePath.move(to: CGPoint(x: 60.4, y: 73.33)) middleStripePath.addCurve(to: CGPoint(x: 65.02, y: 65.08), controlPoint1: CGPoint(x: 61.74, y: 70.5), controlPoint2: CGPoint(x: 63.33, y: 67.76)) middleStripePath.addLine(to: CGPoint(x: 26.44, y: 65.08)) middleStripePath.addCurve(to: CGPoint(x: 33.45, y: 73.33), controlPoint1: CGPoint(x: 28.53, y: 67.96), controlPoint2: CGPoint(x: 30.92, y: 70.75)) middleStripePath.addLine(to: CGPoint(x: 60.4, y: 73.33)) middleStripePath.close() middleStripePath.miterLimit = 4; stripeColor.setFill() middleStripePath.fill() //// Top Stripe Drawing let topStripePath = UIBezierPath() topStripePath.move(to: CGPoint(x: 70.14, y: 56.97)) topStripePath.addCurve(to: CGPoint(x: 74.37, y: 48.72), controlPoint1: CGPoint(x: 71.74, y: 54.29), controlPoint2: CGPoint(x: 73.23, y: 51.55)) topStripePath.addLine(to: CGPoint(x: 18.49, y: 48.72)) topStripePath.addCurve(to: CGPoint(x: 21.52, y: 56.97), controlPoint1: CGPoint(x: 19.18, y: 51.55), controlPoint2: CGPoint(x: 20.18, y: 54.29)) topStripePath.addLine(to: CGPoint(x: 70.14, y: 56.97)) topStripePath.close() topStripePath.miterLimit = 4; stripeColor.setFill() topStripePath.fill() //// Group //// Bezier 8 Drawing let bezier8Path = UIBezierPath() bezier8Path.move(to: CGPoint(x: 46.05, y: 6.03)) bezier8Path.addCurve(to: CGPoint(x: 46.05, y: 7.69), controlPoint1: CGPoint(x: 46.69, y: 6.42), controlPoint2: CGPoint(x: 46.69, y: 7.3)) bezier8Path.addLine(to: CGPoint(x: 41.88, y: 10.13)) bezier8Path.addLine(to: CGPoint(x: 37.72, y: 12.58)) bezier8Path.addCurve(to: CGPoint(x: 36.29, y: 11.74), controlPoint1: CGPoint(x: 37.08, y: 12.97), controlPoint2: CGPoint(x: 36.29, y: 12.48)) bezier8Path.addLine(to: CGPoint(x: 36.29, y: 1.97)) bezier8Path.addCurve(to: CGPoint(x: 37.72, y: 1.14), controlPoint1: CGPoint(x: 36.29, y: 1.24), controlPoint2: CGPoint(x: 37.08, y: 0.75)) bezier8Path.addLine(to: CGPoint(x: 41.88, y: 3.58)) bezier8Path.addLine(to: CGPoint(x: 46.05, y: 6.03)) bezier8Path.close() bowtieColor.setFill() bezier8Path.fill() //// Bezier 9 Drawing let bezier9Path = UIBezierPath() bezier9Path.move(to: CGPoint(x: 49.09, y: 6.03)) bezier9Path.addCurve(to: CGPoint(x: 49.09, y: 7.69), controlPoint1: CGPoint(x: 48.46, y: 6.42), controlPoint2: CGPoint(x: 48.46, y: 7.3)) bezier9Path.addLine(to: CGPoint(x: 53.26, y: 10.13)) bezier9Path.addLine(to: CGPoint(x: 57.43, y: 12.58)) bezier9Path.addCurve(to: CGPoint(x: 58.85, y: 11.74), controlPoint1: CGPoint(x: 58.07, y: 12.97), controlPoint2: CGPoint(x: 58.85, y: 12.48)) bezier9Path.addLine(to: CGPoint(x: 58.85, y: 1.97)) bezier9Path.addCurve(to: CGPoint(x: 57.43, y: 1.14), controlPoint1: CGPoint(x: 58.85, y: 1.24), controlPoint2: CGPoint(x: 58.07, y: 0.75)) bezier9Path.addLine(to: CGPoint(x: 53.26, y: 3.58)) bezier9Path.addLine(to: CGPoint(x: 49.09, y: 6.03)) bezier9Path.close() bowtieColor.setFill() bezier9Path.fill() //// Rectangle Drawing let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 43.6, y: 3.89, width: 7.1, height: 6.1), cornerRadius: 3.05) bowtieColor.setFill() rectanglePath.fill() } }
apache-2.0
d8dac2f7e3880dcbb6d423734565aa7d
55.106195
153
0.635804
3.003316
false
false
false
false
uasys/swift
test/Parse/deprecated_where.swift
13
4344
// RUN: %target-swift-frontend -typecheck -verify %s -swift-version 4 protocol Mashable { } protocol Womparable { } // FuncDecl: Choose 0 func f1<T>(x: T) {} // FuncDecl: Choose 1 // 1: Inherited constraint func f2<T: Mashable>(x: T) {} // no-warning // 2: Non-trailing where func f3<T where T: Womparable>(x: T) {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{10-30=}} {{37-37= where T: Womparable}} // 3: Has return type func f4<T>(x: T) -> Int { return 2 } // no-warning // 4: Trailing where func f5<T>(x: T) where T : Equatable {} // no-warning // FuncDecl: Choose 2 // 1,2 func f12<T: Mashable where T: Womparable>(x: T) {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{21-41=}} {{48-48= where T: Womparable}} // 1,3 func f13<T: Mashable>(x: T) -> Int { return 2 } // no-warning // 1,4 func f14<T: Mashable>(x: T) where T: Equatable {} // no-warning // 2,3 func f23<T where T: Womparable>(x: T) -> Int { return 2 } // expected-error {{'where' clause next to generic parameters is obsolete}} {{11-31=}} {{45-45= where T: Womparable}} // 2,4 func f24<T where T: Womparable>(x: T) where T: Equatable {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{11-31=}} {{39-44=where T: Womparable,}} // 3,4 func f34<T>(x: T) -> Int where T: Equatable { return 2 } // no-warning // FuncDecl: Choose 3 // 1,2,3 func f123<T: Mashable where T: Womparable>(x: T) -> Int { return 2 } // expected-error {{'where' clause next to generic parameters is obsolete}} {{22-42=}} {{56-56= where T: Womparable}} // 1,2,4 func f124<T: Mashable where T: Womparable>(x: T) where T: Equatable {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{22-42=}} {{50-55=where T: Womparable,}} // 2,3,4 func f234<T where T: Womparable>(x: T) -> Int where T: Equatable { return 2 } // expected-error {{'where' clause next to generic parameters is obsolete}} {{12-32=}} {{47-52=where T: Womparable,}} // FuncDecl: Choose 4 // 1,2,3,4 func f1234<T: Mashable where T: Womparable>(x: T) -> Int where T: Equatable { return 2 } // expected-error {{'where' clause next to generic parameters is obsolete}} {{23-43=}} {{58-63=where T: Womparable,}} // NominalTypeDecl: Choose 0 struct S0<T> {} // NominalTypeDecl: Choose 1 // 1: Inherited constraint struct S1<T: Mashable> {} // no-warning // 2: Non-trailing where struct S2<T where T: Womparable> {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{12-32=}} {{33-33= where T: Womparable}} // 3: Trailing where struct S3<T> where T : Equatable {} // no-warning // NominalTypeDecl: Choose 2 // 1,2 struct S12<T: Mashable where T: Womparable> {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{23-43=}} {{44-44= where T: Womparable}} // 1,3 struct S13<T: Mashable> where T: Equatable {} // no-warning // 2,3 struct S23<T where T: Womparable> where T: Equatable {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{13-33=}} {{35-40=where T: Womparable,}} // NominalTypeDecl: Choose 3 // 1,2,3 struct S123<T: Mashable where T: Womparable> where T: Equatable {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{24-44=}} {{46-51=where T: Womparable,}} protocol ProtoA {} protocol ProtoB {} protocol ProtoC {} protocol ProtoD {} func testCombinedConstraints<T: ProtoA & ProtoB where T: ProtoC>(x: T) {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{48-64=}} {{71-71= where T: ProtoC}} func testCombinedConstraints<T: ProtoA & ProtoB where T: ProtoC>(x: T) where T: ProtoD {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{48-64=}} {{72-77=where T: ProtoC,}} func testCombinedConstraintsOld<T: protocol<ProtoA, ProtoB> where T: ProtoC>(x: T) {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{60-76=}} {{83-83= where T: ProtoC}} // expected-error@-1 {{'protocol<...>' composition syntax has been removed}} func testCombinedConstraintsOld<T: protocol<ProtoA, ProtoB> where T: ProtoC>(x: T) where T: ProtoD {} // expected-error {{'where' clause next to generic parameters is obsolete}} {{60-76=}} {{84-89=where T: ProtoC,}} // expected-error@-1 {{'protocol<...>' composition syntax has been removed}}
apache-2.0
e79a8072793966ba8f4c75bfeb564e1f
51.97561
215
0.673343
3.12743
false
false
false
false
tjw/swift
test/SILGen/init_ref_delegation.swift
2
8556
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @$S19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S } // CHECK-NEXT: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin S.Type) -> S // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[PB]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*S // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] : ${ var S } // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // We don't want the enum to be uninhabited case Foo // CHECK-LABEL: sil hidden @$S19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box ${ var E } // CHECK: [[MARKED_E_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[E_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_E_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin E.Type) -> E // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[PB]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*E self.init(x: X()) // CHECK: destroy_value [[MARKED_E_BOX]] : ${ var E } // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @$S19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: assign [[SELF_BOX1]] to [[PB]] : $*S2 // CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[PB]] : $*S2 self.init(t: X()) // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var S2 } // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C1C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (X, @owned C1) -> @owned C1 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C1 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[ORIG_SELF]] to [init] [[PB]] : $*C1 // CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load [take] [[PB]] : $*C1 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : (C1.Type) -> (X, X) -> C1, $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: store [[SELFP]] to [init] [[PB]] : $*C1 // CHECK: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*C1 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C1 } // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (X, @owned C2) -> @owned C2 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[ORIG_SELF]] to [init] [[PB_SELF]] : $*C2 // CHECK: [[SELF:%[0-9]+]] = load [take] [[PB_SELF]] : $*C2 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : (C2.Type) -> (X, X) -> C2, $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: store [[REPLACE_SELF]] to [init] [[PB_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[PB_SELF]] : $*C2 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C2 } // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C3C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C3) -> @owned C3 convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : (C3.Type) -> (X) -> C3, $@convention(method) (X, @owned C3) -> @owned C3 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @$S19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fc // CHECK: [[PEER:%[0-9]+]] = function_ref @$S19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fc // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
apache-2.0
51cb4bd9b02b9a784381e85d845a3b8f
42.85641
182
0.537886
2.703762
false
false
false
false
testpress/ios-app
ios-app/UI/AccessCodeExamsViewController.swift
1
2580
// // AccessCodeExamsViewController.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class AccessCodeExamsViewController: TPBasePagedTableViewController<Exam> { let cellIdentifier = "ExamsTableViewCell" var accessCode: String! required init?(coder aDecoder: NSCoder) { super.init(pager: ExamPager(), coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.setStatusBarColor() (pager as! ExamPager).accessCode = accessCode tableView.register(UINib(nibName: cellIdentifier, bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier) tableView.rowHeight = 105 tableView.allowsSelection = false } // MARK: - Table view data source override func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ExamsTableViewCell cell.initExamCell(items[indexPath.row], accessCode: accessCode!, viewController: self) return cell } override func setEmptyText() { emptyView.setValues(image: Images.ExamsFlatIcon.image, title: Strings.NO_EXAMS, description: Strings.NO_AVAILABLE_EXAM) } @IBAction func back() { dismiss(animated: true, completion: nil) } }
mit
abde428ba3a5403507124ae8a4323d26
36.926471
100
0.692904
4.723443
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Onboarding/Avatar/View/OnboardingAvatarScreen.swift
1
5579
// // Copyright 2021 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 SwiftUI import DesignKit @available(iOS 14.0, *) struct OnboardingAvatarScreen: View { // MARK: - Properties // MARK: Private @Environment(\.theme) private var theme @State private var isPresentingPickerSelection = false // MARK: Public @ObservedObject var viewModel: OnboardingAvatarViewModel.Context var body: some View { ScrollView { VStack(spacing: 0) { avatar .padding(.horizontal, 2) .padding(.bottom, 40) header .padding(.bottom, 40) buttons } .padding(.horizontal) .padding(.top, 8) .frame(maxWidth: OnboardingMetrics.maxContentWidth) } .frame(maxWidth: .infinity, maxHeight: .infinity) .accentColor(theme.colors.accent) .background(theme.colors.background.ignoresSafeArea()) .alert(item: $viewModel.alertInfo) { $0.alert } } /// The user's avatar along with a picker button var avatar: some View { Group { if let avatarImage = viewModel.viewState.avatar { Image(uiImage: avatarImage) .resizable() .scaledToFill() .accessibilityIdentifier("avatarImage") } else { PlaceholderAvatarImage(firstCharacter: viewModel.viewState.placeholderAvatarLetter, colorIndex: viewModel.viewState.placeholderAvatarColorIndex) .accessibilityIdentifier("placeholderAvatar") } } .clipShape(Circle()) .frame(width: 120, height: 120) .overlay(cameraButton, alignment: .bottomTrailing) .onTapGesture { isPresentingPickerSelection = true } .actionSheet(isPresented: $isPresentingPickerSelection) { pickerSelectionActionSheet } .accessibilityElement(children: .ignore) .accessibilityLabel(VectorL10n.onboardingAvatarAccessibilityLabel) .accessibilityValue(VectorL10n.edit) } /// The button to indicate the user can tap to select an avatar /// Note: The whole avatar is tappable to make this easier. var cameraButton: some View { ZStack { Circle() .foregroundColor(theme.colors.background) .shadow(color: .black.opacity(0.15), radius: 2.4, y: 2.4) Image(viewModel.viewState.buttonImage.name) .renderingMode(.template) .foregroundColor(theme.colors.secondaryContent) } .frame(width: 40, height: 40) } /// The action sheet that asks how the user would like to set their avatar. var pickerSelectionActionSheet: ActionSheet { ActionSheet(title: Text(VectorL10n.onboardingAvatarTitle), buttons: [ .default(Text(VectorL10n.imagePickerActionCamera)) { viewModel.send(viewAction: .takePhoto) }, .default(Text(VectorL10n.imagePickerActionLibrary)) { viewModel.send(viewAction: .pickImage) }, .cancel() ]) } /// The screen's title and message views. var header: some View { VStack(spacing: 8) { Text(VectorL10n.onboardingAvatarTitle) .font(theme.fonts.title2B) .multilineTextAlignment(.center) .foregroundColor(theme.colors.primaryContent) Text(VectorL10n.onboardingAvatarMessage) .font(theme.fonts.subheadline) .multilineTextAlignment(.center) .foregroundColor(theme.colors.secondaryContent) } } /// The main action buttons in the form. var buttons: some View { VStack(spacing: 8) { Button(VectorL10n.onboardingPersonalizationSave) { viewModel.send(viewAction: .save) } .buttonStyle(PrimaryActionButtonStyle()) .disabled(viewModel.viewState.avatar == nil) .accessibilityIdentifier("saveButton") Button { viewModel.send(viewAction: .skip) } label: { Text(VectorL10n.onboardingPersonalizationSkip) .font(theme.fonts.body) .padding(12) } } } } // MARK: - Previews @available(iOS 15.0, *) struct OnboardingAvatar_Previews: PreviewProvider { static let stateRenderer = MockOnboardingAvatarScreenState.stateRenderer static var previews: some View { stateRenderer.screenGroup(addNavigation: true) .navigationViewStyle(.stack) .theme(.light).preferredColorScheme(.light) stateRenderer.screenGroup(addNavigation: true) .navigationViewStyle(.stack) .theme(.dark).preferredColorScheme(.dark) } }
apache-2.0
6a8863f3864573e58731d41e9afe90a1
34.535032
99
0.59957
5.071818
false
false
false
false
fe9lix/TimeAway
TimeAway/src/AppDelegate.swift
1
3347
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, LockControllerDelegate, StatusBarMenuDelegate { @IBOutlet weak var statusBarMenu: StatusBarMenu! let mainWindowController = MainWindowController(windowNibName: "MainWindow") let lockController = LockController(userDefaults: UserDefaults.sharedInstance) let timeAwayRepository = TimeAwayRepository(userDefaults: UserDefaults.sharedInstance) func applicationDidFinishLaunching(aNotification: NSNotification) { setupStatusBarMenu() setupLockController() showRecentRecordAfterLaunch() } //MARK: LockController private func setupLockController() { lockController.delegate = self } func lockController(lockController: LockController, didUnlockScreen timeAwayRecord: TimeAwayRecord) { timeAwayRepository.saveRecord(timeAwayRecord) updateStatusBarMenu() if UserDefaults.sharedInstance.reminderEnabled { showRecentRecord() } else { updateRecentRecord() } } //MARK: MainWindowController private func showRecentRecordAfterLaunch() { if !UserDefaults.sharedInstance.hasLaunched { UserDefaults.sharedInstance.hasLaunched = true showRecentRecord() } } private func showRecentRecord() { mainWindowController.bringToFront() updateRecentRecord() } private func updateRecentRecord() { if let recentRecord = timeAwayRepository.recentRecord { mainWindowController.render(TimeAwayPresentationModel(model: recentRecord)) } else { mainWindowController.render(nil) } } //MARK: StatusBarMenu private func setupStatusBarMenu() { statusBarMenu.menuDelegate = self statusBarMenu.showWhenUnlockedEnabled = UserDefaults.sharedInstance.reminderEnabled updateStatusBarMenu() } private func updateStatusBarMenu() { statusBarMenu.history = timeAwayRepository.allRecords.map { record in TimeAwayPresentationModel(model: record) } } @IBAction func statusBarShowRecentTapped(sender: AnyObject) { showRecentRecord() } @IBAction func statusBarShowWhenUnlockedTapped(sender: AnyObject) { statusBarMenu.showWhenUnlockedEnabled = !statusBarMenu.showWhenUnlockedEnabled UserDefaults.sharedInstance.reminderEnabled = statusBarMenu.showWhenUnlockedEnabled } func statusBarMenu(statusBarMenu: StatusBarMenu, didSelectHistoryItem model: TimeAwayPresentationModel) { model.copyToClipboard() } func statusBarMenuDidClearHistory(statusBarMenu: StatusBarMenu) { timeAwayRepository.deleteAll() updateStatusBarMenu() updateRecentRecord() } @IBAction func statusBarAboutTapped(sender: AnyObject) { NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://github.com/fe9lix/TimeAway")!) } @IBAction func statusBarQuitTapped(sender: AnyObject) { NSApplication.sharedApplication().terminate(self) } //MARK: Termination func applicationWillTerminate(aNotification: NSNotification) { } }
mit
0f5bdde92706bd1d7c9b4cfb9cff12dd
30.280374
120
0.68539
5.653716
false
false
false
false
dnevera/IMProcessing
IMProcessing/Classes/Base/IMPGraphics.swift
1
2811
// // IMPGraphics.swift // IMProcessing // // Created by denis svinarchuk on 20.04.16. // Copyright © 2016 Dehancer.photo. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif import Metal import simd public protocol IMPGraphicsProvider { var backgroundColor:IMPColor {get set} var graphics:IMPGraphics! {get} } extension IMPGraphicsProvider{ public var clearColor:MTLClearColor { get { let rgba = backgroundColor.rgba let color = MTLClearColor(red: rgba.r.double, green: rgba.g.double, blue: rgba.b.double, alpha: rgba.a.double) return color } } } public class IMPGraphics: NSObject, IMPContextProvider { public let vertexName:String public let fragmentName:String public var context:IMPContext! public lazy var library:MTLLibrary = { return self.context.defaultLibrary }() public lazy var pipeline:MTLRenderPipelineState? = { do { let renderPipelineDescription = MTLRenderPipelineDescriptor() renderPipelineDescription.vertexDescriptor = self.vertexDescriptor renderPipelineDescription.colorAttachments[0].pixelFormat = IMProcessing.colors.pixelFormat renderPipelineDescription.vertexFunction = self.context.defaultLibrary.newFunctionWithName(self.vertexName) renderPipelineDescription.fragmentFunction = self.context.defaultLibrary.newFunctionWithName(self.fragmentName) return try self.context.device.newRenderPipelineStateWithDescriptor(renderPipelineDescription) } catch let error as NSError{ fatalError(" *** IMPGraphics: \(error)") } }() public required init(context:IMPContext, vertex:String, fragment:String, vertexDescriptor:MTLVertexDescriptor? = nil) { self.context = context self.vertexName = vertex self.fragmentName = fragment self._vertexDescriptor = vertexDescriptor } lazy var _defaultVertexDescriptor:MTLVertexDescriptor = { var v = MTLVertexDescriptor() v.attributes[0].format = .Float3; v.attributes[0].bufferIndex = 0; v.attributes[0].offset = 0; v.attributes[1].format = .Float3; v.attributes[1].bufferIndex = 0; v.attributes[1].offset = sizeof(float3); v.layouts[0].stride = sizeof(IMPVertex) return v }() var _vertexDescriptor:MTLVertexDescriptor? public var vertexDescriptor:MTLVertexDescriptor { return _vertexDescriptor ?? _defaultVertexDescriptor } }
mit
083e754112140b6bbb80514586d4aae6
31.674419
139
0.631673
5.026834
false
false
false
false
PedroTrujilloV/TIY-Assignments
33--The-Eagle-has-Landed/LaberintoLabyrinth/LaberintoLabyrinth/ModeSelectionViewController.swift
1
2933
// // MainViewController.swift // LaberintoLabyrinth // // Created by Pedro Trujillo on 12/6/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit protocol playMazeProtocolDelegate { func gameResult(name:String, scoreTime:NSTimeInterval) } class ModeSelectionViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, playMazeProtocolDelegate { @IBOutlet var modePicker: UIPickerView! var modesArray: Array<playMode> = [] var modesDict: Dictionary = ["":[Int]()] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //modesArray = [ "1 Easy", "1 Medium", "Dificult"] //modesDict = ["Easy": [20,1,1], "Medium": [30,2,1], "Dificult": [35,2,2]] modesArray.append(playMode(dataDictionary: ["id":"01","name":"Easy","mazeSize":"20", "numberOfBalls":"1", "mazeHightRows":"1", "idPlayer":"001", "maxScoreTime":"1234"])) modesArray.append(playMode(dataDictionary: ["id":"02","name":"Medium","mazeSize":"30", "numberOfBalls":"2", "mazeHightRows":"1", "idPlayer":"002", "maxScoreTime":"1234"])) modesArray.append(playMode(dataDictionary: ["id":"03","name":"Dificult","mazeSize":"35", "numberOfBalls":"2", "mazeHightRows":"2", "idPlayer":"001", "maxScoreTime":"1234"])) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return modesArray.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let newPlayMode = modesArray[row] as playMode return newPlayMode.name } @IBAction func PlayTapped(sender: UIButton) { } // 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?) { if segue.identifier == "ShowMazeViewControllerSegue" { let aMode = modesArray[ modePicker.selectedRowInComponent(0)] as playMode let mazeVC = segue.destinationViewController as! MazeViewController mazeVC.delegator = self mazeVC.mazeSize = aMode.mazeSize mazeVC.numberOfBalls = aMode.numberOfBalls mazeVC.mazeHightRows = aMode.mazeHightRows } } // MARK: - Game protocol func gameResult(name:String, scoreTime:Double) { print("name:") print(name) print("scoreTime") print(scoreTime) } }
cc0-1.0
acfe21b4e9aaf703f1be6a88efd9b529
30.869565
181
0.642906
4.280292
false
false
false
false
veeman961/Flicks
Flicks/MoviesViewController.swift
1
8494
// // MoviesViewController.swift // Flicks // // Created by Kevin Rajan on 1/10/16. // Copyright © 2016 veeman961. All rights reserved. // import UIKit import AFNetworking import JTProgressHUD class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var collectionView: UICollectionView! var movies: [NSDictionary]? var refreshControl: UIRefreshControl! var endpoint: String! var detail: Bool = true var tabBarItemTitle: String! @IBOutlet weak var viewTypeButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged) tableView.insertSubview(refreshControl, atIndex: 0) tableView.dataSource = self tableView.delegate = self networkRequest(self.endpoint) //collectionView.registerClass(MovieCollectionViewCell.self, forCellWithReuseIdentifier: "MovieCellIcon") collectionView.backgroundColor = myVariables.backgroundColor if detail { collectionView.hidden = true tableView.hidden = false } else { collectionView.hidden = false tableView.hidden = true } } func networkRequest(endpoint: String) { let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = NSURL(string:"https://api.themoviedb.org/3/\(endpoint)?api_key=\(apiKey)") let request = NSURLRequest(URL: url!) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { self.movies = (responseDictionary["results"] as! [NSDictionary]) self.tableView.reloadData() self.collectionView.reloadData() JTProgressHUD.hide() } } }); task.resume() } override func viewWillAppear(animated: Bool) { if movies == nil { JTProgressHUD.show() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: TableView - Configure the UITableView // numberOfRowsInSection func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let movies = movies { return movies.count } else { return 0 } } // heightForRowAtIndexPath func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120 } // configure cell func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MovieCell = tableView.dequeueReusableCellWithIdentifier("MovieCellDetail", forIndexPath: indexPath) as! MovieCell let movie = movies![indexPath.row] let title = movie["title"] as? String let overview = movie["overview"] as? String cell.titleLabel.text = title cell.overviewLabel.text = overview let baseUrl = "http://image.tmdb.org/t/p/w500/" if let posterPath = movie["poster_path"] as? String { let posterURL = NSURL(string: baseUrl + posterPath) cell.posterImage.setImageWithURL(posterURL!) } let year = (movie["release_date"] as! NSString).substringWithRange(NSRange(location: 0, length: 4)) let rating = movie["vote_average"] as! Double cell.yearLabel.text = String(year) cell.ratingLabel.text = String(format: "%.1f", rating) ratingColor(cell.ratingLabel, rating: rating) cell.selectionStyle = .None return cell } // MARK: CollectionView func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let movies = movies { return movies.count } else { return 0 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCellIcon", forIndexPath: indexPath) as! MovieCollectionViewCell let movie = movies![indexPath.row] let posterPath = movie["poster_path"] as! String let baseUrl = "http://image.tmdb.org/t/p/w500/" let imageUrl = NSURL(string: baseUrl + posterPath) print(cell.heightAnchor) cell.posterImage.setImageWithURL(imageUrl!) return cell } // MARK: Helper methods func ratingColor(label: UILabel, rating: Double) { if rating > 6 { label.backgroundColor = UIColor.yellowColor() label.textColor = UIColor.blackColor() } else if rating > 4 { label.backgroundColor = UIColor.greenColor() label.textColor = UIColor.whiteColor() } else { label.backgroundColor = UIColor.redColor() label.textColor = UIColor.whiteColor() } } /* func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } */ func onRefresh() { networkRequest(self.endpoint) self.refreshControl.endRefreshing() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { NSNotificationCenter.defaultCenter().postNotificationName("closeMenuViaNotification", object: nil) view.endEditing(true) } // MARK: Actions @IBAction func switchAction(sender: AnyObject) { if detail { let image: UIImage = UIImage(named: "detailView.png")! viewTypeButton.image = image tableView.hidden = true collectionView.hidden = false } else { let image: UIImage = UIImage(named: "albumView.png")! viewTypeButton.image = image tableView.hidden = false collectionView.hidden = true } detail = !(detail) } @IBAction func toggleMenu(sender: AnyObject) { NSNotificationCenter.defaultCenter().postNotificationName("toggleMenu", object: nil) } // 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.a if detail { let cell = sender as! UITableViewCell let indexpath = tableView.indexPathForCell(cell) let movie = movies![indexpath!.row] let detailViewController = segue.destinationViewController as! MovieDetailViewController detailViewController.movie = movie } else { let cell = sender as! UICollectionViewCell let indexpath = collectionView.indexPathForCell(cell) let movie = movies![indexpath!.row] let detailViewController = segue.destinationViewController as! MovieDetailViewController detailViewController.movie = movie } } }
apache-2.0
4b6bb23021238d267b9e546ccef6f538
34.3875
180
0.618038
5.580158
false
false
false
false
XGBCCC/JBImageBrowserViewController
JBImageBrowserViewController/JBImageBrowserViewController.swift
1
19553
// // JBImageBrowserView.swift // JBImageBrowserView // // Created by JimBo on 16/2/17. // Copyright © 2016年 JimBo. All rights reserved. // import UIKit import Kingfisher open class JBImageBrowserViewController: UIViewController { fileprivate var imageList:[JBImage]! fileprivate let defaultZoomScale:CGFloat = 1.0 fileprivate let doubleTapZoomScale:CGFloat = 2.0 fileprivate let maxZoomScale:CGFloat = 3.0 fileprivate var defaultAnimationDuration = 0.15 fileprivate var currentPageIndex = 0 //加载失败占位图 fileprivate var failedPlaceholderImage:UIImage? fileprivate var pageScrollView:UIScrollView //pan手势移动最大距离 fileprivate var translationMaxValue:CGFloat = 0 //关闭按钮 fileprivate var activeButton:UIButton? fileprivate var activeButtonSize = CGSize(width: 50, height: 50) fileprivate let activeButtonPadding:CGFloat = 10.0 /** 创建图片浏览器 - parameter imageArray: JBImage Array - parameter failedPlaceholderImage: 加载失败后的占位图 - returns: 图片浏览器实例 */ public init(imageArray:[JBImage]!,failedPlaceholderImage:UIImage?) { self.imageList = imageArray self.failedPlaceholderImage = failedPlaceholderImage self.pageScrollView = UIScrollView() super.init(nibName: nil, bundle: nil) setupUserInterface() configureUserInterface() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open var prefersStatusBarHidden : Bool { return true } //MARK: - UI Setup func setupUserInterface(){ pageScrollView.frame = CGRect(origin: CGPoint(x: 0,y: 0), size: CGSize(width: self.view.bounds.width, height: self.view.bounds.height)) pageScrollView.backgroundColor = UIColor.black pageScrollView.showsHorizontalScrollIndicator = false pageScrollView.showsVerticalScrollIndicator = false pageScrollView.isPagingEnabled = true pageScrollView.bouncesZoom = false pageScrollView.delegate = self pageScrollView.contentSize = CGSize(width: self.pageScrollView.bounds.width*CGFloat(imageList.count), height: self.pageScrollView.bounds.height) view.addSubview(self.pageScrollView) modalPresentationStyle = .overFullScreen modalPresentationCapturesStatusBarAppearance = true let activeImage = (UIImage(named: "JBImagesBrowserVC.bundle/imagesbrowser_item") != nil) ? UIImage(named: "JBImagesBrowserVC.bundle/imagesbrowser_item") : UIImage(named:"Frameworks/JBImageBrowserViewController.framework/JBImagesBrowserVC.bundle/imagesbrowser_item"); activeButton = UIButton(frame: CGRect(origin: CGPoint(x: view.bounds.size.width - CGFloat(activeButtonPadding) - activeButtonSize.width, y: view.bounds.size.height - CGFloat(activeButtonPadding) - activeButtonSize.height), size: activeButtonSize)) activeButton?.setImage(activeImage, for: UIControlState()) activeButton?.addTarget(self, action: #selector(JBImageBrowserViewController.activeButtonClicked), for: .touchUpInside) view.addSubview(activeButton!) } //MARK - UI configure func configureUserInterface(){ for i in 0..<imageList.count{ let item = imageList[i] let zoomScrollView = self.zoomScrollView(i) pageScrollView.addSubview(zoomScrollView) switch(item.sourceType){ case .filePath: if let filePathURL = item.filePathURL { guard filePathURL.isFileURL else{ continue } if let image = UIImage(contentsOfFile:filePathURL.path) { let imageView = imageViewForZoomScrollView(image) zoomScrollView.addSubview(imageView) } } case .image: if let image = item.image { let imageView = imageViewForZoomScrollView(image) zoomScrollView.addSubview(imageView) } case .url: if let url = item.imageURL{ //loading let loadingView = UIActivityIndicatorView(activityIndicatorStyle:.white) loadingView.center = CGPoint(x: zoomScrollView.bounds.width/2, y:zoomScrollView.bounds.height/2) zoomScrollView.addSubview(loadingView) loadingView.startAnimating() let imageView = imageViewForZoomScrollView(url, progressBlock: { (receivedSize, totalSize) -> () in }, completionHandler: { (image, error, cacheType, imageURL) -> () in loadingView.stopAnimating() loadingView.removeFromSuperview() }) zoomScrollView.addSubview(imageView) } } } } //MARK: - Tap gesture recognizer selector func handleZoomScrollViewTap(_ gestureRecognizer:UITapGestureRecognizer){ self.dismiss(animated: true, completion: nil) } func handleZoomScrollViewDoubleTap(_ gestureRecognizer:UITapGestureRecognizer){ if let scrollView = gestureRecognizer.view as? UIScrollView { if let imageView = scrollView.subviews.first as? UIImageView { var zoomScale:CGFloat = doubleTapZoomScale if scrollView.zoomScale != defaultZoomScale { zoomScale = 1.0 scrollView.setZoomScale(zoomScale, animated: true) }else{ let xWidth = scrollView.bounds.width/zoomScale let yHeight = scrollView.bounds.height/zoomScale let x:CGFloat = gestureRecognizer.location(in: imageView).x-xWidth/2 let y:CGFloat = gestureRecognizer.location(in: imageView).y-yHeight/2 scrollView.zoom(to: CGRect(origin: CGPoint(x: x,y: y), size: CGSize(width: xWidth, height: yHeight)), animated: true) } } } } func handleZoomScrollViewPanGestureRecognizer(_ panGestureRecognizer:UIPanGestureRecognizer){ if let scrollView = panGestureRecognizer.view as? UIScrollView { if scrollView.zoomScale == defaultZoomScale { if let imageView = scrollView.subviews.first { let yImageView = imageView.frame.minY let heightImageView = imageView.frame.height let contentOffsetY = scrollView.contentOffset.y switch panGestureRecognizer.state { case .began:break case .changed: //根据imageView移动的距离,设置透明 let yOffset = -panGestureRecognizer.translation(in: scrollView).y scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: yOffset) var alpha = 1-abs(contentOffsetY)/(heightImageView+yImageView) if alpha<0.5{ alpha = 0.5 } self.pageScrollView.backgroundColor = UIColor.black.withAlphaComponent(alpha) //获取移动的最大值。记录最大值的目的是判断,移动结束后的offset跟最大值相比,如果小于最大值,则表示是当前要重置回原位 if abs(yOffset) > self.translationMaxValue{ self.translationMaxValue = abs(yOffset) } case .ended: //获取到imageView将要离开屏幕的方向,是上方消失,还是下方。然后设置相应的渐隐动画 var animationToContentOffsetY:CGFloat = 0 //如果image有一半已经移出界面,则移出界面,或者滑动的速度大于50 let yVelocity = panGestureRecognizer.velocity(in: scrollView).y //需要判断,移动结束后的offset跟最大值相比,如果小于最大值,则表示是当前要重置回原位 if heightImageView/2+yImageView<abs(contentOffsetY) || abs(yVelocity)>100&&self.translationMaxValue<=abs(contentOffsetY) { if contentOffsetY<0 { animationToContentOffsetY = -(heightImageView+yImageView) }else{ animationToContentOffsetY = heightImageView+yImageView } } UIView.animate(withDuration: defaultAnimationDuration, animations: { () -> Void in scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: animationToContentOffsetY) let backgroundColorAlpha:CGFloat = animationToContentOffsetY == 0 ? 1 :0 self.pageScrollView.backgroundColor = UIColor.black.withAlphaComponent(backgroundColorAlpha) }, completion: { [weak self] (finished) -> Void in if animationToContentOffsetY != 0 { self?.dismiss(animated: false, completion: nil) } }) default: break } } } } } //MARK: - Target - Action func activeButtonClicked(){ if let image = self.currentScollViewImage() { let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil) self.present(activityVC, animated: true, completion: nil) } } //MARK: - Func fileprivate func currentScollViewImage() -> UIImage?{ if let currentScrollView = pageScrollView.subviews[currentPageIndex] as? UIScrollView { if let currentImageView = currentScrollView.subviews[0] as? UIImageView { if let currentImage = currentImageView.image { return currentImage } } } return nil } } //MARK: - setup zoomScrollView and imageView extension JBImageBrowserViewController{ //生成zoomScrollView fileprivate func zoomScrollView(_ index:Int) -> UIScrollView{ let frame = CGRect(origin: CGPoint(x: CGFloat(index)*self.pageScrollView.bounds.width, y: 0), size: self.pageScrollView.bounds.size) let zoomScrollView = UIScrollView(frame: frame) zoomScrollView.contentSize = frame.size zoomScrollView.showsHorizontalScrollIndicator = false zoomScrollView.showsVerticalScrollIndicator = false zoomScrollView.bouncesZoom = true zoomScrollView.minimumZoomScale = defaultZoomScale zoomScrollView.maximumZoomScale = maxZoomScale zoomScrollView.delegate = self //点击,显示,隐藏close按钮 let zoomScrollViewTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(JBImageBrowserViewController.handleZoomScrollViewTap(_:))) zoomScrollView.addGestureRecognizer(zoomScrollViewTapGestureRecognizer) //双击缩放 let zoomScrollViewDoubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(JBImageBrowserViewController.handleZoomScrollViewDoubleTap(_:))) zoomScrollViewDoubleTapGestureRecognizer.numberOfTapsRequired = 2 zoomScrollViewDoubleTapGestureRecognizer.numberOfTouchesRequired = 1 zoomScrollView.addGestureRecognizer(zoomScrollViewDoubleTapGestureRecognizer) //pan手势,滑动消失 let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(JBImageBrowserViewController.handleZoomScrollViewPanGestureRecognizer(_:))) panGestureRecognizer.delegate = self panGestureRecognizer.maximumNumberOfTouches = 1 zoomScrollView.addGestureRecognizer(panGestureRecognizer) zoomScrollViewTapGestureRecognizer.require(toFail: zoomScrollViewDoubleTapGestureRecognizer) zoomScrollViewTapGestureRecognizer.require(toFail: panGestureRecognizer) return zoomScrollView } //根据image,自动设置,生成UIImage,并设置好了Frame fileprivate func imageViewForZoomScrollView(_ image:UIImage) -> UIImageView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit //设置imageView的frame,呈现在屏幕中间 imageView.frame = imageViewFrameForZoomScrollView(image) imageView.image = image return imageView } fileprivate func imageViewForZoomScrollView(_ url:URL,progressBlock:DownloadProgressBlock,completionHandler:@escaping CompletionHandler) -> UIImageView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.kf.setImage(with: ImageResource.init(downloadURL: url), placeholder: nil, options: nil, progressBlock: nil) { [weak self,weak imageView] (image, error, cacheType, imageURL) in if let imageView = imageView { if image == nil { imageView.image = self?.failedPlaceholderImage } imageView.frame = (self?.imageViewFrameForZoomScrollView(imageView.image))! completionHandler(image,error,cacheType,imageURL) } } return imageView } //根据image的大小,获取imageView在ZoomScrollView的适合的大小 fileprivate func imageViewFrameForZoomScrollView(_ image:UIImage?)->CGRect{ if let image = image { let xScale:CGFloat = self.pageScrollView.bounds.width/image.size.width let yScale:CGFloat = self.pageScrollView.bounds.height/image.size.height let minScale = min(min(1.0, xScale),yScale) //get new image size let imageWidth = image.size.width*minScale let imageHeight = image.size.height*minScale //设置imageView的frame,呈现在屏幕中间 return CGRect(origin: CGPoint(x:(self.pageScrollView.bounds.width-imageWidth)/2,y:(self.pageScrollView.bounds.height-imageHeight)/2), size: CGSize(width: imageWidth, height: imageHeight)) }else { return CGRect.zero } } } //MARK: - ImageBrowserVC extesion for scrollViewDelegate extension JBImageBrowserViewController:UIScrollViewDelegate{ //返回需要缩放的View public func viewForZooming(in scrollView: UIScrollView) -> UIView? { if scrollView != self.pageScrollView { return scrollView.subviews.first } return nil } //缩放后,重置Frame public func scrollViewDidZoom(_ scrollView: UIScrollView) { //获取到当前页面的图片 if scrollView != self.pageScrollView { if let imageView = scrollView.subviews.first { let scrollBoundsSize = scrollView.bounds.size var imageViewFrame = imageView.frame //如果imageView的宽高小于scrollView的bounds,则继续将Frame置于中间。如果大于,在保持PointZero的位置即可。 if imageViewFrame.size.width < scrollBoundsSize.width{ imageViewFrame.origin.x = CGFloat(floor((scrollBoundsSize.width-imageViewFrame.width)/2.0)) }else { imageViewFrame.origin.x = 0 } if imageViewFrame.size.height < scrollBoundsSize.height{ imageViewFrame.origin.y = CGFloat(floor((scrollBoundsSize.height-imageViewFrame.height)/2.0)) }else{ imageViewFrame.origin.y = 0 } if !imageView.frame.equalTo(imageViewFrame){ imageView.frame = imageViewFrame } } }else{ //如果是pageScrollView,则判断当前页面的Image是否已加载,已加载,则允许进行分享 activeButton?.isEnabled = false if let _ = self.currentScollViewImage() { activeButton?.isEnabled = true } } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.pageScrollView { //如果scrollView去往新的页面了,则重置scrollView的缩放 let newPageIndex = Int(scrollView.contentOffset.x/scrollView.bounds.width) if newPageIndex != currentPageIndex { if let subScrollView = scrollView.subviews[currentPageIndex] as? UIScrollView { if subScrollView.zoomScale != defaultZoomScale { subScrollView.zoomScale = defaultZoomScale } } } currentPageIndex = newPageIndex } } } //MARK - GestureRecognizerDelegate extension JBImageBrowserViewController:UIGestureRecognizerDelegate{ //手势是否确认启动 public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { //这里,我们只取Pan的手势,因为scrollView自己还有手势 if gestureRecognizer.isMember(of: UIPanGestureRecognizer.self){ if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { //只有没有缩放的情况下,才可以接收上下滑动 if let scrollView = gestureRecognizer.view as? UIScrollView { if scrollView.zoomScale == defaultZoomScale{ let velocity = panGestureRecognizer.velocity(in: scrollView) //只接受Y轴的滑动,不接受X轴的 return fabs(velocity.y) > fabs(velocity.x) }else{ return false } } } } return true } }
mit
1fd5f7319dffdfb331092a82edff759a
38.795309
274
0.581976
5.887697
false
false
false
false
RobotRebels/SwiftLessons
students_trashspace/pnaumov/Ticket2.playground/Contents.swift
1
2001
//: Playground - noun: a place where people can play import UIKit enum Books: String { case Swift = "Swift. Основы разработки приложений под iOS и macOS" case Java = "Java SE 8. Базовый курс" case Python = "Простой Python. Современный стиль программирования" } struct Library { public var moscowBooks: Books init(republicBooks: Books) { self.moscowBooks = republicBooks } public func searchOfresults() { switch moscowBooks { case .Python: print("Результат поиска: '\(moscowBooks.rawValue)'") case .Java: print("Результат поиска: '\(moscowBooks.rawValue)'") case .Swift: print("Результат поиска: '\(moscowBooks.rawValue)'") } } } var newLibraryBook: Library = Library(republicBooks: .Python) newLibraryBook.searchOfresults() //1. Создать перечисление с rawValue типом – String и тремя значниями. //2. Создать структуру с публичным свойством типа созданного перечисления. Так же //структура должна иметь один конструктор с одним аргументом типа созданного //перечисления. //3. Помимо этого структура должна иметь публичный метод, который исполняет //различные блоки кода в зависимости от установленного в свойстве значения //перечисления (подсазака: switch). //4. Создать экземпляр структуры и продемонстрировать вызов различных блоков кода //для различных значений перечисления.
mit
c9b977773c83050183dc9955804ddf03
29.020833
82
0.69535
2.803502
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/Foundation.swift
1
11042
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import CoreGraphics //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // These conformances should be located in the `ObjectiveC` module, but they can't // be placed there because string bridging is not available there. extension NSObject : CustomStringConvertible {} extension NSObject : CustomDebugStringConvertible {} public let NSNotFound: Int = .max //===----------------------------------------------------------------------===// // NSLocalizedString //===----------------------------------------------------------------------===// /// Returns the localized version of a string. /// /// - parameter key: An identifying value used to reference a localized string. /// Don't use the empty string as a key. Values keyed by the empty string will /// not be localized. /// - parameter tableName: The name of the table containing the localized string /// identified by `key`. This is the prefix of the strings file—a file with /// the `.strings` extension—containing the localized values. If `tableName` /// is `nil` or the empty string, the `Localizable` table is used. /// - parameter bundle: The bundle containing the table's strings file. The main /// bundle is used by default. /// - parameter value: A user-visible string to return when the localized string /// for `key` cannot be found in the table. If `value` is the empty string, /// `key` would be returned instead. /// - parameter comment: A note to the translator describing the context where /// the localized string is presented to the user. /// /// - returns: A localized version of the string designated by `key` in the /// table identified by `tableName`. If the localized string for `key` cannot /// be found within the table, `value` is returned. However, `key` is returned /// instead when `value` is the empty string. /// /// Export Localizations with Xcode /// ------------------------------- /// /// Xcode can read through a project's code to find invocations of /// `NSLocalizedString(_:tableName:bundle:value:comment:)` and automatically /// generate the appropriate strings files for the project's base localization. /// /// In Xcode, open the project file and, in the `Edit` menu, select /// `Export for Localization`. This will generate an XLIFF bundle containing /// strings files derived from your code along with other localizable assets. /// `xcodebuild` can also be used to generate the localization bundle from the /// command line with the `exportLocalizations` option. /// /// xcodebuild -exportLocalizations -project <projectname>.xcodeproj \ /// -localizationPath <path> /// /// These bundles can be sent to translators for localization, and then /// reimported into your Xcode project. In Xcode, open the project file. In the /// `Edit` menu, select `Import Localizations...`, and select the XLIFF /// folder to import. You can also use `xcodebuild` to import localizations with /// the `importLocalizations` option. /// /// xcodebuild -importLocalizations -project <projectname>.xcodeproj \ /// -localizationPath <path> /// /// Choose Meaningful Keys /// ---------------------- /// /// Words can often have multiple different meanings depending on the context /// in which they're used. For example, the word "Book" can be used as a noun—a /// printed literary work—and it can be used as a verb—the action of making a /// reservation. Words with different meanings which share the same spelling are /// heteronyms. /// /// Different languages often have different heteronyms. "Book" in English is /// one such heteronym, but that's not so in French, where the noun translates /// to "Livre", and the verb translates to "Réserver". For this reason, it's /// important make sure that each use of the same phrase is translated /// appropriately for its context by assigning unique keys to each phrase and /// adding a description comment describing how that phrase is used. /// /// NSLocalizedString("book-tag-title", value: "Book", comment: """ /// noun: A label attached to literary items in the library. /// """) /// /// NSLocalizedString("book-button-title", value: "Book", comment: """ /// verb: Title of the button that makes a reservation. /// """) /// /// Use Only String Literals /// ------------------------ /// /// String literal values must be used with `key`, `tableName`, `value`, and /// `comment`. /// /// Xcode does not evaluate interpolated strings and string variables when /// generating strings files from code. Attempting to localize a string using /// those language features will cause Xcode to export something that resembles /// the original code expression instead of its expected value at runtime. /// Translators would then translate that exported value—leaving /// international users with a localized string containing code. /// /// // Translators will see "1 + 1 = (1 + 1)". /// // International users will see a localization "1 + 1 = (1 + 1)". /// let localizedString = NSLocalizedString("string-interpolation", /// value: "1 + 1 = \(1 + 1)" /// comment: "A math equation.") /// /// To dynamically insert values within localized strings, set `value` to a /// format string, and use `String.localizedStringWithFormat(_:_:)` to insert /// those values. /// /// // Translators will see "1 + 1 = %d" (they know what "%d" means). /// // International users will see a localization of "1 + 1 = 2". /// let format = NSLocalizedString("string-literal", /// value: "1 + 1 = %d", /// comment: "A math equation.") /// let localizedString = String.localizedStringWithFormat(format, (1 + 1)) /// /// Multiline string literals are technically supported, but will result in /// unexpected behavior during internationalization. A newline will be inserted /// before and after the body of text within the string, and translators will /// likely preserve those in their internationalizations. /// /// To preserve some of the aesthetics of having newlines in the string mirrored /// in their code representation, string literal concatenation with the `+` /// operator can be used. /// /// NSLocalizedString("multiline-string-literal", /// value: """ /// This multiline string literal won't work as expected. /// An extra newline is added to the beginning and end of the string. /// """, /// comment: "The description of a sample of code.") /// /// NSLocalizedString("string-literal-contatenation", /// value: "This string literal concatenated with" /// + "this other string literal works just fine.", /// comment: "The description of a sample of code.") /// /// Since comments aren't localized, multiline string literals can be safely /// used with `comment`. /// /// Work with Manually Managed Strings /// ---------------------------------- /// /// If having Xcode generate strings files from code isn't desired behavior, /// call `Bundle.localizedString(forKey:value:table:)` instead. /// /// let greeting = Bundle.localizedString(forKey: "program-greeting", /// value: "Hello, World!", /// table: "Localization") /// /// However, this requires the manual creation and management of that table's /// strings file. /// /// /* Localization.strings */ /// /// /* A friendly greeting to the user when the program starts. */ /// "program-greeting" = "Hello, World!"; /// /// - note: Although `NSLocalizedString(_:tableName:bundle:value:comment:)` /// and `Bundle.localizedString(forKey:value:table:)` can be used in a project /// at the same time, data from manually managed strings files will be /// overwritten by Xcode when their table is also used to look up localized /// strings with `NSLocalizedString(_:tableName:bundle:value:comment:)`. public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value:value, table:tableName) } //===----------------------------------------------------------------------===// // NSLog //===----------------------------------------------------------------------===// public func NSLog(_ format: String, _ args: CVarArg...) { withVaList(args) { NSLogv(format, $0) } } //===----------------------------------------------------------------------===// // AnyHashable //===----------------------------------------------------------------------===// extension AnyHashable : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSObject { // This is unprincipled, but pretty much any object we'll encounter in // Swift is NSObject-conforming enough to have -hash and -isEqual:. return unsafeBitCast(base as AnyObject, to: NSObject.self) } public static func _forceBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) { result = AnyHashable(x) } public static func _conditionallyBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC( _ source: NSObject? ) -> AnyHashable { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty string. if _slowPath(source == nil) { return AnyHashable(String()) } return AnyHashable(source!) } } //===----------------------------------------------------------------------===// // CVarArg for bridged types //===----------------------------------------------------------------------===// extension CVarArg where Self: _ObjectiveCBridgeable { /// Default implementation for bridgeable types. public var _cVarArgEncoding: [Int] { let object = self._bridgeToObjectiveC() _autorelease(object) return _encodeBitsAsWords(object) } }
apache-2.0
4da25c7199db53e686d0bafbb8a90c60
44.016327
82
0.605948
4.963546
false
false
false
false
Ryukie/Ryubo
Ryubo/Ryubo/Classes/View/Home/Cell/RYBottomView.swift
1
4098
// // RYBottomView.swift // Ryubo // // Created by 王荣庆 on 16/2/18. // Copyright © 2016年 Ryukie. All rights reserved. // import UIKit class RYBottomView: UIView { //找到自定义的入口 override init(frame: CGRect) { super.init(frame: frame) setupUI() setClickEvents() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 懒加载子视图 //转发微博的按钮 private lazy var bt_retweeted: UIButton = UIButton(backgroundImageName: nil , titleText: "转发", textFont: 10, textColor: col_darkGray, imageName: "timeline_icon_retweet") // 评论 private lazy var bt_comment: UIButton = UIButton(backgroundImageName: nil, titleText: "评论", textFont: 10, textColor: col_darkGray, imageName: "timeline_icon_comment") //点赞 private lazy var bt_like: UIButton = UIButton(backgroundImageName: nil , titleText: "赞", textFont: 10, textColor: col_darkGray, imageName: "timeline_icon_unlike") // MARK: - 配置点击事件 private func setClickEvents () { bt_comment.addTarget(self, action: "clickBtComment", forControlEvents: .TouchUpInside) bt_like.addTarget(self, action: "clickBtLike", forControlEvents: .TouchUpInside) bt_retweeted.addTarget(self, action: "clickBtRetweet", forControlEvents: .TouchUpInside) } @objc private func clickBtComment () { //需要获取到当前的导航控制器来执行点击按钮跳转 //可以通过闭包/通知/代理等方法实现 //这里通过遍历响应者链条来获取navi //这种方式用的很多可以代替很多情况下的协议代理 let vc = RYCommentVC() //在push之前隐藏底部导航栏 // vc.hidesBottomBarWhenPushed = true getNaviFromResponderChain()?.pushViewController(vc, animated: true) } @objc private func clickBtRetweet () { let vc = RYRetweetVC() // vc.hidesBottomBarWhenPushed = true getNaviFromResponderChain()?.pushViewController(vc, animated: true) } @objc private func clickBtLike () { print("I`m lovin it!") } } //======================================================== // MARK: - 自动布局子控件 extension RYBottomView { //MARK: 设置视图 private func setupUI() { backgroundColor = col_white addSubview(bt_retweeted) addSubview(bt_like) addSubview(bt_comment) bt_retweeted.snp_makeConstraints { (make) -> Void in make.left.top.bottom.equalTo(self) } bt_comment.snp_makeConstraints { (make) -> Void in make.left.equalTo(bt_retweeted.snp_right) make.bottom.top.equalTo(self) make.width.equalTo(bt_retweeted.snp_width) } bt_like.snp_makeConstraints { (make) -> Void in make.left.equalTo(bt_comment.snp_right) make.bottom.top.equalTo(self) make.right.equalTo(self.snp_right) make.width.equalTo(bt_comment.snp_width) } addSeparateLineView() } // MARK: - 设置两条分割线 private func addSeparateLineView () { let lineA = getSeparateLineView() let lineB = getSeparateLineView() addSubview(lineA) addSubview(lineB) let w: CGFloat = 0.5 let scale: CGFloat = 0.4 lineA.snp_makeConstraints { (make) -> Void in make.left.equalTo(bt_retweeted.snp_right) make.centerY.equalTo(self.snp_centerY) make.height.equalTo(self.snp_height).multipliedBy(scale) make.width.equalTo(w) } lineB.snp_makeConstraints { (make) -> Void in make.left.equalTo(bt_comment.snp_right) make.centerY.equalTo(self.snp_centerY) make.height.equalTo(self.snp_height).multipliedBy(scale) make.width.equalTo(w) } } private func getSeparateLineView () -> UIView { let line = UIView() line.backgroundColor = col_lightGray return line } }
mit
426f2b1d2c7a9faae35593d914ada132
35.333333
173
0.622543
3.982255
false
false
false
false
Harry-L/5-3-1
PlateMath/PlateMath/Plates.swift
1
1214
// // Plates.swift // PlateMath // // Created by Harry Liu on 2016-01-18. // Copyright © 2016 HarryLiu. All rights reserved. // import UIKit class Plates: NSObject { func doTheMath(weight weight: Int, bar: Int, collar: Int, five: Int, ten: Int, twentyFive: Int, thirtyFive: Int, fortyFive: Int) -> [Int] { var plates:[Int] = [fortyFive / 2, thirtyFive / 2, twentyFive / 2, ten / 2, five / 2] let plateValues = [45, 35, 25, 10, 5] var setup = [0, 0, 0, 0, 0] var currentWeight = weight currentWeight -= bar currentWeight -= 2 * collar if (currentWeight < 0) { print("Your bar and collars are too heavy") } for (index, plate) in plateValues.enumerate() { while(currentWeight >= (2 * plate) && plates[index] >= 0) { currentWeight -= 2 * plate plates[index] -= 1 setup[index]++ } } if (currentWeight > 5) { print("You don't have enough plates") print(setup) } else { print(setup) } return setup } }
mit
6b6b831b4417d6314717f268a0325809
25.369565
143
0.493817
3.875399
false
false
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/Views/ACBorderedTextField.swift
1
1769
// // ACBorderedTextField.swift // GoWWorldBosses // // Created by Austin Chen on 2016-12-20. // Copyright © 2016 Austin Chen. All rights reserved. // import UIKit @IBDesignable class ACBorderedTextField: UITextField { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } // @IBInspectable UIEdgeInsets is not supported yet, so workaround like below @IBInspectable var textInsets: CGRect = CGRect() // placeholder position override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: textInsets.origin.y, dy: textInsets.size.height); } // text position override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: textInsets.origin.y, dy: textInsets.size.height); } @IBInspectable var placeholderFontColor: UIColor? @IBInspectable var placeholderFontSize: CGFloat = 0 // MARK: life cycle override func layoutSubviews() { super.layoutSubviews() if let ph = self.placeholder, let phc = placeholderFontColor { self.attributedPlaceholder = NSAttributedString(string: ph, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: placeholderFontSize, weight: UIFontWeightRegular), NSForegroundColorAttributeName: phc]) } } }
mit
27809a0f08d901db86f24512693a2631
28.966102
115
0.638575
5.109827
false
false
false
false
uias/Pageboy
Sources/Pageboy/Utilities/WeakContainer.swift
1
483
// // WeakContainer.swift // Pageboy iOS // // Created by Merrick Sapsford on 02/03/2019. // Copyright © 2019 UI At Six. All rights reserved. // import Foundation internal final class WeakWrapper<T: AnyObject> { private(set) weak var object: T? init(_ object: T) { self.object = object } } extension WeakWrapper: Equatable { static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool { return lhs.object === rhs.object } }
mit
1b2728f3bd7bac48b6d841475e2ac69e
18.28
65
0.622407
3.795276
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/Widgets/PhotonActionSheetAnimator.swift
4
3709
/* 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 class PhotonActionSheetAnimator: NSObject, UIViewControllerAnimatedTransitioning { var presenting: Bool = false let animationDuration = 0.4 lazy var shadow: UIView = { let shadow = UIView() shadow.backgroundColor = UIColor(white: 0, alpha: 0.5) return shadow }() func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let screens = (from: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, to: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!) guard let actionSheet = (self.presenting ? screens.to : screens.from) as? PhotonActionSheet else { return } let bottomViewController = (self.presenting ? screens.from : screens.to) as UIViewController animateWitVC(actionSheet, presentingVC: bottomViewController, transitionContext: transitionContext) } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return animationDuration } } extension PhotonActionSheetAnimator: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } } extension PhotonActionSheetAnimator { fileprivate func animateWitVC(_ actionSheet: PhotonActionSheet, presentingVC viewController: UIViewController, transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView if presenting { shadow.frame = containerView.bounds containerView.addSubview(shadow) actionSheet.view.frame = CGRect(origin: CGPoint(x: 0, y: containerView.frame.size.height), size: containerView.frame.size) self.shadow.alpha = 0 containerView.addSubview(actionSheet.view) actionSheet.view.layoutIfNeeded() UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: [], animations: { () -> Void in self.shadow.alpha = 1 actionSheet.view.frame = containerView.bounds actionSheet.view.layoutIfNeeded() }, completion: { (completed) -> Void in transitionContext.completeTransition(completed) }) } else { UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1.2, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in self.shadow.alpha = 0 actionSheet.view.frame = CGRect(origin: CGPoint(x: 0, y: containerView.frame.size.height), size: containerView.frame.size) actionSheet.view.layoutIfNeeded() }, completion: { (completed) -> Void in actionSheet.view.removeFromSuperview() self.shadow.removeFromSuperview() transitionContext.completeTransition(completed) }) } } }
mpl-2.0
256ab2fe8b775038e8892152ca49a4a0
45.949367
202
0.682664
5.795313
false
false
false
false
Legoless/Analytical
Analytical/Classes/Provider/FirebaseProvider.swift
1
9066
// // FirebaseProvider.swift // Analytical // // Created by Dal Rupnik on 30/05/17. // Copyright © 2017 Unified Sense. All rights reserved. // import Analytical import Firebase public enum FirebaseProperties : String { case customOne case creativeName case creativeSlot case groupId case index case locationId case numberOfNights case numberOfPassengers case numberOfRooms case travelClass } public class FirebaseProvider : BaseProvider<Firebase.Analytics>, AnalyticalProvider { public static let GoogleAppId = "GoogleAppIdKey" public static let BundleId = "BundleIdKey" public static let GCMSenderId = "GCMSenderID" public func setup(with properties: Properties?) { guard let googleAppId = properties?[FirebaseProvider.GoogleAppId] as? String, let gcmSenderId = properties?[FirebaseProvider.GCMSenderId] as? String else { return } let options = FirebaseOptions(googleAppID: googleAppId, gcmSenderID: gcmSenderId) if let bundleId = properties?[FirebaseProvider.BundleId] as? String { options.bundleID = bundleId } FirebaseApp.configure(options: options) } public override func event(_ event: AnalyticalEvent) { guard let event = update(event: event) else { return } switch event.type { case .default, .purchase: Analytics.logEvent(event.name, parameters: mergeGlobal(properties: event.properties, overwrite: true)) case .screen: Analytics.setScreenName(event.name, screenClass: nil) case .finishTime: super.event(event) Analytics.logEvent(event.name, parameters: mergeGlobal(properties: event.properties, overwrite: true)) default: super.event(event) } delegate?.analyticalProviderDidSendEvent(self, event: event) } public func flush() { } public func reset() { } public override func activate() { Analytics.logEvent(AnalyticsEventAppOpen, parameters: [:]) } public func identify(userId: String, properties: Properties?) { Analytics.setUserID(userId) if let properties = properties { set(properties: properties) } } public func alias(userId: String, forId: String) { } public func set(properties: Properties) { let properties = prepare(properties: properties)! for (property, value) in properties { if let value = value as? String { Analytics.setUserProperty(value, forName: property) } else { Analytics.setUserProperty(String(describing: value), forName: property) } } } public func increment(property: String, by number: NSDecimalNumber) { } public override func update(event: AnalyticalEvent) -> AnalyticalEvent? { // // Ensure Super gets a chance to update event. // guard var event = super.update(event: event) else { return nil } // // Update event name and properties based on Facebook's values // if let defaultName = DefaultEvent(rawValue: event.name), let updatedName = parse(name: defaultName) { event.name = updatedName } event.properties = prepare(properties: mergeGlobal(properties: event.properties, overwrite: true)) return event } // // MARK: Private Methods // private func parse(name: DefaultEvent) -> String? { switch name { case .addedPaymentInfo: return AnalyticsEventAddPaymentInfo case .addedToWishlist: return AnalyticsEventAddToWishlist case .completedTutorial: return AnalyticsEventTutorialComplete case .addedToCart: return AnalyticsEventAddToCart case .viewContent: return AnalyticsEventSelectContent case .initiatedCheckout: return AnalyticsEventBeginCheckout case .campaignEvent: return AnalyticsEventCampaignDetails case .checkoutProgress: return AnalyticsEventCheckoutProgress case .earnCredits: return AnalyticsEventEarnVirtualCurrency case .purchase: return AnalyticsEventEcommercePurchase case .joinGroup: return AnalyticsEventJoinGroup case .generateLead: return AnalyticsEventGenerateLead case .levelUp: return AnalyticsEventLevelUp case .signUp: return AnalyticsEventLogin case .postScore: return AnalyticsEventPostScore case .presentOffer: return AnalyticsEventPresentOffer case .refund: return AnalyticsEventPurchaseRefund case .removeFromCart: return AnalyticsEventRemoveFromCart case .search: return AnalyticsEventSearch case .checkoutOption: return AnalyticsEventSetCheckoutOption case .share: return AnalyticsEventShare case .completedRegistration: return AnalyticsEventSignUp case .spendCredits: return AnalyticsEventSpendVirtualCurrency case .beginTutorial: return AnalyticsEventTutorialBegin case .unlockedAchievement: return AnalyticsEventUnlockAchievement case .viewItem: return AnalyticsEventViewItem case .viewItemList: return AnalyticsParameterItemList case .searchResults: return AnalyticsEventViewSearchResults default: return nil } } private func prepare(properties: Properties?) -> Properties? { guard let properties = properties else { return nil } var finalProperties : Properties = properties for (property, value) in properties { let property = parse(property: property) if let parsed = parse(value: value) { finalProperties[property] = parsed } } return finalProperties } private func parse(property: String) -> String { switch property { case Property.Purchase.quantity.rawValue: return AnalyticsParameterQuantity case Property.Purchase.item.rawValue: return AnalyticsParameterItemName case Property.Purchase.sku.rawValue: return AnalyticsParameterItemID case Property.Purchase.category.rawValue: return AnalyticsParameterItemCategory case Property.Purchase.source.rawValue: return AnalyticsParameterItemLocationID case Property.Purchase.price.rawValue: return AnalyticsParameterValue case Property.Purchase.currency.rawValue: return AnalyticsParameterCurrency case Property.Location.origin.rawValue: return AnalyticsParameterOrigin case Property.Location.destination.rawValue: return AnalyticsParameterDestination case Property.startDate.rawValue: return AnalyticsParameterStartDate case Property.endDate.rawValue: return AnalyticsParameterEndDate case Property.Purchase.medium.rawValue: return AnalyticsParameterMedium case Property.Purchase.campaign.rawValue: return AnalyticsParameterCampaign case Property.term.rawValue: return AnalyticsParameterTerm case Property.Content.identifier.rawValue: return AnalyticsParameterContent case Property.User.registrationMethod.rawValue: return AnalyticsParameterSignUpMethod default: return property } } private func parse(value: Any) -> Any? { if let string = value as? String { if string.count > 35 { let maxTextSize = string.index(string.startIndex, offsetBy: 35) let substring = string[..<maxTextSize] return String(substring) } return value } if let number = value as? Int { return NSNumber(value: number) } if let number = value as? UInt { return NSNumber(value: number) } if let number = value as? Bool { return NSNumber(value: number) } if let number = value as? Float { return NSNumber(value: number) } if let number = value as? Double { return NSNumber(value: number) } return nil } }
mit
f9184f59f32fe958f30277a2f8547f1d
30.151203
163
0.604302
5.647975
false
false
false
false
briancroom/XcodeUITestingExperiments
Swift/NetworkStubbingExperiment/NetworkStubbingExperiment/ViewController.swift
1
1400
import UIKit class ViewController: UIViewController { let session = NSURLSession.sharedSession() @IBOutlet var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let task = session.dataTaskWithURL(URLWithPath("hello")) { data, _, _ in guard let data = data, string = NSString(data: data, encoding: NSUTF8StringEncoding) else { return } dispatch_async(dispatch_get_main_queue()) { self.label.text = string as String } } task.resume() } @IBAction func checkInTapped() { let request = NSMutableURLRequest(URL: URLWithPath("checkin")) request.HTTPMethod = "POST" request.HTTPBody = "Checking in".dataUsingEncoding(NSUTF8StringEncoding) session.dataTaskWithRequest(request).resume() } private func URLWithPath(path: String) -> NSURL { let baseURLString = NSProcessInfo.processInfo().environment[kServerURLEnvironmentKey] ?? "http://mycoolwebservice.com" return NSURL(string: path, relativeToURL: NSURL(string: baseURLString))! } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
mit
0ab9259839b0231045a92ee77661d9aa
30.818182
127
0.66
5.072464
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00788-t.swift
11
705
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse init(A.Element == A<T.Type) { let end = { c<e)) { protocol C { } print(x) { c } } class B == [[B, a(g()) (m(t: B<T>(Any, ") } class C> : A? = { self.Element>? { }([0x31] == b<d for c { } } } protocol a { protocol b { () { return self.A"a: H) ->()) } func d.Iterator.Element>(Any, let end = ") typealias h: d == c
apache-2.0
4a4771400717ce51281a410e8d47d2dd
21.741935
78
0.642553
2.889344
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/ReadingList+CoreDataClass.swift
1
3609
import Foundation import CoreData public class ReadingList: NSManagedObject { @objc public static let entriesLimitReachedNotification = NSNotification.Name(rawValue:"WMFEntriesLimitReachedNotification") @objc public static let entriesLimitReachedReadingListKey = "readingList" // Note that this returns articleKey strings that do not take language variant into account. // This allows clients to check if an article of any variant is an entry in the list. // This is intentional. public var articleKeys: [String] { let entries = self.entries ?? [] let existingKeys = entries.compactMap { (entry) -> String? in guard entry.isDeletedLocally == false else { return nil } return entry.articleKey } return existingKeys } private var previousCountOfEntries: Int64 = 0 private var isEntriesLimitReached: Bool = false { didSet { guard isEntriesLimitReached, countOfEntries > previousCountOfEntries else { return } let userInfo: [String: Any] = [ReadingList.entriesLimitReachedReadingListKey: self] NotificationCenter.default.post(name: ReadingList.entriesLimitReachedNotification, object: nil, userInfo: userInfo) } } public func updateArticlesAndEntries() throws { previousCountOfEntries = countOfEntries let previousArticles = articles ?? [] let previousKeys = Set<WMFInMemoryURLKey>(previousArticles.compactMap { $0.inMemoryKey }) let validEntries = (entries ?? []).filter { !$0.isDeletedLocally } let validArticleKeys = Set<WMFInMemoryURLKey>(validEntries.compactMap { $0.inMemoryKey }) for article in previousArticles { guard let key = article.inMemoryKey, validArticleKeys.contains(key) else { removeFromArticles(article) article.readingListsDidChange() continue } } if !validArticleKeys.isEmpty { let articleKeysToAdd = validArticleKeys.subtracting(previousKeys) let articlesToAdd = try managedObjectContext?.fetchArticlesWithInMemoryURLKeys(Array(articleKeysToAdd)) ?? [] countOfEntries = Int64(validEntries.count) for article in articlesToAdd { addToArticles(article) article.readingListsDidChange() } let sortedArticles = articles?.sorted(by: { (a, b) -> Bool in guard let aDate = a.savedDate else { return false } guard let bDate = b.savedDate else { return true } return aDate.compare(bDate) == .orderedDescending }) ?? [] let updatedPreviewArticles = NSMutableOrderedSet() for article in sortedArticles { guard updatedPreviewArticles.count < 4 else { break } guard article.imageURLString != nil || article.thumbnailURLString != nil else { continue } updatedPreviewArticles.add(article) } previewArticles = updatedPreviewArticles } else { countOfEntries = 0 articles = [] previewArticles = [] } if let moc = managedObjectContext { isEntriesLimitReached = countOfEntries >= moc.wmf_readingListsConfigMaxEntriesPerList.int64Value } } }
mit
c57985c2dddbf5f3f8577440c96c7d87
40.965116
128
0.605431
5.65674
false
false
false
false
hellogaojun/Swift-coding
02-常量变量/02-常量变量/main.swift
1
1629
// // main.swift // 02-常量变量 // // Created by gaojun on 16/4/2. // Copyright © 2016年 高军. All rights reserved. // import Foundation /* 输出: C: printf("Hello, World!"); OC:NSLog(@"Hello, World!"); Swift1.2:println("Hello, World!") Swift2.0:print("Hello, World!") */ print("Hello, World!") /* “使用let来声明常量,使用var来声明变量” 变量: OC: >先定义再初始化 int num; num = 10; >定义的同时初始化 int num2 = 20; Swift: >先定义再初始化 var num 报错: 没有指定数据类型(type annotation missing in pattern), 在Swift中如果想要先定义一个变量, 以后使用时再初始化必须在定义时告诉编译器变量的类型(类型标注) */ /* >定义的同时初始化 在Swift中如果定义的同时初始化一个变量,可以不用写数据类型, 编译期会根据初始化的值自动推断出变量的类型(其它语言是没有类型推断的) 以后在开发中如果在定义的同时初始化就没有必要指定数据类型, 除非需要明确数据类型的长度或者定义时不初始化才需要指定数据类型 */ //变量 var value1 :Int value1 = 10 var value2:Float = 34 var value3 = 32 var 变量 = 7 //常量 let value4:Float = 2 let value5 = 4 //下面这种表示错误(定义常量时必须初始化) //let value6 //value6 = 12 //常量: //OC: const int num = 10; //Swift: let num = 10 // //错误: //let num : Int //Swift中的常量必须在定义时初始化(OC可以不初始化), 否则会报错 //常量的用途: 某些值以后不需要改变, 例如身份证 //*/ let 常量 = 9 print(变量,常量)
apache-2.0
8589e5e1359dca1c390526aed922e3e3
12.220779
101
0.687623
2.247241
false
false
false
false
akrio714/Wbm
Wbm/Component/Button/BaseButton.swift
1
2490
// // BaseButton.swift // Wbm // // Created by akrio on 2017/7/10. // Copyright © 2017年 akrio. All rights reserved. // import UIKit import SnapKit @IBDesignable public class BaseButton: UIButton { internal var buttonTheme:UIColor.Theme = .blue @IBInspectable public var theme:Int{ get { return buttonTheme.rawValue } set(newTheme){ self.tintColor = UIColor.white buttonTheme = UIColor.Theme(rawValue: newTheme) ?? .blue initFromXIB() self.setBackgroundImage(UIImage.initWith(color: buttonTheme.color), for: .normal) } } @IBInspectable public var customStyle:Bool { set { self.tintColor = UIColor.white //左侧颜色 let TColor = UIColor.withRGBA(229, 0, 93) //右侧颜色 let BColor = UIColor.withRGBA(245, 65, 4) //将颜色和颜色的位置定义在数组内 let gradientColors: [CGColor] = [TColor.cgColor, BColor.cgColor] //创建并实例化CAGradientLayer let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors //(这里的起始和终止位置就是按照坐标系,四个角分别是左上(0,0),左下(0,1),右上(1,0),右下(1,1)) //渲染的起始位置 gradientLayer.startPoint = CGPoint(x: 0, y: 0) //渲染的终止位置 gradientLayer.endPoint = CGPoint(x: 1, y: 0) //设置frame和插入view的layer gradientLayer.frame = self.bounds self.layer.insertSublayer(gradientLayer, at: 0) } get { return self.customStyle } } override public init(frame: CGRect) { super.init(frame: frame) initFromXIB() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initFromXIB() } func initFromXIB() { setBackgroundImage(UIImage.initWith(color: buttonTheme.color.withAlphaComponent(0.8)) , for: .highlighted) setBackgroundImage(UIImage.initWith(color: UIColor.Theme.background.color), for: .disabled) } }
apache-2.0
11304a5ed2431c81a2ee2be9a9b3f025
25.747126
114
0.529437
4.553816
false
false
false
false
matibot/MBAssetsImporter
MBAssetsImporter/PixabayImporter.swift
1
4351
// // PanoramioImporter.swift // MBAssetsImporter // // Created by Mati Bot on 7/28/15. // Copyright © 2015 Mati Bot. All rights reserved. // import UIKit import Photos import Foundation import CoreLocation class PixabayImporter: Importer { var numberOfPictures : Int var task : URLSessionDataTask? init(numberOfPictures : Int) { self.numberOfPictures = numberOfPictures super.init() } override func start() { if (numberOfPictures <= 2 || numberOfPictures > 200) { delegate?.onError(NSError(domain: "", code: 100, userInfo: [NSLocalizedDescriptionKey:"Please specify a number above 2 and less than 200"])) } else{ delegate?.onProgress(0, filename: "Starting", image: nil) self.shouldContinue = true importPhotos() self.delegate?.onStart() } } override func cancel() { super.cancel() if task?.state == .running { task?.cancel() } } func importPhotos(){ let url = String(format:"https://pixabay.com/api/?key=3693221-0fc116c37dd34558929eed174&per_page=\(numberOfPictures)&image_type=photo") task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in print("Task completed") if let data = data { do { var ret : Dictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! Dictionary<String, AnyObject> let photos = ret["hits"] as! Array<Dictionary<String,AnyObject>> OperationQueue.main.addOperation({ () -> Void in self.importPhotos(photos, index: 0) }) } catch let error as NSError { print(error.localizedDescription) } } else if let error = error { print(error.localizedDescription) } else { self.delegate?.onFinish() } }) task?.resume() } func importPhotos(_ photos:Array<Dictionary<String,AnyObject>>, index:Int){ if(self.shouldContinue == false || index >= photos.count){ self.delegate?.onFinish() return } let photo = photos[index] let photoUrl = photo["userImageURL"] as! String let url = URL(string: photoUrl, relativeTo: nil) if let url = url { let data = try! Data(contentsOf: url) let image = UIImage(data: data)! let title = "Image \(index)" let lat = 1.0 let long = 1.0 let date = Date.init(); //update delegate with progress self.delegate?.onProgress(Float(index+1) / Float(photos.count), filename: title, image:image) PHPhotoLibrary.requestAuthorization { (status : PHAuthorizationStatus) -> Void in PHPhotoLibrary.shared().performChanges({ () -> Void in let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image) creationRequest.location = CLLocation(latitude: lat, longitude: long) creationRequest.creationDate = date }, completionHandler: { (success : Bool, error : Error?) -> Void in if(!success && error != nil){ self.delegate?.onError(error!) } OperationQueue.main.addOperation({ () -> Void in if index + 1 < photos.count { self.importPhotos(photos, index: index + 1) }else{ self.delegate?.onFinish() } }) }) } } else { if index + 1 < photos.count { self.importPhotos(photos, index: index + 1) }else{ self.delegate?.onFinish() } } } }
mit
b085170a76972b1bb23308bccf1b826f
34.365854
177
0.511034
5.160142
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Segment Operations.xcplaygroundpage/Contents.swift
1
1810
//: ## Segment Operations //: ### You can create segments that vary parameters in operations linearly or exponentially over a certain duration. //: ### Here we create an alien apocalypse. //: import XCPlayground import AudioKit let generator = AKOperationGenerator() { parameters in let updateRate = parameters[0] // Vary the starting frequency and duration randomly let start = AKOperation.randomNumberPulse() * 2000 + 300 let duration = AKOperation.randomNumberPulse() let frequency = AKOperation.lineSegment( trigger: AKOperation.metronome(frequency: updateRate), start: start, end: 0, duration: duration) // Decrease the amplitude exponentially let amplitude = AKOperation.exponentialSegment( trigger: AKOperation.metronome(frequency: updateRate), start: 0.3, end: 0.01, duration: 1.0 / updateRate) return AKOperation.sineWave(frequency: frequency, amplitude: amplitude) } var delay = AKDelay(generator) //: Add some effects for good fun delay.time = 0.125 delay.feedback = 0.8 var reverb = AKReverb(delay) reverb.loadFactoryPreset(.LargeHall) AudioKit.output = reverb AudioKit.start() generator.parameters = [2.0] generator.start() class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Segment Operations") addSubview(AKPropertySlider( property: "Update Rate", format: "%0.3f Hz", value: generator.parameters[0], minimum: 0.1, maximum: 10, color: AKColor.redColor() ) { rate in generator.parameters[0] = rate delay.time = 0.25 / rate }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
f134aafb4be1c003b19532e290018482
28.193548
117
0.68011
4.513716
false
false
false
false
dcunited001/Spectra
Example/Tests/S3DXMLSpec.swift
1
11401
// // S3DXMLSpec.swift // Spectra // // Created by David Conner on 10/17/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Foundation import Spectra import Ono import Quick import Nimble import Metal class S3DXMLSpec: QuickSpec { override func spec() { let device = MTLCreateSystemDefaultDevice() let library = device!.newDefaultLibrary() let testBundle = NSBundle(forClass: S3DXMLSpec.self) let xmlData: NSData = S3DXML.readXML(testBundle, filename: "S3DXMLTest") let xml = S3DXML(data: xmlData) var descriptorManager = SpectraDescriptorManager(library: library!) descriptorManager = xml.parse(descriptorManager) describe("SpectraDescriptorManager") { it("parses enumGroups from XSD") { let mtlStoreActionEnum = descriptorManager.mtlEnums["mtlSamplerAddressMode"]! expect(mtlStoreActionEnum.getValue("ClampToEdge")) == 0 } } // describe("S3DXML") { // // } describe("S3DXMLMTLFunctionNode") { let vertName = "basic_color_vertex" let fragName = "basic_color_fragment" let compName = "test_compute_function" it("can parse render and compute functions") { let vert = descriptorManager.vertexFunctions[vertName]! expect(vert.name) == vertName let frag = descriptorManager.fragmentFunctions[fragName]! expect(frag.name) == fragName let comp = descriptorManager.computeFunctions["test_compute_function"]! expect(comp.name) == compName } // it("can parse from references") { // // } } describe("S3DXMLMTLVertexDescriptorNode") { it("can parse the attribute descriptor array") { let vertDesc = descriptorManager.vertexDescriptors["common_vertex_desc"]! expect(vertDesc.attributes[0].format) == MTLVertexFormat.Float4 expect(vertDesc.attributes[1].offset) == 16 } it("can parse the buffer layout descriptor array") { let vertDesc = descriptorManager.vertexDescriptors["common_vertex_desc"]! expect(vertDesc.layouts[0].stepFunction) == MTLVertexStepFunction.PerVertex expect(vertDesc.layouts[0].stride) == 48 expect(vertDesc.layouts[0].stepRate) == 1 } // it("can parse from references") { // let vertDesc = descriptorManager.vertexDescriptors["common_vertex_desc"]! // } } describe("S3DXMLMTLTextureDescriptorNode") { it("can parse a MTLVertexDescriptor") { let desc = descriptorManager.textureDescriptors["texture_desc"]! expect(desc.textureType) == MTLTextureType.Type3D expect(desc.pixelFormat) == MTLPixelFormat.RGBA32Float expect(desc.width) == 100 expect(desc.height) == 100 expect(desc.depth) == 100 expect(desc.mipmapLevelCount) == 100 expect(desc.sampleCount) == 100 expect(desc.arrayLength) == 100 // desc.resourceOptions expect(desc.cpuCacheMode) == MTLCPUCacheMode.WriteCombined expect(desc.storageMode) == MTLStorageMode.Shared // expect(desc.usage) == MTLTextureUsage.PixelFormatView } // it("can parse from references") { // // } } describe("S3DXMLMTLSamplerDescriptorNode") { it("can parse a sampler descriptor") { let desc = descriptorManager.samplerDescriptors["sampler_desc"]! expect(desc.minFilter) == MTLSamplerMinMagFilter.Linear expect(desc.magFilter) == MTLSamplerMinMagFilter.Linear expect(desc.mipFilter) == MTLSamplerMipFilter.Linear expect(desc.maxAnisotropy) == 10 expect(desc.sAddressMode) == MTLSamplerAddressMode.Repeat expect(desc.tAddressMode) == MTLSamplerAddressMode.MirrorRepeat expect(desc.rAddressMode) == MTLSamplerAddressMode.ClampToZero expect(desc.normalizedCoordinates) == false expect(desc.lodMinClamp) == 1.0 expect(desc.lodMaxClamp) == 10.0 expect(desc.lodAverage) == true expect(desc.compareFunction) == MTLCompareFunction.Always } } describe("S3DXMLMTLStencilDescriptorNode") { it("can parse a stencil descriptor") { let desc = descriptorManager.stencilDescriptors["stencil_desc"]! expect(desc.stencilCompareFunction) == MTLCompareFunction.Never expect(desc.stencilFailureOperation) == MTLStencilOperation.Replace expect(desc.depthFailureOperation) == MTLStencilOperation.IncrementWrap expect(desc.depthStencilPassOperation) == MTLStencilOperation.DecrementWrap } } describe("S3DXMLMTLDepthStencilDescriptorNode") { it("can parse a depth stencil descriptor") { let desc = descriptorManager.depthStencilDescriptors["depth_stencil_desc"]! expect(desc.depthCompareFunction) == MTLCompareFunction.Never expect(desc.depthWriteEnabled) == true expect(desc.frontFaceStencil) == descriptorManager.stencilDescriptors["stencil_desc"] expect(desc.backFaceStencil) == descriptorManager.stencilDescriptors["stencil_desc"] } } describe("S3DXMLMTLRenderPipelineColorAttachmentDescriptorNode") { it("can parse a render pipeline color attachment descriptor") { let desc = descriptorManager.colorAttachmentDescriptors["color_attach_desc"]! expect(desc.blendingEnabled) == true expect(desc.sourceRGBBlendFactor) == MTLBlendFactor.Zero expect(desc.destinationRGBBlendFactor) == MTLBlendFactor.SourceColor expect(desc.rgbBlendOperation) == MTLBlendOperation.Subtract expect(desc.sourceAlphaBlendFactor) == MTLBlendFactor.BlendAlpha expect(desc.destinationAlphaBlendFactor) == MTLBlendFactor.OneMinusBlendAlpha expect(desc.alphaBlendOperation) == MTLBlendOperation.Max expect(desc.pixelFormat) == MTLPixelFormat.BGRA8Unorm } } describe("S3DXMLMTLRenderPipelineDescriptorNode") { it("can parse a render pipeline descriptor") { let desc = descriptorManager.renderPipelineDescriptors["render_pipeline_desc"]! expect(desc.label) == "render-pipeline-descriptor" expect(desc.sampleCount) == 2 expect(desc.alphaToCoverageEnabled) == true expect(desc.alphaToOneEnabled) == true expect(desc.rasterizationEnabled) == true expect(desc.depthAttachmentPixelFormat) == MTLPixelFormat.Depth32Float expect(desc.stencilAttachmentPixelFormat) == MTLPixelFormat.Stencil8 expect(desc.vertexFunction!.name) == "basic_color_vertex" expect(desc.fragmentFunction!.name) == "basic_color_fragment" expect(desc.vertexDescriptor) == descriptorManager.vertexDescriptors["common_vertex_desc"]! expect(desc.colorAttachments[0]) == descriptorManager.colorAttachmentDescriptors["color_attach_desc"] } } describe("S3DXMLMTLComputePipelineDescribeNode") { it("can parse a compute pipeline descriptor") { let desc = descriptorManager.computePipelineDescriptors["compute_pipeline_desc"]! expect(desc.label) == "compute-pipeline-descriptor" expect(desc.threadGroupSizeIsMultipleOfThreadExecutionWidth) == true expect(desc.computeFunction!.name) == "test_compute_function" } } describe("S3DXMLMTLRenderPassColorAttachmentDescriptorNode") { it("can parse a render pass color attachment descriptor") { let desc = descriptorManager.renderPassColorAttachmentDescriptors["rpass_color_attach_desc"]! expect(desc.level) == 1 expect(desc.slice) == 1 expect(desc.depthPlane) == 1 expect(desc.resolveLevel) == 1 expect(desc.resolveSlice) == 1 expect(desc.resolveDepthPlane) == 1 expect(desc.loadAction) == MTLLoadAction.Load expect(desc.storeAction) == MTLStoreAction.Store //clearColor } } describe("S3DXMLMTLRenderPassDepthAttachmentDescriptorNode") { it("can parse a render pass depth attachment descriptor") { let desc = descriptorManager.renderPassDepthAttachmentDescriptors["rpass_depth_attach_desc"]! expect(desc.level) == 1 expect(desc.slice) == 1 expect(desc.depthPlane) == 1 expect(desc.resolveLevel) == 1 expect(desc.resolveSlice) == 1 expect(desc.resolveDepthPlane) == 1 expect(desc.loadAction) == MTLLoadAction.Load expect(desc.storeAction) == MTLStoreAction.Store expect(desc.clearDepth) == 2.0 expect(desc.depthResolveFilter) == MTLMultisampleDepthResolveFilter.Min } } describe("S3DXMLMTLRenderPassStencilAttachmentDescriptorNode") { it("can parse a render pass stencil attachment descriptor") { let desc = descriptorManager.renderPassStencilAttachmentDescriptors["rpass_stencil_attach_desc"]! expect(desc.level) == 1 expect(desc.slice) == 1 expect(desc.depthPlane) == 1 expect(desc.resolveLevel) == 1 expect(desc.resolveSlice) == 1 expect(desc.resolveDepthPlane) == 1 expect(desc.loadAction) == MTLLoadAction.Load expect(desc.storeAction) == MTLStoreAction.Store expect(desc.clearStencil) == 0 } } describe("S3DXMLMTLRenderPassDescriptorNode") { it("can parse a render pass descriptor") { let desc = descriptorManager.renderPassDescriptors["render_pass_desc"]! let colorAttach = descriptorManager.renderPassColorAttachmentDescriptors["rpass_color_attach_desc"]! let depthAttach = descriptorManager.renderPassDepthAttachmentDescriptors["rpass_depth_attach_desc"]! let stencilAttach = descriptorManager.renderPassStencilAttachmentDescriptors["rpass_stencil_attach_desc"]! expect(desc.colorAttachments[0]) == colorAttach expect(desc.depthAttachment) == depthAttach expect(desc.stencilAttachment) == stencilAttach } } } }
mit
2073d5953d6240b4a955df60e685eb72
47.105485
122
0.597105
5.142084
false
false
false
false
malaonline/iOS
mala-ios/View/TeacherDetail/TeacherDetailsHighScoreTableView.swift
1
5985
// // TeacherDetailsHighScoreTableView.swift // mala-ios // // Created by Elors on 1/11/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit private let TeacherDetailsHighScoreTableViewCellReuseId = "TeacherDetailsHighScoreTableViewCellReuseId" class TeacherDetailsHighScoreTableView: UITableView, UITableViewDelegate, UITableViewDataSource { // MARK: - Variables var models: [HighScoreModel?] = [] { didSet { reloadData() } } // MARK: - Constructed override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) delegate = self dataSource = self register(TeacherDetailsHighScoreTableViewCell.self, forCellReuseIdentifier: TeacherDetailsHighScoreTableViewCellReuseId) // Style isScrollEnabled = false separatorStyle = .none setupTableHeaderView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func setupTableHeaderView() { let headerView = TeacherDetailsHighScoreTableViewCell(style: .default, reuseIdentifier: nil) headerView.setTableTitles(["姓 名", "提分区间", "所在学校", "考入学校"]) headerView.separator.isHidden = true self.tableHeaderView = headerView } // MARK: - DataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TeacherDetailsHighScoreTableViewCellReuseId, for: indexPath) let model = models[indexPath.row] if model == nil { (cell as! TeacherDetailsHighScoreTableViewCell).model = HighScoreModel(name: "-", score: 0, school: "-", admitted: "-") }else { (cell as! TeacherDetailsHighScoreTableViewCell).model = model } return cell } func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } // MARK: - Delegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 33 } } // MARK: - TeacherDetailsHighScoreTableViewCell class TeacherDetailsHighScoreTableViewCell: UITableViewCell { // MARK: - Variables var model: HighScoreModel? { didSet { nameLabel.text = model!.name scoresLabel.text = String(format: "%d", model!.increased_scores) schoolLabel.text = model!.school_name admittedLabel.text = model!.admitted_to } } // MARK: - Components private lazy var nameLabel: UILabel = UILabel.subTitleLabel() private lazy var scoresLabel: UILabel = UILabel.subTitleLabel() private lazy var schoolLabel: UILabel = UILabel.subTitleLabel() private lazy var admittedLabel: UILabel = UILabel.subTitleLabel() lazy var separator: UIView = { let separatorLine = UIView() separatorLine.backgroundColor = UIColor(named: .SeparatorLine) return separatorLine }() // MARK: - Constructed override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.frame = CGRect(x: 0, y: 0, width: MalaScreenWidth - 12, height: 33) setupUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func setupUserInterface() { // SubView contentView.addSubview(nameLabel) contentView.addSubview(scoresLabel) contentView.addSubview(schoolLabel) contentView.addSubview(admittedLabel) contentView.addSubview(separator) // Autolayout nameLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView) maker.bottom.equalTo(contentView) maker.left.equalTo(contentView) } scoresLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView) maker.left.equalTo(nameLabel.snp.right) maker.width.equalTo(nameLabel) maker.height.equalTo(nameLabel) } schoolLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView) maker.left.equalTo(scoresLabel.snp.right) maker.width.equalTo(scoresLabel) maker.height.equalTo(scoresLabel) } admittedLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView) maker.left.equalTo(schoolLabel.snp.right) maker.width.equalTo(schoolLabel) maker.height.equalTo(schoolLabel) maker.right.equalTo(contentView) } separator.snp.makeConstraints { (maker) -> Void in maker.left.equalTo(contentView) maker.right.equalTo(contentView) maker.height.equalTo(MalaScreenOnePixel) maker.bottom.equalTo(contentView) } } // MARK: - API /// 根据传入的表头字符串数组,生成对应的表头 /// /// - parameter titles: 表头字符串数组 func setTableTitles(_ titles: [String]) { nameLabel.text = titles[0] scoresLabel.text = titles[1] schoolLabel.text = titles[2] admittedLabel.text = titles[3] for view in self.contentView.subviews { (view as? UILabel)?.textColor = UIColor(named: .ArticleTitle) } contentView.backgroundColor = UIColor(named: .BaseBoard) } }
mit
9a5322a07fd7380ba843c51b7e673a06
32.534091
131
0.633683
4.877686
false
false
false
false
marcelganczak/swift-js-transpiler
test/weheartswift/conditionals-4.swift
1
177
var a = 2 var b = 2 var c = 2 if (a == b) || (a == c) || (b == c) { print("At least two variables have the same value") } else { print("All the values are different") }
mit
058860fd57e5d4fc702620dc9abde83a
18.777778
55
0.542373
2.854839
false
false
false
false
huahuasj/ios-charts
Charts/Classes/Data/ScatterChartData.swift
6
1407
// // ScatterChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import UIKit public class ScatterChartData: BarLineScatterCandleChartData { public override init() { super.init(); } public override init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } /// Returns the maximum shape-size across all DataSets. public func getGreatestShapeSize() -> CGFloat { var max = CGFloat(0.0); for set in _dataSets { let scatterDataSet = set as? ScatterChartDataSet; if (scatterDataSet == nil) { println("ScatterChartData: Found a DataSet which is not a ScatterChartDataSet"); } else { let size = scatterDataSet!.scatterShapeSize; if (size > max) { max = size; } } } return max; } }
apache-2.0
f87dd67dadc1738a0b77ed80d836788e
22.847458
96
0.538024
4.835052
false
false
false
false
haawa799/WaniKani-iOS
WaniKani/Views/Layouts/CriticalItemsLayout.swift
1
1173
// // CriticalItemsLayout.swift // WaniKani // // Created by Andriy K. on 11/5/15. // Copyright © 2015 Andriy K. All rights reserved. // import UIKit class CriticalItemsLayout: UICollectionViewFlowLayout { private let aspectRatio: CGFloat = 724 / 170 private let defaultCellInset: CGFloat = 7 let rowsSpacing: CGFloat = 1 override func prepareLayout() { sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: defaultCellInset, right: defaultCellInset) let width = collectionViewContentSize().width - sectionInset.left - sectionInset.right let height = width / aspectRatio itemSize = CGSize(width: width, height: height) let headerHeight = height * 0.5 headerReferenceSize = CGSize(width: width, height: headerHeight) if let collectionView = collectionView { let insets = collectionView.contentInset collectionView.contentInset = UIEdgeInsets(top: insets.top + height, left: insets.left, bottom: insets.bottom, right: insets.right) } minimumLineSpacing = rowsSpacing sectionInset = UIEdgeInsets(top: 0, left: defaultCellInset, bottom: height * 0.5, right: defaultCellInset) } }
gpl-3.0
eb1ca58232025185ff2c5cf0572b0c14
31.555556
137
0.713311
4.406015
false
false
false
false
lilongcnc/Swift-weibo2015
ILWEIBO04/ILWEIBO04/Classes/Tools/SQLite.swift
1
4311
// // SQLite.swift // 01-工资表 // // Created by 刘凡 on 15/3/14. // Copyright (c) 2015年 itheima. All rights reserved. // import Foundation class SQLite { /// 单例 private static let instance = SQLite() class var sharedSQLite : SQLite { return instance } /// database_connection 对象 var db: COpaquePointer = nil; /// 打开数据库 func openDatabase(dbName: String) -> Bool { let path = dbName.documentPath() println(path) if (sqlite3_open(path.cStringUsingEncoding(NSUTF8StringEncoding)!, &db) == SQLITE_OK) { return createTable() } else { return false } } /// 创建数据表 private func createTable() -> Bool { var result = false var sql = "CREATE TABLE IF NOT EXISTS T_Status ( \n" + "id integer NOT NULL, \n" + "text TEXT NOT NULL DEFAULT '', \n" + "source TEXT NOT NULL DEFAULT '', \n" + "created_at TEXT NOT NULL DEFAULT '', \n" + "reposts_count INTEGER NOT NULL DEFAULT 0, \n" + "comments_count INTEGER NOT NULL DEFAULT 0, \n" + "attitudes_count INTEGER NOT NULL DEFAULT 0, \n" + "userId INTEGER NOT NULL DEFAULT 0, \n" + "retweetedId INTEGER NOT NULL DEFAULT 0, \n" + "refresh INTEGER NOT NULL DEFAULT 0, \n" + "PRIMARY KEY(id) \n" + "); \n" + "CREATE TABLE IF NOT EXISTS T_StatusPic ( \n" + "id INTEGER NOT NULL, \n" + "statusId INTEGER NOT NULL DEFAULT 0, \n" + "thumbnail_pic text NOT NULL DEFAULT ‘’, \n" + "PRIMARY KEY(id) \n" + "); \n" + "CREATE TABLE IF NOT EXISTS T_User ( \n" + "id integer NOT NULL, \n" + "screen_name TEXT NOT NULL DEFAULT '', \n" + "name TEXT NOT NULL DEFAULT '', \n" + "profile_image_url TEXT NOT NULL DEFAULT '', \n" + "avatar_large TEXT NOT NULL DEFAULT '', \n" + "created_at TEXT NOT NULL DEFAULT '', \n" + "verified INTEGER NOT NULL DEFAULT 0, \n" + "mbrank INTEGER NOT NULL DEFAULT 0, \n" + "PRIMARY KEY(id) \n" + ");" return execSQL(sql) } /// 执行单条操作语句 func execSQL(sql: String) -> Bool { return sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK } /// 执行返回结果数量 func execCount(sql: String) -> Int { let record = execRecordSet(sql) return (record[0] as! [AnyObject])[0] as! Int } /// 执行返回单条记录 func execRow(sql: String) -> [AnyObject]? { let record = execRecordSet(sql) if record.count > 0 { return (record[0] as! [AnyObject]) } else { return nil } } /// 执行 SQL 返回结果集合 func execRecordSet(sql: String) -> [AnyObject] { // 1. 准备 sql var stmt: COpaquePointer = nil var recordList = [AnyObject]() if sqlite3_prepare_v2(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &stmt, nil) == SQLITE_OK { while sqlite3_step(stmt) == SQLITE_ROW { recordList.append(rowData(stmt)) } } // 释放语句 sqlite3_finalize(stmt) return recordList } /// 返回一行数据数组及其数据的类型,供写数据库文件用 private func rowData(stmt: COpaquePointer) -> [AnyObject] { var array = [AnyObject]() for i in 0..<sqlite3_column_count(stmt) { switch sqlite3_column_type(stmt, i) { case SQLITE_FLOAT: array.append(sqlite3_column_double(stmt, i)) case SQLITE_INTEGER: array.append(Int(sqlite3_column_int64(stmt, i))) case SQLITE_TEXT: var chars: UnsafePointer<CChar> = (UnsafePointer<CChar>)(sqlite3_column_text(stmt, i)) array.append(String.fromCString(chars)!) case SQLITE_NULL: array.append(NSNull()) case let type: println("不支持的类型 \(type)") } } return array } }
mit
0fb66445897285988634b743decee5c4
29.607407
113
0.530622
3.945559
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/App Lock/AppLockModule.Router.swift
1
2900
// // Wire // Copyright (C) 2020 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 Foundation import WireSyncEngine import UIKit extension AppLockModule { final class Router: RouterInterface { // MARK: - Properties weak var view: View! } } // MARK: - Perform action extension AppLockModule.Router: AppLockRouterPresenterInterface { func performAction(_ action: AppLockModule.Action) { switch action { case let .createPasscode(shouldInform): presentCreatePasscodeModule(shouldInform: shouldInform) case .inputPasscode: presentInputPasscodeModule() case .informUserOfConfigChange: presentWarningModule() case .openDeviceSettings: presentDeviceSettings() } } private func presentCreatePasscodeModule(shouldInform: Bool) { let passcodeSetupViewController = PasscodeSetupViewController.createKeyboardAvoidingFullScreenView( variant: .dark, context: shouldInform ? .forcedForTeam : .createPasscode, delegate: view) view.present(passcodeSetupViewController, animated: true) } private func presentInputPasscodeModule() { // TODO: [John] Clean this up. // TODO: [John] Inject these arguments. let unlockViewController = UnlockViewController(selfUser: ZMUser.selfUser(), userSession: ZMUserSession.shared()) let keyboardAvoidingViewController = KeyboardAvoidingViewController(viewController: unlockViewController) let navigationController = keyboardAvoidingViewController.wrapInNavigationController(navigationBarClass: TransparentNavigationBar.self) navigationController.modalPresentationStyle = .fullScreen unlockViewController.delegate = view view.present(navigationController, animated: false) } private func presentWarningModule() { let warningViewController = AppLockChangeWarningViewController(isAppLockActive: true) warningViewController.modalPresentationStyle = .fullScreen warningViewController.delegate = view view.present(warningViewController, animated: false) } private func presentDeviceSettings() { UIApplication.shared.openSettings() } }
gpl-3.0
b911a270503cd028a22a93326b904a1e
32.72093
143
0.721034
5.225225
false
false
false
false
dmonagle/vapor-graph
Sources/VaporGraph/Graph.swift
1
9677
import Vapor import FluentProvider import Foundation /** Implements callbacks for the Graph sync lifecycle */ public protocol GraphSyncDelegate { func graphWillSync(forced: Bool) throws func graphDidSync() } open class Graph : GraphSynchronizable { /** Determines how a model with an id that already exists in the Graph will be treated when an attempt is made to inject it. # rebase Captures the changes that have been made to the existing and merges them with the new model. The result is then applied to the existing reference and returned. # deserialize Deserializes the data from the new record into the existing record. This keeps references the same and overwrites any changes that have been made to the original # keepExisting Ignores the incoming record and return a reference to the existing one # replaceReference Replace the current reference with the new one. This could leave other classes with references to a model that no longer exists in the graph. Not really recommended */ public enum DuplicateResolution { case rebase case deserialize case keepExisting case replaceReference } // Defines a priority for syncing each model type. These will be done first, in order and then any other models in the store will be done at random. static public var ModelSyncOrder : [String] = [] public var storeNames : [String] { get { return _store.keys.array } } public init() { } private var _store : [String: GraphModelStore] = [:] public var context : Context = emptyContext public var syncDelegate : GraphSyncDelegate? = nil public func store<T>(forType: T.Type) -> GraphModelStore? where T : Entity { return _store[forType.entity] } public func store(forType name: String) -> GraphModelStore? { return _store[name] } /** Injects a model into the graph. If the id of the model already exists in the graph, the `duplicateResolution` is used to determine how to proceed. - Parameters: - model: A `Graphable` model - duplicateResolution: Specifies how to deal with a duplicate id being inserted - takeSnapshot: If set to `true`, a snapshot will be taken of the model after it is inserted into the graph. If set to `false`, the model is injected without a snapshot. If it's set to `nil` (default) a snapshot will be taken if model.exists is true (ie: it exists in the database). The snapshot is supposed to represent the model's last known state in the database so a snapshot is normally desired when inserting the result of a database query. - Returns: A reference to the injected model. This may not be the same as the reference passed in if the id was a duplicate of a model already in the graph. */ public func inject<T>(_ model : T, duplicateResolution: DuplicateResolution = .rebase, takeSnapshot: Bool? = nil) throws -> T where T : Graphable{ let id : Identifier let takeSnapshot = takeSnapshot ?? model.exists // If takeSnapshot parameter was nil, this causes it to be set to true if the model exists in the database if let modelId = model.id { id = modelId } else { guard let generator = T.graphIdGenerator else { throw GraphError.noId } id = try generator(T.self) // Add the generated id to the model model.id = Identifier(id) } let store = ensureStore(model: model) // If the model, according to it's id, already exists in the store, we need to return the reference already in the graph if let existing : T = store.retrieve(id: id) { // If the model to be injected is exactly the same reference as the existing one, no more needs to be done. if (existing === model) { return existing } switch duplicateResolution { case .keepExisting: return existing case .deserialize: try existing.graphDeserialize(row: try model.makeRow(in: GraphContext.snapshot), in: GraphContext.snapshot) if (takeSnapshot) { try model.takeSnapshot() } return existing case .rebase: try existing.rebase(from: model, updateSnapshot: takeSnapshot) return existing case .replaceReference: // Fall through here as replacing is the same as adding a non-existing break } } try store.add(model) model.graph = self if (takeSnapshot) { try model.takeSnapshot() } return model } /** Injects multiple models into the graph - Returns: An array containing the references of the injected models. This may not be identical to the array passed in due to duplicate handling. */ public func inject<T>(_ models : [T], duplicateResolution: DuplicateResolution = .rebase, takeSnapshot: Bool = false) throws -> [T] where T : Graphable { var results : [T] = [] try models.forEach { model in results.append(try inject(model, duplicateResolution: duplicateResolution, takeSnapshot: takeSnapshot)) } return results } /// Removes a model from the graph. public func remove<T : Graphable>(_ model : T) { _store[T.entity]?.remove(model) model.graph = nil } /// Retrieves an object from the Graph public func retrieve<T : Graphable>(id: Identifier) -> T? { let result : T? = _store[T.entity]?.retrieve(id: id) return result } /// Looks for the given id in the Graph. If it's not present it will search the database for it and, if found, add it to the Graph public func find<T : Graphable>(id: Identifier, duplicateResolution: DuplicateResolution = .rebase) throws -> T? { if let result : T = retrieve(id: id) { return result } guard let result = try T.find(id) else { return nil } return try self.inject(result, duplicateResolution: duplicateResolution, takeSnapshot: true) } /// Convenience: Queries the database for the model with the filter value and returns the result of injecting them into the graph with the given duplication resolution public func findMany<T>(field: String, value: NodeRepresentable, duplicateResolution: DuplicateResolution = .rebase) throws -> [T] where T : Graphable { return try inject(T.makeQuery().filter(field, value).all(), duplicateResolution: duplicateResolution, takeSnapshot: true) } public func clear() { _store = [:] } // MARK: GraphSynchronizable /** Check all stores to see if any model needs synchronization - Returns: `true` if any model in any store needs synchronization */ public func needsSync() throws -> Bool { var result = false try _store.forEach { _, store in if (try store.needsSync()) { result = true return } } return result } /** Sync all models across all stores - Parameters: - force: If set to true, will save each model whether or not it returns true to `needsSync`. Use with care when doing this across the entire graph */ public func sync(executor: Executor? = nil, force: Bool = false) throws { try syncDelegate?.graphWillSync(forced: force) var syncKeys = type(of: self).ModelSyncOrder for key in _store.keys { if !syncKeys.contains(key) { syncKeys.append(key) } } for modelType in syncKeys { if let store = _store[modelType] { try store.sync(executor: executor, force: force) } } syncDelegate?.graphDidSync() } public func forEach(_ body: (Graphable) throws -> Void) rethrows { try _store.forEach { _, store in try store._models.forEach { _, model in try body(model) } } } /// Returns all the models in the stores that can be cast to T and pass the given filter function public func filter<T>(_ filterFunc: (T) -> Bool) -> [T] where T: Graphable { var results: [T] = [] forEach { model in if let m = model as? T { if (filterFunc(m)) { results.append(m) } } } return results } // MARK: Private /// Returns the store for the named `entityName` if it exists or creates it if it doesn't private func ensureStore(entityName: String) -> GraphModelStore { guard let store = _store[entityName] else { let newStore = GraphModelStore() _store[entityName] = newStore return newStore } return store } /// Returns the store for the given `Graphable` type if it exists or creates it if it doesn't private func ensureStore<T : Graphable>(forType : T.Type) -> GraphModelStore { return ensureStore(entityName: forType.entity) } /// Returns the store for the given model if it exists or creates it if it doesn't private func ensureStore(model : Graphable) -> GraphModelStore { return ensureStore(entityName: type(of: model).entity) } }
mit
dd63d61c0c208ef6b359e217ac8f3253
38.020161
171
0.619407
4.743627
false
false
false
false
imzyf/99-projects-of-swift
018-flickr-search/018-flickr-search/FilckrModel/Flickr.swift
1
5932
/** * Copyright (c) 2016 Razeware LLC * * 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 // +6 let apiKey = "c5fdb6882724cc3cea45ccbfcb03a2c" class Flickr { let processingQueue = OperationQueue() func searchFlickrForTerm(_ searchTerm: String, completion : @escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){ guard let searchURL = flickrSearchURLForSearchTerm(searchTerm) else { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) completion(nil, APIError) return } let searchRequest = URLRequest(url: searchURL) URLSession.shared.dataTask(with: searchRequest, completionHandler: { (data, response, error) in if let _ = error { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) OperationQueue.main.addOperation({ completion(nil, APIError) }) return } guard let _ = response as? HTTPURLResponse, let data = data else { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) OperationQueue.main.addOperation({ completion(nil, APIError) }) return } do { guard let resultsDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String: AnyObject], let stat = resultsDictionary["stat"] as? String else { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) OperationQueue.main.addOperation({ completion(nil, APIError) }) return } switch (stat) { case "ok": print("Results processed OK") case "fail": if let message = resultsDictionary["message"] { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:message]) OperationQueue.main.addOperation({ completion(nil, APIError) }) } let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: nil) OperationQueue.main.addOperation({ completion(nil, APIError) }) return default: let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) OperationQueue.main.addOperation({ completion(nil, APIError) }) return } guard let photosContainer = resultsDictionary["photos"] as? [String: AnyObject], let photosReceived = photosContainer["photo"] as? [[String: AnyObject]] else { let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"]) OperationQueue.main.addOperation({ completion(nil, APIError) }) return } var flickrPhotos = [FlickrPhoto]() for photoObject in photosReceived { guard let photoID = photoObject["id"] as? String, let farm = photoObject["farm"] as? Int , let server = photoObject["server"] as? String , let secret = photoObject["secret"] as? String else { break } let flickrPhoto = FlickrPhoto(photoID: photoID, farm: farm, server: server, secret: secret) guard let url = flickrPhoto.flickrImageURL(), let imageData = try? Data(contentsOf: url as URL) else { break } if let image = UIImage(data: imageData) { flickrPhoto.thumbnail = image flickrPhotos.append(flickrPhoto) } } OperationQueue.main.addOperation({ completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil) }) } catch _ { completion(nil, nil) return } }) .resume() } fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL? { guard let escapedTerm = searchTerm.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else { return nil } let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=18&format=json&nojsoncallback=1" guard let url = URL(string:URLString) else { return nil } return url } }
mit
0519b95157a1ac3c1796da28999200e5
36.308176
167
0.62913
5.078767
false
false
false
false
Adlai-Holler/BondPlusCoreData
BondPlusCoreDataTests/BondPlusCoreDataTests.swift
2
6862
import CoreData import Nimble import Quick import BondPlusCoreData import Bond import AlecrimCoreData class DataContext: Context { var stores: Table<Store> { return Table<Store>(context: self) } var items: Table<Item> { return Table<Item>(context: self) } } class NSFetchedResultsDynamicArraySpec: QuickSpec { override func spec() { var context: DataContext! var store: Store! var importMore: (() -> ())! beforeEach { let bundle = NSBundle(forClass: self.classForCoder) // create DB AlecrimCoreData.Config.modelBundle = bundle context = DataContext(stackType: .InMemory, managedObjectModelName: "BondPlusCoreDataTests", storeOptions: nil) // load seed let url = bundle.URLForResource("SeedData", withExtension: "json")! let file = NSInputStream(URL: url)! file.open() var parseError: NSError? let seedData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject] file.close() store = EKManagedObjectMapper.objectFromExternalRepresentation(seedData["store"]! as! [NSObject: AnyObject], withMapping: Store.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! Store context.managedObjectContext.processPendingChanges() importMore = { let url = bundle.URLForResource("MoreData", withExtension: "json")! let file = NSInputStream(URL: url)! file.open() var parseError: NSError? let moreData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject] file.close() let newItems = EKManagedObjectMapper.arrayOfObjectsFromExternalRepresentation(moreData["items"]! as! [[String: AnyObject]], withMapping: Item.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! [Item] store.mutableSetValueForKey("items").addObjectsFromArray(newItems) context.managedObjectContext.processPendingChanges() } } describe("Test Import") { it("should load the store correctly") { expect(store.name).to(equal("Adlai's Grocery")) } it("should load store.items correctly") { expect(store.items.count).to(equal(6)) } it("should load item attributes correctly") { let anyItem = store.items.anyObject()! as! Item let expectedItemNames = Set(["Apple", "Banana", "Cherry", "Asparagus", "Broccoli", "Celery"]) let actualItemNames = Set(context.items.toArray().map { $0.name }) expect(actualItemNames).to(equal(expectedItemNames)) } } describe("Fetched Results Array") { var array: NSFetchedResultsDynamicArray<Item>! var sectionBond: ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>! beforeEach { let importantStore = context.stores.filterBy(attribute: "uuid", value: "2AB5041B-EF80-4910-8105-EC06B978C5DE").first()! let fr = context.items .filterBy(attribute: "store", value: importantStore) .sortBy("itemType", ascending: true) .thenByAscending("name") .toFetchRequest() let frc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context.managedObjectContext, sectionNameKeyPath: "itemType", cacheName: nil) array = NSFetchedResultsDynamicArray(fetchedResultsController: frc) sectionBond = ArrayBond() array ->> sectionBond } it("should report correct number of sections") { expect(array.count).to(equal(2)) } it("should handle deleting the last section correctly") { var removedSections = [Int]() sectionBond.willRemoveListener = {array, indices in removedSections += indices } context.items.filterBy(attribute: "itemType", value: "veggie").delete() context.managedObjectContext.processPendingChanges() expect(removedSections).to(equal([1])) expect(array.count).to(equal(1)) } it("should handle deleting all items correctly") { var removedSections = [Int]() sectionBond.willRemoveListener = {array, indices in removedSections += indices } context.items.delete() context.managedObjectContext.processPendingChanges() for item in context.items { println("item: \(item)") } expect(Set(removedSections)).to(equal(Set([0,1]))) expect(array.count).to(equal(0)) } it("should handle delete at 0,0 correctly") { let firstSectionBond = ArrayBond<Item>() var removedIndices = [Int]() firstSectionBond.willRemoveListener = { array, indices in removedIndices += indices } array[0] ->> firstSectionBond context.managedObjectContext.deleteObject(array[0][0]) context.managedObjectContext.processPendingChanges() expect(removedIndices).to(equal([0])) expect(array.count).to(equal(2)) expect(array[0].count).to(equal(2)) expect(array[0].first!.name).to(equal("Banana")) } it("should handle inserting many items (potentially out-of-order) correctly") { let firstSectionBond = ArrayBond<Item>() var insertedIndices = [Int]() println("Items: \(array[0].value)") firstSectionBond.willInsertListener = { array, indices in insertedIndices += indices } array[0] ->> firstSectionBond importMore() println("Items: \(array[0].value)") expect(insertedIndices).to(equal(Array(3...8))) } it("should handle update at 1,1 correctly") { let lastSectionBond = ArrayBond<Item>() var updatedIndices = [Int]() lastSectionBond.willUpdateListener = { array, indices in updatedIndices = indices } array[1] ->> lastSectionBond let item = array[1][1] item.count-- context.managedObjectContext.processPendingChanges() expect(updatedIndices).to(equal([1])) } it("should handle inserting a section at index 1 correctly") { let sectionsBond = ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>() var insertedSections = [Int]() sectionsBond.willInsertListener = { array, indices in insertedSections += indices } array ->> sectionsBond let newItem = context.items.createEntity() newItem.uuid = NSUUID().UUIDString newItem.name = "Ground beef" newItem.count = 10 newItem.itemType = "meat" newItem.store = store context.managedObjectContext.processPendingChanges() expect(insertedSections).to(equal([1])) } } } }
mit
f15369ea19d2db73a71652f44d985050
37.335196
231
0.644273
4.677573
false
false
false
false
OscarSwanros/swift
benchmark/single-source/UTF8Decode.swift
6
2337
//===--- UTF8Decode.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let UTF8Decode = BenchmarkInfo( name: "UTF8Decode", runFunction: run_UTF8Decode, tags: [.validation, .api, .String]) @inline(never) public func run_UTF8Decode(_ N: Int) { // 1-byte sequences // This test case is the longest as it's the most performance sensitive. let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program." // 2-byte sequences let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа." // 3-byte sequences let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。" // 4-byte sequences // Most commonly emoji, which are usually mixed with other text. let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭." let strings = [ascii, russian, japanese, emoji].map { Array($0.utf8) } func isEmpty(_ result: UnicodeDecodingResult) -> Bool { switch result { case .emptyInput: return true default: return false } } for _ in 1...200*N { for string in strings { var it = string.makeIterator() var utf8 = UTF8() while !isEmpty(utf8.decode(&it)) { } } } }
apache-2.0
b467ab61af311e16745ff2c9f007c0c2
41.431373
591
0.665434
3.718213
false
false
false
false
iosdevelopershq/Camille
Sources/CamilleServices/Karma/KarmaService+User.swift
1
1015
import Chameleon extension KarmaService { func userCount(bot: SlackBot, message: MessageDecorator, match: PatternMatch) throws { let user: ModelPointer<User> = try match.value(key: Keys.user) let count = try storage.get(key: user.id, from: Keys.namespace, or: 0) let response = try message .respond() .text(count == 0 ? ["It doesn't look like", user, "has any karma yet"] : [user, "has", count, "karma"] ) try bot.send(response.makeChatMessage()) } func senderCount(bot: SlackBot, message: MessageDecorator, match: PatternMatch) throws { let count = try storage.get(key: message.sender().id, from: Keys.namespace, or: 0) let response = try message .respond() .text(count == 0 ? ["It doesn't look like you have any karma yet"] : ["You have", count, "karma"] ) try bot.send(response.makeChatMessage()) } }
mit
f22d4b36414b1fb1b57ebb6488f9468a
31.741935
92
0.569458
4.027778
false
false
false
false
TurfDb/Turf
Turf/Observable/MiniRx/SubscribeOn.swift
1
1453
import Foundation class SubscribeOnSink<Value, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Value == Value { typealias Parent = SubscribeOn<Value> let parent: Parent init(parent: Parent, observer: Observer) { self.parent = parent super.init(observer: observer) } func handle(next: Value) { forwardOn(value: next) } func asObserver() -> AnyObserver<Value> { return AnyObserver(handleNext: { next in self.handle(next: next) }) } func run() -> Disposable { return parent.scheduler.schedule { () -> Disposable in return self.parent.source.subscribe(self) } } } class SubscribeOn<Value>: Producer<Value> { fileprivate let source: Observable<Value> let scheduler: RxScheduler init(source: Observable<Value>, scheduler: RxScheduler) { self.source = source self.scheduler = scheduler } override func run<Observer : ObserverType>(_ observer: Observer) -> Disposable where Observer.Value == Value { //calling subscribe, calls run let sink = SubscribeOnSink(parent: self, observer: observer) //calling run on sink sink.disposable = sink.run() return sink } } extension Observable { public func subscribeOn(_ scheduler: RxScheduler) -> Observable<Value> { return SubscribeOn(source: self, scheduler: scheduler) } }
mit
f70d3b8a4569e316d1cbed2fe4f7a1cb
26.942308
114
0.644184
4.512422
false
false
false
false
romansorochak/ParallaxHeader
Exmple/FromCodeCollectionCell.swift
1
1477
// // FromCodeCollectionCell.swift // Exmple // // Created by Roman Sorochak on 31.01.2020. // Copyright © 2020 MagicLab. All rights reserved. // import SnapKit import Reusable class FromCodeCollectionCell: UICollectionViewCell, Reusable { private (set) lazy var imageView: UIImageView = { let v = UIImageView() contentView.addSubview(v) v.snp.makeConstraints({ (make) in make.left.right.equalToSuperview() make.centerX.equalToSuperview() make.top.equalToSuperview() make.bottom.equalToSuperview().inset(22) }) v.contentMode = .scaleAspectFill v.clipsToBounds = true return v }() private (set) lazy var label: UILabel = { let v = UILabel() contentView.addSubview(v) v.snp.makeConstraints({ (make) in make.top.equalTo(self.imageView.snp.bottom).offset(4) make.left.right.equalToSuperview() make.centerX.equalToSuperview() }) v.textAlignment = .center v.backgroundColor = .clear return v }() override init(frame: CGRect) { super.init(frame: frame) imageView.isHidden = false imageView.image = UIImage(named: "profile") label.isHidden = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bd5e8ce7d9b0750077589a2e0d8e3c22
24.448276
65
0.583333
4.626959
false
false
false
false
Snowgan/XLRefreshSwift
Pod/Classes/XLRefreshConst.swift
1
604
// // XLRefreshConst.swift // Pods // // Created by Jennifer on 14/4/2016. // // enum XLRefreshStatus: Int { case Normal case WillRefresh case Refreshing case EndRefresh } let XLStateMap = ["\(XLRefreshStatus.Normal)": "Pull down", "\(XLRefreshStatus.WillRefresh)": "Release", "\(XLRefreshStatus.Refreshing)": "Loading", "\(XLRefreshStatus.EndRefresh)": "Pull down"] let XLRefreshHeaderHeight: CGFloat = 44 let XLRefreshFooterHeight: CGFloat = 40 let XLContentOffsetPath = "contentOffset" let XLContentSizePath = "contentSize"
mit
4658e1e46fa272f02011ff79a1f317a4
23.16
63
0.655629
4.165517
false
false
false
false