repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dathtcheapgo/Jira-Demo
refs/heads/master
Driver/MVC/Core/View/CGBookingNavigationBar/CGBookingNavigationBar.swift
mit
1
// // CGBookingNavigationBar.swift // Rider // // Created by Đinh Anh Huy on 11/2/16. // Copyright © 2016 Đinh Anh Huy. All rights reserved. // import UIKit protocol CGBookingNavigationBarDelegate { func bookingNavigationBarDidChangeIndex(sender: CGBookingNavigationBar, title: String, index: Int) } class CGBookingNavigationBar: BaseXibView { let animateDuration: TimeInterval = Config.shareInstance.animateDuration/2 @IBOutlet var view: UIView! @IBOutlet var viewWrapTitle: UIView! @IBOutlet var imgLeft: UIImageView! @IBOutlet var imgRight: UIImageView! var delegate: CGBookingNavigationBarDelegate? var titles = ["Passenger", "Delivery", "Tour", "Car Hire"] var lbTitles = [UILabel]() var viewForcus = UIView() var leadingConstraintViewForcus: NSLayoutConstraint! @IBAction func leftButtonDidClick(_ sender: UIButton) { } @IBAction func rightButtonDidClick(_ sender: UIButton) { } override func initControl() { //load nib file Bundle.main.loadNibNamed("CGBookingNavigationBar", owner: self, options: nil) view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) _ = view.addConstraintFillInView(view: self, commenParrentView: self) setupTitleLabel() setupViewForcus() } } //MARK: Show, Hide animation extension CGBookingNavigationBar { func show() { self.constraintTop()?.constant = 0 UIView.animate(withDuration: animateDuration, animations: { self.superview?.layoutIfNeeded() }) { (complete) in } } func hide() { self.constraintTop()?.constant = -frame.size.height UIView.animate(withDuration: animateDuration, animations: { self.superview?.layoutIfNeeded() }) { (complete) in } } } //MARK: Setup UI extension CGBookingNavigationBar { func setupTitleLabel() { //setup list title label UI and action for i in 0..<titles.count { let label = UILabel() label.setup() setupGestureForLabel(label: label) label.text = titles[i] label.translatesAutoresizingMaskIntoConstraints = false label.adjustsFontSizeToFitWidth = true viewWrapTitle.addSubview(label) _ = label.addConstraintTopMarginToView(view: viewWrapTitle, commonParrentView: viewWrapTitle) _ = label.addConstraintBotMarginToView(view: viewWrapTitle, commonParrentView: viewWrapTitle) if i == 0 { _ = label.leadingMarginToView(view: viewWrapTitle, commonParrentView: viewWrapTitle) label.textColor = UIColor.forcusColor() } else { _ = label.addConstraintLeftToRight(view: lbTitles.last!, commonParrentView: viewWrapTitle) _ = label.addConstraintEqualWidthToView(view: lbTitles.last!, commonParrentView: viewWrapTitle) } if i == titles.count - 1 { _ = label.trailingMarginToView(view: viewWrapTitle, commonParrentView: viewWrapTitle) } lbTitles.append(label) } } func setupViewForcus() { //setup UI viewForcus.layer.cornerRadius = 5 viewForcus.clipsToBounds = true viewForcus.backgroundColor = UIColor.white //setup constraint let margin: CGFloat = 2 viewForcus.translatesAutoresizingMaskIntoConstraints = false viewWrapTitle.insertSubview(viewForcus, at: 0) leadingConstraintViewForcus = viewForcus.leadingMarginToView( view: viewWrapTitle, commonParrentView: viewWrapTitle, margin: margin) _ = viewForcus.addConstraintTopMarginToView( view: viewWrapTitle, commonParrentView: viewWrapTitle, margin: margin) _ = viewForcus.addConstraintBotMarginToView( view: viewWrapTitle, commonParrentView: viewWrapTitle, margin: -margin) _ = viewForcus.addConstraintEqualWidthToView(view: lbTitles.first!, commonParrentView: viewWrapTitle, margin: -margin) } func setupGestureForLabel(label: UILabel) { let tap = UITapGestureRecognizer(target: self, action: #selector(self.labelDidClick(sender:))) label.addGestureRecognizer(tap) label.isUserInteractionEnabled = true } func labelDidClick(sender: UIGestureRecognizer) { //move viewForcus to label position guard let label = sender.view as? UILabel else { return } let index = CGFloat(lbTitles.index(of: label)!) let width = viewWrapTitle.frame.width/4 var constant = width * index if constant == 0 { constant += 2 } leadingConstraintViewForcus.constant = constant UIView.animate(withDuration: 0.5, animations: { self.layoutIfNeeded() }) { (finish) in let convertIndex = Int(index) let title = self.titles[convertIndex] self.delegate?.bookingNavigationBarDidChangeIndex(sender: self, title: title, index: convertIndex) } _ = lbTitles.map { $0.textColor = UIColor.inforcusColor() } label.textColor = UIColor.forcusColor() } } fileprivate extension UILabel { func setup() { textColor = UIColor.white textAlignment = .center font = self.font.withSize(13) } func setStyle(isForcus: Bool) { if isForcus { textColor = UIColor.forcusColor() } else { textColor = UIColor.inforcusColor() } } } fileprivate extension UIColor { static func forcusColor() -> UIColor { return UIColor.RGB(red: 21, green: 180, blue: 241) } static func inforcusColor() -> UIColor { return UIColor.white } }
b7538b6066778cd64324481f084dcd27
34.106952
89
0.573953
false
false
false
false
swifties/swift-io
refs/heads/master
Sources/SwiftIO/reader/InputStreamReader.swift
apache-2.0
1
/** 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. Created by [email protected] on 31/07/16. */ import Foundation /** Reader to read Strings from InputStream */ public class InputStreamReader: Reader, CustomStringConvertible { ///Byte Order Masks for UTF-16 little endian ///SeeAlso: [wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark) static let UTF16LE_BOM: [UInt8] = [0xFF, 0xFE] ///Byte Order Masks for UTF-16 big endian ///SeeAlso: [wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark) static let UTF16BE_BOM: [UInt8] = [0xFE, 0xFF] ///Byte Order Masks for UTF-32 little endian ///SeeAlso: [wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark) static let UTF32LE_BOM: [UInt8] = [0xFF, 0xFE, 0x00, 0x00] ///Byte Order Masks for UTF-32 big endian ///SeeAlso: [wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark) static let UTF32BE_BOM: [UInt8] = [0x00, 0x00, 0xFE, 0xFF] let stream: InputStream let streamDescription: String let bufferSize: Int let dataUnitSize: Int var data: [UInt8] var buffer: [UInt8] var encoding: String.Encoding var firstData: Bool /** Initializer to read strings from the stream - Parameter stream: Stream to read the data from. Stream will be opened if necessary. - Parameter encoding: Encoding of the data. DEFAULT_ENCODING by default. - Parameter bufferSize: Buffer size to use. DEFAULT_BUFFER_SIZE by default, minimum MINIMUM_BUFFER_SIZE. - Parameter description: Description to be shown at errors etc. For example file path, http address etc. - SeeAlso: DEFAULT_ENCODING - SeeAlso: DEFAULT_BUFFER_SIZE - SeeAlso: MINIMUM_BUFFER_SIZE - Note: Stream is closed by calling close() at deinit(). */ public init(_ stream: InputStream, encoding: String.Encoding = DEFAULT_ENCODING, bufferSize: Int = DEFAULT_BUFFER_SIZE, description: String? = nil) { self.stream = stream self.encoding = encoding self.dataUnitSize = { switch encoding { case String.Encoding.utf32, String.Encoding.utf32LittleEndian, String.Encoding.utf32BigEndian: return 4 case String.Encoding.utf16, String.Encoding.utf16LittleEndian, String.Encoding.utf16BigEndian: return 2 default: return 1 } }() //make the buffer size a number aligned to dataUnitSize bytes self.bufferSize = Int(max(bufferSize, MINIMUM_BUFFER_SIZE) / dataUnitSize) * dataUnitSize self.streamDescription = description ?? stream.description self.firstData = true self.data = [UInt8]() self.buffer = [UInt8](repeating: 0, count: self.bufferSize) if(stream.streamStatus == .notOpen) { self.stream.open() } } /** Analyze data header for BOM sequences - SeeAlso: [Wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark). */ private func analyzeBOM() throws -> Int { if(encoding == .utf16) { //need to specify utf16 encoding reading BOM if(buffer.starts(with: InputStreamReader.UTF16LE_BOM)) { encoding = String.Encoding.utf16LittleEndian return InputStreamReader.UTF16LE_BOM.count } else if(buffer.starts(with: InputStreamReader.UTF16BE_BOM)) { encoding = String.Encoding.utf16BigEndian return InputStreamReader.UTF16BE_BOM.count } throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: "\(description): UTF-16 data without BOM. Please Use UTF-16LE or UTF-16BE instead.") } else if (encoding == .utf32) { //need to specify utf32 encoding reading BOM if(buffer.starts(with: InputStreamReader.UTF32LE_BOM)) { encoding = String.Encoding.utf32LittleEndian return InputStreamReader.UTF32LE_BOM.count } else if(buffer.starts(with: InputStreamReader.UTF32BE_BOM)) { encoding = String.Encoding.utf32BigEndian return InputStreamReader.UTF32BE_BOM.count } throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: "\(description): UTF-32 data without BOM. Please Use UTF-32LE or UTF-32BE instead.") } return 0 } /** Reads next String from the stream. Max String size retrieved is influenced by buffer size and encoding set in the initializer. - Returns: Next string from the stream. Empty String can be returned from the reader - which means more data will be read from the stream on next iteration of read(). Nil when at the end of the stream. - Throws: Exception if read error occurs. */ public func read() throws -> String? { if(stream.streamStatus == .atEnd) { return nil } //read from the stream let count = stream.read(&buffer, maxLength: buffer.count) if(count == -1) { //when error or when stream already closed throw IOException.ErrorReadingFromStream(error: stream.streamError, description: description) } //for first piece of data we need to analyze BOM if(firstData) { var skipBytes = 0 firstData = false skipBytes = try analyzeBOM() data = Array(buffer[skipBytes ..< count]) } else { data.append(contentsOf: buffer.prefix(count)) } //try to read the string from buffer if let string = String(bytes: data, encoding: encoding), !string.isEmpty { //if OK, clear the buffer and return the String data.removeAll(keepingCapacity: true) return string } else { //we are somewhere in the middle of the encoded characters //try to decrement the size of data we use for conversion to String var size = data.count - dataUnitSize while(size > 0) { if let string = String(bytes: data[0 ..< size], encoding: encoding), string.characters.count > 0 { data = Array(data.suffix(from: size)) return string } //try to decrement more size -= dataUnitSize } } if(data.count > bufferSize) { //could not find any string in the data //see: InputStreamReaderTests.test_NoString() throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: description) } //return an empty string - the data will continue to float on next read return "" } /** Closes the stream and releases any system resources associated with it. Once the stream has been closed, further reads will throw an IOException. Closing a previously closed stream has no effect. */ public func close() { stream.close() } /** Returns text description of the Stream. Description can be passed to the Reader initialized. - Return: Text description of the Stream. */ public var description: String { return "\(type(of: self)): \(streamDescription)" } deinit { close() } }
45e191f9ed6486bf667b4e335686a086
35.69163
174
0.600432
false
false
false
false
acastano/tabs-scrolling-controller
refs/heads/master
Tabs/Tabs/Controllers/Selector/SelectorViewController.swift
apache-2.0
1
import UIKit class SelectorViewController: UIViewController { private let buttonTab1 = UIButton() private let buttonTab2 = UIButton() private let bottomBorder1 = UIView() private let bottomBorder2 = UIView() weak var delegate: TabsSelectorDelegate? override func viewDidLoad() { super.viewDidLoad() setupViews() setupHierarchy() setupConstraints() } private func setupViews() { buttonTab1.setTitle(NSLocalizedString("Tab1", comment: ""), for: .normal) buttonTab1.addTarget(self, action: #selector(tab1Tapped), for: .touchUpInside) buttonTab2.setTitle(NSLocalizedString("Tab2", comment: ""), for: .normal) buttonTab2.addTarget(self, action: #selector(tab2Tapped), for: .touchUpInside) bottomBorder1.backgroundColor = .yellow bottomBorder2.backgroundColor = .yellow bottomBorder1.isHidden = false bottomBorder2.isHidden = true buttonTab1.setTitleColor(UIColor(white: 1, alpha: 0.7), for: .normal) buttonTab1.setTitleColor(.white, for: .selected) buttonTab2.setTitleColor(UIColor(white: 1, alpha: 0.7), for: .normal) buttonTab2.setTitleColor(.white, for: .selected) buttonTab1.isSelected = true buttonTab2.isSelected = false } private func setupHierarchy() { view.addSubview(buttonTab1) view.addSubview(buttonTab2) view.addSubview(bottomBorder1) view.addSubview(bottomBorder2) } private func setupConstraints() { buttonTab1.equalWidthTo(buttonTab2) buttonTab1.horizontalSpaceToView(buttonTab2) buttonTab1.pinToSuperview([.left, .top, .bottom]) buttonTab2.pinToSuperview([.right, .top, .bottom]) bottomBorder1.equalWidthTo(buttonTab1) bottomBorder2.equalWidthTo(buttonTab2) bottomBorder1.alignHorizontalCenter(withView: buttonTab1) bottomBorder2.alignHorizontalCenter(withView: buttonTab2) bottomBorder1.addHeightConstraint(withConstant: 3) bottomBorder2.addHeightConstraint(withConstant: 3) bottomBorder1.pinToSuperviewBottom() bottomBorder2.pinToSuperviewBottom() } @objc func tab1Tapped() { delegate?.tabsSelectorDelegateDidSelect(index: 0) bottomBorder1.isHidden = false bottomBorder2.isHidden = true buttonTab1.isSelected = true buttonTab2.isSelected = false } @objc func tab2Tapped() { delegate?.tabsSelectorDelegateDidSelect(index: 1) bottomBorder1.isHidden = true bottomBorder2.isHidden = false buttonTab1.isSelected = false buttonTab2.isSelected = true } } extension SelectorViewController: TabsSelectorComponent { var height: CGFloat { return 48.0 } var viewController: UIViewController { return self } }
da6cac0d1c1a231f7e85f6772f608144
27.91
86
0.679004
false
false
false
false
warnerbros/cpe-manifest-ios-experience
refs/heads/master
Source/In-Movie Experience/ImageSceneDetailCollectionViewCell.swift
apache-2.0
1
// // ImageSceneDetailCollectionViewCell.swift // import Foundation import UIKit class ImageSceneDetailCollectionViewCell: SceneDetailCollectionViewCell { static let NibName = "ImageSceneDetailCollectionViewCell" static let NibNameClipShare = "ClipShareSceneDetailCollectionViewCell" static let ReuseIdentifier = "ImageSceneDetailCollectionViewCellReuseIdentifier" static let ClipShareReuseIdentifier = "ClipShareSceneDetailCollectionViewCellReuseIdentifier" @IBOutlet weak private var imageView: UIImageView! @IBOutlet weak private var playButton: UIButton! @IBOutlet weak private var extraDescriptionLabel: UILabel! private var imageURL: URL? { set { if let url = newValue { imageView.sd_setImage(with: url) } else { imageView.sd_cancelCurrentImageLoad() imageView.image = nil imageView.backgroundColor = UIColor.clear } } get { return nil } } override func timedEventDidChange() { super.timedEventDidChange() imageURL = timedEvent?.thumbnailImageURL playButton.isHidden = timedEvent == nil || (!timedEvent!.isType(.video) && !timedEvent!.isType(.clipShare)) } override func prepareForReuse() { super.prepareForReuse() imageURL = nil playButton.isHidden = true } override func layoutSubviews() { super.layoutSubviews() imageView.contentMode = .scaleAspectFill } }
b9854cc3ec7e5f4c14a1325713abfb7e
27.145455
115
0.667313
false
false
false
false
silence0201/Swift-Study
refs/heads/master
AdvancedSwift/可选值/A Tour of Optional Techniques - Asserting in Debug Builds.playgroundpage/Contents.swift
mit
1
/*: ### Asserting in Debug Builds Still, choosing to crash even on release builds is quite a bold move. Often, you might prefer to assert during debug and test builds, but in production, you'd substitute a valid default value — perhaps zero or an empty array. Enter the interrobang operator, `!?`. We define this operator to assert on failed unwraps and also to substitute a default value when the assertion doesn't trigger in release mode: */ //#-editable-code infix operator !? func !?<T: ExpressibleByIntegerLiteral> (wrapped: T?, failureText: @autoclosure () -> String) -> T { assert(wrapped != nil, failureText()) return wrapped ?? 0 } //#-end-editable-code /*: Now, the following will assert while debugging but print `0` in release: */ //#-editable-code let s = "20" let i = Int(s) !? "Expecting integer, got \"\(s)\"" //#-end-editable-code /*: Overloading for other literal convertible protocols enables a broad coverage of types that can be defaulted: */ //#-editable-code func !?<T: ExpressibleByArrayLiteral> (wrapped: T?, failureText: @autoclosure () -> String) -> T { assert(wrapped != nil, failureText()) return wrapped ?? [] } func !?<T: ExpressibleByStringLiteral> (wrapped: T?, failureText: @autoclosure () -> String) -> T { assert(wrapped != nil, failureText) return wrapped ?? "" } //#-end-editable-code /*: And for when you want to provide a different explicit default, or for non-standard types, we can define a version that takes a pair — the default and the error text: */ //#-editable-code func !?<T>(wrapped: T?, nilDefault: @autoclosure () -> (value: T, text: String)) -> T { assert(wrapped != nil, nilDefault().text) return wrapped ?? nilDefault().value } // Asserts in debug, returns 5 in release Int(s) !? (5, "Expected integer") //#-end-editable-code /*: Since optionally chained method calls on methods that return `Void` return `Void?`, you can also write a non-generic version to detect when an optional chain hits a `nil`, resulting in a no-op: */ //#-editable-code func !?(wrapped: ()?, failureText: @autoclosure () -> String) { assert(wrapped != nil, failureText) } //#-end-editable-code /*: ``` swift-example var output: String? = nil output?.write("something") !? "Wasn't expecting chained nil here" ``` There are three ways to halt execution. The first option, `fatalError`, takes a message and stops execution unconditionally. The second option, `assert`, checks a condition and a message and stops execution if the condition evaluates to `false`. In release builds, the `assert` gets removed — the condition isn't checked (and execution is never halted). The third option is `precondition`, which has the same interface as `assert`, but doesn't get removed from release builds, so if the condition evaluates to `false`, execution is stopped. */
83e7de7d30c98a1c636221211d4280f8
26.509615
80
0.702202
false
false
false
false
devmynd/harbor
refs/heads/develop
Harbor/BuildViewModel.swift
mit
1
import Cocoa struct BuildViewModel { let build: Build let projectId: Int init(build: Build, projectId: Int) { self.build = build self.projectId = projectId } // // MARK: display // var message: String { get { return self.build.message != nil ? self.build.message! : "Unknown" } } var buildUrl: String { get { return "https://codeship.com/projects/\(projectId)/builds/\(build.id!)" } } func authorshipInformation() -> String { let dateString = self.dateString() if let name = self.build.gitHubUsername { return "By \(name) at \(dateString)" } else { return "Started at \(dateString)" } } fileprivate func dateString() -> String { guard let date = self.build.startedAt else { return "Unknown Date" } // TODO: date formatters are expensive (on iOS at least) so it might be worth // caching this let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/YY 'at' hh:mm a" return dateFormatter.string(from: date as Date) } // // MARK: Actions // func openBuildUrl() { let buildURL = URL(string: self.buildUrl)! let workspace = NSWorkspace.shared() workspace.open(buildURL) } }
93ced6718b7582e410f2376ea5a21d8d
20.892857
83
0.634584
false
true
false
false
HarveyHu/PoolScoreboard
refs/heads/master
Pool Scoreboard/Pool Scoreboard/Utils.swift
mit
1
// // Utils.swift // eBike // // Created by HarveyHu on 3/3/16. // Copyright © 2016 HarveyHu. All rights reserved. // import UIKit import RxSwift import RxCocoa func prettyLog(_ message: String = "", file:String = #file, function:String = #function, line:Int = #line) { print("\((file as NSString).lastPathComponent)(\(line)) \(function) \(message)") } func dismissViewController(viewController: UIViewController, animated: Bool) { if viewController.isBeingDismissed || viewController.isBeingPresented { DispatchQueue.main.async { dismissViewController(viewController: viewController, animated: animated) } return } if viewController.presentingViewController != nil { viewController.dismiss(animated: animated, completion: nil) } } func getFrameAvoidStatusBar(frame: CGRect) -> CGRect { let statusBarHeight = UIApplication.shared.statusBarFrame.height let windowFrame = CGRect(x: frame.origin.x, y: statusBarHeight, width: frame.width, height: frame.height - statusBarHeight) return windowFrame } func presentAlert(viewController: UIViewController, title: String, message: String) { #if os(iOS) let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in }) if let presentedVC = viewController.presentedViewController, presentedVC is UIAlertController { presentedVC.dismiss(animated: false, completion: { viewController.present(alertView, animated: true, completion: nil) }) } else { viewController.present(alertView, animated: true, completion: nil) } #endif } func presentAlert(title: String = "", message: String) { #if os(iOS) let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in }) if let rootViewController = UIApplication.shared.keyWindow?.rootViewController { rootViewController.present(alertView, animated: true, completion: nil) } #endif } func presentAlert(title: String = "", message: String, okHandler: (() -> Void)?, cancelHandler: (() -> Void)?) { #if os(iOS) let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in cancelHandler?() }) alertView.addAction(UIAlertAction(title: "OK", style: .default) { _ in okHandler?() }) if let rootViewController = UIApplication.shared.keyWindow?.rootViewController { rootViewController.present(alertView, animated: true, completion: nil) } #endif } func getRandomNumber(digit: UInt32) -> UInt32 { return (arc4random() % digit * 10) } func getCachedImage(imageName: String) -> UIImage? { let imagePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! if FileManager.default.fileExists(atPath: imagePath) { if let image = UIImage(contentsOfFile: imagePath + imageName) { return image } } return nil } func cacheImage(imageName: String, image: UIImage) -> Bool { guard let range = imageName.range(of: ".") else { prettyLog("have no extFileName") return false } var imageData: Data? let extFileName = imageName[range.upperBound...].lowercased() if extFileName == "png" { imageData = image.pngData() } else if extFileName == "jpg" { imageData = image.jpegData(compressionQuality: 0) } if let data = imageData { let imagePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! do { try data.write(to: URL(string: imagePath + imageName)!, options: .atomicWrite) } catch let error { prettyLog("\(error)") return false } return true } return false } func getFileNameFromUrl(urlString: String) -> String? { let reversedString = String(urlString.reversed()) guard let range = reversedString.range(of: "/") else { prettyLog("have no extFileName") return nil } let reversedSubstring = reversedString[..<range.lowerBound] return String(reversedSubstring.reversed()) }
0b7d3410bb81e555ce846f9a247024da
33.401515
127
0.65316
false
false
false
false
yonadev/yona-app-ios
refs/heads/develop
Yona/Yona/Goal.swift
mpl-2.0
1
// // Goals.swift // Yona // // Created by Ben Smith on 12/04/16. // Copyright © 2016 Yona. All rights reserved. // import Foundation struct Goal { var goalID: String? var GoalName: String? var maxDurationMinutes: Int! var selfLinks: String? var editLinks: String? var activityCategoryLink: String? var goalType: String? var zones:[String] = [] var spreadCells : [Int] = [] var isMandatory: Bool? var isHistoryItem : Bool! init(goalData: BodyDataDictionary, activities: [Activities]) { if let links = goalData[YonaConstants.jsonKeys.linksKeys] as? [String: AnyObject]{ if let edit = links[YonaConstants.jsonKeys.editLinkKeys] as? [String: AnyObject], let editLink = edit[YonaConstants.jsonKeys.hrefKey] as? String{ self.editLinks = editLink } if let selfLink = links[YonaConstants.jsonKeys.selfLinkKeys] as? [String:AnyObject], let href = selfLink[YonaConstants.jsonKeys.hrefKey] as? String{ self.selfLinks = href if let lastPath = URL(string: href)?.lastPathComponent { self.goalID = lastPath } } if let activityCategoryLink = links[YonaConstants.jsonKeys.yonaActivityCategory] as? [String:AnyObject], let href = activityCategoryLink[YonaConstants.jsonKeys.hrefKey] as? String{ self.activityCategoryLink = href for activity in activities { if let activityCategoryLink = activity.selfLinks, self.activityCategoryLink == activityCategoryLink { self.GoalName = activity.activityCategoryName } } } } if let zones = goalData[YonaConstants.jsonKeys.zones] as? NSArray { for zone in zones { self.zones.append(zone as! String) } } if let spreds = goalData[YonaConstants.jsonKeys.spredCells] as? NSArray { for data in spreds { self.spreadCells.append(data as! Int) } } if let maxDurationMinutes = goalData[YonaConstants.jsonKeys.maxDuration] as? Int { self.maxDurationMinutes = maxDurationMinutes } else { self.maxDurationMinutes = 0 } if let goalType = goalData[YonaConstants.jsonKeys.goalType] as? String { self.goalType = goalType } if let history = goalData[YonaConstants.jsonKeys.historyItem] as? Bool { isHistoryItem = history } else { isHistoryItem = false } //if goal is of type no go, it has no max minutes, and is type budgetgoal, then mandatory is true if self.maxDurationMinutes == 0 && self.goalType == GoalType.BudgetGoalString.rawValue { self.isMandatory = true self.goalType = GoalType.NoGoGoalString.rawValue } else { //else it is not nogo so mandatory is false self.isMandatory = false } } }
91d2a7e4ead2a051a3308ae3191c1e67
39.554217
125
0.550505
false
false
false
false
hyperconnect/Bond
refs/heads/master
Bond/Bond+Foundation.swift
mit
1
// // Bond+Foundation.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 private var XXContext = 0 @objc private class DynamicKVOHelper: NSObject { let listener: AnyObject -> Void weak var object: NSObject? let keyPath: String init(keyPath: String, object: NSObject, listener: AnyObject -> Void) { self.keyPath = keyPath self.object = object self.listener = listener super.init() self.object?.addObserver(self, forKeyPath: keyPath, options: .New, context: &XXContext) } deinit { object?.removeObserver(self, forKeyPath: keyPath) } override dynamic func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if context == &XXContext { if let newValue: AnyObject = change[NSKeyValueChangeNewKey] { listener(newValue) } } } } @objc private class DynamicNotificationCenterHelper: NSObject { let listener: NSNotification -> Void init(notificationName: String, object: AnyObject?, listener: NSNotification -> Void) { self.listener = listener super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNotification:", name: notificationName, object: object) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } dynamic func didReceiveNotification(notification: NSNotification) { listener(notification) } } public func dynamicObservableFor<T>(object: NSObject, #keyPath: String, #defaultValue: T) -> Dynamic<T> { let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath) let value: T = (keyPathValue != nil) ? (keyPathValue as? T)! : defaultValue let dynamic = InternalDynamic(value) let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) { [unowned dynamic] (v: AnyObject) -> Void in dynamic.updatingFromSelf = true if v is NSNull { dynamic.value = defaultValue } else { dynamic.value = (v as? T)! } dynamic.updatingFromSelf = false } dynamic.retain(helper) return dynamic } public func dynamicObservableFor<T>(object: NSObject, #keyPath: String, #from: AnyObject? -> T, #to: T -> AnyObject?) -> Dynamic<T> { let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath) let dynamic = InternalDynamic(from(keyPathValue)) let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) { [unowned dynamic] (v: AnyObject?) -> Void in dynamic.updatingFromSelf = true dynamic.value = from(v) dynamic.updatingFromSelf = false } let feedbackBond = Bond<T>() { [weak object] value in if let object = object { object.setValue(to(value), forKey: keyPath) } } dynamic.bindTo(feedbackBond, fire: false, strongly: false) dynamic.retain(feedbackBond) dynamic.retain(helper) return dynamic } public func dynamicObservableFor<T>(notificationName: String, #object: AnyObject?, #parser: NSNotification -> T) -> InternalDynamic<T> { let dynamic: InternalDynamic<T> = InternalDynamic() let helper = DynamicNotificationCenterHelper(notificationName: notificationName, object: object) { [unowned dynamic] notification in dynamic.updatingFromSelf = true dynamic.value = parser(notification) dynamic.updatingFromSelf = false } dynamic.retain(helper) return dynamic } public extension Dynamic { public class func asObservableFor(object: NSObject, keyPath: String, defaultValue: T) -> Dynamic<T> { let dynamic: Dynamic<T> = dynamicObservableFor(object, keyPath: keyPath, defaultValue: defaultValue) return dynamic } public class func asObservableFor(notificationName: String, object: AnyObject?, parser: NSNotification -> T) -> Dynamic<T> { let dynamic: InternalDynamic<T> = dynamicObservableFor(notificationName, object: object, parser: parser) return dynamic } }
783deeacf897db40578d5485aa48163f
33.530612
162
0.720449
false
false
false
false
api-ai/api-ai-cocoa-swift
refs/heads/master
AI/src/JSON.swift
apache-2.0
2
// // JSON.swift // AI // // Created by Kuragin Dmitriy on 06/11/15. // Copyright © 2015 Kuragin Dmitriy. All rights reserved. // import Foundation typealias JSONAny = AnyObject typealias JSONObject = [String: AnyObject] typealias JSONArray = [AnyObject] typealias JSONString = String typealias JSONNumber = NSNumber typealias JSONNull = NSNull enum JSON { case object(JSONObject) case array(JSONArray) case number(JSONNumber) case jString(JSONString) case null case none init(_ object: JSONAny?) { self.init(object: object) } init(object: JSONAny?) { if let object = object { switch object { case let object as JSONObject: self = .object(object) case let object as JSONArray: self = .array(object) case let object as JSONNumber: self = .number(object) case let object as JSONString: self = .jString(object) case _ as JSONNull: self = .null default: self = .none } } else { self = .none } } subscript(index: Int) -> JSON { get { if case .array(let array) = self { if index >= 0 && index < array.count { return JSON(array[index]) } return .none } return .none } } subscript(key: String) -> JSON { get { if case .object(let object) = self { return JSON(object[key]) } return .none } } } extension JSON { var string: String? { if case .jString(let object) = self { return object } return .none } var int: Int? { if case .number(let object) = self { return object.intValue } return .none } }
ca0243fcfa34ad0ec9859284227acd8f
21.096774
58
0.481752
false
false
false
false
biohazardlover/ROer
refs/heads/master
Roer/Map+DatabaseRecord.swift
mit
1
import CoreData import CoreSpotlight import MobileCoreServices extension Map { class func map(_ mapName: String, inContext context: NSManagedObjectContext) -> Map? { let request = NSFetchRequest<Map>(entityName: "Map") request.predicate = NSPredicate(format: "mapName == %@", mapName) let map = (try? context.fetch(request))?.first return map } var monsters: [DatabaseRecordCellInfo] { guard let monsterSpawnGroups = monsterSpawnGroups else { return [] } var monsters = [DatabaseRecordCellInfo]() for monsterSpawnGroup in monsterSpawnGroups { guard let monster = monsterSpawnGroup.monster else { continue } monsters.append((monster, monsterSpawnGroup.displaySpawn)) } return monsters } } extension Map { var monsterSpawnGroups: [MonsterSpawnGroup]? { guard let mapName = mapName else { return nil } let fetchRequest = NSFetchRequest<MonsterSpawn>(entityName: "MonsterSpawn") fetchRequest.predicate = NSPredicate(format: "mapName == %@", mapName) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "monsterID", ascending: true)] guard let monsterSpawns = (try? managedObjectContext?.fetch(fetchRequest)) ?? nil else { return nil } return MonsterSpawnGroup.monsterSpawnGroupsWithMonsterSpawns(monsterSpawns) } } extension Map: DatabaseRecord { var smallImageURL: URL? { guard let mapName = mapName else { return nil } return URL(string: "http://file5.ratemyserver.net/maps/\(mapName).gif") } var largeImageURL: URL? { guard let mapName = mapName else { return nil } return URL(string: "http://file5.ratemyserver.net/maps_xl/\(mapName).gif") } var displayName: String? { return mapName } var recordDetails: DatabaseRecordDetails { var recordDetails = DatabaseRecordDetails() recordDetails.appendTitle("Map.Monster".localized, section: .databaseRecords(monsters)) return recordDetails } func correspondingDatabaseRecord(in managedObjectContext: NSManagedObjectContext) -> DatabaseRecord? { guard let mapName = mapName else { return nil } let request = NSFetchRequest<Map>(entityName: "Map") request.predicate = NSPredicate(format: "%K == %@", "mapName", mapName) let results = try? managedObjectContext.fetch(request) return results?.first } } extension Map: Searchable { var searchableItem: CSSearchableItem { let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String) searchableItemAttributeSet.title = mapName searchableItemAttributeSet.contentDescription = nil searchableItemAttributeSet.thumbnailData = nil return CSSearchableItem(uniqueIdentifier: "Map/" + (mapName ?? ""), domainIdentifier: nil, attributeSet: searchableItemAttributeSet) } }
14d0108f35749df8843cbe840b6abaa2
33.366667
140
0.662464
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/QuartzDemo/Controllers/PatternController.swift
mit
2
// // PatternController.swift // QuartzDemo // // Created by 伯驹 黄 on 2017/4/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class PatternController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let quartzPatternView = QuartzPatternView() view.addSubview(quartzPatternView) quartzPatternView.translatesAutoresizingMaskIntoConstraints = false quartzPatternView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true quartzPatternView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true quartzPatternView.topAnchor.constraint(equalTo: view.safeTopAnchor).isActive = true quartzPatternView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor).isActive = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
7a8a6511474f458ebea0e0d5e383f753
31.607143
97
0.736035
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/Potatso/Sync/SyncManager.swift
mit
1
// // SyncManager.swift // Potatso // // Created by LEI on 8/2/16. // Copyright © 2016 TouchingApp. All rights reserved. // import Foundation import CloudKit public enum SyncServiceType: String { case None case iCloud } public protocol SyncServiceProtocol { func setup(_ completion: ((Error?) -> Void)?) func sync(_ manually: Bool, completion: ((Error?) -> Void)?) func stop() } open class SyncManager { static let shared = SyncManager() open static let syncServiceChangedNotification = "syncServiceChangedNotification" fileprivate var services: [SyncServiceType: SyncServiceProtocol] = [:] fileprivate static let serviceTypeKey = "serviceTypeKey" fileprivate(set) var syncing = false var currentSyncServiceType: SyncServiceType { get { if let raw = UserDefaults.standard.object(forKey: SyncManager.serviceTypeKey) as? String, let type = SyncServiceType(rawValue: raw) { return type } return .None } set(new) { guard currentSyncServiceType != new else { return } getCurrentSyncService()?.stop() UserDefaults.standard.set(new.rawValue, forKey: SyncManager.serviceTypeKey) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: SyncManager.syncServiceChangedNotification), object: nil) } } init() { } func getCurrentSyncService() -> SyncServiceProtocol? { return getSyncService(forType: currentSyncServiceType) } func getSyncService(forType type: SyncServiceType) -> SyncServiceProtocol? { if let service = services[type] { return service } let s: SyncServiceProtocol switch type { case .iCloud: s = ICloudSyncService() default: return nil } services[type] = s return s } func showSyncVC(inVC vc:UIViewController? = nil) { guard let currentVC = vc ?? UIApplication.shared.keyWindow?.rootViewController else { return } let syncVC = SyncVC() currentVC.show(syncVC, sender: self) } } extension SyncManager { func setupNewService(_ type: SyncServiceType, completion: ((Error?) -> Void)?) { if let service = getSyncService(forType: type) { service.setup(completion) } else { completion?(nil) } } func setup(_ completion: ((Error?) -> Void)?) { getCurrentSyncService()?.setup(completion) } func sync(_ manually: Bool = false, completion: ((Error?) -> Void)? = nil) { if let service = getCurrentSyncService() { syncing = true NotificationCenter.default.post(name: Notification.Name(rawValue: SyncManager.syncServiceChangedNotification), object: nil) service.sync(manually) { [weak self] error in self?.syncing = false NotificationCenter.default.post(name: Notification.Name(rawValue: SyncManager.syncServiceChangedNotification), object: nil) completion?(error) } } } }
f76d86c07ebff41c102afea2d8de934c
28.697248
145
0.618783
false
false
false
false
LinDing/Positano
refs/heads/master
Positano/Helpers/YepSoundEffect.swift
mit
1
// // YepSoundEffect.swift // Yep // // Created by zhowkevin on 15/9/23. // Copyright © 2015年 Catch Inc. All rights reserved. // import AudioToolbox.AudioServices final public class YepSoundEffect: NSObject { var soundID: SystemSoundID? public init(fileURL: URL) { super.init() var theSoundID: SystemSoundID = 0 let error = AudioServicesCreateSystemSoundID(fileURL as CFURL, &theSoundID) if (error == kAudioServicesNoError) { soundID = theSoundID } else { fatalError("YepSoundEffect: init failed!") } } deinit { if let soundID = soundID { AudioServicesDisposeSystemSoundID(soundID) } } public func play() { if let soundID = soundID { AudioServicesPlaySystemSound(soundID) } } }
2c078ac4d40eea5ed277027fccbd25d0
20.794872
83
0.604706
false
false
false
false
susan335/CoreDataSample
refs/heads/master
CoreDataSample/CoreDataSample/AppDelegate.swift
unlicense
1
// // AppDelegate.swift // CoreDataSample // // Created by Susan on 2014/12/01. // Copyright (c) 2014年 watanave. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let mainManagedObjectContext = self.managedObjectContext; let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType); privateManagedObjectContext.parentContext = mainManagedObjectContext; privateManagedObjectContext.performBlock({ () -> Void in for _ in 0...100 { sleep(2); // 非同期処理っぽく、遅延させてみる let entityDiscription = NSEntityDescription.entityForName("Model", inManagedObjectContext: privateManagedObjectContext); let fetchRequest = NSFetchRequest(); fetchRequest.entity = entityDiscription; var error: NSError? = nil; let count = privateManagedObjectContext.countForFetchRequest(fetchRequest, error: &error); for index in count...count+10 { let managedObject: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Model", inManagedObjectContext: privateManagedObjectContext); let model = managedObject as CoreDataSample.Model; model.someDataA = "String Data \(index)"; model.someDataB = index; } privateManagedObjectContext.save(&error); mainManagedObjectContext?.performBlock({ () -> Void in self.saveContext(); }) } }); return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "jp.watanave.CoreDataSample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CoreDataSample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataSample.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } // ### NSManagedObjectContextに親子関係を作る場合は明示的に MainQueueConcurrencyTypeの指定が必要 // var managedObjectContext = NSManagedObjectContext() var managedObjectContext = NSManagedObjectContext(concurrencyType : .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
5fb622bcf0e1448960cc4d59a8ec4285
53.172414
290
0.692298
false
false
false
false
xedin/swift
refs/heads/master
stdlib/public/core/Random.swift
apache-2.0
1
//===--- Random.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// A type that provides uniformly distributed random data. /// /// When you call methods that use random data, such as creating new random /// values or shuffling a collection, you can pass a `RandomNumberGenerator` /// type to be used as the source for randomness. When you don't pass a /// generator, the default `SystemRandomNumberGenerator` type is used. /// /// When providing new APIs that use randomness, provide a version that accepts /// a generator conforming to the `RandomNumberGenerator` protocol as well as a /// version that uses the default system generator. For example, this `Weekday` /// enumeration provides static methods that return a random day of the week: /// /// enum Weekday: CaseIterable { /// case sunday, monday, tuesday, wednesday, thursday, friday, saturday /// /// static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday { /// return Weekday.allCases.randomElement(using: &generator)! /// } /// /// static func random() -> Weekday { /// var g = SystemRandomNumberGenerator() /// return Weekday.random(using: &g) /// } /// } /// /// Conforming to the RandomNumberGenerator Protocol /// ================================================ /// /// A custom `RandomNumberGenerator` type can have different characteristics /// than the default `SystemRandomNumberGenerator` type. For example, a /// seedable generator can be used to generate a repeatable sequence of random /// values for testing purposes. /// /// To make a custom type conform to the `RandomNumberGenerator` protocol, /// implement the required `next()` method. Each call to `next()` must produce /// a uniform and independent random value. /// /// Types that conform to `RandomNumberGenerator` should specifically document /// the thread safety and quality of the generator. public protocol RandomNumberGenerator { /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: An unsigned 64-bit random value. mutating func next() -> UInt64 } extension RandomNumberGenerator { /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: A random value of `T`. Bits are randomly distributed so that /// every value of `T` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>() -> T { return T._random(using: &self) } /// Returns a random value that is less than the given upper bound. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Parameter upperBound: The upper bound for the randomly generated value. /// Must be non-zero. /// - Returns: A random value of `T` in the range `0..<upperBound`. Every /// value in the range `0..<upperBound` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>( upperBound: T ) -> T { _precondition(upperBound != 0, "upperBound cannot be zero.") #if arch(i386) || arch(arm) // TODO(FIXME) SR-10912 let tmp = (T.max % upperBound) + 1 let range = tmp == upperBound ? 0 : tmp var random: T = 0 repeat { random = next() } while random < range return random % upperBound #else var random: T = next() var m = random.multipliedFullWidth(by: upperBound) if m.low < upperBound { let t = (0 &- upperBound) % upperBound while m.low < t { random = next() m = random.multipliedFullWidth(by: upperBound) } } return m.high #endif } } /// The system's default source of random data. /// /// When you generate random values, shuffle a collection, or perform another /// operation that depends on random data, this type is the generator used by /// default. For example, the two method calls in this example are equivalent: /// /// let x = Int.random(in: 1...100) /// var g = SystemRandomNumberGenerator() /// let y = Int.random(in: 1...100, using: &g) /// /// `SystemRandomNumberGenerator` is automatically seeded, is safe to use in /// multiple threads, and uses a cryptographically secure algorithm whenever /// possible. /// /// Platform Implementation of `SystemRandomNumberGenerator` /// ======================================================== /// /// While the system generator is automatically seeded and thread-safe on every /// platform, the cryptographic quality of the stream of random data produced by /// the generator may vary. For more detail, see the documentation for the APIs /// used by each platform. /// /// - Apple platforms use `arc4random_buf(3)`. /// - Linux platforms use `getrandom(2)` when available; otherwise, they read /// from `/dev/urandom`. @frozen public struct SystemRandomNumberGenerator : RandomNumberGenerator { /// Creates a new instance of the system's default random number generator. @inlinable public init() { } /// Returns a value from a uniform, independent distribution of binary data. /// /// - Returns: An unsigned 64-bit random value. @inlinable public mutating func next() -> UInt64 { var random: UInt64 = 0 swift_stdlib_random(&random, MemoryLayout<UInt64>.size) return random } }
16192883377bf4cf76c91a6f63a51703
38.932099
95
0.666254
false
false
false
false
Anish-kumar-dev/Spring
refs/heads/master
07-day/07-day/Spring/SpringLabel.swift
apache-2.0
67
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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 public class SpringLabel: UILabel, Springable { @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var animation: String = "" @IBInspectable public var force: CGFloat = 1 @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var repeatCount: Float = 1 @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 @IBInspectable public var curve: String = "" public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring : Spring = Spring(self) override public func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } public override func layoutSubviews() { super.layoutSubviews() spring.customLayoutSubviews() } public func animate() { self.spring.animate() } public func animateNext(completion: () -> ()) { self.spring.animateNext(completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: () -> ()) { self.spring.animateToNext(completion) } }
2d32b52edb57ab679fbd8cedb9ce1fe3
36.416667
81
0.71036
false
false
false
false
burningmantech/ranger-ims-mac
refs/heads/master
Incidents/DateTime.swift
apache-2.0
1
// // DateTime.swift // Incidents // // © 2015 Burning Man and its contributors. All rights reserved. // See the file COPYRIGHT.md for terms. // import Foundation struct DateTime: CustomStringConvertible, Comparable, Hashable { private static let rfc3339Formatter = makeRFC3339Formatter() private static let shortFormatter = makeFormatter("dd/HH:mm") private static let formatter = makeFormatter("yyyy-MM-dd HH:mm") private static let longFormatter = makeFormatter("EEEE, MMMM d, yyyy HH:mm:ss zzz") static func fromRFC3339String(string: String) -> DateTime { let nsDate = rfc3339Formatter.dateFromString(string) return DateTime(nsDate: nsDate!) } static func now() -> DateTime { return DateTime(nsDate: NSDate()) } private let nsDate: NSDate var hashValue: Int { return nsDate.hashValue } var description: String { return asRFC3339String() } private init(nsDate: NSDate) { self.nsDate = nsDate } func asRFC3339String() -> String { return DateTime.rfc3339Formatter.stringFromDate(nsDate) } func asShortString() -> String { return DateTime.shortFormatter.stringFromDate(nsDate) } func asString() -> String { return DateTime.formatter.stringFromDate(nsDate) } func asLongString() -> String { return DateTime.longFormatter.stringFromDate(nsDate) } } func ==(lhs: DateTime, rhs: DateTime) -> Bool { return lhs.nsDate.isEqualToDate(rhs.nsDate) } func <(lhs: DateTime, rhs: DateTime) -> Bool { return lhs.nsDate.isLessThan(rhs.nsDate) } private func makeRFC3339Formatter() -> NSDateFormatter { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" return formatter } private func makeFormatter(format: String) -> NSDateFormatter { let formatter = NSDateFormatter() formatter.dateFormat = format return formatter }
05e55776613354413b38ecb673169675
21.1875
90
0.671362
false
false
false
false
kevinlindkvist/lind
refs/heads/master
lind/ULCParser.swift
apache-2.0
1
// // UntypedLambdaCalculusParser.swift // lind // // Created by Kevin Lindkvist on 8/29/16. // Copyright © 2016 lindkvist. All rights reserved. // import Result import Foundation private typealias NamingContext = [String:Int] private typealias TermParser = Parser<String.UnicodeScalarView, NamingContext, ULCTerm> private let identifier = _identifier() private func _identifier() -> Parser<String.UnicodeScalarView, NamingContext, String.UnicodeScalarView> { let alphas = CharacterSet.alphanumerics return many1( satisfy { alphas.contains(UnicodeScalar($0.value)!) } ) } private let variable = _variable() private func _variable() -> TermParser { return identifier >>- { (context: NamingContext, t: String.UnicodeScalarView) in let id = String(t) if let index = context[id] { return (pure(.va(id, index)), context) } else { let index = context.count return (pure(.va(id, index)), union(context, [id:index])) } } } private let lambda = _lambda() private func _lambda() -> TermParser { return (char("\\") *> identifier) >>- { (context: NamingContext, identifier: String.UnicodeScalarView) in let boundName = String(identifier) var context = context context.forEach { name, index in return context[name] = index + 1 } context[boundName] = 0 return ((char(".") *> term) >>- { (context: NamingContext, t: ULCTerm) in var context = context context.forEach { name, index in if (index != 0) { context[name] = index - 1 } } context.removeValue(forKey: boundName) return (pure(.abs(boundName, t)), context) }, context) } } private let nonAppTerm = _nonAppTerm() private func _nonAppTerm() -> TermParser { return (char("(") *> term <* char(")")) <|> lambda <|> variable } private let term = _term() private func _term() -> TermParser { return chainl1(p: nonAppTerm, op: char(" ") *> pure( { t1, t2 in .app(t1, t2)})) } private func untypedLambdaCalculus() -> TermParser { return term <* endOfInput() } func parseUntypedLambdaCalculus(_ str: String) -> Result<([String:Int], ULCTerm), ParseError> { switch parseOnly(untypedLambdaCalculus(), input: (str.unicodeScalars, [:])) { case let .success((g, term)): return .success(g, term) case let .failure(error): return .failure(error) } }
a6d23819f9cfead8835ea8ff8695e1f0
29.670886
105
0.638052
false
false
false
false
pixelmaid/palette-knife
refs/heads/master
Palette-Knife/Stroke.swift
mit
2
// // Stroke.swift // Palette-Knife // // Created by JENNIFER MARY JACOBS on 5/5/16. // Copyright © 2016 pixelmaid. All rights reserved. // import Foundation enum DrawError: ErrorType { case InvalidArc } protocol Geometry { func toJSON()->String } struct StoredDrawing:Geometry{ var angle:Float var scaling:Point var position:Point init(position:Point,scaling:Point,angle:Float){ self.angle = angle self.scaling = scaling self.position = position } //todo: create toJSON method func toJSON()->String{ return "placeholder_string" } } // Segment: line segement described as two points struct Segment:Geometry, Equatable { var point:Point; var handleIn: Point; var handleOut: Point; var parent:Stroke?; var index:Int? var diameter = Float(1); var color = Color(r:0,g:0,b:0); var time = Float(0); init(x:Float,y:Float) { self.init(x:x,y:y,hi_x:0,hi_y:0,ho_x:0,ho_y:0) } init(point:Point){ self.init(point:point,handleIn:Point(x: 0, y: 0),handleOut:Point(x: 0, y: 0)) } init(x:Float,y:Float,hi_x:Float,hi_y:Float,ho_x:Float,ho_y:Float){ let point = Point(x:x,y:y) let hI = Point(x: hi_x,y: hi_y) let hO = Point(x: ho_x,y: ho_y) self.init(point:point,handleIn:hI,handleOut:hO) } init(point:Point,handleIn:Point,handleOut:Point) { self.point = point self.handleIn = handleIn self.handleOut = handleOut } func getTimeDelta()->Float{ let prevSeg = self.getPreviousSegment(); if(prevSeg == nil){ return 0; } let currentTime = self.time; let prevTime = prevSeg!.time; return currentTime-prevTime; } func getPreviousSegment()->Segment?{ if(self.parent != nil){ if(self.index>0){ return parent!.segments[self.index!-1] } } return nil } func toJSON()->String{ var string = "{\"point\":{"+self.point.toJSON()+"}," string += "\"time\":"+String(parent!.getTimeElapsed())+"}" return string } } func ==(lhs: Segment, rhs: Segment) -> Bool { return lhs.point == rhs.point } /*class Arc:Geometry { var center:Point var radius:Float var startAngle:Float var endAngle:Float init(center:Point,startAngle:Float,endAngle:Float, radius:Float) { self.center=center self.startAngle = startAngle self.endAngle = endAngle self.radius = radius } convenience init(point:Point,length:Float,angle:Float, radius:Float) { let p2 = point.pointAtDistance(length, a: angle); let p3 = Line(p:point,v:p2,asVector: false).getMidpoint() let centerX = p3.x + sqrt(pow(radius,2)-pow((length/2),2))*(point.y-p2.y)/length let centerY = p3.y + sqrt(pow(radius,2)-pow((length/2),2))*(p2.x-point.x)/length let center = Point(x: centerX, y: centerY) let startAngle = atan2(point.y - center.y, point.x - center.x); let endAngle = atan2(p2.y - center.y, p2.x - center.x); self.init(center:center,startAngle:startAngle,endAngle:endAngle,radius:radius) } convenience init(x1:Float,y1:Float,x2:Float,y2:Float,x3:Float,y3:Float){ let r = Line(px:x1,py: y1,vx: x2,vy: y2,asVector: false) let t = Line(px: x2,py: y2,vx: x3,vy: y3,asVector: false) let rM = r.getSlope(); //let rB = r.getYIntercept(); let tM = t.getSlope(); //let tB = t.getYIntercept(); let r_midpoint = r.getMidpoint(); //let t_midpoint = t.getMidpoint(); let rpM = 0-(1/rM) //let tpM = 0-(1/tM) let rpB = -rpM*r_midpoint.x+r_midpoint.y; let centerX = (rM*tM*(y3-y1)+rM*(x2+x3)-tM*(x1+x2))/(2*(rM-tM)) let centerY = rpM*centerX + rpB let center = Point(x:centerX,y:centerY) let radius = center.dist(Point(x:x1,y:y1)); let startAngle = atan2(y1 - center.y, x1 - center.x); let endAngle = atan2(y3 - center.y, x3 - center.x); self.init(center:center,startAngle:startAngle,endAngle:endAngle,radius:radius) } func toJSON()->String{ let string = "\"center\":{\"x\":"+String(self.point.x)+",\"y\":"+String(self.point.y)+"\"" return string } }*/ // Stroke: Model for storing a stroke object in multiple representations // as a series of segments // as a series of vectors over time class Stroke:TimeSeries, Geometry { var segments = [Segment](); var xBuffer = CircularBuffer(); var yBuffer = CircularBuffer(); var weightBuffer = CircularBuffer(); let id = NSUUID().UUIDString; let gCodeGenerator = GCodeGenerator(); var parentID: String; init(parentID:String){ self.parentID = parentID; super.init(); gCodeGenerator.startNewStroke(); } func addSegment(_segment:Segment)->Segment{ var segment = _segment; segment.parent = self segment.index = self.segments.count; segment.time = Float(0-timer.timeIntervalSinceNow); segments.append(segment) if(segment.getPreviousSegment() != nil){ xBuffer.push(segment.point.x.get(nil)-segment.getPreviousSegment()!.point.x.get(nil)) yBuffer.push(segment.point.y.get(nil)-segment.getPreviousSegment()!.point.y.get(nil)) } else{ xBuffer.push(0); yBuffer.push(0) } gCodeGenerator.drawSegment(segment) return segment } func addSegment(point:Point)->Segment{ let segment = Segment(point:point) return self.addSegment(segment) } func addSegment(point:Point, d:Float)->Segment{ var segment = Segment(point:point) segment.diameter = d weightBuffer.push(d); return self.addSegment(segment) } func addSegment(segments:[Segment])->[Segment]{ for i in 0...segments.count-1{ self.addSegment(segments[i]) } return segments } func getLength()->Float{ var l = Float(0.0); if(segments.count>1){ for i in 1...segments.count-1{ l += segments[i-1].point.dist(segments[i].point) }} return l; } func toJSON()->String{ var string = "segments:[" for i in 0...segments.count-1{ string += "{"+segments[i].toJSON()+"}" if(i<segments.count-1){ string+="," } } string += "]," return string } /*init(fromPoint:Point,angle:Float,length:Float){ self.fromPoint = fromPoint; self.toPoint = fromPoint.pointAtDistance(length,a:angle) } init(center:Point,radius:Float,startAngle:Float,endAngle:Float,clockwise:Bool){ self.center = center self.radius = radius self.startAngle = startAngle self.endAngle = endAngle self.clockwise = clockwise }*/ func lineTo(to:Point) { // Let's not be picky about calling moveTo() first: let seg = Segment(point:to) self.addSegment(seg); } }
ceb4e7bf93a63b21f90d6789d34b7244
25.608541
98
0.56627
false
false
false
false
mibaldi/ChildBeaconApp
refs/heads/publish
ChildBeaconProject/BD/SQLiteDataStore.swift
apache-2.0
1
// // SQLiteDataStore.swift // iosAPP // // Created by mikel balduciel diaz on 17/2/16. // Copyright © 2016 mikel balduciel diaz. All rights reserved. // import Foundation import SQLite enum DataAccessError: ErrorType { case Datastore_Connection_Error case Insert_Error case Delete_Error case Search_Error case Nil_In_Data } class SQLiteDataStore { static let sharedInstance = SQLiteDataStore() let DB: Connection? private init() { var path = "ChildBeacon.sqlite" if let dirs: [NSString] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as [NSString] { let dir = dirs[0] path = dir.stringByAppendingPathComponent("ChildBeacon.sqlite") print(path) } do { DB = try Connection(path) } catch _ { DB = nil } } func createTables() throws{ do { try BeaconDataHelper.createTable() try BeaconGroupDataHelper.createTable() try NotificationsDataHelper.createTable() }catch{ throw DataAccessError.Datastore_Connection_Error } } }
c564242b154a6a9cdce23d37fe2ca04e
25.102041
149
0.608764
false
false
false
false
firebase/firebase-ios-sdk
refs/heads/master
ReleaseTooling/Sources/ManifestParser/GHAMatrixSpecCollector.swift
apache-2.0
1
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ArgumentParser import FirebaseManifest import Foundation import Utils /// SDKPodspec is to help generate an array of podspec in json file, e.g. /// ``` output.json /// [{"podspec":"FirebaseABTesting.podspec"},{"podspec":"FirebaseAnalytics.podspec"}] /// ``` struct SDKPodspec: Codable { let podspec: String let allowWarnings: Bool } struct GHAMatrixSpecCollector { var SDKRepoURL: URL var outputSpecFileURL: URL var excludedSDKs: [String] = [] func getPodsInManifest(_ manifest: Manifest) -> [String: SDKPodspec] { var podsMap: [String: SDKPodspec] = [:] for pod in manifest.pods { podsMap[pod.name] = SDKPodspec(podspec: pod.name, allowWarnings: pod.allowWarnings) } return podsMap } func getAllPodspecs() -> [SDKPodspec] { var output: [SDKPodspec] = [] let fileManager = FileManager.default let podsMap = getPodsInManifest(FirebaseManifest.shared) do { let fileURLs = try fileManager.contentsOfDirectory( at: SDKRepoURL, includingPropertiesForKeys: nil ) for url in fileURLs { let fileNameComponents = url.lastPathComponent.components(separatedBy: ".") if fileNameComponents.count > 1, fileNameComponents[1] == "podspec" { let specName = fileNameComponents[0] if let spec = podsMap[specName] { output.append(spec) } else { print("\(specName) is not in manifiest") } } } } catch { print("Error while enumerating files: \(error.localizedDescription)") } return output } func generateMatrixJson(to filePath: URL) throws { let sdkPodspecs: [SDKPodspec] = getAllPodspecs() // Trim whitespaces so the GitHub Actions matrix can read. let str = try String( decoding: JSONEncoder().encode(sdkPodspecs), as: UTF8.self ) try str.trimmingCharacters(in: .whitespacesAndNewlines).write( to: filePath, atomically: true, encoding: String.Encoding.utf8 ) } }
5f8518679717dab57a2024c5168f6107
30.46988
89
0.677259
false
false
false
false
RoverPlatform/rover-ios
refs/heads/master
Sources/Experiences/Services/SessionController.swift
apache-2.0
2
// // SessionController.swift // Rover // // Created by Sean Rucker on 2018-05-21. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import UIKit /// Responsible for emitting events including a view duration for open and closable registered sessions, such as /// Experience Viewed or Screen Viewed. Includes some basic hysteresis for ensuring that rapidly re-opened sessions are /// aggregated into a single session. class SessionController { /// The shared singleton sesion controller. static let shared = SessionController() private let keepAliveTime: Int = 10 private var observers: [NSObjectProtocol] = [] private init() { #if swift(>=4.2) let didBecomeActiveNotification = UIApplication.didBecomeActiveNotification let willResignActiveNotification = UIApplication.willResignActiveNotification #else let didBecomeActiveNotification = NSNotification.Name.UIApplicationDidBecomeActive let willResignActiveNotification = NSNotification.Name.UIApplicationWillResignActive #endif observers = [ NotificationCenter.default.addObserver( forName: didBecomeActiveNotification, object: nil, queue: OperationQueue.main, using: { _ in self.entries.forEach { $0.value.session.start() } } ), NotificationCenter.default.addObserver( forName: willResignActiveNotification, object: nil, queue: OperationQueue.main, using: { _ in self.entries.forEach { $0.value.session.end() } } ) ] } deinit { observers.forEach(NotificationCenter.default.removeObserver) } // MARK: Registration private struct Entry { let session: Session var isUnregistered = false init(session: Session) { self.session = session } } private var entries = [String: Entry]() func registerSession(identifier: String, completionHandler: @escaping (Double) -> Void) { if var entry = entries[identifier] { entry.session.start() if entry.isUnregistered { entry.isUnregistered = false entries[identifier] = entry } return } let session = Session(keepAliveTime: keepAliveTime) { result in completionHandler(result.duration) if let entry = self.entries[identifier], entry.isUnregistered { self.entries[identifier] = nil } } session.start() entries[identifier] = Entry(session: session) } func unregisterSession(identifier: String) { if var entry = entries[identifier] { entry.isUnregistered = true entries[identifier] = entry entry.session.end() } } } private class Session { let keepAliveTime: Int struct Result { var startedAt: Date var endedAt: Date var duration: Double { return endedAt.timeIntervalSince1970 - startedAt.timeIntervalSince1970 } init(startedAt: Date, endedAt: Date) { self.startedAt = startedAt self.endedAt = endedAt } init(startedAt: Date) { let now = Date() self.init(startedAt: startedAt, endedAt: now) } } private let completionHandler: (Result) -> Void enum State { case ready case started(startedAt: Date) case ending(startedAt: Date, timer: Timer) case complete(result: Result) } private(set) var state: State = .ready { didSet { if case .complete(let result) = state { completionHandler(result) } } } init(keepAliveTime: Int, completionHandler: @escaping (Result) -> Void) { self.keepAliveTime = keepAliveTime self.completionHandler = completionHandler } func start() { switch state { case .ready, .complete: let now = Date() state = .started(startedAt: now) case .started: break case let .ending(startedAt, timer): timer.invalidate() state = .started(startedAt: startedAt) } } func end() { switch state { case .ready, .ending, .complete: break case .started(let startedAt): // Capture endedAt now, as opposed to when the timer fires let endedAt = Date() // Start a background task before running the timer to allow it to run its course if the app is backgrounded while ending the session. var backgroundTaskID: UIBackgroundTaskIdentifier! backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Keep Alive Timer") { [weak self] in self?.finish(endedAt: endedAt) UIApplication.shared.endBackgroundTask(backgroundTaskID) } let timeInterval = TimeInterval(keepAliveTime) let timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { [weak self] _ in self?.finish(endedAt: endedAt) UIApplication.shared.endBackgroundTask(backgroundTaskID) }) state = .ending(startedAt: startedAt, timer: timer) } } func finish(endedAt: Date) { switch state { case let .ending(startedAt, timer): timer.invalidate() let result = Result(startedAt: startedAt, endedAt: endedAt) state = .complete(result: result) default: break } } }
07feae2478b2514d710c05068077eac9
30.229592
146
0.56298
false
false
false
false
legendecas/Rocket.Chat.iOS
refs/heads/sdk
Rocket.Chat.Shared/Managers/UserManager.swift
mit
1
// // UserManager.swift // Rocket.Chat // // Created by Rafael K. Streit on 8/17/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation /// A manager that manages all user related actions public class UserManager: SocketManagerInjected { /// Subscribe active users' changes public func changes() { let request = [ "msg": "sub", "name": "activeUsers", "params": [] ] as [String : Any] socketManager.send(request) { _ in } } /// Subscribe user data changes public func userDataChanges() { let request = [ "msg": "sub", "name": "userData", "params": [] ] as [String : Any] socketManager.send(request) { _ in } } /// Set current user's statue /// /// - Parameters: /// - status: new status /// - completion: will be called after action completion public func setUserStatus(status: UserStatus, completion: @escaping MessageCompletion) { let request = [ "msg": "method", "method": "UserPresence:setDefaultStatus", "params": [status.rawValue] ] as [String : Any] socketManager.send(request) { (response) in completion(response) } } /// Set current user's presence /// /// - Parameters: /// - status: new presence /// - completion: will be called after action completion public func setUserPresence(status: UserPresence, completion: @escaping MessageCompletion) { let method = "UserPresence:".appending(status.rawValue) let request = [ "msg": "method", "method": method, "params": [] ] as [String : Any] socketManager.send(request) { (response) in completion(response) } } }
d44ca9cd7bd383e7d7c9bcb4d3d0f8ce
25.152778
96
0.555497
false
false
false
false
hydrantwiki/hwIOSApp
refs/heads/master
hwIOSApp/hwIOSApp/AveragingLocationManager.swift
mit
1
// // LocationAverager.swift // hwIOSApp // // Created by Brian Nelson on 10/23/15. // Copyright © 2015 Brian Nelson. All rights reserved. // import Foundation import CoreLocation public class AveragingLocationManager: NSObject, CLLocationManagerDelegate { public var QuantityCollected:Int = 0 var cancelCollecting:Bool var locationManager : CLLocationManager var quantityToCollect : Int var periodBetween : Double var warmUpPeriod : Int var alreadyRequested:Bool var allowed:Bool = false var locationAverage:LocationAverage; var completionHandlers:[(Int, Location?)->Void] = [] public var locationAverageUpdated:ILocationUpdated? = nil var completionFired:Bool = false; override init() { locationManager = CLLocationManager(); quantityToCollect = 10; periodBetween = 1; warmUpPeriod = 1; cancelCollecting = false; locationAverage = LocationAverage(); alreadyRequested = false; } public func Start(completion: (count:Int, location:Location?) ->Void) { completionHandlers.append(completion) locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; if (CLLocationManager.authorizationStatus() == .NotDetermined) { locationManager.requestWhenInUseAuthorization(); } else if (CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse) { allowed = true; } if (allowed) { NSTimer.scheduledTimerWithTimeInterval( 0, target: self, selector: #selector(AveragingLocationManager.RequestLocation), userInfo: nil, repeats: false); } } public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if (status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse) { allowed = true; } else { allowed = false; } } public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { locationAverage.add(location.coordinate.latitude, longitude: location.coordinate.longitude, elevation: location.altitude, accuracy:location.horizontalAccuracy) QuantityCollected += 1 if (QuantityCollected <= quantityToCollect) { if (locationAverageUpdated != nil) { let currentAverage:Location? = locationAverage.getAverage(); if (currentAverage != nil) { locationAverageUpdated!.NewLocation( QuantityCollected, latitude:currentAverage!.latitude!, longitude:currentAverage!.longitude!, elevation:currentAverage!.elevation!, accuracy:currentAverage!.accuracy!); } } } if (QuantityCollected < quantityToCollect) { NSTimer.scheduledTimerWithTimeInterval( 0, target: self, selector: #selector(AveragingLocationManager.RequestLocation), userInfo: nil, repeats: false); } else { if (completionHandlers.count>0) { locationManager.stopUpdatingLocation(); if (!completionFired) { completionFired = true; completionHandlers[0](QuantityCollected, locationAverage.getAverage()); } } } } } public func RequestLocation() { NSThread.sleepForTimeInterval(0.5); locationManager.requestLocation(); } public func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Failed to find user's location: \(error.localizedDescription)"); locationManager.requestLocation(); } }
d881c18961b28ea9117d9c2411e7f095
31.234483
119
0.556602
false
false
false
false
haddenkim/dew
refs/heads/master
Sources/App/Controllers/PlaceController.swift
mit
1
// // PlaceController.swift // dew // // Created by Hadden Kim on 4/26/17. // // import Vapor import HTTP final class PlaceController { // READ all static func findAll(_ request: Request) throws -> ResponseRepresentable { let placesJSON = try Place.findAll() .map { Place($0) } .filter { $0 != nil } .map { $0! } .map { try $0.makeJSON() } return JSON(placesJSON) } // READ one static func findOne(_ request: Request, _ place: Place) throws -> ResponseRepresentable { return try Response(status: .ok, json: place.makeJSON()) } // CREATE static func create(_ request: Request) throws -> ResponseRepresentable { guard let json = request.json, let place = try? Place.init(json: json) else { throw Abort.badRequest } try place.save() return try Response(status: .created, json: place.makeJSON()) } // UPDATE static func update(_ request: Request, _ place: Place) throws -> ResponseRepresentable { guard let json = request.json, let updatedPlace = try? Place.init(json: json) else { throw Abort.badRequest } // update "allowed" changes place.name = updatedPlace.name place.coordinate = updatedPlace.coordinate place.openHours = updatedPlace.openHours try place.save() return try Response(status: .ok, json: place.makeJSON()) } // DELETE static func delete(_ request: Request, _ place: Place) throws -> ResponseRepresentable { try place.delete() return Response(status: .noContent) } }
8619abb3a0beb5d41d106bb8a73e1b84
24.753623
93
0.563309
false
false
false
false
aborren/dnaXtensions
refs/heads/master
dnaXtensions/Classes/UIColor+dnaXtensions.swift
mit
1
// // UIColor+dnaXtensions.swift // // Created by Dan Isacson on 2017-02-23. // // import UIKit extension UIColor { /// Returns a lighter version of the color. *Optional*: Specify an amount between 0.0 and 1.0. public func lighter(_ amount : CGFloat = 0.25) -> UIColor { return hueColorWithBrightnessAmount(1 + amount) } /// Returns a darker version of the color. *Optional*: Specify an amount between 0.0 and 1.0. public func darker(_ amount : CGFloat = 0.25) -> UIColor { return hueColorWithBrightnessAmount(1 - amount) } fileprivate func hueColorWithBrightnessAmount(_ amount: CGFloat) -> UIColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * amount, alpha: alpha ) } else { return self } } }
3b8f74b170b9205f6ef6e6b6a32f86dc
29.571429
108
0.619626
false
false
false
false
netprotections/atonecon-ios
refs/heads/master
AtoneCon/Sources/AtoneCon.swift
mit
1
// // AtoneCon.swift // AtoneCon // // Created by Pham Ngoc Hanh on 6/30/17. // Copyright © 2017 AsianTech Inc. All rights reserved. // import Foundation import ObjectMapper import SAMKeychain public protocol AtoneConDelegate: class { func atoneCon(atoneCon: AtoneCon, didReceivePaymentEvent event: AtoneCon.PaymentEvent) } final public class AtoneCon { // MARK: - Singleton public static let shared = AtoneCon() // MARK: - Properties internal var options: AtoneCon.Options? public weak var delegate: AtoneConDelegate? fileprivate var payment: Payment? // MARK: - Public Functions public func config(_ options: Options) { self.options = options } public func performPayment(_ payment: Payment) { guard let root = UIApplication.shared.delegate?.window??.rootViewController else { return } guard NetworkReachabilityManager()?.isReachable == true else { let error: [String: Any] = [Define.String.Key.title: Define.String.network, Define.String.Key.message: Define.String.Error.network] let event = PaymentEvent.failed(error) delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: event) return } self.payment = payment let paymentController = PaymentViewController(payment: payment) paymentController.delegate = self root.present(paymentController, animated: true, completion: nil) } public func dismiss(completion: (() -> Void)? = nil) { let root = UIApplication.shared.delegate?.window??.rootViewController root?.dismiss(animated: true, completion: completion) } public func resetAuthenToken() { Session.shared.clearCredential() } } extension AtoneCon { public enum PaymentEvent { case authenticated(String?, String?) case cancelled case finished([String: Any]?) case failed([String: Any]?) case error(String?, String?, String?) } } internal enum AtoneConError: Error { case option([String: Any]?) case payment([String: Any]?) } extension AtoneCon: PaymentViewControllerDelegate { func controller(_ controller: PaymentViewController, didReceiveScriptEvent event: ScriptEvent) { switch event { case .authenticated(let token, let userNo): delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: .authenticated(token, userNo)) case .failed(let response): delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: .failed(response)) case .cancelled: delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: .cancelled) case .succeeded(let response): delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: .finished(response)) case .error(let name, let message, let errors): delegate?.atoneCon(atoneCon: self, didReceivePaymentEvent: .error(name, message, errors)) } } }
e04d64a2f84cd3ccba47a02e112a096d
34.046512
101
0.668215
false
false
false
false
tekgrrl/office-mover-5000
refs/heads/master
ios/OfficeMover5000/OfficeMover5000/ViewController.swift
mit
1
// // ViewController.swift // OfficeMover500 // // Created by Katherine Fang on 10/28/14. // Copyright (c) 2014 Firebase. All rights reserved. // import UIKit let OfficeMoverFirebaseUrl = "https://<your-firebase>.firebaseio.com" class ViewController: RoomViewController { let ref = Firebase(url: OfficeMoverFirebaseUrl) let furnitureRef = Firebase(url: "\(OfficeMoverFirebaseUrl)/furniture") let backgroundRef = Firebase(url: "\(OfficeMoverFirebaseUrl)/background") override func viewDidLoad() { super.viewDidLoad() // Load the furniture items from Firebase furnitureRef.observeEventType(.ChildAdded, withBlock: { [unowned self] snapshot in self.refLocations += ["furniture/\(snapshot.name)"] var furniture = Furniture(snap: snapshot) self.createFurnitureView(furniture) }) // Observe bacakground changes backgroundRef.observeEventType(.Value, withBlock: { [unowned self] snapshot in if let background = snapshot.value as? String { self.setBackgroundLocally(background) } }) } // This should take in a Furniture Model whatever that is. // This creates a view as a button, and makes it draggable. func createFurnitureView(furniture: Furniture) { let view = FurnitureView(furniture: furniture) let currentFurnitureRef = furnitureRef.childByAppendingPath(furniture.key) // move the view from a remote update currentFurnitureRef.observeEventType(.Value, withBlock: { snapshot in // check if snapshot.value does not equal NSNull if snapshot.value as? NSNull != NSNull() { var furniture = Furniture(snap: snapshot) view.setViewState(furniture) } }) // delete the view from remote update currentFurnitureRef.observeEventType(.ChildRemoved, withBlock: { snapshot in view.delete() }) // When the furniture moves, update the Firebase view.moveHandler = { top, left in currentFurnitureRef.updateChildValues([ "top": top, "left": left ]) } // When the furniture rotates, update the Firebase view.rotateHandler = { top, left, rotation in currentFurnitureRef.updateChildValues([ "top": top, "left": left, "rotation": rotation ]) } // When the furniture is deleted, update the Firebase view.deleteHandler = { view.delete() currentFurnitureRef.removeValue() } // For desks, when we edit the name on the desk, update the Firebase view.editHandler = { name in currentFurnitureRef.updateChildValues([ "name": name ]) } // When furniture is moved, it should jump to the top view.moveToTopHandler = { currentFurnitureRef.updateChildValues([ "z-index": ++maxZIndex ]) } roomView.addSubview(view) } // Handling adding a new item from the popover menu func addNewItem(type: String) { let itemRef = furnitureRef.childByAutoId() let furniture = Furniture(key: itemRef.name, type: type) itemRef.setValue(furniture.toJson()) } // Handling changing the background from the popover menu func setBackground(type: String) { backgroundRef.setValue(type) } }
6b4307df64efac72bb9786440c075836
32.463636
90
0.593207
false
false
false
false
lukaszwas/mcommerce-api
refs/heads/master
Sources/App/Models/Stripe/Models/ShippingAddress.swift
mit
1
// // ShippingAddress.swift // Stripe // // Created by Anthony Castelli on 4/15/17. // // import Foundation import Vapor /* Shipping Address https://stripe.com/docs/api/curl#charge_object-shipping-address */ public final class ShippingAddress: StripeModelProtocol { public var city: String? public var country: String? public var addressLine1: String? public var addressLine2: String? public var postalCode: String? public var state: String? public init() { } public init(node: Node) throws { self.city = try node.get("city") self.country = try node.get("country") self.addressLine1 = try node.get("line1") self.addressLine2 = try node.get("line2") self.postalCode = try node.get("postal_code") self.state = try node.get("state") } public func makeNode(in context: Context?) throws -> Node { let object: [String : Any?] = [ "city": self.city, "country": self.country, "line1": self.addressLine1, "line2": self.addressLine2, "postal_code": self.postalCode, "state": self.state ] return try Node(node: object) } }
4d44a857269308e253b1b9719c96b0f6
24.183673
64
0.599676
false
false
false
false
tinrobots/CoreDataPlus
refs/heads/master
Tests/NSManagedObjectContextInvestigationTests.swift
mit
1
// CoreDataPlus import CoreData import XCTest final class NSManagedObjectContextInvestigationTests: InMemoryTestCase { /// Investigation test: calling refreshAllObjects calls refreshObject:mergeChanges on all objects in the context. func testInvestigationRefreshAllObjects() throws { let viewContext = container.viewContext let car1 = Car(context: viewContext) car1.numberPlate = "car1" let car2 = Car(context: viewContext) car2.numberPlate = "car2" try viewContext.save() car1.numberPlate = "car1_updated" viewContext.refreshAllObjects() XCTAssertFalse(car1.isFault) XCTAssertTrue(car2.isFault) XCTAssertEqual(car1.numberPlate, "car1_updated") } /// Investigation test: KVO is fired whenever a property changes (even if the object is not saved in the context). func testInvestigationKVO() throws { let context = container.viewContext let expectation = self.expectation(description: "\(#function)\(#line)") let sportCar1 = SportCar(context: context) var count = 0 let token = sportCar1.observe(\.maker, options: .new) { (car, changes) in count += 1 if count == 2 { expectation.fulfill() } } sportCar1.maker = "McLaren" sportCar1.model = "570GT" sportCar1.numberPlate = "203" sportCar1.maker = "McLaren 2" try context.save() waitForExpectations(timeout: 10) token.invalidate() } /// Investigation test: automaticallyMergesChangesFromParent behaviour func testInvestigationAutomaticallyMergesChangesFromParent() throws { // automaticallyMergesChangesFromParent = true do { let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let storeURL = URL.newDatabaseURL(withID: UUID()) try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) let parentContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) parentContext.persistentStoreCoordinator = psc let car1 = Car(context: parentContext) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = UUID().uuidString try parentContext.save() let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext childContext.automaticallyMergesChangesFromParent = true let childCar = try childContext.performAndWaitResult { context -> Car in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") return car } try parentContext.performSaveAndWait { context in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") car.maker = "😀" XCTAssertEqual(car.maker, "😀") } // this will fail without automaticallyMergesChangesFromParent to true childContext.performAndWait { XCTAssertEqual(childCar.maker, "😀") } } // automaticallyMergesChangesFromParent = false do { let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let storeURL = URL.newDatabaseURL(withID: UUID()) try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) let parentContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) parentContext.persistentStoreCoordinator = psc let car1 = Car(context: parentContext) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = UUID().uuidString try parentContext.save() let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext childContext.automaticallyMergesChangesFromParent = false let childCar = try childContext.performAndWaitResult { context -> Car in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") return car } try parentContext.performSaveAndWait { context in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") car.maker = "😀" XCTAssertEqual(car.maker, "😀") } childContext.performAndWait { XCTAssertEqual(childCar.maker, "FIAT") // no changes } } // automaticallyMergesChangesFromParent = true do { let parentContext = container.viewContext let car1 = Car(context: parentContext) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = UUID().uuidString try parentContext.save() let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext childContext.automaticallyMergesChangesFromParent = true let childCar = try childContext.performAndWaitResult { context -> Car in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") return car } try parentContext.performSaveAndWait { context in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") car.maker = "😀" XCTAssertEqual(car.maker, "😀") } // this will fail without automaticallyMergesChangesFromParent to true childContext.performAndWait { XCTAssertEqual(childCar.maker, "😀") } } // automaticallyMergesChangesFromParent = false do { let parentContext = container.viewContext let car1 = Car(context: parentContext) car1.maker = "FIAT" car1.model = "Panda" car1.numberPlate = UUID().uuidString try parentContext.save() let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) childContext.parent = parentContext childContext.automaticallyMergesChangesFromParent = false let childCar = try childContext.performAndWaitResult { context -> Car in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") return car } try parentContext.performSaveAndWait { context in let car = try XCTUnwrap(try Car.existingObject(with: car1.objectID, in: context)) XCTAssertEqual(car.maker, "FIAT") car.maker = "😀" XCTAssertEqual(car.maker, "😀") } childContext.performAndWait { XCTAssertEqual(childCar.maker, "FIAT") // no changes } } } func testInvestigationStalenessInterval() throws { // Given let context = container.viewContext let car = Car(context: context) car.maker = "FIAT" car.model = "Panda" car.numberPlate = UUID().uuidString try context.save() let fiatPredicate = NSPredicate(format: "%K == %@", #keyPath(Car.maker), "FIAT") let result = try Car.batchUpdate(using: context) { $0.resultType = .updatedObjectIDsResultType $0.propertiesToUpdate = [#keyPath(Car.maker): "FCA"] $0.includesSubentities = true $0.predicate = fiatPredicate } XCTAssertEqual(result.updates?.count, 1) // When, Then car.refresh() XCTAssertEqual(car.maker, "FIAT") // When, Then context.refreshAllObjects() XCTAssertEqual(car.maker, "FIAT") // When, Then context.stalenessInterval = 0 // issue a new fetch request instead of using the row cache car.refresh() XCTAssertEqual(car.maker, "FCA") context.stalenessInterval = -1 // default // The default is a negative value, which represents infinite staleness allowed. 0.0 represents “no staleness acceptable”. } func testInvestigationShouldRefreshRefetchedObjectsIsStillBroken() throws { // https://mjtsai.com/blog/2019/10/17/ // I've opened a feedback myself too: FB7419788 // Given let readContext = container.viewContext let writeContext = container.newBackgroundContext() var writeCar: Car? = nil try writeContext.performAndWaitResult { writeCar = Car(context: writeContext) writeCar?.maker = "FIAT" writeCar?.model = "Panda" writeCar?.numberPlate = UUID().uuidString try $0.save() } // When var readEntity: Car? = nil readContext.performAndWait { readEntity = try! readContext.fetch(Car.newFetchRequest()).first! // Initially the attribute should be FIAT XCTAssertNotNil(readEntity) XCTAssertEqual(readEntity?.maker, "FIAT") } try writeContext.performAndWaitResult { writeCar?.maker = "FCA" try $0.save() } // Then readContext.performAndWait { let request = Car.newFetchRequest() request.shouldRefreshRefetchedObjects = true _ = try! readContext.fetch(request) // ⚠️ Now the attribute should be FCA, but it is still FIAT // This should be XCTAssertEqual, XCTAssertNotEqual is used only to make the test pass until // the problem is fixed XCTAssertNotEqual(readEntity?.maker, "FCA") readContext.refresh(readEntity!, mergeChanges: false) // However, manually refreshing does update it to FCA XCTAssertEqual(readEntity?.maker, "FCA") } } func testInvestigationTransientProperties() throws { let container = InMemoryPersistentContainer.makeNew() let viewContext = container.viewContext let car = Car(context: viewContext) car.maker = "FIAT" car.model = "Panda" car.numberPlate = UUID().uuidString car.currentDrivingSpeed = 50 try viewContext.save() XCTAssertEqual(car.currentDrivingSpeed, 50) viewContext.refreshAllObjects() XCTAssertEqual(car.currentDrivingSpeed, 0) car.currentDrivingSpeed = 100 XCTAssertEqual(car.currentDrivingSpeed, 100) viewContext.reset() XCTAssertEqual(car.currentDrivingSpeed, 0) } func testInvestigationTransientPropertiesBehaviorInParentChildContextRelationship() throws { let container = InMemoryPersistentContainer.makeNew() let viewContext = container.viewContext let childContext = viewContext.newBackgroundContext(asChildContext: true) var carID: NSManagedObjectID? let plateNumber = UUID().uuidString let predicate = NSPredicate(format: "%K == %@", #keyPath(Car.numberPlate), plateNumber) childContext.performAndWait { let car = Car(context: $0) car.maker = "FIAT" car.model = "Panda" car.numberPlate = plateNumber car.currentDrivingSpeed = 50 try! $0.save() carID = car.objectID XCTAssertEqual(car.currentDrivingSpeed, 50) print($0.registeredObjects) car.currentDrivingSpeed = 20 // ⚠️ dirting the context again } childContext.performAndWait { print(childContext.registeredObjects) } let id = try XCTUnwrap(carID) let car = try XCTUnwrap(Car.object(with: id, in: viewContext)) XCTAssertEqual(car.maker, "FIAT") XCTAssertEqual(car.model, "Panda") XCTAssertEqual(car.numberPlate, plateNumber) XCTAssertEqual(car.currentDrivingSpeed, 50, "The transient property value should be equal to the one saved by the child context.") try childContext.performAndWait { XCTAssertFalse(childContext.registeredObjects.isEmpty) // ⚠️ this condition is verified only because we have dirted the context after a save let car = try XCTUnwrap($0.object(with: id) as? Car) XCTAssertEqual(car.currentDrivingSpeed, 20) try $0.save() } XCTAssertEqual(car.currentDrivingSpeed, 20, "The transient property value should be equal to the one saved by the child context.") try childContext.performAndWait { XCTAssertTrue(childContext.registeredObjects.isEmpty) // ⚠️ it seems that after a save, the objects are freed unless the context gets dirted again let car = try XCTUnwrap(try Car.fetchUnique(in: $0, where: predicate)) XCTAssertEqual(car.currentDrivingSpeed, 0) } // see testInvestigationContextRegisteredObjectBehaviorAfterSaving } func testInvestigationContextRegisteredObjectBehaviorAfterSaving() throws { let context = container.newBackgroundContext() // A context keeps registered objects until it's dirted try context.performAndWait { let person = Person(context: context) person.firstName = "Alessandro" person.lastName = "Marzoli" try $0.save() let person2 = Person(context: context) person2.firstName = "Andrea" person2.lastName = "Marzoli" // context dirted because person2 isn't yet saved } context.performAndWait { XCTAssertFalse(context.registeredObjects.isEmpty) } try context.performAndWait { try $0.save() // context is no more dirted, everything has been saved } context.performAndWait { XCTAssertTrue(context.registeredObjects.isEmpty) } try context.performAndWait { let person = Person(context: context) person.firstName = "Valedmaro" person.lastName = "Marzoli" try $0.save() // context is no more dirted, everything has been saved } context.performAndWait { XCTAssertTrue(context.registeredObjects.isEmpty) } } func testFetchAsNSArrayUsingBatchSize() throws { // For this investigation you have to enable SQL logs in the test plan (-com.apple.CoreData.SQLDebug 3) let context = container.viewContext context.fillWithSampleData() try context.save() context.reset() // NSFetchedResultsController isn't affected do { let request = Car.fetchRequest() request.addSortDescriptors([NSSortDescriptor(key: #keyPath(Car.maker), ascending: true)]) request.fetchBatchSize = 10 let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) try frc.performFetch() // A SELECT with LIMIT 10 is executed every 10 looped cars ✅ frc.fetchedObjects?.forEach { car in let _ = car as! Car } } // Running a Swift fetch request with a batch size doesn't work, you have to find a way to fallback to Obj-C // https://mjtsai.com/blog/2021/03/31/making-nsfetchrequest-fetchbatchsize-work-with-swift/ // https://developer.apple.com/forums/thread/651325 // This fetch will execute SELECT with LIMIT 10 just one time ✅ // let cars_batchLimit_working = try Car.fetch(in: context) { $0.fetchLimit = 10 } // This fetch will execute SELECT with LIMIT 10 as many times as needed to fetch all the cars ❌ //let cars_batchSize_not_working = try Car.fetch(in: context) { $0.fetchBatchSize = 10 } // cars is a _PFBatchFaultingArray proxy let cars = try Car.fetchNSArray(in: context) { $0.fetchBatchSize = 10 } // This for loop will trigger a SELECT with LIMIT 10 every 10 looped cars. ✅ cars.forEach { car in let _ = car as! Car } // This enumeration will trigger a SELECT with LIMIT 10 every 10 enumerated cars. ✅ cars.enumerateObjects { car, _, _ in let _ = car as! Car } // firstObject will trigger only a single SELECT with LIMIT 10 ✅ let _ = cars.firstObject as! Car } }
3466edb7803d348c15104fdafc20555f
34.681395
152
0.69302
false
false
false
false
lhc70000/iina
refs/heads/develop
iina/QuickSettingViewController.swift
gpl-3.0
1
// // QuickSettingViewController.swift // iina // // Created by lhc on 12/8/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa class QuickSettingViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, SidebarViewController { override var nibName: NSNib.Name { return NSNib.Name("QuickSettingViewController") } let sliderSteps = 24.0 /** Similiar to the one in `PlaylistViewController`. Since IBOutlet is `nil` when the view is not loaded at first time, use this variable to cache which tab it need to switch to when the view is ready. The value will be handled after loaded. */ private var pendingSwitchRequest: TabViewType? /** Tab type. Use TrackType for now. Propobably not a good choice. */ typealias TabViewType = MPVTrack.TrackType weak var player: PlayerCore! weak var mainWindow: MainWindowController! { didSet { self.player = mainWindow.player } } var currentTab: TabViewType = .video var observers: [NSObjectProtocol] = [] @IBOutlet weak var videoTabBtn: NSButton! @IBOutlet weak var audioTabBtn: NSButton! @IBOutlet weak var subTabBtn: NSButton! @IBOutlet weak var tabView: NSTabView! @IBOutlet weak var buttonTopConstraint: NSLayoutConstraint! @IBOutlet weak var videoTableView: NSTableView! @IBOutlet weak var audioTableView: NSTableView! @IBOutlet weak var subTableView: NSTableView! @IBOutlet weak var secSubTableView: NSTableView! @IBOutlet weak var rotateSegment: NSSegmentedControl! @IBOutlet weak var aspectSegment: NSSegmentedControl! @IBOutlet weak var customAspectTextField: NSTextField! @IBOutlet weak var cropSegment: NSSegmentedControl! @IBOutlet weak var speedSlider: NSSlider! @IBOutlet weak var speedSliderIndicator: NSTextField! @IBOutlet weak var speedSliderConstraint: NSLayoutConstraint! @IBOutlet weak var customSpeedTextField: NSTextField! @IBOutlet weak var deinterlaceCheckBtn: NSButton! @IBOutlet weak var brightnessSlider: NSSlider! @IBOutlet weak var contrastSlider: NSSlider! @IBOutlet weak var saturationSlider: NSSlider! @IBOutlet weak var gammaSlider: NSSlider! @IBOutlet weak var hueSlider: NSSlider! @IBOutlet weak var audioDelaySlider: NSSlider! @IBOutlet weak var audioDelaySliderIndicator: NSTextField! @IBOutlet weak var audioDelaySliderConstraint: NSLayoutConstraint! @IBOutlet weak var customAudioDelayTextField: NSTextField! @IBOutlet weak var subLoadSementedControl: NSSegmentedControl! @IBOutlet weak var subDelaySlider: NSSlider! @IBOutlet weak var subDelaySliderIndicator: NSTextField! @IBOutlet weak var subDelaySliderConstraint: NSLayoutConstraint! @IBOutlet weak var customSubDelayTextField: NSTextField! @IBOutlet weak var audioEqSlider1: NSSlider! @IBOutlet weak var audioEqSlider2: NSSlider! @IBOutlet weak var audioEqSlider3: NSSlider! @IBOutlet weak var audioEqSlider4: NSSlider! @IBOutlet weak var audioEqSlider5: NSSlider! @IBOutlet weak var audioEqSlider6: NSSlider! @IBOutlet weak var audioEqSlider7: NSSlider! @IBOutlet weak var audioEqSlider8: NSSlider! @IBOutlet weak var audioEqSlider9: NSSlider! @IBOutlet weak var audioEqSlider10: NSSlider! @IBOutlet weak var subScaleSlider: NSSlider! @IBOutlet weak var subScaleResetBtn: NSButton! @IBOutlet weak var subPosSlider: NSSlider! @IBOutlet weak var subTextColorWell: NSColorWell! @IBOutlet weak var subTextSizePopUp: NSPopUpButton! @IBOutlet weak var subTextBorderColorWell: NSColorWell! @IBOutlet weak var subTextBorderWidthPopUp: NSPopUpButton! @IBOutlet weak var subTextBgColorWell: NSColorWell! @IBOutlet weak var subTextFontBtn: NSButton! var downShift: CGFloat = 0 { didSet { buttonTopConstraint.constant = downShift } } override func viewDidLoad() { super.viewDidLoad() withAllTableViews { (view, _) in view.delegate = self view.dataSource = self view.superview?.superview?.layer?.cornerRadius = 4 } // colors if #available(macOS 10.14, *) { withAllTableViews { tableView, _ in tableView.backgroundColor = NSColor(named: .sidebarTableBackground)! } } if pendingSwitchRequest != nil { switchToTab(pendingSwitchRequest!) pendingSwitchRequest = nil } subLoadSementedControl.image(forSegment: 1)?.isTemplate = true func observe(_ name: Notification.Name, block: @escaping (Notification) -> Void) { observers.append(NotificationCenter.default.addObserver(forName: name, object: player, queue: .main, using: block)) } // notifications observe(.iinaTracklistChanged) { _ in self.withAllTableViews { view, _ in view.reloadData() } } observe(.iinaVIDChanged) { _ in self.videoTableView.reloadData() } observe(.iinaAIDChanged) { _ in self.audioTableView.reloadData() } observe(.iinaSIDChanged) { _ in self.subTableView.reloadData() self.secSubTableView.reloadData() } } // MARK: - Validate UI /** Do syncronization*/ override func viewDidAppear() { // image sub super.viewDidAppear() updateControlsState() } deinit { observers.forEach { NotificationCenter.default.removeObserver($0) } } private func updateControlsState() { updateVideoTabControl() updateAudioTabControl() updateSubTabControl() updateVideoEqState() updateAudioEqState() } private func updateVideoTabControl() { if let index = AppData.aspectsInPanel.index(of: player.info.unsureAspect) { aspectSegment.selectedSegment = index } else { aspectSegment.selectedSegment = -1 } if let index = AppData.cropsInPanel.index(of: player.info.unsureCrop) { cropSegment.selectedSegment = index } else { cropSegment.selectedSegment = -1 } rotateSegment.selectSegment(withTag: AppData.rotations.index(of: player.info.rotation) ?? -1) deinterlaceCheckBtn.state = player.info.deinterlace ? .on : .off let speed = player.mpv.getDouble(MPVOption.PlaybackControl.speed) customSpeedTextField.doubleValue = speed let sliderValue = log(speed / AppData.minSpeed) / log(AppData.maxSpeed / AppData.minSpeed) * sliderSteps speedSlider.doubleValue = sliderValue redraw(indicator: speedSliderIndicator, constraint: speedSliderConstraint, slider: speedSlider, value: "\(customSpeedTextField.stringValue)x") } private func updateAudioTabControl() { let audioDelay = player.mpv.getDouble(MPVOption.Audio.audioDelay) audioDelaySlider.doubleValue = audioDelay customAudioDelayTextField.doubleValue = audioDelay redraw(indicator: audioDelaySliderIndicator, constraint: audioDelaySliderConstraint, slider: audioDelaySlider, value: "\(customAudioDelayTextField.stringValue)s") } private func updateSubTabControl() { if let currSub = player.info.currentTrack(.sub) { subScaleSlider.isEnabled = !currSub.isImageSub // FIXME: CollorWells cannot be disable? let enableTextSettings = !(currSub.isAssSub || currSub.isImageSub) [subTextColorWell, subTextSizePopUp, subTextBgColorWell, subTextBorderColorWell, subTextBorderWidthPopUp, subTextFontBtn].forEach { $0.isEnabled = enableTextSettings } } let currSubScale = player.mpv.getDouble(MPVOption.Subtitles.subScale).clamped(to: 0.1...10) let displaySubScale = Utility.toDisplaySubScale(fromRealSubScale: currSubScale) subScaleSlider.doubleValue = displaySubScale + (displaySubScale > 0 ? -1 : 1) let subDelay = player.mpv.getDouble(MPVOption.Subtitles.subDelay) subDelaySlider.doubleValue = subDelay customSubDelayTextField.doubleValue = subDelay redraw(indicator: subDelaySliderIndicator, constraint: subDelaySliderConstraint, slider: subDelaySlider, value: "\(customSubDelayTextField.stringValue)s") let currSubPos = player.mpv.getInt(MPVOption.Subtitles.subPos) subPosSlider.intValue = Int32(currSubPos) let fontSize = player.mpv.getInt(MPVOption.Subtitles.subFontSize) subTextSizePopUp.selectItem(withTitle: fontSize.description) let borderWidth = player.mpv.getDouble(MPVOption.Subtitles.subBorderSize) subTextBorderWidthPopUp.selectItem(at: -1) subTextBorderWidthPopUp.itemArray.forEach { item in if borderWidth == Double(item.title) { subTextBorderWidthPopUp.select(item) } } } private func updateVideoEqState() { brightnessSlider.intValue = Int32(player.info.brightness) contrastSlider.intValue = Int32(player.info.contrast) saturationSlider.intValue = Int32(player.info.saturation) gammaSlider.intValue = Int32(player.info.gamma) hueSlider.intValue = Int32(player.info.hue) } private func updateAudioEqState() { if let filters = player.info.audioEqFilters { withAllAudioEqSliders { slider in if let gain = filters[slider.tag]?.stringFormat.dropLast().split(separator: "=").last { slider.doubleValue = Double(gain) ?? 0 } else { slider.doubleValue = 0 } } } else { withAllAudioEqSliders { $0.doubleValue = 0 } } } func reload() { guard isViewLoaded else { return } if currentTab == .audio { audioTableView.reloadData() updateAudioTabControl() updateAudioEqState() } else if currentTab == .video { videoTableView.reloadData() updateVideoTabControl() updateVideoEqState() } else if currentTab == .sub { subTableView.reloadData() secSubTableView.reloadData() updateSubTabControl() } } // MARK: - Switch tab /** Switch tab (call from other objects) */ func pleaseSwitchToTab(_ tab: TabViewType) { if isViewLoaded { switchToTab(tab) } else { // cache the request pendingSwitchRequest = tab } } /** Switch tab (for internal call) */ private func switchToTab(_ tab: TabViewType) { let button: NSButton switch tab { case .video: button = videoTabBtn case .audio: button = audioTabBtn case .sub: button = subTabBtn default: return } tabBtnAction(button) } // MARK: - NSTableView delegate func numberOfRows(in tableView: NSTableView) -> Int { if tableView == videoTableView { return player.info.videoTracks.count + 1 } else if tableView == audioTableView { return player.info.audioTracks.count + 1 } else if tableView == subTableView || tableView == secSubTableView { return player.info.subTracks.count + 1 } else { return 0 } } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { // get track according to tableview // row=0: <None> row=1~: tracks[row-1] let track: MPVTrack? let activeId: Int let columnName = tableColumn?.identifier if tableView == videoTableView { track = row == 0 ? nil : player.info.videoTracks[at: row-1] activeId = player.info.vid! } else if tableView == audioTableView { track = row == 0 ? nil : player.info.audioTracks[at: row-1] activeId = player.info.aid! } else if tableView == subTableView { track = row == 0 ? nil : player.info.subTracks[at: row-1] activeId = player.info.sid! } else if tableView == secSubTableView { track = row == 0 ? nil : player.info.subTracks[at: row-1] activeId = player.info.secondSid! } else { return nil } // return track data if columnName == .isChosen { let isChosen = track == nil ? (activeId == 0) : (track!.id == activeId) return isChosen ? Constants.String.dot : "" } else if columnName == .trackName { return track?.infoString ?? Constants.String.trackNone } else if columnName == .trackId { return track?.idString } return nil } func tableViewSelectionDidChange(_ notification: Notification) { withAllTableViews { (view, type) in if view.numberOfSelectedRows > 0 { // note that track ids start from 1 let subId = view.selectedRow > 0 ? player.info.trackList(type)[view.selectedRow-1].id : 0 self.player.setTrack(subId, forType: type) view.deselectAll(self) } } // Revalidate layout and controls updateControlsState() } private func withAllTableViews(_ block: (NSTableView, MPVTrack.TrackType) -> Void) { block(audioTableView, .audio) block(subTableView, .sub) block(secSubTableView, .secondSub) block(videoTableView, .video) } private func withAllAudioEqSliders(_ block: (NSSlider) -> Void) { [audioEqSlider1, audioEqSlider2, audioEqSlider3, audioEqSlider4, audioEqSlider5, audioEqSlider6, audioEqSlider7, audioEqSlider8, audioEqSlider9, audioEqSlider10].forEach { block($0) } } // MARK: - Actions // MARK: Tab buttons @IBAction func tabBtnAction(_ sender: NSButton) { tabView.selectTabViewItem(at: sender.tag) [videoTabBtn, audioTabBtn, subTabBtn].forEach { Utility.setActive($0, false) } Utility.setActive(sender, true) reload() } // MARK: Video tab @IBAction func aspectChangedAction(_ sender: NSSegmentedControl) { let aspect = AppData.aspectsInPanel[sender.selectedSegment] player.setVideoAspect(aspect) mainWindow.displayOSD(.aspect(aspect)) } @IBAction func cropChangedAction(_ sender: NSSegmentedControl) { let cropStr = AppData.cropsInPanel[sender.selectedSegment] player.setCrop(fromString: cropStr) mainWindow.displayOSD(.crop(cropStr)) } @IBAction func rotationChangedAction(_ sender: NSSegmentedControl) { let value = AppData.rotations[sender.selectedSegment] player.setVideoRotate(value) mainWindow.displayOSD(.rotate(value)) } @IBAction func customAspectEditFinishedAction(_ sender: AnyObject?) { let value = customAspectTextField.stringValue if value != "" { aspectSegment.setSelected(false, forSegment: aspectSegment.selectedSegment) player.setVideoAspect(value) mainWindow.displayOSD(.aspect(value)) } } private func redraw(indicator: NSTextField, constraint: NSLayoutConstraint, slider: NSSlider, value: String) { indicator.stringValue = value let offset: CGFloat = 6 let sliderInnerWidth = slider.frame.width - offset * 2 constraint.constant = offset + sliderInnerWidth * CGFloat((slider.doubleValue - slider.minValue) / (slider.maxValue - slider.minValue)) view.layout() } @IBAction func speedChangedAction(_ sender: NSSlider) { // Each step is 64^(1/24) // 0 1 .. 7 8 9 .. 24 // 0.250x 0.297x .. 0.841x 1.000x 1.189x .. 16.00x let eventType = NSApp.currentEvent!.type if eventType == .leftMouseDown { sender.allowsTickMarkValuesOnly = true } if eventType == .leftMouseUp { sender.allowsTickMarkValuesOnly = false } let sliderValue = sender.doubleValue let value = AppData.minSpeed * pow(AppData.maxSpeed / AppData.minSpeed, sliderValue / sliderSteps) customSpeedTextField.doubleValue = value player.setSpeed(value) redraw(indicator: speedSliderIndicator, constraint: speedSliderConstraint, slider: speedSlider, value: "\(customSpeedTextField.stringValue)x") } @IBAction func customSpeedEditFinishedAction(_ sender: NSTextField) { if sender.stringValue.isEmpty { sender.stringValue = "1" } let value = customSpeedTextField.doubleValue let sliderValue = log(value / AppData.minSpeed) / log(AppData.maxSpeed / AppData.minSpeed) * sliderSteps speedSlider.doubleValue = sliderValue if player.info.playSpeed != value { player.setSpeed(value) } redraw(indicator: speedSliderIndicator, constraint: speedSliderConstraint, slider: speedSlider, value: "\(sender.stringValue)x") if let window = sender.window { window.makeFirstResponder(window.contentView) } } @IBAction func deinterlaceBtnAction(_ sender: AnyObject) { player.toggleDeinterlace(deinterlaceCheckBtn.state == .on) } @IBAction func equalizerSliderAction(_ sender: NSSlider) { let type: PlayerCore.VideoEqualizerType switch sender { case brightnessSlider: type = .brightness case contrastSlider: type = .contrast case saturationSlider: type = .saturation case gammaSlider: type = .gamma case hueSlider: type = .hue default: return } player.setVideoEqualizer(forOption: type, value: Int(sender.intValue)) } // use tag for buttons @IBAction func resetEqualizerBtnAction(_ sender: NSButton) { let type: PlayerCore.VideoEqualizerType let slider: NSSlider? switch sender.tag { case 0: type = .brightness slider = brightnessSlider case 1: type = .contrast slider = contrastSlider case 2: type = .saturation slider = saturationSlider case 3: type = .gamma slider = gammaSlider case 4: type = .hue slider = hueSlider default: return } player.setVideoEqualizer(forOption: type, value: 0) slider?.intValue = 0 } @IBAction func cropBtnAction(_ sender: AnyObject) { mainWindow.hideSideBar { self.mainWindow.enterInteractiveMode(.crop, selectWholeVideoByDefault: true) } } // MARK: Audio tab @IBAction func loadExternalAudioAction(_ sender: NSButton) { let currentDir = player.info.currentURL?.deletingLastPathComponent() Utility.quickOpenPanel(title: "Load external audio file", chooseDir: false, dir: currentDir) { url in self.player.loadExternalAudioFile(url) self.audioTableView.reloadData() } } @IBAction func audioDelayChangedAction(_ sender: NSSlider) { let eventType = NSApp.currentEvent!.type if eventType == .leftMouseDown { sender.allowsTickMarkValuesOnly = true } if eventType == .leftMouseUp { sender.allowsTickMarkValuesOnly = false } let sliderValue = sender.doubleValue customAudioDelayTextField.doubleValue = sliderValue redraw(indicator: audioDelaySliderIndicator, constraint: audioDelaySliderConstraint, slider: audioDelaySlider, value: "\(customAudioDelayTextField.stringValue)s") if let event = NSApp.currentEvent { if event.type == .leftMouseUp { player.setAudioDelay(sliderValue) } } } @IBAction func customAudioDelayEditFinishedAction(_ sender: NSTextField) { if sender.stringValue.isEmpty { sender.stringValue = "0" } let value = sender.doubleValue player.setAudioDelay(value) audioDelaySlider.doubleValue = value redraw(indicator: audioDelaySliderIndicator, constraint: audioDelaySliderConstraint, slider: audioDelaySlider, value: "\(sender.stringValue)s") } @IBAction func audioEqSliderAction(_ sender: NSSlider) { player.setAudioEq(fromGains: [ audioEqSlider1.doubleValue, audioEqSlider2.doubleValue, audioEqSlider3.doubleValue, audioEqSlider4.doubleValue, audioEqSlider5.doubleValue, audioEqSlider6.doubleValue, audioEqSlider7.doubleValue, audioEqSlider8.doubleValue, audioEqSlider9.doubleValue, audioEqSlider10.doubleValue, ]) } @IBAction func resetAudioEqAction(_ sender: AnyObject) { player.removeAudioEqFilter() updateAudioEqState() } // MARK: Sub tab @IBAction func loadExternalSubAction(_ sender: NSSegmentedControl) { if sender.selectedSegment == 0 { let currentDir = player.info.currentURL?.deletingLastPathComponent() Utility.quickOpenPanel(title: "Load external subtitle", chooseDir: false, dir: currentDir) { url in // set a delay self.player.loadExternalSubFile(url, delay: true) self.subTableView.reloadData() self.secSubTableView.reloadData() } } else if sender.selectedSegment == 1 { showSubChooseMenu(forView: sender) } } func showSubChooseMenu(forView view: NSView, showLoadedSubs: Bool = false) { let activeSubs = player.info.trackList(.sub) + player.info.trackList(.secondSub) let menu = NSMenu() menu.autoenablesItems = false // loaded subtitles if showLoadedSubs { if player.info.subTracks.isEmpty { menu.addItem(withTitle: NSLocalizedString("subtrack.no_loaded", comment: "No subtitles loaded"), enabled: false) } else { menu.addItem(withTitle: NSLocalizedString("track.none", comment: "<None>"), action: #selector(self.chosenSubFromMenu(_:)), target: self, stateOn: player.info.sid == 0 ? true : false) for sub in player.info.subTracks { menu.addItem(withTitle: sub.readableTitle, action: #selector(self.chosenSubFromMenu(_:)), target: self, obj: sub, stateOn: sub.id == player.info.sid ? true : false) } } menu.addItem(NSMenuItem.separator()) } // external subtitles let addMenuItem = { (sub: FileInfo) -> Void in let isActive = !showLoadedSubs && activeSubs.contains { $0.externalFilename == sub.path } menu.addItem(withTitle: "\(sub.filename).\(sub.ext)", action: #selector(self.chosenSubFromMenu(_:)), target: self, obj: sub, stateOn: isActive ? true : false) } if player.info.currentSubsInfo.isEmpty { menu.addItem(withTitle: NSLocalizedString("subtrack.no_external", comment: "No external subtitles found"), enabled: false) } else { if let videoInfo = player.info.currentVideosInfo.first(where: { $0.url == player.info.currentURL }), !videoInfo.relatedSubs.isEmpty { videoInfo.relatedSubs.forEach(addMenuItem) menu.addItem(NSMenuItem.separator()) } player.info.currentSubsInfo.sorted { (f1, f2) in return f1.filename.localizedStandardCompare(f2.filename) == .orderedAscending }.forEach(addMenuItem) } NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: view) } @objc func chosenSubFromMenu(_ sender: NSMenuItem) { if let fileInfo = sender.representedObject as? FileInfo { player.loadExternalSubFile(fileInfo.url) } else if let sub = sender.representedObject as? MPVTrack { player.setTrack(sub.id, forType: .sub) } else { player.setTrack(0, forType: .sub) } } @IBAction func searchOnlineAction(_ sender: AnyObject) { mainWindow.menuActionHandler.menuFindOnlineSub(.dummy) } @IBAction func subDelayChangedAction(_ sender: NSSlider) { let eventType = NSApp.currentEvent!.type if eventType == .leftMouseDown { sender.allowsTickMarkValuesOnly = true } if eventType == .leftMouseUp { sender.allowsTickMarkValuesOnly = false } let sliderValue = sender.doubleValue customSubDelayTextField.doubleValue = sliderValue redraw(indicator: subDelaySliderIndicator, constraint: subDelaySliderConstraint, slider: subDelaySlider, value: "\(customSubDelayTextField.stringValue)s") if let event = NSApp.currentEvent { if event.type == .leftMouseUp { player.setSubDelay(sliderValue) } } } @IBAction func customSubDelayEditFinishedAction(_ sender: NSTextField) { if sender.stringValue.isEmpty { sender.stringValue = "0" } let value = sender.doubleValue player.setSubDelay(value) subDelaySlider.doubleValue = value redraw(indicator: subDelaySliderIndicator, constraint: subDelaySliderConstraint, slider: subDelaySlider, value: "\(sender.stringValue)s") } @IBAction func subScaleReset(_ sender: AnyObject) { player.setSubScale(1) subScaleSlider.doubleValue = 0 } @IBAction func subPosSliderAction(_ sender: NSSlider) { player.setSubPos(Int(sender.intValue)) } @IBAction func subScaleSliderAction(_ sender: NSSlider) { let value = sender.doubleValue let mappedValue: Double, realValue: Double // map [-10, -1], [1, 10] to [-9, 9], bounds may change in future if value > 0 { mappedValue = round((value + 1) * 20) / 20 realValue = mappedValue } else { mappedValue = round((value - 1) * 20) / 20 realValue = 1 / mappedValue } player.setSubScale(realValue) } @IBAction func subTextColorAction(_ sender: AnyObject) { player.setSubTextColor(subTextColorWell.color.mpvColorString) } @IBAction func subTextSizeAction(_ sender: AnyObject) { if let selectedItem = subTextSizePopUp.selectedItem { if let value = Double(selectedItem.title) { player.setSubTextSize(value) } } } @IBAction func subTextBorderColorAction(_ sender: AnyObject) { player.setSubTextBorderColor(subTextBorderColorWell.color.mpvColorString) } @IBAction func subTextBorderWidthAction(_ sender: AnyObject) { if let value = Double(subTextBorderWidthPopUp.stringValue) { player.setSubTextBorderSize(value) } } @IBAction func subTextBgColorAction(_ sender: AnyObject) { player.setSubTextBgColor(subTextBgColorWell.color.mpvColorString) } @IBAction func subFontAction(_ sender: AnyObject) { Utility.quickFontPickerWindow() { self.player.setSubFont($0 ?? "") } } } class QuickSettingView: NSView { override func mouseDown(with event: NSEvent) {} }
e2f7df8b4548831d60d433d98937091d
33.276423
173
0.699755
false
false
false
false
ihomway/RayWenderlichCourses
refs/heads/master
Mastering Auto Layout/MasteringAutoLayout/MasteringAutoLayout/MapViewController.swift
mit
1
// // MapViewController.swift // MasteringAutoLayout // // Created by HOMWAY on 27/06/2017. // Copyright © 2017 ihomway. All rights reserved. // import UIKit class MapViewController: UIViewController { @IBOutlet weak var desiredXConstraint: NSLayoutConstraint! @IBOutlet weak var desiredYConstraint: NSLayoutConstraint! @IBOutlet weak var marker: UIView! @IBOutlet weak var markerImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func decideArrowOrX() { // 1 let currentPoint = marker.frame.origin let desiredPoint = CGPoint(x: desiredXConstraint.constant, // 2 y: desiredYConstraint.constant) if currentPoint == desiredPoint { markerImageView.image = UIImage(named: "x") markerImageView.transform = CGAffineTransform.identity } else { // 3 markerImageView.image = UIImage(named: "arrow") // 4 let angle = angleBetween(currentPoint, desiredPoint) markerImageView.transform = CGAffineTransform(rotationAngle: angle) } } func angleBetween(_ firstPoint: CGPoint, _ secondPoint: CGPoint) -> CGFloat { let deltaX = secondPoint.x - firstPoint.x let deltaY = secondPoint.y - firstPoint.y return atan2(deltaY, deltaX) } } extension MapViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { decideArrowOrX() } }
753aab5f1772a4833ac4f01d80d5c81c
25.896552
78
0.726923
false
false
false
false
charmaex/JDSegues
refs/heads/master
JDSegues/JDSegueScaleOut.swift
mit
1
// // JDSegueScaleOut.swift // JDSegues // // Created by Jan Dammshäuser on 29.08.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit /// Segue where the current screen scales out to a point or the center of the screen. @objc public class JDSegueScaleOut: UIStoryboardSegue, JDSegueDelayable, JDSegueOriginable { /// Defines at which point the animation should start /// - parameter Default: center of the screen public var animationOrigin: CGPoint? /// Time the transition animation takes /// - parameter Default: 0.5 seconds public var transitionTime: NSTimeInterval = 0.5 /// Time the transition animation is delayed after calling /// - parameter Default: 0 seconds public var transitionDelay: NSTimeInterval = 0 /// Animation Curve /// - parameter Default: CurveLinear public var animationOption: UIViewAnimationOptions = .CurveLinear public override func perform() { let sourceVC = sourceViewController let destinationVC = destinationViewController setupScreens() delay() { sourceVC.view.window!.insertSubview(destinationVC.view, belowSubview: sourceVC.view) UIView.animateWithDuration(self.transitionTime, delay: 0, options: self.animationOption, animations: { if let center = self.animationOrigin { sourceVC.view.center = center } sourceVC.view.transform = CGAffineTransformMakeScale(0.05, 0.05) }) { finished in self.finishSegue() { sourceVC.view.transform = CGAffineTransformMakeScale(1, 1) } } } } }
dccfabfa2b6dadc0acf477fffdd7ff95
31.122807
114
0.611688
false
false
false
false
ArthurKK/ImageScout
refs/heads/master
Source/ImageScout.swift
mit
2
import QuartzCore public enum ScoutedImageType: String { case GIF = "gif" case PNG = "png" case JPEG = "jpeg" case Unsupported = "unsupported" } public typealias ScoutCompletionBlock = (NSError?, CGSize, ScoutedImageType) -> () let unsupportedFormatErrorMessage = "Unsupported image format. ImageScout only supports PNG, GIF, and JPEG." let unableToParseErrorMessage = "Scouting operation failed. The remote image is likely malformated or corrupt." let invalidURIErrorMessage = "Invalid URI parameter." let errorDomain = "ImageScoutErrorDomain" public class ImageScout { private var session: NSURLSession private var sessionDelegate = SessionDelegate() private var queue = NSOperationQueue() private var operations = [String : ScoutOperation]() public init() { let sessionConfig = NSURLSessionConfiguration.ephemeralSessionConfiguration() session = NSURLSession(configuration: sessionConfig, delegate: sessionDelegate, delegateQueue: nil) sessionDelegate.scout = self } /// Takes a URL string and a completion block and returns void. /// The completion block takes an optional error, a size, and an image type, /// and returns void. public func scoutImageWithURI(URI: String, completion: ScoutCompletionBlock) { if let unwrappedURL = NSURL(string: URI) { let operation = ScoutOperation(task: session.dataTaskWithURL(unwrappedURL)) operation.completionBlock = { [unowned self] in completion(operation.error, operation.size, operation.type) self.operations[URI] = nil } addOperation(operation, withURI: URI) } else { let URLError = ImageScout.error(invalidURIErrorMessage, code: 100) completion(URLError, CGSizeZero, ScoutedImageType.Unsupported) } } // MARK: Delegate Methods func didReceiveData(data: NSData, task: NSURLSessionDataTask) { if let requestURL = task.currentRequest.URL?.absoluteString, let operation = operations[requestURL] { operation.appendData(data) } } func didCompleteWithError(error: NSError?, task: NSURLSessionDataTask) { if let requestURL = task.currentRequest.URL?.absoluteString { let completionError = error ?? ImageScout.error(unableToParseErrorMessage, code: 101) if let operation = operations[requestURL] { operation.terminateWithError(completionError) } } } // MARK: Private Methods private func addOperation(operation: ScoutOperation, withURI URI: String) { operations[URI] = operation queue.addOperation(operation) } // MARK: Class Methods class func error(message: String, code: Int) -> NSError { return NSError(domain: errorDomain, code:code, userInfo:[NSLocalizedDescriptionKey: message]) } }
65d8318496f044820f55107f731d1dd0
32.91358
111
0.730881
false
true
false
false
hi-hu/Hu-Tumbler
refs/heads/master
Hu-Tumbler/MainContainerViewController.swift
mit
1
// // MainContainerViewController.swift // Hu-Tumbler // // Created by Hi_Hu on 3/6/15. // Copyright (c) 2015 hi_hu. All rights reserved. // import UIKit class MainContainerViewController: UIViewController { @IBOutlet weak var mainContainerVC: UIView! @IBOutlet weak var exploreImage: UIImageView! @IBOutlet weak var loginBtn: UIButton! // array of tab controller buttons @IBOutlet var tabControlButtons: [UIButton]! // array holding the views var vcArray = [UIViewController]() var homeVC: HomeViewController! var searchVC: TrendingViewController! var composeVC: ComposeViewController! var accountVC: AccountViewController! var activityVC: SearchViewController! // index defaulted to home var selectedIndex: Int! = 0 // custom transitions var composeTransition: FadeTransition! var loginTransition: LoginTransition! override func viewDidLoad() { super.viewDidLoad() // set the status bar style to light UIApplication.sharedApplication().statusBarStyle = .LightContent // view controller instantiation var storyboard = UIStoryboard(name: "Main", bundle: nil) homeVC = storyboard.instantiateViewControllerWithIdentifier("homeSBID") as HomeViewController searchVC = storyboard.instantiateViewControllerWithIdentifier("trendingSBID") as TrendingViewController composeVC = storyboard.instantiateViewControllerWithIdentifier("composeSBID") as ComposeViewController accountVC = storyboard.instantiateViewControllerWithIdentifier("accountSBID") as AccountViewController activityVC = storyboard.instantiateViewControllerWithIdentifier("searchSBID") as SearchViewController // add the instantiated views into the array vcArray = [homeVC, searchVC, accountVC, activityVC] // default to homepage displayContentController(mainContainerVC, content: homeVC) tabControlButtons[0].selected = true // animate the explore bubble to bob up and down UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { () -> Void in self.exploreImage.center.y = self.exploreImage.center.y - 6 }) { (Bool) -> Void in // code } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tabBtnDidPress(sender: AnyObject) { var oldIndex = selectedIndex selectedIndex = sender.tag if selectedIndex != 0 { loginBtn.hidden = true } else { loginBtn.hidden = false } if selectedIndex == 1 { exploreImage.hidden = true } // deactivate button and remove current view tabControlButtons[oldIndex].selected = false hideContentController(mainContainerVC, content: vcArray[oldIndex]) // activate button add new selected view tabControlButtons[selectedIndex].selected = true displayContentController(mainContainerVC, content: vcArray[selectedIndex]) } // perform custom segue @IBAction func composeDidPress(sender: AnyObject) { performSegueWithIdentifier("composeSegue", sender: self) } @IBAction func loginDidPress(sender: AnyObject) { performSegueWithIdentifier("loginSegue", sender: self) } // add a subbview to the specified container func displayContentController(container: UIView, content: UIViewController) { addChildViewController(content) mainContainerVC.addSubview(content.view) content.didMoveToParentViewController(self) } // remove a subview from the specified container func hideContentController(container: UIView, content: UIViewController) { content.willMoveToParentViewController(nil) content.view.removeFromSuperview() content.removeFromParentViewController() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationViewController = segue.destinationViewController as UIViewController if segue.identifier == "composeSegue" { // instantiate the transition composeTransition = FadeTransition() composeTransition.duration = 0.3 destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom destinationViewController.transitioningDelegate = composeTransition } else if segue.identifier == "loginSegue" { // instantiate the transition loginTransition = LoginTransition() loginTransition.duration = 0.3 destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom destinationViewController.transitioningDelegate = loginTransition } } }
16881bb938ec52a453d5a049863de266
35.244755
154
0.675285
false
false
false
false
martinpucik/VIPER-Example
refs/heads/master
VIPER-Example/Modules/Main/Presenter/MainPresenter.swift
mit
1
// // ResetPasswordPresenter.swift // oneprove-ios // import UIKit class MainPresenter { var interactor: MainInteractorInterface? var wireframe: MainWireframeInterface? weak var view: MainViewInterface? } extension MainPresenter: MainPresenterInterface { // MARK: - Presenter Protocol func viewDidAppear() {} // MARK: - View func resetButtonTapped() { wireframe?.pushResetPassword() } func menuButtonTapped() { wireframe?.presentMenu() } func takeOverviewButtonTapped() { let artwork = Artwork.init(name: "Mona Lisa", id: "1753716") wireframe?.presentTakeOverview(withArtwork: artwork) } func swipeRecognized(withPan pan: UIScreenEdgePanGestureRecognizer) { let translation = pan.translation(in: pan.view!) let movementOnAxis = translation.x / pan.view!.bounds.width let positiveMovementOnAxis = fmaxf(Float(movementOnAxis), 0.0) let positiveMovementOnAxisPercent = fminf(positiveMovementOnAxis, 1.0) let progress = CGFloat(positiveMovementOnAxisPercent) switch pan.state { case .began: wireframe?.presentMenuInteractive() case .changed: wireframe?.updateInteraction(withProgress: progress) case .cancelled: wireframe?.cancelInteraction() case .ended: progress > 0.3 ? wireframe?.finishInteraction():wireframe?.cancelInteraction() default: break } } }
1e2fa2ad3dfbf178a7813d342e5f9039
28.192308
90
0.655468
false
false
false
false
wangchong321/tucao
refs/heads/master
WCWeiBo/WCWeiBo/Classes/Tools/Emoticons/EmoticonsTextView.swift
mit
1
// // EmoticonsTextView.swift // 01-表情键盘 // // Created by apple on 15/5/23. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit class EmoticonsTextView: UITextView { /// 插入表情符号 func insertEmoticon(emoticon: Emoticons) { // 0. 判断是否是删除按钮 if emoticon.isRemoveButton { deleteBackward() return } // 1. 判断是否是图片表情 if emoticon.chs != nil { // 1. 创建图片附件属性文本 let attrStr = EmoticonsAttachment.emoticonString(emoticon, height: font.lineHeight) // 2. 将文本添加到 textView // 1> 从 textView 拿出可变的文本 var textStr = NSMutableAttributedString(attributedString: attributedText) // 2> 追加文本 textStr.replaceCharactersInRange(selectedRange, withAttributedString: attrStr) // 3> 重新添加整个文本的属性 /** name 是文本属性的名字 value 是文本属性的值 */ textStr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, textStr.length)) // 4> 记录当前用户选中的光标位置 let range = selectedRange // 5> 设置文本,替换了 textView 的所有属性文本 attributedText = textStr // 6> 恢复光标位置 selectedRange = NSMakeRange(range.location + 1, 0) // 7> 直接调用代理方法 // 前面的问号:代理是否存在,如果代理不存在,就不调用方法 // 后面的问号:一定要实现代理方法 delegate?.textViewDidChange!(self) } else if emoticon.emojiStr != nil { // 将 emoji 字符串插入的 textView replaceRange(selectedTextRange!, withText: emoticon.emojiStr!) } } /// 返回文本框中的完整文本 func fullText() -> String { let attrStr = attributedText var strM = String() attributedText.enumerateAttributesInRange(NSMakeRange(0, attrStr.length), options: NSAttributedStringEnumerationOptions(0)) { (dict, range, _) in // 通过跟踪,能够发现,如果有 NSAttachment 说明是图片,否则是文本 // 需要解决一个问题:从 NSAttachment 中获取到表情文字 if let attachment = dict["NSAttachment"] as? EmoticonsAttachment { println("有图片 \(attachment.chs)") strM += attachment.chs! } else { let str = (attrStr.string as NSString).substringWithRange(range) println("---\(str)") strM += str } } return strM } }
448a9f57b55f27bd05e574d9f94d04cb
29.962963
153
0.53429
false
false
false
false
ChristianPraiss/Osmosis
refs/heads/master
Pod/Classes/PopulateOperation.swift
mit
1
// // PopulateOperation.swift // Pods // // Created by Christian Praiß on 12/26/15. // // import Foundation import Kanna internal class PopulateOperation: OsmosisOperation { var queries: [OsmosisPopulateKey: OsmosisSelector] var type: HTMLSelectorType var next: OsmosisOperation? var errorHandler: OsmosisErrorCallback? init(queries: [OsmosisPopulateKey: OsmosisSelector], type: HTMLSelectorType, errorHandler: OsmosisErrorCallback? = nil){ self.queries = queries self.type = type self.errorHandler = errorHandler } func execute(doc: HTMLDocument?, currentURL: NSURL?, node: XMLElement?, dict: [String: AnyObject]) { var newDict = dict for (key, query) in queries { var nodes: XMLNodeSet? switch type { case .CSS: nodes = node?.css(query.selector) case .XPath: nodes = node?.xpath(query.selector) } if let nodes = nodes where nodes.count != 0 { switch key { case .Single(let key): if let node = nodes.first { if let selector = query.attribute { newDict[key] = node[selector] }else{ newDict[key] = node.text } }else{ self.errorHandler?(error: NSError(domain: "No node found for populate \(query)", code: 500, userInfo: nil)) } case .Array(let key): var contentArray = [String]() for node in nodes { if let selector = query.attribute { contentArray.append(node[selector] ?? "") }else{ contentArray.append(node.text ?? "") } } newDict[key] = contentArray } }else{ self.errorHandler?(error: NSError(domain: "No node found for populate \(query)", code: 500, userInfo: nil)) } } self.next?.execute(doc, currentURL: currentURL, node: node, dict: newDict) } }
0f001bf00adc5b83f0ff35e4f3e15d5b
34
131
0.495019
false
false
false
false
aschwaighofer/swift
refs/heads/master
validation-test/compiler_crashers_2/0207-sr7371.swift
apache-2.0
8
// RUN: not --crash %target-swift-frontend -emit-ir %s public protocol TypedParserResultTransferType { // Remove type constraint associatedtype Result: ParserResult } public struct AnyTypedParserResultTransferType<P: ParserResult>: TypedParserResultTransferType { public typealias Result = P // Remove property public let result: P } public protocol ParserResult {} public protocol StaticParser: ParserResult {} // Change comformance to ParserResult public protocol TypedStaticParser: StaticParser { // Remove type constraint associatedtype ResultTransferType: TypedParserResultTransferType } // Remove where clause public protocol MutableSelfStaticParser: TypedStaticParser where ResultTransferType == AnyTypedParserResultTransferType<Self> { func parseTypeVar() -> AnyTypedParserResultTransferType<Self> } extension MutableSelfStaticParser { public func anyFunction() -> () { let t = self.parseTypeVar // Remove this and below _ = t() _ = self.parseTypeVar() } }
5e7db39add09b145c88c3f92b32f0d0a
28
127
0.746169
false
false
false
false
ipraba/Bean
refs/heads/master
Pod/Classes/UIImageView+Bean.swift
mit
1
// // BeanExtensions.swift // Pods // // Created by Prabaharan Elangovan on 17/12/15. // // import Foundation /** Extension for Imageview class */ public extension UIImageView { public func setImageWithUrl(url: NSURL, completion: (error : NSError?) -> Void) { self.setImageWithUrl(url, placeholderImage: nil, completion: completion) } public func setImageWithUrl(url: NSURL) { self.setImageWithUrl(url, placeholderImage: nil, completion: nil) } public func setImageWithUrl(url: NSURL, placeholderImage: UIImage? = nil, completion: ((error : NSError?) -> Void)?) { self.image = nil if let _ = placeholderImage { self.image = placeholderImage } download(url).getImage { (url, image, error) -> Void in if error == nil , let _ = image { self.image = image! Cache.sharedCache.storeImage(image!, url: url.absoluteString) if let _ = completion { completion!(error: nil) } } else{ if let _ = completion { completion!(error: error) } } } } }
1d50177563f787081699dd2fa3998eea
26.130435
122
0.536859
false
false
false
false
RetroRebirth/Micronaut
refs/heads/master
platformer/platformer/Controller.swift
mit
1
// // Controller.swift // Micronaut // // Created by Christopher Williams on 1/16/16. // Copyright © 2016 Christopher Williams. All rights reserved. // // Handles all the input from the user. import Foundation import SpriteKit class Controller: NSObject { static var debug = false // Keep track of the relative positioning on the remote static private var initialTouchPos = CGPointMake(0, 0) static private var currentTouchPos = CGPointMake(0, 0) class func initialize(view: SKView) { loadGestures(view) } class func loadGestures(view: SKView) { // Tap let tapRecognizer = UITapGestureRecognizer(target: Controller.self, action: #selector(Controller.tapped(_:))) tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]; view.addGestureRecognizer(tapRecognizer) // Swipe Up let swipeUpRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedUp(_:))) swipeUpRecognizer.direction = .Up view.addGestureRecognizer(swipeUpRecognizer) // Swipe Down let swipeDownRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedDown(_:))) swipeDownRecognizer.direction = .Down view.addGestureRecognizer(swipeDownRecognizer) // Swipe Right let swipeRightRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedRight(_:))) swipeRightRecognizer.direction = .Right view.addGestureRecognizer(swipeRightRecognizer) // Swipe Left let swipeLeftRecognizer = UISwipeGestureRecognizer(target: Controller.self, action: #selector(Controller.swipedLeft(_:))) swipeLeftRecognizer.direction = .Left view.addGestureRecognizer(swipeLeftRecognizer) // Pressed play/pause button let playRecognizer = UITapGestureRecognizer(target: Controller.self, action: #selector(Controller.play(_:))) playRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)]; view.addGestureRecognizer(playRecognizer) } class func play(gestureRecognizer: UIGestureRecognizer) { // Toggle debug controls Controller.debug = !Controller.debug Player.clearVelocity() Player.node?.physicsBody?.affectedByGravity = !Controller.debug } class func tapped(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.warp() } else { Player.setShrink(Player.isBig()) } } class func swipedUp(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.clearVelocity() Player.setVelocityY(Constants.PlayerSpeed, force: true) } else { Player.jump() } } class func swipedDown(gestureRecognizer: UIGestureRecognizer) { if Controller.debug { Player.clearVelocity() Player.setVelocityY(-Constants.PlayerSpeed, force: true) } else { Player.setVelocityX(0.0, force: false) } } class func swipedRight(gestureRecognizer: UIGestureRecognizer) { if debug { Player.clearVelocity() } Player.setVelocityX(Constants.PlayerSpeed, force: false) } class func swipedLeft(gestureRecognizer: UIGestureRecognizer) { if debug { Player.clearVelocity() } Player.setVelocityX(-Constants.PlayerSpeed, force: false) } class func touchBegan(pos: CGPoint) { initialTouchPos = pos currentTouchPos = pos } class func touchMoved(pos: CGPoint) { currentTouchPos = pos } class func touchEnded() { // initialTouchPos = CGPointMake(0, 0) // currentTouchPos = CGPointMake(0, 0) } // Calculates the distance the user has moved their input along the X axis class func getTouchMagnitudeX() -> CGFloat { return (currentTouchPos - initialTouchPos).x } // class func calcNewPlayerVelocityDx() -> CGFloat { // return Constants.PlayerSpeed * Controller.getTouchMagnitudeX() // } }
3dc7d455b61c90e3019d8c9d38e49d84
34.890756
131
0.664169
false
false
false
false
elpassion/el-space-ios
refs/heads/master
ELSpaceTests/TestDoubles/Spies/ApiClientSpy.swift
gpl-3.0
1
@testable import ELSpace import Alamofire import RxSwift class ApiClientSpy: ApiClientProtocol { var response: Response? private(set) var path: String? private(set) var method: HTTPMethod? private(set) var parameters: Parameters? private(set) var encoding: ParameterEncoding? private(set) var headers: HTTPHeaders? // MARK: - ApiClientProtocol func request(path: String, method: HTTPMethod, parameters: Parameters?, encoding: ParameterEncoding?, headers: HTTPHeaders?) -> Observable<Response> { self.path = path self.method = method self.parameters = parameters self.encoding = encoding self.headers = headers return response == nil ? Observable.empty() : Observable.just(response!) } }
eeca83b09c71f39f9b1b8b5a232dcb5a
28.884615
154
0.693694
false
false
false
false
cactis/SwiftEasyKit
refs/heads/master
Source/Classes/Badge.swift
mit
1
// // Badge.swift // Created by ctslin on 2/28/16. import UIKit open class Badge: DefaultView { public var badgeSize: CGFloat! { didSet { styleUI(); } } public var label = UILabel() public var body = UIView() public var size: CGFloat! public var color = K.Badge.backgroundColor.withAlphaComponent(0.8) { didSet { styleUI() } } public var bordered = true { didSet { if bordered { label.bordered(size! / 12, color: UIColor.white.cgColor) } else { label.bordered(size! / 12, color: K.Badge.backgroundColor.cgColor) } } } public func plus(num: Int = 1) { if value != "" { value = String(Int(value)! + num) } else { value = "1" } } public func minus(num: Int = 1) { if value != "" { value = String(Int(value)! - num) } else { value = "" } } public var value: String! { get { return label.text } set { animate { self.label.text = newValue } if newValue != "" && newValue != "0" { label.isHidden = false } else { label.isHidden = true } } } public init(size: CGFloat? = K.Badge.size, value: String = "") { self.size = size self.badgeSize = size! * 1.5 super.init(frame: .zero) self.value = value layout([body.layout([label])]) label.isHidden = true } override open func styleUI() { super.styleUI() size = badgeSize / 1.5 bordered = true label.textColor = K.Badge.color label.font = UIFont.systemFont(ofSize: size) label.backgroundColor = color label.radiused(badgeSize / 2) label.textAlignment = .center } override public init(frame: CGRect) { super.init(frame: frame) } override open func layoutSubviews() { super.layoutSubviews() anchorAndFillEdge(.top, xPad: 0, yPad: 0, otherSize: badgeSize) body.fillSuperview() let w = max(badgeSize, label.intrinsicContentSize.width * 1.35) var yPad: CGFloat = -3 if (superview?.height)! > height { yPad = 2 } label.anchorInCorner(.topRight, xPad: (superview!.width - w) / 4.5, yPad: yPad, width: w, height: badgeSize) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
950b70039d9299bfedc3dffa906acb39
22.546392
112
0.59676
false
false
false
false
cyanzhong/xTextHandler
refs/heads/master
xLibrary/xTextModifier.swift
mit
1
// // ██╗ ██╗████████╗███████╗██╗ ██╗████████╗ // ╚██╗██╔╝╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝ // ╚███╔╝ ██║ █████╗ ╚███╔╝ ██║ // ██╔██╗ ██║ ██╔══╝ ██╔██╗ ██║ // ██╔╝ ██╗ ██║ ███████╗██╔╝ ██╗ ██║ // ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ // // xTextModifier.swift // xTextHandler (https://github.com/cyanzhong/xTextHandler/) // // Created by cyan on 16/7/4. // Copyright © 2016年 cyan. All rights reserved. // import XcodeKit import AppKit /// Text matching & handling class xTextModifier { /// Regular expressions private static let xTextHandlerStringPattern = "\"(.+)\"" // match "abc" private static let xTextHandlerHexPattern = "([0-9a-fA-F]+)" // match 00FFFF private static let xTextHandlerRGBPattern = "([0-9]+.+[0-9]+.+[0-9]+)" // match 20, 20, 20 | 20 20 20 ... private static let xTextHandlerRadixPattern = "([0-9]+)" // match numbers /// Select text with regex & default option /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter pattern: regex pattern /// - parameter handler: handler static func select(invocation: XCSourceEditorCommandInvocation, pattern: String?, handler: xTextModifyHandler) { select(invocation: invocation, pattern: pattern, options: [.selected], handler: handler) } /// Select text with regex /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter pattern: regex pattern /// - parameter options: xTextMatchOptions /// - parameter handler: handler static func select(invocation: XCSourceEditorCommandInvocation, pattern: String?, options: xTextMatchOptions, handler: xTextModifyHandler) { var regex: NSRegularExpression? if pattern != nil { do { try regex = NSRegularExpression(pattern: pattern!, options: .caseInsensitive) } catch { xTextLog(string: "Create regex failed") } } // enumerate selections for i in 0..<invocation.buffer.selections.count { let range = invocation.buffer.selections[i] as! XCSourceTextRange // match clipped text let match = xTextMatcher.match(selection: range, invocation: invocation, options: options) if match.clipboard { // handle clipboard text if match.text.characters.count > 0 { let pasteboard = NSPasteboard.general() pasteboard.declareTypes([NSPasteboardTypeString], owner: nil) pasteboard.setString(handler(match.text), forType: NSPasteboardTypeString) } continue } if match.text.characters.count == 0 { continue } // handle selected text var texts: Array<String> = [] if regex != nil { // match using regex regex!.enumerateMatches(in: match.text, options: [], range: match.range, using: { result, flags, stop in if let range = result?.rangeAt(1) { texts.append((match.text as NSString).substring(with: range)) } }) } else { // match all texts.append((match.text as NSString).substring(with: match.range)) } if texts.count == 0 { continue } var replace = match.text for text in texts { // replace each matched text with handler block if let textRange = replace.range(of: text) { replace.replaceSubrange(textRange, with: handler(text)) } } // separate text to lines using newline charset var lines = replace.components(separatedBy: NSCharacterSet.newlines) lines.removeLast() // update buffer invocation.buffer.lines.replaceObjects(in: NSMakeRange(range.start.line, range.end.line - range.start.line + 1), withObjectsFrom: lines) // cancel selection let newRange = XCSourceTextRange() newRange.start = range.start newRange.end = range.start invocation.buffer.selections[i] = newRange } } /// Select any text with default option /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func any(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { any(invocation: invocation, options: [.selected], handler: handler) } /// Select any text /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter options: xTextMatchOptions /// - parameter handler: handler static func any(invocation: XCSourceEditorCommandInvocation, options: xTextMatchOptions, handler: xTextModifyHandler) { select(invocation: invocation, pattern: nil, options: options, handler: handler) } /// Select numbers /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func radix(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerRadixPattern, handler: handler) } /// Select hex color /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func hex(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerHexPattern, handler: handler) } /// Select RGB color /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func rgb(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerRGBPattern, handler: handler) } }
a352fb3ad2395170433432f24dd51686
36.5
142
0.633158
false
false
false
false
ktchernov/Flappy-Swift-Pig
refs/heads/master
Flappy Swift Pig/GameViewController.swift
gpl-3.0
1
// // GameViewController.swift // Flappy Swift Pig // // Created by Konstantin Tchernov on 12/07/15. // Copyright (c) 2015 Konstantin Tchernov. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
234a3959ce9f8db73b604c382cbb33bc
25.568627
94
0.61107
false
false
false
false
TimurTarasenko/tispr-card-stack
refs/heads/master
TisprCardStack/TisprCardStack/TisprCardStackViewLayout.swift
apache-2.0
1
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // TisprCardStackViewLayout.swift // // Created by Andrei Pitsko on 07/12/15. // Copyright (c) 2015 BuddyHopp Inc. All rights reserved. // import UIKit public class TisprCardStackViewLayout: UICollectionViewLayout, UIGestureRecognizerDelegate { // MARK: - Properties /// The index of the card that is currently on top of the stack. The index 0 represents the oldest card of the stack. var index: Int = 0 { didSet { //workaround for zIndex draggedCellPath = oldValue > index ? NSIndexPath(forItem: index, inSection: 0) : NSIndexPath(forItem: oldValue, inSection: 0) collectionView?.performBatchUpdates({ let x: Void = self.invalidateLayout() }, completion: nil) delegate?.cardDidChangeState(oldValue) } } var delegate: TisprCardStackViewControllerDelegate? /// The maximum number of cards displayed on the top stack. This value includes the currently visible card. @IBInspectable public var topStackMaximumSize: Int = 3 /// The maximum number of cards displayed on the bottom stack. @IBInspectable public var bottomStackMaximumSize: Int = 3 /// The visible height of the card of the bottom stack. @IBInspectable public var bottomStackCardHeight: CGFloat = 50 /// The size of a card in the stack layout. @IBInspectable var cardSize: CGSize = CGSizeMake(280, 380) // The inset or outset margins for the rectangle around the card. @IBInspectable public var cardInsets: UIEdgeInsets = UIEdgeInsetsZero /// A Boolean value indicating whether the pan and swipe gestures on cards are enabled. var gesturesEnabled: Bool = false { didSet { if (gesturesEnabled) { let recognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:")) collectionView?.addGestureRecognizer(recognizer) panGestureRecognizer = recognizer panGestureRecognizer!.delegate = self swipeRecognizerDown = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerDown!.direction = UISwipeGestureRecognizerDirection.Down swipeRecognizerDown!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerDown!) swipeRecognizerDown!.requireGestureRecognizerToFail(panGestureRecognizer!) swipeRecognizerUp = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerUp!.direction = UISwipeGestureRecognizerDirection.Up swipeRecognizerUp!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerUp!) swipeRecognizerUp!.requireGestureRecognizerToFail(panGestureRecognizer!) } else { if let recognizer = panGestureRecognizer { collectionView?.removeGestureRecognizer(recognizer) } if let swipeDownRecog = swipeRecognizerDown { collectionView?.removeGestureRecognizer(swipeDownRecog) } if let swipeUpRecog = swipeRecognizerUp { collectionView?.removeGestureRecognizer(swipeUpRecog) } } } } // Index path of dragged cell private var draggedCellPath: NSIndexPath? // The initial center of the cell being dragged. private var initialCellCenter: CGPoint? // The rotation values of the bottom stack cards. private var bottomStackRotations = [Int: Double]() // Is the animation for new cards in progress? private var newCardAnimationInProgress: Bool = false /// Cards from bottom stack will be rotated with angle = coefficientOfRotation * hade. private let coefficientOfRotation: Double = 0.25 private let angleOfRotationForNewCardAnimation: CGFloat = 0.25 private let verticalOffsetBetweenCardsInTopStack = 10 private let centralCardYPosition = 70 private var panGestureRecognizer: UIPanGestureRecognizer? private var swipeRecognizerDown: UISwipeGestureRecognizer? private var swipeRecognizerUp: UISwipeGestureRecognizer? private let minimumXPanDistanceToSwipe: CGFloat = 100 private let minimumYPanDistanceToSwipe: CGFloat = 60 // MARK: - Getting the Collection View Information override public func collectionViewContentSize() -> CGSize { return collectionView!.frame.size } // MARK: - Providing Layout Attributes override public func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { var result :UICollectionViewLayoutAttributes? if itemIndexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { result = UICollectionViewLayoutAttributes(forCellWithIndexPath: itemIndexPath) let yPosition = collectionViewContentSize().height - cardSize.height //Random direction let directionFromRight = arc4random() % 2 == 0 let xPosition = directionFromRight ? collectionViewContentSize().width : -cardSize.width let cardFrame = CGRectMake(CGFloat(xPosition), yPosition, cardSize.width, cardSize.height) result!.frame = cardFrame result!.zIndex = 1000 - itemIndexPath.item result!.hidden = false result!.transform3D = CATransform3DMakeRotation(directionFromRight ?angleOfRotationForNewCardAnimation : -angleOfRotationForNewCardAnimation, 0, 0, 1) } return result } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let indexPaths = indexPathsForElementsInRect(rect) let layoutAttributes = indexPaths.map { self.layoutAttributesForItemAtIndexPath($0) } return layoutAttributes } public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var result = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) if (indexPath.item >= index) { result = layoutAttributesForTopStackItemWithInitialAttributes(result) } else { result = layoutAttributesForBottomStackItemWithInitialAttributes(result) } //we have to hide invisible cards in top stask due perfomance issues due shadows result.hidden = (result.indexPath.item >= index + topStackMaximumSize) if indexPath.item == draggedCellPath?.item { //workaround for zIndex result.zIndex = 100000 } else { result.zIndex = (indexPath.item >= index) ? (1000 - indexPath.item) : (1000 + indexPath.item) } return result } // MARK: - Implementation private func indexPathsForElementsInRect(rect: CGRect) -> [NSIndexPath] { var result = [NSIndexPath]() let count = collectionView!.numberOfItemsInSection(0) let topStackCount = min(count - (index + 1), topStackMaximumSize - 1) let bottomStackCount = min(index, bottomStackMaximumSize) let start = index - bottomStackCount let end = (index + 1) + topStackCount for i in start..<end { result.append(NSIndexPath(forItem: i, inSection: 0)) } return result } private func layoutAttributesForTopStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { //we should not change position for card which will be hidden for good animation let minYPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(topStackMaximumSize - 1) var yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) yPosition = max(yPosition,minYPosition) //right position for new card if attributes.indexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { //New card has to be displayed if there are no topStackMaximumSize cards in the top stack if attributes.indexPath.item >= index && attributes.indexPath.item < index + topStackMaximumSize { yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) } else { attributes.hidden = true yPosition = centralCardYPosition } } let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let cardFrame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = cardFrame return attributes } private func layoutAttributesForBottomStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let yPosition = collectionView!.frame.size.height - bottomStackCardHeight let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let frame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = frame if let angle = bottomStackRotations[attributes.indexPath.item] { attributes.transform3D = CATransform3DMakeRotation(CGFloat(angle), 0, 0, 1) } return attributes } // MARK: - Handling the Swipe and Pan Gesture internal func handleSwipe(sender: UISwipeGestureRecognizer) { switch sender.direction { case UISwipeGestureRecognizerDirection.Up: // Take the card at the current index // and process the swipe up only if it occurs below it // var temIndex = index // if temIndex >= collectionView!.numberOfItemsInSection(0) { // temIndex-- // } // let currentCard = collectionView!.cellForItemAtIndexPath(NSIndexPath(forItem: temIndex , inSection: 0))! // let point = sender.locationInView(collectionView) // if (point.y > CGRectGetMaxY(currentCard.frame) && index > 0) { index-- // } case UISwipeGestureRecognizerDirection.Down: if index + 1 < collectionView!.numberOfItemsInSection(0) { index++ } default: break } } internal func handlePan(sender: UIPanGestureRecognizer) { if (sender.state == .Began) { let initialPanPoint = sender.locationInView(collectionView) findDraggingCellByCoordinate(initialPanPoint) } else if (sender.state == .Changed) { let newCenter = sender.translationInView(collectionView!) updateCenterPositionOfDraggingCell(newCenter) } else { if let indexPath = draggedCellPath { finishedDragging(collectionView!.cellForItemAtIndexPath(indexPath)!) } } } //Define what card should we drag private func findDraggingCellByCoordinate(touchCoordinate: CGPoint) { if let indexPath = collectionView?.indexPathForItemAtPoint(touchCoordinate) { if indexPath.item >= index { //top stack draggedCellPath = NSIndexPath(forItem: index, inSection: 0) initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } else { //bottomStack if (index > 0 ) { draggedCellPath = NSIndexPath(forItem: index - 1, inSection: 0) } initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } //workaround for fix issue with zIndex let cell = collectionView!.cellForItemAtIndexPath(draggedCellPath!) collectionView?.bringSubviewToFront(cell!) } } //Change position of dragged card private func updateCenterPositionOfDraggingCell(touchCoordinate:CGPoint) { if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let newCenterX = (initialCellCenter!.x + touchCoordinate.x) let newCenterY = (initialCellCenter!.y + touchCoordinate.y) cell.center = CGPoint(x: newCenterX, y:newCenterY) cell.transform = CGAffineTransformMakeRotation(CGFloat(storeAngleOfRotation())) } } } private func finishedDragging(cell: UICollectionViewCell) { let deltaX = abs(cell.center.x - initialCellCenter!.x) let deltaY = abs(cell.center.y - initialCellCenter!.y) let shouldSnapBack = (deltaX < minimumXPanDistanceToSwipe && deltaY < minimumYPanDistanceToSwipe) if shouldSnapBack { UIView.setAnimationsEnabled(false) collectionView!.reloadItemsAtIndexPaths([self.draggedCellPath!]) UIView.setAnimationsEnabled(true) } else { storeAngleOfRotation() if draggedCellPath?.item == index { index++ } else { index-- } initialCellCenter = CGPointZero draggedCellPath = nil } } //Compute and Store angle of rotation private func storeAngleOfRotation() -> Double { var result:Double = 0 if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let centerYIncidence = collectionView!.frame.size.height + cardSize.height - bottomStackCardHeight let gamma:Double = Double((cell.center.x - collectionView!.bounds.size.width/2)/(centerYIncidence - cell.center.y)) result = atan(gamma) bottomStackRotations[strongDraggedCellPath.item] = atan(gamma)*coefficientOfRotation } } return result } // MARK: - appearance of new card func newCardDidAdd(newCardIndex:Int) { collectionView?.performBatchUpdates({ [weak self] _ in self?.newCardAnimationInProgress = true self?.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: newCardIndex, inSection: 0)]) }, completion: {[weak self] _ in let void: ()? = self?.newCardAnimationInProgress = false }) } //MARK: - UIGestureRecognizerDelegate public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { var result:Bool = true if let panGesture = gestureRecognizer as? UIPanGestureRecognizer { let velocity = panGesture.velocityInView(collectionView) result = abs(Int(velocity.y)) < 250 } return result } }
8fc457326957135da88fd84b4c221eab
43.669444
162
0.65624
false
false
false
false
zliw/AsciiSFX
refs/heads/master
AsciiSFX/FrequencyBuffer.swift
mit
1
// // FrequencyBuffer.swift // AsciiSFX // // Created by martin on 08/11/15. // Copyright © 2015 martin. All rights reserved. // import AVFoundation class FrequencyBuffer { var length: UInt32 let buffer: AVAudioPCMBuffer var volumeBuffer: VolumeBuffer private var noteSequence = Array<Note>() private let fadeSampleCount = UInt32(SampleRate / 200) // 5ms init(length: UInt32, sequence:Array<Note>) { self.length = length self.buffer = Helper().getBuffer(length) self.volumeBuffer = VolumeBuffer(length: length) self.noteSequence = sequence self.render() } func render() { let sampleCount = UInt32(self.length * UInt32(SampleRate) / 1000) let sectionLength = Helper().lengthOfSections(sampleCount, sequence: self.noteSequence) self.volumeBuffer.render() var counter = 0 for (var i = 0; i < sectionLength.count; i++) { let length = sectionLength[i] let start = self.noteSequence[i].frequency() let end = self.noteSequence[i].toFrequency() let diff = end - start self.volumeBuffer.fadeInFrom(UInt32(counter), lengthInSamples: fadeSampleCount) self.volumeBuffer.fadeOutTo(UInt32(counter) + length, lengthInSamples: fadeSampleCount) let buffer = self.buffer.floatChannelData[0] for (var j:UInt32 = 0; j < length; j++) { buffer[counter++] = start + (diff * Float(j) / Float(length)) } } } }
7cc0d3419a3c3d96636f581491ac4d9e
29.392157
99
0.621935
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
refs/heads/master
RxSwiftGuideRead/RxSwift-master/Tests/RxCocoaTests/UICollectionView+RxTests.swift
mit
3
// // UICollectionView+RxTests.swift // Tests // // Created by Krunoslav Zaher on 4/8/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import RxSwift import RxCocoa import XCTest // UICollectionView final class UICollectionViewTests : RxTest { func test_DelegateEventCompletesOnDealloc() { let layout = UICollectionViewFlowLayout() let createView: () -> UICollectionView = { UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.itemSelected } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.itemDeselected } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.modelSelected(Int.self) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.modelDeselected(Int.self) } #if os(tvOS) ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.didUpdateFocusInContextWithAnimationCoordinator } #endif } func test_itemSelected() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.itemSelected .subscribe(onNext: { indexPath in resultIndexPath = indexPath }) let testRow = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didSelectItemAt: testRow) XCTAssertEqual(resultIndexPath, testRow) subscription.dispose() } func test_itemDeselected() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.itemDeselected .subscribe(onNext: { indexPath in resultIndexPath = indexPath }) let testRow = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didDeselectItemAt: testRow) XCTAssertEqual(resultIndexPath, testRow) subscription.dispose() } func test_itemHighlighted() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.itemHighlighted .subscribe(onNext: { indexPath in resultIndexPath = indexPath }) let testRow = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didHighlightItemAt: testRow) XCTAssertEqual(resultIndexPath, testRow) subscription.dispose() } func test_itemUnhighlighted() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.itemUnhighlighted .subscribe(onNext: { indexPath in resultIndexPath = indexPath }) let testRow = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didUnhighlightItemAt: testRow) XCTAssertEqual(resultIndexPath, testRow) subscription.dispose() } func test_willDisplayCell() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultCell: UICollectionViewCell? = nil var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.willDisplayCell .subscribe(onNext: { let (cell, indexPath) = $0 resultCell = cell resultIndexPath = indexPath }) let testCell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) let testIndexPath = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, willDisplay: testCell, forItemAt: testIndexPath) XCTAssertEqual(resultCell, testCell) XCTAssertEqual(resultIndexPath, testIndexPath) subscription.dispose() } func test_willDisplaySupplementaryView() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultSupplementaryView: UICollectionReusableView? = nil var resultElementKind: String? = nil var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.willDisplaySupplementaryView .subscribe(onNext: { let (reuseableView, elementKind, indexPath) = $0 resultSupplementaryView = reuseableView resultElementKind = elementKind resultIndexPath = indexPath }) let testSupplementaryView = UICollectionReusableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) let testElementKind = UICollectionView.elementKindSectionHeader let testIndexPath = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, willDisplaySupplementaryView: testSupplementaryView, forElementKind: testElementKind, at: testIndexPath) XCTAssertEqual(resultSupplementaryView, testSupplementaryView) XCTAssertEqual(resultElementKind, testElementKind) XCTAssertEqual(resultIndexPath, testIndexPath) subscription.dispose() } func test_didEndDisplayingCell() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultCell: UICollectionViewCell? = nil var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.didEndDisplayingCell .subscribe(onNext: { let (cell, indexPath) = $0 resultCell = cell resultIndexPath = indexPath }) let testCell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) let testRow = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didEndDisplaying: testCell, forItemAt: testRow) XCTAssertEqual(resultCell, testCell) XCTAssertEqual(resultIndexPath, testRow) subscription.dispose() } func test_didEndDisplayingSupplementaryView() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var resultSupplementaryView: UICollectionReusableView? = nil var resultElementKind: String? = nil var resultIndexPath: IndexPath? = nil let subscription = collectionView.rx.didEndDisplayingSupplementaryView .subscribe(onNext: { let (reuseableView, elementKind, indexPath) = $0 resultSupplementaryView = reuseableView resultElementKind = elementKind resultIndexPath = indexPath }) let testSupplementaryView = UICollectionReusableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) let testElementKind = UICollectionView.elementKindSectionHeader let testIndexPath = IndexPath(row: 1, section: 0) collectionView.delegate!.collectionView!(collectionView, didEndDisplayingSupplementaryView: testSupplementaryView, forElementOfKind: testElementKind, at: testIndexPath) XCTAssertEqual(resultSupplementaryView, testSupplementaryView) XCTAssertEqual(resultElementKind, testElementKind) XCTAssertEqual(resultIndexPath, testIndexPath) subscription.dispose() } @available(iOS 10.0, tvOS 10.0, *) func test_prefetchItems() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var indexPaths: [IndexPath] = [] let subscription = collectionView.rx.prefetchItems .subscribe(onNext: { indexPaths = $0 }) let testIndexPaths = [IndexPath(item: 1, section: 0), IndexPath(item: 2, section: 0)] collectionView.prefetchDataSource!.collectionView(collectionView, prefetchItemsAt: testIndexPaths) XCTAssertEqual(indexPaths, testIndexPaths) subscription.dispose() } @available(iOS 10.0, tvOS 10.0, *) func test_cancelPrefetchingForItems() { let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) var indexPaths: [IndexPath] = [] let subscription = collectionView.rx.cancelPrefetchingForItems .subscribe(onNext: { indexPaths = $0 }) let testIndexPaths = [IndexPath(item: 1, section: 0), IndexPath(item: 2, section: 0)] collectionView.prefetchDataSource!.collectionView!(collectionView, cancelPrefetchingForItemsAt: testIndexPaths) XCTAssertEqual(indexPaths, testIndexPaths) subscription.dispose() } @available(iOS 10.0, tvOS 10.0, *) func test_PrefetchDataSourceEventCompletesOnDealloc() { let layout = UICollectionViewFlowLayout() let createView: () -> UICollectionView = { UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.prefetchItems } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.cancelPrefetchingForItems } } func test_DelegateEventCompletesOnDealloc1() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) let s = items.bind(to: collectionView.rx.items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return UICollectionViewCell(frame: CGRect(x: 1, y: 1, width: 1, height: 1)) } return (collectionView, s) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.modelSelected(Int.self) } } func test_DelegateEventCompletesOnDealloc2() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let s = items.bind(to: collectionView.rx.items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } return (collectionView, s) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.modelSelected(Int.self) } } func test_DelegateEventCompletesOnDealloc2_cellType() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let s = items.bind(to: collectionView.rx.items(cellIdentifier: "a", cellType: UICollectionViewCell.self)) { (index: Int, item: Int, cell) in } return (collectionView, s) } ensureEventDeallocated(createView) { (view: UICollectionView) in view.rx.modelSelected(Int.self) } } func test_ModelSelected_itemsWithCellFactory() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 20.0, height: 20.0) let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") let s = items.bind(to: collectionView.rx.items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return collectionView.dequeueReusableCell(withReuseIdentifier: "a", for: IndexPath(item: index, section: 0)) } return (collectionView, s) } let (collectionView, dataSourceSubscription) = createView() var selectedItem: Int? = nil let s = collectionView.rx.modelSelected(Int.self) .subscribe(onNext: { (item: Int) in selectedItem = item }) collectionView.delegate!.collectionView!(collectionView, didSelectItemAt: IndexPath(row: 1, section: 0)) XCTAssertEqual(selectedItem, 2) dataSourceSubscription.dispose() s.dispose() } func test_ModelSelected_itemsWithCellIdentifier() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSourceSubscription = items.bind(to: collectionView.rx.items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } return (collectionView, dataSourceSubscription) } let (collectionView, dataSourceSubscription) = createView() var selectedItem: Int? = nil let s = collectionView.rx.modelSelected(Int.self) .subscribe(onNext: { item in selectedItem = item }) collectionView.delegate!.collectionView!(collectionView, didSelectItemAt: IndexPath(row: 1, section: 0)) XCTAssertEqual(selectedItem, 2) s.dispose() dataSourceSubscription.dispose() } func test_ModelDeselected_itemsWithCellFactory() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 20.0, height: 20.0) let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let s = items.bind(to: collectionView.rx.items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return collectionView.dequeueReusableCell(withReuseIdentifier: "a", for: IndexPath(item: index, section: 0)) } return (collectionView, s) } let (collectionView, dataSourceSubscription) = createView() var selectedItem: Int? = nil let s = collectionView.rx.modelDeselected(Int.self) .subscribe(onNext: { (item: Int) in selectedItem = item }) collectionView.delegate!.collectionView!(collectionView, didDeselectItemAt: IndexPath(row: 1, section: 0)) XCTAssertEqual(selectedItem, 2) dataSourceSubscription.dispose() s.dispose() } func test_ModelDeselected_itemsWithCellIdentifier() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSourceSubscription = items.bind(to: collectionView.rx.items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } return (collectionView, dataSourceSubscription) } let (collectionView, dataSourceSubscription) = createView() var selectedItem: Int? = nil let s = collectionView.rx.modelDeselected(Int.self) .subscribe(onNext: { item in selectedItem = item }) collectionView.delegate!.collectionView!(collectionView, didDeselectItemAt: IndexPath(row: 1, section: 0)) XCTAssertEqual(selectedItem, 2) s.dispose() dataSourceSubscription.dispose() } func test_modelAtIndexPath_normal() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() let dataSourceSubscription = items.bind(to: collectionView.rx.items(dataSource: dataSource)) return (collectionView, dataSourceSubscription) } let (collectionView, dataSourceSubscription) = createView() let model: Int = try! collectionView.rx.model(at: IndexPath(item: 1, section: 0)) XCTAssertEqual(model, 2) dataSourceSubscription.dispose() } #if os(tvOS) func test_didUpdateFocusInContextWithAnimationCoordinator() { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() let dataSourceSubscription = items.bind(to: collectionView.rx.items(dataSource: dataSource)) return (collectionView, dataSourceSubscription) } let (collectionView, dataSourceSubscription) = createView() var resultContext: UICollectionViewFocusUpdateContext? = nil var resultAnimationCoordinator: UIFocusAnimationCoordinator? = nil let subscription = collectionView.rx.didUpdateFocusInContextWithAnimationCoordinator .subscribe(onNext: { args in let (context, animationCoordinator) = args resultContext = context resultAnimationCoordinator = animationCoordinator }) let context = UICollectionViewFocusUpdateContext() let animationCoordinator = UIFocusAnimationCoordinator() XCTAssertEqual(resultContext, nil) XCTAssertEqual(resultAnimationCoordinator, nil) collectionView.delegate!.collectionView!(collectionView, didUpdateFocusIn: context, with: animationCoordinator) XCTAssertEqual(resultContext, context) XCTAssertEqual(resultAnimationCoordinator, animationCoordinator) subscription.dispose() dataSourceSubscription.dispose() } #endif } extension UICollectionViewTests { func testDataSourceIsBeingRetainedUntilDispose() { var dataSourceDeallocated = false var collectionViewOuter: UICollectionView? = nil var dataSourceSubscription: Disposable! collectionViewOuter?.becomeFirstResponder() autoreleasepool { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") collectionViewOuter = collectionView let dataSource = SectionedViewDataSourceMock() dataSourceSubscription = items.bind(to: collectionView.rx.items(dataSource: dataSource)) _ = dataSource.rx.deallocated.subscribe(onNext: { _ in dataSourceDeallocated = true }) } XCTAssert(dataSourceDeallocated == false) autoreleasepool { dataSourceSubscription.dispose() } XCTAssert(dataSourceDeallocated == true) } func testDataSourceIsBeingRetainedUntilCollectionViewDealloc() { var dataSourceDeallocated = false autoreleasepool { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() _ = items.bind(to: collectionView.rx.items(dataSource: dataSource)) _ = dataSource.rx.deallocated.subscribe(onNext: { _ in dataSourceDeallocated = true }) XCTAssert(dataSourceDeallocated == false) } XCTAssert(dataSourceDeallocated == true) } func testSetDataSourceUsesWeakReference() { var dataSourceDeallocated = false let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) autoreleasepool { collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() _ = collectionView.rx.setDataSource(dataSource) _ = dataSource.rx.deallocated.subscribe(onNext: { _ in dataSourceDeallocated = true }) XCTAssert(dataSourceDeallocated == false) } XCTAssert(dataSourceDeallocated == true) } func testDataSourceIsResetOnDispose() { var disposeEvents: [String] = [] let items: Observable<[Int]> = Observable.just([1, 2, 3]).concat(Observable.never()) .do(onDispose: { disposeEvents.append("disposed") }) let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() let dataSourceSubscription = items.bind(to: collectionView.rx.items(dataSource: dataSource)) return (collectionView, dataSourceSubscription) } let (collectionView, dataSourceSubscription) = createView() XCTAssertTrue(collectionView.dataSource === RxCollectionViewDataSourceProxy.proxy(for: collectionView)) _ = collectionView.rx.sentMessage(#selector(UICollectionView.layoutIfNeeded)).subscribe(onNext: { _ in disposeEvents.append("layoutIfNeeded") }) _ = collectionView.rx.sentMessage(NSSelectorFromString("setDataSource:")).subscribe(onNext: { arguments in let isNull = NSNull().isEqual(arguments[0]) disposeEvents.append("setDataSource:\(isNull ? "nil" : "nn")") }) XCTAssertEqual(disposeEvents, []) dataSourceSubscription.dispose() XCTAssertEqual(disposeEvents, ["disposed", "layoutIfNeeded", "setDataSource:nil", "setDataSource:nn"]) XCTAssertTrue(collectionView.dataSource === collectionView.rx.dataSource) } }
783ec75f758453a85eeaace9a3792f5e
41.048414
176
0.660063
false
true
false
false
L3-DANT/findme-app
refs/heads/master
Examples/CoreData/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift
mit
2
// // Rabbit.swift // CryptoSwift // // Created by Dima Kalachov on 12/11/15. // Copyright © 2015 Marcin Krzyzanowski. All rights reserved. // final public class Rabbit { /// Size of IV in bytes public static let ivSize = 64 / 8 /// Size of key in bytes public static let keySize = 128 / 8 /// Size of block in bytes public static let blockSize = 128 / 8 /// Key private let key: [UInt8] /// IV (optional) private let iv: [UInt8]? /// State variables private var x = [UInt32](count: 8, repeatedValue: 0) /// Counter variables private var c = [UInt32](count: 8, repeatedValue: 0) /// Counter carry private var p7: UInt32 = 0 /// 'a' constants private var a: [UInt32] = [ 0x4D34D34D, 0xD34D34D3, 0x34D34D34, 0x4D34D34D, 0xD34D34D3, 0x34D34D34, 0x4D34D34D, 0xD34D34D3, ] // MARK: - Initializers convenience public init?(key:[UInt8]) { self.init(key: key, iv: nil) } public init?(key:[UInt8], iv:[UInt8]?) { self.key = key self.iv = iv guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { return nil } } // MARK: - private func setup() { p7 = 0 // Key divided into 8 subkeys var k = [UInt32](count: 8, repeatedValue: 0) for j in 0..<8 { k[j] = UInt32(key[Rabbit.blockSize - (2*j + 1)]) | (UInt32(key[Rabbit.blockSize - (2*j + 2)]) << 8) } // Initialize state and counter variables from subkeys for j in 0..<8 { if j % 2 == 0 { x[j] = (k[(j+1) % 8] << 16) | k[j] c[j] = (k[(j+4) % 8] << 16) | k[(j+5) % 8] } else { x[j] = (k[(j+5) % 8] << 16) | k[(j+4) % 8] c[j] = (k[j] << 16) | k[(j+1) % 8] } } // Iterate system four times nextState() nextState() nextState() nextState() // Reinitialize counter variables for j in 0..<8 { c[j] = c[j] ^ x[(j+4) % 8] } if let iv = iv { setupIV(iv) } } private func setupIV(iv: [UInt8]) { // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits // 0 1 2 3 4 5 6 7 IV bytes in array let iv0: UInt32 = integerWithBytes([iv[4], iv[5], iv[6], iv[7]]) let iv1: UInt32 = integerWithBytes([iv[0], iv[1], iv[4], iv[5]]) let iv2: UInt32 = integerWithBytes([iv[0], iv[1], iv[2], iv[3]]) let iv3: UInt32 = integerWithBytes([iv[2], iv[3], iv[6], iv[7]]) // Modify the counter state as function of the IV c[0] = c[0] ^ iv0 c[1] = c[1] ^ iv1 c[2] = c[2] ^ iv2 c[3] = c[3] ^ iv3 c[4] = c[4] ^ iv0 c[5] = c[5] ^ iv1 c[6] = c[6] ^ iv2 c[7] = c[7] ^ iv3 // Iterate system four times nextState() nextState() nextState() nextState() } private func nextState() { // Before an iteration the counters are incremented var carry = p7 for j in 0..<8 { let prev = c[j] c[j] = prev &+ a[j] &+ carry carry = prev > c[j] ? 1 : 0 // detect overflow } p7 = carry // save last carry bit // Iteration of the system var newX = [UInt32](count: 8, repeatedValue: 0) newX[0] = g(0) &+ rotateLeft(g(7), 16) &+ rotateLeft(g(6), 16) newX[1] = g(1) &+ rotateLeft(g(0), 8) &+ g(7) newX[2] = g(2) &+ rotateLeft(g(1), 16) &+ rotateLeft(g(0), 16) newX[3] = g(3) &+ rotateLeft(g(2), 8) &+ g(1) newX[4] = g(4) &+ rotateLeft(g(3), 16) &+ rotateLeft(g(2), 16) newX[5] = g(5) &+ rotateLeft(g(4), 8) &+ g(3) newX[6] = g(6) &+ rotateLeft(g(5), 16) &+ rotateLeft(g(4), 16) newX[7] = g(7) &+ rotateLeft(g(6), 8) &+ g(5) x = newX } private func g(j: Int) -> UInt32 { let sum = x[j] &+ c[j] let square = UInt64(sum) * UInt64(sum) return UInt32(truncatingBitPattern: square ^ (square >> 32)) } private func nextOutput() -> [UInt8] { nextState() var output16 = [UInt16](count: Rabbit.blockSize / 2, repeatedValue: 0) output16[7] = UInt16(truncatingBitPattern: x[0]) ^ UInt16(truncatingBitPattern: x[5] >> 16) output16[6] = UInt16(truncatingBitPattern: x[0] >> 16) ^ UInt16(truncatingBitPattern: x[3]) output16[5] = UInt16(truncatingBitPattern: x[2]) ^ UInt16(truncatingBitPattern: x[7] >> 16) output16[4] = UInt16(truncatingBitPattern: x[2] >> 16) ^ UInt16(truncatingBitPattern: x[5]) output16[3] = UInt16(truncatingBitPattern: x[4]) ^ UInt16(truncatingBitPattern: x[1] >> 16) output16[2] = UInt16(truncatingBitPattern: x[4] >> 16) ^ UInt16(truncatingBitPattern: x[7]) output16[1] = UInt16(truncatingBitPattern: x[6]) ^ UInt16(truncatingBitPattern: x[3] >> 16) output16[0] = UInt16(truncatingBitPattern: x[6] >> 16) ^ UInt16(truncatingBitPattern: x[1]) var output8 = [UInt8](count: Rabbit.blockSize, repeatedValue: 0) for j in 0..<output16.count { output8[j * 2] = UInt8(truncatingBitPattern: output16[j] >> 8) output8[j * 2 + 1] = UInt8(truncatingBitPattern: output16[j]) } return output8 } // MARK: - Public public func encrypt(bytes: [UInt8]) -> [UInt8] { setup() var result = [UInt8](count: bytes.count, repeatedValue: 0) var output = nextOutput() var byteIdx = 0 var outputIdx = 0 while byteIdx < bytes.count { if (outputIdx == Rabbit.blockSize) { output = nextOutput() outputIdx = 0 } result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] byteIdx += 1 outputIdx += 1 } return result } public func decrypt(bytes: [UInt8]) -> [UInt8] { return encrypt(bytes) } } // MARK: - Cipher extension Rabbit: Cipher { public func cipherEncrypt(bytes:[UInt8]) -> [UInt8] { return self.encrypt(bytes) } public func cipherDecrypt(bytes: [UInt8]) -> [UInt8] { return self.decrypt(bytes) } }
08e96c948e33c05c01127f4531623c30
30.35545
111
0.49607
false
false
false
false
yichizhang/Keyboard
refs/heads/master
KeyboardExtension/Keyboard.swift
mit
1
// // Keyboard.swift // Keyboard // // Created by Matt Zanchelli on 6/19/14. // Copyright (c) 2014 Matt Zanchelli. All rights reserved. // import UIKit protocol KeyboardDelegate { func keyboard(keyboard: Keyboard, didSelectKey key: KeyboardKey) } class Keyboard: UIControl { // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) self.autoresizingMask = .FlexibleWidth | .FlexibleHeight self.multipleTouchEnabled = true } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: Properties /// An array of rows (an array) of keys. var keys: [[KeyboardKey]] = [[]] { willSet { // Remove all layout constraints. self.removeConstraints(self.constraints()) // Remove all the rows from the view. for view in self.subviews as! [UIView] { view.removeFromSuperview() } } didSet { var rows = Dictionary<String, UIView>() var previousView: UIView = self for x in 0..<keys.count { let rowOfKeys = keys[x] let row = Keyboard.createRow() let rowName = "row" + x.description rows[rowName] = row // rows.updateValue(row, forKey: rowName) self.addSubview(row) row.setTranslatesAutoresizingMaskIntoConstraints(false) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[row]|", options: nil, metrics: nil, views: ["row": row])) let attribute: NSLayoutAttribute = (x == 0) ? .Top : .Bottom self.addConstraint(NSLayoutConstraint(item: row, attribute: .Top, relatedBy: .Equal, toItem: previousView, attribute: attribute, multiplier: 1, constant: 0)) previousView = row self.addConstraint(NSLayoutConstraint(item: row, attribute: .Height, relatedBy: .Equal, toItem: row.superview, attribute: .Height, multiplier: rowHeights[x], constant: 0)) let metrics = ["top": edgeInsets[x].top, "bottom": edgeInsets[x].bottom] var horizontalVisualFormatString = "H:|-(\(edgeInsets[x].left))-" var views = Dictionary<String, UIView>() var firstEquallySizedView = -1 for i in 0..<rowOfKeys.count { let view = rowOfKeys[i] let viewName = "view" + i.description views.updateValue(view, forKey: viewName) row.addSubview(view) view.setTranslatesAutoresizingMaskIntoConstraints(false) row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(top)-[view]-(bottom)-|", options: nil, metrics: metrics, views: ["view": view])) let contentSize = view.intrinsicContentSize() if contentSize.width == UIViewNoIntrinsicMetric { if firstEquallySizedView < 0 { firstEquallySizedView = i horizontalVisualFormatString += "[\(viewName)]" } else { horizontalVisualFormatString += "[\(viewName)(==view\(firstEquallySizedView.description))]" } } else { horizontalVisualFormatString += "[\(viewName)]" } } horizontalVisualFormatString += "-(\(edgeInsets[x].right))-|" if views.count > 0 { row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormatString, options: nil, metrics: nil, views: views)) } } } } /// The edge insets for each row. var edgeInsets: [UIEdgeInsets] = [] /// The heights for each row. var rowHeights: [CGFloat] = [] // MARK: Helper functions class func createRow() -> UIView { let view = UIView() view.setTranslatesAutoresizingMaskIntoConstraints(false) let divider = KeyboardDivider() view.addSubview(divider) let views = ["divider": divider] divider.setTranslatesAutoresizingMaskIntoConstraints(false) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[divider]|", options: nil, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[divider(0.5)]", options: nil, metrics: nil, views: views)) return view } // MARK: Gesture handling var touchesToViews = Dictionary<UITouch, UIView>() override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { for o in touches { if let touch = o as? UITouch { let view = self.hitTest(touch.locationInView(self), withEvent: event) touchesToViews[touch] = view if let view = view as? KeyboardKey { view.highlighted = true } } } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { for o in touches { if let touch = o as? UITouch { let view = self.hitTest(touch.locationInView(self), withEvent: event) let previousView = touchesToViews[touch] if view != previousView { if let previousView = previousView as? KeyboardKey { previousView.highlighted = false } touchesToViews[touch] = view if let view = view as? KeyboardKey { view.highlighted = true } } } } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { for o in touches { if let touch = o as? UITouch { let view = touchesToViews[touch] if let view = view as? KeyboardKey { view.highlighted = false view.didSelect() } touchesToViews.removeValueForKey(touch) } } } override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { for o in touches { if let touch = o as? UITouch { let view = touchesToViews[touch] if let view = view as? KeyboardKey { view.highlighted = false } touchesToViews.removeValueForKey(touch) } } } } class KeyboardKey: UIView { /// A Boolean value represeting whether the key is highlighted (a touch is inside). var highlighted: Bool = false // What to do when this is selected. var action: () -> () = {} override init(frame: CGRect) { super.init(frame: frame) self.setTranslatesAutoresizingMaskIntoConstraints(false) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Called when a key has been selected. Subclasses can use this to present differently. Must call super! func didSelect() { action() } } class KeyboardDivider: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code self.setTranslatesAutoresizingMaskIntoConstraints(false) self.backgroundColor = KeyboardAppearance.dividerColorForAppearance(UIKeyboardAppearance.Default) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
381428404ec27babee44b6d009f5588a
28.136986
175
0.690958
false
false
false
false
carambalabs/UnsplashKit
refs/heads/master
UnsplashKit/Classes/UnsplashAPI/Models/Collection.swift
mit
1
import Foundation import Unbox // Used from user/:username/collections public struct Collection: Unboxable { // MARK: - Properties /// Collection identifier. public let id: Int /// Collection title. public let title: String /// Collection description. public let description: String? /// Collection published at. public let publishedAt: Date /// Collection curated. public let curated: Bool /// Collection featured. public let featured: Bool /// Collection total photos. public let totalPhotos: UInt /// Collection privateness. public let isPrivate: Bool /// Collection cover photo. public let coverPhoto: Photo? /// Collection user public let user: User? /// Collection links. public let links: CollectionLinks? // MARK: - Unboxable /// Initialize an instance of this model by unboxing a dictionary using an Unboxer public init(unboxer: Unboxer) throws { self.id = try unboxer.unbox(key: "id") self.title = try unboxer.unbox(key: "title") self.description = unboxer.unbox(key: "description") self.publishedAt = try unboxer.unbox(key: "published_at", formatter: DateFormatter.unsplash) self.curated = try unboxer.unbox(key: "curated") self.featured = try unboxer.unbox(key: "featured") self.totalPhotos = try unboxer.unbox(key: "total_photos") self.isPrivate = try unboxer.unbox(key: "private") self.coverPhoto = unboxer.unbox(key: "cover_photo") self.user = unboxer.unbox(key: "user") self.links = unboxer.unbox(key: "links") } } // MARK: - Resources public extension Collection { /// Resource that lists the collections. /// /// - Parameters: /// - page: page to be fetched. /// - perPage: number of items per page. /// - Returns: resource for fetching the collections. public static func list(page: Int = 1, perPage: Int = 10) -> Resource<[Collection]> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "page", value: "\(page)")) queryItems.append(URLQueryItem(name: "per_page", value: "\(perPage)")) return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource that returns the featured collections. /// /// - Parameters: /// - page: page to be fetched. /// - perPage: number of items to be fetched. /// - Returns: resource for fetching the featured collections. public static func featured(page: Int = 1, perPage: Int = 10) -> Resource<[Collection]> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "page", value: "\(page)")) queryItems.append(URLQueryItem(name: "per_page", value: "\(perPage)")) return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/featured" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for fetching curated collections. /// /// - Parameters: /// - page: page to be fetched. /// - perPage: number of items to be fetched. /// - Returns: resource for fetching curated collections. public static func curated(page: Int = 1, perPage: Int = 10) -> Resource<[Collection]> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "page", value: "\(page)")) queryItems.append(URLQueryItem(name: "per_page", value: "\(perPage)")) return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/curated" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for fetching a collection. /// /// - Parameter id: collection identifier. /// - Returns: resource for fetching the collection. public static func get(id: String) -> Resource<Collection> { let queryItems: [URLQueryItem] = [] return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(id)" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for fetching a collection photos. /// /// - Parameters: /// - id: collection id. /// - page: page to be fetched. /// - perPage: items per page. /// - Returns: resource for fetching the photos. public static func photos(id: String, page: Int = 1, perPage: Int = 10) -> Resource<[Photo]> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "page", value: "\(page)")) queryItems.append(URLQueryItem(name: "per_page", value: "\(perPage)")) return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(id)/photos" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for fetching the photos of a curated collection. /// /// - Parameters: /// - id: collection identifier. /// - page: page to be fetched. /// - perPage: number of items per page. /// - Returns: resource for fetching the photos. public static func curatedPhotos(id: String, page: Int = 1, perPage: Int = 10) -> Resource<[Photo]> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "page", value: "\(page)")) queryItems.append(URLQueryItem(name: "per_page", value: "\(perPage)")) return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/curated/\(id)/photos" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for fetching related collections to a given one. /// /// - Parameter id: collection identifier whose related ones will be fetched. /// - Returns: resource for fetching the related collections. public static func related(id: String) -> Resource<[Collection]> { let queryItems: [URLQueryItem] = [] return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(id)/related" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "GET" return request } } /// Resource for creating a collection. /// /// - Parameters: /// - title: collection title. /// - description: collection title. /// - isPrivate: collection private value. /// - Returns: resource for creating the collection. public static func create(title: String, description: String? = nil, isPrivate: Bool? = nil) -> Resource<Collection> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "title", value: title)) if let description = description { queryItems.append(URLQueryItem(name: "description", value: description)) } if let isPrivate = isPrivate { queryItems.append(URLQueryItem(name: "private", value: "\(isPrivate)")) } return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "POST" return request } } /// Resource for updating a collection. /// /// - Parameters: /// - id: collection identifier. /// - title: new title. /// - description: new description. /// - isPrivate: new private value. /// - Returns: resource for updating theh collection. public static func update(id: String, title: String? = nil, description: String? = nil, isPrivate: Bool? = nil) -> Resource<Collection> { var queryItems: [URLQueryItem] = [] if let title = title { queryItems.append(URLQueryItem(name: "title", value: title)) } if let description = description { queryItems.append(URLQueryItem(name: "description", value: description)) } if let isPrivate = isPrivate { queryItems.append(URLQueryItem(name: "private", value: "\(isPrivate)")) } return Resource { (components: URLComponents) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(id)" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "PUT" return request } } /// Resource for deleting the collection. /// /// - Parameter id: collection identifier. /// - Returns: resource for deleting the collection. public static func delete(id: String) -> Resource<Void> { let queryItems: [URLQueryItem] = [] return Resource(request: { (components) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(id)" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "DELETE" return request }, parse: { (_, _) -> Void in return () }) } /// Resource for adding a photo to a collection. /// /// - Parameters: /// - id: photo identifier. /// - collection: collection identifier. /// - Returns: resource for adding the photo. public static func addPhoto(with id: String, to collection: String) -> Resource<Void> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "photo_id", value: "\(id)")) return Resource(request: { (components) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(collection)/add" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "POST" return request }, parse: { (_, _) -> Void in return () }) } /// Resource for deleting a photo from a collection. /// /// - Parameters: /// - id: photo identifier. /// - collection: collection identifier. /// - Returns: resource for deleting the photo. public static func deletePhoto(with id: String, from collection: String) -> Resource<Void> { var queryItems: [URLQueryItem] = [] queryItems.append(URLQueryItem(name: "photo_id", value: "\(id)")) return Resource(request: { (components) -> URLRequest in var mutable: URLComponents = components mutable.path = "/collections/\(collection)/remove" mutable.queryItems = queryItems var request = URLRequest(url: mutable.url!) request.httpMethod = "DELETE" return request }, parse: { (_, _) -> Void in return () }) } }
da050d6a6013c19bff08234aec8fb62b
37.804878
100
0.575581
false
false
false
false
JGiola/swift
refs/heads/main
test/Distributed/Runtime/distributed_actor_func_calls_remoteCall_through_generic_and_inner.swift
apache-2.0
5
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s --color // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574 // UNSUPPORTED: OS=windows-msvc import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem protocol Greeting: DistributedActor { distributed func greeting() -> String distributed func greetingAsyncThrows() async throws -> String } extension Greeting { func greetLocal(name: String) async throws { try await print("\(greetingAsyncThrows()), \(name)!") // requirement is async throws, things work } func greetLocal2(name: String) { print("\(greeting()), \(name)!") } } extension Greeting where SerializationRequirement == Codable { // okay, uses Codable to transfer arguments. distributed func greetDistributed(name: String) async throws { // okay, we're on the actor try await greetLocal(name: name) } distributed func greetDistributed2(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } func greetDistributedNon(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } } extension Greeting where SerializationRequirement == Codable { nonisolated func greetAliceALot() async throws { try await greetDistributed(name: "Alice") // okay, via Codable let rawGreeting = try await greeting() // okay, via Self's serialization requirement // greetLocal(name: "Alice") // would be error: only 'distributed' instance methods can be called on a potentially remote distributed actor}} } } distributed actor Greeter: Greeting { distributed func greeting() -> String { "Hello" } distributed func greetingAsyncThrows() -> String { noop() // no await needed, we're in the same actor return "Hello from AsyncThrows" } func callNoop() { noop() // no await needed, we're in the same actor } distributed func noop() { // nothing } } func test() async throws { let system = DefaultDistributedActorSystem() let g = Greeter(actorSystem: system) let greeting = try await g.greeting() print("greeting(): \(greeting)") // CHECK: greeting(): Hello try await g.greetDistributed(name: "Caplin") // CHECK: Hello from AsyncThrows, Caplin! try await g.greetDistributed2(name: "Caplin") // CHECK: Hello, Caplin! } @main struct Main { static func main() async { try! await test() } }
e11d003de021247f9e02d48d0093b458
30.079208
222
0.7187
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
SwiftyEchartsTest_iOS/SectorGraphicSpec.swift
mit
1
// // SectorGraphicSpec.swift // SwiftyEcharts // // Created by Pluto Y on 08/08/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class SectorGraphicSpec: QuickSpec { override func spec() { let cxShapeValue: Float = 84.2736 let cyShapeValue: Float = 0.99999999 let rShapeValue: Float = 8888 let r0ShapeValue: Float = 0.547 let startAngleShapeValue: Float = 5736.973 let endAngleShapeValue: Float = 0.57346 let clockwiseShapeValue = false let shape = SectorGraphic.Shape() shape.cx = cxShapeValue shape.cy = cyShapeValue shape.r = rShapeValue shape.r0 = r0ShapeValue shape.startAngle = startAngleShapeValue shape.endAngle = endAngleShapeValue shape.clockwise = clockwiseShapeValue describe("For SectorGraphic.Shape") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "cx": cxShapeValue, "cy": cyShapeValue, "r": rShapeValue, "r0": r0ShapeValue, "startAngle": startAngleShapeValue, "endAngle": endAngleShapeValue, "clockwise": clockwiseShapeValue ] expect(shape.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let shapeByEnums = SectorGraphic.Shape( .cx(cxShapeValue), .cy(cyShapeValue), .r(rShapeValue), .r0(r0ShapeValue), .startAngle(startAngleShapeValue), .endAngle(endAngleShapeValue), .clockwise(clockwiseShapeValue) ) expect(shapeByEnums.jsonString).to(equal(shape.jsonString)) } } describe("For SectorGraphic") { let typeValue = GraphicType.sector let idValue = "sectorGraphicIdValue" let actionValue = GraphicAction.remove let leftValue = Position.insideTop let topValue = Position.insideLeft let rightValue = Position.insideBottom let bottomValue = Position.insideRight let boundingValue = GraphicBounding.all let zValue: Float = 75.2764 let zlevelValue: Float = 0.02746 let silentValue = false let invisibleValue = false let cursorValue = "sectorGraphicCursorValue" let draggableValue = true let progressiveValue = true let shapeValue = shape let styleValue = CommonGraphicStyle( .fill(Color.transparent), .stroke(Color.red), .lineWidth(0.000001), .shadowBlur(7.7777777), .shadowOffsetX(8), .shadowOffsetY(0), .shadowColor(Color.green) ) let sectorGraphic = SectorGraphic() sectorGraphic.id = idValue sectorGraphic.action = actionValue sectorGraphic.left = leftValue sectorGraphic.right = rightValue sectorGraphic.top = topValue sectorGraphic.bottom = bottomValue sectorGraphic.bounding = boundingValue sectorGraphic.z = zValue sectorGraphic.zlevel = zlevelValue sectorGraphic.silent = silentValue sectorGraphic.invisible = invisibleValue sectorGraphic.cursor = cursorValue sectorGraphic.draggable = draggableValue sectorGraphic.progressive = progressiveValue sectorGraphic.shape = shapeValue sectorGraphic.style = styleValue it("needs to check the type value") { expect(sectorGraphic.type.jsonString).to(equal(typeValue.jsonString)) } it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeValue, "id": idValue, "$action": actionValue, "left": leftValue, "right": rightValue, "top": topValue, "bottom": bottomValue, "bounding": boundingValue, "z": zValue, "zlevel": zlevelValue, "silent": silentValue, "invisible": invisibleValue, "cursor": cursorValue, "draggable": draggableValue, "progressive": progressiveValue, "shape": shapeValue, "style": styleValue ] expect(sectorGraphic.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let sectorGraphicByEnums = SectorGraphic( .id(idValue), .action(actionValue), .left(leftValue), .right(rightValue), .top(topValue), .bottom(bottomValue), .bounding(boundingValue), .z(zValue), .zlevel(zlevelValue), .silent(silentValue), .invisible(invisibleValue), .cursor(cursorValue), .draggable(draggableValue), .progressive(progressiveValue), .shape(shapeValue), .style(styleValue) ) expect(sectorGraphicByEnums.jsonString).to(equal(sectorGraphic.jsonString)) } } } }
21c4a87c75a3ad2706023c908434df14
36.962264
91
0.509278
false
false
false
false
ajsnow/Forthwith
refs/heads/master
Source/Words.swift
mit
1
// // Words.swift // Forthwith // // Created by Andrew Snow on 10/6/15. // Copyright © 2015 Andrew Snow. All rights reserved. // // MARK: - Stack Manipulation public func drop<T>(s: Stack<T>) { s.drop() } public func drop2<T>(s: Stack<T>) { s.drop(); s.drop() } public func dropAll<T>(s: Stack<T>) { s.removeAll() } public func dup<T>(s: Stack<T>) { s .. s.peek() } public func dup2<T>(s: Stack<T>) { let (b, a) = (s.pop(), s.pop()); s .. b .. a .. b .. a } public func swap<T>(s: Stack<T>) { let (b, a) = (s.pop(), s.pop()); s .. b .. a } public func over<T>(s: Stack<T>) { let (b, a) = (s.pop(), s.pop()); s .. a .. b .. a } public func rot<T>(s: Stack<T>) { let (c, b, a) = (s.pop(), s.pop(), s.pop()); s .. b .. c .. a } public func rightRot<T>(s: Stack<T>) { let (c, b, a) = (s.pop(), s.pop(), s.pop()); s .. c .. a .. b } public func nip<T>(s: Stack<T>) { s .. swap .. drop } public func tuck<T>(s: Stack<T>) { s .. swap .. over } // FIXME: Workaround: The compiler cannot figure out which `dup` to call. public let ddup = { $0 .. (dup as (Stack<Cell>)->() ) } public let ddup2 = { $0 .. (dup2 as (Stack<Cell>)->() ) } // MARK: - Control Flow // We'd prefer the curried function to take an Int (or Bool) instead of the Stack, // (and therefore return a Word instead of null) but we haven't figured out a way // to signal that it should then execute the resulting function as a Word instead // of the 'MoreMagic' way, which fails since the next item on the stack isn't // itself a stack. // // I think we could do soemthing more interesting still: we have if, else, then as // words and overload `..` to be right-associative with them and higher priority, // but that seems like too much work for now. /// If `if` then `then` else `else`. :) public func `if`(then: Word, `else`: Word? = nil)(s: Stack<Cell>) { if s.pop(Bool) { s .. then } else if let `else` = `else` { s .. `else` } // Nil coalescing doesn't seem to work for optional closures, // so my preferred way of writting this doesn't currently work: // s .. (s.pop(Bool) ? then : `else` ?? { _ in } as Word) } /// While checks the top of the stack for a `Bool`, if true, it executes the body, /// and then checks the top again, if false, it jumps over the body. This is similar /// to Forth's `begin` ... `while` ... `repeat` but there is no seperate begin phase. /// Therefore the the programmer will generally first push a `true`, and add the Bool's /// setup/test/creation as the last part of the body. /// Any body ending in `.. true` loops forever. public func `while`(body: Word)(s: Stack<Cell>) -> Stack<Cell> { while s.pop(Bool) { s .. body } return s } /// Loop executes the `body` n times where n is the difference between the top two /// `Int`s on the `Stack`. It behaves much like the Forth word `do?`, except that /// it accepts its bounds in either order (i.e. it will never wrap around through /// Int.max / Int.min). public func loop(body: Word)(s: Stack<Cell>) -> Stack<Cell> { let i = s.pop(Int) let bound = s.pop(Int) let range = i.stride(to: bound, by: i < bound ? 1 : -1) for _ in range { s .. body } return s } // A version of `loop` that exposes the index as %1. public func loopCnt(body: Word)(s: Stack<Cell>) -> Stack<Cell> { let i = s.pop(Int) let bound = s.pop(Int) let range = i.stride(to: bound, by: i < bound ? 1 : -1) for i in range { s .. i .. body } return s } // MARK: - Words, Words, Words public func dot<T>(s: Stack<T>) { print(s.pop(), terminator: "") } public let cr: Word = { print(""); return $0 } public let emit: Word = { print(UnicodeScalar($0.pop(Int)), terminator: ""); return $0 } /// Tick encloses a function (or `Word`) in a `Cell` so that it can be pushed onto the `Stack`. public func tick<A, B>(fn: A -> B)(s: Stack<Cell>) -> Stack<Cell> { s.push(fn); return s } /// Execute takes a Word from the top of the `Stack` and applies it to the stack. public let execute: Word = { let word = $0.pop(Word); return $0 .. word } // We'd like to be able to store stack values back to variables, but // partial application of functions with 'inout' parameters is not allowed. //public func store<T>(inout location: T)(newValue: T) -> () { // location = newValue //} // MARK: - Debug /// While Stack<T> words must be defined with the usual function notation, `Word` /// i.e. Stack<Cell> -> () may be defined in a compact (& thus more Forth-ish) way. public let depth = { $0 .. $0.depth } // Needed for two reasons: // 1. The compiler special cases `print`, telling us it's not a keyword. // 2. Its optional arguments mess up our normal composition word. // `.forEach(print)` has the same problems. public func printStack<T>(s: Stack<T>) { print(s) } // MARK: - Fun/Test public func fib(s: Stack<Cell>) { s .. 0 .. 1 .. rot .. 0 .. loop { $0 .. over .. (+) .. swap } .. drop }
bdedca6e65e7d2a84384f7c0124cb296
37.398438
102
0.616199
false
false
false
false
Ivacker/swift
refs/heads/master
test/Parse/switch.swift
apache-2.0
7
// RUN: %target-parse-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{braced block of statements is an unused closure}} expected-error{{expression resolves to an unused function}} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case let z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case let y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{type 'Int' does not conform to protocol 'BooleanType'}} x = 0 default: x = 1 } // Multiple cases per case block switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (let a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, let a): () case (let a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} case (1, let b): () case (1, let b): // let bindings () // var bindings are not allowed in cases. // FIXME: rdar://problem/23378003 // This will eventually be an error. case (1, var b): // expected-error {{Use of 'var' binding here is not allowed}} {{10-13=let}} () case (var a, 2): // expected-error {{Use of 'var' binding here is not allowed}} {{7-10=let}} () case (let a, 2), (1, let b): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () case (let a, 2), (1, _): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () case (_, 2), (let a, _): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () // OK case (_, 2), (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } // Fallthroughs can't transfer control into a case label with bindings. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' cannot transfer control to a case label that declares variables}} case (let a, let b): t = (b, a) } func test_label(x : Int) { Gronk: switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{enum case 'Bar' not found in type '(Int, Int)'}} break default: break } }
f9787da261f9f457da3da374cb693dc3
25.334601
336
0.653046
false
false
false
false
daaavid/TIY-Assignments
refs/heads/master
11--The-Grail-Diary/The-Grail-Diary/The-Grail-Diary/SolSystem.swift
cc0-1.0
1
// // Sites.swift // The-Grail-Diary // // Created by david on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class SolSystem { var name: String var distance: String var orbit: String var mass: String var picture: String init(dictionary: NSDictionary) { name = dictionary["name"] as! String distance = dictionary["distance"] as! String orbit = dictionary["orbit"] as! String mass = dictionary["mass"] as! String picture = dictionary["picture"] as! String } }
18b20aedb278136dc1970978ac974192
20.555556
56
0.621343
false
false
false
false
shhuangtwn/ProjectLynla
refs/heads/master
Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisYHighLayerDefault.swift
mit
1
// // ChartAxisYHighLayerDefault.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// A ChartAxisLayer for high Y axes class ChartAxisYHighLayerDefault: ChartAxisYLayerDefault { override var low: Bool {return false} /// The start point of the axis line. override var lineP1: CGPoint { return self.p1 } /// The end point of the axis line. override var lineP2: CGPoint { return self.p2 } override func initDrawers() { self.lineDrawer = self.generateLineDrawer(offset: 0) let labelsOffset = self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth self.labelDrawers = self.generateLabelDrawers(offset: labelsOffset) let axisTitleLabelsOffset = labelsOffset + self.labelsMaxWidth + self.settings.axisTitleLabelsToLabelsSpacing self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: axisTitleLabelsOffset) } override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer { let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke begins at the beginning of the frame, not in the middle of it let x = self.p1.x + offset + halfStrokeWidth let p1 = CGPointMake(x, self.p1.y) let p2 = CGPointMake(x, self.p2.y) return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor, strokeWidth: self.settings.axisStrokeWidth) } override func labelsX(offset offset: CGFloat, labelWidth: CGFloat, textAlignment: ChartLabelTextAlignment) -> CGFloat { var labelsX: CGFloat switch textAlignment { case .Left, .Default: labelsX = self.p1.x + offset case .Right: labelsX = self.p1.x + offset + self.labelsMaxWidth - labelWidth } return labelsX } }
236a92d0fc26ad2eb0384f284aa75e6b
35.074074
152
0.677618
false
false
false
false
ixx1232/Getting-Started-swift
refs/heads/master
GettingStartedSwift/GettingStartedSwift/简单值.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" /// 简单值 // 使用 let 来声明常量, 使用 var 来声明变量. 一个常量的值, 在编译的时候, 并不需要有明确地值, 但是你只能为它赋值一次, 也就是说你可以用常量来表示这样这样一个值: 你指需要决定一次, 但是需要使用很多次. var myVariable = 42 myVariable = 50 let myConstant = 42 // 常量或者变量的类型必须和你赋给它们的值一样. 然而, 声明时类型是可选的, 声明的同时赋值的话,编译器会自动推断类型. 在上面的例子中, 编译器推断出 myVariable是一个整数 (integer) 因为它的初始值是整数. // 如果初始值没有提供足够的信息 (或者没有初始值), 那你需要在变量后面声明类型, 用冒号分割. let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble: Double = 70 // 练习: 创建一个常量, 显示指定类型为 Float 并指定初始值为 4 let explicitDouble1: Double = 4 // 值永远不会被隐式转换为其他类型. 如果你需要把一个值转换成其他类型, 请显示转换 let label = "The width is " let width = 94 let widthLabel = label + String(width) // 练习: 删除最后一行中的 String, 错误提示是什么? // error: Binary operator '+' cannot be applied to operands of type 'String' and 'Int' // 产生这个错误的原因是: 类型不一致 // 有一种更简单的把值转换成字符串的方法:把值写到括号中, 并且在括号之前写一个反斜扛. 例如: let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." // 练习: 使用 \()来把一个浮点计算转换成字符串, 并加上某人的名字, 和他打个招呼. // 3a: Floating point calculation let revenue: Float = 160.0 let cost: Float = 70.0 let profit: String = "Today my lemonade stand made \(revenue-cost) dollars of profit" // 3b: Use someone's name in a greeting let personsName: String = "Josh" let greetJosh = "Hi \(personsName)" // 使用方括号 [] 来创建数组和字典, 并使用下标或者键 (key) 来访问元素. var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" shoppingList var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" occupations // 要创建一个空数组或者字典, 使用初始化语法. let emptyArray = [String]() let emptyDictionary = [String: Float]() // 如果类型信息可以被推断出来, 你可以用[] 和 [:] 来创建空数组和空字典--就像你声明变量或者给函数传参数的时候一样 shoppingList = [] occupations = [:]
05b778e41dee1a338b95b16fd14640e8
23.802632
116
0.718302
false
false
false
false
chayelheinsen/PushForParse
refs/heads/master
PushForParse/PushForParseWatchApp Extension/CoreDataController.swift
mit
1
// // CoreDataController.swift // PushForParseWatchApp Extension // // Created by Chayel Heinsen on 10/18/15. // Copyright © 2015 Chayel Heinsen. All rights reserved. // import UIKit import CoreData class CoreDataController: NSObject { // MARK: - Core Data stack static let sharedManager = CoreDataController() lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.chayelheinsen.PushForParse" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("PushForParse", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PushForParse.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
329b17f856f0db653b672ec0f9e8c383
51.607595
291
0.692659
false
false
false
false
rock-n-code/Kashmir
refs/heads/master
Kashmir/Shared/Features/Operations/Extensions/OperationQueueExtensions.swift
mit
1
// // OperationQueueExtensions.swift // Kashmir // // Created by Javier Cicchelli on 21/08/2017. // Copyright © 2017 Rock & Code. All rights reserved. // import Foundation extension OperationQueue { // MARK: Initializers /** Creates a new queue. - parameters: - name: Custom queue name. - maxConcurrentOperationCount: The max concurrent operation count. - qualityOfService: The default service level to apply to operations executed using the queue. */ public convenience init(name: String, maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, qualityOfService: QualityOfService = .default) { self.init() self.name = name self.maxConcurrentOperationCount = maxConcurrentOperationCount self.qualityOfService = qualityOfService } // MARK: Functions /** Add multiple operations to the queue at once. - parameter ops: An array of `Operation` objects that you want to add to the queue. - note: The operations are added to the queue and control returns immediately to the caller. */ public func add(operations ops: [Operation]) { ops.forEach { addOperation($0) } } /** Add a list of chained operations to the queue at once. - parameter ops: An array of `Operation` objects that you want to chain and add to the queue. - note: The operations are added to the queue and control returns immediately to the caller. */ public func add(chainedOperations ops: [Operation]) { ops.enumerated().forEach { (index, operation) in if index > 0 { operation.addDependency(ops[index - 1]) } addOperation(operation) } } /// Pause the queue. public func pause() { isSuspended = true operations.forEach { if let operation = $0 as? ConcurrentOperation { operation.pause() } } } /// Resume the queue. public func resume() { isSuspended = false operations.forEach { if let operation = $0 as? ConcurrentOperation { operation.resume() } } } }
45df08994871b3a2f8b64e66a7c547fd
22.604651
110
0.689655
false
false
false
false
jmgc/swift
refs/heads/master
test/SILOptimizer/specialize_opaque_type_archetypes.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_2.swift -module-name External -emit-module -emit-module-path %t/External.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_3.swift -enable-library-evolution -module-name External2 -emit-module -emit-module-path %t/External2.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_4.swift -I %t -enable-library-evolution -module-name External3 -emit-module -emit-module-path %t/External3.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_3.swift -I %t -enable-library-evolution -module-name External2 -Osize -emit-module -o - | %target-sil-opt -module-name External2 | %FileCheck --check-prefix=RESILIENT %s // RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -enforce-exclusivity=checked -Osize -emit-sil -sil-verify-all %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -enforce-exclusivity=checked -enable-library-evolution -Osize -emit-sil -sil-verify-all %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize import External import External2 import External3 public protocol P { func myValue() -> Int64 } extension Int64: P { public func myValue() -> Int64 { return self } } @inline(never) func useP<T: P> (_ t: T) { print(t) } public func bar(_ x: Int64) -> some P { return x } public func foo(_ x: Int64) -> some P { if x > 0 { return bar(x + 1) } return bar(x - 1) } @inline(never) func getInt() -> Int64 { return 2 } @inline(never) func identity<T>(_ t: T) -> T { return t } // CHECK-LABEL: sil @$s1A10testFooBaryyxAA1PRzlF : $@convention(thin) <T where T : P> (@in_guaranteed T) -> () { // CHECK: bb3([[FOOS_INT:%.*]] : $Builtin.Int64): // CHECK: [[FOO_RES:%.*]] = struct $Int64 ([[FOOS_INT]] : $Builtin.Int64) // CHECK: [[ID:%.*]] = function_ref @$s1A8identityyxxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> Int64 // CHECK: [[ID_RES:%.*]] = apply [[ID]]([[FOO_RES]]) : $@convention(thin) (Int64) -> Int64 // CHECK: [[USEP:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: apply [[USEP]]([[ID_RES]]) : $@convention(thin) (Int64) -> () // CHECK: apply [[USEP]]([[FOO_RES]]) : $@convention(thin) (Int64) -> () public func testFooBar<T:P>(_ t : T) { let x = foo(getInt()) useP(identity(x)) useP(x.myValue()) } struct AddressOnly : P{ var p : P = Int64(1) func myValue() -> Int64 { return p.myValue() } } public func addressOnlyFoo() -> some P { return AddressOnly() } // CHECK-LABEL: sil @$s1A21testAddressOnlyFoobaryyF // CHECK-NOT: return type of // CHECK: return public func testAddressOnlyFoobar() { let x = addressOnlyFoo() let y = x useP(x.myValue()) useP(y.myValue()) } public protocol CP : class { func myValue() -> Int64 } class C : CP { func myValue() -> Int64 { return 0 } } public func returnC() -> some CP { return C() } // CHECK-LABEL: sil @$s1A4useCyyF // CHECK: [[FUN:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: [[INT:%.*]] = struct $Int64 ( // CHECK: = apply [[FUN]]([[INT]]) public func useC() { let c = returnC() useP(c.myValue()) } // CHECK-LABEL: sil @$s1A11useExternalyyF // CHECK: // function_ref Int64.myValue2() // CHECK: [[FUN:%.*]] = function_ref @$ss5Int64V8ExternalE8myValue2AByF // CHECK: apply [[FUN]] public func useExternal() { let e = external() useP(e.myValue2()) } // Call to a resilient function should not be specialized. // CHECK-LABEL: sil @$s1A20useExternalResilientyyF // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External217externalResilientQryF : $@convention(thin) () -> @out @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: apply [[FUN]]([[RES]]) // CHECK: witness_method // CHECK: return public func useExternalResilient() { let e = externalResilient() useP(e.myValue3()) } struct Container { var x : some P { get { return Int64(1) } } } // CHECK-LABEL: sil @$s1A11usePropertyyyF // CHECK: [[VAL:%.*]] = struct $Int64 // CHECK: // function_ref specialized useP<A>(_:) // CHECK: [[FUN:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: apply [[FUN]]([[VAL]]) public func useProperty() { let p = Container().x useP(p.myValue()) } protocol Q { associatedtype T func f() -> T associatedtype T2 func g() -> T2 } struct S : Q { func f()->some P { return Int64(1) } func g()->some CP { return C() } } struct Container2 { var member : S.T mutating func blah(_ x: S.T) { member = x } } class Container3 { @inline(__always) init(member : S.T) { self.member = member } var member : S.T func blah(_ x: S.T) { member = x } } struct Container4 { var member : S.T2 mutating func blah(_ x: S.T2) { member = x } } struct Container5 { var member : (S.T2, S.T) mutating func blah(_ x: S.T2, _ y: S.T) { member = (x,y) } } struct Pair<T, V> { var first: T var second: V } // CHECK-LABEL: sil @$s1A10storedPropyyF // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: return public func storedProp() { var c = Container2(member: S().f()) c.blah(S().f()) var c2 = Container3(member: S().f()) c2.blah(S().f()) var c3 = Container4(member: S().g()) c3.blah(S().g()) var s = S() var c4 = Container5(member: (s.g(), s.f())) c4.blah(s.g(), s.f()) } public func usePair() { var x = Pair(first: bar(1), second: returnC()) useP(x.first.myValue()) useP(x.second.myValue()) } struct MyInt64 : ExternalP2 { var x = Int64(0) public func myValue3() -> Int64 { return x + 3 } } func nonResilient() -> some ExternalP2 { return MyInt64() } // CHECK-LABEL: sil @$s1A019usePairResilientNonC0yyF : $@convention(thin) () -> () // CHECK: alloc_stack $Pair<MyInt64, @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[USEP:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: [[FIRST_MYVALUE3:%.*]] = struct $Int64 // CHECK: apply [[USEP]]([[FIRST_MYVALUE3]]) // CHECK: [[MYVALUE_WITNESS:%.*]] = witness_method $@_opaqueReturnTypeOf("$s9External217externalResilientQryF" // CHECK: [[SECOND_MYVALUE3:%.*]] = apply [[MYVALUE_WITNESS]] // CHECK: apply [[USEP]]([[SECOND_MYVALUE3]]) // CHECK: return public func usePairResilientNonResilient() { var x = Pair(first: nonResilient(), second: externalResilient()) useP(x.first.myValue3()) useP(x.second.myValue3()) } public protocol P3 { associatedtype AT func foo() -> AT } public struct Adapter<T: P3>: P3 { var inner: T public func foo() -> some P3 { return inner } } // Don't assert. // CHECK-LABEL: sil {{.*}} @$s1A7AdapterVyxGAA2P3A2aEP3foo2ATQzyFTW // CHECK: [[F:%.*]] = function_ref @$s1A7AdapterV3fooQryF // CHECK: apply [[F]]<τ_0_0>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : P3> (@in_guaranteed Adapter<τ_0_0>) -> extension P3 { public func foo() -> some P3 { return Adapter(inner: self) } } // We should specialize the opaque type because the resilient function is // inlineable. // CHECK-LABEL: sil @$s1A21useExternalResilient2yyF : $@convention(thin) () -> () // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External226inlinableExternalResilientQryF : $@convention(thin) () -> @out Int64 // CHECK: apply [[FUN]]([[RES]]) // CHECK: return public func useExternalResilient2() { let e = inlinableExternalResilient() useP(e.myValue3()) } // In this case we should only 'peel' one layer of opaque archetypes. // CHECK-LABEL: sil @$s1A21useExternalResilient3yyF // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External3031inlinableExternalResilientCallsD0QryF : $@convention(thin) () -> @out @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: apply [[FUN]]([[RES]]) public func useExternalResilient3() { let e = inlinableExternalResilientCallsResilient() useP(e.myValue3()) } // Check that we can look throught two layers of inlinable resilient functions. // CHECK-LABEL: sil @$s1A21useExternalResilient4yyF // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External3040inlinableExternalResilientCallsInlinablecD0QryF : $@convention(thin) () -> @out Int64 // CHECK: apply [[FUN]]([[RES]]) public func useExternalResilient4() { let e = inlinableExternalResilientCallsInlinableExternalResilient() useP(e.myValue3()) } // CHECK-LABEL: sil @$s1A18testStoredPropertyyyF // CHECK: [[CONTAINER_INIT_FUN:%.*]] = function_ref @$s8External0A9ContainerVACycfC // CHECK: [[CONTAINER:%.*]] = apply [[CONTAINER_INIT_FUN]] // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[COMPUTED_PROP:%.*]] = function_ref @$s8External0A9ContainerV16computedPropertyQrvg // CHECK: apply [[COMPUTED_PROP]]([[RES]], [[CONTAINER]]) // CHECK: [[MYVALUE:%.*]] = function_ref @$ss5Int64V8ExternalE8myValue2AByF : $@convention(method) (Int64) -> Int64 // CHECK: apply [[MYVALUE]] public func testStoredProperty() { let c = ExternalContainer() useP(c.computedProperty.myValue2()) } // CHECK-LABEL: sil @$s1A21testResilientPropertyyyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV16computedPropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientProperty() { let r = ResilientContainer() useP(r.computedProperty.myValue3()) } // CHECK-LABEL: sil @$s1A30testResilientInlinablePropertyyyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV18inlineablePropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty() { let r = ResilientContainer() useP(r.inlineableProperty.myValue3()) } // CHECK-LABEL: sil @$s1A31testResilientInlinableProperty3yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV19inlineableProperty2Qrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty3() { let r = ResilientContainer() useP(r.inlineableProperty2.myValue3()) } // CHECK-LABEL: sil @$s1A22testResilientProperty2yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External319ResilientContainer2V16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V16computedPropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientProperty2() { let r = ResilientContainer2() useP(r.computedProperty.myValue3()) } // The inlinable property recursively calls an resilient property 'peel' one layer of opaque archetypes. // CHECK-LABEL: sil @$s1A31testResilientInlinableProperty2yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V18inlineablePropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty2() { let r = ResilientContainer2() useP(r.inlineableProperty.myValue3()) } // CHECK-LABEL: sil @$s1A035testResilientInlinablePropertyCallsbC0yyF : $@convention(thin) () -> () { // CHECK: [[CONTAINTER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V023inlineablePropertyCallsB10InlineableQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINTER]]) public func testResilientInlinablePropertyCallsResilientInlinable() { let r = ResilientContainer2() useP(r.inlineablePropertyCallsResilientInlineable.myValue3()) } // RESILIENT-LABEL: sil [serialized] [canonical] @$s9External218ResilientContainerV17inlineableContextyyF // RESILIENT: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // RESILIENT: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV16computedPropertyQrvg // RESILIENT: apply [[FUN]]([[RES]], %0) public protocol P4 { associatedtype AT func foo(_ x: Int64) -> AT func test() } struct PA : P4 { func foo(_ x: Int64) -> some P { return Int64(x) } } // CHECK-LABEL: sil private [transparent] [thunk] @$s1A2PAVAA2P4A2aDP4testyyFTW // CHECK: [[V:%.*]] = load %0 : $*PA // CHECK: [[F:%.*]] = function_ref @$s1A2PAV4testyyF // CHECK: apply [[F]]([[V]]) // CHECK-64-LABEL: sil hidden @$s1A2PAV4testyyF : $@convention(method) (PA) -> () // CHECK-64: [[V:%.*]] = integer_literal $Builtin.Int64, 5 // CHECK-64: [[I:%.*]] = struct $Int64 ([[V]] : $Builtin.Int64) // CHECK-64: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () // CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () @inline(never) func testIt<T>(cl: (Int64) throws -> T) { do { print(try cl(5)) } catch (_) {} } // CHECK-LABEL: sil shared [noinline] @$s1A16testPartialApplyyyxAA2P4RzlFAA2PAV_Tg5 // CHECK: [[PA:%.*]] = alloc_stack $PA // CHECK: store %0 to [[PA]] : $*PA // CHECK: [[F:%.*]] = function_ref @$s1A16testPartialApplyyyxAA2P4RzlF2ATQzs5Int64Vcxcfu_AeGcfu0_AA2PAV_TG5 : $@convention(thin) (Int64, @in_guaranteed PA) -> @out Int64 // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[F]]([[PA]]) : $@convention(thin) (Int64, @in_guaranteed PA) -> @out Int64 // CHECK: convert_function [[C]] : $@callee_guaranteed (Int64) -> @out Int64 to $@callee_guaranteed @substituted <τ_0_0> (Int64) -> (@out τ_0_0, @error Error) for <Int64> @inline(never) func testPartialApply<T: P4>(_ t: T) { let fun = t.foo testIt(cl: fun) print(fun(5)) } public func testPartialApply() { testPartialApply(PA()) } struct Trivial<T> { var x : Int64 } func createTrivial<T>(_ t: T) -> Trivial<T> { return Trivial<T>(x: 1) } // CHECK: sil @$s1A11testTrivialyyF : $@convention(thin) () -> () // CHECK: %0 = integer_literal $Builtin.Int64, 1 // CHECK: %1 = struct $Int64 (%0 : $Builtin.Int64) // CHECK: %2 = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: %3 = apply %2(%1) public func testTrivial() { let s = bar(10) let t = createTrivial(s) useP(t.x) } func createTuple<T>(_ t: T) -> (T,T) { return (t, t) } // CHECK: sil @$s1A9testTupleyyF // CHECK: [[I:%.*]] = integer_literal $Builtin.Int64, 10 // CHECK: [[I2:%.*]] = struct $Int64 ([[I]] : $Builtin.Int64) // CHECK: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: apply [[F]]([[I2]]) : $@convention(thin) (Int64) -> () // CHECK: apply [[F]]([[I2]]) : $@convention(thin) (Int64) -> () public func testTuple() { let s = bar(10) let t = createTuple(s) useP(t.0) useP(t.1) } extension PA { func test() { var p = (foo, foo) useP(p.0(5)) useP(p.1(5)) } } public struct Foo { var id : Int = 0 var p : Int64 = 1 } struct Test : RandomAccessCollection { struct Index : Comparable, Hashable { var identifier: AnyHashable? var offset: Int static func < (lhs: Index, rhs: Index) -> Bool { return lhs.offset < rhs.offset } func hash(into hasher: inout Hasher) { hasher.combine(identifier) hasher.combine(offset) } } let foos: [Foo] let ids: [AnyHashable] init(foos: [Foo]) { self.foos = foos self.ids = foos.map { $0.id } } func _index(atOffset n: Int) -> Index { return Index(identifier: ids.isEmpty ? nil : ids[n], offset: n) } var startIndex: Index { return _index(atOffset: 0) } var endIndex: Index { return Index(identifier: nil, offset: ids.endIndex) } func index(after i: Index) -> Index { return _index(atOffset: i.offset + 1) } func index(before i: Index) -> Index { return _index(atOffset: i.offset - 1) } func distance(from start: Index, to end: Index) -> Int { return end.offset - start.offset } func index(_ i: Index, offsetBy n: Int) -> Index { return _index(atOffset: i.offset + n) } subscript(i: Index) -> some P { return foos[i.offset].p } } @inline(never) func useAbstractFunction<T: P>(_ fn: (Int64) -> T) {} public func testThinToThick() { useAbstractFunction(bar) } // CHECK-LABEL: sil @$s1A19rdar56410009_normalyyF public func rdar56410009_normal() { // CHECK: [[EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF // CHECK: = apply [[EXTERNAL_RESILIENT_WRAPPER]]<@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) 🦸>({{%.+}}, {{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : ExternalP2> (@in_guaranteed τ_0_0) -> @out @_opaqueReturnTypeOf("$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF", 0) 🦸<τ_0_0> _ = externalResilientWrapper(externalResilient()) } // CHECK: end sil function '$s1A19rdar56410009_normalyyF' // CHECK-LABEL: sil @$s1A25rdar56410009_inlinedInneryyF public func rdar56410009_inlinedInner() { // CHECK: [[EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF // CHECK: = apply [[EXTERNAL_RESILIENT_WRAPPER]]<Int64>({{%.+}}, {{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : ExternalP2> (@in_guaranteed τ_0_0) -> @out @_opaqueReturnTypeOf("$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF", 0) 🦸<τ_0_0> _ = externalResilientWrapper(inlinableExternalResilient()) } // CHECK: end sil function '$s1A25rdar56410009_inlinedInneryyF' // CHECK-LABEL: sil @$s1A25rdar56410009_inlinedOuteryyF public func rdar56410009_inlinedOuter() { // CHECK: [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5 // CHECK: = apply [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER]]({{%.+}}, {{%.+}}) : $@convention(thin) (@in_guaranteed @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) 🦸) -> @out WrapperP2<@_opaqueReturnTypeOf("$s9External217externalResilientQryF" _ = inlinableExternalResilientWrapper(externalResilient()) } // CHECK: end sil function '$s1A25rdar56410009_inlinedOuteryyF' // Specialized from above // CHECK-LABEL: sil shared [noinline] @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5 // CHECK: [[WRAPPER_INIT:%.+]] = function_ref @$s9External29WrapperP2VyACyxGxcfC // CHECK: = apply [[WRAPPER_INIT]]<@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) 🦸>({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : ExternalP2> (@in τ_0_0, @thin WrapperP2<τ_0_0>.Type) -> @out WrapperP2<τ_0_0> // CHECK: end sil function '$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5' // Specialized from below // CHECK-LABEL: sil shared [noinline] @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5 // CHECK: [[WRAPPER_INIT:%.+]] = function_ref @$s9External29WrapperP2VyACyxGxcfC // CHECK: = apply [[WRAPPER_INIT]]<Int64>({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : ExternalP2> (@in τ_0_0, @thin WrapperP2<τ_0_0>.Type) -> @out WrapperP2<τ_0_0> // CHECK: end sil function '$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5' // CHECK-LABEL: sil @$s1A24rdar56410009_inlinedBothyyF public func rdar56410009_inlinedBoth() { // CHECK: [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5 // CHECK: = apply [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int64) -> @out WrapperP2<Int64> _ = inlinableExternalResilientWrapper(inlinableExternalResilient()) } // CHECK: end sil function '$s1A24rdar56410009_inlinedBothyyF'
0e340363394c11cf45c69f51df7ad350
35.172712
316
0.670693
false
true
false
false
naoyashiga/Dunk
refs/heads/master
DribbbleReader/Shot.swift
mit
1
// // Shot.swift // DribbbleReader // // Created by naoyashiga on 2015/05/17. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import Foundation class Shot: DribbbleBase { var imageUrl:String! var htmlUrl:String! var imageData: Data? var shotName = "" var designerName = "" var avatarUrl = "" var shotCount = 0 override init(data: NSDictionary) { super.init(data: data) let images = data["images"] as! NSDictionary self.imageUrl = Utils.getStringFromJSON(images, key: "normal") self.htmlUrl = data["html_url"] as! String shotName = data["title"] as! String let user = data["user"] as! NSDictionary designerName = Utils.getStringFromJSON(user, key: "name") avatarUrl = Utils.getStringFromJSON(user, key: "avatar_url") shotCount = data["views_count"] as! Int } }
3dbe0b853d2f0eef31bc9bbf42dfa9d8
25.852941
70
0.615553
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/Buttons/examples/ButtonsPointerInteractionExample.swift
apache-2.0
2
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialButtons_Theming import MaterialComponents.MaterialContainerScheme class ButtonsPointerInteractionExample: UIViewController { let floatingButtonPlusDimension = CGFloat(24) let kMinimumAccessibleButtonSize = CGSize(width: 64, height: 48) @objc var containerScheme: MDCContainerScheming = MDCContainerScheme() lazy var containedButton: MDCButton = { let containedButton = MDCButton() containedButton.applyContainedTheme(withScheme: containerScheme) containedButton.setTitle("Tap Me Too", for: UIControl.State()) containedButton.sizeToFit() let containedButtonVerticalInset = min(0, -(kMinimumAccessibleButtonSize.height - containedButton.bounds.height) / 2) let containedButtonHorizontalInset = min(0, -(kMinimumAccessibleButtonSize.width - containedButton.bounds.width) / 2) containedButton.hitAreaInsets = UIEdgeInsets( top: containedButtonVerticalInset, left: containedButtonHorizontalInset, bottom: containedButtonVerticalInset, right: containedButtonHorizontalInset) containedButton.translatesAutoresizingMaskIntoConstraints = false containedButton.addTarget(self, action: #selector(tap), for: .touchUpInside) #if compiler(>=5.2) if #available(iOS 13.4, *) { containedButton.isPointerInteractionEnabled = true } #endif return containedButton }() lazy var textButton: MDCButton = { let textButton = MDCButton() textButton.applyTextTheme(withScheme: MDCContainerScheme()) textButton.setTitle("Touch me", for: UIControl.State()) textButton.sizeToFit() let textButtonVerticalInset = min(0, -(kMinimumAccessibleButtonSize.height - textButton.bounds.height) / 2) let textButtonHorizontalInset = min(0, -(kMinimumAccessibleButtonSize.width - textButton.bounds.width) / 2) textButton.hitAreaInsets = UIEdgeInsets( top: textButtonVerticalInset, left: textButtonHorizontalInset, bottom: textButtonVerticalInset, right: textButtonHorizontalInset) textButton.translatesAutoresizingMaskIntoConstraints = false textButton.addTarget(self, action: #selector(tap), for: .touchUpInside) #if compiler(>=5.2) if #available(iOS 13.4, *) { textButton.isPointerInteractionEnabled = true } #endif return textButton }() lazy var floatingButton: MDCFloatingButton = { let floatingButton = MDCFloatingButton() floatingButton.backgroundColor = containerScheme.colorScheme.backgroundColor floatingButton.sizeToFit() floatingButton.translatesAutoresizingMaskIntoConstraints = false floatingButton.addTarget(self, action: #selector(floatingButtonTapped(_:)), for: .touchUpInside) let plusShapeLayer = ButtonsTypicalUseSupplemental.createPlusShapeLayer(floatingButton) floatingButton.layer.addSublayer(plusShapeLayer) floatingButton.accessibilityLabel = "Create" floatingButton.applySecondaryTheme(withScheme: self.containerScheme) #if compiler(>=5.2) if #available(iOS 13.4, *) { floatingButton.isPointerInteractionEnabled = true } #endif return floatingButton }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = containerScheme.colorScheme.backgroundColor let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 20 stackView.alignment = .center stackView.addArrangedSubview(containedButton) stackView.addArrangedSubview(textButton) stackView.addArrangedSubview(floatingButton) view.addSubview(stackView) stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } @objc func tap(_ sender: Any) { print("\(type(of: sender)) was tapped.") } @objc func floatingButtonTapped(_ sender: MDCFloatingButton) { print("\(type(of: sender)) was tapped.") guard !UIAccessibility.isVoiceOverRunning else { return } sender.collapse(true) { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { sender.expand(true, completion: nil) } } } } extension ButtonsPointerInteractionExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Buttons", "Pointer Interactions"], "primaryDemo": false, "presentable": false, ] } }
5b6e8a75d0b695552e39629f1ea4cd7a
37.323529
100
0.742709
false
false
false
false
Shopify/mobile-buy-sdk-ios
refs/heads/main
Buy/Generated/Storefront/CartDeliveryGroupConnection.swift
mit
1
// // CartDeliveryGroupConnection.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// An auto-generated type for paginating through multiple CartDeliveryGroups. open class CartDeliveryGroupConnectionQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CartDeliveryGroupConnection /// A list of edges. @discardableResult open func edges(alias: String? = nil, _ subfields: (CartDeliveryGroupEdgeQuery) -> Void) -> CartDeliveryGroupConnectionQuery { let subquery = CartDeliveryGroupEdgeQuery() subfields(subquery) addField(field: "edges", aliasSuffix: alias, subfields: subquery) return self } /// A list of the nodes contained in CartDeliveryGroupEdge. @discardableResult open func nodes(alias: String? = nil, _ subfields: (CartDeliveryGroupQuery) -> Void) -> CartDeliveryGroupConnectionQuery { let subquery = CartDeliveryGroupQuery() subfields(subquery) addField(field: "nodes", aliasSuffix: alias, subfields: subquery) return self } /// Information to aid in pagination. @discardableResult open func pageInfo(alias: String? = nil, _ subfields: (PageInfoQuery) -> Void) -> CartDeliveryGroupConnectionQuery { let subquery = PageInfoQuery() subfields(subquery) addField(field: "pageInfo", aliasSuffix: alias, subfields: subquery) return self } } /// An auto-generated type for paginating through multiple CartDeliveryGroups. open class CartDeliveryGroupConnection: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CartDeliveryGroupConnectionQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "edges": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CartDeliveryGroupConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try CartDeliveryGroupEdge(fields: $0) } case "nodes": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CartDeliveryGroupConnection.self, field: fieldName, value: fieldValue) } return try value.map { return try CartDeliveryGroup(fields: $0) } case "pageInfo": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartDeliveryGroupConnection.self, field: fieldName, value: fieldValue) } return try PageInfo(fields: value) default: throw SchemaViolationError(type: CartDeliveryGroupConnection.self, field: fieldName, value: fieldValue) } } /// A list of edges. open var edges: [Storefront.CartDeliveryGroupEdge] { return internalGetEdges() } func internalGetEdges(alias: String? = nil) -> [Storefront.CartDeliveryGroupEdge] { return field(field: "edges", aliasSuffix: alias) as! [Storefront.CartDeliveryGroupEdge] } /// A list of the nodes contained in CartDeliveryGroupEdge. open var nodes: [Storefront.CartDeliveryGroup] { return internalGetNodes() } func internalGetNodes(alias: String? = nil) -> [Storefront.CartDeliveryGroup] { return field(field: "nodes", aliasSuffix: alias) as! [Storefront.CartDeliveryGroup] } /// Information to aid in pagination. open var pageInfo: Storefront.PageInfo { return internalGetPageInfo() } func internalGetPageInfo(alias: String? = nil) -> Storefront.PageInfo { return field(field: "pageInfo", aliasSuffix: alias) as! Storefront.PageInfo } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "edges": internalGetEdges().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "nodes": internalGetNodes().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "pageInfo": response.append(internalGetPageInfo()) response.append(contentsOf: internalGetPageInfo().childResponseObjectMap()) default: break } } return response } } }
d6a870119f615b6077bc52dfc7171a57
34.946309
128
0.728529
false
false
false
false
Ataraxiis/MGW-Esport
refs/heads/develop
AlamofireSample/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift
apache-2.0
67
// // DateTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-13. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // 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 class DateTransform: TransformType { public typealias Object = NSDate public typealias JSON = Double public init() {} public func transformFromJSON(value: AnyObject?) -> NSDate? { if let timeInt = value as? Double { return NSDate(timeIntervalSince1970: NSTimeInterval(timeInt)) } if let timeStr = value as? String { return NSDate(timeIntervalSince1970: NSTimeInterval(atof(timeStr))) } return nil } public func transformToJSON(value: NSDate?) -> Double? { if let date = value { return Double(date.timeIntervalSince1970) } return nil } }
e7d3238fcfd28254b5690a5f07ca8436
32.763636
81
0.735595
false
false
false
false
imindeu/iMindLib.swift
refs/heads/master
Source/iMindLib/Extensions/Int+Extensions.swift
mit
1
// // Int+Extensions.swift // iMindLib // // Created by Mate Gregor on 2017. 01. 26.. // Copyright © 2017. iMind. All rights reserved. // import Foundation public extension Int { /// Converts to a shorter format /// - returns: The abbreviated string object public func abbreviate() -> String { let absValue = abs(self) let sign = self < 0 ? "-" : "" guard absValue >= 1000 else { return "\(sign)\(absValue)" } let doubleValue = Double(absValue) let exp = Int(log10(doubleValue) / 3.0 ) let units = ["k", "M", "G", "T", "P", "E"] let roundedValue = round(10 * doubleValue / pow(1000.0, Double(exp))) / 10 return "\(sign)\(Int(roundedValue))\(units[exp-1])" } /// Converts to it's roman number format /// - returns: The roman number string object public func toRoman() -> String { var number = self guard number > 0 else { return "" } let values = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)] return values.reduce("", { (result, value) -> String in let count = number / value.1 if count != 0 { return result + (1...count).reduce("", { (res, _) -> String in number -= value.1 return res + value.0 }) } return result }) } }
eaded17664683cc850ed4e8fb2b28552
28.035088
82
0.45136
false
false
false
false
stevehe-campray/BSBDJ
refs/heads/master
BSBDJ/BSBDJ/Base/BSBTabBar.swift
mit
1
// // BSBTabBar.swift // BSBDJ // // Created by hejingjin on 16/3/15. // Copyright © 2016年 baisibudejie. All rights reserved. // //////////////////////////////////////////////////////////////////// // _ooOoo_ // // o8888888o // // 88" . "88 // // (| ^_^ |) // // O\ = /O // // ____/`---'\____ // // .' \\| |// `. // // / \\||| : |||// \ // // / _||||| -:- |||||- \ // // | | \\\ - /// | | // // | \_| ''\---/'' | | // // \ .-\__ `-` ___/-. / // // ___`. .' /--.--\ `. . ___ // // ."" '< `.___\_<|>_/___.' >'"". // // | | : `- \`.;`\ _ /`;.`/ - ` : | | // // \ \ `-. \_ __\ /__ _/ .-` / / // // ========`-.____`-.___\_____/___.-`____.-'======== // // `=---=' // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // 佛祖保佑 永无BUG 永不修改 // //////////////////////////////////////////////////////////////////// import UIKit class BSBTabBar: UITabBar { //成员属性 var publishbutton:UIButton? override init(frame: CGRect) { super.init(frame: frame) let publishButton:UIButton = UIButton() publishButton.setBackgroundImage(UIImage(named: "tabBar_publish_icon"), forState: UIControlState.Normal) publishButton.setBackgroundImage(UIImage(named: "tabBar_publish_click_icon"), forState: UIControlState.Highlighted) publishbutton = publishButton publishbutton!.addTarget(self, action:#selector(BSBTabBar.publishClick(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(publishButton); } override func layoutSubviews() { super.layoutSubviews() // 原来的4个 let width = self.frame.size.width/5; publishbutton?.bounds = CGRectMake(0, 0, 49, 49); publishbutton?.center = CGPoint(x: self.frame.size.width/2, y:self.frame.size.height/2) var i = 0; for control in self.subviews{ if !control.isKindOfClass(UIControl) || control.isKindOfClass(UIButton){ continue } //重新计算 control.xmg_width = width; control.xmg_x = i > 1 ? width * CGFloat((i + 1)) : width * CGFloat(i); i++ } } func publishClick(btn : UIButton){ let publishvc : BSBPublishViewController = BSBPublishViewController(nibName: "BSBPublishViewController",bundle: nil) self.window?.rootViewController?.presentViewController(publishvc, animated: false, completion: { }); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
1433234944483e49b84618984b240ceb
39.741176
137
0.352007
false
false
false
false
maxadamski/swift-corelibs-foundation
refs/heads/master
TestFoundation/TestNSURLResponse.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSURLResponse : XCTestCase { var allTests : [(String, () -> ())] { return [ ("test_URL", test_URL), ("test_MIMEType", test_MIMEType), ("test_ExpectedContentLength", test_ExpectedContentLength), ("test_TextEncodingName", test_TextEncodingName) ] } func test_URL() { let url = NSURL(string: "a/test/path")! let res = NSURLResponse(URL: url, MIMEType: "txt", expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res.URL, url, "should be the expected url") } func test_MIMEType() { let mimetype1 = "text/plain" let mimetype2 = "application/wordperfect" let res1 = NSURLResponse(URL: NSURL(string: "test")!, MIMEType: mimetype1, expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res1.MIMEType, mimetype1, "should be the passed in mimetype") let res2 = NSURLResponse(URL: NSURL(string: "test")!, MIMEType: mimetype2, expectedContentLength: 0, textEncodingName: nil) XCTAssertEqual(res2.MIMEType, mimetype2, "should be the other mimetype") } func test_ExpectedContentLength() { let zeroContentLength = 0 let positiveContentLength = 100 let url = NSURL(string: "test")! let res1 = NSURLResponse(URL: url, MIMEType: "text/plain", expectedContentLength: zeroContentLength, textEncodingName: nil) XCTAssertEqual(res1.expectedContentLength, Int64(zeroContentLength), "should be Int65 of the zero length") let res2 = NSURLResponse(URL: url, MIMEType: "text/plain", expectedContentLength: positiveContentLength, textEncodingName: nil) XCTAssertEqual(res2.expectedContentLength, Int64(positiveContentLength), "should be Int64 of the positive content length") } func test_TextEncodingName() { let encoding = "utf8" let url = NSURL(string: "test")! let res1 = NSURLResponse(URL: url, MIMEType: nil, expectedContentLength: 0, textEncodingName: encoding) XCTAssertEqual(res1.textEncodingName, encoding, "should be the utf8 encoding") let res2 = NSURLResponse(URL: url, MIMEType: nil, expectedContentLength: 0, textEncodingName: nil) XCTAssertNil(res2.textEncodingName) } }
abe7ad251d316d8f722976db37f08a0c
43.269841
135
0.684362
false
true
false
false
kyouko-taiga/anzen
refs/heads/master
Sources/AnzenIR/AIREmissionDriver.swift
apache-2.0
1
import AST /// A driver for a module's AIR code emitting. public class AIREmissionDriver { private var requestedImpl: [(FunDecl, FunctionType)] = [] private var processedImpl: Set<String> = [] public init() {} public func emitMainUnit(_ module: ModuleDecl, context: ASTContext) -> AIRUnit { let unit = AIRUnit(name: module.id?.qualifiedName ?? "__air_unit") let builder = AIRBuilder(unit: unit, context: context) // Emit the main function's prologue. let mainFnType = unit.getFunctionType(from: [], to: .nothing) let mainFn = builder.unit.getFunction(name: "main", type: mainFnType) mainFn.appendBlock(label: "entry") builder.currentBlock = mainFn.appendBlock(label: "exit") builder.buildReturn() // Emit the main function's body. emitFunctionBody( builder: builder, function: mainFn, locals: [:], returnRegister: nil, body: module.statements, typeEmitter: TypeEmitter(builder: builder, typeBindings: [:])) // Emit the implementation requests. emitImplementationRequests(builder: builder) return unit } private func emitFunctionPrologue( builder: AIRBuilder, name: String, declaration: FunDecl, type: FunctionType, typeEmitter: TypeEmitter) -> FunctionPrologue { var fnType = typeEmitter.emitType(of: type) if declaration.kind == .method || declaration.kind == .destructor { // Methods and destructors are lowered into static functions that take the self symbol and // return the "actual" method as a closure. let symbols = declaration.innerScope!.symbols["self"]! assert(symbols.count == 1) let methTy = fnType.codomain as! AIRFunctionType fnType = builder.unit.getFunctionType( from: fnType.domain + methTy.domain, to: methTy.codomain) } else if !declaration.captures.isEmpty { // If the function captures symbols, we need to emit a context-free version of the it, which // gets the captured values as parameters. This boils down to extending the domain. let additional = declaration.captures.map { typeEmitter.emitType(of: $0.type!) } fnType = builder.unit.getFunctionType(from: additional + fnType.domain, to: fnType.codomain) } // Retrieve the function object. let function = builder.unit.getFunction(name: name, type: fnType) function.debugInfo = declaration.debugInfo function.debugInfo![.anzenType] = type assert(function.blocks.isEmpty) builder.currentBlock = function.appendBlock(label: "entry") // Create the function's locals. var locals: [Symbol: AIRValue] = [:] // Handle self for constructors, desctructors and methods. if declaration.kind != .regular { let selfSymbol = declaration.innerScope!.symbols["self"]![0] let debugInfo: DebugInfo = [ .range: declaration.range, .anzenType: selfSymbol.type!, .name: "self"] locals[selfSymbol] = declaration.kind == .constructor ? builder.buildAlloc(type: fnType.codomain, withID: 0, debugInfo: debugInfo) : AIRParameter( type: fnType.domain[0], id: builder.currentBlock!.nextRegisterID(), debugInfo: debugInfo) } // Create the function parameters captured by closure. for sym in declaration.captures { let paramref = AIRParameter( type: typeEmitter.emitType(of: sym.type!), id: builder.currentBlock!.nextRegisterID(), debugInfo: [.anzenType: sym.type!, .name: sym.name]) locals[sym] = paramref } // Create the function parameters. for (paramDecl, paramSign) in zip(declaration.parameters, type.domain) { let paramref = AIRParameter( type: typeEmitter.emitType(of: paramSign.type), id: builder.currentBlock!.nextRegisterID(), debugInfo: paramDecl.debugInfo) locals[paramDecl.symbol!] = paramref } // Create the return register. let returnRegister: AIRRegister? if declaration.kind == .constructor { let selfSymbol = declaration.innerScope!.symbols["self"]![0] returnRegister = locals[selfSymbol] as? AIRRegister } else if type.codomain != NothingType.get { returnRegister = builder.buildMakeRef(type: fnType.codomain, withID: 0) } else { returnRegister = nil } // Emit the function return. builder.currentBlock = function.appendBlock(label: "exit") if returnRegister != nil { builder.buildReturn(value: returnRegister!) } else { builder.buildReturn() } return FunctionPrologue(function: function, locals: locals, returnRegister: returnRegister) } // swiftlint:disable function_parameter_count private func emitFunctionBody( builder: AIRBuilder, function: AIRFunction, locals: [Symbol: AIRValue], returnRegister: AIRRegister?, body: [Node], typeEmitter: TypeEmitter) { // Set the builder's cursor. builder.currentBlock = function.blocks.first?.value // Emit the function's body. let emitter = AIREmitter( builder: builder, locals: locals, returnRegister: returnRegister, typeEmitter: typeEmitter) try! emitter.visit(body) // Make sure the last instruction is a jump to the exit block. if !(builder.currentBlock!.instructions.last is JumpInst) { builder.buildJump(label: function.blocks.last!.value.label) } // Save the implementation requests. requestedImpl.append(contentsOf: emitter.requestedImpl) } // swiftlint:enable function_parameter_count private func emitImplementationRequests(builder: AIRBuilder) { while let (decl, type) = requestedImpl.popLast() { let functionName = decl.getAIRName(specializedWithType: type) guard !processedImpl.contains(functionName) else { continue } processedImpl.insert(functionName) guard let functionBody = decl.body else { continue } var typeBindings: [PlaceholderType: TypeBase] = [:] guard specializes(lhs: type, rhs: decl.type!, in: builder.context, bindings: &typeBindings) else { fatalError("type mismatch") } let typeEmitter = TypeEmitter(builder: builder, typeBindings: typeBindings) let prologue = emitFunctionPrologue( builder: builder, name: functionName, declaration: decl, type: type, typeEmitter: typeEmitter) emitFunctionBody( builder: builder, function: prologue.function, locals: prologue.locals, returnRegister: prologue.returnRegister, body: functionBody.statements, typeEmitter: typeEmitter) } } } private struct FunctionPrologue { let function: AIRFunction let locals: [Symbol: AIRValue] let returnRegister: AIRRegister? }
498902f03e87a217e7a094262492716a
32.935
98
0.67865
false
false
false
false
Conaaando/vector-texture-atlas
refs/heads/master
VectorTextureAtlas/GameViewController.swift
mit
1
// // GameViewController.swift // VectorTextureAtlas // // Created by Fernando Fernandes on 3/5/15. // Copyright (c) 2015 Bigorna. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { // MARK: - Properties lazy var skView: SKView = { [unowned self] in return self.view as! SKView }() lazy var mainScene: MainScene = { return MainScene.unarchiveFromFile("MainScene") as! MainScene }() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupView() setupMainScene() presentMainScene() } // MARK: - Private Methods private func setupView() { skView.showsFPS = true skView.showsNodeCount = true // Sprite Kit applies additional optimizations to improve rendering performance skView.ignoresSiblingOrder = true } private func setupMainScene() { // Set the scale mode to scale to fit the window mainScene.scaleMode = .AspectFill } private func presentMainScene() { skView.presentScene(mainScene) } // MARK: - ViewController Configuration override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func prefersStatusBarHidden() -> Bool { return true } }
c29d9f1bbe554db16675af5f3ae3b5d6
22.736111
87
0.61615
false
false
false
false
LongPF/FaceTube
refs/heads/master
FaceTube/Record/FTCaptureViewController.swift
mit
1
// // FTCaptureViewController.swift // FaceTube // // Created by 龙鹏飞 on 2017/4/18. // Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved. // import UIKit class FTCaptureViewController: FTViewController { /// 预览view var previewView: FTPreviewView! /// camer var camera: FTCamera! /// overlayView上面放着事件按钮 var overlayView: FTCameraOverlayView! //MARK: ************************ life cycle ************************ override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let eaglContext = FTContextManager.shared.eaglContext self.previewView = FTPreviewView.init(frame: self.view.bounds, context: eaglContext!) self.previewView.coreImageContext = FTContextManager.shared.ciContext self.view.addSubview(self.previewView) self.camera = FTCamera() self.camera.imageTarget = self.previewView self.overlayView = FTCameraOverlayView.init(camera: self.camera) self.overlayView.frame = self.view.bounds self.overlayView.delegate = self self.view.addSubview(self.overlayView) var error: NSError? = nil if self.camera.setupSession(&error){ self.camera.startSession() }else{ print(error?.localizedDescription ?? "setupSession error") } } override func viewWillAppear(_ animated: Bool) { UIApplication.shared.setStatusBarHidden(true, with: .none) navigationController?.setNavigationBarHidden(true, animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let tabbarController = tabBarController as? FTTabbarContrller{ DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5, execute: { tabbarController.showTabBar(show: false, aniamtie: true) }) } } override var prefersStatusBarHidden: Bool{ return true; } } extension FTCaptureViewController: FTCameraOverlayViewProtocol { func close2back() { if let tabbarController = tabBarController as? FTTabbarContrller{ tabbarController.showTabBar(show: true, aniamtie: false) } tabBarController?.selectedIndex = 0 } }
ad65ad994ae1fb81b84def93c99cd845
29.807692
93
0.633375
false
false
false
false
adamgraham/STween
refs/heads/master
STween/STweenTests/Tweening/TweenAnimatorTest.swift
mit
1
// // TweenAnimatorTest.swift // STween // // Created by Adam Graham on 6/16/16. // Copyright © 2016 Adam Graham. All rights reserved. // import XCTest @testable import STween class TweenAnimatorTest: XCTestCase { override func setUp() { super.setUp() Tweener.default.killAll() } override func tearDown() { Tweener.default.killAll() super.tearDown() } // MARK: Initialization func testInitialization() { let target = UIView() let anotherTarget = UIView() let tween = TweenAnimator(targets: target, anotherTarget) XCTAssertNil(tween.tweener) XCTAssertEqual(tween.targets, [target, anotherTarget]) XCTAssertTrue(tween.tweens.isEmpty) XCTAssertEqual(tween.state, .new) XCTAssertEqual(tween.ease, Defaults.ease) XCTAssertEqual(tween.delay, Defaults.delay) XCTAssertEqual(tween.duration, Defaults.duration) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertNil(tween.onUpdate) XCTAssertNil(tween.onStart) XCTAssertNil(tween.onStop) XCTAssertNil(tween.onRestart) XCTAssertNil(tween.onPause) XCTAssertNil(tween.onResume) XCTAssertNil(tween.onComplete) XCTAssertNil(tween.onKill) XCTAssertNil(tween.onRevive) } // MARK: Tweening func testTweenTo() { let target = UIView() let tween = TweenAnimator(targets: target).to(.x(100.0), .y(100.0)) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) } func testTweenToCustomProperty() { struct CustomProperty: TweenableProperty { var animation: ((UILabel) -> (TimeInterval) -> Void) { return { _ in return { _ in } } } } let target = UILabel() target.textColor = .black let tween = TweenAnimator(targets: target) .to(.x(100.0), .y(100.0)) .to(.textColor(.white)) .to(CustomProperty()) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertColor(target.textColor, .black) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertColor(target.textColor, .gray) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertColor(target.textColor, .white) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) } func testTweenToDelayed() { let target = UIView() let tween = TweenAnimator(targets: target).to(.x(100.0), .y(100.0)) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.delay = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) } func testTweenFrom() { let target = UIView() let tween = TweenAnimator(targets: target).from(.x(100.0), .y(100.0)) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) } func testTweenFromCustomProperty() { struct CustomProperty: TweenableProperty { var animation: ((UILabel) -> (TimeInterval) -> Void) { return { _ in return { _ in } } } } let target = UILabel() target.textColor = .black let tween = TweenAnimator(targets: target) .from(.x(100.0), .y(100.0)) .from(.textColor(.white)) .from(CustomProperty()) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertColor(target.textColor, .white) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertColor(target.textColor, .gray) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertColor(target.textColor, .black) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) } func testTweenFromDelayed() { let target = UIView() let tween = TweenAnimator(targets: target).from(.x(100.0), .y(100.0)) tween.onUpdate = { _ in XCTAssertNotEqual(tween.elapsed, 0.0) } tween.onComplete = { _ in XCTAssertEqual(tween.elapsed, tween.duration) } tween.ease = .linear tween.duration = 1.0 tween.delay = 1.0 tween.start() XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertEqual(target.frame.origin.y, 100.0) tween.update(by: 0.5) XCTAssertEqual(tween.elapsed, 0.5) XCTAssertEqual(target.frame.origin.x, 50.0) XCTAssertEqual(target.frame.origin.y, 50.0) tween.update(by: 1.0) XCTAssertEqual(tween.elapsed, 1.0) XCTAssertEqual(target.frame.origin.x, 0.0) XCTAssertEqual(target.frame.origin.y, 0.0) } // MARK: State Control func testUpdate() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onUpdate = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.update(by: .ulpOfOne)) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.update(by: .ulpOfOne)) XCTAssertEqual(tween.state, .active) XCTAssertTrue(callbackInvoked) } func testUpdateWithDelay() { let tween = TweenAnimator(targets: UIView()) tween.delay = 1.0 var callbackInvoked = false tween.onUpdate = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.update(by: .ulpOfOne)) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .delayed) XCTAssertTrue(tween.update(by: .ulpOfOne)) XCTAssertEqual(tween.state, .delayed) XCTAssertFalse(callbackInvoked) XCTAssertTrue(tween.update(by: tween.delay)) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.update(by: .ulpOfOne)) XCTAssertTrue(callbackInvoked) } func testStart() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onStart = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertFalse(tween.start()) XCTAssertTrue(callbackInvoked) } func testStartWithDelay() { let tween = TweenAnimator(targets: UIView()) tween.delay = 1.0 var callbackInvoked = false tween.onStart = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .delayed) XCTAssertFalse(tween.start()) XCTAssertFalse(callbackInvoked) XCTAssertTrue(tween.update(by: tween.delay)) XCTAssertEqual(tween.state, .active) XCTAssertTrue(callbackInvoked) } func testStop() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onStop = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.stop()) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.stop()) XCTAssertEqual(tween.state, .inactive) XCTAssertTrue(callbackInvoked) } func testRestart() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onRestart = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.stop()) XCTAssertEqual(tween.state, .inactive) XCTAssertTrue(tween.restart()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.restart()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.kill()) XCTAssertEqual(tween.state, .killed) XCTAssertFalse(tween.restart()) XCTAssertEqual(tween.state, .killed) XCTAssertTrue(callbackInvoked) } func testPause() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onPause = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.pause()) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.pause()) XCTAssertEqual(tween.state, .paused) XCTAssertTrue(callbackInvoked) } func testResume() { let tween = TweenAnimator(targets: UIView()) var callbackInvoked = false tween.onResume = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.resume()) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.pause()) XCTAssertEqual(tween.state, .paused) XCTAssertTrue(tween.resume()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(callbackInvoked) } func testResumeWithDelay() { let tween = TweenAnimator(targets: UIView()) tween.delay = 1.0 var callbackInvoked = false tween.onResume = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertFalse(tween.resume()) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .delayed) XCTAssertTrue(tween.pause()) XCTAssertEqual(tween.state, .paused) XCTAssertTrue(tween.resume()) XCTAssertEqual(tween.state, .delayed) XCTAssertTrue(callbackInvoked) } func testCompleteWithAutoKillOn() { Defaults.autoKillCompletedTweens = true defer { Defaults.reset() } let target = UIView() let tween = TweenAnimator(targets: target).to(.x(100.0)) var callbackInvoked = false tween.onComplete = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.complete()) XCTAssertEqual(tween.state, .killed) XCTAssertFalse(tween.complete()) XCTAssertEqual(tween.state, .killed) XCTAssertEqual(tween.elapsed, tween.duration) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertTrue(callbackInvoked) } func testCompleteWithAutoKillOff() { Defaults.autoKillCompletedTweens = false defer { Defaults.reset() } let target = UIView() let tween = TweenAnimator(targets: target).to(.x(100.0)) var callbackInvoked = false tween.onComplete = { _ in callbackInvoked = true } XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.complete()) XCTAssertEqual(tween.state, .completed) XCTAssertFalse(tween.complete()) XCTAssertEqual(tween.state, .completed) XCTAssertEqual(tween.elapsed, tween.duration) XCTAssertEqual(target.frame.origin.x, 100.0) XCTAssertTrue(callbackInvoked) } func testKill() { let tween = TweenAnimator(targets: UIView()) Tweener.default.track(tween) var callbackInvoked = false tween.onKill = { _ in callbackInvoked = true } XCTAssertTrue(Tweener.default.isTracking(tween)) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.kill()) XCTAssertEqual(tween.state, .killed) XCTAssertFalse(tween.kill()) XCTAssertTrue(callbackInvoked) XCTAssertFalse(Tweener.default.isTracking(tween)) } func testRevive() { let tween = TweenAnimator(targets: UIView()) Tweener.default.track(tween) var callbackInvoked = false tween.onRevive = { _ in callbackInvoked = true } XCTAssertTrue(Tweener.default.isTracking(tween)) XCTAssertEqual(tween.state, .new) XCTAssertTrue(tween.start()) XCTAssertEqual(tween.state, .active) XCTAssertFalse(tween.revive()) XCTAssertEqual(tween.state, .active) XCTAssertTrue(tween.kill()) XCTAssertEqual(tween.state, .killed) XCTAssertFalse(Tweener.default.isTracking(tween)) XCTAssertTrue(tween.revive()) XCTAssertEqual(tween.state, .new) XCTAssertEqual(tween.elapsed, 0.0) XCTAssertTrue(callbackInvoked) XCTAssertTrue(Tweener.default.isTracking(tween)) } }
73b836741c2b14cc32b5e117cc445803
30.992278
81
0.618211
false
false
false
false
adamdahan/GraphKit
refs/heads/v3.x.x
Source/EntityGroup.swift
agpl-3.0
1
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // // #internal import CoreData @objc(EntityGroup) internal class EntityGroup : NSManagedObject { @NSManaged internal var name: String @NSManaged internal var node: ManagedEntity private var context: NSManagedObjectContext? internal var worker: NSManagedObjectContext? { get { if nil == context { let graph: Graph = Graph() context = graph.worker } return context } } /** :name: init :description: Initializer for the Model Object. */ convenience init(name: String) { let g: Graph = Graph() var w: NSManagedObjectContext? = g.worker self.init(entity: NSEntityDescription.entityForName(GraphUtility.entityGroupDescriptionName, inManagedObjectContext: w!)!, insertIntoManagedObjectContext: w) self.name = name context = w } /** :name: delete :description: Deletes the Object Model. */ internal func delete() { worker?.deleteObject(self) } }
93b0f544cd9bcc49e739effb870ac6ad
28.913793
159
0.732565
false
false
false
false
Zewo/Epoch
refs/heads/master
Sources/Media/Media/Coding.swift
mit
1
enum MapSuperKey : String, CodingKey { case `super` } extension String : CodingKey { public var stringValue: String { return self } public init?(stringValue: String) { self = stringValue } public var intValue: Int? { return Int(self) } public init?(intValue: Int) { self = String(intValue) } } extension Int : CodingKey { public var stringValue: String { return description } public init?(stringValue: String) { guard let int = Int(stringValue) else { return nil } self = int } public var intValue: Int? { return self } public init?(intValue: Int) { self = intValue } } extension EncodingError.Context { public init(codingPath: [CodingKey] = []) { self.codingPath = codingPath self.debugDescription = "" self.underlyingError = nil; } public init(debugDescription: String) { self.codingPath = [] self.debugDescription = debugDescription self.underlyingError = nil } } extension DecodingError.Context { public init(codingPath: [CodingKey] = []) { self.codingPath = codingPath self.debugDescription = "" self.underlyingError = nil } public init(debugDescription: String) { self.codingPath = [] self.debugDescription = debugDescription self.underlyingError = nil } }
b8956039d3b914f371145342c75e88a5
20.183099
48
0.577128
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/ChatModule/Chat/View/JCNetworkTipsCell.swift
mit
1
// // JCNetworkTipsCell.swift // JChat // // Created by JIGUANG on 2017/6/12. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit class JCNetworkTipsCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } override func awakeFromNib() { super.awakeFromNib() _init() } private lazy var statueView: UIImageView = { let statueView = UIImageView() statueView.image = UIImage.loadImage("com_icon_send_error") return statueView }() private lazy var tipsLabel: UILabel = { let tipsLabel = UILabel() tipsLabel.text = "当前网络不可用,请检查您的网络设置" tipsLabel.font = UIFont.systemFont(ofSize: 14) return tipsLabel }() //MARK: - private func private func _init() { backgroundColor = UIColor(netHex: 0xFFDFE0) contentView.addSubview(statueView) contentView.addSubview(tipsLabel) addConstraint(_JCLayoutConstraintMake(tipsLabel, .left, .equal, statueView, .right, 11.5)) addConstraint(_JCLayoutConstraintMake(tipsLabel, .centerY, .equal, contentView, .centerY)) addConstraint(_JCLayoutConstraintMake(tipsLabel, .right, .equal, contentView, .right)) addConstraint(_JCLayoutConstraintMake(tipsLabel, .height, .equal, contentView, .height)) addConstraint(_JCLayoutConstraintMake(statueView, .centerY, .equal, contentView, .centerY)) addConstraint(_JCLayoutConstraintMake(statueView, .left, .equal, contentView, .left, 15)) addConstraint(_JCLayoutConstraintMake(statueView, .height, .equal, nil, .notAnAttribute, 21)) addConstraint(_JCLayoutConstraintMake(statueView, .width, .equal, nil, .notAnAttribute, 21)) } }
b4744e3741c2f9d0360919429ddf8913
34.142857
101
0.667683
false
false
false
false
JLCdeSwift/DangTangDemo
refs/heads/master
Carthage/Checkouts/ReactiveSwift/Sources/Action.swift
agpl-3.0
15
import Dispatch import Foundation import Result /// Represents an action that will do some work when executed with a value of /// type `Input`, then return zero or more values of type `Output` and/or fail /// with an error of type `Error`. If no failure should be possible, NoError can /// be specified for the `Error` parameter. /// /// Actions enforce serial execution. Any attempt to execute an action multiple /// times concurrently will return an error. public final class Action<Input, Output, Error: Swift.Error> { private let deinitToken: Lifetime.Token private let executeClosure: (_ state: Any, _ input: Input) -> SignalProducer<Output, Error> private let eventsObserver: Signal<Event<Output, Error>, NoError>.Observer private let disabledErrorsObserver: Signal<(), NoError>.Observer /// The lifetime of the Action. public let lifetime: Lifetime /// A signal of all events generated from applications of the Action. /// /// In other words, this will send every `Event` from every signal generated /// by each SignalProducer returned from apply() except `ActionError.disabled`. public let events: Signal<Event<Output, Error>, NoError> /// A signal of all values generated from applications of the Action. /// /// In other words, this will send every value from every signal generated /// by each SignalProducer returned from apply() except `ActionError.disabled`. public let values: Signal<Output, NoError> /// A signal of all errors generated from applications of the Action. /// /// In other words, this will send errors from every signal generated by /// each SignalProducer returned from apply() except `ActionError.disabled`. public let errors: Signal<Error, NoError> /// A signal which is triggered by `ActionError.disabled`. public let disabledErrors: Signal<(), NoError> /// A signal of all completed events generated from applications of the action. /// /// In other words, this will send completed events from every signal generated /// by each SignalProducer returned from apply(). public let completed: Signal<(), NoError> /// Whether the action is currently executing. public let isExecuting: Property<Bool> /// Whether the action is currently enabled. public let isEnabled: Property<Bool> private let state: MutableProperty<ActionState> /// Initializes an action that will be conditionally enabled based on the /// value of `state`. Creates a `SignalProducer` for each input and the /// current value of `state`. /// /// - note: `Action` guarantees that changes to `state` are observed in a /// thread-safe way. Thus, the value passed to `isEnabled` will /// always be identical to the value passed to `execute`, for each /// application of the action. /// /// - note: This initializer should only be used if you need to provide /// custom input can also influence whether the action is enabled. /// The various convenience initializers should cover most use cases. /// /// - parameters: /// - state: A property that provides the current state of the action /// whenever `apply()` is called. /// - enabledIf: A predicate that, given the current value of `state`, /// returns whether the action should be enabled. /// - execute: A closure that returns the `SignalProducer` returned by /// calling `apply(Input)` on the action, optionally using /// the current value of `state`. public init<State: PropertyProtocol>(state property: State, enabledIf isEnabled: @escaping (State.Value) -> Bool, _ execute: @escaping (State.Value, Input) -> SignalProducer<Output, Error>) { deinitToken = Lifetime.Token() lifetime = Lifetime(deinitToken) // Retain the `property` for the created `Action`. lifetime.observeEnded { _ = property } executeClosure = { state, input in execute(state as! State.Value, input) } (events, eventsObserver) = Signal<Event<Output, Error>, NoError>.pipe() (disabledErrors, disabledErrorsObserver) = Signal<(), NoError>.pipe() values = events.filterMap { $0.value } errors = events.filterMap { $0.error } completed = events.filter { $0.isCompleted }.map { _ in } let initial = ActionState(value: property.value, isEnabled: { isEnabled($0 as! State.Value) }) state = MutableProperty(initial) property.signal .take(during: state.lifetime) .observeValues { [weak state] newValue in state?.modify { $0.value = newValue } } self.isEnabled = state.map { $0.isEnabled }.skipRepeats() self.isExecuting = state.map { $0.isExecuting }.skipRepeats() } /// Initializes an action that will be conditionally enabled, and creates a /// `SignalProducer` for each input. /// /// - parameters: /// - enabledIf: Boolean property that shows whether the action is /// enabled. /// - execute: A closure that returns the signal producer returned by /// calling `apply(Input)` on the action. public convenience init<P: PropertyProtocol>(enabledIf property: P, _ execute: @escaping (Input) -> SignalProducer<Output, Error>) where P.Value == Bool { self.init(state: property, enabledIf: { $0 }) { _, input in execute(input) } } /// Initializes an action that will be enabled by default, and creates a /// SignalProducer for each input. /// /// - parameters: /// - execute: A closure that returns the signal producer returned by /// calling `apply(Input)` on the action. public convenience init(_ execute: @escaping (Input) -> SignalProducer<Output, Error>) { self.init(enabledIf: Property(value: true), execute) } deinit { eventsObserver.sendCompleted() disabledErrorsObserver.sendCompleted() } /// Creates a SignalProducer that, when started, will execute the action /// with the given input, then forward the results upon the produced Signal. /// /// - note: If the action is disabled when the returned SignalProducer is /// started, the produced signal will send `ActionError.disabled`, /// and nothing will be sent upon `values` or `errors` for that /// particular signal. /// /// - parameters: /// - input: A value that will be passed to the closure creating the signal /// producer. public func apply(_ input: Input) -> SignalProducer<Output, ActionError<Error>> { return SignalProducer { observer, disposable in let startingState = self.state.modify { state -> Any? in if state.isEnabled { state.isExecuting = true return state.value } else { return nil } } guard let state = startingState else { observer.send(error: .disabled) self.disabledErrorsObserver.send(value: ()) return } self.executeClosure(state, input).startWithSignal { signal, signalDisposable in disposable += signalDisposable signal.observe { event in observer.action(event.mapError(ActionError.producerFailed)) self.eventsObserver.send(value: event) } } disposable += { self.state.modify { $0.isExecuting = false } } } } } private struct ActionState { var isExecuting: Bool = false var value: Any { didSet { userEnabled = userEnabledClosure(value) } } private var userEnabled: Bool private let userEnabledClosure: (Any) -> Bool init(value: Any, isEnabled: @escaping (Any) -> Bool) { self.value = value self.userEnabled = isEnabled(value) self.userEnabledClosure = isEnabled } /// Whether the action should be enabled for the given combination of user /// enabledness and executing status. fileprivate var isEnabled: Bool { return userEnabled && !isExecuting } } /// A protocol used to constraint `Action` initializers. @available(swift, deprecated: 3.1, message: "This protocol is no longer necessary and will be removed in a future version of ReactiveSwift. Use Action directly instead.") public protocol ActionProtocol: BindingTargetProvider, BindingTargetProtocol { /// The type of argument to apply the action to. associatedtype Input /// The type of values returned by the action. associatedtype Output /// The type of error when the action fails. If errors aren't possible then /// `NoError` can be used. associatedtype Error: Swift.Error /// Initializes an action that will be conditionally enabled based on the /// value of `state`. Creates a `SignalProducer` for each input and the /// current value of `state`. /// /// - note: `Action` guarantees that changes to `state` are observed in a /// thread-safe way. Thus, the value passed to `isEnabled` will /// always be identical to the value passed to `execute`, for each /// application of the action. /// /// - note: This initializer should only be used if you need to provide /// custom input can also influence whether the action is enabled. /// The various convenience initializers should cover most use cases. /// /// - parameters: /// - state: A property that provides the current state of the action /// whenever `apply()` is called. /// - enabledIf: A predicate that, given the current value of `state`, /// returns whether the action should be enabled. /// - execute: A closure that returns the `SignalProducer` returned by /// calling `apply(Input)` on the action, optionally using /// the current value of `state`. init<State: PropertyProtocol>(state property: State, enabledIf isEnabled: @escaping (State.Value) -> Bool, _ execute: @escaping (State.Value, Input) -> SignalProducer<Output, Error>) /// Whether the action is currently enabled. var isEnabled: Property<Bool> { get } /// Extracts an action from the receiver. var action: Action<Input, Output, Error> { get } /// Creates a SignalProducer that, when started, will execute the action /// with the given input, then forward the results upon the produced Signal. /// /// - note: If the action is disabled when the returned SignalProducer is /// started, the produced signal will send `ActionError.disabled`, /// and nothing will be sent upon `values` or `errors` for that /// particular signal. /// /// - parameters: /// - input: A value that will be passed to the closure creating the signal /// producer. func apply(_ input: Input) -> SignalProducer<Output, ActionError<Error>> } extension Action: ActionProtocol { public var action: Action { return self } public var bindingTarget: BindingTarget<Input> { return BindingTarget(lifetime: lifetime) { [weak self] in self?.apply($0).start() } } } extension ActionProtocol where Input == Void { /// Initializes an action that uses an `Optional` property for its input, /// and is disabled whenever the input is `nil`. When executed, a `SignalProducer` /// is created with the current value of the input. /// /// - parameters: /// - input: An `Optional` property whose current value is used as input /// whenever the action is executed. The action is disabled /// whenever the value is `nil`. /// - execute: A closure to return a new `SignalProducer` based on the /// current value of `input`. public init<P: PropertyProtocol, T>(input: P, _ execute: @escaping (T) -> SignalProducer<Output, Error>) where P.Value == T? { self.init(state: input, enabledIf: { $0 != nil }) { input, _ in execute(input!) } } /// Initializes an action that uses a property for its input. When executed, /// a `SignalProducer` is created with the current value of the input. /// /// - parameters: /// - input: A property whose current value is used as input /// whenever the action is executed. /// - execute: A closure to return a new `SignalProducer` based on the /// current value of `input`. public init<P: PropertyProtocol, T>(input: P, _ execute: @escaping (T) -> SignalProducer<Output, Error>) where P.Value == T { self.init(input: input.map(Optional.some), execute) } } /// The type of error that can occur from Action.apply, where `Error` is the /// type of error that can be generated by the specific Action instance. public enum ActionError<Error: Swift.Error>: Swift.Error { /// The producer returned from apply() was started while the Action was /// disabled. case disabled /// The producer returned from apply() sent the given error. case producerFailed(Error) } public func == <Error: Equatable>(lhs: ActionError<Error>, rhs: ActionError<Error>) -> Bool { switch (lhs, rhs) { case (.disabled, .disabled): return true case let (.producerFailed(left), .producerFailed(right)): return left == right default: return false } }
47adfdce61accf26bf52c502efa7f951
38.046154
192
0.691962
false
false
false
false
meninsilicium/apple-swifty
refs/heads/development
JSONValidation.swift
mpl-2.0
1
// // author: fabrice truillot de chambrier // created: 29.01.2015 // // license: see license.txt // // © 2015-2015, men in silicium sàrl // // MARK: JSONValidation public struct JSONValidation { public private(set) var validators: Set<JSONValidator> // Freezable public private(set) var isFrozen: Bool = false } // MARK: types public typealias JSONValidationFunction = ( validation: JSONValidation, value: JSONValue ) -> Bool // MARK: initialization extension JSONValidation { public init() { self.validators = Set() } } // MARK: subscripts extension JSONValidation { /// subscript with a JSONPath private subscript( path: JSONPath ) -> JSONValidator? { // [ path: JSONPath ] -> JSONValidator? get { var validator: JSONValidator? = nil self.validators.enumerate { ( index, ivalidator ) -> Bool in if ivalidator.path == path { validator = ivalidator return false } return true } return validator } // [ path: JSONPath ] = JSONValidator set( validator ) { if self.isFrozen { return } let lvalidator = JSONValidator( path: path ) if let validator = validator { self.validators.remove( lvalidator ) self.validators.insert( validator ) } else { self.validators.remove( lvalidator ) } } } } extension JSONValidation { public mutating func assess( path: JSONPath, optional: Bool = true, function: JSONValidationFunction ) { self.insert( path, optional: optional, function: function ) } public mutating func insert( path: JSONPath, optional: Bool = true, function: JSONValidationFunction ) { if self.isFrozen { return } var validator = JSONValidator( path: path ) validator.optional = optional validator.function = function self.validators.insert( validator ) } public mutating func remove( path: JSONPath ) -> JSONValidator? { if self.isFrozen { return nil } var validator = JSONValidator( path: path ) return self.validators.remove( validator ) } } // MARK: Freezable extension JSONValidation : Freezable { public mutating func freeze() -> Bool { if self.isFrozen { return true } self.isFrozen = true return false } } // MARK: validation extension JSONValidation { public func validate( json: JSONValue ) -> Bool { var valid: Bool = true self.validators.foreach { ( validator: JSONValidator ) in let ivalid = validator.validate( self, json: json ) valid = valid && ivalid } return valid } } extension JSONValue { public func validate( validation: JSONValidation ) -> Bool { return validation.validate( self ) } } // MARK: - // MARK: JSONValidator public struct JSONValidator : Hashable { public private(set) var path: JSONPath public private(set) var optional: Bool = true private var function: JSONValidationFunction? } // MARK: initialization extension JSONValidator { init() { self.path = JSONPath() self.function = nil } public init( path: JSONPath ) { self.path = path self.function = nil } public init( path: JSONPath, optional: Bool ) { self.path = path self.optional = optional self.function = nil } } // MARK: Equatable extension JSONValidator : Equatable {} public func ==( lhs: JSONValidator, rhs: JSONValidator ) -> Bool { return lhs.path == rhs.path } // MARK: Hashable extension JSONValidator : Hashable { public var hashValue: Int { return self.path.hashValue } } // MARK: validation extension JSONValidator { func validate( validation: JSONValidation, json: JSONValue ) -> Bool { if let subjson = json[ self.path ] { if let function = self.function { let valid = function( validation: validation, value: subjson ) return valid } return true } return self.optional } }
83d20704827c53ca062e683e241151ea
16.61215
105
0.681613
false
false
false
false
bingoogolapple/SwiftNote-PartOne
refs/heads/master
CustomView/MyCustomViews/MyView.swift
apache-2.0
1
// // MyView.swift // CustomView // // Created by bingoogol on 14/7/27. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit @IBDesignable class MyView: UIView { required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override init(frame: CGRect) { super.init(frame: frame) // Initialization code } @IBInspectable var str:String = "Hello" @IBInspectable var borderWidth:CGFloat = 0 { didSet{ layer.borderWidth = borderWidth } } @IBInspectable var borderCorlor:UIColor = UIColor.clearColor() { didSet{ layer.borderColor = borderCorlor.CGColor } } @IBInspectable var cornerRadius:CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
74bafbebc3455f999891b3aa85f21702
19.686275
78
0.618009
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKitUI/Views/Information Screens/CorrectionRangeOverrideInformationView.swift
mit
1
// // CorrectionRangeOverrideInformationView.swift // LoopKitUI // // Created by Anna Quinlan on 7/2/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import LoopKit import SwiftUI public struct CorrectionRangeOverrideInformationView: View { let preset: CorrectionRangeOverrides.Preset var onExit: (() -> Void)? let mode: SettingsPresentationMode @Environment(\.presentationMode) var presentationMode @Environment(\.carbTintColor) var carbTintColor @Environment(\.glucoseTintColor) var glucoseTintColor @Environment(\.appName) var appName public init( preset: CorrectionRangeOverrides.Preset, onExit: (() -> Void)? = nil, mode: SettingsPresentationMode = .acceptanceFlow ) { self.preset = preset self.onExit = onExit self.mode = mode } public var body: some View { GlucoseTherapySettingInformationView( therapySetting: preset.therapySetting, onExit: onExit, mode: mode, appName: appName, text: AnyView(section(for: preset)) ) } private func section(for preset: CorrectionRangeOverrides.Preset) -> some View { VStack(alignment: .leading, spacing: 15) { description(for: preset) .foregroundColor(.secondary) } } private func description(for preset: CorrectionRangeOverrides.Preset) -> some View { switch preset { case .preMeal: return VStack(alignment: .leading, spacing: 20) { Text(String(format: LocalizedString("Your Pre-Meal Range should be the glucose value (or range of values) you want %1$@ to target by the time you take your first bite of your meal. This range will be in effect when you activate the Pre-Meal Preset button.", comment: "Information about pre-meal range format (1: app name)"), appName)) Text(LocalizedString("This will typically be", comment: "Information about pre-meal range relative to correction range")) + Text(LocalizedString(" lower ", comment: "Information about pre-meal range relative to correction range")).bold().italic() + Text(LocalizedString("than your Correction Range.", comment: "Information about pre-meal range relative to correction range")) } .fixedSize(horizontal: false, vertical: true) // prevent text from being cut off case .workout: return VStack(alignment: .leading, spacing: 20) { Text(String(format: LocalizedString("Workout Range is the glucose value or range of values you want %1$@ to target during activity. This range will be in effect when you activate the Workout Preset button.", comment: "Information about workout range format (1: app name)"), appName)) Text(LocalizedString("This will typically be", comment: "Information about workout range relative to correction range")) + Text(LocalizedString(" higher ", comment: "Information about workout range relative to correction range")).bold().italic() + Text(LocalizedString("than your Correction Range.", comment: "Information about workout range relative to correction range")) } .fixedSize(horizontal: false, vertical: true) // prevent text from being cut off } } } struct CorrectionRangeOverrideInformationView_Previews: PreviewProvider { static var previews: some View { NavigationView { CorrectionRangeOverrideInformationView(preset: .preMeal) } .colorScheme(.light) .previewDevice(PreviewDevice(rawValue: "iPhone SE 2")) .previewDisplayName("Pre-Meal SE light") NavigationView { CorrectionRangeOverrideInformationView(preset: .workout) } .colorScheme(.light) .previewDevice(PreviewDevice(rawValue: "iPhone SE 2")) .previewDisplayName("Workout SE light") NavigationView { CorrectionRangeOverrideInformationView(preset: .preMeal) } .preferredColorScheme(.dark) .colorScheme(.dark) .previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max")) .previewDisplayName("Pre-Meal 11 Pro dark") NavigationView { CorrectionRangeOverrideInformationView(preset: .workout) } .preferredColorScheme(.dark) .colorScheme(.dark) .previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max")) .previewDisplayName("Workout 11 Pro dark") } }
4bab9df7b7211fa5bd0f05d192079eca
46.041667
391
0.669841
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift
gpl-2.0
2
import Foundation import WordPressShared /// This class renders a view with top and bottom separators, meant to be used as UITableView section /// header in NotificationsViewController. /// class NoteTableHeaderView: UIView { // MARK: - Public Properties var title: String? { set { // For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height! let unwrappedTitle = newValue?.localizedUppercase ?? String() let attributes = Style.sectionHeaderRegularStyle titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes) setNeedsLayout() } get { return titleLabel.text } } var separatorColor: UIColor? { set { contentView.bottomColor = newValue ?? UIColor.clear contentView.topColor = newValue ?? UIColor.clear } get { return contentView.bottomColor } } class func makeFromNib() -> NoteTableHeaderView { return Bundle.main.loadNibNamed("NoteTableHeaderView", owner: self, options: nil)?.first as! NoteTableHeaderView } // MARK: - Convenience Initializers override func awakeFromNib() { super.awakeFromNib() // Make sure the Outlets are loaded assert(contentView != nil) assert(imageView != nil) assert(titleLabel != nil) // Background + Separators backgroundColor = UIColor.clear contentView.backgroundColor = Style.sectionHeaderBackgroundColor contentView.bottomVisible = true contentView.topVisible = true } // MARK: - Aliases typealias Style = WPStyleGuide.Notifications // MARK: - Static Properties static let estimatedHeight = CGFloat(26) // MARK: - Outlets @IBOutlet fileprivate var contentView: SeparatorsView! @IBOutlet fileprivate var imageView: UIImageView! @IBOutlet fileprivate var titleLabel: UILabel! }
6bb57037c8667440bcebd817a68ff98a
30.578125
120
0.656111
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Cells/VerifyCoInfoFieldCell.swift
mit
1
// // VerifyCoInfoFieldCell.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // struct VerifyCoInfoFieldItem { let placeholder: String let title: String } class VerifyCoInfoFieldCell: UITableViewCell, Updatable { public var inputText: String? { return textField.text } private lazy var textField: UITextField = { let textField = UITextField() return textField }() private lazy var leftView: UILabel = { let label = UILabel(frame: CGSize(width: 100, height: 20).rect) label.textColor = UIColor(hex: 0x333333) label.font = UIFontMake(13) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none textField.leftView = leftView textField.leftViewMode = .always contentView.addSubview(textField) textField.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.height.equalTo(44) make.leading.equalTo(PADDING) make.trailing.equalTo(-PADDING) } HZUIHelper.generateBottomLine(in: contentView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(viewData: VerifyCoInfoFieldItem) { let attr = NSAttributedString(string: viewData.placeholder, attributes: [ .font: UIFontMake(15), .foregroundColor: UIColor(hex: 0x9B9B9B) ]) textField.attributedPlaceholder = attr leftView.text = viewData.title } }
6c07759443ae0b9fe8493e513d6e06b4
25.923077
81
0.642857
false
false
false
false
naebada-dev/swift
refs/heads/master
language-guide/Tests/language-guideTests/initialization/ClassInheritanceAndInitializationTests.swift
apache-2.0
1
import XCTest class ClassInheritanceAndInitializationTests : XCTestCase { override func setUp() { super.setUp(); print("############################"); } override func tearDown() { print("############################"); super.tearDown(); } /* Class Inheritance and Initialization 클래스의 스토어드 프로퍼티, 슈퍼클래스로부터 상속받는 어떤 프로퍼티들을 포함하여,는 반드시 초기화 과정에서 초기값이 설정되어야 한다. 스위프트는 모든 스토어드 프로퍼티가 초기값을 갖는 것을 보장하기 위해 두 가지 이니셜라이저를 제공한다. 지정 이니셜라이저(designated initializer)와 편의 이니셜라이저(convenience initializer) */ /* Designated Initializers and Convenience Initializers 지정 이니셜라이저는 주요(primary) 이니셜라이저이다. 지정 이니셜라이저는 그 클래스에서 소개하는 모든 프로퍼티를 완전히 초기화하고 적절한 슈퍼클래스의 이니설라이저를 호출한다. 클래스는 매우 적은 지정 이니셜라이저를 가지는 경향이 있다. 주로 한 개의 지정 이니셜라이저를 가지는게 보통이다. 지정 이니셜라이저는 슈퍼클래스로 초기화 과정을 계속하기 위한 깔때기(funnel) 포인트이다. 모든 클래스는 반드시 하나 이상의 지정 이니셜라이저를 가져야 한다. 편의 이니셜라이저는 초기화 과정을 지원하는 부가적인 이니셜라이저이다. 지정 이니셜라이저의 파라미터를 설정하며 지정 이니셜라이저를 호출하는 편의 이니셜라이저를 정의할 수 있다. 특별한 사용 사례 또는 입력 값을 위해 편의 이니셜라이저를 정의할 수 있다. */ /* Syntax for Designated and Convenience Initializers 지정 이니셜라이저 init(parameters) { statements } 편의 이니셜라이저 convenience init(parameters) { statements } */ /* Initializer Delegation for Class Types 지정 이니셜라이저와 편의 이니셜라이저 사이의 관계를 간단히 하기 위해서 스위프트는 이니셜라이저 사이의 위임을 위해 다음과 같은 세가지 룰을 적용한다. Rule 1 - 지정 이니셜라이저는 반드시 슈퍼클래스의 지정 이니셜라이저를 호출해야만 한다. Rule 2 - 편의 이니셜라이저는 반드시 같은 클래스의 다른 이니셜라이저를 호출해야만 한다. Rule 3 - 편의 이니셜라이저는 반드시 궁극적으로 지정 이니셜라이저를 호출해야만 한다. 간단히 말하면, - 지정 이니셜라이저는 항상 반드시 위로 위임한다. - 편의 이니셜라이저는 항산 반드시 옆으로 위임한다. */ /* Two-Phase Initialization 스위프트의 클래스 초기화는 두 단계 과정이다. 과정 1 - 해당 클래스가 소개한 스토어드 프로퍼티를 초기화한다. 과정 2 - 각 클래스는 인스턴스 생성 전에 스토어드 프로퍼티의 값을 변경할 기회가 주어진다. 스위프트 컴파일러는 2 단계 초기화를 보장하기 위해서 4개의 safely-check를 수행한다. Safety check 1 - 지정 이니셜라이저는 그 클래스에서 선언한 모든 프로퍼티는 슈퍼클래스의 이니셜라이저로 위임하기 전에 초기화되는 것을 보장해야 한다. Safety check 2 - 지정 이니셜라이저는 상속받은 프로퍼티에 값을 할당하기 전에 슈퍼클래스의 이니셜라이저로 위임해야 한다. Safety check 3 - 편의 이니셜라이저는 같은 클래스에 정의된 프로퍼티를 포함하여 어떤 프로퍼티에 값을 할당하기 전에 다른 이니셜라이저로 위임해야 한다. Safety check4 - 이니셜라이저는 어떠한 인스턴스 메소드도 호출할 수 없고 어떤 인스턴스 프로퍼티의 값을 읽을 수 없다. 첫번째 초기화 단계가 완료되기 전까지 self를 참조할 수 없다. 위의 4가지 safety check 기반으로 2단계 초기화가 어떻게 진행되는지는 아래와 같다. Phase 1 - 지정 또는 편의 이니셜라이저가 호출된다. - 새로운 인스턴스의 메모리는 할당되고, 아직 초기화되지 않는다. - 지정 이니셜라이저는 그 클래스가 소개한 모든 스토어드 프로퍼티가 값을 가지고 있는지 확인한다. 이러한 스토어드 프로퍼티의 메모리는 지금 초기화된다. - 지정 이니셜라이저는 같은 작업을 수행하기 위해서 수퍼클래스의 이니셜라이즈는 호출한다. - 상속 계층을 따라 위로 올라간다. - 최상위 클래스에서 모든 스토어드 프로퍼티가 모두 값을 가지고 있는 것을 확실히 한다. 인스턴스의 메모리는 완전히 초기화되었다고 생각한다. phase 1 완료. Phase 2 - 체인의 최상위에서 아래로 동작하면서, 각 체인의 지정 이니셜라이저는 인스턴스를 customize 할 수 있는 옵션을 가진다. 각 지정 이니셜라이지는 self, 프로퍼티에 접근하거나 메소드를 호출할 수 있다. - 마지막으로 편의 이니셜라이저도 위와 같은 동작을 한다. */ /* Initializer Inheritance and Overriding 스위프트의 서브클래스는 기본적으로 슈퍼클래스의 이니셜라이저를 상속하지 않는다. 슈퍼클래스의 지정 이니셜라이저를 오버라이딩할 수 있다. 서브클래스에서 슈퍼클래스의 편의 이니셜라이저를 직접 호출할 수 없으므로 슈퍼클래스의 편의 이니셜라이저에 매칭되는 서브클래스의 이니셜라이저는 override 키워드가 필요없다. */ func testClassInitialization() { let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") let bicycle = Bicycle() print("Bicycle: \(bicycle.description)") let hoverboard = Hoverboard(color: "silver") print("Hoverboard: \(hoverboard.description)") } private class Vehicle { // 기본 이니셜라이저 init() // 기본 이니셜라리저는 지정 이니셜라이저가 된다. var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } } private class Bicycle: Vehicle { // 커스텀 지정 이니셜라이저 정의 override init() { // 슈퍼클래스의 지정 이니셜라이저 호출 super.init() // 상속받은 프로퍼티의 값을 변경 numberOfWheels = 2 } } private class Hoverboard: Vehicle { var color: String init(color: String) { self.color = color // super.init() implicitly called here } override var description: String { return "\(super.description) in a beautiful \(color)" } } /* Automatic Initializer Inheritance 기본적으로 서브클래스는 슈퍼클래스의 이니셜라이저를 상속하지 않는다. 그러나 슈퍼클래스의 이니셜라이저는 특정 조건이 만족하면 자동적으로 상속된다. Rule 1 - 서브클래스가 아무런 지정 이니셜라이저를 정의하지 않은 경우, 슈퍼클래스의 지정 이니셜라이저를 자정 이니셜라이저는 상속된다. Rule 2 - 서브클래스가 슈퍼클래스의 모든 지정 이니셜라이저의 구현을 제공안 경우, Rule 1의 경우이거나 커스텀 구현을 제공한 경우, 슈퍼클래스의 모든 편의 이니셜라이저는 자동으로 상속된다. */ func testInitializersInherit() { let namedMeat = Food(name: "Bacon") print("\(namedMeat.name)") let mysteryMeat = Food() print("\(mysteryMeat.name)") } private class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } func testInitializersInherit2() { let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) } private class RecipeIngredient : Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } // 상위클래스의 지정 이니셜라이저 override // Rule 2 에 의해서 상위클래스의 init() 상속 override convenience init(name: String) { self.init(name: name, quantity: 1) } } func testInitializersInherit3() { var breakfastList = [ ShoppingListItem2(), ShoppingListItem2(name: "Bacon"), ShoppingListItem2(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } } private class ShoppingListItem2 : RecipeIngredient { // Rule 1에 의해서 상위클래스의 이니셜라이저 상속 var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } }
e503de759fc7a676584542ea15371dbf
24.728682
78
0.569449
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/Pods/SwiftyStoreKit/SwiftyStoreKit/AppleReceiptValidator.swift
mit
1
// // InAppReceipt.swift // SwiftyStoreKit // // Created by phimage on 22/12/15. // 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 // https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html public struct AppleReceiptValidator: ReceiptValidator { public enum VerifyReceiptURLType: String { case production = "https://buy.itunes.apple.com/verifyReceipt" case sandbox = "https://sandbox.itunes.apple.com/verifyReceipt" } private let service: VerifyReceiptURLType private let sharedSecret: String? /** * Reference Apple Receipt Validator * - Parameter service: Either .production or .sandbox * - Parameter sharedSecret: Only used for receipts that contain auto-renewable subscriptions. Your app’s shared secret (a hexadecimal string). */ public init(service: VerifyReceiptURLType = .production, sharedSecret: String? = nil) { self.service = service self.sharedSecret = sharedSecret } public func validate(receiptData: Data, completion: @escaping (VerifyReceiptResult) -> Void) { let storeURL = URL(string: service.rawValue)! // safe (until no more) let storeRequest = NSMutableURLRequest(url: storeURL) storeRequest.httpMethod = "POST" let receipt = receiptData.base64EncodedString(options: []) let requestContents: NSMutableDictionary = [ "receipt-data": receipt ] // password if defined if let password = sharedSecret { requestContents.setValue(password, forKey: "password") } // Encore request body do { storeRequest.httpBody = try JSONSerialization.data(withJSONObject: requestContents, options: []) } catch let e { completion(.error(error: .requestBodyEncodeError(error: e))) return } // Remote task let task = URLSession.shared.dataTask(with: storeRequest as URLRequest) { data, _, error -> Void in // there is an error if let networkError = error { completion(.error(error: .networkError(error: networkError))) return } // there is no data guard let safeData = data else { completion(.error(error: .noRemoteData)) return } // cannot decode data guard let receiptInfo = try? JSONSerialization.jsonObject(with: safeData, options: .mutableLeaves) as? ReceiptInfo ?? [:] else { let jsonStr = String(data: safeData, encoding: String.Encoding.utf8) completion(.error(error: .jsonDecodeError(string: jsonStr))) return } // get status from info if let status = receiptInfo["status"] as? Int { /* * http://stackoverflow.com/questions/16187231/how-do-i-know-if-an-in-app-purchase-receipt-comes-from-the-sandbox * How do I verify my receipt (iOS)? * Always verify your receipt first with the production URL; proceed to verify * with the sandbox URL if you receive a 21007 status code. Following this * approach ensures that you do not have to switch between URLs while your * application is being tested or reviewed in the sandbox or is live in the * App Store. * Note: The 21007 status code indicates that this receipt is a sandbox receipt, * but it was sent to the production service for verification. */ let receiptStatus = ReceiptStatus(rawValue: status) ?? ReceiptStatus.unknown if case .testReceipt = receiptStatus { let sandboxValidator = AppleReceiptValidator(service: .sandbox, sharedSecret: self.sharedSecret) sandboxValidator.validate(receiptData: receiptData, completion: completion) } else { if receiptStatus.isValid { completion(.success(receipt: receiptInfo)) } else { completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: receiptStatus))) } } } else { completion(.error(error: .receiptInvalid(receipt: receiptInfo, status: ReceiptStatus.none))) } } task.resume() } }
794b8721b630f26d7ed7820c2636e1b2
39.008065
148
0.725055
false
false
false
false
LGLee/common-classes
refs/heads/master
iCarousel-master/Examples/Swift Example/SwiftExample/ViewController.swift
apache-2.0
2
// // ViewController.swift // SwiftExample // // Created by Nick Lockwood on 30/07/2014. // Copyright (c) 2014 Charcoal Design. All rights reserved. // import UIKit class ViewController: UIViewController, iCarouselDataSource, iCarouselDelegate { var items: [Int] = [] @IBOutlet var carousel : iCarousel! override func awakeFromNib() { super.awakeFromNib() for i in 0...99 { items.append(i) } } override func viewDidLoad() { super.viewDidLoad() carousel.type = .CoverFlow2 } func numberOfItemsInCarousel(carousel: iCarousel) -> Int { return items.count } func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView { var label: UILabel var itemView: UIImageView //create new view if no view is available for recycling if (view == nil) { //don't do anything specific to the index within //this `if (view == nil) {...}` statement because the view will be //recycled and used with other index values later itemView = UIImageView(frame:CGRect(x:0, y:0, width:200, height:200)) itemView.image = UIImage(named: "page.png") itemView.contentMode = .Center label = UILabel(frame:itemView.bounds) label.backgroundColor = UIColor.clearColor() label.textAlignment = .Center label.font = label.font.fontWithSize(50) label.tag = 1 itemView.addSubview(label) } else { //get a reference to the label in the recycled view itemView = view as! UIImageView; label = itemView.viewWithTag(1) as! UILabel! } //set item label //remember to always set any properties of your carousel item //views outside of the `if (view == nil) {...}` check otherwise //you'll get weird issues with carousel item content appearing //in the wrong place in the carousel label.text = "\(items[index])" return itemView } func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat { if (option == .Spacing) { return value * 1.1 } return value } }
19e053a288ff7619cbfe03a55b4e4ade
27.8
117
0.580065
false
false
false
false
radianttap/Coordinator
refs/heads/master
Coordinator/UIKit-CoordinatingExtensions.swift
mit
1
// // UIKit-CoordinatingExtensions.swift // Radiant Tap Essentials // // Copyright © 2016 Radiant Tap // MIT License · http://choosealicense.com/licenses/mit/ // import UIKit // Inject parentCoordinator property into all UIViewControllers extension UIViewController { private class WeakCoordinatingTrampoline: NSObject { weak var coordinating: Coordinating? } private struct AssociatedKeys { static var ParentCoordinator = "ParentCoordinator" } public weak var parentCoordinator: Coordinating? { get { let trampoline = objc_getAssociatedObject(self, &AssociatedKeys.ParentCoordinator) as? WeakCoordinatingTrampoline return trampoline?.coordinating } set { let trampoline = WeakCoordinatingTrampoline() trampoline.coordinating = newValue objc_setAssociatedObject(self, &AssociatedKeys.ParentCoordinator, trampoline, .OBJC_ASSOCIATION_RETAIN) } } } /** Driving engine of the message passing through the app, with no need for Delegate pattern nor Singletons. It piggy-backs on the `UIResponder.next` in order to pass the message through UIView/UIVC hierarchy of any depth and complexity. However, it does not interfere with the regular `UIResponder` functionality. At the `UIViewController` level (see below), it‘s intercepted to switch up to the coordinator, if the UIVC has one. Once that happens, it stays in the `Coordinator` hierarchy, since coordinator can be nested only inside other coordinators. */ extension UIResponder { @objc open var coordinatingResponder: UIResponder? { return next } /* // sort-of implementation of the custom message/command to put into your Coordinable extension func messageTemplate(args: Whatever, sender: Any? = nil) { coordinatingResponder?.messageTemplate(args: args, sender: sender) } */ } extension UIViewController { /** Returns `parentCoordinator` if this controller has one, or its parent `UIViewController` if it has one, or its view's `superview`. Copied from `UIResponder.next` documentation: - The `UIResponder` class does not store or set the next responder automatically, instead returning nil by default. - Subclasses must override this method to set the next responder. - UIViewController implements the method by returning its view’s superview; - UIWindow returns the application object, and UIApplication returns nil. */ override open var coordinatingResponder: UIResponder? { guard let parentCoordinator = self.parentCoordinator else { guard let parentController = self.parent else { guard let presentingController = self.presentingViewController else { return view.superview } return presentingController as UIResponder } return parentController as UIResponder } return parentCoordinator as? UIResponder } }
83299f47492372a450e4f5c361b79d0e
30.877778
128
0.745904
false
false
false
false
cheyongzi/MGTV-Swift
refs/heads/master
MGTV-Swift/Share/Extension/UIViewController+Extension.swift
mit
1
// // UIViewController+Extension.swift // MGTV-Swift // // Created by Che Yongzi on 16/10/17. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit extension UIViewController { func barItem(_ imageName: String, frame: CGRect) -> UIBarButtonItem { let imageView = UIImageView.init(frame: frame) imageView.image = UIImage(named: imageName) let barItem = UIBarButtonItem(customView: imageView) return barItem } func barItem(imageName: String, frame: CGRect, selector: Selector?) -> UIBarButtonItem { let button = UIButton(type: .custom) button.frame = frame button.setImage(UIImage(named: imageName), for: .normal) if let sel = selector { button.addTarget(self, action: sel, for: .touchUpInside) } let item = UIBarButtonItem(customView: button) return item } func barItem(title: String, frame: CGRect, selector: Selector?) -> UIBarButtonItem { let button = UIButton(type: .custom) button.frame = frame button.setAttributedTitle(NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 15)]), for: .normal) if let sel = selector { button.addTarget(self, action: sel, for: .touchUpInside) } let item = UIBarButtonItem(customView: button) return item } func barItem(_ width: CGFloat) -> UIBarButtonItem { let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) space.width = width return space } } extension UIViewController { static func visibleController(_ viewController: UIViewController) -> UIViewController { if let controller = viewController.presentedViewController { return UIViewController.visibleController(controller) } else if let navController = viewController as? UINavigationController { guard navController.viewControllers.count > 0 else { return viewController } return UIViewController.visibleController(navController.topViewController!) } else if let tabBarController = viewController as? UITabBarController { guard (tabBarController.viewControllers?.count)! > 0 else { return viewController } return UIViewController.visibleController(tabBarController.selectedViewController!) }else { return viewController } } static func currentController() -> UIViewController { let viewController = BaseTabBarController.mainController return UIViewController.visibleController(viewController) } }
e9e100c99721ef172286704391ff3c6d
37.791667
197
0.66416
false
false
false
false
Where2Go/swiftsina
refs/heads/master
GZWeibo05/Class/Module/NewFeature/Controller/CZWelcomeViewController.swift
apache-2.0
2
// // CZWelcomeViewController.swift // GZWeibo05 // // Created by zhangping on 15/10/29. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit import SDWebImage class CZWelcomeViewController: UIViewController { // MARK: - 属性 /// 头像底部约束 private var iconViewBottomCons: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() prepareUI() if let urlString = CZUserAccount.loadAccount()?.avatar_large { // 设置用户的头像 iconView.cz_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "avatar_default_big")) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // 开始动画 iconViewBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - 160) // usingSpringWithDamping: 值越小弹簧效果越明显 0 - 1 // initialSpringVelocity: 初速度 UIView.animateWithDuration(1.0, delay: 0.1, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.view.layoutIfNeeded() }) { (_) -> Void in UIView.animateWithDuration(1, animations: { () -> Void in self.welcomeLabel.alpha = 1 }, completion: { (_) -> Void in (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(true) }) } } /// MARK: - 准备UI private func prepareUI() { // 添加子控件 view.addSubview(backgorundImageView) view.addSubview(iconView) view.addSubview(welcomeLabel) // 添加约束 backgorundImageView.translatesAutoresizingMaskIntoConstraints = false iconView.translatesAutoresizingMaskIntoConstraints = false welcomeLabel.translatesAutoresizingMaskIntoConstraints = false // 背景 // 填充父控件 VFL /* H | 父控件的左边 | 父控件的右边 V | 父控件的顶部 | 父控件的底部 */ // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : backgorundImageView])) // // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : backgorundImageView])) // 填充父控件 backgorundImageView.ff_Fill(view) // 头像 // view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) // // view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85)) // // view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85)) // // // 垂直 底部160 // iconViewBottomCons = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160) // view.addConstraint(iconViewBottomCons!) // 内部: ff_AlignInner, 中间下边: ff_AlignType.BottomCenter // 返回所有的约束 let cons = iconView.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: 85, height: 85), offset: CGPoint(x: 0, y: -160)) // 在所有的约束里面查找某个约束 // iconView: 获取哪个view上面的约束 // constraintsList: iconView上面的所有约束 // attribute: 获取的约束 iconViewBottomCons = iconView.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom) // 欢迎归来 // H // view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) // view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) welcomeLabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 16)) } // MARK: - 懒加载 /// 背景 private lazy var backgorundImageView: UIImageView = UIImageView(image: UIImage(named: "ad_background")) /// 头像 private lazy var iconView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "avatar_default_big")) // 切成圆 imageView.layer.cornerRadius = 42.5 imageView.layer.masksToBounds = true return imageView }() /// 欢迎归来 private lazy var welcomeLabel: UILabel = { let label = UILabel() label.text = "欢迎归来" label.alpha = 0 return label }() }
bf18e99a0f3bd9032f1758c0ac931304
41.15873
225
0.648532
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestMarker.swift
mit
1
// // QuestMarker.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 11/2/17. // import Foundation public struct QuestMarker: Codable, Equatable { public let id: String? public let name: String? public let status: String? public let time: Double public let assetId: String? // FK to the CDAsset init(id: String?, name: String?, status: String?, time: Double, assetId: String? = nil) { self.id = id self.name = name self.status = status self.time = time self.assetId = assetId } } // MARK: - JSON Key public struct QuestMarkers: Codable { public let markers: [QuestMarker] } // MARK: - Equatable extension QuestMarker { public static func ==(lhs: QuestMarker, rhs: QuestMarker) -> Bool { if lhs.id != rhs.id { return false } if lhs.name != rhs.name { return false } if lhs.status != rhs.status { return false } if lhs.time != rhs.time { return false } if lhs.assetId != rhs.assetId { return false } return true } }
2406a2f9a643da97ab31ea7db4b2c0ac
19.912281
93
0.553691
false
false
false
false
ludoded/ReceiptBot
refs/heads/master
ReceiptBot/Scene/Expenses/ExpensesWorker.swift
lgpl-3.0
1
// // ExpensesWorker.swift // ReceiptBot // // Created by Haik Ampardjian on 4/5/17. // Copyright (c) 2017 receiptbot. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit import Charts class ExpensesWorker { let entityId: Int init(entityId: Int) { self.entityId = entityId } func fetchLineData(callback: @escaping (RebotValueWrapper<LineChartDataSet>) -> ()) { LineChartResponse.loadType(request: API.lineChart(with: entityId)) { (lineResp, message) in guard message == nil else { callback(.none(message: message!)); return } guard let line = lineResp else { callback(.none(message: "Can't parse Line Data!")); return } var values: [ChartDataEntry] = [] let lastMonth: Double = Double(line.months.last?.monthYear ?? "0") ?? 0 for month in line.months { var monthVal = Double(month.monthYear) ?? 0 monthVal = monthVal > lastMonth ? monthVal - 12 : monthVal values.append(ChartDataEntry(x: monthVal, y: Double(month.totalAmount))) } let dataSet = LineChartDataSet(values: values, label: nil) dataSet.colors = [RebotColor.Line.line] dataSet.drawValuesEnabled = true dataSet.drawCirclesEnabled = true dataSet.circleColors = [RebotColor.Line.point] dataSet.drawCircleHoleEnabled = true dataSet.circleHoleColor = .white dataSet.lineWidth = 3.0 dataSet.fillAlpha = 0.5 dataSet.fill = Fill(color: RebotColor.Line.fill) dataSet.drawFilledEnabled = true dataSet.mode = .cubicBezier callback(.value(dataSet)) } } }
86322ef9d93c41605610ac716a02d96d
35.811321
105
0.598667
false
false
false
false
fhchina/firefox-ios
refs/heads/master
Sync/Synchronizers/IndependentRecordSynchronizer.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger class Uploader { /** * Upload just about anything that can be turned into something we can upload. */ func sequentialPosts<T>(items: [T], by: Int, lastTimestamp: Timestamp, storageOp: ([T], Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { // This needs to be a real Array, not an ArraySlice, // for the types to line up. let chunks = chunk(items, by: by).map { Array($0) } let start = deferResult(lastTimestamp) let perChunk: ([T], Timestamp) -> DeferredTimestamp = { (records, timestamp) in // TODO: detect interruptions -- clients uploading records during our sync -- // by using ifUnmodifiedSince. We can detect uploaded records since our download // (chain the download timestamp into this function), and we can detect uploads // that race with our own (chain download timestamps across 'walk' steps). // If we do that, we can also advance our last fetch timestamp after each chunk. log.debug("Uploading \(records.count) records.") return storageOp(records, timestamp) } return walk(chunks, start, perChunk) } } public class IndependentRecordSynchronizer: BaseSingleCollectionSynchronizer { func applyIncomingToStorage<T>(records: [T], fetched: Timestamp, apply: T -> Success) -> Success { func done() -> Success { log.debug("Bumping fetch timestamp to \(fetched).") self.lastFetched = fetched return succeed() } if records.isEmpty { log.debug("No records; done applying.") return done() } return walk(records, apply) >>> done } /* * On each chunk that we upload, we pass along the server modified timestamp to the next, * chained through the provided `onUpload` function. * * The last chunk passes this modified timestamp out, and we assign it to lastFetched. * * The idea of this is twofold: * * 1. It does the fast-forwarding that every other Sync client does. * * 2. It allows us to (eventually) pass the last collection modified time as If-Unmodified-Since * on each upload batch, as we do between the download and the upload phase. * This alone allows us to detect conflicts from racing clients. * * In order to implement the latter, we'd need to chain the date from getSince in place of the * 0 in the call to uploadOutgoingFromStorage in each synchronizer. */ func uploadRecords<T>(records: [Record<T>], by: Int, lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>, onUpload: ([GUID], Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { if records.isEmpty { log.debug("No modified records to upload.") return deferResult(lastTimestamp) } let storageOp: ([Record<T>], Timestamp) -> DeferredTimestamp = { records, timestamp in // TODO: use I-U-S. // Each time we do the storage operation, we might receive a backoff notification. // For a success response, this will be on the subsequent request, which means we don't // have to worry about handling successes and failures mixed with backoffs here. return storageClient.post(records, ifUnmodifiedSince: nil) >>== { onUpload($0.value.success, $0.value.modified) } } log.debug("Uploading \(records.count) modified records.") // Chain the last upload timestamp right into our lastFetched timestamp. // This is what Sync clients tend to do, but we can probably do better. // Upload 50 records at a time. return Uploader().sequentialPosts(records, by: by, lastTimestamp: lastTimestamp, storageOp: storageOp) >>== effect(self.setTimestamp) } }
c2545219cb661ecdc02ad1c5984c416a
43.147368
199
0.651324
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Unit/View/UnitTableViewCell.swift
mit
2
// // UnitTableViewCell.swift // DereGuide // // Created by zzk on 16/7/28. // Copyright © 2016 zzk. All rights reserved. // import UIKit import SnapKit class UnitTableViewCell: UITableViewCell { var iconStackView: UIStackView! var cardIcons: [CGSSCardIconView] { return iconStackView.arrangedSubviews.compactMap { ($0 as? UnitSimulationCardView)?.icon } } // var appealStackView: UIStackView! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) prepareUI() } private func prepareUI() { var views = [UIView]() for _ in 0...5 { let view = UnitSimulationCardView() views.append(view) } iconStackView = UIStackView(arrangedSubviews: views) iconStackView.spacing = 5 iconStackView.distribution = .fillEqually iconStackView.isUserInteractionEnabled = false contentView.addSubview(iconStackView) // var labels = [UILabel]() // let colors = [Color.life, Color.vocal, Color.dance, Color.visual, UIColor.darkGray] // for i in 0...4 { // let label = UILabel() // label.font = UIFont.init(name: "menlo", size: 12) // label.textColor = colors[i] // labels.append(label) // } // // appealStackView = UIStackView(arrangedSubviews: labels) // appealStackView.spacing = 5 // appealStackView.distribution = .equalCentering // contentView.addSubview(appealStackView) iconStackView.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.greaterThanOrEqualTo(10) make.right.lessThanOrEqualTo(-10) // make the view as wide as possible make.right.equalTo(-10).priority(900) make.left.equalTo(10).priority(900) // make.bottom.equalTo(-10) make.width.lessThanOrEqualTo(96 * 6 + 25) make.centerX.equalToSuperview() } // appealStackView.snp.makeConstraints { (make) in // make.left.equalTo(10) // make.right.equalTo(-10) // make.top.equalTo(iconStackView.snp.bottom) // make.bottom.equalTo(-5) // } accessoryType = .disclosureIndicator } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareUI() } func setup(with unit: Unit) { for i in 0...5 { let member = unit[i] if let card = member.card, let view = iconStackView.arrangedSubviews[i] as? UnitSimulationCardView { view.icon.cardID = card.id if i != 5 { if card.skill != nil { view.skillLabel.text = "SLv.\((member.skillLevel))" } else { view.skillLabel.text = "n/a" } } else { view.skillLabel.text = "n/a" } view.potentialLabel.setup(with: member.potential) } } } }
a839c115d171b24534ff3c4e988587bc
31.39
112
0.552948
false
false
false
false
KrishMunot/swift
refs/heads/master
test/type/array.swift
apache-2.0
3
// RUN: %target-parse-verify-swift // Array types. class Base1 { func f0(_ x: [Int]) { } func f0a(_ x: [Int]?) { } func f1(_ x: [[Int]]) { } func f1a(_ x: [[Int]]?) { } func f2(_ x: [[Int] -> [Int]]) { } func f2a(_ x: [[Int]? -> [Int]?]?) { } } class Derived1 : Base1 { override func f0(_ x: Array<Int>) { } override func f0a(_ x: Optional<Array<Int>>) { } override func f1(_ x: Array<Array<Int>>) { } override func f1a(_ x: Optional<Array<Array<Int>>>) { } override func f2(_ x: Array<Array<Int> -> Array<Int>>) { } override func f2a(_ x: Optional<Array<Optional<Array<Int>> -> Optional<Array<Int>>>>) { } } // Array types in generic specializations. struct X<T> { } func testGenericSpec() { _ = X<[Int]>() } // Array types for construction. func constructArray(_ n: Int) { var ones = [Int](repeating: 1, count: n) ones[5] = 0 var matrix = [[Float]]() matrix[1][2] = 3.14159 var _: [Int?] = [Int?]() } // Fix-Its from the old syntax to the new. typealias FixIt0 = Int[] // expected-error{{array types are now written with the brackets around the element type}}{{20-20=[}}{{23-24=}}
d7fbae7077da0da703927a02c9106e86
24.681818
136
0.581416
false
false
false
false
ykyouhei/QiitaKit
refs/heads/master
Example/APITableViewController.swift
mit
1
// // APITableViewController.swift // QiitaKit // // Created by kyo__hei on 2016/07/16. // Copyright © 2016年 kyo__hei. All rights reserved. // import UIKit import QiitaKit internal final class APITableViewController: UITableViewController { fileprivate var successObject: Any? override func viewDidLoad() { super.viewDidLoad() title = currentUser.name navigationController?.delegate = self } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).row { case 0: send(QiitaAPI.User.GetAuthenticatedUserRequest()) case 1: send(QiitaAPI.User.GetUsersRequest( page: 1, perPage: 10) ) case 2: send(QiitaAPI.User.GetFolloweesRequest( userID: currentUser.id, page: 1, perPage: 10) ) case 3: send(QiitaAPI.User.GetFollowersRequest( userID: currentUser.id, page: 1, perPage: 10) ) case 4: send(QiitaAPI.Item.GetItemsRequest( type: .authenticatedUser, page: 1, perPage: 10) ) case 5: send(QiitaAPI.Tag.GetFollowingTagsRequest( userID: currentUser.id, page: 1, perPage: 10) ) default: break } } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.destination { case let vc as RequestViewController: vc.object = successObject default: break } } func send<T: QiitaRequest>(_ request: T) { let indicator = UIActivityIndicatorView(frame: view.bounds) indicator.startAnimating() indicator.activityIndicatorViewStyle = .gray view.addSubview(indicator) APIClient().send(request) { result in indicator.removeFromSuperview() switch result { case .success(let object): print(object) self.successObject = object self.performSegue(withIdentifier: "showRequest", sender: nil) case .failure(let error): self.showErrorAlert(error) } } } } extension APITableViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController is LoginViewController { let _ = try? AuthManager.sharedManager.logout() } } }
654a15fdd68b975002029e7cd9001ab8
26.902655
106
0.527117
false
false
false
false
soapyigu/LeetCode_Swift
refs/heads/master
DP/DifferentWaysAddParentheses.swift
mit
1
/** * Question Link: https://leetcode.com/problems/different-ways-to-add-parentheses/ * Primary idea: Divide and Conquer, calculate left and right separately and union results * * Note: Keep a memo dictionary to avoid duplicate calculations * Time Complexity: O(n^n), Space Complexity: O(n) * */ class DifferentWaysAddParentheses { var memo = [String: [Int]]() func diffWaysToCompute(_ input: String) -> [Int] { if let nums = memo[input] { return nums } var res = [Int]() let chars = Array(input.characters) for (i, char) in chars.enumerated() { if char == "+" || char == "*" || char == "-" { let leftResults = diffWaysToCompute(String(chars[0..<i])) let rightResults = diffWaysToCompute(String(chars[i + 1..<chars.count])) for leftRes in leftResults { for rightRes in rightResults { if char == "+" { res.append(leftRes + rightRes) } if char == "-" { res.append(leftRes - rightRes) } if char == "*" { res.append(leftRes * rightRes) } } } } } if res.count == 0 { res.append(Int(input)!) } memo[input] = res return res } }
26c55d341a92835666833901dff76366
30.2
90
0.44644
false
false
false
false
jdanthinne/PIImageCache
refs/heads/master
PIImageCache/PIImageCache/ViewController.swift
mit
2
import UIKit class ViewController: UIViewController { let cache = PIImageCache() let lormpixelCategory = [ "animals", "cats", "city", "fashion" ] var count = 0 @IBOutlet var imgView: UIImageView! @IBAction func btnPushed(sender: AnyObject) { count++ if count >= lormpixelCategory.count { count = 0 } let url = NSURL(string: "http://lorempixel.com/200/200/" + lormpixelCategory[count] )! imgView.imageOfURL(url) } override func didReceiveMemoryWarning() { cache.allMemoryCacheDelete() } }
76471d03fa1ed39d7340f0cbc0faf127
18
90
0.639719
false
false
false
false
milankamilya/MKPostCardMenu
refs/heads/master
PostCardMenuClasses/MKFixedFluidView.swift
mit
1
// // MKFixedFluidView.swift // PostcardMenu // // Created by Milan Kamilya on 23/09/15. // Copyright (c) 2015 innofied. All rights reserved. // import UIKit enum MKFluidMenuSide { case Right case Left } protocol MKFixedFluidViewDelegate { func fixedFluidView(fixedFluidView:MKFixedFluidView, didOpenFromSide:MKFluidMenuSide); func fixedFluidView(fixedFluidView:MKFixedFluidView, didCloseToSide:MKFluidMenuSide); } class MKFixedFluidView: MKFluidView { //MARK: - PUBLIC PROPERTIES var destinationPoint: CGPoint? = CGPointMake(70, 290) var isOpen: Bool? = false var isTogglePressed: Bool? = false var delegate: MKFixedFluidViewDelegate? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - USER INTERACTION // touch Began func touchBegan(var touchPoint: CGPoint) { print("touchBegan") if !isOpen! { touchPoint = CGPointMake(touchPoint.x, destinationPoint!.y ) super.initializeTouchRecognizer(touchPoint) } } // touch Moving func touchMoving(var touchPoint: CGPoint) { print("touchMoving \(touchPoint)\n") if !isOpen! { touchPoint = CGPointMake(touchPoint.x, destinationPoint!.y ) super.movingTouchRecognizer(touchPoint) } } // touch End func touchEnded(touchPoint: CGPoint, callback onComplition:((Void) -> Void )?) { if !isOpen! && !isTogglePressed! { print("touchEnded \(destinationPoint!)") super.movingTouchRecognizer( destinationPoint!, animationBundle: AnimationBundle(duration: 0.3, delay: 0.0, dumping: 1.0, velocity: 1.0), callback: onComplition) isOpen = true delegate?.fixedFluidView(self, didOpenFromSide: MKFluidMenuSide.Right) } isTogglePressed = false } // Open / Close func toggleCurve(callback onComplition:((Void) -> Void )?) { print("toggleCurve") if isOpen! { super.endTouchRecognizer(destinationPoint!, callback: onComplition) isOpen = false delegate?.fixedFluidView(self, didCloseToSide: MKFluidMenuSide.Right) } else { super.initializeTouchRecognizer( destinationPoint!, animationBundle: AnimationBundle(duration: 0.3, delay: 0.0, dumping: 1.0, velocity: 1.0)) isOpen = true delegate?.fixedFluidView(self, didOpenFromSide: MKFluidMenuSide.Right) } //isTogglePressed = true } }
069dd586ef469875fe574613e218c7df
28.391304
173
0.627959
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/InlineAudioPlayerView.swift
gpl-2.0
1
// // InlineAudioPlayerView.swift // TelegramMac // // Created by keepcoder on 21/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox import SwiftSignalKit import RangeSet class InlineAudioPlayerView: NavigationHeaderView, APDelegate { struct ContextObject { let controller: APController let context: AccountContext let tableView: TableView? let supportTableView: TableView? } var contextValue: ContextObject? { return header?.contextObject as? ContextObject } var controller: APController? { return contextValue?.controller } var context: AccountContext? { return contextValue?.context } private let previous:ImageButton = ImageButton() private let next:ImageButton = ImageButton() private let playPause = Button() private let playPauseView = LottiePlayerView() private let dismiss:ImageButton = ImageButton() private let repeatControl:ImageButton = ImageButton() private let volumeControl: ImageButton = ImageButton() private let progressView:LinearProgressControl = LinearProgressControl(progressHeight: 2) private var artistNameView:TextView? private let trackNameView:TextView = TextView() private let textViewContainer = Control() private let containerView:Control private let separator:View = View() private let playingSpeed: ImageButton = ImageButton() private var message:Message? private(set) var instantVideoPip:InstantVideoPIP? private var ranges: (RangeSet<Int64>, Int64)? private var bufferingStatusDisposable: MetaDisposable = MetaDisposable() override init(_ header: NavigationHeader) { separator.backgroundColor = .border dismiss.disableActions() repeatControl.disableActions() trackNameView.isSelectable = false trackNameView.userInteractionEnabled = false containerView = Control(frame: NSMakeRect(0, 0, 0, header.height)) super.init(header) dismiss.set(handler: { [weak self] _ in self?.stopAndHide(true) }, for: .Click) previous.set(handler: { [weak self] _ in self?.controller?.prev() }, for: .Click) next.set(handler: { [weak self] _ in self?.controller?.next() }, for: .Click) playPause.set(handler: { [weak self] _ in self?.controller?.playOrPause() }, for: .Click) repeatControl.set(handler: { [weak self] _ in if let controller = self?.controller { controller.nextRepeatState() } }, for: .Click) progressView.onUserChanged = { [weak self] progress in self?.controller?.set(trackProgress: progress) self?.progressView.set(progress: CGFloat(progress), animated: false) } var paused: Bool = false progressView.startScrobbling = { [weak self] in guard let controller = self?.controller else { return } if controller.isPlaying { _ = self?.controller?.pause() paused = true } else { paused = false } } progressView.endScrobbling = { [weak self] in if paused { DispatchQueue.main.async { _ = self?.controller?.play() } } } progressView.set(handler: { [weak self] control in let control = control as! LinearProgressControl if let strongSelf = self { strongSelf.controller?.set(trackProgress: control.interactiveValue) strongSelf.progressView.set(progress: CGFloat(control.interactiveValue), animated: false) } }, for: .Click) previous.autohighlight = false next.autohighlight = false playPause.autohighlight = false repeatControl.autohighlight = false volumeControl.autohighlight = false playingSpeed.autohighlight = false previous.scaleOnClick = true next.scaleOnClick = true playPause.scaleOnClick = true repeatControl.scaleOnClick = true volumeControl.scaleOnClick = true playingSpeed.scaleOnClick = true containerView.addSubview(previous) containerView.addSubview(next) playPause.addSubview(playPauseView) playPause.setFrameSize(NSMakeSize(34, 34)) playPauseView.setFrameSize(playPause.frame.size) containerView.addSubview(playPause) containerView.addSubview(dismiss) containerView.addSubview(repeatControl) containerView.addSubview(textViewContainer) containerView.addSubview(playingSpeed) containerView.addSubview(volumeControl) addSubview(containerView) addSubview(separator) addSubview(progressView) textViewContainer.addSubview(trackNameView) trackNameView.userInteractionEnabled = false trackNameView.isEventLess = true textViewContainer.set(handler: { [weak self] _ in self?.showAudioPlayerList() }, for: .LongOver) textViewContainer.set(handler: { [weak self] _ in self?.gotoMessage() }, for: .SingleClick) playingSpeed.set(handler: { [weak self] control in FastSettings.setPlayingRate(FastSettings.playingRate != 1 ? 1.0 : 1.75) self?.controller?.baseRate = FastSettings.playingRate }, for: .Click) volumeControl.set(handler: { [weak self] control in if control.popover == nil { showPopover(for: control, with: VolumeControllerPopover(initialValue: CGFloat(FastSettings.volumeRate), updatedValue: { updatedVolume in FastSettings.setVolumeRate(Float(updatedVolume)) self?.controller?.volume = FastSettings.volumeRate }), edge: .maxY, inset: NSMakePoint(-5, -50)) } }, for: .Hover) volumeControl.set(handler: { control in FastSettings.setVolumeRate(FastSettings.volumeRate > 0 ? 0 : 1.0) if let popover = control.popover?.controller as? VolumeControllerPopover { popover.value = CGFloat(FastSettings.volumeRate) } }, for: .Up) updateLocalizationAndTheme(theme: theme) } private func showAudioPlayerList() { guard let window = kitWindow, let context = self.context else {return} let point = containerView.convert(window.mouseLocationOutsideOfEventStream, from: nil) if NSPointInRect(point, textViewContainer.frame) { if let controller = controller as? APChatMusicController, let song = controller.currentSong { switch song.stableId { case let .message(message): showPopover(for: textViewContainer, with: PlayerListController(audioPlayer: self, context: controller.context, currentContext: context, messageIndex: MessageIndex(message), messages: controller.messages), edge: .minX, inset: NSMakePoint(-130, -60)) default: break } } } } func updateStatus(_ ranges: RangeSet<Int64>, _ size: Int64) { self.ranges = (ranges, size) if let ranges = self.ranges, !ranges.0.isEmpty, ranges.1 != 0 { for range in ranges.0.ranges { var progress = (CGFloat(range.count) / CGFloat(ranges.1)) progress = progress == 1.0 ? 0 : progress progressView.set(fetchingProgress: progress, animated: progress > 0) break } } } private var playProgressStyle:ControlStyle { return ControlStyle(foregroundColor: theme.colors.accent, backgroundColor: .clear, highlightColor: .clear) } private var fetchProgressStyle:ControlStyle { return ControlStyle(foregroundColor: theme.colors.grayTransparent, backgroundColor: .clear, highlightColor: .clear) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) let theme = (theme as! TelegramPresentationTheme) progressView.fetchingColor = theme.colors.accent.withAlphaComponent(0.5) backgroundColor = theme.colors.background containerView.backgroundColor = theme.colors.background artistNameView?.backgroundColor = theme.colors.background separator.backgroundColor = theme.colors.border controller?.notifyGlobalStateChanged(animated: false) } private func gotoMessage() { if let message = message, let context = context, context.peerId == controller?.context.peerId { if let controller = context.bindings.rootNavigation().controller as? ChatController, controller.chatInteraction.peerId == message.id.peerId { controller.chatInteraction.focusMessageId(nil, message.id, .center(id: 0, innerId: nil, animated: true, focus: .init(focus: false), inset: 0)) } else { context.bindings.rootNavigation().push(ChatController(context: context, chatLocation: .peer(message.id.peerId), messageId: message.id)) } } } override func update(with contextObject: Any) { super.update(with: contextObject) let contextObject = contextObject as! ContextObject let controller = contextObject.controller self.bufferingStatusDisposable.set((controller.bufferingStatus |> deliverOnMainQueue).start(next: { [weak self] status in if let status = status { self?.updateStatus(status.0, status.1) } })) controller.baseRate = (controller is APChatVoiceController) ? FastSettings.playingRate : 1.0 self.playingSpeed.isHidden = !(controller is APChatVoiceController) controller.add(listener: self) self.ready.set(controller.ready.get()) repeatControl.isHidden = !controller.canMakeRepeat if let tableView = contextObject.tableView { if self.instantVideoPip == nil { self.instantVideoPip = InstantVideoPIP(controller, context: controller.context, window: controller.context.window) } self.instantVideoPip?.updateTableView(tableView, context: controller.context, controller: controller) addGlobalAudioToVisible(tableView: tableView) } if let supportTableView = contextObject.supportTableView { addGlobalAudioToVisible(tableView: supportTableView) } if let song = controller.currentSong { songDidChanged(song: song, for: controller, animated: true) } } private func addGlobalAudioToVisible(tableView: TableView) { if let controller = controller { tableView.enumerateViews(with: { (view) in var contentView: NSView? = (view as? ChatRowView)?.contentView.subviews.last ?? (view as? PeerMediaMusicRowView) if let view = ((view as? ChatMessageView)?.webpageContent as? WPMediaContentView)?.contentNode { contentView = view } if let view = view as? ChatGroupedView { for content in view.contents { controller.add(listener: content) } } else if let view = contentView as? ChatAudioContentView { controller.add(listener: view) } else if let view = contentView as? ChatVideoMessageContentView { controller.add(listener: view) } else if let view = contentView as? WPMediaContentView { if let contentNode = view.contentNode as? ChatAudioContentView { controller.add(listener: contentNode) } } else if let view = view as? PeerMediaMusicRowView { controller.add(listener: view) } else if let view = view as? PeerMediaVoiceRowView { controller.add(listener: view) } return true }) controller.notifyGlobalStateChanged(animated: false) } } deinit { bufferingStatusDisposable.dispose() } func attributedTitle(for song:APSongItem) -> (NSAttributedString, NSAttributedString?) { let trackName:NSAttributedString let artistName:NSAttributedString? if song.songName.isEmpty { trackName = .initialize(string: song.performerName, color: theme.colors.text, font: .normal(.text)) artistName = nil } else { trackName = .initialize(string: song.songName, color: theme.colors.text, font: .normal(.text)) if !song.performerName.isEmpty { artistName = .initialize(string: song.performerName, color: theme.colors.grayText, font: .normal(.text)) } else { artistName = nil } } return (trackName, artistName) } private func update(_ song: APSongItem, controller: APController, animated: Bool) { dismiss.set(image: theme.icons.audioplayer_dismiss, for: .Normal) switch song.entry { case let .song(message): self.message = message default: self.message = nil } next.userInteractionEnabled = controller.nextEnabled previous.userInteractionEnabled = controller.prevEnabled switch controller.nextEnabled { case true: next.set(image: theme.icons.audioplayer_next, for: .Normal) case false: next.set(image: theme.icons.audioplayer_locked_next, for: .Normal) } switch controller.prevEnabled { case true: previous.set(image: theme.icons.audioplayer_prev, for: .Normal) case false: previous.set(image: theme.icons.audioplayer_locked_prev, for: .Normal) } let attr = attributedTitle(for: song) if trackNameView.textLayout?.attributedString != attr.0 { let artist = TextViewLayout(attr.0, maximumNumberOfLines:1, alignment: .left) self.trackNameView.update(artist) } if let attr = attr.1 { let current: TextView if self.artistNameView == nil { current = TextView() current.userInteractionEnabled = false current.isEventLess = true self.artistNameView = current textViewContainer.addSubview(current) } else { current = self.artistNameView! } if current.textLayout?.attributedString != attr { let artist = TextViewLayout(attr, maximumNumberOfLines:1, alignment: .left) current.update(artist) } } else { if let view = self.artistNameView { self.artistNameView = nil if animated { view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in view?.removeFromSuperview() }) } else { view.removeFromSuperview() } } } switch FastSettings.playingRate { case 1.0: playingSpeed.set(image: theme.icons.audioplayer_speed_x1, for: .Normal) default: playingSpeed.set(image: theme.icons.audioplayer_speed_x2, for: .Normal) } switch FastSettings.volumeRate { case 0: volumeControl.set(image: theme.icons.audioplayer_volume_off, for: .Normal) default: volumeControl.set(image: theme.icons.audioplayer_volume, for: .Normal) } switch controller.state.repeatState { case .circle: repeatControl.set(image: theme.icons.audioplayer_repeat_circle, for: .Normal) case .one: repeatControl.set(image: theme.icons.audioplayer_repeat_one, for: .Normal) case .none: repeatControl.set(image: theme.icons.audioplayer_repeat_none, for: .Normal) } switch song.state { case .waiting: progressView.style = playProgressStyle case .stoped: progressView.set(progress: 0, animated: animated) case let .playing(_, _, progress), let .paused(_, _, progress): progressView.style = playProgressStyle progressView.set(progress: CGFloat(progress == .nan ? 0 : progress), animated: animated, duration: 0.2) case let .fetching(progress): progressView.style = fetchProgressStyle progressView.set(progress: CGFloat(progress), animated:animated) } switch controller.state.status { case .playing: play(animated: animated, sticker: LocalAnimatedSticker.playlist_play_pause) case .paused: play(animated: animated, sticker: LocalAnimatedSticker.playlist_pause_play) default: break } _ = previous.sizeToFit() _ = next.sizeToFit() _ = dismiss.sizeToFit() _ = repeatControl.sizeToFit() _ = playingSpeed.sizeToFit() _ = volumeControl.sizeToFit() needsLayout = true } func songDidChanged(song:APSongItem, for controller:APController, animated: Bool) { self.update(song, controller: controller, animated: animated) } func songDidChangedState(song: APSongItem, for controller: APController, animated: Bool) { self.update(song, controller: controller, animated: animated) } func songDidStartPlaying(song:APSongItem, for controller:APController, animated: Bool) { self.update(song, controller: controller, animated: animated) } func songDidStopPlaying(song:APSongItem, for controller:APController, animated: Bool) { self.update(song, controller: controller, animated: animated) } func playerDidChangedTimebase(song:APSongItem, for controller:APController, animated: Bool) { self.update(song, controller: controller, animated: animated) } func audioDidCompleteQueue(for controller:APController, animated: Bool) { stopAndHide(true) } override func layout() { super.layout() containerView.frame = bounds previous.centerY(x: 17) playPause.centerY(x: previous.frame.maxX + 5) next.centerY(x: playPause.frame.maxX + 5) dismiss.centerY(x: frame.width - 20 - dismiss.frame.width) repeatControl.centerY(x: dismiss.frame.minX - 10 - repeatControl.frame.width) progressView.frame = NSMakeRect(0, frame.height - 6, frame.width, 6) let textWidth = frame.width - (next.frame.maxX + dismiss.frame.width + repeatControl.frame.width + (playingSpeed.isHidden ? 0 : playingSpeed.frame.width + 10) + volumeControl.frame.width + 70) artistNameView?.resize(textWidth) trackNameView.resize(textWidth) let effectiveWidth = [artistNameView, trackNameView].compactMap { $0?.frame.width }.max(by: { $0 < $1 }) ?? 0 textViewContainer.setFrameSize(NSMakeSize(effectiveWidth, 40)) textViewContainer.centerY(x: next.frame.maxX + 20) playingSpeed.centerY(x: dismiss.frame.minX - playingSpeed.frame.width - 10) if let artistNameView = artistNameView { trackNameView.setFrameOrigin(NSMakePoint(0, 4)) artistNameView.setFrameOrigin(NSMakePoint(0, textViewContainer.frame.height - artistNameView.frame.height - 4)) } else { trackNameView.centerY(x: 0) } if repeatControl.isHidden { volumeControl.centerY(x: playingSpeed.frame.minX - 10 - volumeControl.frame.width) } else { volumeControl.centerY(x: repeatControl.frame.minX - 10 - volumeControl.frame.width) } separator.frame = NSMakeRect(0, frame.height - .borderSize, frame.width, .borderSize) } private func play(animated: Bool, sticker: LocalAnimatedSticker) { let data = sticker.data if let data = data { let current: Int32 let total: Int32 if playPauseView.animation?.key.key != LottieAnimationKey.bundle(sticker.rawValue) { current = playPauseView.currentFrame ?? 0 total = playPauseView.totalFrames ?? 0 } else { current = 0 total = playPauseView.currentFrame ?? 0 } let animation = LottieAnimation(compressed: data, key: .init(key: .bundle(sticker.rawValue), size: NSMakeSize(34, 34)), cachePurpose: .none, playPolicy: .toEnd(from: animated ? total - current : .max), colors: [.init(keyPath: "", color: theme.colors.accent)], runOnQueue: .mainQueue()) playPauseView.set(animation) } } func stopAndHide(_ animated:Bool) -> Void { controller?.remove(listener: self) controller?.stop() controller?.cleanup() instantVideoPip?.hide() instantVideoPip = nil self.hide(animated) } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0f117a95a8b690b9a7f62def0b82316a
37.074957
297
0.603937
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Foundation+Extras/DateComponents+Extras.swift
apache-2.0
1
// // DateComponents+Extras.swift // SwiftDate // // Created by Daniele Margutti on 07/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation // MARK: - Date Components Extensions public extension Calendar.Component { /// Return a description of the calendar component in seconds. /// Note: Values for `era`,`weekday`,`weekdayOrdinal`, `yearForWeekOfYear`, `calendar`, `timezone` are `nil`. /// For `weekOfYear` it return the same value of `weekOfMonth`. public var timeInterval: Double? { switch self { case .era: return nil case .year: return (Calendar.Component.day.timeInterval! * 365.0) case .month: return (Calendar.Component.minute.timeInterval! * 43800) case .day: return 86400 case .hour: return 3600 case .minute: return 60 case .second: return 1 case .quarter: return (Calendar.Component.day.timeInterval! * 91.25) case .weekOfMonth, .weekOfYear: return (Calendar.Component.day.timeInterval! * 7) case .nanosecond: return 1e-9 default: return nil } } /// Return the localized identifier of a calendar component /// /// - parameter unit: unit /// - parameter value: value /// /// - returns: return the plural or singular form of the time unit used to compose a valid identifier for search a localized /// string in resource bundle internal func localizedKey(forValue value: Int) -> String { let locKey = self.localizedKey let absValue = abs(value) switch absValue { case 0: // zero difference for this unit return "0\(locKey)" case 1: // one unit of difference return locKey default: // more than 1 unit of difference return "\(locKey)\(locKey)" } } internal var localizedKey: String { switch self { case .year: return "y" case .month: return "m" case .weekOfYear: return "w" case .day: return "d" case .hour: return "h" case .minute: return "M" case .second: return "s" default: return "" } } } public extension DateComponents { /// Shortcut for 'all calendar components'. static var allComponentsSet: Set<Calendar.Component> { return [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond, .calendar, .timeZone] } internal static let allComponents: [Calendar.Component] = [.nanosecond, .second, .minute, .hour, .day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal, .weekOfMonth] /// This function return the absolute amount of seconds described by the components of the receiver. /// Note: evaluated value maybe not strictly exact because it ignore the context (calendar/date) of /// the date components. In details: /// - The following keys are ignored: `era`,`weekday`,`weekdayOrdinal`, /// `weekOfYear`, `yearForWeekOfYear`, `calendar`, `timezone /// /// Some other values dependant from dates are fixed. This is a complete table: /// - `year` is 365.0 `days` /// - `month` is 30.4167 `days` (or 43800 minutes) /// - `quarter` is 91.25 `days` /// - `weekOfMonth` is 7 `days` /// - `day` is 86400 `seconds` /// - `hour` is 3600 `seconds` /// - `minute` is 60 `seconds` /// - `nanosecond` is 1e-9 `seconds` public var timeInterval: TimeInterval { var totalAmount: TimeInterval = 0 DateComponents.allComponents.forEach { if let multipler = $0.timeInterval, let value = self.value(for: $0), value != Int(NSDateComponentUndefined) { totalAmount += (TimeInterval(value) * multipler) } } return totalAmount } /// Create a new `DateComponents` instance with builder pattern. /// /// - Parameter builder: callback for builder /// - Returns: new instance public static func create(_ builder: ((inout DateComponents) -> Void)) -> DateComponents { var components = DateComponents() builder(&components) return components } /// Return the current date plus the receive's interval /// The default calendar used is the `SwiftDate.defaultRegion`'s calendar. var fromNow: Date { return SwiftDate.defaultRegion.calendar.date(byAdding: (self as DateComponents) as DateComponents, to: Date() as Date)! } /// Returns the current date minus the receiver's interval /// The default calendar used is the `SwiftDate.defaultRegion`'s calendar. var ago: Date { return SwiftDate.defaultRegion.calendar.date(byAdding: -self as DateComponents, to: Date())! } /// - returns: the date that will occur once the receiver's components pass after the provide date. public func from(_ date: DateRepresentable) -> Date? { return date.calendar.date(byAdding: self, to: date.date) } /// Return `true` if all interval components are zeroes public var isZero: Bool { for component in DateComponents.allComponents { if let value = self.value(for: component), value != 0 { return false } } return true } /// Transform a `DateComponents` instance to a dictionary where key is the `Calendar.Component` and value is the /// value associated. /// /// - returns: a new `[Calendar.Component : Int]` dict representing source `DateComponents` instance internal func toDict() -> [Calendar.Component: Int] { var list: [Calendar.Component: Int] = [:] DateComponents.allComponents.forEach { component in let value = self.value(for: component) if value != nil && value != Int(NSDateComponentUndefined) { list[component] = value! } } return list } /// Alter date components specified into passed dictionary. /// /// - Parameter components: components dictionary with their values. internal mutating func alterComponents(_ components: [Calendar.Component: Int?]) { components.forEach { if let v = $0.value { self.setValue(v, for: $0.key) } } } /// Adds two NSDateComponents and returns their combined individual components. public static func + (lhs: DateComponents, rhs: DateComponents) -> DateComponents { return combine(lhs, rhs: rhs, transform: +) } /// Subtracts two NSDateComponents and returns the relative difference between them. public static func - (lhs: DateComponents, rhs: DateComponents) -> DateComponents { return lhs + (-rhs) } /// Applies the `transform` to the two `T` provided, defaulting either of them if it's /// `nil` internal static func bimap<T>(_ a: T?, _ b: T?, default: T, _ transform: (T, T) -> T) -> T? { if a == nil && b == nil { return nil } return transform(a ?? `default`, b ?? `default`) } /// - returns: a new `NSDateComponents` that represents the negative of all values within the /// components that are not `NSDateComponentUndefined`. public static prefix func - (rhs: DateComponents) -> DateComponents { var components = DateComponents() components.era = rhs.era.map(-) components.year = rhs.year.map(-) components.month = rhs.month.map(-) components.day = rhs.day.map(-) components.hour = rhs.hour.map(-) components.minute = rhs.minute.map(-) components.second = rhs.second.map(-) components.nanosecond = rhs.nanosecond.map(-) components.weekday = rhs.weekday.map(-) components.weekdayOrdinal = rhs.weekdayOrdinal.map(-) components.quarter = rhs.quarter.map(-) components.weekOfMonth = rhs.weekOfMonth.map(-) components.weekOfYear = rhs.weekOfYear.map(-) components.yearForWeekOfYear = rhs.yearForWeekOfYear.map(-) return components } /// Combines two date components using the provided `transform` on all /// values within the components that are not `NSDateComponentUndefined`. private static func combine(_ lhs: DateComponents, rhs: DateComponents, transform: (Int, Int) -> Int) -> DateComponents { var components = DateComponents() components.era = bimap(lhs.era, rhs.era, default: 0, transform) components.year = bimap(lhs.year, rhs.year, default: 0, transform) components.month = bimap(lhs.month, rhs.month, default: 0, transform) components.day = bimap(lhs.day, rhs.day, default: 0, transform) components.hour = bimap(lhs.hour, rhs.hour, default: 0, transform) components.minute = bimap(lhs.minute, rhs.minute, default: 0, transform) components.second = bimap(lhs.second, rhs.second, default: 0, transform) components.nanosecond = bimap(lhs.nanosecond, rhs.nanosecond, default: 0, transform) components.weekday = bimap(lhs.weekday, rhs.weekday, default: 0, transform) components.weekdayOrdinal = bimap(lhs.weekdayOrdinal, rhs.weekdayOrdinal, default: 0, transform) components.quarter = bimap(lhs.quarter, rhs.quarter, default: 0, transform) components.weekOfMonth = bimap(lhs.weekOfMonth, rhs.weekOfMonth, default: 0, transform) components.weekOfYear = bimap(lhs.weekOfYear, rhs.weekOfYear, default: 0, transform) components.yearForWeekOfYear = bimap(lhs.yearForWeekOfYear, rhs.yearForWeekOfYear, default: 0, transform) return components } /// Subscription support for `DateComponents` instances. /// ie. `cmps[.day] = 5` /// /// Note: This does not take into account any built-in errors, `Int.max` returned instead of `nil`. /// /// - Parameter component: component to get public subscript(component: Calendar.Component) -> Int? { switch component { case .era: return era case .year: return year case .month: return month case .day: return day case .hour: return hour case .minute: return minute case .second: return second case .weekday: return weekday case .weekdayOrdinal: return weekdayOrdinal case .quarter: return quarter case .weekOfMonth: return weekOfMonth case .weekOfYear: return weekOfYear case .yearForWeekOfYear: return yearForWeekOfYear case .nanosecond: return nanosecond default: return nil // `calendar` and `timezone` are ignored in this context } } /// Express a `DateComponents` instance in another time unit you choose. /// /// - parameter component: time component /// - parameter calendar: context calendar to use /// /// - returns: the value of interval expressed in selected `Calendar.Component` public func `in`(_ component: Calendar.Component, of calendar: CalendarConvertible? = nil) -> Int? { let cal = (calendar?.toCalendar() ?? SwiftDate.defaultRegion.calendar) let dateFrom = Date() let dateTo = (dateFrom + self) let components: Set<Calendar.Component> = [component] let value = cal.dateComponents(components, from: dateFrom, to: dateTo).value(for: component) return value } /// Express a `DateComponents` instance in a set of time units you choose. /// /// - Parameters: /// - component: time component /// - calendar: context calendar to use /// - Returns: a dictionary of extract values. public func `in`(_ components: Set<Calendar.Component>, of calendar: CalendarConvertible? = nil) -> [Calendar.Component : Int] { let cal = (calendar?.toCalendar() ?? SwiftDate.defaultRegion.calendar) let dateFrom = Date() let dateTo = (dateFrom + self) let extractedCmps = cal.dateComponents(components, from: dateFrom, to: dateTo) return extractedCmps.toDict() } }
14ffd42b162059ec6f16d2579f613f1f
37.77972
129
0.698134
false
false
false
false
Tarovk/Mundus_Client
refs/heads/master
Pods/SKPhotoBrowser/SKPhotoBrowser/SKPagingScrollView.swift
apache-2.0
4
// // SKPagingScrollView.swift // SKPhotoBrowser // // Created by 鈴木 啓司 on 2016/08/18. // Copyright © 2016年 suzuki_keishi. All rights reserved. // import Foundation class SKPagingScrollView: UIScrollView { let pageIndexTagOffset: Int = 1000 let sideMargin: CGFloat = 10 fileprivate var visiblePages = [SKZoomingScrollView]() fileprivate var recycledPages = [SKZoomingScrollView]() fileprivate weak var browser: SKPhotoBrowser? var numberOfPhotos: Int { return browser?.photos.count ?? 0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) isPagingEnabled = true showsHorizontalScrollIndicator = true showsVerticalScrollIndicator = true } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) self.browser = browser updateFrame(bounds, currentPageIndex: browser.currentPageIndex) } func reload() { visiblePages.forEach({$0.removeFromSuperview()}) visiblePages.removeAll() recycledPages.removeAll() } func loadAdjacentPhotosIfNecessary(_ photo: SKPhotoProtocol, currentPageIndex: Int) { guard let browser = browser, let page = pageDisplayingAtPhoto(photo) else { return } let pageIndex = (page.tag - pageIndexTagOffset) if currentPageIndex == pageIndex { // Previous if pageIndex > 0 { let previousPhoto = browser.photos[pageIndex - 1] if previousPhoto.underlyingImage == nil { previousPhoto.loadUnderlyingImageAndNotify() } } // Next if pageIndex < numberOfPhotos - 1 { let nextPhoto = browser.photos[pageIndex + 1] if nextPhoto.underlyingImage == nil { nextPhoto.loadUnderlyingImageAndNotify() } } } } func deleteImage() { // index equals 0 because when we slide between photos delete button is hidden and user cannot to touch on delete button. And visible pages number equals 0 if numberOfPhotos > 0 { visiblePages[0].captionView?.removeFromSuperview() } } func animate(_ frame: CGRect) { setContentOffset(CGPoint(x: frame.origin.x - sideMargin, y: 0), animated: true) } func updateFrame(_ bounds: CGRect, currentPageIndex: Int) { var frame = bounds frame.origin.x -= sideMargin frame.size.width += (2 * sideMargin) self.frame = frame if visiblePages.count > 0 { for page in visiblePages { let pageIndex = page.tag - pageIndexTagOffset page.frame = frameForPageAtIndex(pageIndex) page.setMaxMinZoomScalesForCurrentBounds() if page.captionView != nil { page.captionView.frame = frameForCaptionView(page.captionView, index: pageIndex) } } } updateContentSize() updateContentOffset(currentPageIndex) } func updateContentSize() { contentSize = CGSize(width: bounds.size.width * CGFloat(numberOfPhotos), height: bounds.size.height) } func updateContentOffset(_ index: Int) { let pageWidth = bounds.size.width let newOffset = CGFloat(index) * pageWidth contentOffset = CGPoint(x: newOffset, y: 0) } func tilePages() { guard let browser = browser else { return } let firstIndex: Int = getFirstIndex() let lastIndex: Int = getLastIndex() visiblePages .filter({ $0.tag - pageIndexTagOffset < firstIndex || $0.tag - pageIndexTagOffset > lastIndex }) .forEach { page in recycledPages.append(page) page.prepareForReuse() page.removeFromSuperview() } let visibleSet: Set<SKZoomingScrollView> = Set(visiblePages) let visibleSetWithoutRecycled: Set<SKZoomingScrollView> = visibleSet.subtracting(recycledPages) visiblePages = Array(visibleSetWithoutRecycled) while recycledPages.count > 2 { recycledPages.removeFirst() } for index: Int in firstIndex...lastIndex { if visiblePages.filter({ $0.tag - pageIndexTagOffset == index }).count > 0 { continue } let page: SKZoomingScrollView = SKZoomingScrollView(frame: frame, browser: browser) page.frame = frameForPageAtIndex(index) page.tag = index + pageIndexTagOffset page.photo = browser.photos[index] visiblePages.append(page) addSubview(page) // if exists caption, insert if let captionView: SKCaptionView = createCaptionView(index) { captionView.frame = frameForCaptionView(captionView, index: index) captionView.alpha = browser.areControlsHidden() ? 0 : 1 addSubview(captionView) // ref val for control page.captionView = captionView } } } func frameForCaptionView(_ captionView: SKCaptionView, index: Int) -> CGRect { let pageFrame = frameForPageAtIndex(index) let captionSize = captionView.sizeThatFits(CGSize(width: pageFrame.size.width, height: 0)) let navHeight = browser?.navigationController?.navigationBar.frame.size.height ?? 44 return CGRect(x: pageFrame.origin.x, y: pageFrame.size.height - captionSize.height - navHeight, width: pageFrame.size.width, height: captionSize.height) } func pageDisplayedAtIndex(_ index: Int) -> SKZoomingScrollView? { for page in visiblePages { if page.tag - pageIndexTagOffset == index { return page } } return nil } func pageDisplayingAtPhoto(_ photo: SKPhotoProtocol) -> SKZoomingScrollView? { for page in visiblePages { if page.photo === photo { return page } } return nil } func getCaptionViews() -> Set<SKCaptionView> { var captionViews = Set<SKCaptionView>() visiblePages .filter({ $0.captionView != nil }) .forEach { captionViews.insert($0.captionView) } return captionViews } } private extension SKPagingScrollView { func frameForPageAtIndex(_ index: Int) -> CGRect { var pageFrame = bounds pageFrame.size.width -= (2 * sideMargin) pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + sideMargin return pageFrame } func createCaptionView(_ index: Int) -> SKCaptionView? { guard let photo = browser?.photoAtIndex(index), photo.caption != nil else { return nil } return SKCaptionView(photo: photo) } func getFirstIndex() -> Int { let firstIndex = Int(floor((bounds.minX + sideMargin * 2) / bounds.width)) if firstIndex < 0 { return 0 } if firstIndex > numberOfPhotos - 1 { return numberOfPhotos - 1 } return firstIndex } func getLastIndex() -> Int { let lastIndex = Int(floor((bounds.maxX - sideMargin * 2 - 1) / bounds.width)) if lastIndex < 0 { return 0 } if lastIndex > numberOfPhotos - 1 { return numberOfPhotos - 1 } return lastIndex } }
db6a2770c610c0a442de0820d7737a16
32.72103
163
0.581774
false
false
false
false