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
rachwal/RTM-iOS-Client
RTM Client/BusinessLogic/Persistency/RTMPersistency.swift
1
2498
// Copyright (c) 2015-2016. Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved. import CoreData class RTMPersistency: NSObject, Persistency { var context: NSManagedObjectContext? { return managedObjectContext } func getValues(field: String) -> [AnyObject] { let managedContext = context! let request = NSFetchRequest(entityName: field) do { return try managedContext.executeFetchRequest(request); } catch { return [NSManagedObject]() } } private lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() private lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("RTM_Client", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("RTM_Clients.qlite") 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{ coordinator = nil var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason var error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unresolved error \(error), \(error.userInfo)") abort() } return coordinator }() private lazy var managedObjectContext: NSManagedObjectContext? = { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() }
mit
362b44cc7f207ceb9afc738026cc72e3
36.863636
143
0.670536
6.033816
false
false
false
false
JGiola/TinyThemer
Sources/TinyThemer/TinyThemer.swift
1
1963
import Foundation extension Notification.Name { /// Notification raised every time the style is changed. static public let TinyThemerDidUpdateThemeStyle = Notification.Name(rawValue: "org.giola.jacopo.tinythemerdidupdatethemestyle") } /// Small struct that keeps track of the current style and the `Theme`s of the app. public struct TinyThemer { /// An enumeration of the possible values for the app style /// /// - light: The default style, for light appearence /// - dark: The alternative style, for the dark appearence public enum ThemeStyle { case light case dark } /// Set the style for the app /// /// - Parameter style: The `ThemeStyle` that we want to set for the app. static public func setStyle(style: ThemeStyle) { currentStyle = style } static var currentStyle = ThemeStyle.light { didSet { if oldValue != currentStyle { NotificationCenter.default.post(name: .TinyThemerDidUpdateThemeStyle, object: nil) } } } let lightTheme: Theme let darkTheme: Theme /// The initializer of the `TinyThemer`. /// /// - Parameters: /// - lightTheme: The theme that incapsulate the logic for the light style /// - darkTheme: The theme that incapsulate the logic for the dark style public init(lightTheme: Theme, darkTheme: Theme) { self.lightTheme = lightTheme self.darkTheme = darkTheme } /// Return the theme based on the current style selected. /// /// - Returns: One of the two `Theme` passed on initialization. public func currentTheme() -> Theme { switch TinyThemer.currentStyle { case .light: return lightTheme case .dark: return darkTheme } } } /// Class that incapsulate all the variable for defining the theme of the app public class Theme { } /// The protocol to conform for an instance to be able to change theme. public protocol Themable { var themer: TinyThemer { get } func updateInterface() }
mit
b36a9a6375bdab6cf3754fad3a029203
26.263889
90
0.694345
4.258134
false
false
false
false
jie-cao/SwiftImage
SwiftImage/MD5.swift
2
8276
// // String+MD5.swift // Kingfisher // // This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift // which is a modified version of CryptoSwift: // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset of CryptoSwift as a (temporary?) alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation extension String { func toMD5() -> String { if let data = dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(data) let MD5Data = MD5Calculator.calculate() let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) var MD5String = "" for c in resultEnumerator { MD5String += String(format: "%02x", c) } return MD5String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) let valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T),totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } class HashBase { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(len:Int = 64) -> NSMutableData { let tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.length; var counter = 0; while msgLength % len != (len - 8) { counter++ msgLength++ } let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8))) tmpMessage.appendBytes(bufZeros, length: counter) bufZeros.destroy() bufZeros.dealloc(1) return tmpMessage } } func rotateLeft(v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } class MD5 : HashBase { /** specifies the per-round shift amounts */ private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391] private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> NSData { let tmpMessage = prepare() // hash values var hh = h // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.length * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage.appendBytes(Array(Array(lengthBytes.reverse()))); // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes))) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0) let range = NSRange(location:0, length: M.count * sizeof(UInt32)) chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range) // Initialize hash value for this chunk: var A:UInt32 = hh[0] var B:UInt32 = hh[1] var C:UInt32 = hh[2] var D:UInt32 = hh[3] var dTemp:UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F:UInt32 = 0 switch (j) { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } let buf: NSMutableData = NSMutableData(); for item in hh{ var i:UInt32 = item.littleEndian buf.appendBytes(&i, length: sizeofValue(i)) } return buf.copy() as! NSData; } }
mit
e953811d302a02b2d3dd9a695f45715a
36.420814
213
0.582416
3.681656
false
false
false
false
LemonRuss/TableComponents
TableComponents/Classes/Common/TitleDescriptionAvatarCell/TitleDescriptionAvatarCell.swift
1
2039
// // TitleDescriptionAvatarCell.swift // tonesky // // Created by Alex Lavrinenko on 03.12.16. // Copyright © 2016 Olimjon Kenjaev. All rights reserved. // import UIKit import TableKit //import SDWebImage open class TitleDescriptionAvatarCell: UITableViewCell { @IBOutlet public weak var titleLabel: UILabel! @IBOutlet public weak var descripionLabel: UILabel! @IBOutlet weak var avatarImageView: UIImageView! { didSet { avatarImageView.layer.cornerRadius = (avatarImageView.frame.width / 2) * 0.8 avatarImageView.clipsToBounds = true } } public static func defaultStyle(title: String, description: String, avatar: String) -> Info { return Info(title: title, description: description, avatar: avatar, customizeTitleLabel: { $0.textColor = UIColor(hex: 0x4A4A4A) }, customizeDescriptionLabel: { $0.textColor = UIColor(hex: 0x4A4A4A) $0.isUserInteractionEnabled = true }) } public struct Info { var title: String var description: String var avatar: String var customizeTitleLabel: ((UILabel) -> Void)? var customizeDescriptionLabel: ((UILabel) -> Void)? } public struct Actions { public static let descriptionLabelTapped = "DescriptionLabelTapped" } func descriptionTapped() { TableCellAction(key: Actions.descriptionLabelTapped, sender: self).invoke() } } extension TitleDescriptionAvatarCell: ConfigurableCell { public func configure(with item: Info) { titleLabel.text = item.title descripionLabel.text = item.description if let url = URL(string: item.avatar) { // avatarImageView.sd_setImage(with: url) } if let customizeTitleLabel = item.customizeTitleLabel { customizeTitleLabel(titleLabel) } if let customizeDescriptionLabel = item.customizeDescriptionLabel { customizeDescriptionLabel(descripionLabel) let tap = UITapGestureRecognizer(target: self, action: #selector(descriptionTapped)) descripionLabel.addGestureRecognizer(tap) } } }
mit
d98e0c3c08976af795d1e2b9d55c8072
28.114286
95
0.715407
4.33617
false
false
false
false
nikano1991/NAlertView
NAlertView/NAlertView.swift
1
21325
// // NAlertView.swift // // Created by Marc on 31/05/16. // Copyright © 2016 Nikano. All rights reserved. // import UIKit public enum ButtonsOrientation { case Horizontal case Vertical } /// Struct that stores all the information of an Alert struct Alert: Equatable { var title: String let message: String let buttonsTitle: [AlertButton] let buttonsOrientation: ButtonsOrientation let completion: ((btnPressed:Int) -> Void)? } func ==(lhs: Alert, rhs: Alert) -> Bool { return lhs.title == rhs.title && lhs.message == rhs.message } public typealias UserAction = ((buttonIndex: Int) -> Void) public class NAlertView: UIViewController, UIGestureRecognizerDelegate { // To manage the pending alerts static private var arrayAlerts: [Alert] = [] static private var isAlertShown: Bool = false //MARK: - Custom Properties /// The corner radious of the view public static var cornerRadius: Float = 4 /// The font of the title public static var titleFont: UIFont = UIFont.systemFontOfSize(22) /// The text color of title public static var titleColor = UIColor.blackColor() /// The alignment of the title public static var titleAlign = NSTextAlignment.Center /// The color of the separation line between title and message public static var separationColor = UIColor(red: 238.0/255.0, green: 242.0/255.0, blue: 244.0/255.0, alpha: 1.0) /// The font of the message public static var messageFont: UIFont = UIFont.systemFontOfSize(16) /// The text color of message public static var messageColor = UIColor.blackColor() /// The alignment of the message public static var messageAlign = NSTextAlignment.Center /// The font size of title of button public static var buttonFont: UIFont = UIFont.systemFontOfSize(16) /// The text color of title of default button public static var buttonDefaultTitleColor = UIColor.whiteColor() /// The text color of title of accept button public static var buttonAcceptTitleColor = UIColor.whiteColor() /// The text color of title of cance; button public static var buttonCancelTitleColor = UIColor.whiteColor() /// The background color for the default button public static var buttonDefaultBGColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) /// The background color for the accept button public static var buttonAcceptBGColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) /// The background color for the cancel button public static var buttonCancelBGColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) /// The height of button public static var buttonHeight: Float = 50 /// The corner radious of the button public static var buttonCornerRadius: Float = 0 /// The shadow of the button public static var buttonShadow: Float = 0 //MARK: - Const private let kBGTransparency: CGFloat = 0.43 private let kVerticalGap: CGFloat = 15.0 private let kWidthMargin: CGFloat = 20.0 private let kCancelButtonSpace: CGFloat = 4.0 private let kCancelButtonMargin: CGFloat = 7.0 private let kHeightMargin: CGFloat = 15.0 private let kContentWidth: CGFloat = 270.0 private let kContentHeightMargin: CGFloat = 20.0 private let kTitleLines: Int = 3 private let kButtonBaseTag: Int = 100 private let kButtonHoriSpace: CGFloat = 5.0 private let kButtonVertSpace: CGFloat = 5.0 private var titleLabelSpace: CGFloat = 0.0 private var separatorSpace: CGFloat = 10.0 private var messageTextViewSpace: CGFloat = 0.0 private var buttonsOrientation: ButtonsOrientation = .Horizontal //MARK: - View private var strongSelf: NAlertView? private var contentView = UIView() private var titleLabel: UILabel = UILabel() private var separatorView = UIView() private var messageLabel = UILabel() private var buttons: [UIButton] = [] private var userAction: UserAction? = nil //MARK: - Init public init() { super.init(nibName: nil, bundle: nil) self.view.frame = UIScreen.mainScreen().bounds self.view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] self.view.backgroundColor = UIColor(white: 0.0, alpha: kBGTransparency) strongSelf = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Private private func setupContentView() { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0) contentView.layer.cornerRadius = CGFloat(NAlertView.cornerRadius) contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0) contentView.layer.borderColor = UIColor.init(red: 204/255, green: 204/255, blue: 204/255, alpha: 1).CGColor self.view.addSubview(contentView) //Constraints let heightConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-margin-[contentView]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kContentHeightMargin], views: ["contentView": contentView]) for constraint in heightConstraints { constraint.priority = UILayoutPriorityDefaultHigh } self.view.addConstraints(heightConstraints) self.view.addConstraint(NSLayoutConstraint(item: contentView, attribute: .Leading , relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 20)) self.view.addConstraint(NSLayoutConstraint(item: view, attribute: .Trailing , relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1.0, constant: 20)) self.view.addConstraint(NSLayoutConstraint(item: contentView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) } private func addContentSubviewConstraints() { contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[label]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kWidthMargin], views: ["label": titleLabel])) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[textView]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kWidthMargin], views: ["textView": messageLabel])) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[separatorView]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kWidthMargin], views: ["separatorView": separatorView])) if buttons.count > 0 { let firstButton = buttons.first! let lastButton = buttons.last! if buttons.count == 2 && buttonsOrientation == .Horizontal { let firstButton = buttons.first! contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[firstButton]-space-[lastButton(==firstButton)]-margin-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: ["margin": kWidthMargin, "space": kButtonHoriSpace], views: ["firstButton": firstButton, "lastButton": lastButton])) } else { var previousButton: UIButton? = nil for button in buttons { contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[button]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kWidthMargin], views: ["button": button])) if button != firstButton { if let previousBtn = previousButton { let buttonSpace = kButtonVertSpace contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[previousButton]-space-[button]", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["space": buttonSpace], views: ["previousButton": previousBtn, "button": button])) } } previousButton = button } } contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-margin-[label]-titleSpaceUp-[separatorView]-titleSpaceDown-[textView]-textViewSpace-[button]", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kHeightMargin, "titleSpaceUp": titleLabelSpace, "titleSpaceDown": separatorSpace, "textViewSpace": messageTextViewSpace], views: ["label": titleLabel, "separatorView": separatorView, "textView": messageLabel, "button": firstButton])) let lastButtonMargin = kWidthMargin contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[button]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": lastButtonMargin], views: ["button": lastButton])) } else { // in case that title is nil the spaces should be the same if titleLabel.text == nil { separatorSpace = titleLabelSpace } contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-margin-[label]-titleSpaceUp-[separatorView]-titleSpaceDown-[textView]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": kHeightMargin, "titleSpaceUp": titleLabelSpace, "titleSpaceDown": separatorSpace], views: ["label": titleLabel, "separatorView": separatorView, "textView": messageLabel])) } titleLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Vertical) messageLabel.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Vertical) } private func setupTitleLabel(title: String?) { titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.numberOfLines = kTitleLines titleLabel.textAlignment = NAlertView.titleAlign titleLabel.text = title titleLabel.font = NAlertView.titleFont titleLabel.textColor = NAlertView.titleColor titleLabel.backgroundColor = UIColor.clearColor() contentView.addSubview(titleLabel) if let aTitle = title where aTitle.isEmpty == false { titleLabelSpace = kVerticalGap separatorView.backgroundColor = NAlertView.separationColor }else { } separatorView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(separatorView) // Separator height constraint separatorView.addConstraint(NSLayoutConstraint(item: separatorView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 1)) } private func setupMessage(message: String?) { messageLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.textAlignment = NAlertView.messageAlign messageLabel.text = message ?? "" messageLabel.font = NAlertView.messageFont messageLabel.textColor = NAlertView.messageColor messageLabel.numberOfLines = 0 messageLabel.backgroundColor = UIColor.clearColor() contentView.addSubview(messageLabel) if messageLabel.text?.isEmpty == false { messageTextViewSpace = kContentHeightMargin } } private func setupButtons(arrayButtons: [AlertButton]) { for button in arrayButtons { let btn = createButton(button) contentView.addSubview(btn) buttons.append(btn) } } private func createButton(alertButton: AlertButton) -> UIButton { let button: UIButton = UIButton(type: UIButtonType.Custom) button.translatesAutoresizingMaskIntoConstraints = false button.tag = kButtonBaseTag + buttons.count button.layer.cornerRadius = CGFloat(NAlertView.buttonCornerRadius) button.layer.masksToBounds = true button.setTitle(alertButton.title, forState: .Normal) button.titleLabel?.font = NAlertView.buttonFont switch alertButton.type { case .Accept: button.accessibilityValue = AlertButton.ButtonType.Accept.rawValue button.setTitleColor(NAlertView.buttonAcceptTitleColor, forState: .Normal) button.setBackgroundImage(NAlertView.buttonAcceptBGColor.image(), forState: .Normal) button.setBackgroundImage((NAlertView.buttonAcceptBGColor).darkerColor().image(), forState: .Highlighted) case .Cancel: button.accessibilityValue = AlertButton.ButtonType.Cancel.rawValue button.setTitleColor(NAlertView.buttonCancelTitleColor, forState: .Normal) button.setBackgroundImage(NAlertView.buttonCancelBGColor.image(), forState: .Normal) button.setBackgroundImage((NAlertView.buttonCancelBGColor).darkerColor().image(), forState: .Highlighted) case .Default: button.accessibilityValue = AlertButton.ButtonType.Default.rawValue button.setTitleColor(NAlertView.buttonDefaultTitleColor, forState: .Normal) button.setBackgroundImage(NAlertView.buttonDefaultBGColor.image(), forState: .Normal) button.setBackgroundImage((NAlertView.buttonDefaultBGColor).darkerColor().image(), forState: .Highlighted) } button.backgroundColor = UIColor.clearColor() button.addTarget(self, action: #selector(NAlertView.pressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) //Height constraints let buttonHeight = NAlertView.buttonHeight button.addConstraint(NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: CGFloat(buttonHeight))) return button } @objc private func pressed(sender: UIButton) { let index = sender.tag - kButtonBaseTag close(clickedAtIndex:index) } @objc private func backgroundTapped(sender: AnyObject) { close(clickedAtIndex: nil) } private func close(clickedAtIndex index: Int?) { UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.alpha = 0.0 }) { (Bool) -> Void in self.contentView.removeFromSuperview() self.contentView = UIView() self.view.removeFromSuperview() //Releasing strong refrence of itself. self.strongSelf = nil // Remove alert from quued and show next NAlertView.arrayAlerts.removeFirst() NAlertView.showNext() // Button completion if let action = self.userAction, let ind = index { action(buttonIndex: ind) } } } func dismissAlert(completion: ()->()) { UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.alpha = 0.0 }) { (Bool) -> Void in self.contentView.removeFromSuperview() self.contentView = UIView() self.view.removeFromSuperview() //Releasing strong refrence of itself. self.strongSelf = nil completion() } } /// Override this method to customize the animation of showing the alert view public func animateAlert() { view.alpha = 0 UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.alpha = 1.0 }) let animation = CAKeyframeAnimation(keyPath: "transform") animation.values = [NSValue(CATransform3D: CATransform3DMakeScale(0.95, 0.95, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(1.03, 1.03, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(0.98, 0.98, 0.0)), NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 0.0))] animation.keyTimes = [0, 2.0/4.0, 3.0/4.0, 1] animation.additive = true animation.duration = 0.4 self.contentView.layer.addAnimation(animation, forKey: "animation") } //MARK: - Show /** Shows a custom NAlertView - parameter title: The title of the alert. - parameter message: The message of the alert. - parameter buttons: An array of AlertButton that contains the title and the style of each button - parameter completion: The completion function to be executed after having tapped a button. If an alerts need to be shown while another alert is displayed, the second one will appear after having closed the first one. */ static func showAlertInQueue(title title: String?, message: String, buttons: [AlertButton], buttonsOrientation: ButtonsOrientation = .Horizontal, completion: ((btnPressed:Int) -> Void)? = nil) { var alert = Alert(title: "", message: message, buttonsTitle: buttons, buttonsOrientation: buttonsOrientation, completion: completion) if let titleAux = title { alert.title = titleAux } if (!arrayAlerts.contains(alert)) { arrayAlerts.append(alert) if !isAlertShown { showNext() } } } private static func showNext() { isAlertShown = true // check if there are alerts pending if (arrayAlerts.count > 0) { let alert = arrayAlerts[0] NAlertView().show(title: alert.title, message: alert.message, buttons: alert.buttonsTitle, buttonsOrientation: alert.buttonsOrientation, action: alert.completion) } else { isAlertShown = false } } public func show(title title: String? = nil, message: String?, buttons: [AlertButton], buttonsOrientation: ButtonsOrientation = .Horizontal, dismiss:Bool = true, action: UserAction? = nil) -> NAlertView? { let window: UIWindow = UIApplication.sharedApplication().keyWindow! window.addSubview(view) window.bringSubviewToFront(view) view.frame = window.bounds // background let viewBackground = UIView() viewBackground.backgroundColor = UIColor.clearColor() viewBackground.frame = view.frame view.addSubview(viewBackground) if dismiss { // Add tap recognizer to the background let tap = UITapGestureRecognizer(target: self, action: #selector(NAlertView.backgroundTapped(_:))) tap.delegate = self viewBackground.addGestureRecognizer(tap) } // Setup alert self.buttonsOrientation = buttonsOrientation self.userAction = action setupContentView() setupTitleLabel(title) setupMessage(message) setupButtons(buttons) addContentSubviewConstraints() // Show alert animateAlert() return self.strongSelf } } public struct AlertButton { enum ButtonType: String { case Default case Accept case Cancel } var title: String var type: ButtonType init(title: String? = nil, type: ButtonType) { if let tit = title { self.title = tit } else { switch type { case .Accept: self.title = NSLocalizedString("accept", comment: "Accept") case .Cancel: self.title = NSLocalizedString("cancel", comment: "Cancel") case .Default: self.title = NSLocalizedString("OK", comment: "OK") } } self.type = type } } extension UIColor { func darkerColor() -> UIColor { var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0 if self.getRed(&r, green: &g, blue: &b, alpha: &a){ return UIColor(red: max(r - 0.05, 0.0), green: max(g - 0.05, 0.0), blue: max(b - 0.05, 0.0), alpha: a) } return UIColor() } func image() -> UIImage { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, self.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
35cdb9f09000b493338756c23b152db5
41.648
484
0.645845
5.146995
false
false
false
false
mitchellporter/ios-animations
Animation/CubicBezier.swift
2
2839
import UIKit /* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. This licensed material is licensed under the Apache 2.0 license. http://www.apache.org/licenses/LICENSE-2.0. */ class CubicBezier: NSObject { let cx: CGFloat, bx: CGFloat, ax: CGFloat, cy: CGFloat, by: CGFloat, ay: CGFloat init(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) { let normalizedPoint = CGPointZero; var p1 = CGPointZero var p2 = CGPointZero // Clamp to interval [0..1] p1.x = max(0.0, min(1.0, x1)) p1.y = max(0.0, min(1.0, y1)) p2.x = max(0.0, min(1.0, x2)) p2.y = max(0.0, min(1.0, y2)) // Implicit first and last control points are (0,0) and (1,1). cx = 3.0 * p1.x bx = 3.0 * (p2.x - p1.x) - cx ax = 1.0 - cx - bx cy = 3.0 * p1.y by = 3.0 * (p2.y - p1.y) - cy ay = 1.0 - cy - by } func valueForX(x: CGFloat) -> CGFloat { let epsilon: CGFloat = 1.0 / 200.0 let xSolved = solveCurveX(x, epsilon: epsilon) let y = sampleCurveY(xSolved) return y; } func solveCurveX(x: CGFloat, epsilon: CGFloat) -> CGFloat { var t0: CGFloat, t1: CGFloat, t2: CGFloat, x2: CGFloat, d2: CGFloat var i: Int = 0; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x if (fabs(x2) < epsilon) { return t2; } d2 = sampleCurveDerivativeX(t2) if (fabs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } // Fall back to the bisection method for reliability. t0 = 0.0; t1 = 1.0; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2) if (fabs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) * 0.5 + t0; } // Failure. return t2; } func sampleCurveX(t: CGFloat) -> CGFloat { // 'ax t^3 + bx t^2 + cx t' expanded using Horner's rule. return ((ax * t + bx) * t + cx) * t; } func sampleCurveY(t: CGFloat) -> CGFloat { return ((ay * t + by) * t + cy) * t; } func sampleCurveDerivativeX(t: CGFloat) -> CGFloat { return (3.0 * ax * t + 2.0 * bx) * t + cx; } }
apache-2.0
2821de3b72007a411964233670a5aff5
24.8
108
0.442565
3.350649
false
false
false
false
zhangliangzhi/iosStudyBySwift
xxcolor/Pods/SwiftyStoreKit/SwiftyStoreKit/ProductsInfoController.swift
2
2654
// // ProductsInfoController.swift // SwiftyStoreKit // // Copyright (c) 2015 Andrea Bizzotto ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import StoreKit class ProductsInfoController: NSObject { // MARK: Private declarations // As we can have multiple inflight queries and purchases, we store them in a dictionary by product id private var inflightQueries: [Set<String>: InAppProductQueryRequest] = [:] private(set) var products: [String: SKProduct] = [:] private func addProduct(_ product: SKProduct) { products[product.productIdentifier] = product } private func allProductsMatching(_ productIds: Set<String>) -> Set<SKProduct> { return Set(productIds.flatMap { self.products[$0] }) } private func requestProducts(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) { inflightQueries[productIds] = InAppProductQueryRequest.startQuery(productIds) { result in self.inflightQueries[productIds] = nil for product in result.retrievedProducts { self.addProduct(product) } completion(result) } } func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) { let products = allProductsMatching(productIds) guard products.count == productIds.count else { requestProducts(productIds, completion: completion) return } completion(RetrieveResults(retrievedProducts: products, invalidProductIDs: [], error: nil)) } }
mit
1ad207a5531a50ec468bd1d2fc3b4d4f
37.463768
110
0.71364
4.834244
false
false
false
false
TLOpenSpring/TLTranstionLib-swift
TLTranstionLib-swift/Classes/Animator/TLCardAnimator.swift
1
5439
// // TLCardAnimator.swift // Pods // // Created by Andrew on 16/5/31. // // import UIKit /// 卡片动画 public class TLCardAnimator: TLBaseAnimator { func getAnimatorDuration() -> NSTimeInterval { if(self.animatorDuration < 1){ self.animatorDuration = 1 } return animatorDuration } public override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let model = TransitionModel(context: transitionContext) // if(self.operaiton == .Push){ // pushOperation(model, context: transitionContext) // }else if(self.operaiton == .Pop){ // popOperation(model, context: transitionContext) // }else{ // super.animateTransition(transitionContext) // } if(self.isPositiveAnimation == true){ pushOperation(model, context: transitionContext) }else{ popOperation(model, context: transitionContext) } } /** 推送到下一个控制器 - parameter model: 模型 - parameter context: 转场的上下文 */ override func pushOperation(model: TransitionModel, context: UIViewControllerContextTransitioning) { let frame = model.fromView.frame var offScreenFrame = frame offScreenFrame.origin.y = offScreenFrame.height model.toView.frame = offScreenFrame //插入视图 model.containerView.insertSubview(model.toView, aboveSubview: model.fromView) let t1 = self.firstTransform() let t2 = self.secondTransformWithView(model.fromView) UIView.animateKeyframesWithDuration(getAnimatorDuration(), delay: 0, options: .CalculationModeLinear, animations: { //动画step1 UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.4, animations: { model.fromView.layer.transform = t1 model.fromView.alpha = 0.6 }) //动画step2 UIView.addKeyframeWithRelativeStartTime(0.2, relativeDuration: 0.4, animations: { model.fromView.layer.transform = t2 }) //动画step3 UIView.addKeyframeWithRelativeStartTime(0.6, relativeDuration: 0.2, animations: { model.toView.frame = CGRectOffset(model.toView.frame, 0, -30) }) //动画step4 UIView.addKeyframeWithRelativeStartTime(0.6, relativeDuration: 0.3, animations: { model.toView.frame = frame }) }) { (finished) in model.fromView.frame = frame context.completeTransition(!context.transitionWasCancelled()) } } /** 回滚 - parameter model: 模型 - parameter context: 转场的上下文 */ override func popOperation(model: TransitionModel, context: UIViewControllerContextTransitioning) { let frame = model.fromView.frame model.toView.frame = frame let scale = CATransform3DIdentity model.toView.layer.transform = CATransform3DScale(scale, 0.6, 0.6, 1) model.toView.alpha = 0.6 model.containerView.insertSubview(model.toView, belowSubview: model.fromView) var frameOffsetScreen = frame frameOffsetScreen.origin.y = frame.size.height let t1 = self.firstTransform() UIView.animateKeyframesWithDuration(getAnimatorDuration(), delay: 0, options: .CalculationModeLinear, animations: { //动画step1 UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.3, animations: { model.fromView.frame = frameOffsetScreen }) //动画step2 UIView.addKeyframeWithRelativeStartTime(0.35, relativeDuration: 0.35, animations: { model.toView.layer.transform = t1 model.toView.alpha = 1 }) //动画step3 UIView.addKeyframeWithRelativeStartTime(0.75, relativeDuration: 0.25, animations: { model.toView.layer.transform = CATransform3DIdentity }) }) { (finished) in if context.transitionWasCancelled(){ model.toView.layer.transform = CATransform3DIdentity model.toView.alpha = 1 } context.completeTransition(!context.transitionWasCancelled()) } } //MARK: - Helper Methods func firstTransform() -> CATransform3D { var t1 = CATransform3DIdentity //设置透明度 t1.m34 = 1/900 t1 = CATransform3DScale(t1, 0.95, 0.95, 1) //在x轴上旋转15度 t1 = CATransform3DRotate(t1, 15 * CGFloat(M_PI)/180.0, 1, 0, 0) return t1 } func secondTransformWithView(view:UIView) -> CATransform3D { var t2 = CATransform3DIdentity t2.m34 = self.firstTransform().m34; //在y轴和Z轴上移动 t2 = CATransform3DTranslate(t2, 0, view.frame.size.height * -0.08, view.frame.size.height * -0.08); t2 = CATransform3DScale(t2, 0.8, 0.8, 1) return t2 } }
mit
1746fe6caf44a0651ac689ef833e7837
30.766467
123
0.578888
4.783589
false
false
false
false
wibosco/SwiftPaginationCoreData-Example
SwiftPaginationCoreDataExample/Model/ManagedObjects/Feed.swift
1
1078
// // Feed.swift // SwiftPaginationCoreDataExample // // Created by Home on 28/02/2016. // Copyright © 2016 Boles. All rights reserved. // import Foundation import CoreData import CoreDataServices let kStackOverflowQuestionsBaseURL: NSString = "https://api.stackexchange.com/2.2/questions?order=desc&sort=creation&site=stackoverflow" class Feed: NSManagedObject { //MARK: QuestionFeed class func questionFeed() -> Feed? { return Feed.questionFeed(ServiceManager.sharedInstance.mainManagedObjectContext) } class func questionFeed(managedObjectContext: NSManagedObjectContext) -> Feed? { return managedObjectContext.retrieveFirstEntry(Feed.self) as? Feed } //MARK: Pages func orderedPages() -> NSArray { let indexSort = NSSortDescriptor(key: "index", ascending: true) return (self.pages?.sortedArrayUsingDescriptors([indexSort]))! } func addPage(page: Page) { let mutablePages = self.mutableSetValueForKey("pages") mutablePages.addObject(page) } }
mit
dcab16755ab81c2a32cd0a64f2431d43
25.925
136
0.694522
4.432099
false
false
false
false
MangoMade/MMNavigationController
Example/Example/ViewController.swift
1
4170
// // ViewController.swift // MMNavigationController // // Created by Mango on 2016/11/10. // Copyright © 2016年 MangoMade. All rights reserved. // import UIKit import MMNavigationController class BaseViewController: UIViewController { let nextButton = UIButton(type: .system) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGray view.addSubview(nextButton) nextButton.setTitle("To next page", for: UIControlState()) nextButton.sizeToFit() nextButton.center = Screen.center nextButton.addTarget(self, action: #selector(reponseToNext(_:)), for: .touchUpInside) } @objc func reponseToNext(_ sender: UIButton) { } } class NormalViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() title = "Normal" } override func reponseToNext(_ sender: UIButton) { navigationController?.pushViewController(RandomColorViewController(), animated: true) } } class RandomColorViewController: BaseViewController { var delegate: TestDelegate? = TestDelegate() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white title = "Random Color" mm.navigationBarBackgroundColor = UIColor.random mm.popGestrueEnableWidth = 150 mm.navigationBarTitleColor = UIColor.white mm.gestureDelegate = delegate let gestureEnableLabel = UILabel() gestureEnableLabel.numberOfLines = 0 gestureEnableLabel.textAlignment = .center gestureEnableLabel.text = "pop手势\n\n灰色区域内\n\n有效" gestureEnableLabel.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3) gestureEnableLabel.frame = CGRect(x: 0, y: 0, width: mm.popGestrueEnableWidth, height: view.bounds.height) view.addSubview(gestureEnableLabel) let scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 100, width: Screen.width, height: 100) scrollView.backgroundColor = .gray scrollView.contentSize = CGSize(width: Screen.width * 2, height: 100) view.addSubview(scrollView) } override func reponseToNext(_ sender: UIButton) { navigationController?.pushViewController(HiddenBarViewController(), animated: true) } } class TestDelegate: NSObject { } extension TestDelegate: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } class HiddenBarViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() mm.navigationBarHidden = true let scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 100, width: Screen.width, height: 100) scrollView.backgroundColor = .gray scrollView.contentSize = CGSize(width: Screen.width * 2, height: 100) view.addSubview(scrollView) } override func reponseToNext(_ sender: UIButton) { navigationController?.pushViewController(NormalViewController(), animated: true) } } extension UIColor { static var random: UIColor { let randR = CGFloat(arc4random_uniform(255)) / 255.0 let randG = CGFloat(arc4random_uniform(255)) / 255.0 let randB = CGFloat(arc4random_uniform(255)) / 255.0 return UIColor(red: randR, green: randG, blue: randB, alpha: 1) } } extension UIImage { static func imageWithColor(_ color: UIColor) -> UIImage { let size = CGSize(width: 1, height: 1) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
mit
beba495a07b60a9e4664e83eec25c6af
28.848921
148
0.659436
4.841307
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/Model/Schema/Order.swift
1
1764
// // Order.swift // MyApp // // Created by AST on 8/17/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import ObjectMapper enum OrderStatus: String { case new case cancelled case processing case processed case paid case delivered var title: String { switch self { case .new: return "New" case .cancelled: return "Cancelled" case .processing: return "Processing" case .processed: return "Processed" case .paid: return "Paid" case .delivered: return "Delivered" } } var icon: UIImage { switch self { case .new: return #imageLiteral(resourceName: "ic_new") case .cancelled: return #imageLiteral(resourceName: "ic_cancelgreen") case .paid: return #imageLiteral(resourceName: "ic_paid") case .delivered: return #imageLiteral(resourceName: "ic_delivered") case .processing: return #imageLiteral(resourceName: "ic_orderprocessing") case .processed: return #imageLiteral(resourceName: "ic_ok") } } } final class Order: Mappable { var time = "" var id = 0 var shopId = 0 var typeRaw = "" var status: OrderStatus { set { typeRaw = newValue.rawValue } get { guard let orderState = OrderStatus(rawValue: typeRaw) else { return .new } return orderState } } init?(map: Map) {} init() {} func mapping(map: Map) { time <- map["updatedAt"] id <- map["id"] typeRaw <- map["orderState.name"] shopId <- map["shop.id"] } }
mit
c89f6782b4afbd4f6440ee4b1ebf0ac2
21.896104
82
0.551333
4.321078
false
false
false
false
RishabhTayal/GHReleases
GHReleases/AppDelegate.swift
1
3929
// // AppDelegate.swift // GHReleases // // Created by Tayal, Rishabh on 6/26/17. // Copyright © 2017 Tayal, Rishabh. All rights reserved. // import UIKit import UserNotifications import MWFeedParser @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) let center = UNUserNotificationCenter.current() let options: UNAuthorizationOptions = [.alert, .sound, .badge] center.requestAuthorization(options: options) { (s, e) in } let repo = Repository.instance(dict: ["name": "GHReleases", "owner": "RishabhTayal"]) UserDefaults.storeRepo(repository: repo) return true } //TODO: implement tap handle // func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) { // switch response.actionIdentifier { // case UNNotificationDismissActionIdentifier: // break // case UNNotificationDefaultActionIdentifier: // print("opened" + response.description) // break // default: break // } // completionHandler() // } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let repos = UserDefaults.standard.array(forKey: UserDefaultsKey.Repositories) { var apiCompletionCount = 0 for repoObj in repos { let repo = Repository.instance(dict: repoObj as! [String : Any]) fetchData(repository: repo) { (d, e) in DispatchQueue.main.async { apiCompletionCount += 1 if repo.version != d?.first?.title { self.triggerLocalNotification(repository: repo, version: (d?.first?.title)!) repo.version = d?.first?.title UserDefaults.storeRepo(repository: repo) } else { #if DEBUG self.triggerLocalNotification(repository: repo, version: (d?.first?.title)!) #endif } if apiCompletionCount == repos.count { completionHandler(UIBackgroundFetchResult.newData) } } } } } else { completionHandler(.noData) } } func fetchData(repository: Repository, completion: @escaping ServiceCaller.CompletionBlock) { ServiceCaller().makeCall(repository: repository.owner + "/" + repository.name) { (items, error) in completion(items, error) } } func triggerLocalNotification(repository: Repository, version: String) { let content = UNMutableNotificationContent() content.title = "New release available" content.subtitle = version content.body = repository.owner + " released a new release for " + repository.name content.sound = .default() content.userInfo = repository.toJSON() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let identifier = repository.owner + "/" + repository.name let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (e) in } } }
mit
230751793224e5a9cfb1f331e23ee026
39.494845
185
0.60056
5.579545
false
false
false
false
karwa/swift-corelibs-foundation
Foundation/NSData.swift
2
35815
// 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 #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public struct NSDataReadingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let dataReadingMappedIfSafe = NSDataReadingOptions(rawValue: UInt(1 << 0)) public static let dataReadingUncached = NSDataReadingOptions(rawValue: UInt(1 << 1)) public static let dataReadingMappedAlways = NSDataReadingOptions(rawValue: UInt(1 << 2)) } public struct NSDataWritingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let dataWritingAtomic = NSDataWritingOptions(rawValue: UInt(1 << 0)) public static let dataWritingWithoutOverwriting = NSDataWritingOptions(rawValue: UInt(1 << 1)) } public struct NSDataSearchOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let backwards = NSDataSearchOptions(rawValue: UInt(1 << 0)) public static let anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } public struct NSDataBase64EncodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let encoding64CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 0)) public static let encoding76CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 1)) public static let encodingEndLineWithCarriageReturn = NSDataBase64EncodingOptions(rawValue: UInt(1 << 4)) public static let encodingEndLineWithLineFeed = NSDataBase64EncodingOptions(rawValue: UInt(1 << 5)) } public struct NSDataBase64DecodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ignoreUnknownCharacters = NSDataBase64DecodingOptions(rawValue: UInt(1 << 0)) public static let anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } private final class _NSDataDeallocator { var handler: (UnsafeMutablePointer<Void>, Int) -> Void = {_,_ in } } private let __kCFMutable: CFOptionFlags = 0x01 private let __kCFGrowable: CFOptionFlags = 0x02 private let __kCFMutableVarietyMask: CFOptionFlags = 0x03 private let __kCFBytesInline: CFOptionFlags = 0x04 private let __kCFUseAllocator: CFOptionFlags = 0x08 private let __kCFDontDeallocate: CFOptionFlags = 0x10 private let __kCFAllocatesCollectable: CFOptionFlags = 0x20 public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { typealias CFType = CFData private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 private var _deallocator: UnsafeMutablePointer<Void>? = nil // for CF only private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift private var _bytes: UnsafeMutablePointer<UInt8>? = nil internal var _cfObject: CFType { if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { return unsafeBitCast(self, to: CFType.self) } else { return CFDataCreate(kCFAllocatorSystemDefault, UnsafePointer<UInt8>(self.bytes), self.length) } } public override required convenience init() { let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer<Void>.self) self.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } public override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } public override func isEqual(_ object: AnyObject?) -> Bool { if let data = object as? NSData { return self.isEqual(to: data) } else { return false } } deinit { if let allocatedBytes = _bytes { _deallocHandler?.handler(allocatedBytes, _length) } if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { _CFDeinit(self._cfObject) } } internal init(bytes: UnsafeMutablePointer<Void>?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init() let options : CFOptionFlags = (self.dynamicType == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0 if copy { _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, UnsafeMutablePointer<UInt8>(bytes), length, false) if let handler = deallocator { handler(bytes!, length) } } else { if let handler = deallocator { _deallocHandler!.handler = handler } // The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, UnsafeMutablePointer<UInt8>(bytes), length, true) } } public var length: Int { return CFDataGetLength(_cfObject) } public var bytes: UnsafePointer<Void> { return UnsafePointer<Void>(CFDataGetBytePtr(_cfObject)) } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(_ zone: NSZone) -> AnyObject { return self } public override func mutableCopy() -> AnyObject { return mutableCopyWithZone(nil) } public func mutableCopyWithZone(_ zone: NSZone) -> AnyObject { return NSMutableData(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public func encodeWithCoder(_ aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.data") } else { aCoder.encodeBytes(UnsafePointer<UInt8>(self.bytes), length: self.length) } } public required convenience init?(coder aDecoder: NSCoder) { if !aDecoder.allowsKeyedCoding { if let data = aDecoder.decodeDataObject() { self.init(data: data) } else { return nil } } else if aDecoder.dynamicType == NSKeyedUnarchiver.self || aDecoder.containsValueForKey("NS.data") { guard let data = aDecoder._decodePropertyListForKey("NS.data") as? NSData else { return nil } self.init(data: data) } else { var len = 0 let bytes = aDecoder.decodeBytesForKey("NS.bytes", returnedLength: &len) self.init(bytes: bytes, length: len) } } public static func supportsSecureCoding() -> Bool { return true } private func byteDescription(limit: Int? = nil) -> String { var s = "" let buffer = UnsafePointer<UInt8>(bytes) var i = 0 while i < self.length { if i > 0 && i % 4 == 0 { // if there's a limit, and we're at the barrier where we'd add the ellipses, don't add a space. if let limit = limit where self.length > limit && i == self.length - (limit / 2) { /* do nothing */ } else { s += " " } } let byte = buffer[i] var byteStr = String(byte, radix: 16, uppercase: false) if byte <= 0xf { byteStr = "0\(byteStr)" } s += byteStr // if we've hit the midpoint of the limit, skip to the last (limit / 2) bytes. if let limit = limit where self.length > limit && i == (limit / 2) - 1 { s += " ... " i = self.length - (limit / 2) } else { i += 1 } } return s } override public var debugDescription: String { return "<\(byteDescription(limit: 1024))>" } override public var description: String { return "<\(byteDescription())>" } override public var _cfTypeID: CFTypeID { return CFDataGetTypeID() } } extension NSData { public convenience init(bytes: UnsafePointer<Void>?, length: Int) { self.init(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int) { self.init(bytes: bytes, length: length, copy: false, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, freeWhenDone b: Bool) { self.init(bytes: bytes, length: length, copy: false) { buffer, length in if b { free(buffer) } } } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { self.init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } internal struct NSDataReadResult { var bytes: UnsafeMutablePointer<Void> var length: Int var deallocator: ((buffer: UnsafeMutablePointer<Void>, length: Int) -> Void)? } internal static func readBytesFromFileWithExtendedAttributes(_ path: String, options: NSDataReadingOptions) throws -> NSDataReadResult { let fd = _CFOpenFile(path, O_RDONLY) if fd < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } defer { close(fd) } var info = stat() let ret = withUnsafeMutablePointer(&info) { infoPointer -> Bool in if fstat(fd, infoPointer) < 0 { return false } return true } if !ret { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let length = Int(info.st_size) if options.contains(.dataReadingMappedAlways) { let data = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0) // Swift does not currently expose MAP_FAILURE if data != UnsafeMutablePointer<Void>(bitPattern: -1) { return NSDataReadResult(bytes: data!, length: length) { buffer, length in munmap(buffer, length) } } } let data = malloc(length)! var remaining = Int(info.st_size) var total = 0 while remaining > 0 { let amt = read(fd, data.advanced(by: total), remaining) if amt < 0 { break } remaining -= amt total += amt } if remaining != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } return NSDataReadResult(bytes: data, length: length) { buffer, length in free(buffer) } } public convenience init(contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions) throws { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } public convenience init?(contentsOfFile path: String) { do { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: []) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } catch { return nil } } public convenience init(data: NSData) { self.init(bytes:data.bytes, length: data.length) } public convenience init(contentsOfURL url: NSURL, options readOptionsMask: NSDataReadingOptions) throws { if url.fileURL { try self.init(contentsOfFile: url.path!, options: readOptionsMask) } else { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let cond = NSCondition() var resError: NSError? var resData: NSData? let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in resData = data resError = error cond.broadcast() }) task.resume() cond.wait() if resData == nil { throw resError! } self.init(data: resData!) } } public convenience init?(contentsOfURL url: NSURL) { do { try self.init(contentsOfURL: url, options: []) } catch { return nil } } } extension NSData { public func getBytes(_ buffer: UnsafeMutablePointer<Void>, length: Int) { CFDataGetBytes(_cfObject, CFRangeMake(0, length), UnsafeMutablePointer<UInt8>(buffer)) } public func getBytes(_ buffer: UnsafeMutablePointer<Void>, range: NSRange) { CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), UnsafeMutablePointer<UInt8>(buffer)) } public func isEqual(to other: NSData) -> Bool { if self === other { return true } if length != other.length { return false } let bytes1 = bytes let bytes2 = other.bytes if bytes1 == bytes2 { return true } return memcmp(bytes1, bytes2, length) == 0 } public func subdata(with range: NSRange) -> NSData { if range.length == 0 { return NSData() } if range.location == 0 && range.length == self.length { return copyWithZone(nil) as! NSData } return NSData(bytes: bytes.advanced(by: range.location), length: range.length) } internal func makeTemporaryFileInDirectory(_ dirPath: String) throws -> (Int32, String) { let template = dirPath._nsObject.stringByAppendingPathComponent("tmp.XXXXXX") let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: maxLength) template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dirPath) } let pathResult = NSFileManager.defaultManager().string(withFileSystemRepresentation:buf, length: Int(strlen(buf))) return (fd, pathResult) } internal class func writeToFileDescriptor(_ fd: Int32, path: String? = nil, buf: UnsafePointer<Void>, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int repeat { #if os(OSX) || os(iOS) bytesWritten = Darwin.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #elseif os(Linux) bytesWritten = Glibc.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #endif } while (bytesWritten < 0 && errno == EINTR) if bytesWritten <= 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else { bytesRemaining -= bytesWritten } } } public func write(toFile path: String, options writeOptionsMask: NSDataWritingOptions = []) throws { var fd : Int32 var mode : mode_t? = nil let useAuxiliaryFile = writeOptionsMask.contains(.dataWritingAtomic) var auxFilePath : String? = nil if useAuxiliaryFile { // Preserve permissions. var info = stat() if lstat(path, &info) == 0 { mode = info.st_mode } else if errno != ENOENT && errno != ENAMETOOLONG { throw _NSErrorWithErrno(errno, reading: false, path: path) } let (newFD, path) = try self.makeTemporaryFileInDirectory(path._nsObject.stringByDeletingLastPathComponent) fd = newFD auxFilePath = path fchmod(fd, 0o666) } else { var flags = O_WRONLY | O_CREAT | O_TRUNC if writeOptionsMask.contains(.dataWritingWithoutOverwriting) { flags |= O_EXCL } fd = _CFOpenFileWithMode(path, flags, 0o666) } if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } defer { close(fd) } try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in if range.length > 0 { do { try NSData.writeToFileDescriptor(fd, path: path, buf: buf, length: range.length) if fsync(fd) < 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } catch let err { if let auxFilePath = auxFilePath { do { try NSFileManager.defaultManager().removeItem(atPath: auxFilePath) } catch _ {} } throw err } } } if let auxFilePath = auxFilePath { if rename(auxFilePath, path) != 0 { do { try NSFileManager.defaultManager().removeItem(atPath: auxFilePath) } catch _ {} throw _NSErrorWithErrno(errno, reading: false, path: path) } if let mode = mode { chmod(path, mode) } } } public func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { do { try write(toFile: path, options: useAuxiliaryFile ? .dataWritingAtomic : []) } catch { return false } return true } public func write(to url: NSURL, atomically: Bool) -> Bool { if url.fileURL { if let path = url.path { return write(toFile: path, atomically: atomically) } } return false } /// Write the contents of the receiver to a location specified by the given file URL. /// /// - parameter url: The location to which the receiver’s contents will be written. /// - parameter writeOptionsMask: An option set specifying file writing options. /// /// - throws: This method returns Void and is marked with the `throws` keyword to indicate that it throws an error in the event of failure. /// /// This method is invoked in a `try` expression and the caller is responsible for handling any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42) in [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097) and [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) in [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216). public func write(to url: NSURL, options writeOptionsMask: NSDataWritingOptions = []) throws { guard let path = url.path where url.fileURL == true else { let userInfo = [NSLocalizedDescriptionKey : "The folder at “\(url)” does not exist or is not a file URL.", // NSLocalizedString() not yet available NSURLErrorKey : url.absoluteString ?? ""] as Dictionary<String, Any> throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: userInfo) } try write(toFile: path, options: writeOptionsMask) } public func range(of dataToFind: NSData, options mask: NSDataSearchOptions = [], in searchRange: NSRange) -> NSRange { guard dataToFind.length > 0 else {return NSRange(location: NSNotFound, length: 0)} guard let searchRange = searchRange.toRange() else {fatalError("invalid range")} precondition(searchRange.endIndex <= self.length, "range outside the bounds of data") let baseData = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(self.bytes), count: self.length)[searchRange] let search = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(dataToFind.bytes), count: dataToFind.length) let location : Int? let anchored = mask.contains(.anchored) if mask.contains(.backwards) { location = NSData.searchSubSequence(search.reversed(), inSequence: baseData.reversed(),anchored : anchored).map {$0.base-search.count} } else { location = NSData.searchSubSequence(search, inSequence: baseData,anchored : anchored) } return location.map {NSRange(location: $0, length: search.count)} ?? NSRange(location: NSNotFound, length: 0) } private static func searchSubSequence<T : Collection, T2 : Sequence where T.Iterator.Element : Equatable, T.Iterator.Element == T2.Iterator.Element, T.SubSequence.Iterator.Element == T.Iterator.Element, T.Indices.Iterator.Element == T.Index>(_ subSequence : T2, inSequence seq: T,anchored : Bool) -> T.Index? { for index in seq.indices { if seq.suffix(from: index).starts(with: subSequence) { return index } if anchored {return nil} } return nil } internal func enumerateByteRangesUsingBlockRethrows(_ block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws { var err : ErrorProtocol? = nil self.enumerateBytes() { (buf, range, stop) -> Void in do { try block(buf, range, stop) } catch let e { err = e } } if let err = err { throw err } } public func enumerateBytes(_ block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) -> Void) { var stop = false withUnsafeMutablePointer(&stop) { stopPointer in block(bytes, NSMakeRange(0, length), stopPointer) } } } extension NSData : _CFBridgable { } extension CFData : _NSBridgable { typealias NSType = NSData internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } } extension NSMutableData { internal var _cfMutableObject: CFMutableData { return unsafeBitCast(self, to: CFMutableData.self) } } public class NSMutableData : NSData { public required convenience init() { self.init(bytes: nil, length: 0) } internal override init(bytes: UnsafeMutablePointer<Void>?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } public var mutableBytes: UnsafeMutablePointer<Void> { return UnsafeMutablePointer(CFDataGetMutableBytePtr(_cfMutableObject)) } public override var length: Int { get { return CFDataGetLength(_cfObject) } set { CFDataSetLength(_cfMutableObject, newValue) } } public override func copyWithZone(_ zone: NSZone) -> AnyObject { return NSData(data: self) } } extension NSData { /* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64Encoded base64String: String, options: NSDataBase64DecodingOptions) { let encodedBytes = Array(base64String.utf8) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ public func base64EncodedString(_ options: NSDataBase64EncodingOptions = []) -> String { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) let characters = encodedBytes.map { Character(UnicodeScalar($0)) } return String(characters) } /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64Encoded base64Data: NSData, options: NSDataBase64DecodingOptions) { var encodedBytes = [UInt8](repeating: 0, count: base64Data.length) base64Data.getBytes(&encodedBytes, length: encodedBytes.count) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ public func base64EncodedData(_ options: NSDataBase64EncodingOptions = []) -> NSData { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) return NSData(bytes: encodedBytes, length: encodedBytes.count) } /** The ranges of ASCII characters that are used to encode data in Base64. */ private static let base64ByteMappings: [Range<UInt8>] = [ 65 ..< 91, // A-Z 97 ..< 123, // a-z 48 ..< 58, // 0-9 43 ..< 44, // + 47 ..< 48, // / ] /** Padding character used when the number of bytes to encode is not divisible by 3 */ private static let base64Padding : UInt8 = 61 // = /** This method takes a byte with a character from Base64-encoded string and gets the binary value that the character corresponds to. - parameter byte: The byte with the Base64 character. - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) */ private enum Base64DecodedByte { case Valid(UInt8) case Invalid case Padding } private static func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { guard byte != base64Padding else {return .Padding} var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { let result = decodedStart + (byte - range.lowerBound) return .Valid(result) } decodedStart += range.upperBound - range.lowerBound } return .Invalid } /** This method takes six bits of binary data and encodes it as a character in Base64. The value in the byte must be less than 64, because a Base64 character can only represent 6 bits. - parameter byte: The byte to encode - returns: The ASCII value for the encoded character. */ private static func base64EncodeByte(_ byte: UInt8) -> UInt8 { assert(byte < 64) var decodedStart: UInt8 = 0 for range in base64ByteMappings { let decodedRange = decodedStart ..< decodedStart + (range.upperBound - range.lowerBound) if decodedRange.contains(byte) { return range.lowerBound + (byte - decodedStart) } decodedStart += range.upperBound - range.lowerBound } return 0 } /** This method decodes Base64-encoded data. If the input contains any bytes that are not valid Base64 characters, this will return nil. - parameter bytes: The Base64 bytes - parameter options: Options for handling invalid input - returns: The decoded bytes. */ private static func base64DecodeBytes(_ bytes: [UInt8], options: NSDataBase64DecodingOptions = []) -> [UInt8]? { var decodedBytes = [UInt8]() decodedBytes.reserveCapacity((bytes.count/3)*2) var currentByte : UInt8 = 0 var validCharacterCount = 0 var paddingCount = 0 var index = 0 for base64Char in bytes { let value : UInt8 switch base64DecodeByte(base64Char) { case .Valid(let v): value = v validCharacterCount += 1 case .Invalid: if options.contains(.ignoreUnknownCharacters) { continue } else { return nil } case .Padding: paddingCount += 1 continue } //padding found in the middle of the sequence is invalid if paddingCount > 0 { return nil } switch index%4 { case 0: currentByte = (value << 2) case 1: currentByte |= (value >> 4) decodedBytes.append(currentByte) currentByte = (value << 4) case 2: currentByte |= (value >> 2) decodedBytes.append(currentByte) currentByte = (value << 6) case 3: currentByte |= value decodedBytes.append(currentByte) default: fatalError() } index += 1 } guard (validCharacterCount + paddingCount)%4 == 0 else { //invalid character count return nil } return decodedBytes } /** This method encodes data in Base64. - parameter bytes: The bytes you want to encode - parameter options: Options for formatting the result - returns: The Base64-encoding for those bytes. */ private static func base64EncodeBytes(_ bytes: [UInt8], options: NSDataBase64EncodingOptions = []) -> [UInt8] { var result = [UInt8]() result.reserveCapacity((bytes.count/3)*4) let lineOptions : (lineLength : Int, separator : [UInt8])? = { let lineLength: Int if options.contains(.encoding64CharacterLineLength) { lineLength = 64 } else if options.contains(.encoding76CharacterLineLength) { lineLength = 76 } else { return nil } var separator = [UInt8]() if options.contains(.encodingEndLineWithCarriageReturn) { separator.append(13) } if options.contains(.encodingEndLineWithLineFeed) { separator.append(10) } //if the kind of line ending to insert is not specified, the default line ending is Carriage Return + Line Feed. if separator.count == 0 {separator = [13,10]} return (lineLength,separator) }() var currentLineCount = 0 let appendByteToResult : (UInt8) -> () = { result.append($0) currentLineCount += 1 if let options = lineOptions where currentLineCount == options.lineLength { result.append(contentsOf: options.separator) currentLineCount = 0 } } var currentByte : UInt8 = 0 for (index,value) in bytes.enumerated() { switch index%3 { case 0: currentByte = (value >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 6) >> 2) case 1: currentByte |= (value >> 4) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 4) >> 2) case 2: currentByte |= (value >> 6) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 2) >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) default: fatalError() } } //add padding switch bytes.count%3 { case 0: break //no padding needed case 1: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) appendByteToResult(self.base64Padding) case 2: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) default: fatalError() } return result } } extension NSMutableData { public func append(_ bytes: UnsafePointer<Void>, length: Int) { CFDataAppendBytes(_cfMutableObject, UnsafePointer<UInt8>(bytes), length) } public func append(_ other: NSData) { append(other.bytes, length: other.length) } public func increaseLength(by extraLength: Int) { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } public func replaceBytes(in range: NSRange, withBytes bytes: UnsafePointer<Void>) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), length) } public func resetBytes(in range: NSRange) { bzero(mutableBytes.advanced(by: range.location), range.length) } public func setData(_ data: NSData) { length = data.length replaceBytes(in: NSMakeRange(0, data.length), withBytes: data.bytes) } public func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafePointer<Void>, length replacementLength: Int) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), replacementLength) } } extension NSMutableData { public convenience init?(capacity: Int) { self.init(bytes: nil, length: 0) } public convenience init?(length: Int) { let memory = malloc(length) self.init(bytes: memory, length: length, copy: false) { buffer, amount in free(buffer) } } }
apache-2.0
1767c06910defea6a0223a5df830aad8
38.178337
924
0.601413
4.846914
false
false
false
false
PrashantMangukiya/SwiftCoreImageFilter
SwiftCoreImageFilter/SwiftCoreImageFilter/ViewController.swift
1
12186
// // ViewController.swift // SwiftCoreImageFilter // // Created by Prashant on 16/11/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit import MobileCoreServices class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // Outlet & action - camera button @IBOutlet var cameraButton: UIBarButtonItem! @IBAction func cameraButtonAction(_ sender: AnyObject) { // show action shee to choose image source. self.showImageSourceActionSheet() } // Outlet & action - save button @IBOutlet var saveButton: UIBarButtonItem! @IBAction func saveButtonAction(_ sender: UIBarButtonItem) { // save image to photo gallery self.saveImageToPhotoGallery() } // Outlet - image preview @IBOutlet var previewImageView: UIImageView! // Selected image var selctedImage: UIImage! // message label @IBOutlet var messageLabel: UILabel! // filter Title and Name list var filterTitleList: [String]! var filterNameList: [String]! // filter selection picker @IBOutlet var filterPicker: UIPickerView! // MARK: - view functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // set filter title list array. self.filterTitleList = ["(( Choose Filter ))" ,"PhotoEffectChrome", "PhotoEffectFade", "PhotoEffectInstant", "PhotoEffectMono", "PhotoEffectNoir", "PhotoEffectProcess", "PhotoEffectTonal", "PhotoEffectTransfer"] // set filter name list array. self.filterNameList = ["No Filter" ,"CIPhotoEffectChrome", "CIPhotoEffectFade", "CIPhotoEffectInstant", "CIPhotoEffectMono", "CIPhotoEffectNoir", "CIPhotoEffectProcess", "CIPhotoEffectTonal", "CIPhotoEffectTransfer"] // set delegate for filter picker self.filterPicker.delegate = self self.filterPicker.dataSource = self // disable filter pickerView self.filterPicker.isUserInteractionEnabled = false // show message label self.messageLabel.isHidden = false // disable save button self.saveButton.isEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: image picker delegate function // set selected image in preview func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // dismiss image picker controller picker.dismiss(animated: true, completion: nil) // if image selected the set in preview. if let newImage = info[UIImagePickerControllerOriginalImage] as? UIImage { // set selected image into variable self.selctedImage = newImage // set preview for selected image self.previewImageView.image = self.selctedImage // enable filter pickerView self.filterPicker.isUserInteractionEnabled = true // hide message label self.messageLabel.isHidden = true // disable save button self.saveButton.isEnabled = false // set filter pickerview to default position self.filterPicker.selectRow(0, inComponent: 0, animated: true) } } // Close image picker func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // dismiss image picker controller picker.dismiss(animated: true, completion: nil) } // MARK: - picker view delegate and data source (to choose filter name) // how many component (i.e. column) to be displayed within picker view func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // How many rows are there is each component func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.filterTitleList.count } // title/content for row in given component func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.filterTitleList[row] } // called when row selected from any component within picker view func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // disable save button if filter not selected. // enable save button if filter selected. if row == 0 { self.saveButton.isEnabled = false }else{ self.saveButton.isEnabled = true } // call funtion to apply the selected filter self.applyFilter(selectedFilterIndex: row) } // MARK: - Utility functions { // Show action sheet for image source selection fileprivate func showImageSourceActionSheet() { // create alert controller having style as ActionSheet let alertCtrl = UIAlertController(title: "Select Image Source" , message: nil, preferredStyle: UIAlertControllerStyle.actionSheet) // create photo gallery action let galleryAction = UIAlertAction(title: "Photo Gallery", style: UIAlertActionStyle.default, handler: { (alertAction) -> Void in self.showPhotoGallery() } ) // create camera action let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default, handler: { (alertAction) -> Void in self.showCamera() } ) // create cancel action let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil) // add action to alert controller alertCtrl.addAction(galleryAction) alertCtrl.addAction(cameraAction) alertCtrl.addAction(cancelAction) // do this setting for ipad alertCtrl.modalPresentationStyle = UIModalPresentationStyle.popover let popover = alertCtrl.popoverPresentationController popover?.barButtonItem = self.cameraButton // present action sheet self.present(alertCtrl, animated: true, completion: nil) } // Show photo gallery to choose image fileprivate func showPhotoGallery() -> Void { // debug print("Choose - Photo Gallery") // show picker to select image form gallery if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) { // create image picker let imagePicker = UIImagePickerController() // set image picker property imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.allowsEditing = false // do this settings to show popover within iPad imagePicker.modalPresentationStyle = UIModalPresentationStyle.popover let popover = imagePicker.popoverPresentationController popover!.barButtonItem = self.cameraButton // show image picker self.present(imagePicker, animated: true, completion: nil) }else{ self.showAlertMessage(alertTitle: "Not Supported", alertMessage: "Device can not access gallery.") } } // Show camera to capture image fileprivate func showCamera() -> Void { // debug print("Choose - Camera") // show camera if( UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { // create image picker let imagePicker = UIImagePickerController() // set image picker property imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.photo imagePicker.allowsEditing = false // do this settings to show popover within iPad imagePicker.modalPresentationStyle = UIModalPresentationStyle.popover let popover = imagePicker.popoverPresentationController popover!.barButtonItem = self.cameraButton // show image picker with camera. self.present(imagePicker, animated: true, completion: nil) }else { self.showAlertMessage(alertTitle: "Not Supported", alertMessage: "Camera not supported in emulator.") } } // apply filter to current image fileprivate func applyFilter(selectedFilterIndex filterIndex: Int) { // print("Filter - \(self.filterNameList[filterIndex)") /* filter name 0 - NO Filter, 1 - PhotoEffectChrome, 2 - PhotoEffectFade, 3 - PhotoEffectInstant, 4 - PhotoEffectMono, 5 - PhotoEffectNoir, 6 - PhotoEffectProcess, 7 - PhotoEffectTonal, 8 - PhotoEffectTransfer */ // if No filter selected then apply default image and return. if filterIndex == 0 { // set image selected image self.previewImageView.image = self.selctedImage return } // Create and apply filter // 1 - create source image let sourceImage = CIImage(image: self.selctedImage) // 2 - create filter using name let myFilter = CIFilter(name: self.filterNameList[filterIndex]) myFilter?.setDefaults() // 3 - set source image myFilter?.setValue(sourceImage, forKey: kCIInputImageKey) // 4 - create core image context let context = CIContext(options: nil) // 5 - output filtered image as cgImage with dimension. let outputCGImage = context.createCGImage(myFilter!.outputImage!, from: myFilter!.outputImage!.extent) // 6 - convert filtered CGImage to UIImage let filteredImage = UIImage(cgImage: outputCGImage!) // 7 - set filtered image to preview self.previewImageView.image = filteredImage } // save imaage to photo gallery fileprivate func saveImageToPhotoGallery(){ // Save image DispatchQueue.main.async { UIImageWriteToSavedPhotosAlbum(self.previewImageView.image!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil) } } // show message after image saved to photo gallery. func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) { // show success or error message. if error == nil { self.showAlertMessage(alertTitle: "Success", alertMessage: "Image Saved To Photo Gallery") } else { self.showAlertMessage(alertTitle: "Error!", alertMessage: (error?.localizedDescription)! ) } } // Show alert message with OK button func showAlertMessage(alertTitle: String, alertMessage: String) { let myAlertVC = UIAlertController( title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) myAlertVC.addAction(okAction) self.present(myAlertVC, animated: true, completion: nil) } }
mit
20218c1e431d957a9306342aecb2760e
33.420904
224
0.628396
5.883631
false
false
false
false
yeokm1/nus-soc-print-ios
NUS SOC Print/AboutViewController.swift
1
1081
// // AboutViewController.swift // NUS SOC Print // // Created by Yeo Kheng Meng on 5/9/14. // Copyright (c) 2014 Yeo Kheng Meng. All rights reserved. // import Foundation class AboutViewController: GAITrackedViewController { let TAG = "AboutViewController" @IBOutlet weak var placeToPutVersion: UILabel! @IBAction func closeButtonPress(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.screenName = TAG; } override func viewDidLoad() { super.viewDidLoad() let versionString = getVersionString() let buildDate = ConstantsObjC.getBuildDate() placeToPutVersion.text = "NUS SOC Print " + versionString + " (" + buildDate + ")" } @IBAction func sourceCodeButtonPress(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://github.com/yeokm1/nus-soc-print-ios")!) } }
mit
45c0e829cbfcc7babcd5fa5c9a6aa92f
24.761905
112
0.641998
4.430328
false
false
false
false
coppercash/Anna
Demos/Easy/Easy/MasterViewController.swift
1
3817
// // MasterViewController.swift // Easy // // Created by William on 2018/6/24. // Copyright © 2018 coppercash. All rights reserved. // import UIKit import Anna class MasterViewController: UITableViewController, AnalyzableObject { var detailViewController: DetailViewController? = nil var objects = [Any]() lazy var analyzer: Analyzing = { Analyzer.analyzer(with: self) }() static let subAnalyzableKeys: Set<String> = [#keyPath(tableView)] deinit { self.analyzer.detach() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.leftBarButtonItem = editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) navigationItem.rightBarButtonItem = addButton if let split = splitViewController { let controllers = split.viewControllers detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } self.analyzer.enable(naming: "master") } override func viewWillAppear(_ animated: Bool) { clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func insertNewObject(_ sender: Any) { objects.insert(NSDate(), at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object as Date controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! AnalyzableTableViewCell cell.analyzer.enable(naming: "cell") let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description cell.analyzer.update(object.description, for: "text") return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
eb84d0d973d3539cd75e0f17ab33c86e
35
139
0.671122
5.3
false
false
false
false
cam-hop/APIUtility
RxSwiftFluxDemo/Carthage/Checkouts/RxSwift/RxCocoa/macOS/NSControl+Rx.swift
7
2810
// // NSControl+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(macOS) import Cocoa #if !RX_NO_MODULE import RxSwift #endif fileprivate var rx_value_key: UInt8 = 0 fileprivate var rx_control_events_key: UInt8 = 0 extension Reactive where Base: NSControl { /// Reactive wrapper for control event. public var controlEvent: ControlEvent<Void> { MainScheduler.ensureExecutingOnScheduler() let source = lazyInstanceObservable(&rx_control_events_key) { () -> Observable<Void> in Observable.create { [weak control = self.base] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = control else { observer.on(.completed) return Disposables.create() } let observer = ControlTarget(control: control) { control in observer.on(.next()) } return observer }.takeUntil(self.deallocated) } return ControlEvent(events: source) } /// You might be wondering why the ugly `as!` casts etc, well, for some reason if /// Swift compiler knows C is UIControl type and optimizations are turned on, it will crash. static func value<C: AnyObject, T: Equatable>(_ control: C, getter: @escaping (C) -> T, setter: @escaping (C, T) -> Void) -> ControlProperty<T> { MainScheduler.ensureExecutingOnScheduler() let source = (control as! NSObject).rx.lazyInstanceObservable(&rx_value_key) { () -> Observable<T> in return Observable.create { [weak weakControl = control] (observer: AnyObserver<T>) in guard let control = weakControl else { observer.on(.completed) return Disposables.create() } observer.on(.next(getter(control))) let observer = ControlTarget(control: control as! NSControl) { _ in if let control = weakControl { observer.on(.next(getter(control))) } } return observer } .distinctUntilChanged() .takeUntil((control as! NSObject).rx.deallocated) } let bindingObserver = UIBindingObserver(UIElement: control, binding: setter) return ControlProperty(values: source, valueSink: bindingObserver) } /// Bindable sink for `enabled` property. public var isEnabled: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: self.base) { (owner, value) in owner.isEnabled = value } } } #endif
mit
a7499ed21f6f16945f82a8e6301c9831
32.440476
149
0.586686
4.945423
false
false
false
false
gregttn/GTProgressBar
Example/Tests/GTProgressBarVertical.swift
1
8337
// // GTProgressBarVertical.swift // GTProgressBar // // Created by Grzegorz Tatarzyn on 04/08/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest import Nimble import GTProgressBar class GTProgressBarVertical: XCTestCase { private let backgroundViewIndex = 1 private let labelViewIndex = 0 private let labelFrameSize: CGSize = CGSize(width: 32, height: 15) private let labelInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) private let insetsOffset: CGFloat = 10 private let minimumBarWidth: CGFloat = 20 private let minimumBarHeight: CGFloat = 20 func testShouldCalculateCorrectFramesWhenVerticalBarWithoutLabel() { let view = setupView() { view in view.displayLabel = false view.progress = 0.5 } let backgroundView = view.subviews[backgroundViewIndex] let expectedBackgroundFrame = CGRect(origin: CGPoint.zero, size: view.frame.size) expect(backgroundView.frame).to(equal(expectedBackgroundFrame)) let fillView = backgroundView.subviews.first! let expectedFillViewFrame = CGRect(origin: CGPoint(x: 4, y: 50), size: CGSize(width:92, height: 46)) expect(fillView.frame).to(equal(expectedFillViewFrame)) } func testShouldCalculateRoundedCornerBasedOnWidth() { let view = setupView(frame: CGRect(x: 0, y: 0, width: 20, height: 100)) { view in view.displayLabel = false } let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.layer.cornerRadius).to(equal(7)) } func testShouldChangePositionAndHeightOfFillViewWhenUsingAnimateTo() { let view = setupView() { view in view.displayLabel = false view.progress = 0.1 } view.animateTo(progress: 0.5) let fillView = view.subviews[backgroundViewIndex].subviews.first! let expectedFillViewFrame = CGRect(origin: CGPoint(x: 4, y: 50), size: CGSize(width:92, height: 46)) expect(fillView.frame).to(equal(expectedFillViewFrame)) } func testCompletionHandlerFiredwWhenUsingAnimateTo() { let view = setupView() { view in view.displayLabel = false view.progress = 0.1 } var completion = false view.animateTo(progress: 0.5) { completion = true } RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1)) expect(completion).toEventually(equal(true)) } func testShouldChangeCalculateCorrectFrameForFillViewWhenAnticlockwiseDirectionUsed() { let view = setupView() { view in view.displayLabel = false view.progress = 0.1 view.direction = .anticlockwise } view.animateTo(progress: 0.5) let fillView = view.subviews[backgroundViewIndex].subviews.first! let expectedFillViewFrame = CGRect(origin: CGPoint(x: 4, y: 4), size: CGSize(width:92, height: 46)) expect(fillView.frame).to(equal(expectedFillViewFrame)) } func testSizeToFitCreatesMinimalSizeWithHorizontalLabelAlignment() { let view = setupView() view.frame = CGRect.zero view.sizeToFit() let width: CGFloat = labelFrameSize.width + labelInsets.left + labelInsets.right + minimumBarWidth expect(view.frame.size.height).to(equal(minimumBarHeight)) expect(view.frame.size.width).to(equal(width)) } func testSizeToFitCreatesMinimalSizeWithVerticalLabelAlignment() { let view = setupView() { view in view.labelPosition = .top } view.frame = CGRect.zero view.sizeToFit() let height: CGFloat = labelFrameSize.height + labelInsets.top + labelInsets.bottom + minimumBarHeight let width: CGFloat = labelFrameSize.width + labelInsets.left + labelInsets.right expect(view.frame.size.height).to(equal(height)) expect(view.frame.size.width).to(equal(width)) } func testLabelCenteredHorizontallyWhenLabelOnTheTop() { let view = setupView() { view in view.labelPosition = .top } let label = view.subviews[labelViewIndex] expect(label.center.x).to(equal(view.center.x)) } func testLabelCenteredHorizontallyWhenLabelOnTheBottom() { let view = setupView() { view in view.labelPosition = .bottom } let label = view.subviews[labelViewIndex] expect(label.center.x).to(equal(view.center.x)) } func testLabelCenteredVerticallyWhenLabelOnTheRight() { let view = setupView() { view in view.labelPosition = .right } let label = view.subviews[labelViewIndex] expect(label.center.y).to(equal(view.center.y)) } func testLabelCenteredVerticallyWhenLabelOnTheLeft() { let view = setupView() { view in view.labelPosition = .left } let label = view.subviews[labelViewIndex] expect(label.center.y).to(equal(view.center.y)) } func testBarCenteredHorizontally() { let view = setupView() let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.center.y).to(equal(view.center.y)) } func testBarCenteredVerticallyWhenNoLabel() { let view = setupView() { view in view.displayLabel = false } let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.center.x).to(equal(view.center.x)) } func testBarCenteredVerticallyWhenNoLabelAndWidthRestricted() { let view = setupView() { view in view.displayLabel = false view.barMaxWidth = 20 } let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.center.x).to(equal(view.center.x)) } func testBarCenteredVerticallyWhenWidthRestrictedAndLabelOnTheTop() { let view = setupView() { view in view.labelPosition = .top view.barMaxWidth = 20 } let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.center.x).to(equal(view.center.x)) } func testBarCenteredVerticallyWhenWidthRestrictedAndLabelOnTheBottom() { let view = setupView() { view in view.labelPosition = .top view.barMaxWidth = 20 } let backgroundView = view.subviews[backgroundViewIndex] expect(backgroundView.center.x).to(equal(view.center.x)) } func testFillViewHasTheSameFrameAsBackgroundViewWhenNoInsetsSetAndFullProgressSet() { let view = setupView() { view in view.labelPosition = .top view.barFillInset = 0 view.progress = 1 } let backgroundView = view.subviews[backgroundViewIndex] let fillView = backgroundView.subviews.first! expect(fillView.frame.origin).to(equal(CGPoint.zero)) expect(fillView.frame.size).to(equal(backgroundView.frame.size)) } func testSettingBarMaxWidthIntPopulatesTheBarMaxWidthVariable() { let view = setupView() view.barMaxWidth = nil view.barMaxWidthInt = 2 expect(view.barMaxWidth!).to(equal(CGFloat(view.barMaxWidthInt))) } func testSettingBarMaxWidthIntOfZeroMakesTheBarMaxHeightVariableAbsent() { let view = setupView() view.barMaxWidth = 2.0 view.barMaxWidthInt = 0 expect(view.barMaxWidth).to(beNil()) } private func setupView(frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100), configure: (GTProgressBar) -> Void = { _ in } ) -> GTProgressBar { let view = GTProgressBar(frame: frame) view.orientation = GTProgressBarOrientation.vertical configure(view) view.layoutSubviews() return view } }
mit
eef72549114c74740107b01d7b0e6a41
32.079365
133
0.618882
4.680517
false
true
false
false
NSCabezon/SwiftExtensions
SwiftExtensions/UIDeviceExtensions.swift
1
893
import Foundation import UIKit public extension UIDevice { var deviceModel: String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = Mirror(reflecting: machine) var identifier = "" for child in mirror.children { if let value = child.value as? Int8, value != 0 { let escaped = UnicodeScalar(UInt8(value)).escaped(asASCII: false) identifier.append(escaped) } } return identifier } var isIpad: Bool { return deviceModel.contains("iPad") } static var vendorID: String { return UIDevice.current.identifierForVendor?.uuidString ??? "" } public var osName: String { return "ios" } public var osVersion: String { return UIDevice.current.systemVersion } }
apache-2.0
083e9b7924b2942f81e44b8f233ab10c
20.780488
81
0.590146
4.775401
false
false
false
false
gmission/gmission-ios
gmission/Carthage/Checkouts/Alamofire/Example/Source/MasterViewController.swift
16
3846
// MasterViewController.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import UIKit class MasterViewController: UITableViewController { @IBOutlet weak var titleImageView: UIImageView! var detailViewController: DetailViewController? = nil var objects = NSMutableArray() // MARK: - View Lifecycle override func awakeFromNib() { super.awakeFromNib() navigationItem.titleView = titleImageView } override func viewDidLoad() { super.viewDidLoad() if let split = splitViewController { let controllers = split.viewControllers if let navigationController = controllers.last as? UINavigationController, topViewController = navigationController.topViewController as? DetailViewController { detailViewController = topViewController } } } // MARK: - UIStoryboardSegue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let navigationController = segue.destinationViewController as? UINavigationController, detailViewController = navigationController.topViewController as? DetailViewController { func requestForSegue(segue: UIStoryboardSegue) -> Request? { switch segue.identifier! { case "GET": detailViewController.segueIdentifier = "GET" return Alamofire.request(.GET, "https://httpbin.org/get") case "POST": detailViewController.segueIdentifier = "POST" return Alamofire.request(.POST, "https://httpbin.org/post") case "PUT": detailViewController.segueIdentifier = "PUT" return Alamofire.request(.PUT, "https://httpbin.org/put") case "DELETE": detailViewController.segueIdentifier = "DELETE" return Alamofire.request(.DELETE, "https://httpbin.org/delete") case "DOWNLOAD": detailViewController.segueIdentifier = "DOWNLOAD" let destination = Alamofire.Request.suggestedDownloadDestination( directory: .CachesDirectory, domain: .UserDomainMask ) return Alamofire.download(.GET, "https://httpbin.org/stream/1", destination: destination) default: return nil } } if let request = requestForSegue(segue) { detailViewController.request = request } } } }
mit
ac0f729403c76713a5b8fbf5bed278ac
39.463158
109
0.639178
5.868702
false
false
false
false
alskipp/Argo
ArgoTests/Tests/SwiftDictionaryDecodingTests.swift
4
1501
import XCTest import Argo class SwiftDictionaryDecodingTests: XCTestCase { func testDecodingAllTypesFromSwiftDictionary() { let typesDict = [ "numerics": [ "int": 5, "int64": 900719,//9254740992, Dictionaries can't handle 64bit ints (iOS only, Mac works) "int64_string": "1076543210012345678", "double": 3.4, "float": 1.1, "int_opt": 4 ], "bool": false, "string_array": ["hello", "world"], "embedded": [ "string_array": ["hello", "world"], "string_array_opt": [] ], "user_opt": [ "id": 6, "name": "Cooler User" ], "dict": [ "foo": "bar" ] ] let model: TestModel? = decode(typesDict) XCTAssert(model != nil) XCTAssert(model?.numerics.int == 5) XCTAssert(model?.numerics.int64 == 900719)//9254740992) XCTAssert(model?.numerics.double == 3.4) XCTAssert(model?.numerics.float == 1.1) XCTAssert(model?.numerics.intOpt != nil) XCTAssert(model?.numerics.intOpt! == 4) XCTAssert(model?.string == "Cooler User") XCTAssert(model?.bool == false) XCTAssert(model?.stringArray.count == 2) XCTAssert(model?.stringArrayOpt == nil) XCTAssert(model?.eStringArray.count == 2) XCTAssert(model?.eStringArrayOpt != nil) XCTAssert(model?.eStringArrayOpt?.count == 0) XCTAssert(model?.userOpt != nil) XCTAssert(model?.userOpt?.id == 6) XCTAssert(model?.dict ?? [:] == ["foo": "bar"]) } }
mit
2d6194a249edeaceaf001e7055f854eb
29.02
96
0.586942
3.590909
false
true
false
false
dobnezmi/EmotionNote
EmotionNote/Charts/Highlight/Highlight.swift
1
7338
// // Highlight.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import UIKit @objc(ChartHighlight) open class Highlight: NSObject { /// the x-value of the highlighted value fileprivate var _x = Double.nan /// the y-value of the highlighted value fileprivate var _y = Double.nan /// the x-pixel of the highlight fileprivate var _xPx = CGFloat.nan /// the y-pixel of the highlight fileprivate var _yPx = CGFloat.nan /// the index of the data object - in case it refers to more than one open var dataIndex = Int(-1) /// the index of the dataset the highlighted value is in fileprivate var _dataSetIndex = Int(0) /// index which value of a stacked bar entry is highlighted /// /// **default**: -1 fileprivate var _stackIndex = Int(-1) /// the axis the highlighted value belongs to fileprivate var _axis: YAxis.AxisDependency = YAxis.AxisDependency.left /// the x-position (pixels) on which this highlight object was last drawn open var drawX: CGFloat = 0.0 /// the y-position (pixels) on which this highlight object was last drawn open var drawY: CGFloat = 0.0 public override init() { super.init() } /// - parameter x: the x-value of the highlighted value /// - parameter y: the y-value of the highlighted value /// - parameter xPx: the x-pixel of the highlighted value /// - parameter yPx: the y-pixel of the highlighted value /// - parameter dataIndex: the index of the Data the highlighted value belongs to /// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to /// - parameter stackIndex: references which value of a stacked-bar entry has been selected /// - parameter axis: the axis the highlighted value belongs to public init( x: Double, y: Double, xPx: CGFloat, yPx: CGFloat, dataIndex: Int, dataSetIndex: Int, stackIndex: Int, axis: YAxis.AxisDependency) { super.init() _x = x _y = y _xPx = xPx _yPx = yPx self.dataIndex = dataIndex _dataSetIndex = dataSetIndex _stackIndex = stackIndex _axis = axis } /// - parameter x: the x-value of the highlighted value /// - parameter y: the y-value of the highlighted value /// - parameter xPx: the x-pixel of the highlighted value /// - parameter yPx: the y-pixel of the highlighted value /// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to /// - parameter stackIndex: references which value of a stacked-bar entry has been selected /// - parameter axis: the axis the highlighted value belongs to public convenience init( x: Double, y: Double, xPx: CGFloat, yPx: CGFloat, dataSetIndex: Int, stackIndex: Int, axis: YAxis.AxisDependency) { self.init(x: x, y: y, xPx: xPx, yPx: yPx, dataIndex: 0, dataSetIndex: dataSetIndex, stackIndex: stackIndex, axis: axis) } /// - parameter x: the x-value of the highlighted value /// - parameter y: the y-value of the highlighted value /// - parameter xPx: the x-pixel of the highlighted value /// - parameter yPx: the y-pixel of the highlighted value /// - parameter dataIndex: the index of the Data the highlighted value belongs to /// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to /// - parameter stackIndex: references which value of a stacked-bar entry has been selected /// - parameter axis: the axis the highlighted value belongs to public init( x: Double, y: Double, xPx: CGFloat, yPx: CGFloat, dataSetIndex: Int, axis: YAxis.AxisDependency) { super.init() _x = x _y = y _xPx = xPx _yPx = yPx _dataSetIndex = dataSetIndex _axis = axis } /// - parameter x: the x-value of the highlighted value /// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to public init(x: Double, dataSetIndex: Int) { _x = x _dataSetIndex = dataSetIndex } /// - parameter x: the x-value of the highlighted value /// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to /// - parameter stackIndex: references which value of a stacked-bar entry has been selected public convenience init(x: Double, dataSetIndex: Int, stackIndex: Int) { self.init(x: x, dataSetIndex: dataSetIndex) _stackIndex = stackIndex } open var x: Double { return _x } open var y: Double { return _y } open var xPx: CGFloat { return _xPx } open var yPx: CGFloat { return _yPx } open var dataSetIndex: Int { return _dataSetIndex } open var stackIndex: Int { return _stackIndex } open var axis: YAxis.AxisDependency { return _axis } open var isStacked: Bool { return _stackIndex >= 0 } /// Sets the x- and y-position (pixels) where this highlight was last drawn. open func setDraw(x: CGFloat, y: CGFloat) { self.drawX = x self.drawY = y } /// Sets the x- and y-position (pixels) where this highlight was last drawn. open func setDraw(pt: CGPoint) { self.drawX = pt.x self.drawY = pt.y } // MARK: NSObject open override var description: String { return "Highlight, x: \(_x), y: \(_y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)" } open override func isEqual(_ object: Any?) -> Bool { if object == nil { return false } if !(object! as AnyObject).isKind(of: type(of: self)) { return false } if (object! as AnyObject).x != _x { return false } if (object! as AnyObject).y != _y { return false } if (object! as AnyObject).dataIndex != dataIndex { return false } if (object! as AnyObject).dataSetIndex != _dataSetIndex { return false } if (object! as AnyObject).stackIndex != _stackIndex { return false } return true } } func ==(lhs: Highlight, rhs: Highlight) -> Bool { if lhs === rhs { return true } if !lhs.isKind(of: type(of: rhs)) { return false } if lhs._x != rhs._x { return false } if lhs._y != rhs._y { return false } if lhs.dataIndex != rhs.dataIndex { return false } if lhs._dataSetIndex != rhs._dataSetIndex { return false } if lhs._stackIndex != rhs._stackIndex { return false } return true }
apache-2.0
bcc1188615e613502968629037439caf
27.889764
173
0.585173
4.50184
false
false
false
false
luckymarmot/ThemeKit
Demo/Demo/ContentViewController.swift
1
4376
// // ContentViewController.swift // Demo // // Created by Nuno Grilo on 29/09/2016. // Copyright © 2016 Paw & Nuno Grilo. All rights reserved. // import Cocoa import ThemeKit class ContentViewController: NSViewController, NSTextDelegate { /// Our content view @IBOutlet var contentView: NSView! /// Our text view @IBOutlet var contentTextView: NSTextView! /// Our placeholder view when no note is selected. @IBOutlet var noSelectionPlaceholder: NSView! override func viewDidLoad() { super.viewDidLoad() // Setup our Text View contentTextView.textColor = ThemeColor.contentTextColor contentTextView.backgroundColor = ThemeColor.contentBackgroundColor contentTextView.drawsBackground = true contentTextView.textContainer?.lineFragmentPadding = 16 var font = NSFont(name: "GillSans-Light", size: 16) if font == nil { font = NSFont.systemFont(ofSize: 14) } contentTextView.font = font let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4.4 contentTextView.defaultParagraphStyle = paragraphStyle // Setup our clipping view background color (text view parent) if let clipView = contentTextView.enclosingScrollView?.contentView { clipView.backgroundColor = ThemeColor.contentBackgroundColor clipView.drawsBackground = true } // Observe note selection change notifications NotificationCenter.default.addObserver(forName: .didChangeNoteSelection, object: nil, queue: nil) { (notification) in let obj = notification.object if let viewController = obj as? NSViewController, viewController.view.window == self.view.window { self.representedObject = notification.userInfo?["note"] } } // Fix white scrollbar view when in dark theme and scrollbars are set to // always be shown on *System Preferences > General*. if let scrollView = contentTextView.enclosingScrollView { scrollView.backgroundColor = ThemeColor.contentBackgroundColor scrollView.wantsLayer = true } // Observe theme changes NotificationCenter.default.addObserver(self, selector: #selector(didChangeTheme(_:)), name: .didChangeTheme, object: nil) } override var representedObject: Any? { didSet { var subview: NSView if let note = representedObject as? Note { contentTextView.string = note.text contentTextView.scrollToBeginningOfDocument(self) noSelectionPlaceholder.removeFromSuperview() subview = contentView } else { contentTextView.string = "" contentView.removeFromSuperview() subview = noSelectionPlaceholder } self.view.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = true subview.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] subview.frame = view.bounds } } // MARK: - // MARK: Theme related @objc private func didChangeTheme(_ notification: Notification? = nil) { // Update `NSScroller` background color based on current theme DispatchQueue.main.async { self.contentTextView.enclosingScrollView?.verticalScroller?.layer?.backgroundColor = ThemeColor.contentBackgroundColor.cgColor } // If in fullscreen, need to re-focus current window if let window = view.window { let isWindowInFullScreen = window.styleMask.contains(NSWindow.StyleMask.fullScreen) || window.className == "NSToolbarFullScreenWindow" if isWindowInFullScreen { DispatchQueue.main.async { window.makeKey() } } } } // MARK: - // MARK: NSTextDelegate public func textDidChange(_ notification: Notification) { if let note = representedObject as? Note { note.text = contentTextView.string note.lastModified = Date() NotificationCenter.default.post(name: .didEditNoteText, object: self, userInfo: ["note": note]) } } }
mit
4311ce7f46443b41950617bee5485752
35.764706
146
0.644343
5.616175
false
false
false
false
prey/prey-ios-client
Prey/Classes/PreyAction.swift
1
6821
// // PreyAction.swift // Prey // // Created by Javier Cala Uribe on 5/05/16. // Copyright © 2016 Prey, Inc. All rights reserved. // import Foundation class PreyAction : Operation { // MARK: Properties var target: kAction var command: kCommand var options: NSDictionary? var messageId: String? var deviceJobId: String? var triggerId: String? var isActive: Bool = false // MARK: Functions // Initialize with Target init(withTarget t: kAction, withCommand cmd: kCommand, withOptions opt: NSDictionary?) { target = t command = cmd options = opt } // Start method @objc override func start() {} // Stop method @objc func stop() {} // Get method @objc func get() {} // Return Prey New Action class func newAction(withName target:kAction, withCommand cmd:kCommand, withOptions opt: NSDictionary?) -> PreyAction? { let actionItem: PreyAction? switch target { case kAction.location: actionItem = Location.initLocationAction(withTarget: kAction.location, withCommand: cmd, withOptions: opt) case kAction.alarm: actionItem = Alarm(withTarget: kAction.alarm, withCommand: cmd, withOptions: opt) case kAction.alert: actionItem = Alert(withTarget: kAction.alert, withCommand: cmd, withOptions: opt) case kAction.report: actionItem = Report(withTarget: kAction.report, withCommand: cmd, withOptions: opt) case kAction.geofencing: actionItem = Geofencing(withTarget: kAction.geofencing, withCommand: cmd, withOptions: opt) case kAction.detach: actionItem = Detach(withTarget: kAction.detach, withCommand: cmd, withOptions: opt) case kAction.camouflage: actionItem = Camouflage(withTarget: kAction.camouflage, withCommand: cmd, withOptions: opt) case kAction.ping: actionItem = Ping(withTarget: kAction.ping, withCommand: cmd, withOptions: opt) case kAction.tree: actionItem = FileRetrieval(withTarget: kAction.tree, withCommand: cmd, withOptions: opt) case kAction.fileretrieval: actionItem = FileRetrieval(withTarget: kAction.fileretrieval, withCommand: cmd, withOptions: opt) case kAction.triggers: actionItem = Trigger(withTarget: kAction.triggers, withCommand: cmd, withOptions: opt) case kAction.user_activated: actionItem = UserActivated(withTarget: kAction.user_activated, withCommand: cmd, withOptions: opt) } return actionItem } // Return params to response endpoint func getParamsTo(_ target:String, command:String, status:String) -> [String: Any] { // Params struct var params:[String: Any] = [ kData.status.rawValue : status, kData.target.rawValue : target, kData.command.rawValue : command] if let jobId = deviceJobId { let jobIdJson = [kOptions.device_job_id.rawValue : jobId] params[kData.reason.rawValue] = jobIdJson } if let tigreId = triggerId { let triggerIdJson = [kOptions.trigger_id.rawValue : tigreId] params[kData.reason.rawValue] = triggerIdJson } return params } // Send data to panel func sendData(_ params:[String: Any], toEndpoint:String) { PreyLogger("data") // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey, PreyConfig.sharedInstance.isRegistered { PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:params, messageId:messageId, httpMethod:Method.POST.rawValue, endPoint:toEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.dataSend, preyAction:self, onCompletion:{(isSuccess: Bool) in PreyLogger("Request dataSend")})) } else { PreyLogger("Error send data auth") } } // Send report to panel func sendDataReport(_ params:NSMutableDictionary, images:NSMutableDictionary, toEndpoint:String) { // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey, PreyConfig.sharedInstance.isRegistered { PreyHTTPClient.sharedInstance.sendDataReportToPrey(username, password:"x", params:params, images: images, messageId:messageId, httpMethod:Method.POST.rawValue, endPoint:toEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.dataSend, preyAction:self, onCompletion:{(isSuccess: Bool) in PreyLogger("Request dataSend")})) } else { PreyLogger("Error send data auth") } } // Check Geofence Zones func checkGeofenceZones(_ action:Geofencing) { // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey { PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:nil, messageId:nil, httpMethod:Method.GET.rawValue, endPoint:geofencingEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.geofenceZones, preyAction:action, onCompletion:{(isSuccess: Bool) in PreyLogger("Request geofencesZones")})) } else { PreyLogger("Error auth check Geofence") } } // Check Triggers func checkTriggers(_ action:Trigger) { // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey { PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:nil, messageId:nil, httpMethod:Method.GET.rawValue, endPoint:triggerEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.trigger, preyAction:action, onCompletion:{(isSuccess: Bool) in PreyLogger("Request triggers on panel")})) } else { PreyLogger("Error auth check Triggers") } } // Delete device in Panel func sendDeleteDevice(_ onCompletion:@escaping (_ isSuccess: Bool) -> Void) { // Check userApiKey isn't empty if let username = PreyConfig.sharedInstance.userApiKey { PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:nil, messageId:nil, httpMethod:Method.DELETE.rawValue, endPoint:deleteDeviceEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.deleteDevice, preyAction:nil, onCompletion:onCompletion)) } else { let titleMsg = "Couldn't delete your device".localized let alertMsg = "Device not ready!".localized displayErrorAlert(alertMsg, titleMessage:titleMsg) onCompletion(false) } } }
gpl-3.0
9d3cf1aa014d5f9375a390501136ad8d
39.838323
344
0.665249
4.642614
false
false
false
false
ifeherva/HSTracker
HSTracker/UIs/StatsManager/Statistics.swift
1
4207
// // Statistics.swift // HSTracker // // Created by Matthew Welborn on 6/8/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Cocoa import RealmSwift class Statistics: NSWindowController { @IBOutlet weak var selectedDeckIcon: NSImageView! @IBOutlet weak var selectedDeckName: NSTextField! @IBOutlet weak var tabs: NSTabView! var deck: Deck? var statsTab: StatsTab? var ladderTab: LadderTab? var tabSizes = [NSTabViewItem: CGSize]() override func windowDidLoad() { super.windowDidLoad() update() statsTab = StatsTab(nibName: NSNib.Name(rawValue: "StatsTab"), bundle: nil) statsTab!.deck = self.deck ladderTab = LadderTab(nibName: NSNib.Name(rawValue: "LadderTab"), bundle: nil) ladderTab!.deck = self.deck ladderTab!.guessRankAndUpdate() let statsTabView = NSTabViewItem(viewController: statsTab!) statsTabView.label = NSLocalizedString("Statistics", comment: "") tabSizes[statsTabView] = statsTab!.view.frame.size let ladderTabView = NSTabViewItem(viewController: ladderTab!) ladderTabView.label = NSLocalizedString("The Climb", comment: "") tabSizes[ladderTabView] = ladderTab!.view.frame.size tabs.addTabViewItem(statsTabView) tabs.addTabViewItem(ladderTabView) resizeWindowToFitTab(statsTabView) tabs.delegate = self tabs.selectTabViewItem(statsTabView) // We need to update the display both when the // stats change NotificationCenter.default .addObserver(self, selector: #selector(update), name: NSNotification.Name(rawValue: Events.reload_decks), object: nil) } func resizeWindowToFitTab(_ tab: NSTabViewItem) { //TODO: centering? guard let desiredTabSize = tabSizes[tab], let swindow = self.window else { return } let currentTabSize = tab.view!.frame.size let windowSize = swindow.frame.size let newSize = CGSize( width: windowSize.width + desiredTabSize.width - currentTabSize.width, height: windowSize.height + desiredTabSize.height - currentTabSize.height) var frame = swindow.frame frame.origin.y = swindow.frame.origin.y - newSize.height + windowSize.height frame.size = newSize swindow.setFrame(frame, display: true) } @objc func update() { if let deck = self.deck { // XXX: This might be unsafe // I'm assuming that the player class names // and class assets are always the same let imageName = deck.playerClass.rawValue.lowercased() selectedDeckIcon.image = NSImage(named: NSImage.Name(rawValue: imageName)) selectedDeckName.stringValue = deck.name } else { selectedDeckIcon.image = NSImage(named: NSImage.Name(rawValue: "error")) selectedDeckName.stringValue = "No deck selected." } } @IBAction func closeWindow(_ sender: AnyObject) { self.window?.sheetParent?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK) } @IBAction func deleteStatistics(_ sender: AnyObject) { if let deck = deck { let msg = String(format: NSLocalizedString("Are you sure you want to delete the " + "statistics for the deck %@ ?", comment: ""), deck.name) NSAlert.show(style: .informational, message: msg, window: self.window!) { RealmHelper.removeAllGameStats(from: deck) DispatchQueue.main.async { self.statsTab!.statsTable.reloadData() } } } } } extension Statistics: NSTabViewDelegate { func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { if tabView == tabs { guard let item = tabViewItem else { return } resizeWindowToFitTab(item) } } }
mit
489abdc485bfd828b07de59a634ea596
33.47541
100
0.608179
4.948235
false
false
false
false
julianshen/SwSelect
SwSelect/HTML.swift
1
5665
// // HTML.swift // SwSelect // // Created by Julian Shen on 2015/10/5. // Copyright © 2015年 cowbay.wtf. All rights reserved. // import Foundation import libxml2 public enum SwHTMLNodeType { case ErrorNode case TextNode case DocumentNode case ElementNode case CommentNode case DoctypeNode } public typealias SwHTMLAttribute = (name:String, val:String) public struct SwHTMLNode:CustomStringConvertible { let _node: xmlNodePtr public var tag:String? { let _tag = String.fromCString(UnsafePointer<CChar>(_node.memory.name)) return _tag } public var data:String { if _node.memory.type == XML_ELEMENT_NODE { return tag! } let _data = String.fromCString(UnsafePointer<CChar>(_node.memory.content)) ?? "" return _data } public var text:String { var result:String = "" for c in children { switch c.type { case .TextNode: result += c.data case .ElementNode: result += c.text default: break } } return result } public var type:SwHTMLNodeType { switch(_node.memory.type.rawValue) { case XML_ELEMENT_NODE.rawValue: return .ElementNode case XML_TEXT_NODE.rawValue: return .TextNode case XML_COMMENT_NODE.rawValue: return .CommentNode case XML_DOCUMENT_NODE.rawValue: return .DocumentNode case XML_DOCUMENT_TYPE_NODE.rawValue: return .DoctypeNode default: return .ErrorNode } } public var ns:String? { let _ns = String.fromCString(UnsafePointer<CChar>(_node.memory.ns)) return _ns } public var attributes:AnySequence<SwHTMLAttribute> { let properties = _node.memory.properties if(properties != nil) { return AnySequence<SwHTMLAttribute> { _ -> AnyGenerator<SwHTMLAttribute> in var cursor = properties return anyGenerator { if cursor == nil { return nil } let current = cursor //Assign current cursor = cursor.memory.next //Move cursor to next let name = String.fromCString(UnsafePointer<CChar>(current.memory.name)) ?? "" let v = xmlGetProp(self._node, current.memory.name) let val = String.fromCString(UnsafePointer<CChar>(v)) ?? "" if v != nil { xmlFree(v) } return SwHTMLAttribute(name, val) } } } else { return AnySequence<SwHTMLAttribute> { _ -> EmptyGenerator<SwHTMLAttribute> in return EmptyGenerator<SwHTMLAttribute>() } } } public func attr(name: String) -> String? { let v = xmlGetProp(self._node, name) defer { if v != nil { xmlFree(v) } } if let val = String.fromCString(UnsafePointer<CChar>(v)) { return val } return nil } public var children:AnySequence<SwHTMLNode> { let _children = _node.memory.children if _children == nil { return AnySequence<SwHTMLNode> { _ -> EmptyGenerator<SwHTMLNode> in return EmptyGenerator<SwHTMLNode>() } } return AnySequence<SwHTMLNode> { _ -> AnyGenerator<SwHTMLNode> in var cursor = _children return anyGenerator { if cursor == nil { return nil } let current = cursor cursor = cursor.memory.next return SwHTMLNode(_node: current) } } } public var firstChild:SwHTMLNode? { for c in children { return c } return nil } public var lastChild:SwHTMLNode? { var n:SwHTMLNode? for c in children { n = c } return n } public var nextSibling:SwHTMLNode? { let next = _node.memory.next if(next == nil) { return nil } return SwHTMLNode(_node: next) } public var prevSibling:SwHTMLNode? { let prev = _node.memory.prev if(prev == nil) { return nil } return SwHTMLNode(_node: prev) } public var parent:SwHTMLNode? { let p = _node.memory.parent if(p == nil) { return nil } return SwHTMLNode(_node: p) } public var description:String { if type == .ElementNode { var str:String = "<" str += self.tag ?? "" for attr in self.attributes { str += " " + attr.name + "=\"" + attr.val + "\"" } str += ">" return str } else { return self.data ?? "" } } } extension SwHTMLNode: Equatable {} public func ==(lhs: SwHTMLNode, rhs: SwHTMLNode) -> Bool { return lhs._node == rhs._node }
mit
3d5548b810a327c45df83cd02c5c8449
24.504505
98
0.475804
5.001767
false
false
false
false
alsfox/ZYJModel
ZYJModel/ZYJModel/Extension/ZYJModel+Update.swift
1
2573
// // ZYJModel+Update.swift // ZYJModel // // Created by 张亚举 on 16/6/24. // Copyright © 2016年 张亚举. All rights reserved. // import UIKit extension ZYJModel { /// 更新 Model internal func zyj_update(resBlock: (res: Bool) -> ()) { self.dynamicType.zyj_find(hostId: self.zyj_replaceHostId()) { (result) in if result != nil { let modelSql = self.zyj_updateKeyValue() let superHostId = self.zyj_superHostId != 0 ? "AND zyj_superHostId = \(self.zyj_superHostId) " : "" let superName = self.zyj_superName != nil ? "AND zyj_superName = '\(self.zyj_superName!)' " : "" let superProName = self.zyj_superPerNmae != nil ? "AND zyj_superPerNmae = '\(self.zyj_superPerNmae!)'" : "" let sql = "UPDATE \(self.classForCoder) SET \(modelSql) WHERE zyj_hostId = \(self.zyj_replaceHostId()) \(superHostId) \(superName) \(superProName) ;" self.dynamicType.zyj_select(wheres: nil, results: { (results) in HHLog("\(results)") }) HHLog("\(sql)"); let insertRes = ZYJFMDB.executeUpdate(sql) resBlock(res:insertRes); }else { HHLog("数据库没有此条数据") } } } /// 单个数据更新 func zyj_updateKeyValue() -> String { var names = String() self.enumratePer { (ivar) in var proprety = self.zyj_modelKeyValue(ivar: ivar as ZYJIvar) if let valueArr = proprety.arrValue { valueArr.zyj_deleteAction(superId: self.zyj_replaceHostId(), superProName: "\(self.classForCoder)", superName: ivar.ivarName, deleteBlock: { }) valueArr.zyj_inserts(superId: self.zyj_replaceHostId(), superProName: "\(self.classForCoder)", superName: ivar.ivarName, block: { }) proprety.value = "" } names.append(" \(proprety.nsme) = \(proprety.value),") } return (names as NSString).substring(to: (names as NSString).length - 1); } }
mit
ae9400fd8683e3ef1a8fd8fbf684eb2b
31.358974
167
0.459984
4.263514
false
false
false
false
hffmnn/Swiftz
Swiftz/JSON.swift
1
9930
// // JSON.swift // swiftz // // Created by Maxwell Swadling on 5/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation public enum JSONValue : Printable { case JSONArray([JSONValue]) case JSONObject(Dictionary<String, JSONValue>) case JSONNumber(Double) case JSONString(String) case JSONBool(Bool) case JSONNull() private func values() -> NSObject { switch self { case let JSONArray(xs): return NSArray(array: xs.map { $0.values() }) case let JSONObject(xs): return NSDictionary(dictionary: map(dict: xs)({ (k: String, v: JSONValue) -> (String, AnyObject) in return (NSString(string: k), v.values()) })) case let JSONNumber(n): return NSNumber(double: n) case let JSONString(s): return NSString(string: s) case let JSONBool(b): return NSNumber(bool: b) case let JSONNull(): return NSNull() } } // we know this is safe because of the NSJSONSerialization docs private static func make(a : NSObject) -> JSONValue { switch a { case let xs as NSArray: return .JSONArray(xs.mapToArray { self.make($0 as NSObject) }) case let xs as NSDictionary: return JSONValue.JSONObject(xs.mapValuesToDictionary { (k: AnyObject, v: AnyObject) in return (String(k as NSString), self.make(v as NSObject)) }) case let xs as NSNumber: // TODO: number or bool?... return .JSONNumber(Double(xs.doubleValue)) case let xs as NSString: return .JSONString(String(xs)) case let xs as NSNull: return .JSONNull() default: return error("Non-exhaustive pattern match performed."); } } public func encode() -> NSData? { var e: NSError? let opts: NSJSONWritingOptions = nil // TODO: check s is a dict or array return NSJSONSerialization.dataWithJSONObject(self.values(), options:opts, error: &e) } // TODO: should this be optional? public static func decode(s : NSData) -> JSONValue? { var e: NSError? let opts: NSJSONReadingOptions = nil let r: AnyObject? = NSJSONSerialization.JSONObjectWithData(s, options: opts, error: &e) if let json: AnyObject = r { return make(json as NSObject) } else { return .None } } public static func decode(s : String) -> JSONValue? { return JSONValue.decode(s.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) } public var description : String { get { switch self { case .JSONNull(): return "JSONNull()" case let .JSONBool(b): return "JSONBool(\(b))" case let .JSONString(s): return "JSONString(\(s))" case let .JSONNumber(n): return "JSONNumber(\(n))" case let .JSONObject(o): return "JSONObject(\(o))" case let .JSONArray(a): return "JSONArray(\(a))" } } } } // you'll have more fun if you match tuples // Equatable public func ==(lhs : JSONValue, rhs : JSONValue) -> Bool { switch (lhs, rhs) { case (.JSONNull(), .JSONNull()): return true case let (.JSONBool(l), .JSONBool(r)) where l == r: return true case let (.JSONString(l), .JSONString(r)) where l == r: return true case let (.JSONNumber(l), .JSONNumber(r)) where l == r: return true case let (.JSONObject(l), .JSONObject(r)) where equal(l, r, { (v1: (String, JSONValue), v2: (String, JSONValue)) in v1.0 == v2.0 && v1.1 == v2.1 }): return true case let (.JSONArray(l), .JSONArray(r)) where equal(l, r, { $0 == $1 }): return true default: return false } } public func !=(lhs : JSONValue, rhs : JSONValue) -> Bool { return !(lhs == rhs) } // someday someone will ask for this //// Comparable //func <=(lhs: JSValue, rhs: JSValue) -> Bool { // return false; //} // //func >(lhs: JSValue, rhs: JSValue) -> Bool { // return !(lhs <= rhs) //} // //func >=(lhs: JSValue, rhs: JSValue) -> Bool { // return (lhs > rhs || lhs == rhs) //} // //func <(lhs: JSValue, rhs: JSValue) -> Bool { // return !(lhs >= rhs) //} public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs) >>- { A.fromJSON($0) } default: return .None } } public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A]? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs) >>- JArrayFrom<A, A>.fromJSON default: return .None } } public func <? <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A]? { switch lhs { case let .JSONObject(d): return resolveKeypath(d, rhs) >>- JDictionaryFrom<A, A>.fromJSON default: return .None } } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> A { if let r : A = (lhs <? rhs) { return r } return error("Cannot find value at keypath \(rhs) in JSON object \(rhs).") } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [A] { if let r : [A] = (lhs <? rhs) { return r } return error("Cannot find array at keypath \(rhs) in JSON object \(rhs).") } public func <! <A : JSONDecodable where A == A.J>(lhs : JSONValue, rhs : JSONKeypath) -> [String:A] { if let r : [String:A] = (lhs <? rhs) { return r } return error("Cannot find object at keypath \(rhs) in JSON object \(rhs).") } // traits public protocol JSONDecodable { typealias J = Self class func fromJSON(x: JSONValue) -> J? } public protocol JSONEncodable { typealias J class func toJSON(x: J) -> JSONValue } // J mate public protocol JSON : JSONDecodable, JSONEncodable { } // instances extension Bool : JSON { public static func fromJSON(x : JSONValue) -> Bool? { switch x { case let .JSONBool(n): return n case .JSONNumber(0): return false case .JSONNumber(1): return true default: return Optional.None } } public static func toJSON(xs : Bool) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension Int : JSON { public static func fromJSON(x : JSONValue) -> Int? { switch x { case let .JSONNumber(n): return Int(n) default: return Optional.None } } public static func toJSON(xs : Int) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension Double : JSON { public static func fromJSON(x : JSONValue) -> Double? { switch x { case let .JSONNumber(n): return n default: return Optional.None } } public static func toJSON(xs : Double) -> JSONValue { return JSONValue.JSONNumber(xs) } } extension NSNumber : JSON { public class func fromJSON(x : JSONValue) -> NSNumber? { switch x { case let .JSONNumber(n): return NSNumber(double: n) default: return Optional.None } } public class func toJSON(xs : NSNumber) -> JSONValue { return JSONValue.JSONNumber(Double(xs)) } } extension String : JSON { public static func fromJSON(x : JSONValue) -> String? { switch x { case let .JSONString(n): return n default: return Optional.None } } public static func toJSON(xs : String) -> JSONValue { return JSONValue.JSONString(xs) } } // or unit... extension NSNull : JSON { public class func fromJSON(x : JSONValue) -> NSNull? { switch x { case .JSONNull(): return NSNull() default: return Optional.None } } public class func toJSON(xs : NSNull) -> JSONValue { return JSONValue.JSONNull() } } // container types should be split public struct JArrayFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable { public typealias J = [A] public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONArray(xs): let r = xs.map({ B.fromJSON($0) }) let rp = mapFlatten(r) if r.count == rp.count { return rp } else { return nil } default: return Optional.None } } } public struct JArrayTo<A, B : JSONEncodable where B.J == A> : JSONEncodable { public typealias J = [A] public static func toJSON(xs: J) -> JSONValue { return JSONValue.JSONArray(xs.map { B.toJSON($0) } ) } } public struct JArray<A, B : JSON where B.J == A> : JSON { public typealias J = [A] public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONArray(xs): let r = xs.map({ B.fromJSON($0) }) let rp = mapFlatten(r) if r.count == rp.count { return rp } else { return nil } default: return Optional.None } } public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONArray(xs.map { B.toJSON($0) } ) } } public struct JDictionaryFrom<A, B : JSONDecodable where B.J == A> : JSONDecodable { public typealias J = Dictionary<String, A> public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONObject(xs): return map(dict: xs)({ k, x in return (k, B.fromJSON(x)!) }) default: return Optional.None } } } public struct JDictionaryTo<A, B : JSONEncodable where B.J == A> : JSONEncodable { public typealias J = Dictionary<String, A> public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONObject(map(dict: xs)({ k, x -> (String, JSONValue) in return (k, B.toJSON(x)) })) } } public struct JDictionary<A, B : JSON where B.J == A> : JSON { public typealias J = Dictionary<String, A> public static func fromJSON(x : JSONValue) -> J? { switch x { case let .JSONObject(xs): return map(dict: xs)({ k, x in return (k, B.fromJSON(x)!) }) default: return Optional.None } } public static func toJSON(xs : J) -> JSONValue { return JSONValue.JSONObject(map(dict: xs)({ k, x in return (k, B.toJSON(x)) })) } } /// MARK: Implementation Details private func resolveKeypath(lhs : Dictionary<String, JSONValue>, rhs : JSONKeypath) -> JSONValue? { if rhs.path.isEmpty { return .None } if let o = lhs[rhs.path.first!] { switch o { case let .JSONObject(d) where rhs.path.count > 1: let tail = Array(rhs.path[1..<rhs.path.count]) return resolveKeypath(d, JSONKeypath(tail)) default: return o } } return .None }
bsd-3-clause
cd700627b59ce9d381240a88b70908da
22.419811
108
0.643505
3.155386
false
false
false
false
qichen0401/QCUtilitySwift
QCUtilitySwift/Classes/ReviewManager.swift
1
1249
// // ReviewManager.swift // Pods // // Created by Qi Chen on 6/6/17. // // import UIKit import StoreKit public class ReviewManager: NSObject { struct defaultValues { static let fireCount = 3 static let countKey = "reviewManager_Count" } public static let shared = ReviewManager() public var fireCount = defaultValues.fireCount @objc public func count() { let userDefaults = UserDefaults.standard var count = userDefaults.integer(forKey: defaultValues.countKey) count += 1 if count >= fireCount { count = 0 if #available(iOS 10.3, *) { SKStoreReviewController.requestReview() } else { // Fallback on earlier versions } } userDefaults.set(count, forKey: defaultValues.countKey) userDefaults.synchronize() } public func start() { NotificationCenter.default.addObserver(self, selector: #selector(ReviewManager.count), name: .UIApplicationWillEnterForeground, object: nil) count() } public func start(fireCount fc: Int) { RateAppManager.fireCount = fc start() } }
mit
2406f812cd3e8c752d48becc50d3efc7
23.98
148
0.586869
4.822394
false
false
false
false
GlobusLTD/components-ios
Demo/Sources/ViewControllers/DataView/Calendar/CalendarDataViewController.swift
1
2166
// // Globus // import Globus class CalendarDataViewController: GLBDataViewController { // MARK: - Property public var dataViewContainer: GLBDataViewCalendarContainer? // MARK: - Init / Free override func setup() { super.setup() self.edgesForExtendedLayout = UIRectEdge(rawValue: 0); self.title = "CalendarDataView" } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() self.navigationItem.glb_removeAllLeftBarButtonItems(animated: false) self.navigationItem.glb_addLeftBarButtonNormalImage(UIImage(named: "MenuButton"), target: self, action: #selector(pressedMenu(_ :)), animated: false) } // MARK: - GLBViewController override func update() { super.update() self.dataView?.batchUpdate({ let now = NSDate() self.dataViewContainer?.prepareBegin(now.glb_beginningOfMonth()!, end: now.glb_endOfMonth()!) }) } override func clear() { self.dataView?.batchUpdate({ self.dataViewContainer?.cleanup() }) super.clear() } // MARK: - GLBDataViewController override func configureDataView() { self.dataViewContainer = GLBDataViewCalendarContainer(calendar: Calendar.current) self.dataView?.registerIdentifier(GLBDataViewCalendarMonthIdentifier, withViewClass: CalendarMonthDataViewCell.self) self.dataView?.registerIdentifier(GLBDataViewCalendarWeekdayIdentifier, withViewClass: CalendarWeekdayDataViewCell.self) self.dataView?.registerIdentifier(GLBDataViewCalendarDayIdentifier, withViewClass: CalendarDayDataViewCell.self) self.dataView?.container = self.dataViewContainer; } override func cleanupDataView() { super.cleanupDataView(); self.dataViewContainer = nil; } // MARK: - Actions @IBAction internal func pressedMenu(_ sender: Any) { self.glb_slideViewController?.showLeftViewController(animated: true, complete: nil) } }
mit
91422a8f6665c2a50bb7a759c903763d
28.27027
157
0.645891
4.990783
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/ManagementApi/RequestsParams/CLDRenameRequestParams.swift
1
3165
// // CLDRenameRequestParams.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** This class represents the different parameters that can be passed when performing a rename request. */ @objcMembers open class CLDRenameRequestParams: CLDRequestParams { // MARK: Init public override init() { super.init() } /** Initializes a CLDRenameRequestParams instance. - parameter fromPublicId: The current identifier of the uploaded asset. - parameter toPublicId: The new identifier to assign to the uploaded asset. - parameter overwrite: A boolean parameter indicating whether or not to overwrite an existing image with the target Public ID. Default: false. - parameter invalidate: A boolean parameter whether to invalidate CDN cached copies of the image (and all its transformed versions). Default: false. - returns: A new instance of CLDRenameRequestParams. */ internal init(fromPublicId: String, toPublicId: String, overwrite: Bool? = nil, invalidate: Bool? = nil) { super.init() setParam(RenameParams.FromPublicId.rawValue, value: fromPublicId) setParam(RenameParams.ToPublicId.rawValue, value: toPublicId) setParam(RenameParams.Overwrite.rawValue, value: overwrite) setParam(RenameParams.Invalidate.rawValue, value: invalidate) } /** Initializes a CLDRenameRequestParams instance. - parameter params: A dictionary of the request parameters. - returns: A new instance of CLDRenameRequestParams. */ public init(params: [String : AnyObject]) { super.init() self.params = params } // MARK: - Rename Params fileprivate enum RenameParams: String { case FromPublicId = "from_public_id" case ToPublicId = "to_public_id" case Overwrite = "overwrite" case Invalidate = "invalidate" } }
mit
b734497c699f8c0f4243bb4924ece802
40.103896
160
0.68436
4.730942
false
false
false
false
jpush/aurora-imui
iOS/IMUIMessageCollectionView/Views/IMUIMessageStatusView.swift
1
1432
// // IMUIMessageStatusView.swift // IMUIChat // // Created by oshumini on 2017/5/14. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit public class IMUIMessageDefaultStatusView: UIButton, IMUIMessageStatusViewProtocol { public func layoutMediaDownloading() { } public func layoutMediaDownloadFail() { } public var statusViewID: String { return "" } var activityIndicator = UIActivityIndicatorView() override init(frame: CGRect) { super.init(frame: frame) activityIndicator.hidesWhenStopped = true self.addSubview(activityIndicator) self.setImage(UIImage.imuiImage(with: "message_status_fail"), for: .selected) } override public var frame: CGRect { didSet { activityIndicator.color = UIColor.black activityIndicator.frame = frame activityIndicator.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - IMUIMessageStatusViewProtocol public func layoutFailedStatus() { self.isSelected = true activityIndicator.stopAnimating() } public func layoutSendingStatus() { self.isSelected = false activityIndicator.startAnimating() } public func layoutSuccessStatus() { self.isSelected = false activityIndicator.stopAnimating() } }
mit
42411a0b7c0cbfac42aba62c43107699
21.68254
87
0.696291
4.507886
false
false
false
false
panjinqiang11/Swift-WeiBo
WeiBo/WeiBo/Class/View/Compose/PJComposeButton.swift
1
1264
// // PJComposeButton.swift // WeiBo // // Created by 潘金强 on 16/7/18. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit //自定义composeView的 button class PJComposeButton: UIButton { var composeMenu :PJComposeButtonList? override init(frame: CGRect) { super.init(frame: frame) setUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUI() { titleLabel?.font = UIFont.systemFontOfSize(15) setTitleColor(UIColor.grayColor(), forState: .Normal) titleLabel?.textAlignment = .Center } // 重写highlighted属性 override var highlighted: Bool { get { return false } set { } } override func layoutSubviews() { super.layoutSubviews() imageView?.x = 0 imageView?.y = 0 imageView?.width = width imageView?.height = width titleLabel?.x = 0 titleLabel?.y = width titleLabel?.width = width titleLabel?.height = height - width } }
mit
9fe6adf4a6a63db01947992565aaa6aa
18.571429
61
0.531225
4.77907
false
false
false
false
LuAndreCast/iOS_WatchProjects
watchOS2/Heart Rate/v3 Heart Rate Stream/HealthStoreWorkout.swift
1
4761
// // Workout.swift // HealthWatchExample // // Created by Luis Castillo on 8/5/16. // Copyright © 2016 LC. All rights reserved. // import Foundation import HealthKit protocol HealthStoreWorkoutDelegate { func healthStoreWorkout_stateChanged(_ state:HKWorkoutSessionState) func healthStoreWorkout_error(_ error:NSError) } @objc final class HealthStoreWorkout: NSObject, HKWorkoutSessionDelegate { fileprivate var session: HKWorkoutSession? { didSet { self.session?.delegate = self } }// let healthStore: HKHealthStore? = { guard HKHealthStore.isHealthDataAvailable() else { return nil } return HKHealthStore() }() var isMonitoring:Bool { if session != nil { return true } return false } var delegate:HealthStoreWorkoutDelegate? //MARK: - Start Workout func startWorkout(_ workoutSession:HKWorkoutSession = HKWorkoutSession(activityType: .running, locationType: .indoor) ) { //health data avaliable? guard HKHealthStore.isHealthDataAvailable() else { //notify listener let error = NSError(domain: Errors.healthStore.domain, code: Errors.healthStore.avaliableData.code, userInfo:Errors.healthStore.avaliableData.description ) self.delegate?.healthStoreWorkout_error(error) return } //valid session? self.session = workoutSession guard let currSession = self.session else { //notify listener let error:NSError = NSError(domain: Errors.workOut.domain, code: Errors.workOut.start.code, userInfo:Errors.workOut.start.description ) self.delegate?.healthStoreWorkout_error(error) return } //starting session self.healthStore?.start(currSession) }//eom //MARK: - End Workout func endWorkout() { //health data avaliable? guard HKHealthStore.isHealthDataAvailable() else { //notify listener let error = NSError(domain: Errors.healthStore.domain, code: Errors.healthStore.avaliableData.code, userInfo:Errors.healthStore.avaliableData.description ) self.delegate?.healthStoreWorkout_error(error) return } //valid session? guard let currSession = self.session else { //notify listener let error:NSError = NSError(domain: Errors.workOut.domain, code: Errors.workOut.end.code, userInfo:Errors.workOut.end.description ) self.delegate?.healthStoreWorkout_error(error) return } //ending session self.healthStore?.end(currSession) }//eom //MARK: Delegates func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { DispatchQueue.main.async { [unowned self] in switch toState { case .notStarted: if verbose { print("workoutSession Changed to 'Not Started'") } //notify listener self.delegate?.healthStoreWorkout_stateChanged(HKWorkoutSessionState.notStarted) break case .running: if verbose { print("workoutSession Changed to 'Running'") } //notify listener self.delegate?.healthStoreWorkout_stateChanged(HKWorkoutSessionState.running) case .ended: if verbose { print("workoutSession Changed to 'Ended'") } //notify listener self.delegate?.healthStoreWorkout_stateChanged(HKWorkoutSessionState.ended) default: break } } }//eom func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) { //notify listener self.delegate?.healthStoreWorkout_error(error as NSError) }//eom }//eoc
mit
4d4ac9c94de765c7f714fa8bcc6f0705
30.111111
123
0.533403
5.826193
false
false
false
false
dsoisson/SwiftLearningExercises
Todos_4.playground/Sources/Todo.swift
1
1841
import Foundation //public enum TodoStatus: String { // case NotStarted = "Not Started" // case InProgress = "In Progress" // case Stopped // case Completed //} // //public struct Coordinate { // // public var latitude: Double // public var longitude: Double // // public init(latitude: Double, longitude: Double) { // // self.latitude = latitude // self.longitude = longitude // } //} // //public class Person { // // public var id: String? // public var first: String? // public var last: String? // // public init() { // // } //} // public class Todo { public var body: String? public var done: Bool? public var id: Int? public var priority: Int? public var title: String? // public var description: String { // // return "\tid: \(id ?? "")\n\ttitle: \(title ?? "")" // //} public var asDictionary: [String:AnyObject] { var dictionary = [String:AnyObject]() dictionary["body"] = body dictionary["done"] = done dictionary["id"] = id dictionary["priority"] = priority dictionary["title"] = title return dictionary } public init() { } } public func ==(lhs: Todo, rhs: Todo) -> Bool { return lhs.id == rhs.id } extension Todo: Equatable {} extension Todo: Hashable { public var hashValue: Int { return "\(title)".hashValue } } extension Array where Element: Todo { public var asDictionary: [[String:AnyObject]] { var dictionaries = [[String:AnyObject]]() for element in self { dictionaries.append(element.asDictionary) } return dictionaries } }
mit
66737456f6a9e6df5e5e046c1fb8b6fa
17.59596
61
0.533406
4.241935
false
false
false
false
IamAlchemist/DemoDynamicCollectionView
DemoDynamicCollectionView/NewtownianCollectionViewController.swift
1
1091
// // NewtownianCollectionViewController.swift // DemoDynamicCollectionView // // Created by Wizard Li on 1/6/16. // Copyright © 2016 morgenworks. All rights reserved. // import UIKit class NewtownianCollectionViewController : UICollectionViewController { var collectionViewDatasource : NewtownianCollectionViewDataSource? override func viewDidLoad() { super.viewDidLoad() collectionViewDatasource = NewtownianCollectionViewDataSource() collectionView!.dataSource = collectionViewDatasource } @IBAction func addButtonTapped(sender: UIBarButtonItem) { collectionViewDatasource?.increaseItem() collectionView?.reloadData() } @IBAction func deleteButtonTapped(sender: UIBarButtonItem) { if let collectionViewDatasource = collectionViewDatasource where collectionViewDatasource.data.count == 0 { navigationController?.popViewControllerAnimated(true) } collectionViewDatasource?.decreaseItem() collectionView?.reloadData() } }
mit
dddce64adda2dd791d4fd81110376b8c
29.277778
71
0.706422
5.923913
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/ThirdLibrary/EFQRCodeSource/CIImage+.swift
1
2646
// // CIImage+.swift // Pods // // Created by EyreFree on 2017/3/29. // // Copyright (c) 2017 EyreFree <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage public extension CIImage { // Convert CIImage To CGImage // http://wiki.hawkguide.com/wiki/Swift:_Convert_between_CGImage,_CIImage_and_UIImage public func toCGImage() -> CGImage? { return CIContext().createCGImage(self, from: self.extent) } // Size func size() -> CGSize { return self.extent.size } // Get QRCode from image func recognizeQRCode(options: [String : Any]? = nil) -> [String] { var result = [String]() let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: options) guard let features = detector?.features(in: self) else { return result } for feature in features { if let tryString = (feature as? CIQRCodeFeature)?.messageString { result.append(tryString) } } return result } // Create QR CIImage static func generateQRCode(string: String, inputCorrectionLevel: EFInputCorrectionLevel = .m) -> CIImage? { let stringData = string.data(using: String.Encoding.utf8) if let qrFilter = CIFilter(name: "CIQRCodeGenerator") { qrFilter.setValue(stringData, forKey: "inputMessage") qrFilter.setValue(["L", "M", "Q", "H"][inputCorrectionLevel.rawValue], forKey: "inputCorrectionLevel") return qrFilter.outputImage } return nil } }
mit
76245237e5c1a405cd89f632da033555
38.492537
114
0.677627
4.447059
false
false
false
false
d3st1ny94/LiquidHazard
LiquidHazard/ViewController.swift
1
11926
// // ViewController.swift // LiquidHazard // // Created by adan de la pena on 6/20/16. // Copyright © 2016 adan de la pena. All rights reserved. // import UIKit import CoreMotion class ViewController: UIViewController { let gravity: Float = 9.80665 let ptmRatio: Float = 32 let particleRadius: Float = 4 var particleSystem: UnsafeMutablePointer<Void>! var uniformBuffer: MTLBuffer! = nil let motionManager: CMMotionManager = CMMotionManager() var device: MTLDevice! = nil var metalLayer: CAMetalLayer! = nil var vertexData:[Float] = [] var particleCount: Int = 0 var vertexBuffer: MTLBuffer! = nil var secondBuffer: MTLBuffer! = nil var GridMember: Grid? var gridData: [[Float]] = [[]] var pipelineGoalState: MTLRenderPipelineState! = nil var pipelineState: MTLRenderPipelineState! = nil var pipelineWallState: MTLRenderPipelineState! = nil var commandQueue: MTLCommandQueue! = nil var goalBuffer: MTLBuffer! = nil var StarterNumber: Int = 0 override func viewDidLoad() { super.viewDidLoad() resetGame() /* LiquidFun.createEdgeWithOrigin(Vector2D(x: 0, y: 0), destination: Vector2D(x: screenWidth / ptmRatio, y: screenHeight / ptmRatio)) */ createMetalLayer() gridData = (GridMember?.getVertexData())! refreshVertexBuffer() refreshUniformBuffer() buildRenderPipeline() render() let displayLink = CADisplayLink(target: self, selector: Selector("update:")) displayLink.frameInterval = 1 displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: { (accelerometerData, error) -> Void in if let data = accelerometerData { let acceleration = data.acceleration let gravityX = self.gravity * Float(acceleration.x) let gravityY = self.gravity * Float(acceleration.y) LiquidFun.setGravity(Vector2D(x: gravityX, y: gravityY)) } }) } func resetGame(){ LiquidFun.resetWorldWithGravity(Vector2D(x: 0, y: -gravity)) particleSystem = LiquidFun.createParticleSystemWithRadius(particleRadius / ptmRatio, dampingStrength: 0.2, gravityScale: 1, density: 1.2) LiquidFun.setParticleLimitForSystem(particleSystem, maxParticles: 1500) let screenSize: CGSize = UIScreen.mainScreen().bounds.size let screenWidth = Float(screenSize.width) let screenHeight = Float(screenSize.height) LiquidFun.createParticleBoxForSystem(particleSystem, position: Vector2D(x: screenWidth * 0.5 / ptmRatio, y: screenHeight * 0.5 / ptmRatio), size: Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio)) //count our particles for goal StarterNumber = Int(LiquidFun.particleCountForSystem(particleSystem)) LiquidFun.createEdgeBoxWithOrigin(Vector2D(x: 0, y: 0), size: Size2D(width: screenWidth / ptmRatio, height: screenHeight / ptmRatio)) GridMember = Grid(NumberOfCols: 18, NumberOfRows: 12, screenSize: Size2D(width : screenWidth, height: screenHeight), ptmRatio: ptmRatio) LiquidFun.createGoalWithSizeAndOrigin(Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio), origin: Vector2D(x: 0,y: 0)) vertexData = [ 0.0, 0.0, 0.0, 0, 100, 0.0, 100, 00, 0.0, 100, 100, 0.0] } func yodatime(vData: [Float]) -> MTLBuffer { let vSize = vData.count * sizeofValue(vData[0]) let ret:MTLBuffer? = device?.newBufferWithBytes(vData, length: vSize, options: []) return ret! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func update(displayLink:CADisplayLink) { autoreleasepool { LiquidFun.worldStep(displayLink.duration, velocityIterations: 8, positionIterations: 5) self.refreshVertexBuffer() self.render() } } func createMetalLayer() { device = MTLCreateSystemDefaultDevice() metalLayer = CAMetalLayer() metalLayer.device = device metalLayer.pixelFormat = .BGRA8Unorm metalLayer.framebufferOnly = true metalLayer.frame = view.layer.frame view.layer.addSublayer(metalLayer) } func refreshVertexBuffer () { particleCount = Int(LiquidFun.particleCountForSystem(particleSystem)) let positions = LiquidFun.particlePositionsForSystem(particleSystem) let bufferSize = sizeof(Float) * particleCount * 2 vertexBuffer = device.newBufferWithBytes(positions, length: bufferSize, options: []) } func makeOrthographicMatrix(left left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> [Float] { let ral = right + left let rsl = right - left let tab = top + bottom let tsb = top - bottom let fan = far + near let fsn = far - near return [2.0 / rsl, 0.0, 0.0, 0.0, 0.0, 2.0 / tsb, 0.0, 0.0, 0.0, 0.0, -2.0 / fsn, 0.0, -ral / rsl, -tab / tsb, -fan / fsn, 1.0] } func printParticleInfo() { let count = Int(LiquidFun.particleCountForSystem(particleSystem)) print("There are \(count) particles present") let positions = UnsafePointer<Vector2D>(LiquidFun.particlePositionsForSystem(particleSystem)) for i in 0..<count { let position = positions[i] print("particle: \(i) position: (\(position.x), \(position.y))") } } func refreshUniformBuffer () { // 1 let screenSize: CGSize = UIScreen.mainScreen().bounds.size let screenWidth = Float(screenSize.width) let screenHeight = Float(screenSize.height) let ndcMatrix = makeOrthographicMatrix(left: 0, right: screenWidth, bottom: 0, top: screenHeight, near: -1, far: 1) var radius = particleRadius var ratio = ptmRatio // 2 let floatSize = sizeof(Float) let float4x4ByteAlignment = floatSize * 4 let float4x4Size = floatSize * 16 let paddingBytesSize = float4x4ByteAlignment - floatSize * 2 let uniformsStructSize = float4x4Size + floatSize * 2 + paddingBytesSize // 3 uniformBuffer = device.newBufferWithLength(uniformsStructSize, options: []) let bufferPointer = uniformBuffer.contents() memcpy(bufferPointer, ndcMatrix, float4x4Size) memcpy(bufferPointer + float4x4Size, &ratio, floatSize) memcpy(bufferPointer + float4x4Size + floatSize, &radius, floatSize) } func buildRenderPipeline() { // 1 let defaultLibrary = device.newDefaultLibrary() var fragmentProgram = defaultLibrary?.newFunctionWithName("basic_fragment") var vertexProgram = defaultLibrary?.newFunctionWithName("particle_vertex") // 2 let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexProgram pipelineDescriptor.fragmentFunction = fragmentProgram pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm do { pipelineState = try device.newRenderPipelineStateWithDescriptor(pipelineDescriptor) } catch { print("Error occurred when creating render pipeline state: \(error)"); } fragmentProgram = defaultLibrary!.newFunctionWithName("wall_fragment") vertexProgram = defaultLibrary!.newFunctionWithName("basic_vertex") let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm do{ pipelineWallState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) } catch { } fragmentProgram = defaultLibrary!.newFunctionWithName("goal_fragment") vertexProgram = defaultLibrary!.newFunctionWithName("basic_vertex") let pipelineStateDescriptor2 = MTLRenderPipelineDescriptor() pipelineStateDescriptor2.vertexFunction = vertexProgram pipelineStateDescriptor2.fragmentFunction = fragmentProgram pipelineStateDescriptor2.colorAttachments[0].pixelFormat = .BGRA8Unorm do{ pipelineGoalState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor2) } catch { } // 3 commandQueue = device.newCommandQueue() } func youBallin() -> Bool{ let ballsin = Int(LiquidFun.getBallIn()); if ballsin == StarterNumber - 1 { return true } else { return false } } func render() { if let drawable = metalLayer.nextDrawable() { let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .Clear renderPassDescriptor.colorAttachments[0].storeAction = .Store renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) let commandBuffer = commandQueue.commandBuffer() let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) renderEncoder.setRenderPipelineState(pipelineState) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0) renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, atIndex: 1) if particleCount > 1 { renderEncoder.drawPrimitives(.Point, vertexStart: 0, vertexCount: particleCount, instanceCount: 1) } else { if youBallin() { //win resetGame(); } else { //lose } } renderEncoder.setRenderPipelineState(pipelineWallState) for i in 1...gridData.count{ secondBuffer = yodatime(gridData[i-1]) renderEncoder.setVertexBuffer(secondBuffer, offset: 0, atIndex: 2) renderEncoder.drawPrimitives(.LineStrip, vertexStart: 0, vertexCount: 4) } renderEncoder.setRenderPipelineState(pipelineGoalState) goalBuffer = yodatime(vertexData) renderEncoder.setVertexBuffer(goalBuffer, offset: 0, atIndex: 2) renderEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4) renderEncoder.endEncoding() commandBuffer.presentDrawable(drawable) commandBuffer.commit() } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // for touch in touches { /* let touchLocation = touch.locationInView(view) let position = Vector2D(x: Float(touchLocation.x) / ptmRatio, y: Float(view.bounds.height - touchLocation.y) / ptmRatio) let size = Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio) LiquidFun.createParticleBoxForSystem(particleSystem, position: position, size: size)*/ // } super.touchesBegan(touches, withEvent:event) } }
gpl-3.0
a25480da0f037efdf8dd22d3d5489fa9
38.61794
208
0.633543
4.825981
false
false
false
false
tigclaw/days-of-swift
Project 11/DeletingAndRearranging/DeletingAndRearranging/GroceriesTableViewController.swift
1
4976
// // GroceriesTableViewController.swift // PullToRefreshTableView // // Created by Angela Lin on 1/19/17. // Copyright © 2017 Angela Lin. All rights reserved. // import UIKit class GroceryTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class GroceriesTableViewController: UITableViewController { private let cellId = "cellId" var groceryList = ["Milk", "Apple", "Ham", "Eggs", "Pizza", "Flour", "Onions", "Peppers", "Strawberries", "Cheese"] override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Groceries" self.navigationItem.leftBarButtonItem = self.editButtonItem self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(clickAddNew(sender:))) tableView.register(GroceryTableViewCell.self, forCellReuseIdentifier: cellId) // Refresh control is already built into UITableViewController, need to declare a new one first and then set it to the already built-in one. let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(handleRefresh(sender:)), for: .valueChanged) self.refreshControl = refreshControl } // MARK: Functions func clickAddNew(sender: UIBarButtonItem) { print("Clicked +") let alert = UIAlertController(title: "Grocery List", message: "What do you want to add?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { something in if let textField = alert.textFields?.first, let newItem = textField.text { self.groceryList.append(newItem) print("New item added -> \(newItem)") let doneAlert = UIAlertController(title: "Added!", message: "Pull to refresh to see your added item(s)", preferredStyle: .alert) self.present(doneAlert, animated: true, completion: { done in self.perform(#selector(self.dismiss(sender:)), with: doneAlert, afterDelay: 1) } ) } } )) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addTextField(configurationHandler: {(textField) in textField.placeholder = "Enter item" }) present(alert, animated: true, completion: nil) } func dismiss(sender: AnyObject) { self.dismiss(animated: true, completion: nil) } func handleRefresh(sender: AnyObject) { print("Pulled refresh control") tableView.reloadData() refreshControl?.endRefreshing() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groceryList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! GroceryTableViewCell cell.textLabel?.text = groceryList[indexPath.row] cell.accessoryType = .disclosureIndicator cell.selectionStyle = .none return cell } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source print("Item to remove -> \(groceryList[indexPath.row])") groceryList.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { let itemToMove = groceryList[fromIndexPath.row] print("Item to re-arrange -> \(groceryList[fromIndexPath.row]). from index# \(fromIndexPath.row), to: \(to.row)") groceryList.remove(at: fromIndexPath.row) groceryList.insert(itemToMove, at: to.row) } }
mit
8718826e74341173ebf7f351085ba840
35.313869
148
0.621106
5.209424
false
false
false
false
rmavani/SocialQP
QPrint/Controllers/MyProfile/MyProfileViewController.swift
1
18146
// // MyProfileViewController.swift // QPrint // // Created by Admin on 23/02/17. // Copyright © 2017 Admin. All rights reserved. // import UIKit class MyProfileViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ChangePasswordDelegate, SBPickerSelectorDelegate { // MARK: - Initialize IBOutlets @IBOutlet var lblTitle : UILabel! @IBOutlet var imgProfilePic : UIImageView! @IBOutlet var txtFullName : UITextField! @IBOutlet var txtEmailID : UITextField! @IBOutlet var btnEditImage : UIButton! @IBOutlet var btnDateOfBirth : UIButton! @IBOutlet var btnCity : UIButton! @IBOutlet var btnChangePassword : UIButton! @IBOutlet var btnSaveChanges : UIButton! // MARK: - Initialize Variables let imagePickerController: UIImagePickerController = UIImagePickerController() var imgSelectedImage : UIImage! var strUserId : String = "" var strPassword : String = "" var strContactNo : String = "" var isProfileChange = false var arr_City : NSMutableArray = NSMutableArray() var picker: SBPickerSelector = SBPickerSelector.picker() var strCityID : String = "" // MARK: - Initialize override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = true self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false lblTitle.layer.shadowOpacity = 0.5 lblTitle.layer.shadowOffset = CGSize(width : 0.5, height : 0.5) lblTitle.layer.shadowColor = UIColor.darkGray.cgColor let dictData = UserDefaults.standard.data(forKey: "UserData") let dictRegisterData = NSKeyedUnarchiver.unarchiveObject(with: dictData!) as! NSMutableDictionary print(dictRegisterData) strUserId = (dictRegisterData.object(forKey: "userid") as? String)! strContactNo = (dictRegisterData.object(forKey: "contactno") as? String)! txtFullName.text = (dictRegisterData.object(forKey: "firstname") as? String)! txtEmailID.text = (dictRegisterData.object(forKey: "email") as? String)! btnDateOfBirth.setTitle("", for: UIControlState.normal) btnCity.setTitle("", for: UIControlState.normal) let imgUrl : String = dictRegisterData.value(forKey: "profilepic") as! String imgProfilePic.sd_setImage(with: NSURL(string: imgUrl) as URL!, placeholderImage: UIImage(named: "defaul_pic")) self.getCityData() picker.delegate = self } // MARK: - ChangePasswordDelegate Method func hideSavePasswordPopup(controller:ChangePasswordViewController) { self.view.endEditing(true) strPassword = controller.txtConfirmPassword.text! self.changepassword() } func hideCancelPasswordPopup() { self.view.endEditing(true) self.dismissPopupViewController(animationType: .TopBottom) } // MARK: - UIButton Click Events @IBAction func btn_EditImageClick(_ sender: UIButton) { self.view.endEditing(true) let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: NSLocalizedString("Upload Photos", comment: "comment"), message: "Please Select one of Option to get Image.", preferredStyle: .actionSheet) let cancelActionButton: UIAlertAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "comment"), style: .cancel) { action -> Void in } actionSheetControllerIOS8.addAction(cancelActionButton) let saveActionButton: UIAlertAction = UIAlertAction(title: NSLocalizedString("Choose From Gallery", comment: "comment"), style: .default) { action -> Void in self.imagePickerController.sourceType = .photoLibrary self.imagePickerController.allowsEditing = true self.imagePickerController.delegate = self self.present(self.imagePickerController, animated: true, completion: {() -> Void in }) } actionSheetControllerIOS8.addAction(saveActionButton) let deleteActionButton: UIAlertAction = UIAlertAction(title: NSLocalizedString("Choose From Camera", comment: "comment"), style: .default) { action -> Void in if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { self.imagePickerController.sourceType = .camera self.imagePickerController.allowsEditing = true self.imagePickerController.delegate = self self.present(self.imagePickerController, animated: true, completion: {() -> Void in }) } else { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString,msg: NSLocalizedString("You don't have camera", comment: "comment") as NSString) } } actionSheetControllerIOS8.addAction(deleteActionButton) self.present(actionSheetControllerIOS8, animated: true, completion: nil) } @IBAction func btn_DateOfBirthClick(_ sender: UIButton) { self.view.endEditing(true) } @IBAction func btn_CityClick(_ sender: UIButton) { self.view.endEditing(true) self.view .endEditing(true) let point: CGPoint = view.convert(sender.frame.origin, from: sender.superview) var frame: CGRect = sender.frame frame.origin = point picker.pickerType = SBPickerSelectorType.text picker.pickerData = arr_City.value(forKeyPath: "name") as! Array picker.showPickerIpad(from: frame, in: view) // if strCityID != ""{ // picker.selectRow(Int(strCityID)!, inComponent: 0, animated: true) // } } @IBAction func btn_ChangePasswordClick(_ sender: UIButton) { self.view.endEditing(true) let changePassword : ChangePasswordViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChangePasswordViewController") as! ChangePasswordViewController changePassword.delegate = self self.presentpopupViewController(popupViewController: changePassword, animationType: .TopBottom, completion: { () -> Void in }) } @IBAction func btn_SaveChangesClick(_ sender: UIButton) { self.view.endEditing(true) if ((txtFullName.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) == "") { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Please Enter Valid Full Name.") return } if (AppUtilities.sharedInstance.isValidEmail(testStr: txtEmailID.text!)) == false { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Please Enter Valid Email ID.") return } let strLatitude = UserDefaults.standard.object(forKey: "latitude") let strLongitude = UserDefaults.standard.object(forKey: "longitude") // var str = NSString(format: "method=editprofile&userid=\(strUserId)&firstname=\(txtFullName.text)&email=\(txtEmailID.text)&address=\("")&contactno=\(strContactNo)&city=\(strCityID)&lat=\(strLatitude!)&lng=\(strLongitude!)" as NSString) let boundary = generateBoundaryString() var param = NSMutableDictionary() param = [ "userid" : strUserId, "firstname" : txtFullName.text as Any as! String, "email" : txtEmailID.text as Any as! String, "address" : "", "contactno" : strContactNo, "city" : strCityID, "lat" : strLatitude! as Any as! String, "lng" : strLongitude! as Any as! String, "method" : "editprofile"] print("URL STRING ",param) let request = NSMutableURLRequest(url: NSURL(string: BASE_URL)! as URL) request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = createBodyWithParameters(parameters: param, boundary: boundary) as Data let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if error != nil { AppUtilities.sharedInstance.hideLoader() return } do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary DispatchQueue.main.async( execute: { AppUtilities.sharedInstance.hideLoader() print(json! as NSDictionary) if let success : String = json?.value(forKey: "success") as? String { if(success == "1") { let ArrDic : NSMutableDictionary = NSMutableDictionary(dictionary : json!.value(forKey: "data") as! NSDictionary) let arrData = NSKeyedArchiver.archivedData(withRootObject: ArrDic) let pref : UserDefaults = UserDefaults() pref.set(arrData, forKey: "UserData") pref.synchronize() AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Profile Updated Successfully..") } else { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Something wrong..") } } }) } catch let err { AppUtilities.sharedInstance.hideLoader() } } task.resume() } // MARK: - API Methods // MARK: get City API func getCityData() { if AppUtilities.isConnectedToNetwork() { AppUtilities.sharedInstance.showLoader() let str = NSString(format: "method=getcity" as NSString) AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in DispatchQueue.main.async( execute: { AppUtilities.sharedInstance.hideLoader() if success { print("object ",object!) if(object?.value(forKeyPath: "error") as! String == "0") { self.arr_City = NSMutableArray(array: object?.value(forKey: "data") as! NSArray) let dictData = UserDefaults.standard.data(forKey: "UserData") let dictRegisterData = NSKeyedUnarchiver.unarchiveObject(with: dictData!) as! NSMutableDictionary let strCity = dictRegisterData.object(forKey: "city") as! String self.strCityID = strCity let resultPredicate = NSPredicate(format: "SELF.id = %@", strCity) let filterArrNew = self.arr_City.filtered(using: resultPredicate) let arrayTemp = filterArrNew as NSArray if arrayTemp.count > 0 { let dict = arrayTemp.object(at: 0) as! NSDictionary self.btnCity.setTitle(dict.object(forKey: "name") as! String?, for: UIControlState.normal) } } else { let msg = object!.value(forKeyPath: "message") as! String AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString) } } else { let msg = object!.value(forKeyPath: "message") as! String print(msg) } }) }) } else { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!") } } // MARK: Change Password API func changepassword() { if AppUtilities.isConnectedToNetwork() { AppUtilities.sharedInstance.showLoader() let dictChangePwdData : NSMutableDictionary = NSMutableDictionary() dictChangePwdData.setValue(strPassword, forKey: "newpassword") let strNewPwd = dictChangePwdData.object(forKey: "newpassword") as! String let str = NSString(format: "method=changepassword&userid=\(strUserId)&newpassword=\(strNewPwd)" as NSString) print(str) AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in DispatchQueue.main.async( execute: { AppUtilities.sharedInstance.hideLoader() if success { print("object ",object!) if(object?.value(forKeyPath: "error") as! String == "0") { let msg = object!.value(forKeyPath: "message") as! String AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString) } else { let msg = object!.value(forKeyPath: "message") as! String AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString) } } else { let msg = object!.value(forKeyPath: "message") as! String print(msg) } }) }) } else { AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!") } } // MARK: - SBPickerSelector Delegate Methods func pickerSelector(_ selector: SBPickerSelector!, selectedValue value: String!, index idx: Int) { btnCity.setTitle(value, for: .normal) let dict : NSDictionary = arr_City.object(at: idx) as! NSDictionary strCityID = dict.object(forKey: "id") as! String } // MARK: - UIImagePickerController Delegate Method func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if (info[UIImagePickerControllerEditedImage] as? UIImage) != nil { if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage { imgSelectedImage = self.resizeImage(image: pickedImage, newWidth: 200) self.imgProfilePic.image = pickedImage } picker.dismiss(animated: true, completion: nil) } picker.dismiss(animated: true, completion: nil) } // MARK: - Resize Image func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } //MARK: - get Boundry func generateBoundaryString() -> String { return "Boundary-\(NSUUID().uuidString)" } func createBodyWithParameters(parameters: NSMutableDictionary?,boundary: String) -> NSData { let body = NSMutableData() if parameters != nil { for (key, value) in parameters! { if(value is String || value is NSString){ body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition:form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!) body.append("\(value)\r\n".data(using: String.Encoding.utf8)!) } } if imgSelectedImage != nil { let filename = "image.png" //"image\(i).png" let data = UIImageJPEGRepresentation(imgSelectedImage as UIImage,1); body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition:form-data; name=\"profilepic\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!) body.append(data!) body.append("\r\n".data(using: String.Encoding.utf8)!) } } body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!) return body } // MARK: - Other Methods override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
27ebf519b3957a8aa276ecdff9f14ee7
43.364303
244
0.573602
5.374704
false
false
false
false
atuooo/notGIF
notGIF/Controllers/Transition/PushDetailAnimator.swift
1
3155
// // PushDetailAnimator.swift // notGIF // // Created by ooatuoo on 2017/6/8. // Copyright © 2017年 xyz. All rights reserved. // import UIKit fileprivate let duration = 0.5 class PushDetailAnimator: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let listVC = transitionContext.viewController(forKey: .from) as? GIFListViewController, let detailVC = transitionContext.viewController(forKey: .to) as? GIFDetailViewController, let listView = transitionContext.view(forKey: .from), let detailView = transitionContext.view(forKey: .to) else { transitionContext.completeTransition(true) return } let container = transitionContext.containerView container.insertSubview(detailView, belowSubview: listView) if let selectIP = listVC.selectIndexPath, let listCell = listVC.collectionView.cellForItem(at: selectIP) as? GIFListCell { let imageOriginFrame = listCell.imageView.frame let imageBeginRect = listVC.collectionView.convert(listCell.frame, to: UIApplication.shared.keyWindow) let imageFinalRect = UIScreen.main.bounds let imageView: NotGIFImageView = listCell.imageView listCell.isInTransition = true listVC.shouldPlay = false listCell.isHidden = true imageView.startAnimating() imageView.frame = imageBeginRect container.addSubview(imageView) detailView.alpha = 0 detailVC.showToolViewToWindow() UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 2, options: [], animations: { detailView.alpha = 1 listVC.collectionView.alpha = 0 imageView.frame = imageFinalRect }, completion: { _ in imageView.stopAnimating() let detailCell = detailVC.collectionView.cellForItem(at: selectIP) as? GIFDetailCell detailCell?.imageView.startAnimating() imageView.removeFromSuperview() imageView.frame = imageOriginFrame listCell.contentView.insertSubview(imageView, at: 0) listCell.isInTransition = false // listCell.isHidden = false detailVC.moveToolViewToView() let isSuccess = !transitionContext.transitionWasCancelled transitionContext.completeTransition(isSuccess) }) } else { detailView.alpha = 1 transitionContext.completeTransition(true) } } }
mit
c5e731fe96052552b3a358bb2195a5ee
36.975904
142
0.599937
6.14425
false
false
false
false
hooman/swift
test/stdlib/BridgeStorage.swift
13
5349
//===--- BridgeStorage.swift ----------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // Bridged types are notionally single-word beasts that either store // an objc class or a native Swift class. We'd like to be able to // distinguish these cases efficiently. // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Swift //===--- Code mimics the stdlib without using spare pointer bits ----------===// import SwiftShims protocol BridgeStorage { associatedtype Native : AnyObject associatedtype ObjC : AnyObject init(native: Native, isFlagged: Bool) init(native: Native) init(objC: ObjC) mutating func isUniquelyReferencedNative() -> Bool mutating func isUniquelyReferencedUnflaggedNative() -> Bool var isNative: Bool {get} var isObjC: Bool {get} var nativeInstance: Native {get} var unflaggedNativeInstance: Native {get} var objCInstance: ObjC {get} } extension _BridgeStorage : BridgeStorage {} //===----------------------------------------------------------------------===// //===--- Testing code -----------------------------------------------------===// //===----------------------------------------------------------------------===// import StdlibUnittest var allTests = TestSuite("DiscriminatedBridgeObject") class C { deinit { print("bye C!") } } import Foundation func isOSAtLeast(_ major: Int, _ minor: Int, patch: Int = 0) -> Bool { // isOperatingSystemAtLeastVersion() is unavailable on some OS versions. if #available(iOS 8.0, OSX 10.10, *) { let procInfo: AnyObject = ProcessInfo.processInfo return procInfo.isOperatingSystemAtLeast( OperatingSystemVersion(majorVersion: major, minorVersion: minor, patchVersion: patch)) } return false } func expectTagged(_ s: NSString, _ expected: Bool) -> NSString { #if arch(x86_64) let mask: UInt = 0x8000000000000001 #elseif arch(arm64) let mask: UInt = 0x8000000000000000 #else let mask: UInt = 0 #endif var osSupportsTaggedStrings: Bool #if os(iOS) // NSTaggedPointerString is enabled starting in iOS 9.0. osSupportsTaggedStrings = isOSAtLeast(9,0) #elseif os(tvOS) || os(watchOS) // NSTaggedPointerString is supported in all versions of TVOS and watchOS. osSupportsTaggedStrings = true #elseif os(OSX) // NSTaggedPointerString is enabled starting in OS X 10.10. osSupportsTaggedStrings = isOSAtLeast(10,10) #endif let taggedStringsSupported = osSupportsTaggedStrings && mask != 0 let tagged = unsafeBitCast(s, to: UInt.self) & mask != 0 if taggedStringsSupported && expected == tagged { // okay } else if !taggedStringsSupported && !tagged { // okay } else { let un = !tagged ? "un" : "" fatalError("Unexpectedly \(un)tagged pointer for string \"\(s)\"") } return s } var taggedNSString : NSString { return expectTagged(NSString(format: "foo"), true) } var unTaggedNSString : NSString { return expectTagged("fûtbōl" as NSString, false) } allTests.test("_BridgeStorage") { typealias B = _BridgeStorage<C> let oy: NSString = "oy" expectTrue(B(objC: oy).objCInstance === oy) for flag in [false, true] { do { var b = B(native: C(), isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.isUniquelyReferencedNative()) if !flag { expectTrue(b.isUniquelyReferencedUnflaggedNative()) } } do { let c = C() var b = B(native: c, isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectFalse(b.isUniquelyReferencedNative()) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.nativeInstance === c) if !flag { expectTrue(b.unflaggedNativeInstance === c) expectFalse(b.isUniquelyReferencedUnflaggedNative()) } // Keep 'c' alive for the isUniquelyReferenced check above. _fixLifetime(c) } } var b = B(native: C(), isFlagged: false) expectTrue(b.isUniquelyReferencedNative()) // Add a reference and verify that it's still native but no longer unique var c = b expectFalse(b.isUniquelyReferencedNative()) _fixLifetime(b) // make sure b is not killed early _fixLifetime(c) // make sure c is not killed early let n = C() var bb = B(native: n) expectTrue(bb.nativeInstance === n) expectTrue(bb.isNative) expectTrue(bb.isUnflaggedNative) expectFalse(bb.isObjC) var d = B(objC: taggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) d = B(objC: unTaggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) } runAllTests()
apache-2.0
315d024649fe22bfb5e23330cb0f13cd
27.902703
80
0.638676
4.357783
false
false
false
false
MomentaBV/CwlUtils
Sources/CwlUtils/CwlKeyValueObserver.swift
1
12787
// // CwlKeyValueObserver.swift // CwlUtils // // Created by Matt Gallagher on 2015/02/03. // Copyright © 2015 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation /// A wrapper around key-value observing so that you: /// 1. don't need to implement `observeValue` yourself, you can instead handle changes in a closure /// 2. you get a `CallbackReason` for each change which includes `valueChanged`, `pathChanged`, `sourceDeleted`. /// 3. observation is automatically cancelled if you release the KeyValueObserver or the source is released /// /// A majority of the complexity in this class comes from the fact that we turn key-value observing on keyPaths into a series of chained KeyValueObservers that we manage ourselves. This gives us more information when things change but we're re-implementing a number of things that Cococa key-value observing normally gives us for free. Generally in this class, anything involving the `tailPath` is managing observations of the path. /// /// THREAD SAFETY: /// This class is memory safe even when observations are triggered concurrently from different threads. /// Do note though that while all changes are registered under the mutex, callbacks are invoked *outside* the mutex, so it is possible for callbacks to be invoked in a different order than the internal synchronized order. /// In general, this shouldn't be a problem (since key-value observing is not itself synchronized so there *isn't* an authoritative ordering). However, this may cause unexpected behavior if you invoke `cancel` on this class. If you `cancel` the `KeyValueObserver` while it is concurrently processing changes on another thread, this might result in callback invocations occurring *after* the call to `cancel`. This will only happen if the changes associated with those callbacks were received *before* the `cancel` - it's just the callback that's getting invoked later. public class KeyValueObserver: NSObject { public typealias Callback = (_ change: [NSKeyValueChangeKey: Any], _ reason: CallbackReason) -> Void // This is the user-supplied callback function private var callback: Callback? // When observing a keyPath, we use a separate KeyValueObserver for each component of the path. The `tailObserver` is the `KeyValueObserver` for the *next* element in the path. private var tailObserver: KeyValueObserver? // This is the key that we're observing on `source` private let key: String // This is any path beyond the key. private let tailPath: String? // This is the set of options passed on construction private let options: NSKeyValueObservingOptions // Used to ensure memory safety for the callback and tailObserver. private let mutex = DispatchQueue(label: "") // Our "deletionBlock" is called to notify us that the source is being deallocated (so we can remove the key value observation before a warning is logged) and this happens during the source's "objc_destructinstance" function. At this point, a `weak` var will be `nil` and an `unowned` will trigger a `_swift_abortRetainUnowned` failure. // So we're left with `Unmanaged`. Careful cancellation before the source is deallocated is necessary to ensure we don't access an invalid memory location. private let source: Unmanaged<NSObject> /// The `CallbackReason` explains the location in the path where the change occurred. /// /// - valueChanged: the observed value changed /// - pathChanged: one of the connected elements in the path changed /// - sourceDeleted: the observed source was deallocated /// - cancelled: will never be sent public enum CallbackReason { case valueChanged case pathChanged case sourceDeleted case cancelled } /// Establish the key value observing. /// /// - Parameters: /// - source: object on which there's a property we wish to observe /// - keyPath: a key or keyPath identifying the property we wish to observe /// - options: same as for the normal `addObserver` method /// - callback: will be invoked on each change with the change dictionary and the change reason public init(source: NSObject, keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.new.union(NSKeyValueObservingOptions.initial), callback: @escaping Callback) { self.callback = callback self.source = Unmanaged.passUnretained(source) self.options = options // Look for "." indicating a key path var range = keyPath.range(of: ".") // If we have a collection operator, consider the next path component as part of this key if let r = range, keyPath.hasPrefix("@") { range = keyPath.range(of: ".", range: keyPath.index(after: r.lowerBound)..<keyPath.endIndex, locale: nil) } // Set the key and tailPath based on whether we detected multiple path components if let r = range { self.key = keyPath.substring(to: r.lowerBound) self.tailPath = keyPath.substring(from: keyPath.index(after: r.lowerBound)) } else { self.key = keyPath // If we're observing a weak property, add an observer on self to the source to detect when it may be set to nil without going through the property setter var p: String? = nil if let propertyName = keyPath.cString(using: String.Encoding.utf8) { let property = class_getProperty(type(of: source), propertyName) // Look for both the "id" and "weak" attributes. if property != nil, let attributes = String(validatingUTF8: property_getAttributes(property))?.components(separatedBy: ","), attributes.filter({ $0.hasPrefix("T@") || $0 == "W" }).count == 2 { p = "self" } } self.tailPath = p } super.init() // Detect if the source is deleted let deletionBlock = OnDelete { [weak self] in self?.cancel(.sourceDeleted) } objc_setAssociatedObject(source, Unmanaged.passUnretained(self).toOpaque(), deletionBlock, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) // Start observing the source if key != "self" { var currentOptions = options if !isObservingTail { currentOptions = NSKeyValueObservingOptions.new.union(options.intersection(NSKeyValueObservingOptions.prior)) } source.addObserver(self, forKeyPath: key, options: currentOptions, context: Unmanaged.passUnretained(self).toOpaque()) } // Start observing the value of the source if tailPath != nil { updateTailObserver(onValue: source.value(forKeyPath: self.key) as? NSObject, isInitial: true) } } deinit { cancel() } // This method is called when the key path between the source and the observed property changes. This will recursively create KeyValueObservers along the path. // // Mutex notes: Method must be called from *INSIDE* mutex (although, it must be *OUTSIDE* the tailObserver's mutex). private func updateTailObserver(onValue: NSObject?, isInitial: Bool) { tailObserver?.cancel() tailObserver = nil if let _ = self.callback, let tp = tailPath, let currentValue = onValue { let currentOptions = isInitial ? self.options : self.options.subtracting(NSKeyValueObservingOptions.initial) self.tailObserver = KeyValueObserver(source: currentValue, keyPath: tp, options: currentOptions, callback: self.tailCallback) } } // This method is called from the `tailObserver` (representing a change in the key path, not the observed property) // // Mutex notes: Method is called *OUTSIDE* mutex since it is used as a callback function for the `tailObserver` private func tailCallback(_ change: [NSKeyValueChangeKey: Any], reason: CallbackReason) { switch reason { case .cancelled: return case .sourceDeleted: let c = mutex.sync(execute: { () -> Callback? in updateTailObserver(onValue: nil, isInitial: false) return self.callback }) c?(change, self.isObservingTail ? .valueChanged : .pathChanged) default: let c = mutex.sync { self.callback } c?(change, reason) } } // The method returns `false` if there are subsequent `KeyValueObserver`s observing part of the path between us and the observed property and `true` if we are directly observing the property. // // Mutex notes: Safe for invocation in or out of mutex private var isObservingTail: Bool { return tailPath == nil || tailPath == "self" } // Weak properties need `self` observed, as well as the property, to correctly detect changes. // // Mutex notes: Safe for invocation in or out of mutex private var needsWeakTailObserver: Bool { return tailPath == "self" } // Accessor for the observed property value. This will correctly get the value from the end of the key path if we are using a tailObserver. // // Mutex notes: Method must be called from *INSIDE* mutex. private func sourceValue() -> Any? { if let t = tailObserver, !isObservingTail { return t.sourceValue() } else { return source.takeUnretainedValue().value(forKeyPath: key) } } // If we're observing a key path, then we need to update our chain of KeyValueObservers when part of the path changes. This starts that process from the change point. // // Mutex notes: Method must be called from *INSIDE* mutex. private func updateTailObserverGivenChangeDictionary(change: [NSKeyValueChangeKey: Any]) { if let newValue = change[NSKeyValueChangeKey.newKey] as? NSObject { let value: NSObject? = newValue == NSNull() ? nil : newValue updateTailObserver(onValue: value, isInitial: false) } else { updateTailObserver(onValue: sourceValue() as? NSObject, isInitial: false) } } // Implementation of standard key-value observing method. public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if context != Unmanaged.passUnretained(self).toOpaque() { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } guard let c = change else { assertionFailure("Expected change dictionary") return } if self.isObservingTail { let cb = mutex.sync { () -> Callback? in if needsWeakTailObserver { updateTailObserverGivenChangeDictionary(change: c) } return self.callback } cb?(c, .valueChanged) } else { let tuple = mutex.sync { () -> (Callback, [NSKeyValueChangeKey: Any])? in var transmittedChange: [NSKeyValueChangeKey: Any] = [:] if !options.intersection(NSKeyValueObservingOptions.old).isEmpty { transmittedChange[NSKeyValueChangeKey.oldKey] = tailObserver?.sourceValue() } if let _ = c[NSKeyValueChangeKey.notificationIsPriorKey] as? Bool { transmittedChange[NSKeyValueChangeKey.notificationIsPriorKey] = true } updateTailObserverGivenChangeDictionary(change: c) if !options.intersection(NSKeyValueObservingOptions.new).isEmpty { transmittedChange[NSKeyValueChangeKey.newKey] = tailObserver?.sourceValue() } if let c = callback { return (c, transmittedChange) } return nil } if let (cb, tc) = tuple { cb(tc, .pathChanged) } } } /// Stop observing. public func cancel() { cancel(.cancelled) } // Mutex notes: Method is called *OUTSIDE* mutex private func cancel(_ reason: CallbackReason) { let cb = mutex.sync { () -> Callback? in guard let c = callback else { return nil } // Flag as inactive callback = nil // Remove the observations from this object if key != "self" { source.takeUnretainedValue().removeObserver(self, forKeyPath: key, context: Unmanaged.passUnretained(self).toOpaque()) } // Cancel the OnDelete object let unknown = objc_getAssociatedObject(source, Unmanaged.passUnretained(self).toOpaque()) if let deletionObject = unknown as? OnDelete { deletionObject.cancel() } // And clear the associated object objc_setAssociatedObject(source, Unmanaged.passUnretained(self).toOpaque(), nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); // Remove tail observers updateTailObserver(onValue: nil, isInitial: false) // Send notifications return reason != .cancelled ? c : nil } cb?([:], reason) } }
isc
3766ace8ef505e84d4a94254b0f2a68e
43.706294
568
0.732598
4.116549
false
false
false
false
lockersoft/SpaceDroidsNotes
TwoDGame/GameScene.swift
1
14528
// // GameScene.swift // TwoDGame // // Created by Dave Jones on 3/26/16. // Copyright (c) 2016 Lockersoft. All rights reserved. // // TODO: Add Options Screen // Add Levels // Add Startup screen with levels and buttons // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var asteroid : Asteroid! var asteroid2 : Asteroid! var asteroid3 : Asteroid! var asteroids = [Asteroid]() // var nodesToRemove = [SKSpriteNode]() // array to hold nodes that need to be removed var rocket = SKSpriteNode(fileNamed: "Spaceship") var scoreNode = SKLabelNode() var score = 0 var rotationOffset : CGFloat = 0.0 var shipLives = 2 var maxLives = 5 var livesNodes = [SKNode]() // array to hold "lives" ship icon var gameOver = false var xMax : CGFloat = 0.0 var yMax : CGFloat = 0.0 var xMin : CGFloat = 0.0 var yMin : CGFloat = 0.0 // create rotation gesture recognizer let rotateGesture = UIRotationGestureRecognizer() let longTapGesture = UILongPressGestureRecognizer() var phaserSound = SKAction.playSoundFileNamed("scifi10.mp3", waitForCompletion: false) var asteroidExplosionSound = SKAction.playSoundFileNamed("blast", waitForCompletion: false) var shipRotation = 0.0 /// // Main Play Scene // override func didMoveToView(view: SKView) { /* Setup your scene here */ self.physicsWorld.contactDelegate = self xMax = self.scene!.frame.size.height / 2 yMax = self.scene!.frame.size.width / 2 xMin = -xMax yMin = -yMax for i in 0..<maxLives { let tempNode = self.childNodeWithName("Life\(i)")! tempNode.hidden = true livesNodes.append( tempNode ) } rotateGesture.addTarget(self, action: "rotateRocket:") self.view!.addGestureRecognizer(rotateGesture) longTapGesture.addTarget(self, action: "addAsteroid:") self.view!.addGestureRecognizer(longTapGesture) displayShip() scoreNode = self.childNodeWithName("Score")! as! SKLabelNode // asteroid = self.childNodeWithName("LargeAsteroid") as! Asteroid! // asteroid.position = CGPoint(x: 200, y: 200) // asteroid.initializeAsteroid( "large" ) // asteroid.animateAsteroid() asteroid = Asteroid( pos: CGPoint( x:-200, y:500), size: "large" ) asteroid2 = Asteroid(pos: CGPoint( x:200, y:500), size: "medium" ) asteroid3 = Asteroid(pos: CGPoint( x:200, y:300), size: "small" ) self.addChild(asteroid) self.addChild(asteroid2) self.addChild(asteroid3) asteroids.append( asteroid ) asteroids.append( asteroid2 ) asteroids.append( asteroid3 ) for _ in 0..<10 { let tempAsteroid = Asteroid( pos: randomCGPoint(xMax, maxY: yMax)) asteroids.append(tempAsteroid) self.addChild(tempAsteroid) } let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Hello, World!" myLabel.fontSize = 45 myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) // let vector = CGVector(dx: 5, dy: 5) var action = SKAction.scaleBy(-0.1, duration: 5.0) myLabel.runAction(SKAction.repeatActionForever(action)) action = SKAction.rotateByAngle(CGFloat(M_PI), duration:2) myLabel.runAction(SKAction.repeatActionForever(action)) self.addChild(myLabel) resetShipLivesDisplay() /* var largeRock:SKSpriteNode = SKSpriteNode() if let someSpriteNode:SKSpriteNode = self.childNodeWithName("LargeAsteroid") as? SKSpriteNode { largeRock = someSpriteNode } */ // let largeRock = SKSpriteNode(imageNamed: "a10000") //largeRock.position = CGPoint( x:500, y:500) //largeRock.xScale = 1.0 //largeRock.yScale = 1.0 // let moveAction = SKAction.moveBy(vector, duration: 1) //largeRock.runAction(SKAction.repeatActionForever(moveAction)) // largeRock.runAction(SKAction.repeatActionForever(animatePlayerAction), withKey: "largeRockSpin") //self.addChild( largeRock) } func displayShip(){ rocket = SKSpriteNode(imageNamed: "Spaceship") rocket!.zPosition = 100 // Move to top rocket!.position = CGPoint(x: 0,y: 0) rocket!.setScale( 0.4 ) rocket!.physicsBody = SKPhysicsBody(circleOfRadius: rocket!.size.width / 3) rocket!.physicsBody!.allowsRotation = true rocket!.physicsBody!.categoryBitMask = PhysicsCategory.SpaceShip rocket!.physicsBody!.collisionBitMask = PhysicsCategory.None // Make it invulnerable temporarily rocket!.physicsBody!.contactTestBitMask = PhysicsCategory.None rocket!.physicsBody!.mass = Mass.SpaceShip rocket!.runAction( SKAction.sequence( [SKAction.waitForDuration(10.0), SKAction.runBlock({ self.rocket!.physicsBody!.collisionBitMask = PhysicsCategory.Asteroid // Make it vulnerable again self.rocket!.physicsBody!.contactTestBitMask = PhysicsCategory.Asteroid }) ])) self.addChild( rocket! ) } func rotateRocket(gesture: UIRotationGestureRecognizer) { if( gesture.state == .Changed ){ rocket!.zRotation = -gesture.rotation + rotationOffset } if( gesture.state == .Ended ){ rotationOffset = rocket!.zRotation } } func createPhaserShot(){ // http://gamedev.stackexchange.com/questions/18340/get-position-of-point-on-circumference-of-circle-given-an-angle // http://www.soundjig.com/pages/soundfx/scifi.html let ninetyDegreesInRadians = CGFloat(90.0 * M_PI / 180.0) let phaserShot = SKSpriteNode(imageNamed: "phaserShot") phaserShot.name = "phaserShot" phaserShot.zRotation = rocket!.zRotation phaserShot.xScale = 0.1 phaserShot.yScale = 0.1 phaserShot.position = CGPointMake(rocket!.position.x, rocket!.position.y) let xDist = (cos(phaserShot.zRotation + ninetyDegreesInRadians) * 1000 ) + phaserShot.position.x let yDist = (sin(phaserShot.zRotation + ninetyDegreesInRadians) * 1000 ) + phaserShot.position.y print( phaserShot.zRotation, xDist, yDist ) let vector = CGPointMake(xDist, yDist) let moveAction = SKAction.moveTo(vector, duration: 2) phaserShot.runAction(SKAction.repeatActionForever(moveAction)) // Add physics to asteroid phaserShot.physicsBody = SKPhysicsBody(circleOfRadius: phaserShot.size.width ) phaserShot.physicsBody?.allowsRotation = true phaserShot.physicsBody!.categoryBitMask = PhysicsCategory.PhaserShot phaserShot.physicsBody!.collisionBitMask = PhysicsCategory.Asteroid & PhysicsCategory.PhaserShot phaserShot.physicsBody!.contactTestBitMask = PhysicsCategory.PhaserShot | PhysicsCategory.Asteroid phaserShot.physicsBody!.mass = Mass.PhaserShot addChild(phaserShot) runAction(phaserSound) } func addAsteroid( gesture: UILongPressGestureRecognizer ){ let location = gesture.locationInView(self.view) print( gesture.locationInView(self.view), terminator: "" ) let asteroid = Asteroid(pos: location) asteroids.append(asteroid) self.addChild(asteroid) } func finishGame(){ gameOver = true let goNode = self.childNodeWithName("gameOver") as? SKLabelNode // add from .sks goNode?.setScale( 0.1 ) // let moveAction = SKAction.moveTo(CGPoint(x: 0,y: 0), duration: 5.0) // let rotateAction = SKAction.fadeInWithDuration(5.0) let goAction = SKAction(named: "GameOver")! goNode!.runAction( SKAction.sequence([goAction, SKAction.waitForDuration(2), SKAction.removeFromParent()] )) } /// Mark: UPDATE // UPDATE override func update(currentTime: NSTimeInterval){ if( (Asteroid.count() == 0 || shipLives <= 0 ) && !gameOver){ finishGame() } // Move all the asteroids for asteroid in asteroids { asteroid.move() } // Find all phaserShots and remove it IF off screen for child in self.children { if child.name == "phaserShot" { if let child = child as? SKSpriteNode { if( child.position.x > xMax || child.position.x < xMin){ child.removeFromParent() } if( child.position.y > yMax || child.position.y < yMin){ child.removeFromParent() } } } else if( child.name == "Asteroidlarge" || // Check off screen and wrap child.name == "Asteroidmedium" || child.name == "Asteroidsmall") { // print( child.position.x, child.position.y ) // Put the asteroid at the other side of the screen so it "wraps" around if( child.position.y > yMax ){ child.position.y = yMin } else if( child.position.y < yMin){ child.position.y = yMax } if( child.position.x > xMax ){ child.position.x = xMin } else if( child.position.x < xMin ){ child.position.x = xMax } } } scoreNode.text = "Score: " + String(score) } func shipExplode( location : CGPoint) -> SKEmitterNode { var burstNode : SKEmitterNode = SKEmitterNode() if let burstPath = NSBundle.mainBundle().pathForResource( "ShipExplosion", ofType: "sks") { burstNode = NSKeyedUnarchiver.unarchiveObjectWithFile(burstPath) as! SKEmitterNode burstNode.position = location burstNode.name = "ShipExplosion" burstNode.runAction(SKAction.sequence( [ asteroidExplosionSound, SKAction.waitForDuration(0.5), SKAction.fadeAlphaTo(0.0, duration: 0.3), SKAction.removeFromParent(), SKAction.waitForDuration(5.0) ])) } shipLives -= 1 resetShipLivesDisplay() if( shipLives <= 0 ){ shipLives = 0 finishGame() } else { displayShip() } return burstNode } func resetShipLivesDisplay(){ for i in 0..<shipLives { livesNodes[i].hidden = false } for i in shipLives..<maxLives { livesNodes[i].hidden = true } } func didBeginContact(contact: SKPhysicsContact) { // Handle an asteroid hitting the main player spaceship if( contact.bodyA.categoryBitMask == PhysicsCategory.SpaceShip || contact.bodyB.categoryBitMask == PhysicsCategory.SpaceShip){ print("Something hit the spaceship") print( "A: \(contact.bodyA.node?.name), B: \(contact.bodyB.node?.name)" ) // Remove Spaceship and Asteroid // nodesToRemove.append(contact.bodyA.node! as! SKSpriteNode) // nodesToRemove.append(contact.bodyB.node! as! SKSpriteNode) contact.bodyA.node!.removeFromParent() contact.bodyB.node!.removeFromParent() // Add a super explosion self.addChild(shipExplode(contact.contactPoint)) runAction(asteroidExplosionSound) } // Handle a phasershot hitting an asteroid if ( ((contact.bodyA.categoryBitMask == PhysicsCategory.Asteroid) && (contact.bodyB.categoryBitMask == PhysicsCategory.PhaserShot)) || ((contact.bodyA.categoryBitMask == PhysicsCategory.PhaserShot) && (contact.bodyB.categoryBitMask == PhysicsCategory.Asteroid)) ) { print( "A: \(contact.bodyA.node?.name), B: \(contact.bodyB.node?.name)" ) print( contact.bodyA.categoryBitMask, contact.bodyB.categoryBitMask ) if let bodyA = contact.bodyA.node as? SKSpriteNode, let bodyB = contact.bodyB.node as? SKSpriteNode { let contactPoint = contact.contactPoint // Explode whichever body is the asteroid if( bodyA.name == "phaserShot" ){ self.addChild((bodyB as! Asteroid).explode()) // Remove the asteroid from the list of asteroids runAction(asteroidExplosionSound) } if( bodyB.name == "phaserShot" ){ self.addChild((bodyA as! Asteroid).explode()) runAction(asteroidExplosionSound) } bodyA.removeFromParent() bodyB.removeFromParent() // Replace with 2 smaller asteroids var tempAsteroid : Asteroid print( asteroid.name ) if( bodyA.name == "Asteroidlarge" || bodyB.name == "Asteroidlarge" ){ for _ in 0..<2 { tempAsteroid = Asteroid(pos: contactPoint, size: "medium") asteroids.append(tempAsteroid) self.addChild(tempAsteroid) } score += 1 } if( bodyA.name == "Asteroidmedium" || bodyB.name == "Asteroidmedium" ){ for _ in 0..<2 { tempAsteroid = Asteroid(pos: contactPoint, size: "small") asteroids.append(tempAsteroid) self.addChild(tempAsteroid) } score += 5 } if( bodyA.name == "Asteroidsmall" || bodyB.name == "Asteroidsmall" ){ score += 10 } } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { _ = touch.locationInNode(self) createPhaserShot() if( gameOver ){ // Go back to main Play Scene let scene = MainMenu(fileNamed: "MainMenu") scene?.scaleMode = .AspectFill self.view?.presentScene(scene!, transition: SKTransition.doorsOpenHorizontalWithDuration(1)) } /*let sprite = SKSpriteNode(imageNamed:"a10000") sprite.xScale = 1.5 sprite.yScale = 1.5 sprite.position = location */ // let vector = CGVector(dx: 5, dy: 5) // let actionScale = SKAction.scaleBy(-0.1, duration: 0.5) // sprite.runAction(SKAction.repeatActionForever(action)) // let actionRotate = SKAction.rotateByAngle(CGFloat(M_PI), duration:0.5) // sprite.runAction(SKAction.repeatActionForever(action)) // let actionMove = SKAction.moveBy(vector, duration: 1.0) // sprite.runAction(SKAction.repeatActionForever(action)) // let sequence = SKAction.sequence([actionScale, actionRotate, actionMove]) // sprite.runAction(SKAction.repeatActionForever(sequence )) // self.addChild(sprite) } } }
gpl-3.0
055967fe2ea7fc5cf26225b7855cbe21
33.673031
119
0.631333
4.208575
false
false
false
false
alexzatsepin/omim
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewStatus/TransportRoutePreviewStatus.swift
8
3347
@objc(MWMTransportRoutePreviewStatus) final class TransportRoutePreviewStatus: SolidTouchView { @IBOutlet private weak var etaLabel: UILabel! @IBOutlet private weak var stepsCollectionView: TransportTransitStepsCollectionView! @IBOutlet private weak var stepsCollectionViewHeight: NSLayoutConstraint! private var hiddenConstraint: NSLayoutConstraint! @objc weak var ownerView: UIView! weak var navigationInfo: MWMNavigationDashboardEntity? private var isVisible = false { didSet { alternative(iPhone: { guard self.isVisible != oldValue else { return } if self.isVisible { self.addView() } DispatchQueue.main.async { guard let sv = self.superview else { return } sv.animateConstraints(animations: { self.hiddenConstraint.isActive = !self.isVisible }, completion: { if !self.isVisible { self.removeFromSuperview() } }) } }, iPad: { self.isHidden = !self.isVisible })() } } private func addView() { guard superview != ownerView else { return } ownerView.addSubview(self) addConstraints() } private func addConstraints() { var lAnchor = ownerView.leadingAnchor var tAnchor = ownerView.trailingAnchor var bAnchor = ownerView.bottomAnchor if #available(iOS 11.0, *) { let layoutGuide = ownerView.safeAreaLayoutGuide lAnchor = layoutGuide.leadingAnchor tAnchor = layoutGuide.trailingAnchor bAnchor = layoutGuide.bottomAnchor } leadingAnchor.constraint(equalTo: lAnchor).isActive = true trailingAnchor.constraint(equalTo: tAnchor).isActive = true hiddenConstraint = topAnchor.constraint(equalTo: bAnchor) hiddenConstraint.priority = UILayoutPriority.defaultHigh hiddenConstraint.isActive = true let visibleConstraint = bottomAnchor.constraint(equalTo: bAnchor) visibleConstraint.priority = UILayoutPriority.defaultLow visibleConstraint.isActive = true } @objc func hide() { isVisible = false } @objc func showReady() { isVisible = true updateHeight() } @objc func onNavigationInfoUpdated(_ info: MWMNavigationDashboardEntity) { navigationInfo = info etaLabel.attributedText = info.estimate stepsCollectionView.steps = info.transitSteps } private func updateHeight() { guard stepsCollectionViewHeight.constant != stepsCollectionView.contentSize.height else { return } DispatchQueue.main.async { self.animateConstraints(animations: { self.stepsCollectionViewHeight.constant = self.stepsCollectionView.contentSize.height }) } } override func layoutSubviews() { super.layoutSubviews() updateHeight() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateHeight() } override var sideButtonsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var visibleAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } override var widgetsAreaAffectDirections: MWMAvailableAreaAffectDirections { return alternative(iPhone: .bottom, iPad: []) } }
apache-2.0
d08212f53633983c6859b759d0733d10
29.990741
102
0.713774
5.078907
false
false
false
false
rolandleth/LTHExtensions
Demo/LTHExtensionsTests/UIViewTests.swift
1
1186
// // UIViewTests.swift // LTHExtensions // // Created by Roland Leth on 20.12.2016. // Copyright © 2016 Roland Leth. All rights reserved. // import XCTest @testable import LTHExtensions class UIViewTests: XCTestCase { private var view = UIView(frame: .zero) override func setUp() { super.setUp() view.frame = CGRect(x: 10, y: 11, width: 12, height: 13) } func testGetX() { XCTAssertEqual(10, view.x) } func testSetX() { view.x = 100 XCTAssertEqual(100, view.x) } func testGetY() { XCTAssertEqual(11, view.y) } func testSetY() { view.y = 110 XCTAssertEqual(110, view.y) } func testGetWidth() { XCTAssertEqual(12, view.width) } func testSetWidth() { view.width = 120 XCTAssertEqual(120, view.width) } func testGetHeight() { XCTAssertEqual(13, view.height) } func testSetHeight() { view.height = 130 XCTAssertEqual(130, view.height) } func testAppendOperator() { let subview = UIView(frame: .zero) view << subview XCTAssertEqual([subview], view.subviews) } func testSubscript() { let subview = UIView(frame: .zero) view.addSubview(subview) XCTAssertEqual(subview, view.subviews[0]) } }
mit
d061877110d4c2676638ebd89c3e2bd3
15.690141
58
0.664979
3.030691
false
true
false
false
Burning-Man-Earth/iBurn-iOS
iBurn/CreditsViewController.swift
1
4742
// // CreditsViewController.swift // iBurn // // Created by Christopher Ballinger on 8/9/15. // Copyright (c) 2015 Burning Man Earth. All rights reserved. // import UIKit import Mantle import VTAcknowledgementsViewController open class SubtitleCell: UITableViewCell { static let kReuseIdentifier = "kSubtitleIdentifier" public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: SubtitleCell.kReuseIdentifier) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private enum SectionInfo: Int { case people = 0 case licenses } class CreditsViewController: UITableViewController { var creditsInfoArray:[BRCCreditsInfo] = [] init () { super.init(style: UITableView.Style.grouped) } required init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() let dataBundle = Bundle.brc_data let creditsURL = dataBundle.url(forResource: "credits", withExtension:"json") let creditsData = try? Data(contentsOf: creditsURL!) do { if let creditsArray = try JSONSerialization.jsonObject(with: creditsData!, options:JSONSerialization.ReadingOptions()) as? NSArray { let creditsInfo = try MTLJSONAdapter.models(of: BRCCreditsInfo.self,fromJSONArray: creditsArray as [AnyObject]) self.creditsInfoArray = creditsInfo as! [BRCCreditsInfo] assert(self.creditsInfoArray.count > 0, "Empty credits info!") } } catch { } self.tableView.register(SubtitleCell.self, forCellReuseIdentifier: SubtitleCell.kReuseIdentifier) self.tableView.rowHeight = 55 } override func viewWillAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionInfo.people.rawValue { return self.creditsInfoArray.count } else if section == SectionInfo.licenses.rawValue { return 1 } return 0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == SectionInfo.people.rawValue { return "Thank you!" } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SubtitleCell.kReuseIdentifier, for: indexPath) // style cell cell.textLabel!.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline) cell.detailTextLabel!.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline) cell.detailTextLabel!.textColor = UIColor.lightGray cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator // set body if indexPath.section == SectionInfo.people.rawValue { let creditsInfo = self.creditsInfoArray[indexPath.row] cell.textLabel!.text = creditsInfo.name cell.detailTextLabel!.text = creditsInfo.blurb } else if indexPath.section == SectionInfo.licenses.rawValue { cell.textLabel!.text = "Open Source Licenses" cell.detailTextLabel!.text = nil } return cell } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == SectionInfo.people.rawValue { let creditsInfo = self.creditsInfoArray[indexPath.row] if let url = creditsInfo.url { WebViewHelper.presentWebView(url: url, from: self) } } else if indexPath.section == SectionInfo.licenses.rawValue { let ackVC = BRCAcknowledgementsViewController(headerLabel: nil) self.navigationController?.pushViewController(ackVC!, animated: true) } } }
mpl-2.0
48299410e87eafddd404dae9eeb088c2
34.924242
144
0.664488
5.087983
false
false
false
false
Mindera/Alicerce
Sources/View/CollectionReusableViewSizer.swift
1
4423
import UIKit public final class CollectionReusableViewSizer<View: UICollectionReusableView & ReusableViewModelView> { public typealias ViewModel = View.ViewModel public enum Dimension: Hashable { case compressed case expanded case fixed(CGFloat) case custom(CGFloat, UILayoutPriority) var size: CGFloat { switch self { case .compressed: return 0 case .expanded: return .greatestFiniteMagnitude case .fixed(let size), .custom(let size, _): return size } } var priority: UILayoutPriority { switch self { case .compressed, .expanded: return .fittingSizeLevel case .fixed: return .required case .custom(_, let priority): return priority } } } private lazy var view = View() public init() {} public func sizeFor( viewModel: ViewModel, width: Dimension = .compressed, height: Dimension = .compressed, attributes: UICollectionViewLayoutAttributes? = nil ) -> CGSize { assert(view.viewModel == nil, "🧟‍♂️ Zombie view model detected! Kill it with fire!") view.viewModel = viewModel // the sizer populates the dummy view with the view model attributes.flatMap(view.apply) let layoutView: UIView switch view { case let cell as UICollectionViewCell: layoutView = cell.contentView // because UIKit reasons default: layoutView = view } let size = layoutView.systemLayoutSizeFitting( CGSize(width: width.size, height: height.size), withHorizontalFittingPriority: width.priority, verticalFittingPriority: height.priority ) view.prepareForReuse() // cleans up the dummy view and sets its viewModel to nil return size } } public struct ConstantSizerCacheKey: Hashable {} public protocol SizerViewModelView: ReusableViewModelView { associatedtype SizerCacheKey: Hashable = ConstantSizerCacheKey static func sizerCacheKeyFor(viewModel: ViewModel) -> SizerCacheKey } public extension SizerViewModelView where SizerCacheKey == ConstantSizerCacheKey { static func sizerCacheKeyFor(viewModel: ViewModel) -> SizerCacheKey { return SizerCacheKey() } } public final class CollectionReusableViewSizerCache<View: UICollectionReusableView & SizerViewModelView> { public typealias Sizer = CollectionReusableViewSizer<View> private struct Key: Hashable { let key: View.SizerCacheKey let width: Sizer.Dimension let height: Sizer.Dimension } private var sizer = Sizer() private var cache = [Key: CGSize]() public init() {} public func sizeFor( viewModel: Sizer.ViewModel, width: Sizer.Dimension = .compressed, height: Sizer.Dimension = .compressed, attributes: UICollectionViewLayoutAttributes? = nil ) -> CGSize { let key = Key(key: View.sizerCacheKeyFor(viewModel: viewModel), width: width, height: height) if let cachedSize = cache[key] { return cachedSize } let size = sizer.sizeFor(viewModel: viewModel, width: width, height: height, attributes: attributes) cache[key] = size return size } } public final class CollectionReusableViewSizerCacheGroup { private var sizers = [String: AnyObject]() public init() {} public func sizeFor<View: UICollectionReusableView & SizerViewModelView>( _ type: View.Type, viewModel: CollectionReusableViewSizer<View>.ViewModel, width: CollectionReusableViewSizer<View>.Dimension = .compressed, height: CollectionReusableViewSizer<View>.Dimension = .compressed, attributes: UICollectionViewLayoutAttributes? = nil ) -> CGSize { typealias Sizer = CollectionReusableViewSizerCache<View> let key = NSStringFromClass(View.self) if let sizer = sizers[key] as? Sizer { return sizer.sizeFor(viewModel: viewModel, width: width, height: height, attributes: attributes) } let sizer = Sizer() sizers[key] = sizer return sizer.sizeFor(viewModel: viewModel, width: width, height: height, attributes: attributes) } }
mit
fd72f587a561aba5f0ebdcff1c527bfd
29.652778
108
0.647485
5.261025
false
false
false
false
1985apps/PineKit
Pod/Classes/PineAjax.swift
2
4496
// // PineAjax.swift // Pods // // Created by Prakash Raman on 18/04/16. // // import UIKit import SwiftyJSON import Alamofire /*open class PineAjax: NSObject { open static var baseUrl = "http://" open var headers : Dictionary <String, String> = Dictionary<String, String>() open var request: Request? open var url : String = "" open var _parameters : Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() open var method = Alamofire.Method.GET open var _files : [Dictionary<String, AnyObject>] = [] fileprivate var successCallback : (_ json: JSON, _ response: Response<AnyObject, NSError>) -> Void = {_ in } fileprivate var errorCallback : (_ json: JSON, _ response: Response<AnyObject, NSError>) -> Void = {_ in } public init(method: Alamofire.Method = .GET, url: String){ self.url = url self.method = method } open func params(_ params: Dictionary<String, AnyObject>) -> PineAjax { self._parameters = params return self } open func file(_ name: String, data: Data, fileName: String, mimeType: String = "image/jpg") -> PineAjax { let item = ["name": name, "data": data, "fileName": fileName, "mimeType": mimeType] as [String : Any] self._files.append(item as [String : AnyObject]) return self } open func run() -> PineAjax { print("Running the Ajax: params: \(self._parameters)") return self._files.count > 0 ? runUpload() : runRequest() } open func runRequest() -> PineAjax { let url = PineAjax.baseUrl + self.url if let token = PineSimpleData.getString("token") { headers["token"] = token print("Token: \(token)") } self.request = Alamofire.request(self.method, url, parameters: self._parameters, headers: headers) .responseJSON(completionHandler: self.onResponse) return self } open func runUpload() -> PineAjax { let url = PineAjax.baseUrl + self.url if let token = PineSimpleData.getString("token") { headers["token"] = token print("Token: \(token)") } Alamofire.upload( .POST, url, headers: headers, multipartFormData: { multipartFormData in for (file) in self._files { multipartFormData.appendBodyPart(data: (file["data"] as! NSData), name: (file["name"] as! String), fileName: (file["fileName"] as! String), mimeType: (file["mimeType"] as! String)) } for (key, value) in self._parameters { multipartFormData.appendBodyPart(data: String(value).dataUsingEncoding(NSUTF8StringEncoding)!, name: key) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in let json = JSON(rawValue: response.result.value!) let code = response.response?.statusCode if code >= 200 && code <= 300 { self.successCallback(json: json!, response: response) } else { self.errorCallback(json: json!, response: response) } } case .Failure(let encodingError): print(encodingError) } } ) return self } open func onResponse(_ response: Response<AnyObject, NSError>) -> Void { var json = JSON(rawValue: "{}") if response.result.value != nil { json = JSON(rawValue: response.result.value!) } let code = response.response?.statusCode if code >= 200 && code <= 300 { self.successCallback(json: json!, response: response) } else { self.errorCallback(json: json!, response: response) } } open func success(_ callback: (_ json: JSON, _ response: Response<AnyObject, NSError>) -> Void) -> PineAjax { self.successCallback = callback return self } open func error(_ callback: (_ json: JSON, _ response: Response<AnyObject, NSError>) -> Void ) -> PineAjax { self.errorCallback = callback return self } } */
mit
f4361f6ee55e0379cfe537f5c82f4bb7
34.968
200
0.552491
4.67846
false
false
false
false
airander/redis-framework
Redis-Framework/Redis-Framework/RedisClient+Keys.swift
1
25311
// // RedisClient+Keys.swift // Redis-Framework // // Copyright (c) 2015, Eric Orion Anderson // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation public enum RedisMigrationType:String { case copy = "COPY" case replace = "REPLACE" } extension RedisClient { /// DEL key [key ...] Removes the specified keys. A key is ignored if it does not exist. /// /// - returns: Integer reply: The number of keys that were removed. public func delete(keys:[String], completionHandler:@escaping RedisCommandIntegerBlock) { var command:String = "DEL" for(_, key) in keys.enumerated() { command = command + " " + RESPUtilities.respString(from: key) } self.send(command, completionHandler: completionHandler) } /// DUMP key /// /// Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command. /// The serialization format is opaque and non-standard, however it has a few semantical characteristics: /// It contains a 64-bit checksum that is used to make sure errors will be detected. The RESTORE command makes sure to check the checksum before synthesizing a key using the serialized value. /// Values are encoded in the same format used by RDB. /// An RDB version is encoded inside the serialized value, so that different Redis versions with incompatible RDB formats will refuse to process the serialized value. /// The serialized value does NOT contain expire information. In order to capture the time to live of the current value the PTTL command should be used. /// If key does not exist a nil bulk reply is returned. /// /// - returns: Bulk string reply: the serialized value. *NOTE* This is not fully tested and doesn't encode directly to UTF-8 public func dump(key:String, completionHandler:@escaping RedisCommandDataBlock) { self.send("DUMP \(RESPUtilities.respString(from: key))", completionHandler: { (data: Data?, error) -> Void in if error != nil { completionHandler(nil, error) } else { //custom parsing for binary data, not UTF-8 compliant let customData:NSData = data! as NSData let clrfData:Data = "\r\n".data(using: String.Encoding.utf8)! let crlfFirstRange:NSRange = customData.range(of: clrfData, options: NSData.SearchOptions(), in: NSMakeRange(0, customData.length)) if crlfFirstRange.location != NSNotFound { //simple check for the first \r\n let crlfEndRange:NSRange = customData.range(of: clrfData, options: NSData.SearchOptions.backwards, in: NSMakeRange(0, customData.length)) if crlfEndRange.location != crlfFirstRange.location { //assuming found last \r\n let serialzedData:Data = customData.subdata(with: NSMakeRange(crlfFirstRange.location+crlfFirstRange.length, customData.length-(crlfFirstRange.location+crlfFirstRange.length)-(crlfFirstRange.length))) completionHandler(serialzedData, nil) return } } completionHandler(nil, NSError(domain: RedisErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:"Unexpected response format"])) } }) } /// EXISTS key /// /// Returns if key exists. /// /// - returns: Integer reply, specifically: 1 if the key exists. 0 if the key does not exist. public func exists(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("EXISTS \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// EXPIRE key seconds /// /// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is /// often said to be volatile in Redis terminology. /// The timeout is cleared only when the key is removed using the DEL command or overwritten using the SET or GETSET commands. /// This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will /// leave the timeout untouched. For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH, /// or altering the field value of a hash with HSET are all operations that will leave the timeout untouched. /// The timeout can also be cleared, turning the key back into a persistent key, using the PERSIST command. /// If a key is renamed with RENAME, the associated time to live is transferred to the new key name. /// If a key is overwritten by RENAME, like in the case of an existing key Key_A that is overwritten by a call like RENAME Key_B Key_A, /// it does not matter if the original Key_A had a timeout associated or not, the new key Key_A will inherit all the characteristics of Key_B. /// /// Refreshing expires /// /// It is possible to call EXPIRE using as argument a key that already has an existing expire set. In this case the time to live of a key is /// updated to the new value. There are many useful applications for this, an example is documented in the Navigation session pattern section below. /// /// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set. public func expire(key:String, seconds:Int, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("EXPIRE \(RESPUtilities.respString(from: key)) \(seconds)", completionHandler: completionHandler) } /// EXPIREAT key timestamp /// /// EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), /// it takes an absolute Unix timestamp (seconds since January 1, 1970). /// Please for the specific semantics of the command refer to the documentation of EXPIRE. /// /// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set (see: EXPIRE). public func expire(key:String, at date:Date, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("EXPIREAT \(RESPUtilities.respString(from: key)) \(Int(date.timeIntervalSince1970))", completionHandler: completionHandler) } /// KEYS pattern /// /// Returns all keys matching pattern. /// While the time complexity for this operation is O(N), the constant times are fairly low. For example, /// Redis running on an entry level laptop can scan a 1 million key database in 40 milliseconds. /// Warning: consider KEYS as a command that should only be used in production environments with extreme care. /// It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, /// such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, /// consider using SCAN or sets. /// Supported glob-style patterns: /// /// h?llo matches hello, hallo and hxllo /// /// h*llo matches hllo and heeeello /// /// h[ae]llo matches hello and hallo, but not hillo /// /// Use \ to escape special characters if you want to match them verbatim. /// /// - returns: Array reply: list of keys matching pattern. public func keys(pattern:String, completionHandler:@escaping RedisCommandArrayBlock) { self.send("KEYS \(RESPUtilities.respString(from: pattern))", completionHandler: completionHandler) } /// MIGRATE host port key destination-db timeout [COPY] [REPLACE] /// /// Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the /// original instance and is guaranteed to exist in the target instance. /// The command is atomic and blocks the two instances for the time required to transfer the key, at any given time the key will /// appear to exist in a given instance or in the other instance, unless a timeout error occurs. /// The command internally uses DUMP to generate the serialized version of the key value, and RESTORE in order to synthesize the key in the target instance. /// The source instance acts as a client for the target instance. If the target instance returns OK to the RESTORE command, the source instance deletes the key using DEL. /// The timeout specifies the maximum idle time in any moment of the communication with the destination instance in milliseconds. /// This means that the operation does not need to be completed within the specified amount of milliseconds, /// but that the transfer should make progresses without blocking for more than the specified amount of milliseconds. /// MIGRATE needs to perform I/O operations and to honor the specified timeout. When there is an I/O error during the transfer or if the timeout /// is reached the operation is aborted and the special error - IOERR returned. When this happens the following two cases are possible: /// The key may be on both the instances. /// The key may be only in the source instance. /// It is not possible for the key to get lost in the event of a timeout, but the client calling MIGRATE, in the event of a timeout error, /// should check if the key is also present in the target instance and act accordingly. /// When any other error is returned (starting with ERR) MIGRATE guarantees that the key is still only present in the originating instance /// (unless a key with the same name was also already present on the target instance). /// /// - returns: Simple string reply: On success OK is returned. public func migrate(host:String, port:Int, key:String, destinationDB:String, timeoutInMilliseconds:Int, migrationType:RedisMigrationType, completionHandler:@escaping RedisCommandStringBlock) { self.send("MIGRATE \(host) \(port) \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: destinationDB)) \(timeoutInMilliseconds) \(migrationType.rawValue)", completionHandler: completionHandler) } /// MOVE key db /// /// Move key from the currently selected database (see SELECT) to the specified destination database. /// When key already exists in the destination database, or it does not exist in the source database, /// it does nothing. It is possible to use MOVE as a locking primitive because of this. /// /// - returns: Integer reply, specifically: 1 if key was moved. 0 if key was not moved. public func move(key:String, db:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("MOVE \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: db))", completionHandler: completionHandler) } /// OBJECT REFCOUNT key /// /// The OBJECT command allows to inspect the internals of Redis Objects associated with keys. It is useful for debugging or to understand if your keys /// are using the specially encoded data types to save space. Your application may also use the information reported by the OBJECT command to implement /// application level key eviction policies when using Redis as a Cache. /// /// - returns: Interger reply: The number of references of the value associated with the specified key. This command is mainly useful for debugging. public func objectRefCount(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("OBJECT REFCOUNT \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// OBJECT ENCODING key /// /// The OBJECT command allows to inspect the internals of Redis Objects associated with keys. It is useful for debugging or to understand if your keys /// are using the specially encoded data types to save space. Your application may also use the information reported by the OBJECT command to implement /// application level key eviction policies when using Redis as a Cache. /// /// Objects can be encoded in different ways: /// Strings can be encoded as raw (normal string encoding) or int (strings representing integers in a 64 bit signed interval are encoded in this way in order to save space). /// Lists can be encoded as ziplist or linkedlist. The ziplist is the special representation that is used to save space for small lists. /// Sets can be encoded as intset or hashtable. The intset is a special encoding used for small sets composed solely of integers. /// Hashes can be encoded as zipmap or hashtable. The zipmap is a special encoding used for small hashes. /// Sorted Sets can be encoded as ziplist or skiplist format. As for the List type small sorted sets can be specially encoded using ziplist, /// while the skiplist encoding is the one that works with sorted sets of any size. /// /// - returns: Bulk string reply: The kind of internal representation used in order to store the value associated with a key. public func objectEncoding(key:String, completionHandler:@escaping RedisCommandStringBlock) { self.send("OBJECT ENCODING \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// PERSIST key /// /// Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated). /// /// - returns: Integer reply, specifically: 1 if the timeout was removed. 0 if key does not exist or does not have an associated timeout. public func persist(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("PERSIST \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// PEXPIRE key milliseconds /// /// This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds. /// /// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set. public func pExpire(key:String, milliseconds:UInt, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("PEXPIRE \(RESPUtilities.respString(from: key)) \(milliseconds)", completionHandler: completionHandler) } /// PEXPIREAT key milliseconds-timestamp /// /// PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds. /// /// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set (see: EXPIRE). public func pExpire(key:String, at date:Date, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("PEXPIREAT \(RESPUtilities.respString(from: key)) \(Int(date.timeIntervalSince1970*1000))", completionHandler: completionHandler) } /// PTTL key /// /// Like TTL this command returns the remaining time to live of a key that has an expire set, /// with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds. /// /// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. /// Starting with Redis 2.8 the return value in case of error changed: /// The command returns -2 if the key does not exist. /// The command returns -1 if the key exists but has no associated expire. /// /// - returns: Integer reply: TTL in milliseconds, or a negative value in order to signal an error (see the description above). public func pttl(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("PTTL \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// RANDOMKEY /// /// Return a random key from the currently selected database. /// /// - returns: Bulk string reply: the random key, or nil when the database is empty. public func randomKey(completionHandler:@escaping RedisCommandStringBlock) { self.send("RANDOMKEY", completionHandler: completionHandler) } /// RENAME key newkey /// /// Renames key to newkey. It returns an error when the source and destination names are the same, or when key does not exist. /// If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted /// key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation. /// /// - returns: Simple string reply public func rename(key:String, newKey:String, completionHandler:@escaping RedisCommandStringBlock) { self.send("RENAME \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: newKey))", completionHandler: completionHandler) } /// RENAMENX key newkey /// /// Renames key to newkey if newkey does not yet exist. It returns an error under the same conditions as RENAME. /// /// - returns: Integer reply, specifically: 1 if key was renamed to newkey. 0 if newkey already exists. public func renameNX(key:String, newKey:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("RENAMENX \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: newKey))", completionHandler: completionHandler) } /// RESTORE key ttl serialized-value /// /// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP). /// If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set. /// RESTORE checks the RDB version and data checksum. If they don't match an error is returned. /// /// - returns: Simple string reply: The command returns OK on success. public func restore(key:String, ttl:UInt = 0, serializedValue:Data, completionHandler:@escaping RedisCommandStringBlock) { self.send("RESTORE \(RESPUtilities.respString(from: key)) \(ttl)", data:serializedValue, completionHandler: completionHandler) } // SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination] // TODO: /// TTL key /// /// Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset. /// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. /// Starting with Redis 2.8 the return value in case of error changed: /// The command returns -2 if the key does not exist. /// The command returns -1 if the key exists but has no associated expire. /// See also the PTTL command that returns the same information with milliseconds resolution (Only available in Redis 2.6 or greater). /// /// - returns: Integer reply: TTL in seconds, or a negative value in order to signal an error (see the description above). public func ttl(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("TTL \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// TYPE key /// /// Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset and hash. /// /// - returns: Simple string reply: type of key, or none when key does not exist. public func type(key:String, completionHandler:@escaping RedisCommandStringBlock) { self.send("TYPE \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// SCAN cursor [MATCH pattern] [COUNT count] /// /// SCAN basic usage /// /// SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user /// needs to use as the cursor argument in the next call. /// /// Scan guarantees /// /// The SCAN command, and the other commands in the SCAN family, are able to provide to the user a set of guarantees associated to full iterations. /// A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration. /// This means that if a given element is inside the collection when an iteration is started, and is still there when an iteration terminates, /// then at some point SCAN returned it to the user. /// A full iteration never returns any element that was NOT present in the collection from the start to the end of a full iteration. /// So if an element was removed before the start of an iteration, and is never added back to the collection for all the time an iteration lasts, /// SCAN ensures that this element will never be returned. /// /// Number of elements returned at every SCAN call /// /// SCAN family functions do not guarantee that the number of elements returned per call are in a given range. /// The commands are also allowed to return zero elements, and the client should not consider the iteration complete as long as the returned cursor is not zero. /// /// The COUNT option /// /// While SCAN does not provide guarantees about the number of elements returned at every iteration, /// it is possible to empirically adjust the behavior of SCAN using the COUNT option. /// Basically with COUNT the user specified the amount of work that should be done at every call in order to retrieve elements from the collection. /// This is just an hint for the implementation, however generally speaking this is what you could expect most of the times from the implementation. /// The default COUNT value is 10. /// When iterating the key space, or a Set, Hash or Sorted Set that is big enough to be represented by an hash table, assuming no MATCH option is used, /// the server will usually return count or a bit more than count elements per call. /// When iterating Sets encoded as intsets (small sets composed of just integers), or Hashes and Sorted Sets encoded as ziplists /// (small hashes and sets composed of small individual values), usually all the elements are returned in the first SCAN call regardless of the COUNT value. /// /// The MATCH option /// /// It is possible to only iterate elements matching a given glob-style pattern, similarly to the behavior of the KEYS command that takes a pattern as only argument. /// To do so, just append the MATCH <pattern> arguments at the end of the SCAN command (it works with all the SCAN family commands). /// /// - returns: SCAN return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements. SCAN array of elements is a list of keys. public func scan(cursor:UInt, pattern:String? = nil, count:UInt? = nil, completionHandler:@escaping RedisCommandArrayBlock) { var command:String = "SCAN \(cursor)" if let pattern = pattern { command = command + " MATCH \(RESPUtilities.respString(from: pattern))" } if let count = count { command = command + " COUNT \(count)" } self.send(command, completionHandler: completionHandler) } }
bsd-2-clause
effd2cb36e48417528a9e7ee32ed58c4
66.676471
260
0.714749
4.651902
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/SoftNMS.swift
1
2419
// // SoftNMS.swift // CardScan // // Created by xaen on 4/3/20. // import Accelerate import Foundation struct SoftNMS { static func softNMS( subsetBoxes: [[Float]], probs: [Float], probThreshold: Float, sigma: Float, topK: Int, candidateSize: Int ) -> ([[Float]], [Float]) { var pickedBoxes = [[Float]]() var pickedScores = [Float]() var subsetBoxes = subsetBoxes var probs = probs while subsetBoxes.count > 0 { var maxElement: Float = 0.0 var vdspIndex: vDSP_Length = 0 vDSP_maxvi(probs, 1, &maxElement, &vdspIndex, vDSP_Length(probs.count)) let maxIdx = Int(vdspIndex) let currentBox = subsetBoxes[maxIdx] pickedBoxes.append(subsetBoxes[maxIdx]) pickedScores.append(maxElement) if subsetBoxes.count == 1 { break } //Take the last box and replace the max box with the last box subsetBoxes.remove(at: maxIdx) probs.remove(at: maxIdx) var ious = [Float](repeating: 0.0, count: subsetBoxes.count) let currentBoxRect = CGRect( x: Double(currentBox[0]), y: Double(currentBox[1]), width: Double(currentBox[2] - currentBox[0]), height: Double(currentBox[3] - currentBox[1]) ) for i in 0..<subsetBoxes.count { ious[i] = currentBoxRect.iou( nextBox: CGRect( x: Double(subsetBoxes[i][0]), y: Double(subsetBoxes[i][1]), width: Double(subsetBoxes[i][2] - subsetBoxes[i][0]), height: Double(subsetBoxes[i][3] - subsetBoxes[i][1]) ) ) } var probsPrunned = [Float]() var subsetBoxesPrunned = [[Float]]() for i in 0..<probs.count { probs[i] = probs[i] * exp(-(ious[i] * ious[i]) / sigma) if probs[i] > probThreshold { probsPrunned.append(probs[i]) subsetBoxesPrunned.append(subsetBoxes[i]) } } probs = probsPrunned subsetBoxes = subsetBoxesPrunned } return (pickedBoxes, pickedScores) } }
mit
98d4897d2403a728d2101a6d3f578a16
29.2375
83
0.497726
4.079258
false
false
false
false
diegosanchezr/Chatto
Chatto/Source/ChatController/AccessoryViewRevealer.swift
1
3198
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public protocol AccessoryViewRevealable { func revealAccessoryView(maximumOffset offset: CGFloat, animated: Bool) } class AccessoryViewRevealer: NSObject, UIGestureRecognizerDelegate { private let panRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer() private let collectionView: UICollectionView init(collectionView: UICollectionView) { self.collectionView = collectionView super.init() self.collectionView.addGestureRecognizer(self.panRecognizer) self.panRecognizer.addTarget(self, action: "handlePan:") self.panRecognizer.delegate = self } @objc private func handlePan(panRecognizer: UIPanGestureRecognizer) { switch panRecognizer.state { case .Began: break case .Changed: let translation = panRecognizer.translationInView(self.collectionView) self.revealAccessoryView(atOffset: -translation.x) case .Ended, .Cancelled, .Failed: self.revealAccessoryView(atOffset: 0) default: break } } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer != self.panRecognizer { return true } let translation = self.panRecognizer.translationInView(self.collectionView) let x = CGFloat.abs(translation.x), y = CGFloat.abs(translation.y) let angleRads = atan2(y, x) let threshold: CGFloat = 0.0872665 // ~5 degrees return angleRads < threshold } private func revealAccessoryView(atOffset offset: CGFloat) { for cell in self.collectionView.visibleCells() { if let cell = cell as? AccessoryViewRevealable { cell.revealAccessoryView(maximumOffset: offset, animated: offset == 0) } } } }
mit
41182e3e2d3e264ed79889ca8d04533d
38
172
0.721388
5.294702
false
false
false
false
huangboju/Moots
Examples/SwiftUI/SwiftUI-Apple/WorkingWithUIControls/Complete/Landmarks/Landmarks/Models/Profile.swift
4
819
/* See LICENSE folder for this sample’s licensing information. Abstract: An object that models a user profile. */ import Foundation struct Profile { var username: String var prefersNotifications: Bool var seasonalPhoto: Season var goalDate: Date static let `default` = Self(username: "g_kumar", prefersNotifications: true, seasonalPhoto: .winter) init(username: String, prefersNotifications: Bool = true, seasonalPhoto: Season = .winter) { self.username = username self.prefersNotifications = prefersNotifications self.seasonalPhoto = seasonalPhoto self.goalDate = Date() } enum Season: String, CaseIterable { case spring = "🌷" case summer = "🌞" case autumn = "🍂" case winter = "☃️" } }
mit
03519d35064dc87e78fdb47b9316a10c
25.8
104
0.651741
4.253968
false
false
false
false
andreyvit/ExpressiveCollections.swift
Source/Substitution.swift
1
1061
import Foundation public extension String { public func substituteValues(values: [String: String]) -> String { var result = self for (k, v) in values { result = result.stringByReplacingOccurrencesOfString(k, withString: v) } return result } public func substituteValues(values: [String: [String]]) -> [String] { for (k, v) in values { if self == k { return v } } var result = self for (k, v) in values { if v.count == 1 { result = result.stringByReplacingOccurrencesOfString(k, withString: v[0]) } } return [result] } } public extension SequenceType where Generator.Element == String { public func substituteValues(values: [String: String]) -> [String] { return self.map { $0.substituteValues(values) } } public func substituteValues(values: [String: [String]]) -> [String] { return self.flatMap { $0.substituteValues(values) } } }
mit
d92e72a40b96cb3e352325749fb31fd8
24.878049
89
0.565504
4.420833
false
false
false
false
mrbeal15/Where_You_At-Xcode
Where-You-At/Where-You-At/Invite.swift
2
1912
// // Invite.swift // Where-You-At // // Created by Apprentice on 11/20/15. // Copyright © 2015 Apprentice. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class Invite: UIViewController { var groupName = String() var currentGroup = String() override func viewDidLoad() { super.viewDidLoad() currentGroup = groupName print("************URL******************") print("http://whereyouat1.herokuapp.com/groups/\(currentGroup)/invite") print("*********************************") // Do any additional setup after loading the view. } @IBOutlet var invite: UITextField! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addGroupMember(sender: UIButton) { Alamofire.request(.POST, "http://whereyouat1.herokuapp.com/groups/\(currentGroup)/invite", parameters: ["email": "\(self.invite.text!)"]) .responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) self.performSegueWithIdentifier("addGroupMember", sender: self) } case .Failure(let error): print(error) } } } /* // 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. } */ }
mit
d1ee8dce3dee615a9fada4c3bba6319d
29.333333
145
0.568289
5.109626
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Extensions/UIAlertControllerExtension.swift
1
5242
// // UIAlertControllerExtension.swift // Inbbbox // // Created by Peter Bruz on 09/03/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import AOAlertController extension UIAlertController { // MARK: Shared Settings class func setupSharedSettings() { AOAlertSettings.sharedSettings.backgroundColor = .backgroundGrayColor() AOAlertSettings.sharedSettings.linesColor = .backgroundGrayColor() AOAlertSettings.sharedSettings.defaultActionColor = .pinkColor() AOAlertSettings.sharedSettings.cancelActionColor = .pinkColor() AOAlertSettings.sharedSettings.messageFont = UIFont.systemFont(ofSize: 17, weight: UIFontWeightMedium) AOAlertSettings.sharedSettings.defaultActionFont = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) AOAlertSettings.sharedSettings.cancelActionFont = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) AOAlertSettings.sharedSettings.destructiveActionFont = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) } // MARK: Buckets class func provideBucketName(_ createHandler: @escaping (_ bucketName: String) -> Void) -> AlertViewController { let alertTitle = Localized("UIAlertControllerExtension.NewBucket", comment: "Allows user to create new bucket.") let alertMessage = Localized("UIAlertControllerExtension.ProvideName", comment: "Provide name for new bucket") let alert = AlertViewController(title: alertTitle, message: alertMessage, preferredStyle: .alert) let cancelActionTitle = Localized("UIAlertControllerExtension.Cancel", comment: "Cancel creating new bucket.") alert.addAction(UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil)) let createActionTitle = Localized("UIAlertControllerExtension.Create", comment: "Create new bucket.") alert.addAction(UIAlertAction(title: createActionTitle, style: .default) { _ in if let bucketName = alert.textFields?[0].text { createHandler(bucketName) } }) alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = Localized("UIAlertControllerExtension.BucketName", comment: "Asks user to enter bucket name.") }) return alert } // MARK: Other class func inappropriateContentReported() -> AOAlertController { let message = Localized("UIAlertControllerExtension.InappropriateContentReported", comment: "nil") let okActionTitle = Localized("UIAlertControllerExtension.OK", comment: "OK") let okAction = AOAlertAction(title: okActionTitle, style: .default, handler: nil) return UIAlertController.createAlert(message, action: okAction) } class func emailAccountNotFound() -> AOAlertController { let message = Localized("UIAlertControllerExtension.EmailError", comment: "Displayed when user device is not capable of/configured to send emails.") return UIAlertController.createAlert(message) } class func willSignOutUser() -> AOAlertController { let message = Localized("ShotsCollectionViewController.SignOut", comment: "Message informing user will be logged out because of an error.") let alert = AOAlertController(title: nil, message: message, style: .alert) let dismissActionTitle = Localized("ShotsCollectionViewController.Dismiss", comment: "Dismiss error alert.") let dismissAction = AOAlertAction(title: dismissActionTitle, style: .default) { _ in Authenticator.logout() if let delegate = UIApplication.shared.delegate as? AppDelegate { delegate.rollbackToLoginViewController() } } alert.addAction(dismissAction) return alert } class func cantSendFeedback() -> AOAlertController { let message = Localized("UIAlertControllerExtension.CantSendFeedback", comment: "Displayed when user device is not capable of/configured to send emails, shown when trying to send feedback.") return UIAlertController.createAlert(message) } // MARK: Private fileprivate class func defaultDismissAction(_ style: AOAlertActionStyle = .default) -> AOAlertAction { let title = Localized("UIAlertControllerExtension.Dismiss", comment: "Dismiss") return AOAlertAction(title: title, style: style, handler: nil) } fileprivate class func createAlert(_ message: String, action: AOAlertAction = UIAlertController.defaultDismissAction(), style: AOAlertControllerStyle = .alert) -> AOAlertController { let alert = AOAlertController(title: nil, message: message, style: style) alert.addAction(action) return alert } }
gpl-3.0
38300d1bb3644aeda7468c5696e5ae70
43.042017
159
0.656936
5.599359
false
false
false
false
aotian16/SwiftGameDemo
Cat/Cat/EkoPoint.swift
1
921
// // EkoPoint.swift // Cat // // Created by 童进 on 15/11/25. // Copyright © 2015年 qefee. All rights reserved. // import UIKit import SpriteKit enum PointType { case gray case red } class EkoPoint: SKSpriteNode { var prePointIndex = -1 var arrPoint = [Int]() var step = 99 var index = 0 var type = PointType.gray var isEdge = false var label: SKLabelNode? func onSetLabel(text: String) { if let l = label { l.name = "\(name).label" l.text = text l.zPosition = 11 } else { let l = SKLabelNode(text: text) l.name = "\(name).label" l.fontSize = 20 l.position = CGPointMake(0, -10) l.userInteractionEnabled = false l.zPosition = 11 addChild(l) label = l } } }
mit
d24da063d7fd9a7d7cd565840367655b
20.255814
49
0.49453
3.872881
false
false
false
false
iaguilarmartin/HackerBooks
HackerBooks/BookViewController.swift
1
3422
import UIKit // View Controller to display detailed book information class BookViewController: UIViewController, LibraryViewControllerDelegate, UISplitViewControllerDelegate { //MARK: - Properties var model: Book? //MARK: - IBOutlets @IBOutlet weak var bookImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorsLabel: UILabel! @IBOutlet weak var tagsLabel: UILabel! @IBOutlet weak var favoritesButton: UIBarButtonItem! //MARK: - Initializers init(model: Book?) { self.model = model super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.edgesForExtendedLayout = UIRectEdge() updateView() if self.splitViewController?.displayMode == .primaryHidden { self.navigationItem.rightBarButtonItem = self.splitViewController?.displayModeButtonItem } } //MARK: - IBActions @IBAction func readBook(_ sender: AnyObject) { if let book = self.model { let pdfVC = PDFViewController(model: book) self.navigationController?.pushViewController(pdfVC, animated: true) } } @IBAction func favoriteBook(_ sender: AnyObject) { if self.model != nil { self.model?.isFavorite = !(self.model?.isFavorite)! updateView() } } //MARK: - Functions // Function that updates the view based on model state func updateView() { if let book = self.model { self.title = book.title self.view.isHidden = false self.titleLabel.text = book.title self.authorsLabel.text = book.authors.joined(separator: ", ") self.tagsLabel.text = book.tags.joined(separator: ", ") if let maybeImage = try? DataDownloader.downloadExternalFileFromURL(book.image), let image = maybeImage { self.bookImage.image = UIImage(data: image) } if book.isFavorite { favoritesButton.title = "Quitar de favoritos" } else { favoritesButton.title = "Añadir a favoritos" } // If no model is set then main view is hidden } else { self.title = "Ningún libro seleccionado" self.view.isHidden = true } } //MARK: - LibraryViewControllerDelegate func libraryViewController(_ libraryVC: LibraryViewController, didSelectBook book: Book) { self.model = book updateView() } //MARK: - UISplitViewControllerDelegate func splitViewController(_ svc: UISplitViewController, willChangeTo displayMode: UISplitViewControllerDisplayMode) { // If the screen is in portrait mode the library is displayed at the rigth // button of the NavigationBar if displayMode == .primaryHidden { self.navigationItem.rightBarButtonItem = self.splitViewController?.displayModeButtonItem } else if displayMode == .allVisible { self.navigationItem.rightBarButtonItem = nil } } }
mit
3f9623f80a5417696b4c236c7a2dfec2
32.529412
120
0.611111
5.245399
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/Nimble/Sources/Nimble/DSL+Wait.swift
56
4313
import Foundation #if _runtime(_ObjC) private enum ErrorResult { case Exception(NSException) case Error(ErrorType) case None } /// Only classes, protocols, methods, properties, and subscript declarations can be /// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style /// asynchronous waiting logic so that it may be called from Objective-C and Swift. internal class NMBWait: NSObject { internal class func until( timeout timeout: NSTimeInterval, file: FileString = #file, line: UInt = #line, action: (() -> Void) -> Void) -> Void { return throwableUntil(timeout: timeout, file: file, line: line) { (done: () -> Void) throws -> Void in action() { done() } } } // Using a throwable closure makes this method not objc compatible. internal class func throwableUntil( timeout timeout: NSTimeInterval, file: FileString = #file, line: UInt = #line, action: (() -> Void) throws -> Void) -> Void { let awaiter = NimbleEnvironment.activeInstance.awaiter let leeway = timeout / 2.0 let result = awaiter.performBlock { (done: (ErrorResult) -> Void) throws -> Void in dispatch_async(dispatch_get_main_queue()) { let capture = NMBExceptionCapture( handler: ({ exception in done(.Exception(exception)) }), finally: ({ }) ) capture.tryBlock { do { try action() { done(.None) } } catch let e { done(.Error(e)) } } } }.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line) switch result { case .Incomplete: internalError("Reached .Incomplete state for waitUntil(...).") case .BlockedRunLoop: fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway), file: file, line: line) case .TimedOut: let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) case let .RaisedException(exception): fail("Unexpected exception raised: \(exception)") case let .ErrorThrown(error): fail("Unexpected error thrown: \(error)") case .Completed(.Exception(let exception)): fail("Unexpected exception raised: \(exception)") case .Completed(.Error(let error)): fail("Unexpected error thrown: \(error)") case .Completed(.None): // success break } } @objc(untilFile:line:action:) internal class func until(file: FileString = #file, line: UInt = #line, action: (() -> Void) -> Void) -> Void { until(timeout: 1, file: file, line: line, action: action) } } internal func blockedRunLoopErrorMessageFor(fnName: String, leeway: NSTimeInterval) -> String { return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." } /// Wait asynchronously until the done closure is called or the timeout has been reached. /// /// @discussion /// Call the done() closure to indicate the waiting has completed. /// /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func waitUntil(timeout timeout: NSTimeInterval = 1, file: FileString = #file, line: UInt = #line, action: (() -> Void) -> Void) -> Void { NMBWait.until(timeout: timeout, file: file, line: line, action: action) } #endif
apache-2.0
c9c9e3da18d83fc7ad6a7b531e1a0f20
45.376344
381
0.580107
4.940435
false
false
false
false
apple/swift-syntax
Tests/SwiftOperatorsTest/OperatorTableTests.swift
1
13566
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 XCTest import SwiftSyntax import SwiftParser @_spi(Testing) import SwiftOperators import _SwiftSyntaxTestSupport /// Visitor that looks for ExprSequenceSyntax nodes. private class ExprSequenceSearcher: SyntaxAnyVisitor { var foundSequenceExpr = false override func visit( _ node: SequenceExprSyntax ) -> SyntaxVisitorContinueKind { foundSequenceExpr = true return .skipChildren } override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind{ return foundSequenceExpr ? .skipChildren : .visitChildren } } extension SyntaxProtocol { /// Determine whether the given syntax contains an ExprSequence anywhere. var containsExprSequence: Bool { let searcher = ExprSequenceSearcher(viewMode: .sourceAccurate) searcher.walk(self) return searcher.foundSequenceExpr } } /// A syntax rewriter that folds explicitly-parenthesized sequence expressions /// into a structured syntax tree. class ExplicitParenFolder : SyntaxRewriter { override func visit(_ node: TupleExprSyntax) -> ExprSyntax { // Identify syntax nodes of the form (x (op) y), which is a // TupleExprSyntax(SequenceExpr(x, (op), y)). guard node.elementList.count == 1, let firstNode = node.elementList.first, firstNode.label == nil, let sequenceExpr = firstNode.expression.as(SequenceExprSyntax.self), sequenceExpr.elements.count == 3, let leftOperand = sequenceExpr.elements.first, let middleExpr = sequenceExpr.elements.removingFirst().first, let rightOperand = sequenceExpr.elements.removingFirst().removingFirst().first else { return ExprSyntax(node) } return OperatorTable.makeBinaryOperationExpr( lhs: visit(Syntax(leftOperand)).as(ExprSyntax.self)!, op: visit(Syntax(middleExpr)).as(ExprSyntax.self)!, rhs: visit(Syntax(rightOperand)).as(ExprSyntax.self)! ) } } extension OperatorTable { /// Assert that parsing and folding the given "unfolded" source code /// produces the same syntax tree as the fully-parenthesized version of /// the same source. /// /// The `expectedSource` should be a fully-parenthesized expression, e.g., /// `(a + (b * c))` that expresses how the initial code should have been /// folded. func assertExpectedFold( _ source: String, _ fullyParenthesizedSource: String ) throws { // Parse and fold the source we're testing. let parsed = Parser.parse(source: source) let foldedSyntax = try foldAll(parsed) XCTAssertFalse(foldedSyntax.containsExprSequence) // Parse and "fold" the parenthesized version. let parenthesizedParsed = Parser.parse(source: fullyParenthesizedSource) let parenthesizedSyntax = ExplicitParenFolder().visit(parenthesizedParsed) XCTAssertFalse(parenthesizedSyntax.containsExprSequence) // Make sure the two have the same structure. let subtreeMatcher = SubtreeMatcher(Syntax(foldedSyntax), markers: [:]) do { try subtreeMatcher.assertSameStructure(Syntax(parenthesizedSyntax)) } catch { XCTFail("Matching for a subtree failed with error: \(error)") } } } public class OperatorPrecedenceTests: XCTestCase { func testLogicalExprsSingle() throws { let opPrecedence = OperatorTable.logicalOperators let parsed = Parser.parse(source: "x && y || w && v || z") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! let foldedExpr = try opPrecedence.foldSingle(sequenceExpr) XCTAssertEqual("\(foldedExpr)", "x && y || w && v || z") XCTAssertNil(foldedExpr.as(SequenceExprSyntax.self)) } func testLogicalExprs() throws { let opPrecedence = OperatorTable.logicalOperators try opPrecedence.assertExpectedFold("x && y || w", "((x && y) || w)") try opPrecedence.assertExpectedFold("x || y && w", "(x || (y && w))") } func testSwiftExprs() throws { let opPrecedence = OperatorTable.standardOperators let parsed = Parser.parse(source: "(x + y > 17) && x && y || w && v || z") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! let foldedExpr = try opPrecedence.foldSingle(sequenceExpr) XCTAssertEqual("\(foldedExpr)", "(x + y > 17) && x && y || w && v || z") XCTAssertNil(foldedExpr.as(SequenceExprSyntax.self)) } func testNestedSwiftExprs() throws { let opPrecedence = OperatorTable.standardOperators let parsed = Parser.parse(source: "(x + y > 17) && x && y || w && v || z") let foldedAll = try opPrecedence.foldAll(parsed) XCTAssertEqual("\(foldedAll)", "(x + y > 17) && x && y || w && v || z") XCTAssertFalse(foldedAll.containsExprSequence) } func testAssignExprs() throws { let opPrecedence = OperatorTable.standardOperators try opPrecedence.assertExpectedFold("a = b + c", "(a = (b + c))") try opPrecedence.assertExpectedFold("a = b = c", "(a = (b = c))") } func testCastExprs() throws { let opPrecedence = OperatorTable.standardOperators try opPrecedence.assertExpectedFold("a is (b)", "(a is (b))") try opPrecedence.assertExpectedFold("a as c == nil", "((a as c) == nil)") } func testArrowExpr() throws { let opPrecedence = OperatorTable.standardOperators try opPrecedence.assertExpectedFold( "a = b -> c -> d", "(a = (b -> (c -> d)))" ) } func testParsedLogicalExprs() throws { let logicalOperatorSources = """ precedencegroup LogicalDisjunctionPrecedence { associativity: left } precedencegroup LogicalConjunctionPrecedence { associativity: left higherThan: LogicalDisjunctionPrecedence } // "Conjunctive" infix operator &&: LogicalConjunctionPrecedence // "Disjunctive" infix operator ||: LogicalDisjunctionPrecedence """ let parsedOperatorPrecedence = Parser.parse(source: logicalOperatorSources) var opPrecedence = OperatorTable() try opPrecedence.addSourceFile(parsedOperatorPrecedence) let parsed = Parser.parse(source: "x && y || w && v || z") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! let foldedExpr = try opPrecedence.foldSingle(sequenceExpr) XCTAssertEqual("\(foldedExpr)", "x && y || w && v || z") XCTAssertNil(foldedExpr.as(SequenceExprSyntax.self)) } func testParseErrors() { let sources = """ infix operator + infix operator + precedencegroup A { associativity: none higherThan: B } precedencegroup A { associativity: none higherThan: B } """ let parsedOperatorPrecedence = Parser.parse(source: sources) var opPrecedence = OperatorTable() var errors: [OperatorError] = [] opPrecedence.addSourceFile(parsedOperatorPrecedence) { error in errors.append(error) } XCTAssertEqual(errors.count, 2) guard case let .operatorAlreadyExists(existing, new) = errors[0] else { XCTFail("expected an 'operator already exists' error") return } XCTAssertEqual(errors[0].message, "redefinition of infix operator '+'") _ = existing _ = new guard case let .groupAlreadyExists(existingGroup, newGroup) = errors[1] else { XCTFail("expected a 'group already exists' error") return } XCTAssertEqual(errors[1].message, "redefinition of precedence group 'A'") _ = newGroup _ = existingGroup } func testUnaryErrors() { let sources = """ prefix operator + prefix operator + postfix operator - prefix operator - postfix operator* postfix operator* """ let parsedOperatorPrecedence = Parser.parse(source: sources) var opPrecedence = OperatorTable() var errors: [OperatorError] = [] opPrecedence.addSourceFile(parsedOperatorPrecedence) { error in errors.append(error) } XCTAssertEqual(errors.count, 2) guard case let .operatorAlreadyExists(existing, new) = errors[0] else { XCTFail("expected an 'operator already exists' error") return } XCTAssertEqual(errors[0].message, "redefinition of prefix operator '+'") XCTAssertEqual(errors[1].message, "redefinition of postfix operator '*'") _ = existing _ = new } func testFoldErrors() throws { let parsedOperatorPrecedence = Parser.parse(source: """ precedencegroup A { associativity: none } precedencegroup C { associativity: none lowerThan: B } precedencegroup D { associativity: none } infix operator +: A infix operator -: A infix operator *: C infix operator ++: D """) var opPrecedence = OperatorTable() try opPrecedence.addSourceFile(parsedOperatorPrecedence) do { var errors: [OperatorError] = [] let parsed = Parser.parse(source: "a + b * c") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! _ = opPrecedence.foldSingle(sequenceExpr) { error in errors.append(error) } XCTAssertEqual(errors.count, 2) guard case let .missingGroup(groupName, location) = errors[0] else { XCTFail("expected a 'missing group' error") return } XCTAssertEqual(groupName, "B") XCTAssertEqual(errors[0].message, "unknown precedence group 'B'") _ = location } do { var errors: [OperatorError] = [] let parsed = Parser.parse(source: "a / c") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! _ = opPrecedence.foldSingle(sequenceExpr) { error in errors.append(error) } XCTAssertEqual(errors.count, 1) guard case let .missingOperator(operatorName, location) = errors[0] else { XCTFail("expected a 'missing operator' error") return } XCTAssertEqual(operatorName, "/") XCTAssertEqual(errors[0].message, "unknown infix operator '/'") _ = location } do { var errors: [OperatorError] = [] let parsed = Parser.parse(source: "a + b - c") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! _ = opPrecedence.foldSingle(sequenceExpr) { error in errors.append(error) } XCTAssertEqual(errors.count, 1) guard case let .incomparableOperators(_, leftGroup, _, rightGroup) = errors[0] else { XCTFail("expected an 'incomparable operator' error") return } XCTAssertEqual(leftGroup, "A") XCTAssertEqual(rightGroup, "A") XCTAssertEqual( errors[0].message, "adjacent operators are in non-associative precedence group 'A'") } do { var errors: [OperatorError] = [] let parsed = Parser.parse(source: "a ++ b - d") let sequenceExpr = parsed.statements.first!.item.as(SequenceExprSyntax.self)! _ = opPrecedence.foldSingle(sequenceExpr) { error in errors.append(error) } XCTAssertEqual(errors.count, 1) guard case let .incomparableOperators(_, leftGroup, _, rightGroup) = errors[0] else { XCTFail("expected an 'incomparable operator' error") return } XCTAssertEqual(leftGroup, "D") XCTAssertEqual(rightGroup, "A") XCTAssertEqual( errors[0].message, "adjacent operators are in unordered precedence groups 'D' and 'A'") } } func testTernaryExpr() throws { let opPrecedence = OperatorTable.standardOperators try opPrecedence.assertExpectedFold( "b + c ? y : z ? z2 : z3", "((b + c) ? y : (z ? z2 : z3))") } func testTryAwait() throws { let opPrecedence = OperatorTable.standardOperators try opPrecedence.assertExpectedFold("try x + y", "try (x + y)") try opPrecedence.assertExpectedFold( "await x + y + z", "await ((x + y) + z)") } func testInfixOperatorLookup() throws { let opPrecedence = OperatorTable.standardOperators do { let op = try XCTUnwrap(opPrecedence.infixOperator(named: "+")) XCTAssertEqual(op.kind, .infix) XCTAssertEqual(op.name, "+") XCTAssertEqual(op.precedenceGroup, "AdditionPrecedence") } do { let op = try XCTUnwrap(opPrecedence.infixOperator(named: "...")) XCTAssertEqual(op.kind, .infix) XCTAssertEqual(op.name, "...") XCTAssertEqual(op.precedenceGroup, "RangeFormationPrecedence") } XCTAssertNil(opPrecedence.infixOperator(named: "^*^")) } func testUnaryOperatorLookup() throws { let opPrecedence = OperatorTable.standardOperators do { let op = try XCTUnwrap(opPrecedence.prefixOperator(named: "-")) XCTAssertEqual(op.kind, .prefix) XCTAssertEqual(op.name, "-") XCTAssertNil(op.precedenceGroup) } do { let op = try XCTUnwrap(opPrecedence.postfixOperator(named: "...")) XCTAssertEqual(op.kind, .postfix) XCTAssertEqual(op.name, "...") XCTAssertNil(op.precedenceGroup) } } }
apache-2.0
821d1f117c352d492756e28dac532a8d
30.84507
82
0.652956
4.373308
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/Utilities/FocusableTextField.swift
1
4461
import SwiftUI #if canImport(UIKit) import UIKit #endif #if canImport(UIKit) /// A TextField that is backed by UIKit that allows us to get/set its first responder state struct FocusableTextField: UIViewRepresentable { @Binding private var isFirstResponder: Bool @Binding private var text: String private var configuration = { (_: UITextField) in } private var onReturnTapped = {} private var characterLimit: Int? init( text: Binding<String>, isFirstResponder: Binding<Bool>, characterLimit: Int? = nil, configuration: @escaping (UITextField) -> Void = { _ in }, onReturnTapped: @escaping () -> Void = {} ) { self.configuration = configuration _text = text _isFirstResponder = isFirstResponder self.characterLimit = characterLimit self.onReturnTapped = onReturnTapped } func makeUIView(context: Context) -> UITextField { let view = UITextField() view.setContentHuggingPriority(.defaultHigh, for: .vertical) view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) view.addTarget(context.coordinator, action: #selector(Coordinator.textViewDidChange), for: .editingChanged) view.delegate = context.coordinator return view } func updateUIView(_ uiView: UITextField, context: Context) { uiView.text = text configuration(uiView) DispatchQueue.main.async { [isFirstResponder] in switch isFirstResponder { case true: uiView.becomeFirstResponder() case false: uiView.resignFirstResponder() } } } func makeCoordinator() -> Coordinator { Coordinator( $text, isFirstResponder: $isFirstResponder, characterLimit: characterLimit, onReturnTapped: onReturnTapped ) } class Coordinator: NSObject, UITextFieldDelegate { var text: Binding<String> var isFirstResponder: Binding<Bool> var onReturnTapped: () -> Void var characterLimit: Int? init( _ text: Binding<String>, isFirstResponder: Binding<Bool>, characterLimit: Int? = nil, onReturnTapped: @escaping () -> Void ) { self.text = text self.isFirstResponder = isFirstResponder self.onReturnTapped = onReturnTapped self.characterLimit = characterLimit } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let characterLimit = characterLimit else { return true } let currentText = textField.text ?? "" // attempt to read the range they are trying to change, or exit if we can't guard let stringRange = Range(range, in: currentText) else { return false } // add their new text to the existing text let updatedText = currentText.replacingCharacters(in: stringRange, with: string) // make sure the result is under 16 characters return updatedText.count <= characterLimit } @objc func textViewDidChange(_ textField: UITextField) { text.wrappedValue = textField.text ?? "" } func textFieldDidBeginEditing(_ textField: UITextField) { // Dispatching is necessary otherwise the view doesn't update properly DispatchQueue.main.async { self.isFirstResponder.wrappedValue = true } } func textFieldDidEndEditing(_ textField: UITextField) { // Dispatching is necessary otherwise the view doesn't update properly DispatchQueue.main.async { self.isFirstResponder.wrappedValue = false } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Dispatching is necessary otherwise the view doesn't update properly DispatchQueue.main.async(execute: onReturnTapped) return true } } } struct FocusableTextField_Previews: PreviewProvider { static var previews: some View { FocusableTextField( text: .constant("[email protected]"), isFirstResponder: .constant(false) ) .padding() } } #endif
lgpl-3.0
3d21322c5235c510dfa49b30a320a75d
32.795455
133
0.61892
5.507407
false
false
false
false
RuiAAPeres/TeamGen
TeamGenFoundation/Sources/Repositories/GroupsRepository.swift
1
4497
import ReactiveSwift import Result import Disk public protocol GroupsRepositoryProtocol { func groups() -> SignalProducer<[Group], CoreError> func group(withName name: String) -> SignalProducer<Group, CoreError> func delete(withName name: String) -> SignalProducer<Void, CoreError> func insert(group: Group) -> SignalProducer<Group, CoreError> func update(group: Group) -> SignalProducer<Group, CoreError> } public struct GroupsRepository: GroupsRepositoryProtocol { private let filename: String private let queue = QueueScheduler() public init(filename: String = "groups.json") { self.filename = filename } public func groups() -> SignalProducer<[Group], CoreError> { return SignalProducer {[filename] o, _ in do { let group = try Disk.retrieve(filename, from: .applicationSupport, as: [Group].self) o.send(value: group) o.sendCompleted() } catch let error as NSError where error.domain == "DiskErrorDomain" { try? Disk.save([] as [Group], to: .applicationSupport, as: filename) o.send(value: []) o.sendCompleted() } catch { o.send(error: CoreError.reading("Couldn't find any group")) } } .start(on: queue) } public func group(withName name: String) -> SignalProducer<Group, CoreError> { func findGroup(groups: [Group]) -> SignalProducer<Group, CoreError> { let filter: (Group) -> Bool = { $0.name == name } guard let group = groups.filter(filter).first else { return SignalProducer(error: CoreError.reading("\(name) not found")) } return SignalProducer(value: group) } return groups() .flatMap(.latest, findGroup) .start(on: queue) } public func insert(group: Group) -> SignalProducer<Group, CoreError> { let alreadyExists: ([Group]) -> SignalProducer<[Group], CoreError> = { groups in guard groups.contains(group) == false else { return SignalProducer(error: CoreError.inserting("Already exists")) } return SignalProducer(value: groups) } let sanityCheck: (Group) -> SignalProducer<Group, CoreError> = { group in let isValid = GroupsRepository.areSkillsValid_sanityCheck(group: group) return isValid ? SignalProducer(value: group) : SignalProducer(error: CoreError.inserting("Invalid group")) } return SignalProducer(value: group) .flatMap(.latest, sanityCheck) .combineLatest(with: self.groups().flatMap(.latest, alreadyExists)) .map { return $0.1 + [$0.0] } .flatMap(.latest, saveGroups) .then(SignalProducer(value: group)) .start(on: queue) } public func delete(withName name: String) -> SignalProducer<Void, CoreError> { func removeGroup(groups: [Group]) -> [Group] { let filter: (Group) -> Bool = { $0.name != name } return groups.filter(filter) } return groups() .map(removeGroup) .flatMap(.latest, saveGroups) .map { _ in } .start(on: queue) } public func update(group: Group) -> SignalProducer<Group, CoreError> { return delete(withName: group.name) .then(insert(group: group)) .start(on: queue) } } extension GroupsRepository { private func saveGroups(groups: [Group]) -> SignalProducer<[Group], CoreError> { return SignalProducer {[filename] o, _ in do { try Disk.save(groups, to: .applicationSupport, as: filename) o.send(value: groups) o.sendCompleted() } catch { o.send(error: CoreError.inserting("save groups failed")) } } } } extension GroupsRepository { static fileprivate func areSkillsValid_sanityCheck(group: Group) -> Bool { let skillSpecs = group.skillSpec let players = group.players let reducer: (Bool, Player) -> Bool = { isValid, player in let playerSkillSpecs = player.skills.compactMap { $0.spec } return isValid && playerSkillSpecs == skillSpecs } return players.reduce(true, reducer) } }
mit
ad4e46bb0a9aa7f91794dbb643df6611
34.690476
126
0.582388
4.617043
false
false
false
false
AnRanScheme/MagiRefresh
ExampleRepo/MagiRefresh/ViewController.swift
1
2317
// // ViewController.swift // MagiRefresh // // Created by AnRanScheme on 09/27/2018. // Copyright (c) 2018 AnRanScheme. All rights reserved. // import UIKit import MagiRefresh func Delay(_ seconds: Double, completion:@escaping ()->()) { let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * seconds )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { completion() } } class ViewController: UIViewController { lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.bounds, style: .plain) tableView.tableFooterView = UIView() tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: ViewController.identifier) let header = MagiReplicatorHeader() header.themeColor = UIColor.red tableView.magiRefresh.header = header header.magiRefreshingClosure({ print("刷新") Delay(3, completion: { tableView.magiRefresh.header?.endRefreshingWithAlertText("哈哈哈哈哈", completion: nil) }) }) let footer = MagiArrowFooter() tableView.magiRefresh.footer = footer footer.magiRefreshingClosure({ print("刷新") Delay(3, completion: { tableView.magiRefresh.footer?.endRefreshing() }) }) return tableView }() fileprivate static let identifier = "CellID" override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: ViewController.identifier, for: indexPath) cell.textLabel?.text = "title--------\(indexPath.row)" return cell } } extension ViewController: UITableViewDelegate { }
mit
093d2d1b81e5df551323a29792d8e155
27.036585
109
0.60896
5.052747
false
false
false
false
apple/swift
test/SILOptimizer/Inputs/definite_init_cross_module/OtherModule.swift
16
875
public struct Point { public var x, y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } public struct ImmutablePoint { public let x, y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } public struct GenericPoint<T> { public var x, y: T public init(x: T, y: T) { self.x = x self.y = y } } public struct PrivatePoint { private var x, y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } public struct Empty { public init() {} } public struct GenericEmpty<T> { public init() {} } open class VisibleNoArgsDesignatedInit { var x: Float public init() { x = 0.0 } // Add some designated inits the subclass cannot see. private init(x: Float) { self.x = x } fileprivate init(y: Float) { self.x = y } internal init(z: Float) { self.x = z } }
apache-2.0
31768ce4b1b459382d8bdff91f731b39
15.203704
55
0.601143
3.017241
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/ViewControllerExtensions.swift
1
10267
// // ViewControllerExtensions.swift // RsyncOSX // // Created by Thomas Evensen on 28.10.2017. // Copyright © 2017 Thomas Evensen. All rights reserved. // import Cocoa import Foundation protocol VcMain { var storyboard: NSStoryboard? { get } } extension VcMain { var storyboard: NSStoryboard? { return NSStoryboard(name: "Main", bundle: nil) } var sheetviewstoryboard: NSStoryboard? { return NSStoryboard(name: "SheetViews", bundle: nil) } // StoryboardOutputID var viewControllerAllOutput: NSViewController? { return (storyboard?.instantiateController(withIdentifier: "StoryboardOutputID") as? NSViewController) } // Sheetviews // Userconfiguration var viewControllerUserconfiguration: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardUserconfigID") as? NSViewController) } // Information about rsync output var viewControllerInformation: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardInformationID") as? NSViewController) } // AssistID var viewControllerAssist: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AssistID") as? NSViewController) } // Profile var viewControllerProfile: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "ProfileID") as? NSViewController) } // About var viewControllerAbout: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AboutID") as? NSViewController) } // Remote Info var viewControllerRemoteInfo: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardRemoteInfoID") as? NSViewController) } // Quick backup process var viewControllerQuickBackup: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardQuickBackupID") as? NSViewController) } // local and remote info var viewControllerInformationLocalRemote: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardLocalRemoteID") as? NSViewController) } // Estimating var viewControllerEstimating: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardEstimatingID") as? NSViewController) } // Progressbar process var viewControllerProgress: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardProgressID") as? NSViewController) } // Rsync userparams var viewControllerRsyncParams: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardRsyncParamsID") as? NSViewController) } // Edit var editViewController: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "StoryboardEditID") as? NSViewController) } // RsyncCommand var rsynccommand: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "RsyncCommand") as? NSViewController) } // Schedules view var schedulesview: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "ViewControllertabSchedule") as? NSViewController) } // Add task var addtaskViewController: NSViewController? { return (sheetviewstoryboard?.instantiateController(withIdentifier: "AddTaskID") as? NSViewController) } } // Protocol for dismissing a viewcontroller protocol DismissViewController: AnyObject { func dismiss_view(viewcontroller: NSViewController) } protocol SetDismisser { func dismissview(viewcontroller: NSViewController, vcontroller: ViewController) } extension SetDismisser { var dismissDelegateMain: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } var dismissDelegateSchedule: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcschedule) as? ViewControllerSchedule } var dismissDelegateCopyFiles: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore } var dimissDelegateSnapshot: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcsnapshot) as? ViewControllerSnapshots } var dismissDelegateLoggData: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcloggdata) as? ViewControllerLoggData } var dismissDelegateSsh: DismissViewController? { return SharedReference.shared.getvcref(viewcontroller: .vcssh) as? ViewControllerSsh } func dismissview(viewcontroller _: NSViewController, vcontroller: ViewController) { if vcontroller == .vctabmain { dismissDelegateMain?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcschedule { dismissDelegateSchedule?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcrestore { dismissDelegateCopyFiles?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcsnapshot { dimissDelegateSnapshot?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcloggdata { dismissDelegateLoggData?.dismiss_view(viewcontroller: (self as? NSViewController)!) } else if vcontroller == .vcssh { dismissDelegateSsh?.dismiss_view(viewcontroller: (self as? NSViewController)!) } } } // Protocol for deselecting rowtable protocol DeselectRowTable: AnyObject { func deselect() } protocol Deselect { var deselectDelegateMain: DeselectRowTable? { get } var deselectDelegateSchedule: DeselectRowTable? { get } } extension Deselect { var deselectDelegateMain: DeselectRowTable? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } var deselectDelegateSchedule: DeselectRowTable? { return SharedReference.shared.getvcref(viewcontroller: .vcschedule) as? ViewControllerSchedule } func deselectrowtable(vcontroller: ViewController) { if vcontroller == .vctabmain { deselectDelegateMain?.deselect() } else { deselectDelegateSchedule?.deselect() } } } protocol Index { func index() -> Int? } extension Index { func index() -> Int? { weak var getindexDelegate: GetSelecetedIndex? getindexDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain return getindexDelegate?.getindex() } } protocol Delay { func delayWithSeconds(_ seconds: Double, completion: @escaping () -> Void) } extension Delay { func delayWithSeconds(_ seconds: Double, completion: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completion() } } } protocol Connected { func connected(config: Configuration?) -> Bool func connected(server: String?) -> Bool } extension Connected { func connected(config: Configuration?) -> Bool { var port = 22 if let config = config { if config.offsiteServer.isEmpty == false { if let sshport: Int = config.sshport { port = sshport } let success = TCPconnections().verifyTCPconnection(config.offsiteServer, port: port, timeout: 1) return success } else { return true } } return false } func connected(server: String?) -> Bool { if let server = server { let port = 22 if server.isEmpty == false { let success = TCPconnections().verifyTCPconnection(server, port: port, timeout: 1) return success } else { return true } } return false } } protocol Abort { func abort() } extension Abort { func abort() { let view = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain view?.abortOperations() } } protocol Help { func help() } extension Help { func help() { NSWorkspace.shared.open(URL(string: "https://rsyncosx.netlify.app/post/rsyncosxdocs/")!) } } protocol GetOutput: AnyObject { func getoutput() -> [String] } protocol OutPut { var informationDelegateMain: GetOutput? { get } } extension OutPut { var informationDelegateMain: GetOutput? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } func getinfo() -> [String] { return (informationDelegateMain?.getoutput()) ?? [""] } } protocol RsyncIsChanged: AnyObject { func rsyncischanged() } protocol NewRsync { func newrsync() } extension NewRsync { func newrsync() { let view = SharedReference.shared.getvcref(viewcontroller: .vcsidebar) as? ViewControllerSideBar view?.rsyncischanged() } } protocol TemporaryRestorePath { func temporaryrestorepath() } protocol ChangeTemporaryRestorePath { func changetemporaryrestorepath() } extension ChangeTemporaryRestorePath { func changetemporaryrestorepath() { let view = SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore view?.temporaryrestorepath() } } extension Sequence { func sorted<T: Comparable>( by keyPath: KeyPath<Element, T>, using comparator: (T, T) -> Bool = (<) ) -> [Element] { sorted { a, b in comparator(a[keyPath: keyPath], b[keyPath: keyPath]) } } }
mit
3fb4d25300f24a19d6bfa101108db91e
29.372781
112
0.683226
4.831059
false
false
false
false
luckymore0520/GreenTea
Loyalty/Activity/Views/ActivityToolBar.swift
1
1758
// // ActivityToolBar.swift // Loyalty // // Created by WangKun on 16/4/10. // Copyright © 2016年 WangKun. All rights reserved. // import UIKit import Cartography class ActivityToolBar: UIView { var clickHandlers:[()->Void] = [] required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } //传入按钮颜色的数组(提供默认参数)、图片数组、按钮标题数组以及回调数组 func updateView(colorArray:[UIColor] = [UIColor.globalLightGreenColor(),UIColor.globalLightBlueColor()],imageArray:[String]!,titleArray:[String]!, clickHandlers:[()->Void]) { var buttonArray:[UIButton] = [] let buttonWidth = self.frame.size.width / CGFloat(titleArray.count) for i in 0...imageArray.count-1 { let button = UIButton(type: UIButtonType.Custom) button.setImage(UIImage(named: imageArray[i]), forState: UIControlState.Normal) button.setTitle(" \(titleArray[i])", forState: UIControlState.Normal) button.backgroundColor = colorArray[i] self.addSubview(button) button.tag = i button.addTarget(self, action: #selector(ActivityToolBar.onButtonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) buttonArray.append(button) constrain(button,self) { button,view in button.left == view.left + buttonWidth * CGFloat(i) button.top == view.top button.height == view.height button.width == buttonWidth } } self.clickHandlers = clickHandlers } func onButtonClicked(sender:UIButton) { let tag = sender.tag clickHandlers[tag]() } }
mit
78a79b6044ccc8e0a09501829a543c31
35.630435
178
0.624332
4.44591
false
false
false
false
willhains/Kotoba
code/Kotoba/WordListDataSource.swift
1
2732
// // Created by Will Hains on 2020-06-21. // Copyright (c) 2020 Will Hains. All rights reserved. // import Foundation /// Model of user's saved words. protocol WordListDataSource { /// Access saved words by index. subscript(index: Int) -> Word { get } /// The number of saved words. var count: Int { get } /// Add `word` to the word list. mutating func add(word: Word) /// Delete the word at `index` from the word list. mutating func delete(wordAt index: Int) /// Delete all words from the word list. mutating func clear() /// All words, delimited by newlines func asText() -> String /// Latest word var latestWord: Word? { get } } // Default implementations extension WordListDataSource where Self: WordListStrings { subscript(index: Int) -> Word { get { Word(text: wordStrings[index]) } set { wordStrings[index] = newValue.text } } var count: Int { wordStrings.count } mutating func add(word: Word) { // Prevent duplicates; move to top of list instead wordStrings.add(possibleDuplicate: word.canonicalise()) debugLog("add: wordStrings=\(wordStrings.first ?? "")..\(wordStrings.last ?? "")") } mutating func delete(wordAt index: Int) { wordStrings.remove(at: index) debugLog("remove: wordStrings=\(wordStrings.first ?? "")..\(wordStrings.last ?? "")") } mutating func clear() { wordStrings = [] } func asText() -> String { // NOTE: Adding a newline at the end makes it easier to edit in a text editor like Notes. // It also conforms to the POSIX standard. // https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline#729795 wordStrings.joined(separator: "\n") + "\n" } var latestWord: Word? { wordStrings.first.map(Word.init) } } // MARK:- Array extensions for WordList // TODO #14: Consider changing Array to Set, and sorting by date added. extension Array where Element: Equatable { /// Remove the first matching `element`, if it exists. mutating func remove(_ element: Element) { if let existingIndex = firstIndex(of: element) { self.remove(at: existingIndex) } } /// Add `element` to the head without duplicating existing mutating func add(possibleDuplicate element: Element) { remove(element) insert(element, at: 0) } } // MARK:- WordListDataSource implementation backed by UserDefaults / NSUbiquitousKeyValueStore private let _WORD_LIST_KEY = "words" extension NSUbiquitousKeyValueStore: WordListStrings, WordListDataSource { var wordStrings: [String] { get { object(forKey: _WORD_LIST_KEY) as? [String] ?? [] } set { NSUbiquitousKeyValueStore.default.set(newValue, forKey: _WORD_LIST_KEY) } } static var iCloudEnabledInSettings: Bool { FileManager.default.ubiquityIdentityToken != nil } }
mit
e544ec67a811411707f93f2d62fe7f8b
24.53271
95
0.704978
3.445145
false
false
false
false
vector-im/vector-ios
Riot/Managers/KeyValueStorage/MemoryStore.swift
1
2694
// // Copyright 2020 Vector Creations Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class MemoryStore { private(set) var map: [KeyValueStoreKey: Any] = [:] private func setObject(_ value: Any?, forKey key: KeyValueStoreKey) { if let value = value { map[key] = value } else { try? removeObject(forKey: key) } } private func object(forKey key: KeyValueStoreKey) -> Any? { return map[key] } init(withMap map: [KeyValueStoreKey: Any] = [:]) { self.map = map } } extension MemoryStore: KeyValueStore { // setters func set(_ value: Data?, forKey key: KeyValueStoreKey) throws { setObject(value, forKey: key) } func set(_ value: String?, forKey key: KeyValueStoreKey) throws { setObject(value, forKey: key) } func set(_ value: Bool?, forKey key: KeyValueStoreKey) throws { setObject(value, forKey: key) } func set(_ value: Int?, forKey key: KeyValueStoreKey) throws { setObject(value, forKey: key) } func set(_ value: UInt?, forKey key: KeyValueStoreKey) throws { setObject(value, forKey: key) } // getters func data(forKey key: KeyValueStoreKey) throws -> Data? { return object(forKey: key) as? Data } func string(forKey key: KeyValueStoreKey) throws -> String? { return object(forKey: key) as? String } func bool(forKey key: KeyValueStoreKey) throws -> Bool? { return object(forKey: key) as? Bool } func integer(forKey key: KeyValueStoreKey) throws -> Int? { return object(forKey: key) as? Int } func unsignedInteger(forKey key: KeyValueStoreKey) throws -> UInt? { return object(forKey: key) as? UInt } // checkers func containsObject(forKey key: KeyValueStoreKey) -> Bool { return object(forKey: key) != nil } // remove func removeObject(forKey key: KeyValueStoreKey) throws { map.removeValue(forKey: key) } func removeAll() throws { map.removeAll() } }
apache-2.0
8b5a020c9d868c092191ed89a783f894
26.212121
75
0.62101
4.262658
false
false
false
false
CoderJChen/SWWB
CJWB/CJWB/Classes/Main/CJVisitorView.swift
1
1183
// // CJVisitorView.swift // CJWB // // Created by 星驿ios on 2017/8/2. // Copyright © 2017年 CJ. All rights reserved. // import UIKit class CJVisitorView: UIView { @IBOutlet weak var rotationView: UIImageView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var loginBtn: UIButton! class func visitorView() -> CJVisitorView{ return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)!.first as! CJVisitorView } func setupVisitorViewInfo(_ iconName:String,title:String){ iconView.image = UIImage(named: iconName) tipLabel.text = title rotationView.isHidden = true } func addRotationAnim() -> Void { // 旋转 let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnim.fromValue = 0 rotationAnim.toValue = Double.pi * 2 rotationAnim.repeatCount = MAXFLOAT rotationAnim.duration = 5 rotationAnim.isRemovedOnCompletion = false rotationView.layer.add(rotationAnim, forKey: nil) } }
apache-2.0
75370fe6c69da89e6402dc94d8abaa4b
28.3
105
0.66041
4.542636
false
false
false
false
Shuangzuan/Pew
Pew/PlayerLaser.swift
1
1217
// // PlayerLaser.swift // Pew // // Created by Shuangzuan He on 4/16/15. // Copyright (c) 2015 Pretty Seven. All rights reserved. // import SpriteKit class PlayerLaser: Entity { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(imageNamed: "laserbeam_blue", maxHp: 1, healthBarType: .None) setupCollisionBody() } private func setupCollisionBody() { let offset = CGPoint(x: size.width * anchorPoint.x, y: size.height * anchorPoint.y) let path = CGPathCreateMutable() moveToPoint(CGPoint(x: 7, y: 12), path: path, offset: offset) addLineToPoint(CGPoint(x: 53, y: 11), path: path, offset: offset) addLineToPoint(CGPoint(x: 53, y: 5), path: path, offset: offset) addLineToPoint(CGPoint(x: 7, y: 6), path: path, offset: offset) CGPathCloseSubpath(path) physicsBody = SKPhysicsBody(polygonFromPath: path) physicsBody?.categoryBitMask = PhysicsCategory.PlayerLaser physicsBody?.collisionBitMask = 0 physicsBody?.contactTestBitMask = PhysicsCategory.Asteroid | PhysicsCategory.Alien } }
mit
d354f67929bbd693ae857c227e20a127
31.891892
91
0.648316
4.097643
false
false
false
false
lionchina/RxSwiftBook
RxValidation/RxValidation/AppDelegate.swift
1
4603
// // AppDelegate.swift // RxValidation // // Created by MaxChen on 04/08/2017. // Copyright © 2017 com.linglustudio. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RxValidation") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
96609ff13d04527c1d3296ad58f92c76
48.483871
285
0.686658
5.840102
false
false
false
false
mcddx330/Pumpkin
Pumpkin/PKFuncs.swift
1
1543
// // PKFuncs.swift // Pumpkin // // Created by dimbow. on 3/29/15. // Copyright (c) 2015 dimbow. All rights reserved. // private let view_height = (cgfloat:UIScreen.mainScreen().bounds.size.height,double:Double(UIScreen.mainScreen().bounds.size.height)); private let view_width = (cgfloat:UIScreen.mainScreen().bounds.size.width,double:Double(UIScreen.mainScreen().bounds.size.width)); private let view_middle_height = (cgfloat:view_height.cgfloat/2,double:view_height.double/2); private let view_middle_width = (cgfloat:view_width.cgfloat/2,double:view_width.double/2); private let view_middle_height_middleup = (cgfloat:view_middle_height.cgfloat+(view_middle_height.cgfloat/2),double:(view_middle_height.double)+(view_middle_height.double/2)); private let view_middle_height_middledown = (cgfloat:view_middle_height.cgfloat/2,double:view_middle_height.double/2); private let view_middle_width_middleleft = (cgfloat:view_middle_width.cgfloat/2,double:view_middle_width.double/2); private let view_middle_width_middleright = (cgfloat:view_middle_width.cgfloat+(view_middle_width.cgfloat/2),double:view_middle_width.double+(view_middle_width.double/2)); public let PKPosition = ( Height:( Full:view_height, Middle:view_middle_height, MiddleUp:view_middle_height_middleup, MiddleDown:view_middle_height_middledown ), Width:( Full:view_width, Middle:view_middle_width, MiddleLeft:view_middle_width_middleleft, MiddleRight:view_middle_width_middleright ) );
mit
29ef9fd8cce9a1560c68a46bfdfab4a8
45.787879
175
0.738172
3.289979
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ExportedInvitationController.swift
1
17472
// // ExportedInvitationController.swift // Telegram // // Created by Mikhail Filimonov on 17.01.2021. // Copyright © 2021 Telegram. All rights reserved. // import Cocoa import TelegramCore import SwiftSignalKit import Postbox import TGUIKit private final class ExportInvitationArguments { let context: (joined: PeerInvitationImportersContext, requested: PeerInvitationImportersContext) let accountContext: AccountContext let copyLink: (String)->Void let shareLink: (String)->Void let openProfile:(PeerId)->Void let revokeLink: (_ExportedInvitation)->Void let editLink:(_ExportedInvitation)->Void init(context: (joined: PeerInvitationImportersContext, requested: PeerInvitationImportersContext), accountContext: AccountContext, copyLink: @escaping(String)->Void, shareLink: @escaping(String)->Void, openProfile:@escaping(PeerId)->Void, revokeLink: @escaping(_ExportedInvitation)->Void, editLink: @escaping(_ExportedInvitation)->Void) { self.context = context self.accountContext = accountContext self.copyLink = copyLink self.shareLink = shareLink self.openProfile = openProfile self.revokeLink = revokeLink self.editLink = editLink } } private struct State : Equatable { var requestedState: PeerInvitationImportersState? var joinedState: PeerInvitationImportersState? } private let _id_link = InputDataIdentifier("_id_link") private func _id_admin(_ peerId: PeerId) -> InputDataIdentifier { return InputDataIdentifier("_id_admin_\(peerId.toInt64())") } private func _id_peer(_ peerId: PeerId, joined: Bool) -> InputDataIdentifier { return InputDataIdentifier("_id_peer_\(peerId.toInt64())_\(joined)") } private func entries(_ state: State, admin: Peer?, invitation: _ExportedInvitation, arguments: ExportInvitationArguments) -> [InputDataEntry] { let joinedState: PeerInvitationImportersState? = state.joinedState let requestedState: PeerInvitationImportersState? = state.requestedState var entries:[InputDataEntry] = [] var sectionId: Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_link, equatable: InputDataEquatable(invitation), comparable: nil, item: { initialSize, stableId in return ExportedInvitationRowItem(initialSize, stableId: stableId, context: arguments.accountContext, exportedLink: invitation, lastPeers: [], viewType: .singleItem, mode: .short, menuItems: { var items:[ContextMenuItem] = [] items.append(ContextMenuItem(strings().exportedInvitationContextCopy, handler: { arguments.copyLink(invitation.link) }, itemImage: MenuAnimation.menu_copy.value)) if !invitation.isRevoked { if !invitation.isExpired { items.append(ContextMenuItem(strings().manageLinksContextShare, handler: { arguments.shareLink(invitation.link) }, itemImage: MenuAnimation.menu_share.value)) } if !invitation.isPermanent { items.append(ContextMenuItem(strings().manageLinksContextEdit, handler: { arguments.editLink(invitation) }, itemImage: MenuAnimation.menu_edit.value)) } if admin?.isBot == true { } else { if !items.isEmpty { items.append(ContextSeparatorItem()) } items.append(ContextMenuItem(strings().manageLinksContextRevoke, handler: { arguments.revokeLink(invitation) }, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value)) } } return .single(items) }, share: arguments.shareLink, copyLink: arguments.copyLink) })) let dateFormatter = DateFormatter() dateFormatter.locale = appAppearance.locale dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short if let admin = admin { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().exportedInvitationLinkCreatedBy), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_admin(admin.id), equatable: InputDataEquatable(PeerEquatable(admin)), comparable: nil, item: { initialSize, stableId in return ShortPeerRowItem(initialSize, peer: admin, account: arguments.accountContext.account, context: arguments.accountContext, stableId: stableId, height: 48, photoSize: NSMakeSize(36, 36), status: dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(invitation.date))), inset: NSEdgeInsetsMake(0, 30, 0, 30), viewType: .singleItem) })) } if let requestedState = requestedState { let importers = requestedState.importers.filter { $0.peer.peer != nil } if !importers.isEmpty { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().exportedInvitationPeopleRequestedCountable(Int(requestedState.count))), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 for importer in requestedState.importers { struct Tuple : Equatable { let importer: PeerInvitationImportersState.Importer let viewType: GeneralViewType } let tuple = Tuple(importer: importer, viewType: bestGeneralViewType(requestedState.importers, for: importer)) entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_peer(importer.peer.peerId, joined: false), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in return ShortPeerRowItem(initialSize, peer: tuple.importer.peer.peer!, account: arguments.accountContext.account, context: arguments.accountContext, stableId: stableId, height: 48, photoSize: NSMakeSize(36, 36), status: dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(importer.date))), inset: NSEdgeInsetsMake(0, 30, 0, 30), viewType: tuple.viewType, action: { arguments.openProfile(tuple.importer.peer.peerId) }, contextMenuItems: { let items = [ContextMenuItem(strings().exportedInvitationContextOpenProfile, handler: { arguments.openProfile(tuple.importer.peer.peerId) })] return .single(items) }) })) } } } if let joinedState = joinedState { let importers = joinedState.importers.filter { $0.peer.peer != nil } if !importers.isEmpty { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().exportedInvitationPeopleJoinedCountable(Int(joinedState.count))), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem))) index += 1 for importer in joinedState.importers { struct Tuple : Equatable { let importer: PeerInvitationImportersState.Importer let viewType: GeneralViewType } let tuple = Tuple(importer: importer, viewType: bestGeneralViewType(joinedState.importers, for: importer)) entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_peer(importer.peer.peerId, joined: true), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in return ShortPeerRowItem(initialSize, peer: tuple.importer.peer.peer!, account: arguments.accountContext.account, context: arguments.accountContext, stableId: stableId, height: 48, photoSize: NSMakeSize(36, 36), status: dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(importer.date))), inset: NSEdgeInsetsMake(0, 30, 0, 30), viewType: tuple.viewType, action: { arguments.openProfile(tuple.importer.peer.peerId) }, contextMenuItems: { let items = [ContextMenuItem(strings().exportedInvitationContextOpenProfile, handler: { arguments.openProfile(tuple.importer.peer.peerId) })] return .single(items) }) })) } } if joinedState.count == 0, !invitation.isExpired, !invitation.isRevoked, let usageCount = invitation.usageLimit, invitation.count == nil { entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("_id_join_count"), equatable: nil, comparable: nil, item: { initialSize, stableId in return GeneralBlockTextRowItem(initialSize, stableId: stableId, viewType: .singleItem, text: strings().inviteLinkEmptyJoinDescCountable(Int(usageCount)), font: .normal(.text)) })) } } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func ExportedInvitationController(invitation: _ExportedInvitation, peerId: PeerId, accountContext: AccountContext, manager: InviteLinkPeerManager, context: (joined: PeerInvitationImportersContext, requested: PeerInvitationImportersContext)) -> InputDataModalController { let actionsDisposable = DisposableSet() var getController:(()->InputDataController?)? = nil var getModalController:(()->InputDataModalController?)? = nil let arguments = ExportInvitationArguments(context: context, accountContext: accountContext, copyLink: { link in getController?()?.show(toaster: ControllerToaster(text: strings().shareLinkCopied)) copyToClipboard(link) }, shareLink: { link in showModal(with: ShareModalController(ShareLinkObject(accountContext, link: link)), for: accountContext.window) }, openProfile: { peerId in getModalController?()?.close() accountContext.bindings.rootNavigation().push(PeerInfoController(context: accountContext, peerId: peerId)) }, revokeLink: { [weak manager] link in confirm(for: accountContext.window, header: strings().channelRevokeLinkConfirmHeader, information: strings().channelRevokeLinkConfirmText, okTitle: strings().channelRevokeLinkConfirmOK, cancelTitle: strings().modalCancel, successHandler: { _ in if let manager = manager { _ = showModalProgress(signal: manager.revokePeerExportedInvitation(link: link), for: accountContext.window).start() getModalController?()?.close() } }) }, editLink: { [weak manager] link in getModalController?()?.close() showModal(with: ClosureInviteLinkController(context: accountContext, peerId: peerId, mode: .edit(link), save: { [weak manager] updated in let signal = manager?.editPeerExportedInvitation(link: link, title: updated.title, expireDate: updated.date == .max ? 0 : updated.date + Int32(Date().timeIntervalSince1970), usageLimit: updated.count == .max ? 0 : updated.count) if let signal = signal { _ = showModalProgress(signal: signal, for: accountContext.window).start() } }), for: accountContext.window) }) let initialState = State() let statePromise = ValuePromise<State>(ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } actionsDisposable.add(combineLatest(context.joined.state, context.requested.state).start(next: { joined, requested in updateState { current in var current = current current.requestedState = requested current.joinedState = joined return current } })) let dataSignal = combineLatest(queue: prepareQueue, statePromise.get(), accountContext.account.postbox.transaction { $0.getPeer(invitation.adminId) }) |> deliverOnPrepareQueue |> map { state, admin in return entries(state, admin: admin, invitation: invitation, arguments: arguments) } |> map { entries in return InputDataSignalValue(entries: entries) } let controller = InputDataController(dataSignal: dataSignal, title: invitation.title ?? strings().exportedInvitationTitle) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { getModalController?()?.close() }) let dateFormatter = DateFormatter() dateFormatter.locale = appAppearance.locale dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short let getSubtitle:()->String? = { var subtitle: String? = nil if invitation.isRevoked { subtitle = strings().exportedInvitationStatusRevoked } else { if let expireDate = invitation.expireDate { if expireDate > Int32(Date().timeIntervalSince1970) { let left = Int(expireDate) - Int(Date().timeIntervalSince1970) if left <= Int(Int32.secondsInDay) { let minutes = left / 60 % 60 let seconds = left % 60 let hours = left / 60 / 60 let string = String(format: "%@:%@:%@", hours < 10 ? "0\(hours)" : "\(hours)", minutes < 10 ? "0\(minutes)" : "\(minutes)", seconds < 10 ? "0\(seconds)" : "\(seconds)") subtitle = strings().inviteLinkStickerTimeLeft(string) } else { subtitle = strings().inviteLinkStickerTimeLeft(autoremoveLocalized(left)) } } else { subtitle = strings().exportedInvitationStatusExpired } } } return subtitle } controller.centerModalHeader = ModalHeaderData(title: invitation.title ?? strings().exportedInvitationTitle, subtitle: getSubtitle()) getController = { [weak controller] in return controller } controller.updateDatas = { data in return .none } controller.onDeinit = { actionsDisposable.dispose() updateState { current in var current = current current.joinedState = nil current.requestedState = nil return current } } let modalInteractions = ModalInteractions(acceptTitle: strings().exportedInvitationDone, accept: { [weak controller] in controller?.validateInputValues() }, drawBorder: true, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions, closeHandler: { f in f() }, size: NSMakeSize(340, 350)) getModalController = { [weak modalController] in return modalController } controller.validateData = { data in return .success(.custom { getModalController?()?.close() }) } let joined = context.joined let requested = context.requested controller.didLoaded = { [weak requested, weak joined] controller, _ in controller.tableView.setScrollHandler { [weak joined, weak requested] position in switch position.direction { case .bottom: let state = stateValue.with { $0 } if let requestedState = state.requestedState { if requestedState.canLoadMore { requested?.loadMore() break } } if let joinedState = state.joinedState { if joinedState.canLoadMore { joined?.loadMore() break } } default: break } } } let timer = SwiftSignalKit.Timer(timeout: 1, repeat: true, completion: { [weak modalController, weak controller] in if let modalController = modalController { controller?.centerModalHeader = ModalHeaderData(title: invitation.title ?? strings().exportedInvitationTitle, subtitle: getSubtitle()) modalController.updateLocalizationAndTheme(theme: theme) } }, queue: .mainQueue()) timer.start() controller.contextObject = timer return modalController }
gpl-2.0
d89ad45b39b941961d975a41bad8e396
46.218919
399
0.630244
5.263935
false
false
false
false
CKOTech/checkoutkit-ios
CheckoutKit/CheckoutKit/CardTokenResponse.swift
1
2121
// // CardTokenResponse.swift // CheckoutKit // // Created by Manon Henrioux on 17/08/2015. // Copyright (c) 2015 Checkout.com. All rights reserved. // import Foundation /** Class used for receiving REST messages, it has the same format as the expected response. We extract the useful information based on this. */ open class CardTokenResponse: Serializable { open var cardToken: String! open var liveMode: Bool! open var created: String! open var used: Bool! open var card: CardToken! /** Default constructor @param cardToken String containing the id of the card @param liveMode boolean, if the request was on a live server or not @param created String containing time information about the creation of the card token @param used boolean, if the token has already been used or not @param card CardToken object containing all the information needed to charge the card */ public init(cardToken: String, liveMode: Bool, created: String, used: Bool, card: CardToken) { self.cardToken = cardToken self.liveMode = liveMode self.created = created self.used = used self.card = card } /** Convenience constructor @param data Dictionary [String: AnyObject] containing a JSON representation of a CardTokenResponse instance */ public required init?(data: [String: AnyObject]) { if let ct = data["id"] as? String, let created = data["created"] as? String, let lm = data["liveMode"] as? Bool, let used = data["used"] as? Bool, let card = data["card"] as? [String: AnyObject] { self.cardToken = ct self.created = created self.liveMode = lm self.used = used let c = CardToken(data: card) if c == nil { return nil } else { self.card = c! } } else { return nil } } }
mit
28e4ca8f06e7d47689d6c381bab497c3
27.662162
144
0.579915
4.723831
false
false
false
false
longitachi/ZLPhotoBrowser
Sources/Extensions/UIImage+ZLPhotoBrowser.swift
1
19462
// // UIImage+ZLPhotoBrowser.swift // ZLPhotoBrowser // // Created by long on 2020/8/22. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Accelerate import MobileCoreServices // MARK: data 转 gif image public extension ZLPhotoBrowserWrapper where Base: UIImage { static func animateGifImage(data: Data) -> UIImage? { // Kingfisher let info: [String: Any] = [ kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF ] guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else { return UIImage(data: data) } let frameCount = CGImageSourceGetCount(imageSource) guard frameCount > 1 else { return UIImage(data: data) } var images = [UIImage]() var frameDuration = [Int]() for i in 0..<frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else { return nil } // Get current animated GIF frame duration let currFrameDuration = getFrameDuration(from: imageSource, at: i) // Second to ms frameDuration.append(Int(currFrameDuration * 1000)) images.append(UIImage(cgImage: imageRef, scale: 1, orientation: .up)) } // https://github.com/kiritmodi2702/GIF-Swift let duration: Int = { var sum = 0 for val in frameDuration { sum += val } return sum }() // 求出每一帧的最大公约数 let gcd = gcdForArray(frameDuration) var frames = [UIImage]() for i in 0..<frameCount { let frameImage = images[i] // 每张图片的时长除以最大公约数,得出需要展示的张数 let count = Int(frameDuration[i] / gcd) for _ in 0..<count { frames.append(frameImage) } } return .animatedImage(with: frames, duration: TimeInterval(duration) / 1000) } /// Calculates frame duration at a specific index for a gif from an `imageSource`. static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval { guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil) as? [String: Any] else { return 0.0 } let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any] return getFrameDuration(from: gifInfo) } /// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary. static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval { let defaultFrameDuration = 0.1 guard let gifInfo = gifInfo else { return defaultFrameDuration } let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return defaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration } private static func gcdForArray(_ array: [Int]) -> Int { if array.isEmpty { return 1 } var gcd = array[0] for val in array { gcd = gcdForPair(val, gcd) } return gcd } private static func gcdForPair(_ num1: Int?, _ num2: Int?) -> Int { guard var num1 = num1, var num2 = num2 else { return num1 ?? (num2 ?? 0) } if num1 < num2 { swap(&num1, &num2) } var rest: Int while true { rest = num1 % num2 if rest == 0 { return num2 } else { num1 = num2 num2 = rest } } } } // MARK: image edit public extension ZLPhotoBrowserWrapper where Base: UIImage { /// 修复转向 func fixOrientation() -> UIImage { if base.imageOrientation == .up { return base } var transform = CGAffineTransform.identity switch base.imageOrientation { case .down, .downMirrored: transform = CGAffineTransform(translationX: width, y: height) transform = transform.rotated(by: .pi) case .left, .leftMirrored: transform = CGAffineTransform(translationX: width, y: 0) transform = transform.rotated(by: CGFloat.pi / 2) case .right, .rightMirrored: transform = CGAffineTransform(translationX: 0, y: height) transform = transform.rotated(by: -CGFloat.pi / 2) default: break } switch base.imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: width, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: height, y: 0) transform = transform.scaledBy(x: -1, y: 1) default: break } guard let cgImage = base.cgImage, let colorSpace = cgImage.colorSpace else { return base } let context = CGContext( data: nil, width: Int(width), height: Int(height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: cgImage.bitmapInfo.rawValue ) context?.concatenate(transform) switch base.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width)) default: context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height)) } guard let newCgImage = context?.makeImage() else { return base } return UIImage(cgImage: newCgImage) } /// 旋转方向 func rotate(orientation: UIImage.Orientation) -> UIImage { guard let imagRef = base.cgImage else { return base } let rect = CGRect(origin: .zero, size: CGSize(width: CGFloat(imagRef.width), height: CGFloat(imagRef.height))) var bnds = rect var transform = CGAffineTransform.identity switch orientation { case .up: return base case .upMirrored: transform = transform.translatedBy(x: rect.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .down: transform = transform.translatedBy(x: rect.width, y: rect.height) transform = transform.rotated(by: .pi) case .downMirrored: transform = transform.translatedBy(x: 0, y: rect.height) transform = transform.scaledBy(x: 1, y: -1) case .left: bnds = swapRectWidthAndHeight(bnds) transform = transform.translatedBy(x: 0, y: rect.width) transform = transform.rotated(by: CGFloat.pi * 3 / 2) case .leftMirrored: bnds = swapRectWidthAndHeight(bnds) transform = transform.translatedBy(x: rect.height, y: rect.width) transform = transform.scaledBy(x: -1, y: 1) transform = transform.rotated(by: CGFloat.pi * 3 / 2) case .right: bnds = swapRectWidthAndHeight(bnds) transform = transform.translatedBy(x: rect.height, y: 0) transform = transform.rotated(by: CGFloat.pi / 2) case .rightMirrored: bnds = swapRectWidthAndHeight(bnds) transform = transform.scaledBy(x: -1, y: 1) transform = transform.rotated(by: CGFloat.pi / 2) @unknown default: return base } UIGraphicsBeginImageContext(bnds.size) let context = UIGraphicsGetCurrentContext() switch orientation { case .left, .leftMirrored, .right, .rightMirrored: context?.scaleBy(x: -1, y: 1) context?.translateBy(x: -rect.height, y: 0) default: context?.scaleBy(x: 1, y: -1) context?.translateBy(x: 0, y: -rect.height) } context?.concatenate(transform) context?.draw(imagRef, in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage ?? base } func swapRectWidthAndHeight(_ rect: CGRect) -> CGRect { var r = rect r.size.width = rect.height r.size.height = rect.width return r } func rotate(degress: CGFloat) -> UIImage { guard degress != 0, let cgImage = base.cgImage else { return base } let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height)) let t = CGAffineTransform(rotationAngle: degress) rotatedViewBox.transform = t let rotatedSize = rotatedViewBox.frame.size UIGraphicsBeginImageContext(rotatedSize) let bitmap = UIGraphicsGetCurrentContext() bitmap?.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2) bitmap?.rotate(by: degress) bitmap?.scaleBy(x: 1.0, y: -1.0) bitmap?.draw(cgImage, in: CGRect(x: -width / 2, y: -height / 2, width: width, height: height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage ?? base } /// 加马赛克 func mosaicImage() -> UIImage? { guard let cgImage = base.cgImage else { return nil } let scale = 8 * width / UIScreen.main.bounds.width let currCiImage = CIImage(cgImage: cgImage) let filter = CIFilter(name: "CIPixellate") filter?.setValue(currCiImage, forKey: kCIInputImageKey) filter?.setValue(scale, forKey: kCIInputScaleKey) guard let outputImage = filter?.outputImage else { return nil } let context = CIContext() if let cgImage = context.createCGImage(outputImage, from: CGRect(origin: .zero, size: base.size)) { return UIImage(cgImage: cgImage) } else { return nil } } func resize(_ size: CGSize) -> UIImage? { if size.width <= 0 || size.height <= 0 { return nil } UIGraphicsBeginImageContextWithOptions(size, false, base.scale) base.draw(in: CGRect(origin: .zero, size: size)) let temp = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return temp } /// Processing speed is better than resize(:) method func resize_vI(_ size: CGSize) -> UIImage? { guard let cgImage = base.cgImage else { return nil } var format = vImage_CGImageFormat( bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), version: 0, decode: nil, renderingIntent: .defaultIntent ) var sourceBuffer = vImage_Buffer() defer { if #available(iOS 13.0, *) { sourceBuffer.free() } else { sourceBuffer.data.deallocate() } } var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags)) guard error == kvImageNoError else { return nil } let destWidth = Int(size.width) let destHeight = Int(size.height) let bytesPerPixel = cgImage.bitsPerPixel / 8 let destBytesPerRow = destWidth * bytesPerPixel let destData = UnsafeMutablePointer<UInt8>.allocate(capacity: destHeight * destBytesPerRow) defer { destData.deallocate() } var destBuffer = vImage_Buffer(data: destData, height: vImagePixelCount(destHeight), width: vImagePixelCount(destWidth), rowBytes: destBytesPerRow) // scale the image error = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, nil, numericCast(kvImageHighQualityResampling)) guard error == kvImageNoError else { return nil } // create a CGImage from vImage_Buffer guard let destCGImage = vImageCreateCGImageFromBuffer(&destBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue() else { return nil } guard error == kvImageNoError else { return nil } // create a UIImage return UIImage(cgImage: destCGImage, scale: base.scale, orientation: base.imageOrientation) } func toCIImage() -> CIImage? { var ciImage = base.ciImage if ciImage == nil, let cgImage = base.cgImage { ciImage = CIImage(cgImage: cgImage) } return ciImage } func clipImage(angle: CGFloat, editRect: CGRect, isCircle: Bool) -> UIImage? { let a = ((Int(angle) % 360) - 360) % 360 var newImage: UIImage = base if a == -90 { newImage = rotate(orientation: .left) } else if a == -180 { newImage = rotate(orientation: .down) } else if a == -270 { newImage = rotate(orientation: .right) } guard editRect.size != newImage.size else { return newImage } let origin = CGPoint(x: -editRect.minX, y: -editRect.minY) UIGraphicsBeginImageContextWithOptions(editRect.size, false, newImage.scale) let context = UIGraphicsGetCurrentContext() if isCircle { context?.addEllipse(in: CGRect(origin: .zero, size: editRect.size)) context?.clip() } newImage.draw(at: origin) let temp = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgi = temp?.cgImage else { return temp } let clipImage = UIImage(cgImage: cgi, scale: newImage.scale, orientation: .up) return clipImage } func blurImage(level: CGFloat) -> UIImage? { guard let ciImage = toCIImage() else { return nil } let blurFilter = CIFilter(name: "CIGaussianBlur") blurFilter?.setValue(ciImage, forKey: "inputImage") blurFilter?.setValue(level, forKey: "inputRadius") guard let outputImage = blurFilter?.outputImage else { return nil } let context = CIContext() guard let cgImage = context.createCGImage(outputImage, from: ciImage.extent) else { return nil } return UIImage(cgImage: cgImage) } } public extension ZLPhotoBrowserWrapper where Base: UIImage { /// 调整图片亮度、对比度、饱和度 /// - Parameters: /// - brightness: value in [-1, 1] /// - contrast: value in [-1, 1] /// - saturation: value in [-1, 1] func adjust(brightness: Float, contrast: Float, saturation: Float) -> UIImage? { guard let ciImage = toCIImage() else { return base } let filter = CIFilter(name: "CIColorControls") filter?.setValue(ciImage, forKey: kCIInputImageKey) filter?.setValue(ZLEditImageConfiguration.AdjustTool.brightness.filterValue(brightness), forKey: ZLEditImageConfiguration.AdjustTool.brightness.key) filter?.setValue(ZLEditImageConfiguration.AdjustTool.contrast.filterValue(contrast), forKey: ZLEditImageConfiguration.AdjustTool.contrast.key) filter?.setValue(ZLEditImageConfiguration.AdjustTool.saturation.filterValue(saturation), forKey: ZLEditImageConfiguration.AdjustTool.saturation.key) let outputCIImage = filter?.outputImage return outputCIImage?.zl.toUIImage() } } public extension ZLPhotoBrowserWrapper where Base: UIImage { static func image(withColor color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func fillColor(_ color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(base.size, false, base.scale) let drawRect = CGRect(x: 0, y: 0, width: base.zl.width, height: base.zl.height) color.setFill() UIRectFill(drawRect) base.draw(in: drawRect, blendMode: .destinationIn, alpha: 1) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } } public extension ZLPhotoBrowserWrapper where Base: UIImage { var width: CGFloat { base.size.width } var height: CGFloat { base.size.height } } extension ZLPhotoBrowserWrapper where Base: UIImage { static func getImage(_ named: String) -> UIImage? { if ZLCustomImageDeploy.imageNames.contains(named), let image = UIImage(named: named) { return image } if let image = ZLCustomImageDeploy.imageForKey[named] { return image } return UIImage(named: named, in: Bundle.zlPhotoBrowserBundle, compatibleWith: nil) } } public extension ZLPhotoBrowserWrapper where Base: CIImage { func toUIImage() -> UIImage? { let context = CIContext() guard let cgImage = context.createCGImage(base, from: base.extent) else { return nil } return UIImage(cgImage: cgImage) } }
mit
671c3e648b1d6cc6bffc04eb3ebf494f
35.90458
171
0.605285
4.753687
false
false
false
false
lucasmpaim/EasyRest
Sources/EasyRest/Classes/Service.swift
1
2665
// // Service.swift // Pods // // Created by Vithorio Polten on 3/25/16. // Base on Tof Template // // import Foundation open class Service<R> where R: Routable { public init() { } open var interceptors: [Interceptor]? {return nil} open var loggerLevel: LogLevel { return .verbose } open var loggerClass: Loggable.Type { return EasyRest.sharedInstance.globalLogClass } open var base: String { get { fatalError("Override to provide baseUrl") } } open func builder<T: Codable>(_ routes: R, type: T.Type) throws -> APIBuilder<T> { let builder = try routes.builder(base, type: type) builder.logger = self.loggerClass.init() builder.logger?.logLevel = self.loggerLevel if (interceptors != nil) { _ = builder.addInterceptors(interceptors!) } return builder } open func call<E: Codable>(_ routes: R, type: E.Type, onSuccess: @escaping (Response<E>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) throws -> CancelationToken<E> { let token = CancelationToken<E>() try builder(routes, type: type) .cancelToken(token: token) .build() .execute(onSuccess, onError: onError, always: always) return token } open func upload<E: Codable>(_ routes: R, type: E.Type, onProgress: @escaping (Float) -> Void, onSuccess: @escaping (Response<E>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) throws { try builder(routes, type: type) .build() .upload( onProgress, onSuccess: onSuccess, onError: onError, always: always ) } open func download(_ routes: R, onProgress: @escaping (Float) -> Void, onSuccess: @escaping (Response<Data>?) -> Void, onError: @escaping (RestError?) -> Void, always: @escaping () -> Void) throws { try builder(routes, type: Data.self) .build() .download( onProgress, onSuccess: onSuccess, onError: onError, always: always ) } }
mit
1a12acd2776ea3731d20f9a68d84e971
30.352941
92
0.479925
4.863139
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Collections/CollectionsView.swift
1
6346
// // Wire // Copyright (C) 2016 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 UIKit final class CollectionsView: UIView { var collectionViewLayout: CollectionViewLeftAlignedFlowLayout! var collectionView: UICollectionView! let noResultsView = NoResultsView() static let useAutolayout = false var noItemsInLibrary: Bool = false { didSet { noResultsView.isHidden = !noItemsInLibrary } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .from(scheme: .contentBackground) recreateLayout() collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout) collectionView.register(CollectionImageCell.self, forCellWithReuseIdentifier: CollectionImageCell.reuseIdentifier) collectionView.register(CollectionFileCell.self, forCellWithReuseIdentifier: CollectionFileCell.reuseIdentifier) collectionView.register(CollectionAudioCell.self, forCellWithReuseIdentifier: CollectionAudioCell.reuseIdentifier) collectionView.register(CollectionVideoCell.self, forCellWithReuseIdentifier: CollectionVideoCell.reuseIdentifier) collectionView.register(CollectionLinkCell.self, forCellWithReuseIdentifier: CollectionLinkCell.reuseIdentifier) collectionView.register(CollectionLoadingCell.self, forCellWithReuseIdentifier: CollectionLoadingCell.reuseIdentifier) collectionView.register(CollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionHeaderView.reuseIdentifier) collectionView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = false collectionView.allowsSelection = true collectionView.alwaysBounceVertical = true collectionView.isScrollEnabled = true collectionView.backgroundColor = UIColor.clear addSubview(collectionView) noResultsView.label.accessibilityLabel = "no items" noResultsView.label.text = "collections.section.no_items".localized(uppercased: true) noResultsView.icon = .library noResultsView.isHidden = true addSubview(noResultsView) } private func recreateLayout() { let layout = CollectionViewLeftAlignedFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 8, right: 16) if CollectionsView.useAutolayout { layout.estimatedItemSize = CGSize(width: 64, height: 64) } collectionViewLayout = layout } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static func closeButton() -> IconButton { let button = IconButton(style: .default) button.setIcon(.cross, size: .tiny, for: .normal) button.frame = CGRect(x: 0, y: 0, width: 48, height: 32) button.accessibilityIdentifier = "close" button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -24) return button } static func backButton() -> IconButton { let button = IconButton(style: .default) button.setIcon(.backArrow, size: .tiny, for: .normal) button.frame = CGRect(x: 0, y: 0, width: 32, height: 20) button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0) button.accessibilityIdentifier = "back" return button } func constrainViews(searchViewController: TextSearchViewController) { let searchBar = searchViewController.searchBar let resultsView = searchViewController.resultsView [searchBar, resultsView].forEach { addSubview($0) } let centerYConstraint = noResultsView.centerYAnchor.constraint(equalTo: centerYAnchor) centerYConstraint.priority = .defaultLow [searchBar, resultsView, collectionView, noResultsView].prepareForLayout() NSLayoutConstraint.activate([ searchBar.topAnchor.constraint(equalTo: topAnchor), searchBar.leadingAnchor.constraint(equalTo: leadingAnchor), searchBar.trailingAnchor.constraint(equalTo: trailingAnchor), searchBar.heightAnchor.constraint(equalToConstant: 56), collectionView.topAnchor.constraint(equalTo: searchBar.bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: trailingAnchor), collectionView.bottomAnchor.constraint(equalTo: bottomAnchor), noResultsView.topAnchor.constraint(greaterThanOrEqualTo: searchBar.bottomAnchor, constant: 12), noResultsView.centerXAnchor.constraint(equalTo: centerXAnchor), centerYConstraint, noResultsView.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -12), noResultsView.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 24), noResultsView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -24), resultsView.topAnchor.constraint(equalTo: collectionView.topAnchor), resultsView.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor), resultsView.leftAnchor.constraint(equalTo: collectionView.leftAnchor), resultsView.rightAnchor.constraint(equalTo: collectionView.rightAnchor) ]) } }
gpl-3.0
f94a82ccb022dc8ecb43c6a562d0eb8c
44.654676
188
0.727072
5.537522
false
false
false
false
lojals/JOCircleViz
CircleViz/CircleViz/CircleVizz.swift
1
3444
// // CircleVizz.swift // CircleViz // // Created by Jorge Raul Ovalle Zuleta on 5/5/15. // Copyright (c) 2015 Jorge R Ovalle Z. All rights reserved. // import UIKit class CircleVizz: UIView { var btn1:UIButton! var btn2:UIButton! var btn3:UIButton! var btn4:UIButton! var tapGesture:UITapGestureRecognizer! var multi:CGFloat! override func awakeFromNib() { //self.backgroundColor = UIColor.grayColor() btn1 = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) btn1.layer.cornerRadius = btn1.frame.width/2 btn1.backgroundColor = UIColor.orangeColor() btn1.addTarget(self, action: Selector("animate:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(btn1) btn2 = UIButton(frame: CGRect(x: 50, y: 120, width: 16, height: 16)) btn2.layer.cornerRadius = btn2.frame.width/2 btn2.backgroundColor = UIColor.greenColor() btn2.addTarget(self, action: Selector("animate:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(btn2) btn3 = UIButton(frame: CGRect(x: 150, y: 300, width: 70, height: 70)) btn3.layer.cornerRadius = btn3.frame.width/2 btn3.backgroundColor = UIColor.blueColor() btn3.addTarget(self, action: Selector("animate:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(btn3) btn4 = UIButton(frame: CGRect(x: 100, y: 300, width: 32, height: 32)) btn4.layer.cornerRadius = btn4.frame.width/2 btn4.backgroundColor = UIColor.redColor() btn4.center = btn3.center btn4.addTarget(self, action: Selector("animate:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(btn4) tapGesture = UITapGestureRecognizer(target: self, action: Selector("animate2:")) addGestureRecognizer(tapGesture) } func animate(sender:UIView){ var centerBtn1 = sender.center var sizeBtn1 = sender.frame var centerTotal = self.center var sizeTotal = frame.size multi = frame.width/sender.frame.width /*var pop = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY) print(frame.width/btn1.frame.width) pop.toValue = NSValue(CGSize: CGSizeMake(multi,multi)) layer.pop_addAnimation(pop, forKey: "abc") println((multi)*btn1.frame.width)*/ var pop = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) print(frame.width/btn1.frame.width) pop.toValue = NSValue(CGSize: CGSizeMake(multi,multi)) pop_addAnimation(pop, forKey: "abc") var pop2 = POPSpringAnimation(propertyNamed: kPOPViewCenter) pop2.toValue = NSValue(CGPoint: CGPointMake(((((center.x - sender.center.x)*multi)+160)), (((center.y - sender.center.y)*multi)+160))) pop_addAnimation(pop2, forKey: "abc2") } func animate2(sender:UIView){ var pop = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) print(frame.width/btn1.frame.width) pop.toValue = NSValue(CGSize: CGSizeMake(1,1)) pop_addAnimation(pop, forKey: "abc") var pop2 = POPSpringAnimation(propertyNamed: kPOPViewCenter) pop2.toValue = NSValue(CGPoint: CGPointMake(160,284)) pop_addAnimation(pop2, forKey: "abc2") } }
mit
6bc84b93f0cfc4f860f9b9ffcb3a8cb8
36.846154
142
0.646632
4.154403
false
false
false
false
ketoo/actor-platform
actor-apps/app-ios/Actor/Resources/AppTheme.swift
13
13786
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation var MainAppTheme = AppTheme() class AppTheme { var navigation: AppNavigationBar { get { return AppNavigationBar() } } var tab: AppTabBar { get { return AppTabBar() } } var search: AppSearchBar { get { return AppSearchBar() } } var list: AppList { get { return AppList() } } var bubbles: ChatBubbles { get { return ChatBubbles() } } var text: AppText { get { return AppText() } } var chat: AppChat { get { return AppChat() } } var common: AppCommon { get { return AppCommon() } } func applyAppearance(application: UIApplication) { navigation.applyAppearance(application) tab.applyAppearance(application) search.applyAppearance(application) list.applyAppearance(application) } } class AppText { var textPrimary: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } } class AppChat { var chatField: UIColor { get { return UIColor.whiteColor() } } var attachColor: UIColor { get { return UIColor.RGB(0x5085CB) } } var sendEnabled: UIColor { get { return UIColor.RGB(0x50A1D6) } } var sendDisabled: UIColor { get { return UIColor.alphaBlack(0.56) } } var profileBgTint: UIColor { get { return UIColor.RGB(0x5085CB) } } } class AppCommon { var isDarkKeyboard: Bool { get { return false } } var tokenFieldText: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldTextSelected: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldBg: UIColor { get { return UIColor.RGB(0x5085CB) } } } class ChatBubbles { // Basic colors var text : UIColor { get { return UIColor.RGB(0x141617) } } var textUnsupported : UIColor { get { return UIColor.RGB(0x50b1ae) } } var bgOut: UIColor { get { return UIColor.RGB(0xD2FEFD) } } var bgOutBorder: UIColor { get { return UIColor.RGB(0x99E4E3) } } var bgIn : UIColor { get { return UIColor.whiteColor() } } var bgInBorder:UIColor { get { return UIColor.RGB(0xCCCCCC) } } var statusActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDanger : UIColor { get { return UIColor.redColor() } } var statusMediaActive : UIColor { get { return UIColor.RGB(0x1ed2f9) } } var statusMediaPassive : UIColor { get { return UIColor.whiteColor() } } // TODO: Fix var statusMediaDanger : UIColor { get { return UIColor.redColor() } } var statusDialogActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusDialogPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDialogDanger : UIColor { get { return UIColor.redColor() } } // Dialog-based colors var statusDialogSending : UIColor { get { return statusDialogPassive } } var statusDialogSent : UIColor { get { return statusDialogPassive } } var statusDialogReceived : UIColor { get { return statusDialogPassive } } var statusDialogRead : UIColor { get { return statusDialogActive } } var statusDialogError : UIColor { get { return statusDialogDanger } } // Text-based bubble colors var statusSending : UIColor { get { return statusPassive } } var statusSent : UIColor { get { return statusPassive } } var statusReceived : UIColor { get { return statusPassive } } var statusRead : UIColor { get { return statusActive } } var statusError : UIColor { get { return statusDanger } } var textBgOut: UIColor { get { return bgOut } } var textBgOutBorder : UIColor { get { return bgOutBorder } } var textBgIn : UIColor { get { return bgIn } } var textBgInBorder : UIColor { get { return bgInBorder } } var textDateOut : UIColor { get { return UIColor.alphaBlack(0.27) } } var textDateIn : UIColor { get { return UIColor.RGB(0x979797) } } var textOut : UIColor { get { return text } } var textIn : UIColor { get { return text } } var textUnsupportedOut : UIColor { get { return textUnsupported } } var textUnsupportedIn : UIColor { get { return textUnsupported } } // Media-based bubble colors var statusMediaSending : UIColor { get { return statusMediaPassive } } var statusMediaSent : UIColor { get { return statusMediaPassive } } var statusMediaReceived : UIColor { get { return statusMediaPassive } } var statusMediaRead : UIColor { get { return statusMediaActive } } var statusMediaError : UIColor { get { return statusMediaDanger } } var mediaBgOut: UIColor { get { return UIColor.whiteColor() } } var mediaBgOutBorder: UIColor { get { return UIColor.RGB(0xCCCCCC) } } var mediaBgIn: UIColor { get { return mediaBgOut } } var mediaBgInBorder: UIColor { get { return mediaBgOutBorder } } var mediaDateBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.54) } } var mediaDate: UIColor { get { return UIColor.whiteColor() } } // Service-based bubble colors var serviceBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.56) } } var chatBgTint: UIColor { get { return UIColor.RGB(0xe7e0c4) } } } class AppList { var actionColor : UIColor { get { return UIColor.RGB(0x5085CB) } } var bgColor: UIColor { get { return UIColor.whiteColor() } } var bgSelectedColor : UIColor { get { return UIColor.RGB(0xd9d9d9) } } var backyardColor : UIColor { get { return UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) } } var separatorColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x1e/255.0) } } var textColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var hintColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } var sectionColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } // var arrowColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogText: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var dialogDate: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var unreadText: UIColor { get { return UIColor.whiteColor() } } var unreadBg: UIColor { get { return UIColor.RGB(0x50A1D6) } } var contactsTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var contactsShortTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } func applyAppearance(application: UIApplication) { UITableViewHeaderFooterView.appearance().tintColor = sectionColor } } class AppSearchBar { var statusBarLightContent : Bool { get { return false } } var backgroundColor : UIColor { get { return UIColor.RGB(0xf1f1f1) } } var cancelColor : UIColor { get { return UIColor.RGB(0x8E8E93) } } var fieldBackgroundColor: UIColor { get { return UIColor.whiteColor() } } var fieldTextColor: UIColor { get { return UIColor.blackColor().alpha(0.56) } } func applyAppearance(application: UIApplication) { // SearchBar Text Color var textField = UITextField.my_appearanceWhenContainedIn(UISearchBar.self) // textField.tintColor = UIColor.redColor() var font = UIFont(name: "HelveticaNeue", size: 14.0) textField.defaultTextAttributes = [NSFontAttributeName: font!, NSForegroundColorAttributeName : fieldTextColor] } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func styleSearchBar(searchBar: UISearchBar) { // SearchBar Minimal Style searchBar.searchBarStyle = UISearchBarStyle.Default // SearchBar Transculent searchBar.translucent = false // SearchBar placeholder animation fix searchBar.placeholder = ""; // SearchBar background color searchBar.barTintColor = backgroundColor.forTransparentBar() searchBar.setBackgroundImage(Imaging.imageWithColor(backgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) searchBar.backgroundColor = backgroundColor // SearchBar field color var fieldBg = Imaging.imageWithColor(fieldBackgroundColor, size: CGSize(width: 14,height: 28)) .roundCorners(14, h: 28, roundSize: 4) searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal) // SearchBar cancel color searchBar.tintColor = cancelColor } } class AppTabBar { private let mainColor = UIColor.RGB(0x5085CB) var backgroundColor : UIColor { get { return UIColor.whiteColor() } } var showText : Bool { get { return true } } var selectedIconColor: UIColor { get { return mainColor } } var selectedTextColor : UIColor { get { return mainColor } } var unselectedIconColor:UIColor { get { return mainColor.alpha(0.56) } } var unselectedTextColor : UIColor { get { return mainColor.alpha(0.56) } } var barShadow : String? { get { return "CardTop2" } } func createSelectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(selectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func createUnselectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(unselectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func applyAppearance(application: UIApplication) { var tabBar = UITabBar.appearance() // TabBar Background color tabBar.barTintColor = backgroundColor; // TabBar Shadow if (barShadow != nil) { tabBar.shadowImage = UIImage(named: barShadow!); } else { tabBar.shadowImage = nil } var tabBarItem = UITabBarItem.appearance() // TabBar Unselected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: unselectedTextColor], forState: UIControlState.Normal) // TabBar Selected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor], forState: UIControlState.Selected) } } class AppNavigationBar { var statusBarLightContent : Bool { get { return true } } var barColor:UIColor { get { return /*UIColor.RGB(0x5085CB)*/ UIColor.RGB(0x3576cc) } } var barSolidColor:UIColor { get { return UIColor.RGB(0x5085CB) } } var titleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleActiveColor: UIColor { get { return UIColor.whiteColor() } } var shadowImage : String? { get { return nil } } func applyAppearance(application: UIApplication) { // StatusBar style if (statusBarLightContent) { application.statusBarStyle = UIStatusBarStyle.LightContent } else { application.statusBarStyle = UIStatusBarStyle.Default } var navAppearance = UINavigationBar.appearance(); // NavigationBar Icon navAppearance.tintColor = titleColor; // NavigationBar Text navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: titleColor]; // NavigationBar Background navAppearance.barTintColor = barColor; // navAppearance.setBackgroundImage(Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 1)), forBarMetrics: UIBarMetrics.Default) // navAppearance.shadowImage = Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 2)) // Small hack for correct background color UISearchBar.appearance().backgroundColor = barColor // NavigationBar Shadow // navAppearance.shadowImage = nil // if (shadowImage == nil) { // navAppearance.shadowImage = UIImage() // navAppearance.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) // } else { // navAppearance.shadowImage = UIImage(named: shadowImage!) // } } func applyAuthStatusBar() { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func applyStatusBarFast() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false) } } }
mit
eca8348b49896abf0d0d53c3220ad9c7
41.81677
181
0.662121
4.475974
false
false
false
false
gottesmm/swift
test/Serialization/class.swift
7
2162
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -emit-object -emit-module -o %t %S/Inputs/def_class.swift -disable-objc-attr-requires-foundation-module // RUN: llvm-bcanalyzer %t/def_class.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Defs To Decls" -sil-debug-serialization -I %t %s | %FileCheck %s -check-prefix=SIL // RUN: echo "import def_class; struct A : ClassProto {}" | not %target-swift-frontend -typecheck -I %t - 2>&1 | %FileCheck %s -check-prefix=CHECK-STRUCT // CHECK-NOT: UnknownCode // CHECK-STRUCT: non-class type 'A' cannot conform to class protocol 'ClassProto' // Make sure we can "merge" def_class. // RUN: %target-swift-frontend -emit-module -o %t-merged.swiftmodule %t/def_class.swiftmodule -module-name def_class import def_class var a : Empty var b = TwoInts(a: 1, b: 2) var computedProperty : ComputedProperty var sum = b.x + b.y + computedProperty.value var intWrapper = ResettableIntWrapper() var r : Resettable = intWrapper r.reset() r.doReset() class AnotherIntWrapper : SpecialResettable, ClassProto { init() { value = 0 } var value : Int func reset() { value = 0 } func compute() { value = 42 } } var intWrapper2 = AnotherIntWrapper() r = intWrapper2 r.reset() var c : Cacheable = intWrapper2 c.compute() c.reset() var p = Pair(a: 1, b: 2.5) p.first = 2 p.second = 5.0 struct Int {} var gc = GenericCtor<Int>() gc.doSomething() a = StillEmpty() r = StillEmpty() var bp = BoolPair<Bool>() bp.bothTrue() var rawBP : Pair<Bool, Bool> rawBP = bp var rev : SpecialPair<Double> rev.first = 42 var comp : Computable = rev var simpleSub = ReadonlySimpleSubscript() var subVal = simpleSub[4] var complexSub = ComplexSubscript() complexSub[4, false] = complexSub[3, true] var rsrc = Resource() getReqPairLike() // SIL-LABEL: sil public_external [transparent] [fragile] @_TFsoi1pFTSiSi_Si : $@convention(thin) (Int, Int) -> Int { func test(_ sharer: ResourceSharer) {} class HasNoOptionalReqs : ObjCProtoWithOptional { } HasNoOptionalReqs() OptionalImplementer().unrelated() extension def_class.ComputedProperty { }
apache-2.0
00edc97e53c346ad2411e91dfff7c9dc
23.292135
158
0.703515
3.147016
false
false
false
false
JohnEstropia/CoreStore
Sources/Relationship.ToManyUnordered.swift
1
24465
// // Relationship.ToManyUnordered.swift // CoreStore // // Copyright © 2020 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - RelationshipContainer extension RelationshipContainer { // MARK: - ToManyUnordered /** The containing type for to-many unordered relationships. Any `CoreStoreObject` subclass can be a destination type. Inverse relationships should be declared from the destination type as well, using the `inverse:` argument for the relationship. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyUnordered<Dog>("pets", inverse: { $0.master }) } ``` - Important: `Relationship.ToManyUnordered` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class ToManyUnordered<D: CoreStoreObject>: ToManyRelationshipKeyPathStringConvertible, RelationshipProtocol { /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { nil }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToOne<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyOrdered<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** Initializes the metadata for the relationship. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. Make sure to declare this relationship's inverse relationship on its destination object. Due to Swift's compiler limitation, only one of the relationship and its inverse can declare an `inverse:` argument. ``` class Dog: CoreStoreObject { let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let pets = Relationship.ToManyOrdered<Dog>("pets", inverse: { $0.master }) } ``` - parameter keyPath: the permanent name for this relationship. - parameter minCount: the minimum number of objects in this relationship UNLESS THE RELATIONSHIP IS EMPTY. This means there might be zero objects in the relationship, which might be less than `minCount`. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter maxCount: the maximum number of objects in this relationship. If the number of objects in the relationship do not satisfy `minCount` and `maxCount`, the transaction's commit (or auto-commit) would fail with a validation error. - parameter inverse: the inverse relationship that is declared for the destination object. All relationships require an "inverse", so updates to to this object's relationship are also reflected on its destination object. - parameter deleteRule: defines what happens to relationship when an object is deleted. Valid values are `.nullify`, `.cascade`, and `.delete`. Defaults to `.nullify`. - parameter versionHashModifier: used to mark or denote a relationship as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public convenience init( _ keyPath: KeyPathString, inverse: @escaping (D) -> RelationshipContainer<D>.ToManyUnordered<O>, deleteRule: DeleteRule = .nullify, minCount: Int = 0, maxCount: Int = 0, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.init( keyPath: keyPath, inverseKeyPath: { inverse(D.meta).keyPath }, deleteRule: deleteRule, minCount: minCount, maxCount: maxCount, versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths() ) } /** The relationship value */ public var value: ReturnValueType { get { return Set(self.nativeValue.map({ D.cs_fromRaw(object: $0 as! NSManagedObject) })) } set { self.nativeValue = NSSet(array: newValue.map({ $0.rawObject! })) } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = D // MARK: RelationshipKeyPathStringConvertible public typealias ReturnValueType = Set<DestinationValueType> // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: RelationshipProtocol internal let entityDescriptionValues: () -> RelationshipProtocol.EntityDescriptionValues internal var rawObject: CoreStoreManagedObject? internal var nativeValue: NSSet { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return object.getValue( forKvcKey: self.keyPath, didGetValue: { ($0 as! NSSet?) ?? [] } ) } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) object.setValue( newValue, forKvcKey: self.keyPath ) } } } internal var valueForSnapshot: Any? { return Set(self.value.map({ $0.objectID() })) } // MARK: Private private init(keyPath: KeyPathString, inverseKeyPath: @escaping () -> KeyPathString?, deleteRule: DeleteRule, minCount: Int, maxCount: Int, versionHashModifier: @autoclosure @escaping () -> String?, renamingIdentifier: @autoclosure @escaping () -> String?, affectedByKeyPaths: @autoclosure @escaping () -> Set<String>) { self.keyPath = keyPath self.entityDescriptionValues = { let range = (Swift.max(0, minCount) ... maxCount) return ( isToMany: true, isOrdered: false, deleteRule: deleteRule.nativeValue, inverse: (type: D.self, keyPath: inverseKeyPath()), versionHashModifier: versionHashModifier(), renamingIdentifier: renamingIdentifier(), affectedByKeyPaths: affectedByKeyPaths(), minCount: range.lowerBound, maxCount: range.upperBound ) } } } } // MARK: - Convenience extension RelationshipContainer.ToManyUnordered: Sequence { /** The number of elements in the set. */ public var count: Int { return self.nativeValue.count } /** A Boolean value indicating whether the range contains no elements. */ public var isEmpty: Bool { return self.nativeValue.count == 0 } // MARK: Sequence public typealias Iterator = AnyIterator<D> public func makeIterator() -> Iterator { var iterator = self.nativeValue.makeIterator() return AnyIterator({ iterator.next().flatMap({ D.cs_fromRaw(object: $0 as! NSManagedObject) }) }) } } // MARK: - Operations infix operator .= : AssignmentPrecedence infix operator .== : ComparisonPrecedence extension RelationshipContainer.ToManyUnordered { /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= [dog, cat] ``` is equivalent to ``` person.pets.value = [dog, cat] ``` */ public static func .= <S: Sequence>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ newValue: S) where S.Iterator.Element == D { relationship.nativeValue = NSSet(array: newValue.map({ $0.rawObject! })) } /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= anotherPerson.pets ``` is equivalent to ``` person.pets.value = anotherPerson.pets.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyUnordered<D>) { relationship.nativeValue = relationship2.nativeValue } /** Assigns a sequence of objects to the relationship. The operation ``` person.pets .= anotherPerson.pets ``` is equivalent to ``` person.pets.value = anotherPerson.pets.value ``` */ public static func .= <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyOrdered<D>) { relationship.nativeValue = NSSet(set: relationship2.nativeValue.set) } /** Compares the if the relationship's objects and a set of objects have the same elements. ``` if person.pets .== Set<Animal>([dog, cat]) { ... } ``` is equivalent to ``` if person.pets.value == Set<Animal>([dog, cat]) { ... } ``` */ public static func .== (_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ set: Set<D>) -> Bool { return relationship.nativeValue.isEqual(to: Set(set.map({ $0.rawObject! }))) } /** Compares if a set of objects and a relationship's objects have the same elements. ``` if Set<Animal>([dog, cat]) .== person.pets { ... } ``` is equivalent to ``` if Set<Animal>([dog, cat]) == person.pets.value { ... } ``` */ public static func .== (_ set: Set<D>, _ relationship: RelationshipContainer<O>.ToManyUnordered<D>) -> Bool { return relationship.nativeValue.isEqual(to: Set(set.map({ $0.rawObject! }))) } /** Compares if a relationship's objects and another relationship's objects have the same elements. ``` if person.pets .== anotherPerson.pets { ... } ``` is equivalent to ``` if person.pets.value == anotherPerson.pets.value { ... } ``` */ public static func .== <O2>(_ relationship: RelationshipContainer<O>.ToManyUnordered<D>, _ relationship2: RelationshipContainer<O2>.ToManyUnordered<D>) -> Bool { return relationship.nativeValue.isEqual(relationship2.nativeValue) } }
mit
4418ef69551e2f137b9758ef86f1c63e
52.067245
413
0.659295
5.191851
false
false
false
false
bgerstle/wikipedia-ios
Wikipedia/Code/WelcomeAnimationExtensions.swift
2
2827
import Foundation extension CGFloat { func wmf_denormalizeUsingReference (reference: CGFloat) -> CGFloat { return self * reference } func wmf_radiansFromDegrees() -> CGFloat{ return ((self) / 180.0 * CGFloat(M_PI)) } } extension CGPoint { func wmf_denormalizeUsingSize (size: CGSize) -> CGPoint { return CGPointMake( self.x.wmf_denormalizeUsingReference(size.width), self.y.wmf_denormalizeUsingReference(size.height) ) } } extension CGSize { func wmf_denormalizeUsingSize (size: CGSize) -> CGSize { return CGSizeMake( self.width.wmf_denormalizeUsingReference(size.width), self.height.wmf_denormalizeUsingReference(size.height) ) } } extension CGRect { func wmf_denormalizeUsingSize (size: CGSize) -> CGRect { let point = self.origin.wmf_denormalizeUsingSize(size) let size = self.size.wmf_denormalizeUsingSize(size) return CGRectMake( point.x, point.y, size.width, size.height ) } } extension CALayer { public func wmf_animateToOpacity(opacity: Double, transform: CATransform3D, delay: Double, duration: Double){ self.addAnimation(CABasicAnimation.wmf_animationToTransform(transform, delay: delay, duration: duration), forKey: nil) self.addAnimation(CABasicAnimation.wmf_animationToOpacity(opacity, delay: delay, duration: duration), forKey: nil) } } extension CABasicAnimation { class func wmf_animationToTransform(transform: CATransform3D, delay: Double, duration: Double) -> CABasicAnimation { let anim = CABasicAnimation(keyPath: "transform") anim.duration = duration anim.beginTime = CACurrentMediaTime() + delay anim.fillMode = kCAFillModeForwards anim.removedOnCompletion = false anim.toValue = NSValue(CATransform3D: transform) anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return anim; } class func wmf_animationToOpacity(opacity: Double, delay: Double, duration: Double) -> CABasicAnimation { let anim = CABasicAnimation(keyPath: "opacity") anim.duration = duration anim.beginTime = CACurrentMediaTime() + delay anim.fillMode = kCAFillModeForwards anim.removedOnCompletion = false anim.toValue = opacity anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return anim; } } extension CATransform3D { static func wmf_rotationTransformWithDegrees(degrees: CGFloat) -> CATransform3D { return CATransform3DMakeRotation( CGFloat(degrees).wmf_radiansFromDegrees(), 0.0, 0.0, 1.0 ) } }
mit
b772c37658c1ff182ad4a0c2b4d55271
33.47561
126
0.6682
4.634426
false
false
false
false
fancymax/12306ForMac
12306ForMac/Service/Dama.swift
1
5224
// // Dama.swift // 12306ForMac // // Created by fancymax on 16/8/10. // Copyright © 2016年 fancy. All rights reserved. // import Foundation import Alamofire import SwiftyJSON fileprivate func md5(_ string: String) -> String { let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1) var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH)) CC_MD5_Init(context) CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8))) CC_MD5_Final(&digest, context) context.deallocate(capacity: 1) var hexString = "" for byte in digest { hexString += String(format:"%02x", byte) } return hexString } extension Data { func hexedString() -> String { return reduce("") {$0 + String(format: "%02x", $1)} } func MD5() -> Data { var result = Data(count: Int(CC_MD5_DIGEST_LENGTH)) _ = result.withUnsafeMutableBytes {resultPtr in self.withUnsafeBytes {(bytes: UnsafePointer<UInt8>) in CC_MD5(bytes, CC_LONG(count), resultPtr) } } return result } } class Dama: NSObject { static let sharedInstance = Dama() let AppId:String = "43327" let AppKey:String = "36f3ff0b2f66f2b3f1cd9b5953095858" private override init() { super.init() } private func getCurrentFileHex(ofImage image:NSImage)->String { let originData = image.tiffRepresentation let imageRep = NSBitmapImageRep(data: originData!) let imageData = imageRep!.representation(using: .PNG, properties: ["NSImageCompressionFactor":1.0])! let result = imageData.hexedString() return result } private func getpwd(_ user:String,password:String) -> String{ let nameMD5 = md5(user) let passwordMD5 = md5(password) let x1MD5 = md5(nameMD5 + passwordMD5) let x2MD5 = md5(AppKey + x1MD5) return x2MD5 } private func getsign(ofUser user:String) ->String { let key = AppKey + user let x1MD5 = md5(key) let x2 = x1MD5[x1MD5.startIndex...x1MD5.index(x1MD5.startIndex, offsetBy: 7)] return x2 } private func getFileDataSign2(ofImage image:NSImage,user:String)->String{ let originData = image.tiffRepresentation let imageRep = NSBitmapImageRep(data: originData!) let imageData = imageRep!.representation(using: .PNG, properties: ["NSImageCompressionFactor":1.0])! let AppKeyData = AppKey.data(using: String.Encoding.utf8) let AppUserData = user.data(using: String.Encoding.utf8) var finalData = Data() finalData.append(AppKeyData!) finalData.append(AppUserData!) finalData.append(imageData) let x1MD5 = finalData.MD5().hexedString() let startIndex = x1MD5.startIndex return x1MD5[startIndex...x1MD5.index(startIndex, offsetBy: 7)] } func getBalance(_ user:String,password:String,success:@escaping (String)->Void,failure:@escaping (NSError)->Void){ let url = "http://api.dama2.com:7766/app/d2Balance" let pwd = getpwd(user,password: password) let sign = getsign(ofUser: user) let urlX = "\(url)?appID=\(AppId)&user=\(user)&pwd=\(pwd)&sign=\(sign)" Alamofire.request(urlX).responseJSON { response in switch(response.result){ case .failure(let error): failure(error as NSError) case .success(let data): if let balanceVal = JSON(data)["balance"].string { success(balanceVal) } else { if let errorCode = JSON(data)["ret"].int { failure(DamaError.errorWithCode(errorCode)) } } } } } func dama(_ user:String,password:String,ofImage image:NSImage,success:@escaping (String)->Void,failure:@escaping (NSError)->Void){ let pwd = getpwd(user,password: password) let sign = getFileDataSign2(ofImage: image,user: user) let type = "287" let fileData = getCurrentFileHex(ofImage: image) let url = "http://api.dama2.com:7766/app/d2File" let params = ["appID":AppId, "user":user, "pwd":pwd, "type":type, "fileData":fileData, "sign":sign] Alamofire.request(url, method:.post, parameters: params).responseJSON { response in switch(response.result) { case .failure(let error): failure(error as NSError) case .success(let data): if let imageCode = JSON(data)["result"].string { success(imageCode) } else { if let errorCode = JSON(data)["ret"].int { failure(DamaError.errorWithCode(errorCode)) } } } } } }
mit
610b008937b17321e7cf1b9e9b8eaa94
33.348684
134
0.566367
4.127273
false
false
false
false
ProudOfZiggy/SIFloatingCollection_Swift
Example/Example/ViewController.swift
1
1561
// // ViewController.swift // Example // // Created by Neverland on 15.08.15. // Copyright (c) 2015 ProudOfZiggy. All rights reserved. // import UIKit import SpriteKit class ViewController: UIViewController { fileprivate var skView: SKView! fileprivate var floatingCollectionScene: BubblesScene! override func viewDidLoad() { super.viewDidLoad() skView = SKView(frame: UIScreen.main.bounds) skView.backgroundColor = SKColor.white view.addSubview(skView) floatingCollectionScene = BubblesScene(size: skView.bounds.size) let navBarHeight = navigationController!.navigationBar.frame.height let statusBarHeight = UIApplication.shared.statusBarFrame.height floatingCollectionScene.topOffset = navBarHeight + statusBarHeight skView.presentScene(floatingCollectionScene) navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(commitSelection) ) navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(addBubble) ) for _ in 0..<20 { addBubble() } } func addBubble() { let newNode = BubbleNode.instantiate() floatingCollectionScene.addChild(newNode) } func commitSelection() { floatingCollectionScene.performCommitSelectionAnimation() } }
mit
df7176eaa13f87613fd78415502de30d
27.907407
75
0.647662
5.255892
false
false
false
false
PlutoMa/SwiftProjects
009.Swipeable Cell/SwipeableCell/SwipeableCell/ViewController.swift
1
4460
// // ViewController.swift // SwipeableCell // // Created by Dareway on 2017/10/18. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit class ViewController: UIViewController { private let cellHeight: CGFloat = 60.0 private let colorRatio: CGFloat = 10.0 private let tableView = UITableView(frame: CGRect.zero, style: .plain) private let lyric = "when i was young i'd listen to the radio,waiting for my favorite songs,when they played i'd sing along,it make me smile,those were such happy times and not so long ago,how i wondered where they'd gone,but they're back again just like a long lost friend,all the songs i love so well,every shalala every wo'wo,still shines,every shing-a-ling-a-ling" private var dataSource: Array<String>! private let actionController = UIAlertController(title: "", message: "", preferredStyle: .alert) override func viewDidLoad() { super.viewDidLoad() dataSource = lyric.split(separator: ",").map(String.init) tableView.frame = view.bounds view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() let cells = tableView.visibleCells let tableHeight = tableView.frame.height for (index, cell) in cells.enumerated() { cell.frame.origin.y = tableHeight UIView.animate(withDuration: 1.0, delay: 0.04 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.frame.origin.y = 0 }, completion: nil) } } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } if cell!.contentView.layer.sublayers != nil { for layer in cell!.contentView.layer.sublayers! { layer.removeFromSuperlayer() } } let layer = CAGradientLayer() layer.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: cellHeight) let topColor = UIColor(red: CGFloat(indexPath.row * 2) * colorRatio / 255.0, green: 1.0, blue: CGFloat(indexPath.row * 2) * colorRatio / 255.0, alpha: 1.0) let bottomColor = UIColor(red: CGFloat(indexPath.row * 2 + 1) * colorRatio / 255.0, green: 1.0, blue: CGFloat(indexPath.row * 2 + 1) * colorRatio / 255.0, alpha: 1.0) layer.colors = [topColor.cgColor, bottomColor.cgColor] cell?.contentView.layer.addSublayer(layer) cell?.textLabel?.text = dataSource[indexPath.row] return cell! } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let likeAction = UITableViewRowAction(style: .normal, title: "👍") { (action, index) in self.actionController.message = "Like" self.showAlertController() } likeAction.backgroundColor = UIColor.white let dislikeAction = UITableViewRowAction(style: .normal, title: "👎") { (action, index) in self.actionController.message = "Dislike" self.showAlertController() } dislikeAction.backgroundColor = UIColor.white return [likeAction, dislikeAction] } func showAlertController() -> Void { self.present(actionController, animated: true) { let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { (timer) in self.actionController.dismiss(animated: true, completion: nil) }) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) } } }
mit
5830d2f3795a3eb4cad1dd622200caed
40.212963
372
0.643451
4.59814
false
false
false
false
WebberLai/WLComics
WLComics/View Controllers/Left View Controllers/FavoriteTableViewController.swift
1
13151
// // FavoriteTableViewController.swift // WLComics // // Created by Webber Lai on 2017/8/31. // Copyright © 2017年 webberlai. All rights reserved. // import UIKit import Kingfisher import SwiftyDropbox class FavoriteTableViewController: UITableViewController { var myFavoriteList : Array? = FavoriteComics.listAllFavorite() var currentIndex : Int = 0 var currentSection : Int = 0 var comicSectionTitles = [String]() var comicLibrary : Dictionary = [String: [NSMutableDictionary]]() var sortedComicLib = NSMutableDictionary() let client = DropboxClientsManager.authorizedClient override func viewDidLoad() { super.viewDidLoad() self.title = "收藏列表" tableView.register(UINib(nibName: "ComicTableViewCell", bundle: nil), forCellReuseIdentifier: "ComicTableViewCell") navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .bookmarks , target: self, action: #selector(loginDropbox)) } @objc func loginDropbox(){ DropboxClientsManager.authorizeFromController(UIApplication.shared, controller: self, openURL: { (url: URL) -> Void in UIApplication.shared.openURL(url) }) } func reloadFavoriteComics () { myFavoriteList = FavoriteComics.listAllFavorite() self.sortComicList() tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.reloadFavoriteComics() //Sync Favorite List if let client = DropboxClientsManager.authorizedClient { client.files.listFolder(path: "").response { response, error in if let result = response { print("Folder contents: \(result)") if result.entries.count == 0 { //上傳本地的 print("上傳本地的") self.uploadDropboxPlsit() }else{ //同步雲端的下來 print("同步雲端的下來") self.downloadDropboxPlist() } } else { print("Error: \(error!)") } } } } func uploadDropboxPlsit() { if let client = DropboxClientsManager.authorizedClient { client.files.listFolder(path: "").response { response, error in if let _ = response { let fileData = FavoriteComics.getFavoritePlistData()! //let fileData = "testing data example".data(using: String.Encoding.utf8, allowLossyConversion: false)! let _ = client.files.upload(path: "/MyFavoritesComics.plist", mode: .overwrite , input: fileData).response { response, error in if let response = response { print("Dropbox 上傳完成 \(response)") } else if let error = error { print("Dropbox 上傳失敗 \(error)") } } .progress { progressData in print(progressData) } } else { print("Dropbox 上傳失敗 Error: \(error!)") } } } } func downloadDropboxPlist (){ if let client = DropboxClientsManager.authorizedClient { client.files.listFolder(path:"").response { response, error in if let _ = response { let fileManager = FileManager.default let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] let destURL = directoryURL.appendingPathComponent("MyFavoritesComics.plist") let destination: (URL, HTTPURLResponse) -> URL = { temporaryURL, response in return destURL } client.files.download(path: "/MyFavoritesComics.plist", overwrite: true, destination: destination) .response { response, error in if let response = response { print("Dropbox 下載完成 \(response)") self.reloadFavoriteComics() } else if let error = error { print("Dropbox 下載失敗 \(error)") } } .progress { progressData in print(progressData) } } else { print("Dropbox 下載失敗 Error: \(error!)") } } } } func sortComicList(){ comicLibrary.removeAll() sortedComicLib.removeAllObjects() for comic : NSMutableDictionary in myFavoriteList! { let s : String = self.translateChineseStringToPyinyin(chineseStr:comic.object(forKey:"name") as! String) let comicKey = String(s.prefix(1)) if var comicValues = self.comicLibrary[comicKey] { comicValues.append(comic) comicLibrary[comicKey] = comicValues } else { comicLibrary[comicKey] = [comic] } } comicSectionTitles = [String](comicLibrary.keys) comicSectionTitles = comicSectionTitles.sorted(by: { $0 < $1 }) let sortedByKeyLibrary = comicLibrary.sorted { firstDictionary, secondDictionary in return firstDictionary.0 < secondDictionary.0 } for (index, title) in comicSectionTitles.enumerated(){ let comics = sortedByKeyLibrary[index].value let comicDict : NSDictionary = NSDictionary.init(object: comics, forKey: title as NSCopying) sortedComicLib.addEntries(from: (comicDict as NSCopying) as! [AnyHashable : Any]) } } func translateChineseStringToPyinyin(chineseStr:String) -> String { var translatedPinyinStr:String = "" let zhcnStrToTranslate:CFMutableString = NSMutableString(string: chineseStr) var translatedOk:Bool = CFStringTransform(zhcnStrToTranslate, nil, kCFStringTransformMandarinLatin, false) if translatedOk { let translatedPinyinWithAccents = zhcnStrToTranslate translatedOk = CFStringTransform(translatedPinyinWithAccents, nil, kCFStringTransformStripCombiningMarks, false) if translatedOk { translatedPinyinStr = translatedPinyinWithAccents as String } } return translatedPinyinStr.uppercased() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return comicSectionTitles.count } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { var tpIndex:Int = 0 for character in comicSectionTitles{ if character == title{ return tpIndex } tpIndex += 1 } return 0 } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return comicSectionTitles } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return comicSectionTitles[section] } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let comics : [NSMutableDictionary] = self.sortedComicLib.object(forKey:comicSectionTitles[section]) as! [NSMutableDictionary] return comics.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return 116 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ComicTableViewCell") as! ComicTableViewCell cell.favoriteBtn.isHidden = true let comics : [NSMutableDictionary] = self.sortedComicLib.object(forKey:comicSectionTitles[indexPath.section]) as! [NSMutableDictionary] let comicDict : NSMutableDictionary = comics[indexPath.row] let url = URL(string: comicDict.object(forKey: "icon_url") as! String)! cell.coverImageView!.kf.setImage(with: url, placeholder: Image.init(named:"comic_place_holder"), options: [.transition(ImageTransition.fade(1))], progressBlock: { receivedSize, totalSize in }, completionHandler: { image, error, cacheType, imageURL in }) cell.comicNametextLabel.text = comicDict.object(forKey: "name") as? String return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { currentIndex = indexPath.row currentSection = indexPath.section self.performSegue(withIdentifier: "showEpisodes", sender: self) } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { var comics : [NSMutableDictionary] = sortedComicLib.object(forKey:comicSectionTitles[indexPath.section]) as! [NSMutableDictionary] let comicDict : NSMutableDictionary = comics[indexPath.row] let deleteComic = WLComics.sharedInstance().getR8Comic().generatorFakeComic(comicDict.object(forKey: "comic_id") as! String , name: comicDict.object(forKey: "name") as! String) FavoriteComics.removeComicFromMyFavorite(deleteComic) for (index, element) in (myFavoriteList?.enumerated())!{ if element == comicDict{ myFavoriteList?.remove(at:index) break } } for (index,element) in comics.enumerated(){ if element == comicDict{ comics.remove(at:index) break } } sortedComicLib.setObject(comics, forKey: comicSectionTitles[indexPath.section] as NSCopying) tableView.deleteRows(at: [indexPath], with: .fade) self.uploadDropboxPlsit() tableView.reloadData() } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showEpisodes" { let comics : [NSMutableDictionary] = sortedComicLib.object(forKey:comicSectionTitles[currentSection]) as! [NSMutableDictionary] let comicDict : NSMutableDictionary = comics[currentIndex] let currentComic = WLComics.sharedInstance().getR8Comic().generatorFakeComic(comicDict.object(forKey: "comic_id") as! String , name: comicDict.object(forKey: "name") as! String) currentComic.setSmallIconUrl(comicDict.object(forKey: "icon_url") as! String) let comicEpisodesViewController = segue.destination as! ComicEpisodesViewController comicEpisodesViewController.currentComic = currentComic comicEpisodesViewController.title = currentComic.getName() } } }
mit
13e8fa03012dd05f78566bda2f0926e1
40.942122
147
0.577047
5.515433
false
false
false
false
dreamsxin/swift
test/SILGen/unmanaged.swift
6
2277
// RUN: %target-swift-frontend -emit-sil %s | FileCheck %s class C {} struct Holder { unowned(unsafe) var value: C } _ = Holder(value: C()) // CHECK-LABEL:sil hidden @_TFV9unmanaged6HolderC{{.*}} : $@convention(method) (@owned C, @thin Holder.Type) -> Holder // CHECK: bb0([[T0:%.*]] : $C, // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C // CHECK-NEXT: strong_release [[T0]] : $C // CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C) // CHECK-NEXT: return [[T2]] : $Holder func set(holder holder: inout Holder) { holder.value = C() } // CHECK-LABEL:sil hidden @_TF9unmanaged3setFT6holderRVS_6Holder_T_ : $@convention(thin) (@inout Holder) -> () // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK: [[T0:%.*]] = function_ref @_TFC9unmanaged1CC{{.*}} // CHECK: [[C:%.*]] = apply [[T0]]( // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[ADDR]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]] // CHECK-NEXT: store [[T1]] to [[T0]] // CHECK-NEXT: strong_release [[C]] // CHECK-NEXT: tuple () // CHECK-NEXT: return func get(holder holder: inout Holder) -> C { return holder.value } // CHECK-LABEL:sil hidden @_TF9unmanaged3getFT6holderRVS_6Holder_CS_1C : $@convention(thin) (@inout Holder) -> @owned C // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK-NEXT: debug_value_addr %0 : $*Holder, var, name "holder", argno 1 // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[ADDR]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*@sil_unmanaged C // CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]] // CHECK-NEXT: strong_retain [[T2]] // CHECK-NEXT: return [[T2]] func project(fn fn: () -> Holder) -> C { return fn().value } // CHECK-LABEL:sil hidden @_TF9unmanaged7projectFT2fnFT_VS_6Holder_CS_1C : $@convention(thin) (@owned @callee_owned () -> Holder) -> @owned C // CHECK: bb0([[FN:%.*]] : $@callee_owned () -> Holder): // CHECK: strong_retain [[FN]] // CHECK-NEXT: [[T0:%.*]] = apply [[FN]]() // CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value // CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]] // CHECK-NEXT: strong_retain [[T2]] // CHECK-NEXT: strong_release [[FN]] // CHECK-NEXT: return [[T2]]
apache-2.0
c10b28504ff3239fd4d4ea6d30c0a081
41.962264
141
0.58498
2.911765
false
false
false
false
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Module/Discovery/Controller/DiscoveryController.swift
1
3229
// // DiscoveryController.swift // SinaWeiBo // // Created by 何启亮 on 16/5/10. // Copyright © 2016年 HQL. All rights reserved. // import UIKit class DiscoveryController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
8519e05ea87f33b26dd5d8a09d88449e
32.894737
157
0.686025
5.532646
false
false
false
false
yanagiba/swift-ast
Sources/AST/Type/TypeAnnotation.swift
2
1354
/* Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Source public class TypeAnnotation : LocatableNode { public let type: Type public let attributes: Attributes public let isInOutParameter: Bool public init( type: Type, attributes: Attributes = [], isInOutParameter: Bool = false ) { self.type = type self.attributes = attributes self.isInOutParameter = isInOutParameter } // MARK: - ASTTextRepresentable override public var textDescription: String { let attr = attributes.isEmpty ? "" : "\(attributes.textDescription) " let inoutStr = isInOutParameter ? "inout " : "" return ": \(attr)\(inoutStr)\(type.textDescription)" } } extension TypeAnnotation : ASTTextRepresentable, SourceLocatable { }
apache-2.0
7147814d0c8ff5658c3d61c4db783ed9
29.772727
85
0.728951
4.701389
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/WMFImageTextActivitySource.swift
1
1114
import UIKit open class WMFImageTextActivitySource: NSObject, UIActivityItemSource { let info: MWKImageInfo public required init(info: MWKImageInfo) { self.info = info super.init() } open func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return String() } open func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? { var text: String? if activityType == UIActivityType.postToTwitter { text = WMFLocalizedString("share-on-twitter-sign-off", value:"via @Wikipedia", comment:"Text placed at the end of a tweet when sharing. Contains the wikipedia twitter handle") }else if activityType == UIActivityType.postToFacebook || activityType == UIActivityType.mail || activityType == UIActivityType.postToFlickr { text = info.filePageURL?.absoluteString }else { text = nil } return text } }
mit
1bc8d0b65ed836365903c8a0a17fa376
32.757576
187
0.66158
5.802083
false
false
false
false
AbdullahBayraktar/restaurants-app
RestaurantsApp/RestaurantsApp/Features/RetaurantsList/DataManagers/RestaurantsDataManager.swift
1
1322
// // RestaurantsDataManager.swift // RestaurantsApp // // Created by Abdullah Bayraktar on 26/09/2017. // Copyright © 2017 AB. All rights reserved. // import Foundation import SwiftyJSON typealias FetchRestaurantsCompletionHandler = (RestaurantsModel?, String) -> Void class RestaurantsDataManager: NSObject { struct JSONFile { static let name = "restaurants" static let ext = "json" } /** Fetches restaurants from local JSON file. - Parameter completionHandler: Callback after call is completed. */ class func fetchDataFromJSON( with completionHandler: FetchRestaurantsCompletionHandler) { do { if let file = Bundle.main.url(forResource: JSONFile.name, withExtension: JSONFile.ext) { let data = try Data(contentsOf: file) let json = JSON(data: data, options: JSONSerialization.ReadingOptions()) let restaurantsModel = RestaurantsModel(jsonData: json["restaurants"]) print(json) completionHandler(restaurantsModel, "") } else { completionHandler(nil, "no file") } } catch { print(error.localizedDescription) } } }
mit
b3fa9f58a77a7d9b137bd260b3e2cb40
27.717391
100
0.596518
5.160156
false
false
false
false
lammertw/BrightnessToggle
BrightnessToggle/BrightnessToggle.swift
1
995
// // BrightnessToggle.swift // NSInternational // // Created by Lammert Westerhoff on 04/02/16. // Copyright © 2016 Lammert Westerhoff. All rights reserved. // import Foundation private var brightness: CGFloat? public var setToMax: Bool { brightness != nil } public var enabled = true private func internalMaxBrightness() { UIScreen.main.brightness = 1 } public func maxBrightness() { if enabled && !setToMax { brightness = UIScreen.main.brightness internalMaxBrightness() } } private func internalRestoreBrightness() { if let brightness = brightness { UIScreen.main.brightness = brightness } } public func restoreBrightness() { if enabled { internalRestoreBrightness() brightness = nil } } public func applicationWillResignActive() { if enabled { internalRestoreBrightness() } } public func applicationWillEnterForeground() { if enabled && setToMax { internalMaxBrightness() } }
mit
eb15b5ef349f47f1c8c34f40d1b36635
18.88
61
0.682093
4.284483
false
false
false
false
PGSSoft/ParallaxView
Sources/Other/ParallaxMotionEffect.swift
1
1810
// // ParallaxMotionEffect.swift // // Created by Łukasz Śliwiński on 20/04/16. // Copyright © 2016 Łukasz Śliwiński. All rights reserved. // import UIKit /// A UIMotionEffect subclass that makes parallax motion effect by applying custom transformation. /// Allows to customize the motion effect. open class ParallaxMotionEffect: UIMotionEffect { // MARK: Properties /// How far camera is from the object open var cameraPositionZ = CGFloat(0) /// The maximum angle horizontally open var viewingAngleX = CGFloat(Double.pi/4/8) /// The maximum angle vertically open var viewingAngleY = CGFloat(Double.pi/4/8) /// Maximum deviation relative to the center open var panValue = CGFloat(8) /// Perspective value. The closer is to 0 the deepest is the perspective open var m34 = CGFloat(-1.0/700) // MARK: UIMotionEffect override open func keyPathsAndRelativeValues(forViewerOffset viewerOffset: UIOffset) -> [String : Any]? { var transform = CATransform3DIdentity transform.m34 = m34 var newViewerOffset = viewerOffset newViewerOffset.horizontal = newViewerOffset.horizontal <= -1.0 ? -1.0 : newViewerOffset.horizontal newViewerOffset.vertical = newViewerOffset.vertical <= -1.0 ? -1.0 : newViewerOffset.vertical transform = CATransform3DTranslate( transform, panValue*newViewerOffset.horizontal, panValue*newViewerOffset.vertical, cameraPositionZ ) transform = CATransform3DRotate(transform, viewingAngleX * newViewerOffset.vertical, 1, 0, 0) transform = CATransform3DRotate(transform, viewingAngleY * -newViewerOffset.horizontal, 0, 1, 0) return ["layer.transform": NSValue(caTransform3D: transform)] } }
mit
866243bfbbe4312b2c3d803725586dde
31.781818
109
0.697726
4.344578
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Renderers/PieChartRenderer.swift
2
37683
// // PieChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class PieChartRenderer: DataRenderer { @objc open weak var chart: PieChartView? @objc public init(chart: PieChartView, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } open override func drawData(context: CGContext) { guard let chart = chart else { return } let pieData = chart.data if pieData != nil { // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() for set in pieData!.dataSets as! [IPieChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } } @objc open func calculateMinimumRadiusForSpacedSlice( center: CGPoint, radius: CGFloat, angle: CGFloat, arcStartPointX: CGFloat, arcStartPointY: CGFloat, startAngle: CGFloat, sweepAngle: CGFloat) -> CGFloat { let angleMiddle = startAngle + sweepAngle / 2.0 // Other point of the arc let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle).DEG2RAD) let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle).DEG2RAD) // Middle point on the arc let arcMidPointX = center.x + radius * cos(angleMiddle.DEG2RAD) let arcMidPointY = center.y + radius * sin(angleMiddle.DEG2RAD) // This is the base of the contained triangle let basePointsDistance = sqrt( pow(arcEndPointX - arcStartPointX, 2) + pow(arcEndPointY - arcStartPointY, 2)) // After reducing space from both sides of the "slice", // the angle of the contained triangle should stay the same. // So let's find out the height of that triangle. let containedTriangleHeight = (basePointsDistance / 2.0 * tan((180.0 - angle).DEG2RAD / 2.0)) // Now we subtract that from the radius var spacedRadius = radius - containedTriangleHeight // And now subtract the height of the arc that's between the triangle and the outer circle spacedRadius -= sqrt( pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) + pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2)) return spacedRadius } /// Calculates the sliceSpace to use based on visible values and their size compared to the set sliceSpace. @objc open func getSliceSpace(dataSet: IPieChartDataSet) -> CGFloat { guard dataSet.automaticallyDisableSliceSpacing, let data = chart?.data as? PieChartData else { return dataSet.sliceSpace } let spaceSizeRatio = dataSet.sliceSpace / min(viewPortHandler.contentWidth, viewPortHandler.contentHeight) let minValueRatio = dataSet.yMin / data.yValueSum * 2.0 let sliceSpace = spaceSizeRatio > CGFloat(minValueRatio) ? 0.0 : dataSet.sliceSpace return sliceSpace } @objc open func drawDataSet(context: CGContext, dataSet: IPieChartDataSet) { guard let chart = chart else {return } var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle let phaseX = animator.phaseX let phaseY = animator.phaseY let entryCount = dataSet.entryCount var drawAngles = chart.drawAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 var visibleAngleCount = 0 for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } if ((abs(e.y) > Double.ulpOfOne)) { visibleAngleCount += 1 } } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : getSliceSpace(dataSet: dataSet) context.saveGState() // Make the chart header the first element in the accessible elements array // We can do this in drawDataSet, since we know PieChartView can have only 1 dataSet // Also since there's only 1 dataset, we don't use the typical createAccessibleHeader() here. // NOTE: - Since we want to summarize the total count of slices/portions/elements, use a default string here // This is unlike when we are naming individual slices, wherein it's alright to not use a prefix as descriptor. // i.e. We want to VO to say "3 Elements" even if the developer didn't specify an accessibility prefix // If prefix is unspecified it is safe to assume they did not want to use "Element 1", so that uses a default empty string let prefix: String = chart.data?.accessibilityEntryLabelPrefix ?? "Element" let description = chart.chartDescription?.text ?? dataSet.label ?? chart.centerText ?? "Pie Chart" let element = NSUIAccessibilityElement(accessibilityContainer: chart) element.accessibilityLabel = description + ". \(entryCount) \(prefix + (entryCount == 1 ? "" : "s"))" element.accessibilityFrame = chart.bounds element.isHeader = true accessibleChartElements.append(element) for j in 0 ..< entryCount { let sliceAngle = drawAngles[j] var innerRadius = userInnerRadius guard let e = dataSet.entryForIndex(j) else { continue } // draw only if the value is greater than zero if (abs(e.y) > Double.ulpOfOne) { if !chart.needsHighlight(index: j) { let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0 context.setFillColor(dataSet.color(atIndex: j).cgColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / radius.DEG2RAD let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * CGFloat(phaseY) var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * CGFloat(phaseY) if sweepAngleOuter < 0.0 { sweepAngleOuter = 0.0 } let arcStartPointX = center.x + radius * cos(startAngleOuter.DEG2RAD) let arcStartPointY = center.y + radius * sin(startAngleOuter.DEG2RAD) let path = CGMutablePath() path.move(to: CGPoint(x: arcStartPointX, y: arcStartPointY)) path.addRelativeArc(center: center, radius: radius, startAngle: startAngleOuter.DEG2RAD, delta: sweepAngleOuter.DEG2RAD) if drawInnerArc && (innerRadius > 0.0 || accountForSliceSpacing) { if accountForSliceSpacing { var minSpacedRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * CGFloat(phaseY), arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = min(max(innerRadius, minSpacedRadius), radius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / innerRadius.DEG2RAD let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * CGFloat(phaseY) var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * CGFloat(phaseY) if sweepAngleInner < 0.0 { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner path.addLine( to: CGPoint( x: center.x + innerRadius * cos(endAngleInner.DEG2RAD), y: center.y + innerRadius * sin(endAngleInner.DEG2RAD))) path.addRelativeArc(center: center, radius: innerRadius, startAngle: endAngleInner.DEG2RAD, delta: -sweepAngleInner.DEG2RAD) } else { if accountForSliceSpacing { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let sliceSpaceOffset = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * CGFloat(phaseY), arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle.DEG2RAD) let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle.DEG2RAD) path.addLine( to: CGPoint( x: arcEndPointX, y: arcEndPointY)) } else { path.addLine(to: center) } } path.closeSubpath() context.beginPath() context.addPath(path) context.fillPath(using: .evenOdd) let axElement = createAccessibleElement(withIndex: j, container: chart, dataSet: dataSet) { (element) in element.accessibilityFrame = path.boundingBoxOfPath } accessibleChartElements.append(axElement) } } angle += sliceAngle * CGFloat(phaseX) } // Post this notification to let VoiceOver account for the redrawn frames accessibilityPostLayoutChangedNotification() context.restoreGState() } open override func drawValues(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let center = chart.centerCircleBox // get whole the radius let radius = chart.radius let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let phaseX = animator.phaseX let phaseY = animator.phaseY var labelRadiusOffset = radius / 10.0 * 3.0 if chart.drawHoleEnabled { labelRadiusOffset = (radius - (radius * chart.holeRadiusPercent)) / 2.0 } let labelRadius = radius - labelRadiusOffset var dataSets = data.dataSets let yValueSum = (data as! PieChartData).yValueSum let drawEntryLabels = chart.isDrawEntryLabelsEnabled let usePercentValuesEnabled = chart.usePercentValuesEnabled let entryLabelColor = chart.entryLabelColor let entryLabelFont = chart.entryLabelFont var angle: CGFloat = 0.0 var xIndex = 0 context.saveGState() defer { context.restoreGState() } for i in 0 ..< dataSets.count { guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue } let drawValues = dataSet.isDrawValuesEnabled if !drawValues && !drawEntryLabels && !dataSet.isDrawIconsEnabled { continue } let iconsOffset = dataSet.iconsOffset let xValuePosition = dataSet.xValuePosition let yValuePosition = dataSet.yValuePosition let valueFont = dataSet.valueFont let entryLabelFont = dataSet.entryLabelFont let lineHeight = valueFont.lineHeight guard let formatter = dataSet.valueFormatter else { continue } for j in 0 ..< dataSet.entryCount { guard let e = dataSet.entryForIndex(j) else { continue } let pe = e as? PieChartDataEntry if xIndex == 0 { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * CGFloat(phaseX) } let sliceAngle = drawAngles[xIndex] let sliceSpace = getSliceSpace(dataSet: dataSet) let sliceSpaceMiddleAngle = sliceSpace / labelRadius.DEG2RAD // offset needed to center the drawn text in the slice let angleOffset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0 angle = angle + angleOffset let transformedAngle = rotationAngle + angle * CGFloat(phaseY) let value = usePercentValuesEnabled ? e.y / yValueSum * 100.0 : e.y let valueText = formatter.stringForValue( value, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler) let sliceXBase = cos(transformedAngle.DEG2RAD) let sliceYBase = sin(transformedAngle.DEG2RAD) let drawXOutside = drawEntryLabels && xValuePosition == .outsideSlice let drawYOutside = drawValues && yValuePosition == .outsideSlice let drawXInside = drawEntryLabels && xValuePosition == .insideSlice let drawYInside = drawValues && yValuePosition == .insideSlice let valueTextColor = dataSet.valueTextColorAt(j) let entryLabelColor = dataSet.entryLabelColor if drawXOutside || drawYOutside { let valueLineLength1 = dataSet.valueLinePart1Length let valueLineLength2 = dataSet.valueLinePart2Length let valueLinePart1OffsetPercentage = dataSet.valueLinePart1OffsetPercentage var pt2: CGPoint var labelPoint: CGPoint var align: NSTextAlignment var line1Radius: CGFloat if chart.drawHoleEnabled { line1Radius = (radius - (radius * chart.holeRadiusPercent)) * valueLinePart1OffsetPercentage + (radius * chart.holeRadiusPercent) } else { line1Radius = radius * valueLinePart1OffsetPercentage } let polyline2Length = dataSet.valueLineVariableLength ? labelRadius * valueLineLength2 * abs(sin(transformedAngle.DEG2RAD)) : labelRadius * valueLineLength2 let pt0 = CGPoint( x: line1Radius * sliceXBase + center.x, y: line1Radius * sliceYBase + center.y) let pt1 = CGPoint( x: labelRadius * (1 + valueLineLength1) * sliceXBase + center.x, y: labelRadius * (1 + valueLineLength1) * sliceYBase + center.y) if transformedAngle.truncatingRemainder(dividingBy: 360.0) >= 90.0 && transformedAngle.truncatingRemainder(dividingBy: 360.0) <= 270.0 { pt2 = CGPoint(x: pt1.x - polyline2Length, y: pt1.y) align = .right labelPoint = CGPoint(x: pt2.x - 5, y: pt2.y - lineHeight) } else { pt2 = CGPoint(x: pt1.x + polyline2Length, y: pt1.y) align = .left labelPoint = CGPoint(x: pt2.x + 5, y: pt2.y - lineHeight) } if dataSet.valueLineColor != nil { context.setStrokeColor(dataSet.valueLineColor!.cgColor) context.setLineWidth(dataSet.valueLineWidth) context.move(to: CGPoint(x: pt0.x, y: pt0.y)) context.addLine(to: CGPoint(x: pt1.x, y: pt1.y)) context.addLine(to: CGPoint(x: pt2.x, y: pt2.y)) context.drawPath(using: CGPathDrawingMode.stroke) } if drawXOutside && drawYOutside { ChartUtils.drawText( context: context, text: valueText, point: labelPoint, align: align, attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor] ) if j < data.entryCount && pe?.label != nil { ChartUtils.drawText( context: context, text: pe!.label!, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight), align: align, attributes: [ NSAttributedString.Key.font: entryLabelFont ?? valueFont, NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor] ) } } else if drawXOutside { if j < data.entryCount && pe?.label != nil { ChartUtils.drawText( context: context, text: pe!.label!, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0), align: align, attributes: [ NSAttributedString.Key.font: entryLabelFont ?? valueFont, NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor] ) } } else if drawYOutside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0), align: align, attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor] ) } } if drawXInside || drawYInside { // calculate the text position let x = labelRadius * sliceXBase + center.x let y = labelRadius * sliceYBase + center.y - lineHeight if drawXInside && drawYInside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: x, y: y), align: .center, attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor] ) if j < data.entryCount && pe?.label != nil { ChartUtils.drawText( context: context, text: pe!.label!, point: CGPoint(x: x, y: y + lineHeight), align: .center, attributes: [ NSAttributedString.Key.font: entryLabelFont ?? valueFont, NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor] ) } } else if drawXInside { if j < data.entryCount && pe?.label != nil { ChartUtils.drawText( context: context, text: pe!.label!, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .center, attributes: [ NSAttributedString.Key.font: entryLabelFont ?? valueFont, NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor] ) } } else if drawYInside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .center, attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor] ) } } if let icon = e.icon, dataSet.isDrawIconsEnabled { // calculate the icon's position let x = (labelRadius + iconsOffset.y) * sliceXBase + center.x var y = (labelRadius + iconsOffset.y) * sliceYBase + center.y y += iconsOffset.x ChartUtils.drawImage(context: context, image: icon, x: x, y: y, size: icon.size) } xIndex += 1 } } } open override func drawExtras(context: CGContext) { drawHole(context: context) drawCenterText(context: context) } /// draws the hole in the center of the chart and the transparent circle / hole private func drawHole(context: CGContext) { guard let chart = chart else { return } if chart.drawHoleEnabled { context.saveGState() let radius = chart.radius let holeRadius = radius * chart.holeRadiusPercent let center = chart.centerCircleBox if let holeColor = chart.holeColor { if holeColor != NSUIColor.clear { // draw the hole-circle context.setFillColor(chart.holeColor!.cgColor) context.fillEllipse(in: CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) } } // only draw the circle if it can be seen (not covered by the hole) if let transparentCircleColor = chart.transparentCircleColor { if transparentCircleColor != NSUIColor.clear && chart.transparentCircleRadiusPercent > chart.holeRadiusPercent { let alpha = animator.phaseX * animator.phaseY let secondHoleRadius = radius * chart.transparentCircleRadiusPercent // make transparent context.setAlpha(CGFloat(alpha)) context.setFillColor(transparentCircleColor.cgColor) // draw the transparent-circle context.beginPath() context.addEllipse(in: CGRect( x: center.x - secondHoleRadius, y: center.y - secondHoleRadius, width: secondHoleRadius * 2.0, height: secondHoleRadius * 2.0)) context.addEllipse(in: CGRect( x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) context.fillPath(using: .evenOdd) } } context.restoreGState() } } /// draws the description text in the center of the pie chart makes most sense when center-hole is enabled private func drawCenterText(context: CGContext) { guard let chart = chart, let centerAttributedText = chart.centerAttributedText else { return } if chart.drawCenterTextEnabled && centerAttributedText.length > 0 { let center = chart.centerCircleBox let offset = chart.centerTextOffset let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius let x = center.x + offset.x let y = center.y + offset.y let holeRect = CGRect( x: x - innerRadius, y: y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0) var boundingRect = holeRect if chart.centerTextRadiusPercent > 0.0 { boundingRect = boundingRect.insetBy(dx: (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, dy: (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0) } let textBounds = centerAttributedText.boundingRect(with: boundingRect.size, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil) var drawingRect = boundingRect drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0 drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0 drawingRect.size = textBounds.size context.saveGState() let clippingPath = CGPath(ellipseIn: holeRect, transform: nil) context.beginPath() context.addPath(clippingPath) context.clip() centerAttributedText.draw(with: drawingRect, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil) context.restoreGState() } } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let chart = chart, let data = chart.data else { return } context.saveGState() let phaseX = animator.phaseX let phaseY = animator.phaseY var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 // Append highlighted accessibility slices into this array, so we can prioritize them over unselected slices var highlightedAccessibleElements: [NSUIAccessibilityElement] = [] for i in 0 ..< indices.count { // get the index to highlight let index = Int(indices[i].x) if index >= drawAngles.count { continue } guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue } if !set.isHighlightEnabled { continue } let entryCount = set.entryCount var visibleAngleCount = 0 for j in 0 ..< entryCount { guard let e = set.entryForIndex(j) else { continue } if ((abs(e.y) > Double.ulpOfOne)) { visibleAngleCount += 1 } } if index == 0 { angle = 0.0 } else { angle = absoluteAngles[index - 1] * CGFloat(phaseX) } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace let sliceAngle = drawAngles[index] var innerRadius = userInnerRadius let shift = set.selectionShift let highlightedRadius = radius + shift let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0 context.setFillColor(set.highlightColor?.cgColor ?? set.color(atIndex: index).cgColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / radius.DEG2RAD let sliceSpaceAngleShifted = visibleAngleCount == 1 ? 0.0 : sliceSpace / highlightedRadius.DEG2RAD let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * CGFloat(phaseY) var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * CGFloat(phaseY) if sweepAngleOuter < 0.0 { sweepAngleOuter = 0.0 } let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * CGFloat(phaseY) var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * CGFloat(phaseY) if sweepAngleShifted < 0.0 { sweepAngleShifted = 0.0 } let path = CGMutablePath() path.move(to: CGPoint(x: center.x + highlightedRadius * cos(startAngleShifted.DEG2RAD), y: center.y + highlightedRadius * sin(startAngleShifted.DEG2RAD))) path.addRelativeArc(center: center, radius: highlightedRadius, startAngle: startAngleShifted.DEG2RAD, delta: sweepAngleShifted.DEG2RAD) var sliceSpaceRadius: CGFloat = 0.0 if accountForSliceSpacing { sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * CGFloat(phaseY), arcStartPointX: center.x + radius * cos(startAngleOuter.DEG2RAD), arcStartPointY: center.y + radius * sin(startAngleOuter.DEG2RAD), startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) } if drawInnerArc && (innerRadius > 0.0 || accountForSliceSpacing) { if accountForSliceSpacing { var minSpacedRadius = sliceSpaceRadius if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = min(max(innerRadius, minSpacedRadius), radius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / innerRadius.DEG2RAD let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * CGFloat(phaseY) var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * CGFloat(phaseY) if sweepAngleInner < 0.0 { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner path.addLine( to: CGPoint( x: center.x + innerRadius * cos(endAngleInner.DEG2RAD), y: center.y + innerRadius * sin(endAngleInner.DEG2RAD))) path.addRelativeArc(center: center, radius: innerRadius, startAngle: endAngleInner.DEG2RAD, delta: -sweepAngleInner.DEG2RAD) } else { if accountForSliceSpacing { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle.DEG2RAD) let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle.DEG2RAD) path.addLine( to: CGPoint( x: arcEndPointX, y: arcEndPointY)) } else { path.addLine(to: center) } } path.closeSubpath() context.beginPath() context.addPath(path) context.fillPath(using: .evenOdd) let axElement = createAccessibleElement(withIndex: index, container: chart, dataSet: set) { (element) in element.accessibilityFrame = path.boundingBoxOfPath element.isSelected = true } highlightedAccessibleElements.append(axElement) } // Prepend selected slices before the already rendered unselected ones. // NOTE: - This relies on drawDataSet() being called before drawHighlighted in PieChartView. accessibleChartElements.insert(contentsOf: highlightedAccessibleElements, at: 1) context.restoreGState() } /// Creates an NSUIAccessibilityElement representing a slice of the PieChart. /// The element only has it's container and label set based on the chart and dataSet. Use the modifier to alter traits and frame. private func createAccessibleElement(withIndex idx: Int, container: PieChartView, dataSet: IPieChartDataSet, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) guard let e = dataSet.entryForIndex(idx) else { return element } guard let formatter = dataSet.valueFormatter else { return element } guard let data = container.data as? PieChartData else { return element } var elementValueText = formatter.stringForValue( e.y, entry: e, dataSetIndex: idx, viewPortHandler: viewPortHandler) if container.usePercentValuesEnabled { let value = e.y / data.yValueSum * 100.0 let valueText = formatter.stringForValue( value, entry: e, dataSetIndex: idx, viewPortHandler: viewPortHandler) elementValueText = valueText } let pieChartDataEntry = (dataSet.entryForIndex(idx) as? PieChartDataEntry) let isCount = data.accessibilityEntryLabelSuffixIsCount let prefix = data.accessibilityEntryLabelPrefix?.appending("\(idx + 1)") ?? pieChartDataEntry?.label ?? "" let suffix = data.accessibilityEntryLabelSuffix ?? "" element.accessibilityLabel = "\(prefix) : \(elementValueText) \(suffix + (isCount ? (e.y == 1.0 ? "" : "s") : "") )" // The modifier allows changing of traits and frame depending on highlight, rotation, etc modifier(element) return element } }
apache-2.0
3c221acca479a22a79b9fb4f3441df7b
39.782468
223
0.515511
5.637792
false
false
false
false
shorlander/firefox-ios
ClientTests/PrefsTests.swift
26
3551
/* 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/. */ @testable import Client import Foundation import Shared import XCTest class PrefsTests: XCTestCase { var prefs: NSUserDefaultsPrefs! override func setUp() { super.setUp() prefs = NSUserDefaultsPrefs(prefix: "PrefsTests") } override func tearDown() { prefs.clearAll() super.tearDown() } func testClearPrefs() { prefs.setObject("foo", forKey: "bar") XCTAssertEqual(prefs.stringForKey("bar")!, "foo") // Ensure clearing prefs is branch-specific. let otherPrefs = NSUserDefaultsPrefs(prefix: "othermockaccount") otherPrefs.clearAll() XCTAssertEqual(prefs.stringForKey("bar")!, "foo") prefs.clearAll() XCTAssertNil(prefs.stringForKey("bar")) } func testStringForKey() { XCTAssertNil(prefs.stringForKey("key")) prefs.setObject("value", forKey: "key") XCTAssertEqual(prefs.stringForKey("key")!, "value") // Non-String values return nil. prefs.setObject(1, forKey: "key") XCTAssertNil(prefs.stringForKey("key")) } func testBoolForKey() { XCTAssertNil(prefs.boolForKey("key")) prefs.setObject(true, forKey: "key") XCTAssertEqual(prefs.boolForKey("key")!, true) prefs.setObject(false, forKey: "key") XCTAssertEqual(prefs.boolForKey("key")!, false) // We would like non-Bool values to return nil, but I can't figure out how to differentiate. // Instead, this documents the undesired behaviour. prefs.setObject(1, forKey: "key") XCTAssertEqual(prefs.boolForKey("key")!, true) prefs.setObject("1", forKey: "key") XCTAssertNil(prefs.boolForKey("key")) prefs.setObject("x", forKey: "key") XCTAssertNil(prefs.boolForKey("key")) } func testStringArrayForKey() { XCTAssertNil(prefs.stringArrayForKey("key")) prefs.setObject(["value1", "value2"], forKey: "key") XCTAssertEqual(prefs.stringArrayForKey("key")!, ["value1", "value2"]) // Non-[String] values return nil. prefs.setObject(1, forKey: "key") XCTAssertNil(prefs.stringArrayForKey("key")) // [Non-String] values return nil. prefs.setObject([1, 2], forKey: "key") XCTAssertNil(prefs.stringArrayForKey("key")) } func testMockProfilePrefsRoundtripsTimestamps() { let prefs = MockProfilePrefs().branch("baz") let val: Timestamp = Date.now() prefs.setLong(val, forKey: "foobar") XCTAssertEqual(val, prefs.unsignedLongForKey("foobar")!) } func testMockProfilePrefsKeys() { let prefs = MockProfilePrefs().branch("baz") as! MockProfilePrefs let val: Timestamp = Date.now() prefs.setLong(val, forKey: "foobar") XCTAssertEqual(val, (prefs.things["baz.foobar"] as! NSNumber).uint64Value) } func testMockProfilePrefsClearAll() { let prefs1 = MockProfilePrefs().branch("bar") as! MockProfilePrefs let prefs2 = MockProfilePrefs().branch("baz") as! MockProfilePrefs // Ensure clearing prefs is branch-specific. prefs1.setInt(123, forKey: "foo") prefs2.clearAll() XCTAssertEqual(123, prefs1.intForKey("foo")!) prefs1.clearAll() XCTAssertNil(prefs1.intForKey("foo") as AnyObject?) } }
mpl-2.0
3e61fb6aea6869e8bfb115c4ccb352c8
34.51
100
0.639257
4.472292
false
true
false
false
codestergit/LTMorphingLabel
LTMorphingLabel/NSString+LTMorphingLabel.swift
1
5083
// // NSString+LTMorphingLabel.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2014 Lex Tang, http://LexTang.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation enum LTCharacterDiffType: Int, DebugPrintable { case Same = 0 case Add = 1 case Delete case Move case MoveAndAdd case Replace var debugDescription: String { get { switch self { case .Same: return "Same" case .Add: return "Add" case .Delete: return "Delete" case .Move: return "Move" case .MoveAndAdd: return "MoveAndAdd" default: return "Replace" } } } } struct LTCharacterDiffResult: DebugPrintable { var diffType: LTCharacterDiffType var moveOffset: Int var skip: Bool var debugDescription: String { get { switch diffType { case .Same: return "The character is unchanged." case .Add: return "A new character is ADDED." case .Delete: return "The character is DELETED." case .Move: return "The character is MOVED to \(moveOffset)." case .MoveAndAdd: return "The character is MOVED to \(moveOffset) and a new character is ADDED." default: return "The character is REPLACED with a new character." } } } } @infix func >>(lhs: String, rhs: String) -> Array<LTCharacterDiffResult> { var diffResults = Array<LTCharacterDiffResult>() let newChars = enumerate(rhs) let lhsLength = countElements(lhs) let rhsLength = countElements(rhs) var skipIndexes = Array<Int>() for i in 0..<(max(lhsLength, rhsLength) + 1) { var result = LTCharacterDiffResult(diffType: .Add, moveOffset: 0, skip: false) // If new string is longer than the original one if i > lhsLength - 1 { result.diffType = .Add diffResults.append(result) continue } let leftChar = Array(lhs)[i] // Search left character in the new string var foundCharacterInRhs = false for (j, newChar) in newChars { let currentCharWouldBeReplaced = { (index: Int) -> Bool in for k in skipIndexes { if index == k { return true } } return false }(j) if currentCharWouldBeReplaced { continue } if leftChar == newChar { skipIndexes.append(j) foundCharacterInRhs = true if i == j { // Character not changed result.diffType = .Same } else { // foundCharacterInRhs and move result.diffType = .Move if i <= rhsLength - 1 { // Move to a new index and add a new character to new original place result.diffType = .MoveAndAdd } result.moveOffset = j - i } break } } if !foundCharacterInRhs { if i < countElements(rhs) - 1 { result.diffType = .Replace } else { result.diffType = .Delete } } if i > lhsLength - 1 { result.diffType = .Add } diffResults.append(result) } var i = 0 for result in diffResults { switch result.diffType { case .Move, .MoveAndAdd: diffResults[i + result.moveOffset].skip = true default: Foundation.NSNotFound } i++ } return diffResults }
mit
fd1e46f694cba7c7caab36a24f2fc4d0
28.505814
92
0.549557
4.738562
false
false
false
false
jboulter11/Vis
Vis/VSInfoViewController.swift
1
6362
// // VSInfoViewController.swift // Vis // // Created by james grippo on 4/2/16. // Copyright © 2016 Squad. All rights reserved. // import Cocoa import FileKit class VSInfoViewController: NSViewController { // It's hard to see these view on the storyboard but the textview is inside of the // scrollview. The image view is stacked ontop of the scrollview. @IBOutlet weak var scrollView: NSScrollView! @IBOutlet var fileInfo: NSTextView! @IBOutlet weak var imageDisplay: NSImageView! // These are all the ten labels on the storyboard for // VSInfoViewController. @IBOutlet weak var sizeInfo: NSTextField! @IBOutlet weak var size: NSTextField! @IBOutlet weak var type: NSTextField! @IBOutlet weak var kind: NSTextField! @IBOutlet weak var created: NSTextField! @IBOutlet weak var createdDate: NSTextField! @IBOutlet weak var modified: NSTextField! @IBOutlet weak var modifiedDate: NSTextField! @IBOutlet weak var location: NSTextField! @IBOutlet weak var locationInfo: NSTextField! @IBOutlet weak var titleTextView: NSTextField! // This is the place where we store text from a file for the text view var textStorage: NSTextStorage! override func viewWillAppear() { super.viewWillAppear() preferredContentSize = NSSize(width: 500, height: 300) } override func viewDidLoad() { super.viewDidLoad() imageDisplay.wantsLayer = true // These string values correspond to the first column of labels created.stringValue = "Created:" modified.stringValue = "Modified:" size.stringValue = "Size:" location.stringValue = "Where:" kind.stringValue = "Kind:" // This is our observer for file selection. This is called whenever a new file is selected. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didReceiveNotification), name: "SelectedPathDidChange", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didReceiveNotification), name: "SelectionChangedFromTreeMap", object: nil) } // This function calls displayInformationForPath, which updates the entire view to the current path func didReceiveNotification() { displayInformationForPath(VSExec.exec.selectedPath) } // Function to update the view to the current path func displayInformationForPath ( fpath: Path) { // Date formatter turns an NSDate object ( IE 12/6/2016 ) into a string let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .ShortStyle dateFormatter.timeStyle = .ShortStyle // Number formatter adds commas to a number let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle // Hides the overlapping views fileInfo.editable = false fileInfo.hidden = true scrollView.hidden = true imageDisplay.hidden = true // Sets the values for file type titleTextView.stringValue = fpath.fileName locationInfo.stringValue = fpath.rawValue sizeInfo.stringValue = "\(numberFormatter.stringFromNumber(NSNumber(unsignedLongLong: fpath.fileSize!))!) Bytes" type.stringValue = fpath.pathExtension createdDate.stringValue = dateFormatter.stringFromDate(fpath.creationDate!) modifiedDate.stringValue = dateFormatter.stringFromDate(fpath.modificationDate!) if (fpath.isDirectory) { displayDirectory(fpath) } // Different functions for each type of file else { switch fpath.pathExtension { case "txt": displayTextFile(fpath) case "jpeg": displayImageFile(fpath) type.stringValue = "JPEG Image" case "jpg": displayImageFile(fpath) type.stringValue = "JPEG Image" case "png": displayImageFile(fpath) type.stringValue = "PNG Image" case "pdf": displayImageFile(fpath) type.stringValue = "Portable Document Format" case "tif": displayImageFile(fpath) type.stringValue = "TIFF Image" default: displayDefaultFile(fpath) } } } // function to display a text file func displayTextFile (fpath: Path) { textStorage = NSTextStorage() let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(containerSize: view.frame.size) layoutManager.addTextContainer(textContainer) var text: String = "" do { text = try String(contentsOfFile: fpath.rawValue, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} fileInfo.textStorage?.setAttributedString(NSAttributedString(string: text)) type.stringValue = "Plain Text Document" scrollView.hidden = false fileInfo.hidden = false } // function to display a directory func displayDirectory (fpath: Path) { type.stringValue = "Directory" let fImage: NSImage = NSImage(named: "Folder")! imageDisplay.layer?.backgroundColor = NSColor.clearColor().CGColor imageDisplay.hidden = false scrollView.hidden = true imageDisplay.image = fImage } //function to display the default file (a file type that hasn't been implemented yet) func displayDefaultFile (fpath: Path) { imageDisplay.hidden = true fileInfo.hidden = true scrollView.hidden = true } // function to display an image func displayImageFile (fpath: Path) { imageDisplay.hidden = false do{ let image = NSImage(contentsOfFile: fpath.rawValue) imageDisplay.image = image } } // TODO: Write test for this class, testing correct info displayed for file }
mit
5944e1d0d5a8320b2221f64ee91c1f45
32.303665
157
0.631347
5.363406
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Dictionaries/StopwordsDictionary.swift
1
956
// // StopwordsDictionary.swift // // // Created by Vladislav Fitc on 20/01/2021. // import Foundation public struct StopwordsDictionary: CustomDictionary { public static var name: DictionaryName = .stopwords } extension StopwordsDictionary { public struct Entry: DictionaryEntry, Codable, Equatable { public enum State: String, Codable { case enabled case disabled } public let objectID: ObjectID public let language: Language /// The stop word being added or modified. When `word` already exists in the standard dictionary provided by Algolia, the entry can be overridden by the one provided by the user. public let word: String /// The state of the entry public let state: State? public init(objectID: ObjectID, language: Language, word: String, state: State) { self.objectID = objectID self.language = language self.word = word self.state = state } } }
mit
08d95382cffb9ea0ca069fc401e65e74
21.232558
182
0.692469
4.530806
false
false
false
false
hamin/FayeSwift
Sources/FayeClient.swift
1
5250
// // FayeClient.swift // FayeSwift // // Created by Haris Amin on 8/31/14. // Copyright (c) 2014 Haris Amin. All rights reserved. // import Foundation import SwiftyJSON // MARK: Subscription State public enum FayeSubscriptionState { case pending(FayeSubscriptionModel) case subscribed(FayeSubscriptionModel) case queued(FayeSubscriptionModel) case subscribingTo(FayeSubscriptionModel) case unknown(FayeSubscriptionModel?) } // MARK: Type Aliases public typealias ChannelSubscriptionBlock = (NSDictionary) -> Void // MARK: FayeClient open class FayeClient : TransportDelegate { open var fayeURLString:String { didSet { if let transport = self.transport { transport.urlString = fayeURLString } } } open var fayeClientId:String? open weak var delegate:FayeClientDelegate? var transport:WebsocketTransport? open var transportHeaders: [String: String]? = nil { didSet { if let transport = self.transport { transport.headers = self.transportHeaders } } } open internal(set) var fayeConnected:Bool? { didSet { if fayeConnected == false { unsubscribeAllSubscriptions() } } } var connectionInitiated:Bool? var messageNumber:UInt32 = 0 var queuedSubscriptions = Array<FayeSubscriptionModel>() var pendingSubscriptions = Array<FayeSubscriptionModel>() var openSubscriptions = Array<FayeSubscriptionModel>() var channelSubscriptionBlocks = Dictionary<String, ChannelSubscriptionBlock>() lazy var pendingSubscriptionSchedule: Timer = { return Timer.scheduledTimer( timeInterval: 45, target: self, selector: #selector(pendingSubscriptionsAction(_:)), userInfo: nil, repeats: true ) }() /// Default in 10 seconds let timeOut: Int let readOperationQueue = DispatchQueue(label: "com.hamin.fayeclient.read", attributes: []) let writeOperationQueue = DispatchQueue(label: "com.hamin.fayeclient.write", attributes: DispatchQueue.Attributes.concurrent) let queuedSubsLockQueue = DispatchQueue(label:"com.fayeclient.queuedSubscriptionsLockQueue") let pendingSubsLockQueue = DispatchQueue(label:"com.fayeclient.pendingSubscriptionsLockQueue") let openSubsLockQueue = DispatchQueue(label:"com.fayeclient.openSubscriptionsLockQueue") // MARK: Init public init(aFayeURLString:String, channel:String?, timeoutAdvice:Int=10000) { self.fayeURLString = aFayeURLString self.fayeConnected = false; self.timeOut = timeoutAdvice self.transport = WebsocketTransport(url: aFayeURLString) self.transport!.headers = self.transportHeaders self.transport!.delegate = self; if let channel = channel { self.queuedSubscriptions.append(FayeSubscriptionModel(subscription: channel, clientId: fayeClientId)) } } public convenience init(aFayeURLString:String, channel:String, channelBlock:@escaping ChannelSubscriptionBlock) { self.init(aFayeURLString: aFayeURLString, channel: channel) self.channelSubscriptionBlocks[channel] = channelBlock; } deinit { pendingSubscriptionSchedule.invalidate() } // MARK: Client open func connectToServer() { if self.connectionInitiated != true { self.transport?.openConnection() self.connectionInitiated = true; } else { print("Faye: Connection established") } } open func disconnectFromServer() { unsubscribeAllSubscriptions() self.disconnect() } open func sendMessage(_ messageDict: NSDictionary, channel:String) { self.publish(messageDict as! Dictionary, channel: channel) } open func sendMessage(_ messageDict:[String:AnyObject], channel:String) { self.publish(messageDict, channel: channel) } open func sendPing(_ data: Data, completion: (() -> ())?) { writeOperationQueue.async { [unowned self] in self.transport?.sendPing(data, completion: completion) } } open func subscribeToChannel(_ model:FayeSubscriptionModel, block:ChannelSubscriptionBlock?=nil) -> FayeSubscriptionState { guard !self.isSubscribedToChannel(model.subscription) else { return .subscribed(model) } guard !self.pendingSubscriptions.contains(where: { $0 == model }) else { return .pending(model) } if let block = block { self.channelSubscriptionBlocks[model.subscription] = block; } if self.fayeConnected == false { self.queuedSubscriptions.append(model) return .queued(model) } self.subscribe(model) return .subscribingTo(model) } open func subscribeToChannel(_ channel:String, block:ChannelSubscriptionBlock?=nil) -> FayeSubscriptionState { return subscribeToChannel( FayeSubscriptionModel(subscription: channel, clientId: fayeClientId), block: block ) } open func unsubscribeFromChannel(_ channel:String) { _ = removeChannelFromQueuedSubscriptions(channel) self.unsubscribe(channel) self.channelSubscriptionBlocks[channel] = nil; _ = removeChannelFromOpenSubscriptions(channel) _ = removeChannelFromPendingSubscriptions(channel) } }
mit
fcf425071c47118900f463c075963cd7
28.661017
127
0.702476
4.43787
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/DashboardProjects/Views/FundingGraphView.swift
1
8725
import KsApi import Library import Prelude import UIKit private typealias Line = (start: CGPoint, end: CGPoint) public final class FundingGraphView: UIView { fileprivate let goalLabel = UILabel() public override init(frame: CGRect) { super.init(frame: frame) self.setUp() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUp() } fileprivate func setUp() { self.backgroundColor = .clear self.addSubview(self.goalLabel) _ = self.goalLabel |> UILabel.lens.font .~ .ksr_headline(size: 12) |> UILabel.lens.textColor .~ .ksr_white |> UILabel.lens.backgroundColor .~ .ksr_create_700 |> UILabel.lens.textAlignment .~ .center } internal var fundedPointRadius: CGFloat = 12.0 { didSet { self.setNeedsDisplay() } } internal var lineThickness: CGFloat = 1.5 { didSet { self.setNeedsDisplay() } } internal var project: Project! { didSet { self.setNeedsDisplay() } } internal var stats: [ProjectStatsEnvelope.FundingDateStats]! { didSet { self.setNeedsDisplay() } } internal var yAxisTickSize: CGFloat = 1.0 { didSet { self.setNeedsDisplay() } } public override func draw(_ rect: CGRect) { super.draw(rect) // Map the date and pledged amount to (dayNumber, pledgedAmount). let datePledgedPoints = self.stats .enumerated() .map { index, stat in CGPoint(x: index, y: stat.cumulativePledged) } let durationInDays = dateToDayNumber( launchDate: project.dates.launchedAt, currentDate: self.project.dates.deadline ) let goal = self.project.stats.goal let pointsPerDay = (self.bounds.width - self.layoutMargins.left) / durationInDays let pointsPerDollar = self.bounds.height / (CGFloat(DashboardFundingCellViewModel.tickCount) * self.yAxisTickSize) // Draw the funding progress grey line and fill. let line = UIBezierPath() line.lineWidth = self.lineThickness var lastPoint = CGPoint(x: self.layoutMargins.left, y: self.bounds.height) line.move(to: lastPoint) datePledgedPoints.forEach { point in let x = point.x * pointsPerDay + self.layoutMargins.left let y = self.bounds.height - min(point.y * pointsPerDollar, self.bounds.height) line.addLine(to: CGPoint(x: x, y: y)) lastPoint = CGPoint(x: x, y: y) } // Stroke the darker graph line before filling with lighter color. UIColor.ksr_support_400.setStroke() line.stroke() line.addLine(to: CGPoint(x: lastPoint.x, y: self.bounds.height)) line.close() UIColor.ksr_support_300.setFill() line.fill(with: .color, alpha: 0.4) let projectHasFunded = self.stats.last?.cumulativePledged ?? 0 >= goal if projectHasFunded { let rightFundedStat = self.stats.split { $0.cumulativePledged < goal }.last?.first let rightFundedPoint = CGPoint( x: dateToDayNumber( launchDate: stats.first?.date ?? 0, currentDate: rightFundedStat?.date ?? 0 ), y: CGFloat(rightFundedStat?.cumulativePledged ?? 0) ) let leftFundedStat = self.stats.filter { $0.cumulativePledged < goal }.last let leftFundedPoint = isNil(leftFundedStat) ? CGPoint(x: 0.0, y: 0.0) : CGPoint( x: dateToDayNumber( launchDate: self.stats.first?.date ?? 0, currentDate: leftFundedStat?.date ?? 0 ), y: CGFloat(leftFundedStat?.cumulativePledged ?? 0) ) let leftPointX = leftFundedPoint.x * pointsPerDay + self.layoutMargins.left let leftPointY = self.bounds.height - min(leftFundedPoint.y * pointsPerDollar, self.bounds.height) let rightPointX = rightFundedPoint.x * pointsPerDay + self.layoutMargins.left let rightPointY = self.bounds.height - min(rightFundedPoint.y * pointsPerDollar, self.bounds.height) // Surrounding left and right points, used to find slope of line containing funded point. let lineAPoint1 = CGPoint(x: leftPointX, y: leftPointY) let lineAPoint2 = CGPoint(x: rightPointX, y: rightPointY) let lineA = Line(start: lineAPoint1, end: lineAPoint2) // Intersecting funded horizontal line. let lineBPoint1 = CGPoint( x: self.layoutMargins.left, y: self.bounds.height - min(CGFloat(goal) * pointsPerDollar, self.bounds.height) ) let lineBPoint2 = CGPoint( x: self.bounds.width, y: self.bounds.height - min(CGFloat(goal) * pointsPerDollar, self.bounds.height) ) let lineB = Line(start: lineBPoint1, end: lineBPoint2) let fundedPoint = intersection(ofLine: lineA, withLine: lineB) let fundedDotOutline = UIBezierPath( ovalIn: CGRect( x: fundedPoint.x - (self.fundedPointRadius / 2), y: fundedPoint.y - (self.fundedPointRadius / 2), width: self.fundedPointRadius, height: self.fundedPointRadius ) ) let fundedDotFill = UIBezierPath( ovalIn: CGRect( x: fundedPoint.x - (self.fundedPointRadius / 2 / 2), y: fundedPoint.y - (self.fundedPointRadius / 2 / 2), width: self.fundedPointRadius / 2, height: self.fundedPointRadius / 2 ) ) // Draw funding progress line in green from funding point on. let fundedProgressLine = UIBezierPath() fundedProgressLine.lineWidth = self.lineThickness var lastFundedPoint = CGPoint(x: fundedPoint.x, y: fundedPoint.y) fundedProgressLine.move(to: lastFundedPoint) datePledgedPoints.forEach { point in let x = point.x * pointsPerDay + self.layoutMargins.left if x >= fundedPoint.x { let y = self.bounds.height - point.y * pointsPerDollar fundedProgressLine.addLine(to: CGPoint(x: x, y: y)) lastFundedPoint = CGPoint(x: x, y: y) } } // Stroke the darker graph line before filling with lighter color. UIColor.ksr_create_700.setStroke() fundedProgressLine.stroke() fundedProgressLine.addLine(to: CGPoint(x: lastFundedPoint.x, y: self.bounds.height)) fundedProgressLine.addLine(to: CGPoint(x: fundedPoint.x, y: self.bounds.height)) fundedProgressLine.close() UIColor.ksr_create_500.setFill() fundedProgressLine.fill(with: .color, alpha: 0.4) UIColor.ksr_create_700.set() fundedDotOutline.stroke() fundedDotFill.fill() } else { let goalLine = Line( start: CGPoint(x: 0.0, y: self.bounds.height - CGFloat(goal) * pointsPerDollar), end: CGPoint( x: self.bounds.width, y: self.bounds.height - CGFloat(goal) * pointsPerDollar ) ) let goalPath = UIBezierPath() goalPath.lineWidth = self.lineThickness / 2 goalPath.move(to: goalLine.start) goalPath.addLine(to: goalLine.end) UIColor.ksr_create_700.setStroke() goalPath.stroke() self.goalLabel.text = Strings.dashboard_graphs_funding_goal() self.goalLabel.sizeToFit() self.goalLabel.frame = self.goalLabel.frame.insetBy(dx: -6, dy: -3).integral self.goalLabel.center = CGPoint( x: self.bounds.width - 16 - self.goalLabel.frame.width / 2, y: goalLine.end.y - self.goalLabel.frame.height / 2 ) } self.goalLabel.isHidden = projectHasFunded } } // Calculates the point of intersection of Line 1 and Line 2. private func intersection(ofLine line1: Line, withLine line2: Line) -> CGPoint { guard line1.start.x != line1.end.x else { return CGPoint(x: line1.start.x, y: line2.start.y) } let line1Slope = slope(ofLine: line1) let line1YIntercept = yIntercept(ofLine: line1) let line2Slope = slope(ofLine: line2) let line2YIntercept = yIntercept(ofLine: line2) let x = (line2YIntercept - line1YIntercept) / (line1Slope - line2Slope) let y = line1Slope * x + line1YIntercept return CGPoint(x: x, y: y) } // Calculates where a given line will intercept the y-axis, if ever. private func yIntercept(ofLine line: Line) -> CGFloat { return slope(ofLine: line) * (-line.start.x) + line.start.y } // Calculates the slope between two given points, if any. private func slope(ofLine line: Line) -> CGFloat { if line.start.x == line.end.x { fatalError() } return (line.end.y - line.start.y) / (line.end.x - line.start.x) } // Returns the day number, given the start and current date in seconds. private func dateToDayNumber( launchDate: TimeInterval, currentDate: TimeInterval, calendar _: Calendar = AppEnvironment.current.calendar ) -> CGFloat { return CGFloat((currentDate - launchDate) / 60.0 / 60.0 / 24.0) }
apache-2.0
fb2b9006d5ae1bd2b421b6f323d6f8cc
31.195572
106
0.65937
3.681435
false
false
false
false