repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kingcos/Swift-3-Design-Patterns
07-Prototype_Pattern.playground/Contents.swift
1
1763
//: Playground - noun: a place where people can play // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns import UIKit // 工作经历 class WorkExperience { var workDate = "" var company = "" init() {} init(_ workDate: String, _ company: String) { self.workDate = workDate self.company = company } // 克隆 func clone() -> WorkExperience { return WorkExperience(workDate, company) } } // 简历 class Resume { private var name = "" private var sex = "" private var age = "" var work: WorkExperience init(_ name: String) { self.name = name self.work = WorkExperience() } init(_ work: WorkExperience) { self.work = work.clone() } func setPersonalInfo(_ sex: String, _ age: String) { self.sex = sex self.age = age } func setWorkExperience(_ workDate: String, _ company: String) { work.workDate = workDate work.company = company } func display() { print("个人信息:\(name) \(sex) \(age)") print("工作经历:\(work.workDate) \(work.company)") } // 克隆 func clone() -> Resume { let resume = Resume(work) resume.name = name resume.sex = sex resume.age = age return resume } } let resumeA = Resume("Kingcos") resumeA.setPersonalInfo("Boy", "21") resumeA.setWorkExperience("2016.8", "School") let resumeB = resumeA.clone() resumeB.setWorkExperience("2016.9-2016.12", "School") let resumeC = resumeA.clone() resumeC.setWorkExperience("2014-2018", "University") // 深拷贝 resumeA.display() resumeB.display() resumeC.display()
apache-2.0
2135e032b5d3fb5d64eaad0833d80715
20.734177
90
0.585323
3.637712
false
false
false
false
airbnb/lottie-ios
Sources/Public/macOS/FilepathImageProvider.macOS.swift
2
1814
// // FilepathImageProvider.swift // lottie-swift // // Created by Brandon Withrow on 2/1/19. // #if os(macOS) import AppKit /// An `AnimationImageProvider` that provides images by name from a specific filepath. public class FilepathImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// public init(filepath: String) { self.filepath = URL(fileURLWithPath: filepath) } public init(filepath: URL) { self.filepath = filepath } // MARK: Public public func imageForAsset(asset: ImageAsset) -> CGImage? { if asset.name.hasPrefix("data:"), let url = URL(string: asset.name), let data = try? Data(contentsOf: url), let image = NSImage(data: data) { return image.lottie_CGImage } let directPath = filepath.appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: directPath) { return NSImage(contentsOfFile: directPath)?.lottie_CGImage } let pathWithDirectory = filepath.appendingPathComponent(asset.directory).appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: pathWithDirectory) { return NSImage(contentsOfFile: pathWithDirectory)?.lottie_CGImage } LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } // MARK: Internal let filepath: URL } extension NSImage { @nonobjc var lottie_CGImage: CGImage? { guard let imageData = tiffRepresentation else { return nil } guard let sourceData = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil } return CGImageSourceCreateImageAtIndex(sourceData, 0, nil) } } #endif
apache-2.0
26045ee893383d5e9dc3d8aed0d2d585
26.074627
116
0.708379
4.35012
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Widgets/SnackBar.swift
1
9188
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import Shared class SnackBarUX { static var MaxWidth: CGFloat = 400 static let BorderWidth: CGFloat = 0.5 } /** * A specialized version of UIButton for use in SnackBars. These are displayed evenly * spaced in the bottom of the bar. The main convenience of these is that you can pass * in a callback in the constructor (although these also style themselves appropriately). */ typealias SnackBarCallback = (_ bar: SnackBar) -> Void class SnackButton: UIButton { let callback: SnackBarCallback? fileprivate var bar: SnackBar! override open var isHighlighted: Bool { didSet { self.backgroundColor = isHighlighted ? UIColor.theme.snackbar.highlight : .clear } } init(title: String, accessibilityIdentifier: String, bold: Bool = false, callback: @escaping SnackBarCallback) { self.callback = callback super.init(frame: .zero) if bold { titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultStandardFontBold } else { titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultStandardFont } titleLabel?.adjustsFontForContentSizeCategory = false setTitle(title, for: .normal) setTitleColor(UIColor.theme.snackbar.highlightText, for: .highlighted) setTitleColor(UIColor.theme.snackbar.title, for: .normal) addTarget(self, action: #selector(onClick), for: .touchUpInside) self.accessibilityIdentifier = accessibilityIdentifier } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func onClick() { callback?(bar) } func drawSeparator() { let separator = UIView() separator.backgroundColor = UIColor.theme.snackbar.border self.addSubview(separator) separator.snp.makeConstraints { make in make.leading.equalTo(self) make.width.equalTo(SnackBarUX.BorderWidth) make.top.bottom.equalTo(self) } } } class SnackBar: UIView { let snackbarClassIdentifier: String let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit // These are required to make sure that the image is _never_ smaller or larger than its actual size imageView.setContentHuggingPriority(.required, for: .horizontal) imageView.setContentHuggingPriority(.required, for: .vertical) imageView.setContentCompressionResistancePriority(.required, for: .horizontal) imageView.setContentCompressionResistancePriority(.required, for: .vertical) return imageView }() private lazy var textLabel: UILabel = { let label = UILabel() label.font = DynamicFontHelper.defaultHelper.DefaultStandardFont label.lineBreakMode = .byWordWrapping label.setContentCompressionResistancePriority(.required, for: .horizontal) label.numberOfLines = 0 label.textColor = UIColor.Photon.Grey90 // If making themeable, change to UIColor.theme.tableView.rowText label.backgroundColor = UIColor.clear return label }() private lazy var buttonsView: UIStackView = { let stack = UIStackView() stack.distribution = .fillEqually return stack }() private lazy var titleView: UIStackView = { let stack = UIStackView() stack.spacing = UIConstants.DefaultPadding stack.distribution = .fill stack.axis = .horizontal stack.alignment = .center return stack }() // The Constraint for the bottom of this snackbar. We use this to transition it var bottom: Constraint? init(text: String, img: UIImage?, snackbarClassIdentifier: String? = nil) { self.snackbarClassIdentifier = snackbarClassIdentifier ?? text super.init(frame: .zero) imageView.image = img ?? UIImage(named: "defaultFavicon") textLabel.text = text setup() } fileprivate func setup() { addSubview(backgroundView) titleView.addArrangedSubview(imageView) titleView.addArrangedSubview(textLabel) let separator = UIView() separator.backgroundColor = UIColor.theme.snackbar.border addSubview(titleView) addSubview(separator) addSubview(buttonsView) separator.snp.makeConstraints { make in make.leading.trailing.equalTo(self) make.height.equalTo(SnackBarUX.BorderWidth) make.top.equalTo(buttonsView.snp.top).offset(-1) } backgroundView.snp.makeConstraints { make in make.bottom.left.right.equalTo(self) make.top.equalTo(self) } titleView.snp.makeConstraints { make in make.top.equalTo(self).offset(UIConstants.DefaultPadding) make.height.greaterThanOrEqualTo(UIConstants.SnackbarButtonHeight - 2 * UIConstants.DefaultPadding) make.centerX.equalTo(self).priority(500) make.width.lessThanOrEqualTo(self).inset(UIConstants.DefaultPadding * 2).priority(1000) } backgroundColor = UIColor.clear self.clipsToBounds = true //overridden by masksToBounds = false self.layer.borderWidth = SnackBarUX.BorderWidth self.layer.borderColor = UIColor.theme.snackbar.border.cgColor self.layer.cornerRadius = 8 self.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** * Called to check if the snackbar should be removed or not. By default, Snackbars persist forever. * Override this class or use a class like CountdownSnackbar if you want things expire * - returns: true if the snackbar should be kept alive */ func shouldPersist(_ tab: Tab) -> Bool { return true } override func updateConstraints() { super.updateConstraints() buttonsView.snp.remakeConstraints { make in make.top.equalTo(titleView.snp.bottom).offset(UIConstants.DefaultPadding) make.bottom.equalTo(self.snp.bottom) make.leading.trailing.equalTo(self) if self.buttonsView.subviews.count > 0 { make.height.equalTo(UIConstants.SnackbarButtonHeight) } else { make.height.equalTo(0) } } } var showing: Bool { return alpha != 0 && self.superview != nil } func show() { alpha = 1 bottom?.update(offset: 0) } func addButton(_ snackButton: SnackButton) { snackButton.bar = self buttonsView.addArrangedSubview(snackButton) // Only show the separator on the left of the button if it is not the first view if buttonsView.arrangedSubviews.count != 1 { snackButton.drawSeparator() } } } /** * A special version of a snackbar that persists for at least a timeout. After that * it will dismiss itself on the next page load where this tab isn't showing. As long as * you stay on the current tab though, it will persist until you interact with it. */ class TimerSnackBar: SnackBar { fileprivate var timer: Timer? fileprivate var timeout: TimeInterval init(timeout: TimeInterval = 10, text: String, img: UIImage?) { self.timeout = timeout super.init(text: text, img: img) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static func showAppStoreConfirmationBar(forTab tab: Tab, appStoreURL: URL) { let bar = TimerSnackBar(text: Strings.ExternalLinkAppStoreConfirmationTitle, img: UIImage(named: "defaultFavicon")) let openAppStore = SnackButton(title: Strings.AppStoreString, accessibilityIdentifier: "ConfirmOpenInAppStore", bold: true) { bar in tab.removeSnackbar(bar) UIApplication.shared.open(appStoreURL, options: [:]) } let cancelButton = SnackButton(title: Strings.NotNowString, accessibilityIdentifier: "CancelOpenInAppStore", bold: false) { bar in tab.removeSnackbar(bar) } bar.addButton(cancelButton) bar.addButton(openAppStore) tab.addSnackbar(bar) } override func show() { self.timer = Timer(timeInterval: timeout, target: self, selector: #selector(timerDone), userInfo: nil, repeats: false) RunLoop.current.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode) super.show() } @objc func timerDone() { self.timer = nil } override func shouldPersist(_ tab: Tab) -> Bool { if !showing { return timer != nil } return super.shouldPersist(tab) } }
mpl-2.0
56de019e5eeca724f5510ab1894ae601
35.173228
140
0.66576
4.892439
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/MusicItemView.swift
1
1966
// // MusicCollectionCell.swift // MDTableExample // // Created by Leo on 2017/7/11. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit enum MusicCollectionCellStyle { case normal case slogen } class MusicItemView: AvatarItemView { var titleLabel: UILabel! var subTitleLabel: UILabel! var coverImageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit(){ coverImageView = UIImageView(frame: CGRect.zero).added(to: self) titleLabel = UILabel.title().added(to: self) subTitleLabel = UILabel.subTitle().added(to: self) } override func layoutSubviews() { super.layoutSubviews() avatarImageView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width) coverImageView.frame = avatarImageView.frame titleLabel.frame = CGRect(x: 4.0, y: avatarImageView.maxY + 4.0, width: self.frame.width - 8.0, height: 15.0) subTitleLabel.frame = CGRect(x: 4.0, y: titleLabel.maxY + 2.0, width: self.frame.width - 8.0, height: 15.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func config(_ music:NMLatestMusic, style:MusicCollectionCellStyle){ switch style { case .normal: coverImageView.isHidden = true default: coverImageView.image = UIImage(named: "cm4_disc_cover_new") coverImageView.isHidden = false } avatarImageView.asyncSetImage(music.avatar) titleLabel.text = music.title subTitleLabel.text = music.subTitle } } //新歌推荐 class NMLatestMusic { var avatar:UIImage? var title:String var subTitle:String init(avatar:UIImage?, title:String,subTitle:String){ self.avatar = avatar self.title = title self.subTitle = subTitle } }
mit
943cb74604ec7007b70b5e0621fbf237
29.546875
117
0.645524
4.056017
false
false
false
false
jum/ActionSheetPicker
Example Projects/Swift-Example/Swift-Example/ViewControllers/SWTableViewController.swift
1
8072
// // SWTableViewController.swift // Swift-Example // // Created by Petr Korolev on 19/09/14. // Copyright (c) 2014 Petr Korolev. All rights reserved. // import UIKit import CoreActionSheetPicker class SWTableViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var UIDatePickerModeTime: UIButton! @IBAction func TimePickerClicked(_ sender: UIButton) { let datePicker = ActionSheetDatePicker(title: "Time:", datePickerMode: UIDatePickerMode.time, selectedDate: Date(), target: self, action: #selector(SWTableViewController.datePicked(_:)), origin: sender.superview!.superview) datePicker?.minuteInterval = 20 datePicker?.show() } @IBOutlet var textField: UITextField! @IBOutlet var localePicker: UIButton! @IBAction func localePickerClicked(_ sender: UIButton) { ActionSheetLocalePicker.show(withTitle: "Locale picker", initialSelection: nil, doneBlock: { picker, index in print("index = \(index)") print("picker = \(picker)") return }, cancel: { ActionStringCancelBlock in return }, origin: sender.superview!.superview) } @IBAction func DatePickerClicked(_ sender: UIButton) { let datePicker = ActionSheetDatePicker(title: "Date:", datePickerMode: UIDatePickerMode.date, selectedDate: Date(), doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") return }, cancel: { ActionStringCancelBlock in return }, origin: sender.superview!.superview) let secondsInWeek: TimeInterval = 7 * 24 * 60 * 60; datePicker?.minimumDate = Date(timeInterval: -secondsInWeek, since: Date()) datePicker?.maximumDate = Date(timeInterval: secondsInWeek, since: Date()) datePicker?.show() } @IBAction func distancePickerClicked(_ sender: UIButton) { let distancePicker = ActionSheetDistancePicker(title: "Select distance", bigUnitString: "m", bigUnitMax: 2, selectedBigUnit: 1, smallUnitString: "cm", smallUnitMax: 99, selectedSmallUnit: 60, target: self, action: #selector(SWTableViewController.measurementWasSelected(_:smallUnit:element:)), origin: sender.superview!.superview) distancePicker?.show() } func measurementWasSelected(_ bigUnit: NSNumber, smallUnit: NSNumber, element: AnyObject) { print("\(element)") print("\(smallUnit)") print("\(bigUnit)") print("measurementWasSelected") } @IBAction func DateAndTimeClicked(_ sender: UIButton) { let datePicker = ActionSheetDatePicker(title: "DateAndTime:", datePickerMode: UIDatePickerMode.dateAndTime, selectedDate: Date(), doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") return }, cancel: { ActionStringCancelBlock in return }, origin: sender.superview!.superview) let secondsInWeek: TimeInterval = 7 * 24 * 60 * 60; datePicker?.minimumDate = Date(timeInterval: -secondsInWeek, since: Date()) datePicker?.maximumDate = Date(timeInterval: secondsInWeek, since: Date()) datePicker?.minuteInterval = 20 datePicker?.show() } @IBAction func CountdownTimerClicked(_ sender: UIButton) { let datePicker = ActionSheetDatePicker(title: "CountDownTimer:", datePickerMode: UIDatePickerMode.countDownTimer, selectedDate: Date(), doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") return }, cancel: { ActionStringCancelBlock in return }, origin: sender.superview!.superview) datePicker?.countDownDuration = 60 * 7 datePicker?.show() } @IBAction func navigationItemPicker(_ sender: UIBarButtonItem) { ActionSheetStringPicker.show(withTitle: "Nav Bar From Picker", rows: ["One", "Two", "A lot"], initialSelection: 1, doneBlock: { picker, value, index in print("value = \(value)") print("index = \(index)") print("picker = \(picker)") return }, cancel: { ActionStringCancelBlock in return }, origin: sender) } @IBAction func multipleStringPickerClicked(_ sender: UIButton) { let acp = ActionSheetMultipleStringPicker(title: "Multiple String Picker", rows: [ ["One", "Two", "A lot"], ["Many", "Many more", "Infinite"] ], initialSelection: [2, 2], doneBlock: { picker, values, indexes in print("values = \(values)") print("indexes = \(indexes)") print("picker = \(picker)") return }, cancel: { ActionMultipleStringCancelBlock in return }, origin: sender) acp?.pickerTextAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 8.0)] acp?.setTextColor(UIColor.red) acp?.pickerBackgroundColor = UIColor.black acp?.toolbarBackgroundColor = UIColor.yellow acp?.toolbarButtonsColor = UIColor.white acp?.show() } func datePicked(_ obj: Date) { UIDatePickerModeTime.setTitle(obj.description, for: UIControlState()) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return true } @IBAction func hideKeyboard(_ sender: AnyObject) { self.textField.becomeFirstResponder() } // MARK: - Table view data source /* override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
aba966143d3a9b20fe6331550d7677c4
36.027523
337
0.647919
5.121827
false
false
false
false
ludovic-coder/Parsimmon
Parsimmon/Seed.swift
1
1740
// Seed.swift // // Copyright (c) 2015 Ayaka Nonaka // // 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 struct Seed { typealias Language = String fileprivate let language: Language = "en" let linguisticTaggerOptions: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .omitOther] let orthography = NSOrthography(dominantScript: "Latn", languageMap: ["Latn" : ["en"]]) func linguisticTaggerWithOptions(_ options: NSLinguisticTagger.Options) -> NSLinguisticTagger { let tagSchemes = NSLinguisticTagger.availableTagSchemes(forLanguage: self.language) return NSLinguisticTagger(tagSchemes: tagSchemes, options: Int(options.rawValue)) } }
mit
ae0483b3953abcf8bf477ef3d245a7a4
47.333333
109
0.759195
4.652406
false
false
false
false
vapor/socks
Sources/TCP/Socket/TCPServer.swift
2
6401
import Async import Bits import Debugging import Dispatch import COperatingSystem /// Accepts client connections to a socket. /// /// Uses Async.OutputStream API to deliver accepted clients /// with back pressure support. If overwhelmed, input streams /// can cause the TCP server to suspend accepting new connections. /// /// [Learn More →](https://docs.vapor.codes/3.0/sockets/tcp-server/) public struct TCPServer { /// A closure that can dictate if a client will be accepted /// /// `true` for accepted, `false` for not accepted public typealias WillAccept = (TCPClient) -> (Bool) /// Controls whether or not to accept a client /// /// Useful for security purposes public var willAccept: WillAccept? /// This server's TCP socket. public let socket: TCPSocket /// Creates a TCPServer from an existing TCPSocket. public init(socket: TCPSocket) throws { self.socket = socket } /// Starts listening for peers asynchronously public func start(hostname: String = "0.0.0.0", port: UInt16, backlog: Int32 = 128) throws { /// bind the socket and start listening try socket.bind(hostname: hostname, port: port) try socket.listen(backlog: backlog) } /// Accepts a client and outputs to the output stream /// important: the socket _must_ be ready to accept a client /// as indicated by a read source. public mutating func accept() throws -> TCPClient? { guard let accepted = try socket.accept() else { return nil } /// init a tcp client with the socket and assign it an event loop let client = try TCPClient(socket: accepted) /// check the will accept closure to approve this connection if let shouldAccept = willAccept, !shouldAccept(client) { client.close() return nil } /// output the client return client } /// Stops the server public func stop() { socket.close() } } extension TCPServer { /// Create a stream for this TCP server. /// - parameter on: the event loop to accept clients on /// - parameter assigning: the event loops to assign to incoming clients public func stream(on eventLoop: EventLoop) -> TCPClientStream { return .init(server: self, on: eventLoop) } } extension TCPSocket { /// bind - bind a name to a socket /// http://man7.org/linux/man-pages/man2/bind.2.html fileprivate func bind(hostname: String = "0.0.0.0", port: UInt16) throws { var hints = addrinfo() // Support both IPv4 and IPv6 hints.ai_family = AF_INET // Specify that this is a TCP Stream hints.ai_socktype = SOCK_STREAM hints.ai_protocol = IPPROTO_TCP // If the AI_PASSIVE flag is specified in hints.ai_flags, and node is // NULL, then the returned socket addresses will be suitable for // bind(2)ing a socket that will accept(2) connections. hints.ai_flags = AI_PASSIVE // Look ip the sockeaddr for the hostname var result: UnsafeMutablePointer<addrinfo>? var res = getaddrinfo(hostname, port.description, &hints, &result) guard res == 0 else { throw TCPError.gaierrno( res, identifier: "getAddressInfo", possibleCauses: [ "The address that binding was attempted on (\"\(hostname)\":\(port)) does not refer to your machine." ], suggestedFixes: [ "Bind to `0.0.0.0` or to your machine's IP address" ], source: .capture() ) } defer { freeaddrinfo(result) } guard let info = result else { throw TCPError(identifier: "unwrapAddress", reason: "Could not unwrap address info.", source: .capture()) } res = COperatingSystem.bind(descriptor, info.pointee.ai_addr, info.pointee.ai_addrlen) guard res == 0 else { throw TCPError.posix(errno, identifier: "bind", source: .capture()) } } /// listen - listen for connections on a socket /// http://man7.org/linux/man-pages/man2/listen.2.html fileprivate func listen(backlog: Int32 = 4096) throws { let res = COperatingSystem.listen(descriptor, backlog) guard res == 0 else { throw TCPError.posix(errno, identifier: "listen", source: .capture()) } } /// accept, accept4 - accept a connection on a socket /// http://man7.org/linux/man-pages/man2/accept.2.html fileprivate func accept() throws -> TCPSocket? { let (clientfd, address) = try TCPAddress.withSockaddrPointer { address -> Int32? in var size = socklen_t(MemoryLayout<sockaddr>.size) let descriptor = COperatingSystem.accept(self.descriptor, address, &size) guard descriptor > 0 else { switch errno { case EAGAIN: return nil // FIXME: enum return default: throw TCPError.posix(errno, identifier: "accept", source: .capture()) } } return descriptor } guard let c = clientfd else { return nil } let socket = TCPSocket( established: c, isNonBlocking: isNonBlocking, shouldReuseAddress: shouldReuseAddress, address: address ) return socket } } extension TCPError { static func gaierrno( _ gaires: Int32, identifier: String, possibleCauses: [String] = [], suggestedFixes: [String] = [], source: SourceLocation ) -> TCPError { guard gaires != EAI_SYSTEM else { return .posix( errno, identifier: identifier, possibleCauses: possibleCauses, suggestedFixes: suggestedFixes, source: source ) } let message = COperatingSystem.gai_strerror(gaires) let string = String(cString: message!, encoding: .utf8) ?? "unknown" return TCPError( identifier: identifier, reason: string, possibleCauses: possibleCauses, suggestedFixes: suggestedFixes, source: source ) } }
mit
e695d61f984cbbd4308083046f68fe82
31.482234
121
0.594624
4.528662
false
false
false
false
Ranxan/NetworkService
NetworkService/NetworkServiceTests/Mocks/FileServiceTestMock.swift
1
9998
// // FileServiceTest.swift // SMS-iOS Template // // Created by Ranjan Adhikari on 5/24/17. // Copyright © 2017 SMS. All rights reserved. // import Foundation import ObjectMapper import Alamofire /** Service Test Model.. */ class FileServiceTestModel : BaseModel { var id : Int? var userId : Int? var title : String? var body : String? override init() { super.init() } required init?(map: Map) { super.init(map: map) } override func mapping(map: Map) { id <- map["id"] userId <- map["userId"] title <- map["title"] body <- map["body"] } } /** File upload Call configuration.. */ struct FileUploadConfiguration : UploadServiceDelegate { static var path = "/upload" static var method = NetworkServiceHTTPMethod.post typealias V = FileServiceTestModel /*Response Model Type..*/ static var parameters : [String:Any]? = [:] } /** API Call configuration.. */ class FileServiceTestMock { static var MESSAGE_SUCCESS : String = "Success." static var MESSAGE_FAILURE : String = "Failure." var serviceTestResponseState : Bool? = false var serviceTestMessage : String? func uploadTextFile(withKey : String, identifier : String?, callback : @escaping (Bool) -> Void) { let FILE = "XFile.txt" //this is the file. we will write to and read from it let text = "Hi, welcome to another video of Cold Fusion. In this video .." //just a text guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { /**/ callback(false) return } let path = dir.appendingPathComponent(FILE) do { try text.write(to: path, atomically: false, encoding: String.Encoding.utf8) /***/ FileUploadConfiguration.parameters?["file1"] = path.absoluteString FileUploadConfiguration.parameters?["file2"] = path.absoluteString UploadService<FileUploadConfiguration>(uploadIdentifier : identifier ){ p in print(p.fractionCompleted) }.upload(withKey: withKey) { response, error in /***/ guard let responseData = response else { /*Get error message..*/ print(error as Any) self.serviceTestResponseState = false self.serviceTestMessage = error?.errorMessage.rawValue callback(false) return } if let data = responseData.data { /*Response data is available.*/ print(String(describing: data.body)) self.serviceTestResponseState = true self.serviceTestMessage = ServiceTestMock.MESSAGE_SUCCESS callback(true) } else { /*Response status is available, in case response data is not available*/ print(responseData.status?.message ?? "No status Message.") self.serviceTestResponseState = false self.serviceTestMessage = ServiceTestMock.MESSAGE_FAILURE callback(false) } } } catch { print("Error writing to a file.") self.serviceTestResponseState = false self.serviceTestMessage = ServiceTestMock.MESSAGE_FAILURE callback(false) } } /***/ func uploadImageFile(callback : @escaping (Bool) -> Void) { let image = UIImage(named: "icon_phone.png") guard let data = UIImagePNGRepresentation(image!) else { callback(false) return } let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] let fileName = documentsDirectory.appendingPathComponent("icon_phone.png") try? data.write(to: fileName) FileUploadConfiguration.path = fileName.absoluteString UploadService<FileUploadConfiguration>(uploadIdentifier : nil, uploadProgressCallback: nil) .upload(withKey: "ImageFile") { response, error in /*Hanlding response in the closure callback..*/ guard let responseData = response else { print(error as Any) callback(false) return } guard let data = responseData.data else { print(responseData.status?.message ?? "Error!") callback(false) return } print(data) callback(true) } } /***/ func uploadVideoFile(withKey : String, identifier : String?, callback : @escaping (Bool) -> Void) { guard var path = Bundle.main.path(forResource: "song", ofType: "mp4") else { print("File not found.") callback(false) return } let url = URL(fileURLWithPath: path) path = url.absoluteString print(path) FileUploadConfiguration.parameters?["file1"] = path UploadService<FileUploadConfiguration>(uploadIdentifier : nil, uploadProgressCallback: nil) .upload(withKey: withKey) { response, error in /*Hanlding response in the closure callback..*/ guard let responseData = response else { print(error as Any) callback(false) return } guard let data = responseData.data else { print(responseData.status?.message ?? "Error!") callback(false) return } print(data) callback(true) } } /***/ func downloadTextFile(fileName : String, path : String, downloadIdentifier : String?, callback : @escaping (Bool) -> Void) { DownloadService(serviceConfiguration: nil, downloadIdentifier : downloadIdentifier) { progress in print(progress.fractionCompleted) }.download(downloadPath: path, fileName: fileName) { response, error in /*Hanlding response in the closure callback..*/ guard let responseData = response else { print(error as Any) callback(false) return } do { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendingPathComponent(fileName) let filePath = try String(describing: fileURL) /*Reading file contents..*/ let file : FileHandle? = try FileHandle(forReadingFrom: fileURL) if file != nil { // Read all the data let data = file?.readDataToEndOfFile() // Close the file file?.closeFile() // Convert our data to string let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print(str) callback(true) } else { print("Ooops! Something went wrong!") callback(false) } } catch let error as NSError { print("Ooops! Something went wrong: \(error)") callback(false) } } } func downloadMediaFile(fileName : String, path : String, downloadIdentifier : String?, callback : @escaping (Bool) -> Void){ DownloadService(serviceConfiguration: nil, downloadIdentifier : downloadIdentifier) { progress in print(progress.fractionCompleted) }.download(downloadPath: path, fileName: fileName) { response, error in /*Hanlding response in the closure callback..*/ guard let responseData = response else { print(error as Any) callback(false) return } do { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendingPathComponent(fileName) let filePath = try String(describing: fileURL) /*Reading file contents..*/ let file : FileHandle? = try FileHandle(forReadingFrom: fileURL) if file != nil { callback(true) } else { print("Ooops! Something went wrong!") callback(false) } } catch let error as NSError { print("Ooops! Something went wrong: \(error)") callback(false) } } } }
mit
074f9bc93bf91a25d03e8e7702c322e1
35.753676
128
0.493848
5.894458
false
true
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/LiteralExpressionEndIdentationRule.swift
1
3528
import Foundation import SourceKittenFramework public struct LiteralExpressionEndIdentationRule: ASTRule, ConfigurationProviderRule, OptInRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "literal_expression_end_indentation", name: "Literal Expression End Indentation", description: "Array and dictionary literal end should have the same indentation as the line that started it.", kind: .style, nonTriggeringExamples: [ "[1, 2, 3]", "[1,\n" + " 2\n" + "]", "[\n" + " 1,\n" + " 2\n" + "]", "[\n" + " 1,\n" + " 2]\n", " let x = [\n" + " 1,\n" + " 2\n" + " ]", "[key: 2, key2: 3]", "[key: 1,\n" + " key2: 2\n" + "]", "[\n" + " key: 0,\n" + " key2: 20\n" + "]" ], triggeringExamples: [ "let x = [\n" + " 1,\n" + " 2\n" + " ↓]", " let x = [\n" + " 1,\n" + " 2\n" + "↓]", "let x = [\n" + " key: value\n" + " ↓]" ] ) private static let notWhitespace = regex("[^\\s]") public func validate(file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .dictionary || kind == .array else { return [] } let elements = dictionary.elements.filter { $0.kind == "source.lang.swift.structure.elem.expr" } let contents = file.contents.bridge() guard !elements.isEmpty, let offset = dictionary.offset, let length = dictionary.length, let (startLine, _) = contents.lineAndCharacter(forByteOffset: offset), let firstParamOffset = elements[0].offset, let (firstParamLine, _) = contents.lineAndCharacter(forByteOffset: firstParamOffset), startLine != firstParamLine, let lastParamOffset = elements.last?.offset, let (lastParamLine, _) = contents.lineAndCharacter(forByteOffset: lastParamOffset), case let endOffset = offset + length - 1, let (endLine, endPosition) = contents.lineAndCharacter(forByteOffset: endOffset), lastParamLine != endLine else { return [] } let range = file.lines[startLine - 1].range let regex = LiteralExpressionEndIdentationRule.notWhitespace let actual = endPosition - 1 guard let match = regex.firstMatch(in: file.contents, options: [], range: range)?.range, case let expected = match.location - range.location, expected != actual else { return [] } let reason = "\(LiteralExpressionEndIdentationRule.description.description) " + "Expected \(expected), got \(actual)." return [ StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: endOffset), reason: reason) ] } }
mit
45b7f808ace985364b461734065102da
34.938776
118
0.499432
4.689747
false
false
false
false
radazzouz/firefox-ios
Client/Frontend/Browser/TopTabsViewController.swift
1
21303
/* 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 WebKit struct TopTabsUX { static let TopTabsViewHeight: CGFloat = 40 static let TopTabsBackgroundNormalColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1) static let TopTabsBackgroundPrivateColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1) static let TopTabsBackgroundNormalColorInactive = UIColor(red: 178/255, green: 178/255, blue: 178/255, alpha: 1) static let TopTabsBackgroundPrivateColorInactive = UIColor(red: 53/255, green: 53/255, blue: 53/255, alpha: 1) static let PrivateModeToolbarTintColor = UIColor(red: 124 / 255, green: 124 / 255, blue: 124 / 255, alpha: 1) static let TopTabsBackgroundPadding: CGFloat = 35 static let TopTabsBackgroundShadowWidth: CGFloat = 35 static let TabWidth: CGFloat = 180 static let CollectionViewPadding: CGFloat = 15 static let FaderPading: CGFloat = 10 static let SeparatorWidth: CGFloat = 1 static let TabTitleWidth: CGFloat = 110 static let TabTitlePadding: CGFloat = 10 } protocol TopTabsDelegate: class { func topTabsDidPressTabs() func topTabsDidPressNewTab(_ isPrivate: Bool) func topTabsDidTogglePrivateMode() func topTabsDidChangeTab() } protocol TopTabCellDelegate: class { func tabCellDidClose(_ cell: TopTabCell) } class TopTabsViewController: UIViewController { let tabManager: TabManager weak var delegate: TopTabsDelegate? fileprivate var isPrivate = false let faviconNotification = NSNotification.Name(rawValue: FaviconManager.FaviconDidLoad) lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout()) collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.clipsToBounds = false collectionView.accessibilityIdentifier = "Top Tabs View" return collectionView }() fileprivate lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: UIControlEvents.touchUpInside) tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton" return tabsButton }() fileprivate lazy var newTab: UIButton = { let newTab = UIButton.newTabButton() newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: UIControlEvents.touchUpInside) return newTab }() lazy var privateModeButton: PrivateModeButton = { let privateModeButton = PrivateModeButton() privateModeButton.light = true privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: UIControlEvents.touchUpInside) return privateModeButton }() fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = { let delegate = TopTabsLayoutDelegate() delegate.tabSelectionDelegate = self return delegate }() fileprivate var tabsToDisplay: [Tab] { return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs } // Handle animations. fileprivate var tabStore: [Tab] = [] //the actual datastore fileprivate var pendingUpdatesToTabs: [Tab] = [] //the datastore we are transitioning to fileprivate var needReloads: [Tab?] = [] // Tabs that need to be reloaded fileprivate var isUpdating = false fileprivate var pendingReloadData = false fileprivate var oldTabs: [Tab]? // The last state of the tabs before an animation fileprivate weak var oldSelectedTab: Tab? // Used to select the right tab when transitioning between private/normal tabs init(tabManager: TabManager) { self.tabManager = tabManager super.init(nibName: nil, bundle: nil) collectionView.dataSource = self collectionView.delegate = tabLayoutDelegate NotificationCenter.default.addObserver(self, selector: #selector(TopTabsViewController.reloadFavicons(_:)), name: faviconNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: faviconNotification, object: nil) self.tabManager.removeDelegate(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.reloadData() } override func viewDidLoad() { super.viewDidLoad() tabManager.addDelegate(self) self.tabStore = self.tabsToDisplay let topTabFader = TopTabFader() view.addSubview(tabsButton) view.addSubview(newTab) view.addSubview(privateModeButton) view.addSubview(topTabFader) topTabFader.addSubview(collectionView) newTab.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(view) make.size.equalTo(UIConstants.ToolbarHeight) } tabsButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(newTab.snp.leading) make.size.equalTo(UIConstants.ToolbarHeight) } privateModeButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view) make.size.equalTo(UIConstants.ToolbarHeight) } topTabFader.snp.makeConstraints { make in make.top.bottom.equalTo(view) make.leading.equalTo(privateModeButton.snp.trailing).offset(-TopTabsUX.FaderPading) make.trailing.equalTo(tabsButton.snp.leading).offset(TopTabsUX.FaderPading) } collectionView.snp.makeConstraints { make in make.top.bottom.equalTo(view) make.leading.equalTo(privateModeButton.snp.trailing).offset(-TopTabsUX.CollectionViewPadding) make.trailing.equalTo(tabsButton.snp.leading).offset(TopTabsUX.CollectionViewPadding) } view.backgroundColor = UIColor.black tabsButton.applyTheme(Theme.NormalMode) if let currentTab = tabManager.selectedTab { applyTheme(currentTab.isPrivate ? Theme.PrivateMode : Theme.NormalMode) } updateTabCount(tabStore.count) } func switchForegroundStatus(isInForeground reveal: Bool) { // Called when the app leaves the foreground to make sure no information is inadvertently revealed if let cells = self.collectionView.visibleCells as? [TopTabCell] { let alpha: CGFloat = reveal ? 1 : 0 for cell in cells { cell.titleText.alpha = alpha cell.favicon.alpha = alpha } } } func updateTabCount(_ count: Int, animated: Bool = true) { self.tabsButton.updateTabCount(count, animated: animated) } func tabsTrayTapped() { delegate?.topTabsDidPressTabs() } func newTabTapped() { if pendingReloadData { return } self.delegate?.topTabsDidPressNewTab(self.isPrivate) } func togglePrivateModeTapped() { if isUpdating || pendingReloadData { return } let isPrivate = self.isPrivate delegate?.topTabsDidTogglePrivateMode() self.pendingReloadData = true // Stops animations from happening let oldSelectedTab = self.oldSelectedTab self.oldSelectedTab = tabManager.selectedTab self.privateModeButton.setSelected(!isPrivate, animated: true) //if private tabs is empty and we are transitioning to it add a tab if tabManager.privateTabs.isEmpty && !isPrivate { tabManager.addTab(isPrivate: true) } //get the tabs from which we will select which one to nominate for tribute (selection) //the isPrivate boolean still hasnt been flipped. (It'll be flipped in the BVC didSelectedTabChange method) let tabs = !isPrivate ? tabManager.privateTabs : tabManager.normalTabs if let tab = oldSelectedTab, tabs.index(of: tab) != nil { tabManager.selectTab(tab) } else { tabManager.selectTab(tabs.last) } } func reloadFavicons(_ notification: Notification) { // Notifications might be called from a different thread. Make sure animations only happen on the main thread. DispatchQueue.main.async { if let tab = notification.object as? Tab, self.tabStore.index(of: tab) != nil { self.needReloads.append(tab) self.performTabUpdates() } } } func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) { assertIsMainThread("Only animate on the main thread") guard let currentTab = tabManager.selectedTab, let index = tabStore.index(of: currentTab), !collectionView.frame.isEmpty else { return } if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame { if centerCell { collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false) } else { // Padding is added to ensure the tab is completely visible (none of the tab is under the fader) let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0) collectionView.scrollRectToVisible(padFrame, animated: animated) } } } } extension TopTabsViewController: Themeable { func applyTheme(_ themeName: String) { tabsButton.applyTheme(themeName) isPrivate = (themeName == Theme.PrivateMode) privateModeButton.styleForMode(privateMode: isPrivate) newTab.tintColor = isPrivate ? UIConstants.PrivateModePurple : UIColor.white if let layout = collectionView.collectionViewLayout as? TopTabsViewLayout { if isPrivate { layout.themeColor = TopTabsUX.TopTabsBackgroundPrivateColorInactive } else { layout.themeColor = TopTabsUX.TopTabsBackgroundNormalColorInactive } } } } extension TopTabsViewController: TopTabCellDelegate { func tabCellDidClose(_ cell: TopTabCell) { // Trying to remove tabs while animating can lead to crashes as indexes change. If updates are happening don't allow tabs to be removed. guard let index = collectionView.indexPath(for: cell)?.item, !isUpdating else { return } let tab = tabStore[index] if tabsToDisplay.index(of: tab) != nil { tabManager.removeTab(tab) } } } extension TopTabsViewController: UICollectionViewDataSource { @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let index = indexPath.item let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TopTabCell.Identifier, for: indexPath) as! TopTabCell tabCell.delegate = self let tab = tabStore[index] tabCell.style = tab.isPrivate ? .dark : .light tabCell.titleText.text = tab.displayTitle if tab.displayTitle.isEmpty { if tab.webView?.url?.baseDomain?.contains("localhost") ?? true { tabCell.titleText.text = AppMenuConfiguration.NewTabTitleString } else { tabCell.titleText.text = tab.webView?.url?.absoluteDisplayString } tabCell.accessibilityLabel = tab.url?.aboutComponent ?? "" tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tabCell.titleText.text ?? "") } else { tabCell.accessibilityLabel = tab.displayTitle tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle) } tabCell.selectedTab = (tab == tabManager.selectedTab) if let favIcon = tab.displayFavicon, let url = URL(string: favIcon.url) { tabCell.favicon.sd_setImage(with: url) } else { var defaultFavicon = UIImage(named: "defaultFavicon") if tab.isPrivate { defaultFavicon = defaultFavicon?.withRenderingMode(.alwaysTemplate) tabCell.favicon.image = defaultFavicon tabCell.favicon.tintColor = UIColor.white } else { tabCell.favicon.image = defaultFavicon } } return tabCell } @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabStore.count } } extension TopTabsViewController: TabSelectionDelegate { func didSelectTabAtIndex(_ index: Int) { let tab = tabStore[index] if tabsToDisplay.index(of: tab) != nil { tabManager.selectTab(tab) } } } // Collection Diff (animations) extension TopTabsViewController { struct TopTabChangeSet { let reloads: Set<IndexPath> let inserts: Set<IndexPath> let deletes: Set<IndexPath> init(reloadArr: [IndexPath], insertArr: [IndexPath], deleteArr: [IndexPath]) { reloads = Set(reloadArr) inserts = Set(insertArr) deletes = Set(deleteArr) } var all: [Set<IndexPath>] { return [inserts, reloads, deletes] } } // create a TopTabChangeSet which is a snapshot of updates to perfrom on a collectionView func calculateDiffWith(_ oldTabs: [Tab], to newTabs: [Tab], and reloadTabs: [Tab?]) -> TopTabChangeSet { let inserts: [IndexPath] = newTabs.enumerated().flatMap { index, tab in if oldTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } // Create based on what is visibile but filter out tabs we are about to insert. let reloads: [IndexPath] = reloadTabs.flatMap { tab in guard let tab = tab, newTabs.index(of: tab) != nil else { return nil } return IndexPath(row: newTabs.index(of: tab)!, section: 0) }.filter { return inserts.index(of: $0) == nil } let deletes: [IndexPath] = oldTabs.enumerated().flatMap { index, tab in if newTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } return TopTabChangeSet(reloadArr: reloads, insertArr: inserts, deleteArr: deletes) } func updateTabsFrom(_ oldTabs: [Tab]?, to newTabs: [Tab], on completion: (() -> Void)? = nil) { assertIsMainThread("Updates can only be performed from the main thread") guard let oldTabs = oldTabs, !self.isUpdating, !self.pendingReloadData else { return } // Lets create our change set let update = self.calculateDiffWith(oldTabs, to: newTabs, and: needReloads) flushPendingChanges() // If there are no changes. We have nothing to do if update.all.every({ $0.isEmpty }) { completion?() return } // The actual update block. We update the dataStore right before we do the UI updates. let updateBlock = { self.tabStore = newTabs self.collectionView.deleteItems(at: Array(update.deletes)) self.collectionView.insertItems(at: Array(update.inserts)) self.collectionView.reloadItems(at: Array(update.reloads)) } //Lets lock any other updates from happening. self.isUpdating = true self.pendingUpdatesToTabs = newTabs // This var helps other mutations that might happen while updating. // The actual update self.collectionView.performBatchUpdates(updateBlock) { (_) in self.isUpdating = false self.pendingUpdatesToTabs = [] // Sometimes there might be a pending reload. Lets do that. if self.pendingReloadData { return self.reloadData() } // There can be pending animations. Run update again to clear them. let tabs = self.oldTabs ?? self.tabStore let toTabs = self.tabsToDisplay.count >= self.tabStore.count ? self.tabsToDisplay : self.tabStore self.updateTabsFrom(tabs, to: toTabs, on: { if !update.inserts.isEmpty || !update.reloads.isEmpty { self.scrollToCurrentTab() } }) } } fileprivate func flushPendingChanges() { oldTabs = nil needReloads.removeAll() } fileprivate func reloadData() { assertIsMainThread("reloadData must only be called from main thread") if self.isUpdating || self.collectionView.frame == CGRect.zero { self.pendingReloadData = true return } isUpdating = true self.tabStore = self.tabsToDisplay self.newTab.isUserInteractionEnabled = false self.flushPendingChanges() UIView.animate(withDuration: 0.2, animations: { self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.layoutIfNeeded() self.scrollToCurrentTab(true, centerCell: true) }, completion: { (_) in self.isUpdating = false self.pendingReloadData = false self.performTabUpdates() self.newTab.isUserInteractionEnabled = true }) } } extension TopTabsViewController: TabManagerDelegate { // Because we don't know when we are about to transition to private mode // check to make sure that the tab we are trying to add is being added to the right tab group fileprivate func tabsMatchDisplayGroup(_ a: Tab?, b: Tab?) -> Bool { if let a = a, let b = b, a.isPrivate == b.isPrivate { return true } return false } func performTabUpdates() { let fromTabs = !self.pendingUpdatesToTabs.isEmpty ? self.pendingUpdatesToTabs : self.oldTabs self.oldTabs = fromTabs ?? self.tabStore if self.pendingReloadData && !isUpdating { self.reloadData() } else { self.updateTabsFrom(self.oldTabs, to: self.tabsToDisplay) } } // This helps make sure animations don't happen before the view is loaded. fileprivate var isRestoring: Bool { return self.tabManager.isRestoring || self.collectionView.frame == CGRect.zero } func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) { if isRestoring { return } if !tabsMatchDisplayGroup(selected, b: previous) { self.reloadData() } else { self.needReloads.append(selected) self.needReloads.append(previous) performTabUpdates() delegate?.topTabsDidChangeTab() } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) { if isRestoring || (tabManager.selectedTab != nil && !tabsMatchDisplayGroup(tab, b: tabManager.selectedTab)) { return } performTabUpdates() } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) { if isRestoring { return } // If we deleted the last private tab. We'll be switching back to normal browsing. Pause updates till then if self.tabsToDisplay.isEmpty { self.pendingReloadData = true return } // dont want to hold a ref to a deleted tab if tab === oldSelectedTab { oldSelectedTab = nil } performTabUpdates() } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { self.reloadData() } func tabManagerDidAddTabs(_ tabManager: TabManager) { self.reloadData() } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { self.reloadData() } }
mpl-2.0
b48db4c8c9a61d5bddfb4a2c36fc2336
38.45
155
0.6485
5.161861
false
false
false
false
saitjr/STBurgerButtonManager
BurgerButtonManager-runtime/BurgerButtonManager-runtime/UIBarButtonItem+STBlock.swift
1
1162
// // UIBarButtonItem+STBlock.swift // BurgerButtonManager-runtime // // Created by TangJR on 2/7/16. // Copyright © 2016 tangjr. All rights reserved. // import UIKit typealias STBarButtonItemBlock = () -> () class STBarButtonItemWrapper { var block: STBarButtonItemBlock? init(block: STBarButtonItemBlock) { self.block = block } } struct STConst { static var STBarButtonItemWrapperKey = "STBarButtonItemWrapperKey" } extension UIBarButtonItem { convenience init(title: String?, style: UIBarButtonItemStyle, block: STBarButtonItemBlock) { self.init() self.title = title self.style = style target = self action = "buttonTapped" let wrapper = STBarButtonItemWrapper(block: block) objc_setAssociatedObject(self, &STConst.STBarButtonItemWrapperKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func buttonTapped() { if let wrapper = objc_getAssociatedObject(self, &STConst.STBarButtonItemWrapperKey) as? STBarButtonItemWrapper { if let block = wrapper.block { block() } } } }
mit
db1effe1e6b3c45c257dcc1a2e41ad92
26.666667
141
0.672696
4.33209
false
false
false
false
nathanlentz/rivals
Rivals/Rivals/CreateRivalryViewController.swift
1
4964
// // CreateRivalryViewController.swift // Rivals // // Created by Nate Lentz on 4/15/17. // Copyright © 2017 ntnl.design. All rights reserved. // import UIKit import Firebase class CreateRivalryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ @IBOutlet weak var playerTableView: UITableView! var ref: FIRDatabaseReference! // Array of users for adding to table view var players:Array = [User]() @IBOutlet weak var gameNameText: UITextField! override func viewDidLoad() { super.viewDidLoad() ref = FIRDatabase.database().reference() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) view.addGestureRecognizer(tap) view.backgroundColor = RIVALS_SECONDARY } /** We use an unwind segue to get the selected user from player search */ @IBAction func unwindAddPlayerView(segue: UIStoryboardSegue){ if let sourceVC = segue.source as? FindUserTableViewController { if !players.contains(sourceVC.selectedUser) { self.players.append(sourceVC.selectedUser) } } self.playerTableView.reloadData() } /** On 'Start' press, try to create a rivalry and return to home if success */ @IBAction func startRivalryDidPress(_ sender: Any) { if createRivalry(){ // TODO alert let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SWRevealViewController") self.present(vc, animated: true, completion: nil) } else { print("Error creating rivalry") } } func dismissKeyboard() { view.endEditing(true) } /** Create a rivalry given current users in list (plus current user) and string as board game name */ func createRivalry() -> Bool{ // TODO Notify user if validation is not right var success = false if gameNameText.text != "" && players.count > 1 { let currentUserId = FIRAuth.auth()?.currentUser?.uid var playerIds = [String](); for player in players { playerIds.append(player.uid!) } let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short) if createNewRivlary(creatorId: currentUserId!, gameName: gameNameText.text!, players: playerIds, creationDate: timestamp) { success = true } else { success = false } // TODO init game history and comments field, etc } else { print("Failed to submit") let alertController = UIAlertController(title: "Error", message: "Ensure you have more than 1 person and a game name for your rivalry", preferredStyle: .alert) let okAction = UIAlertAction(title: "Okay", style: .default, handler: nil) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) success = false } return success } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return players.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Create cell as an AddPlayerViewCell let cell = tableView.dequeueReusableCell(withIdentifier: "AddPlayerViewCell") as! AddPlayerViewCell // TODO: Add Player image and add player wins/losses let user = players[indexPath.row] cell.userName.text! = players[indexPath.row].name! cell.winsLosses.text! = "Wins / Losses" cell.profileImage.image = UIImage(named: "profile") cell.profileImage.contentMode = .scaleAspectFill if let userProfileImageUrl = user.profileImageUrl { cell.profileImage.loadImageUsingCacheWithUrlString(urlString: userProfileImageUrl) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // do stuff if selected? } // Swipe to remove players from array func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete data from array players.remove(at: indexPath.row) // Delete data from from tableView.deleteRows(at: [indexPath], with: .fade) } } }
apache-2.0
d7b7d0b758759625bdbc998eaa0c1c47
32.308725
171
0.611727
5.251852
false
false
false
false
akaralar/SafariHistorySearch
SafariHistorySearch.playground/Contents.swift
1
5150
import Foundation let HISTORY_PATH = "/Caches/Metadata/Safari/History" let MAX_RESULTS = 20 struct HistoryItem { let url: NSURL? let name: String? let fullText: String? let plistURL: NSURL init(fromPlistAtURL plistUrl: NSURL) { func plistAt(url: NSURL) -> AnyObject { let data = NSData.init(contentsOfURL: url) return try! NSPropertyListSerialization.propertyListWithData(data!, options: .Immutable, format: nil) } plistURL = plistUrl let plist = plistAt(plistUrl) if let urlString = plist.objectForKey("URL") as? String { url = NSURL(string: urlString) } else { url = nil } name = plist.objectForKey("Name") as? String fullText = plist.objectForKey("Full Page Text") as? String } func alfredResult() -> AlfredResult? { return url != nil ? AlfredResult(fromHistoryItem: self) : nil } } struct AlfredResult { static let SafariIconPath = "compass.png" let uid: String let arg: String let title: String let sub: String let icon: String let text: String let type: String = "file" init(fromHistoryItem historyItem: HistoryItem) { let url = historyItem.url!.absoluteString title = historyItem.name ?? "<TITLE_MISSING>" sub = url uid = url text = url arg = historyItem.plistURL.path! icon = AlfredResult.SafariIconPath } func toXML() -> NSXMLElement { let resultXML = NSXMLElement(name: "item") resultXML.addAttribute(NSXMLNode.attributeWithName("uid", stringValue: uid) as! NSXMLNode) resultXML.addChild(NSXMLNode.elementWithName("arg", stringValue: arg) as! NSXMLNode) resultXML.addChild(NSXMLNode.elementWithName("title", stringValue: title) as! NSXMLNode) resultXML.addChild(NSXMLNode.elementWithName("subtitle", stringValue: sub) as! NSXMLNode) resultXML.addChild(NSXMLNode.elementWithName("icon", stringValue: icon) as! NSXMLNode) let copyTextNode = NSXMLElement.elementWithName("text", stringValue: text) copyTextNode.addAttribute(NSXMLNode.attributeWithName("type", stringValue: "copy") as! NSXMLNode) resultXML.addChild(copyTextNode as! NSXMLNode) let largeTypeNode = NSXMLElement.elementWithName("text", stringValue: text) largeTypeNode.addAttribute(NSXMLNode.attributeWithName("type", stringValue: "largetype") as! NSXMLNode) resultXML.addChild(largeTypeNode as! NSXMLNode) return resultXML } } var outputPipe = NSPipe() var totalString = "" func captureStandardOutput(task: NSTask) { task.standardOutput = outputPipe outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify() NSNotificationCenter.defaultCenter().addObserverForName( NSFileHandleDataAvailableNotification, object: outputPipe.fileHandleForReading , queue: nil) { notification in let output = outputPipe.fileHandleForReading.availableData let outputString = String(data: output, encoding: NSUTF8StringEncoding) ?? "" dispatch_async( dispatch_get_main_queue(), { let previousOutput = totalString ?? "" let nextOutput = previousOutput + "\n" + outputString totalString = nextOutput let paths = totalString.componentsSeparatedByString("\n").filter { component in return component != "" } showItemsAtPaths(paths) }) outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify() } } func shell(args: [String]) -> Int32 { let task = NSTask() task.launchPath = "/usr/bin/env" task.arguments = args captureStandardOutput(task) task.launch() task.waitUntilExit() return task.terminationStatus } func showItemsAtPaths(paths: [String]) { var results = [AlfredResult]() let root = NSXMLElement(name: "items") for path in paths { let item = HistoryItem(fromPlistAtURL: NSURL.fileURLWithPath(path)) guard let alfredResult = item.alfredResult() else { continue } let resultXML = alfredResult.toXML() root.addChild(resultXML) results.append(alfredResult) if results.count >= MAX_RESULTS { break } } let xml = NSXMLDocument(rootElement: root) print(xml.XMLStringWithOptions(NSXMLNodePrettyPrint)) } let fileManager = NSFileManager() let libraryURL = try! fileManager.URLForDirectory(.LibraryDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) let fullPath = libraryURL.path!.stringByAppendingString(HISTORY_PATH) var mdfindArgs = ["mdfind", "-onlyin", fullPath] let concattedArgs = Process.arguments.dropFirst() if let args = concattedArgs.first { let splittedArgs = args.componentsSeparatedByString(" ") mdfindArgs.appendContentsOf(splittedArgs) shell(mdfindArgs) }
gpl-3.0
1a3ee094765899f8a7e30926a1aa1d22
35.274648
134
0.650874
4.660633
false
false
false
false
avtr/bluejay
Bluejay/Bluejay/Queue.swift
1
7014
// // Queue.swift // Bluejay // // Created by Jeremy Chiang on 2017-01-18. // Copyright © 2017 Steamclock Software. All rights reserved. // import Foundation import CoreBluetooth /// Allows the queue to notify states or delegate tasks. protocol QueueObserver: class { /// Called when a queue is about to run a connection operation. func willConnect(to peripheral: CBPeripheral) } /// A queue for running Bluetooth operations in a FIFO order. class Queue { /// Reference to the Bluejay that owns this queue. private weak var bluejay: Bluejay? /// Helps determine whether a scan is running or not. private var scan: Scan? /// The array of Bluetooth operations added. private var queue = [Queueable]() /// Helps distinguish one Queue instance from another. private var uuid = UUID() /// Helps determine whether CBCentralManager is being started up for the first time. private var isCBCentralManagerReady = false init(bluejay: Bluejay) { self.bluejay = bluejay log("Queue initialized with UUID: \(uuid.uuidString).") } deinit { log("Deinit Queue with UUID: \(uuid.uuidString).") } func start() { if !isCBCentralManagerReady { log("Starting queue with UUID: \(uuid.uuidString).") isCBCentralManagerReady = true update() } } func add(_ queueable: Queueable) { guard let bluejay = bluejay else { preconditionFailure("Cannot enqueue: Bluejay instance is nil.") } queueable.queue = self queue.append(queueable) /* Don't log the enqueuing of discovering services and discovering characteristics, as they are not exactly interesting and of importance in most cases. */ if !(queueable is DiscoverService) && !(queueable is DiscoverCharacteristic) { // Log more readable details for enqueued ListenCharacteristic queueable. if queueable is ListenCharacteristic { let listen = (queueable as! ListenCharacteristic) let name = listen.value ? "Listen" : "End Listen" let char = listen.characteristicIdentifier.uuid.uuidString log("\(name) for \(char) added to queue with UUID: \(uuid.uuidString).") } else { log("\(queueable) added to queue with UUID: \(uuid.uuidString).") } } if queueable is Scan { if scan == nil { scan = queueable as? Scan } else { queueable.fail(BluejayError.multipleScanNotSupported) } } else if queueable is Connection { // Fail the connection request immediately if Bluejay is still connecting or connected. if bluejay.isConnecting || bluejay.isConnected { queueable.fail(BluejayError.multipleConnectNotSupported) return } // Stop scanning when a connection is enqueued while a scan is still active, so that the queue can pop the scan task and proceed to the connection task without requiring the caller to explicitly stop the scan before making the connection request. if isScanning() { stopScanning() return } } update() } // MARK: - Cancellation @objc func cancelAll(_ error: Error? = nil) { stopScanning(error) for queueable in queue where !queueable.state.isFinished { if let error = error { queueable.fail(error) } else { queueable.cancel() } } queue = [] } func stopScanning(_ error: Error? = nil) { if let error = error { scan?.fail(error) } else { scan?.cancel() } scan = nil } // MARK: - Queue func update() { if queue.isEmpty { // TODO: Minimize redundant calls to update, especially when queue is empty. // log("Queue is empty, nothing to run.") return } if !isCBCentralManagerReady { log("Queue is paused because CBCentralManager is not ready yet.") return } if let queueable = queue.first { // Remove current queueable if finished. if queueable.state.isFinished { if queueable is Scan { scan = nil } queue.removeFirst() update() return } if let bluejay = bluejay { if !bluejay.isBluetoothAvailable { // Fail any queuable if Bluetooth is not even available. queueable.fail(BluejayError.bluetoothUnavailable) } else if !bluejay.isConnected && !(queueable is Scan) && !(queueable is Connection) { // Fail any queueable that is not a Scan nor a Connection if no peripheral is connected. queueable.fail(BluejayError.notConnected) } else if case .running = queueable.state { // Do nothing if the current queueable is still running. return } else if case .notStarted = queueable.state { if let connection = queueable as? Connection { bluejay.willConnect(to: connection.peripheral) } queueable.start() } } else { preconditionFailure("Queue failure: Bluejay is nil.") } } } func process(event: Event, error: Error?) { if isEmpty() { log("Queue is empty but received an event: \(event)") return } if let queueable = queue.first { if let error = error { queueable.fail(error) } else { queueable.process(event: event) } } } // MARK: - States func isEmpty() -> Bool { return queue.isEmpty } func isScanning() -> Bool { return scan != nil } } extension Queue: ConnectionObserver { func bluetoothAvailable(_ available: Bool) { if available { update() } else { if !isEmpty() { cancelAll(BluejayError.bluetoothUnavailable) } } } func connected(_ peripheral: Peripheral) { update() } }
mit
1a9e3224442d895c5dd1b749605e7d97
29.098712
258
0.52146
5.349352
false
false
false
false
huonw/swift
stdlib/public/Platform/Platform.swift
4
11313
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public var noErr: OSStatus { return 0 } /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. @_fixed_layout public struct DarwinBoolean : ExpressibleByBooleanLiteral { var _value: UInt8 public init(_ value: Bool) { self._value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { return _value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension DarwinBoolean : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension DarwinBoolean : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension DarwinBoolean : Equatable { public static func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool { return lhs.boolValue == rhs.boolValue } } public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool { return x.boolValue } #endif //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// public var errno : Int32 { get { return _stdlib_getErrno() } set(val) { return _stdlib_setErrno(val) } } //===----------------------------------------------------------------------===// // stdio.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var stdin : UnsafeMutablePointer<FILE> { get { return __stdinp } set { __stdinp = newValue } } public var stdout : UnsafeMutablePointer<FILE> { get { return __stdoutp } set { __stdoutp = newValue } } public var stderr : UnsafeMutablePointer<FILE> { get { return __stderrp } set { __stderrp = newValue } } public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in vdprintf(Int32(fd), format, va_args) } } public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in return vsnprintf(ptr, len, format, va_args) } } #endif //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _stdlib_open(path, oflag, 0) } #if os(Windows) public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: Int32 ) -> Int32 { return _stdlib_open(path, oflag, mode) } #else public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _stdlib_open(path, oflag, mode) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _stdlib_openat(fd, path, oflag, 0) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _stdlib_openat(fd, path, oflag, mode) } public func fcntl( _ fd: Int32, _ cmd: Int32 ) -> Int32 { return _stdlib_fcntl(fd, cmd, 0) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ value: Int32 ) -> Int32 { return _stdlib_fcntl(fd, cmd, value) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ ptr: UnsafeMutableRawPointer ) -> Int32 { return _stdlib_fcntlPtr(fd, cmd, ptr) } // !os(Windows) #endif #if os(Windows) public var S_IFMT: Int32 { return Int32(0xf000) } public var S_IFREG: Int32 { return Int32(0x8000) } public var S_IFDIR: Int32 { return Int32(0x4000) } public var S_IFCHR: Int32 { return Int32(0x2000) } public var S_IFIFO: Int32 { return Int32(0x1000) } public var S_IREAD: Int32 { return Int32(0x0100) } public var S_IWRITE: Int32 { return Int32(0x0080) } public var S_IEXEC: Int32 { return Int32(0x0040) } #else public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_IFWHT: mode_t { return mode_t(0o160000) } #endif public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_ISTXT: mode_t { return S_ISVTX } public var S_IREAD: mode_t { return S_IRUSR } public var S_IWRITE: mode_t { return S_IWUSR } public var S_IEXEC: mode_t { return S_IXUSR } #endif #endif //===----------------------------------------------------------------------===// // ioctl.h //===----------------------------------------------------------------------===// #if !os(Windows) public func ioctl( _ fd: CInt, _ request: UInt, _ value: CInt ) -> CInt { return _stdlib_ioctl(fd, request, value) } public func ioctl( _ fd: CInt, _ request: UInt, _ ptr: UnsafeMutableRawPointer ) -> CInt { return _stdlib_ioctlPtr(fd, request, ptr) } public func ioctl( _ fd: CInt, _ request: UInt ) -> CInt { return _stdlib_ioctl(fd, request, 0) } // !os(Windows) #endif //===----------------------------------------------------------------------===// // unistd.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func fork() -> Int32 { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func vfork() -> Int32 { fatalError("unavailable function can't be called") } #endif //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) } #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Haiku) public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Cygwin) public typealias sighandler_t = _sig_func_ptr public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Windows) public var SIG_DFL: _crt_signal_t? { return nil } public var SIG_IGN: _crt_signal_t { return unsafeBitCast(1, to: _crt_signal_t.self) } public var SIG_ERR: _crt_signal_t { return unsafeBitCast(-1, to: _crt_signal_t.self) } #else internal var _ignore = _UnsupportedPlatformError() #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// #if !os(Windows) /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: UnsafeMutablePointer<sem_t>? { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS. return UnsafeMutablePointer<sem_t>(bitPattern: -1) #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) #else _UnsupportedPlatformError() #endif } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32 ) -> UnsafeMutablePointer<sem_t>? { return _stdlib_sem_open2(name, oflag) .assumingMemoryBound(to: sem_t.self) } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t>? { return _stdlib_sem_open4(name, oflag, mode, value) .assumingMemoryBound(to: sem_t.self) } #endif //===----------------------------------------------------------------------===// // Misc. //===----------------------------------------------------------------------===// // Some platforms don't have `extern char** environ` imported from C. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _stdlib_getEnviron() } #elseif os(Linux) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return __environ } #endif
apache-2.0
0b947ddf282be1fad568eb1db7216f00
27.002475
127
0.579599
3.454351
false
false
false
false
SuperJerry/Swift
linkedlist.playground/Contents.swift
1
2102
//: Playground - noun: a place where people can play //import UIKit //var str = "Hello, playground" public class Node<T: Equatable> { var value: T var next: Node? = nil init(_ value: T){ self.value = value } } public class Linkedlist<T: Equatable>{ var head: Node<T>? = nil func Insertathead(value: T){ if head == nil{ self.head = Node(value) }else{ let newNode = Node(value) newNode.next = head self.head = newNode } } func Insertattail(value:T){ if head == nil{ self.head = Node(value) }else{ var lastNode = head while lastNode?.next != nil{ lastNode = lastNode?.next } let newNode = Node(value) lastNode?.next = newNode } } func remove(value: T){ if head != nil{ var node = head var previousnode: Node<T>? = nil while node?.value != value && node?.next != nil{ previousnode = node node = node?.next } if node?.value == value{ if node?.next != nil{ previousnode?.next = node?.next }else{ previousnode?.next = nil } } } } var description : String{ var node = head var description = "\(node!.value)" while node?.next != nil{ node = node?.next description += ",\(node!.value)" } return description } } var listInt = Linkedlist<Int>() listInt.Insertathead(20) listInt.Insertattail(30) listInt.Insertattail(40) listInt.Insertathead(10) listInt.Insertathead(0) listInt.description println(listInt.description) var listStr = Linkedlist<String>() listStr.Insertathead("B") listStr.Insertattail("C") listStr.Insertattail("C") listStr.Insertattail("D") listStr.Insertathead("A") listStr.description println(listStr.description) listStr.remove("C") println(listStr.description)
mit
6f4d0f6f2b66ccfb75eea4b82e24c9e9
23.16092
60
0.534729
3.943715
false
false
false
false
happyeverydayzhh/WWDC
WWDC/MainWindowController.swift
4
2357
// // MainWindowController.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() configureWindowAppearance() NSNotificationCenter.defaultCenter().addObserverForName(NSWindowWillCloseNotification, object: nil, queue: nil) { _ in if let window = self.window { Preferences.SharedPreferences().mainWindowFrame = window.frame } } NSNotificationCenter.defaultCenter().addObserverForName(LiveEventNextInfoChangedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { _ in if let liveBanner = LiveEventBannerViewController.DefaultController { liveBanner.event = LiveEventObserver.SharedObserver().nextEvent if let window = self.window { window.contentView!.addSubview(liveBanner.view) liveBanner.prepareForParentView(window.contentView!) } } } } override func showWindow(sender: AnyObject?) { restoreWindowSize() super.showWindow(sender) } private func configureWindowAppearance() { if let window = window { if let view = window.contentView { view.wantsLayer = true } window.styleMask |= NSFullSizeContentViewWindowMask window.titleVisibility = .Hidden window.titlebarAppearsTransparent = true } } private func restoreWindowSize() { if let window = window { var savedFrame = Preferences.SharedPreferences().mainWindowFrame if savedFrame != NSZeroRect { if let screen = NSScreen.mainScreen() { // if the screen's height changed between launches, the window can be too big if savedFrame.size.height > screen.frame.size.height { savedFrame.size.height = screen.frame.size.height } } window.setFrame(savedFrame, display: true) } } } }
bsd-2-clause
e0b48ce068c7583b428adf7951034f86
31.736111
158
0.57955
5.762836
false
false
false
false
cocoaheadsru/server
Sources/App/Common/Extensions/Foundation/String/String+RandomValue.swift
1
1370
import Foundation extension String { static var randomValue: String { let uuid = UUID().uuidString let upperBound = uuid.count - 1 let randomStringLength = Int.random(min: 1, max: upperBound) let randomStringIndex = String.Index(encodedOffset: randomStringLength) let randString = String(uuid[..<randomStringIndex]) return randString } static var randomURL: String { if Bool.randomValue { return "https://\(String.randomValue).\(String.randomValue).\(String.randomValue)" } else { return "http://\(String.randomValue).\(String.randomValue).\(String.randomValue)" } } static var randomPhotoName: String { if Bool.randomValue { return "\(String.randomValue).png" } else { return "\(String.randomValue).jpeg" } } static var randomEmail: String { if Bool.randomValue { return "\(String.randomValue)/@\(String.randomValue).com" } else { return "\(String.randomValue)/@\(String.randomValue).org" } } static var randomPhone: String { let country = "\(Int.randomValue(min: 1, max: 99))" let region = "(\(Int.randomValue(min: 100, max: 999)))" let city = "\(Int.randomValue(min: 100, max: 999))" let building = "\(Int.randomValue(min: 100, max: 999))" return "+" + country + "-" + region + "-" + city + "-" + building } }
mit
df80c84f884c039bc8b7136a0674ab54
29.444444
88
0.632117
4.126506
false
false
false
false
benlangmuir/swift
test/SourceKit/CursorInfo/cursor_stdlib.swift
13
10122
import Foundation var x = NSUTF8StringEncoding var d : AnyIterator<Int> func foo1(_ a : inout [Int]) { a = a.sorted() a.append(1) } struct S1 {} func foo2(_ a : inout [S1]) { a = a.sorted(by: { (a, b) -> Bool in return false }) a.append(S1()) } import Swift func foo3(a: Float, b: Bool) {} // REQUIRES: objc_interop // RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays // RUN: %sourcekitd-test -req=cursor -pos=3:18 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-OVERLAY %s // CHECK-OVERLAY: source.lang.swift.ref.var.global // CHECK-OVERLAY-NEXT: NSUTF8StringEncoding // CHECK-OVERLAY-NEXT: s:10Foundation20NSUTF8StringEncodingSuv // CHECK-OVERLAY-NEXT: source.lang.swift // CHECK-OVERLAY-NEXT: UInt // CHECK-OVERLAY-NEXT: $sSuD // CHECK-OVERLAY-NEXT: Foundation // CHECK-OVERLAY-NEXT: SYSTEM // CHECK-OVERLAY-NEXT: <Declaration>let NSUTF8StringEncoding: <Type usr="s:Su">UInt</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=5:13 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-ITERATOR %s // CHECK-ITERATOR-NOT: _AnyIteratorBase // CHECK-ITERATOR: <Group>Collection/Type-erased</Group> // RUN: %sourcekitd-test -req=cursor -pos=8:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT1 %s // CHECK-REPLACEMENT1: <Group>Collection/Array</Group> // CHECK-REPLACEMENT1: <Declaration>{{.*}}func sorted() -&gt; [<Type usr="s:Si">Int</Type>]</Declaration> // CHECK-REPLACEMENT1: RELATED BEGIN // CHECK-REPLACEMENT1: sorted(by:)</RelatedName> // CHECK-REPLACEMENT1: RELATED END // RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT2 %s // CHECK-REPLACEMENT2: <Group>Collection/Array</Group> // CHECK-REPLACEMENT2: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:Si">Int</Type>)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=15:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT3 %s // CHECK-REPLACEMENT3: <Group>Collection/Array</Group> // CHECK-REPLACEMENT3: func sorted(by areInIncreasingOrder: (<Type usr="s:13cursor_stdlib2S1V">S1</Type> // CHECK-REPLACEMENT3: sorted()</RelatedName> // RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=18:8 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-REPLACEMENT4 %s // CHECK-REPLACEMENT4: <Group>Collection/Array</Group> // CHECK-REPLACEMENT4: <Declaration>{{.*}}mutating func append(_ newElement: <Type usr="s:13cursor_stdlib2S1V">S1</Type>)</Declaration> // CHECK-REPLACEMENT4: SYMBOL GRAPH BEGIN // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "module": { // CHECK-REPLACEMENT4: "name": "Swift", // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "relationships": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "memberOf", // CHECK-REPLACEMENT4: "source": "s:Sa6appendyyxnF", // CHECK-REPLACEMENT4: "target": "s:Sa" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "symbols": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "accessLevel": "public", // CHECK-REPLACEMENT4: "declarationFragments": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "keyword", // CHECK-REPLACEMENT4: "spelling": "mutating" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": " " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "keyword", // CHECK-REPLACEMENT4: "spelling": "func" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": " " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "identifier", // CHECK-REPLACEMENT4: "spelling": "append" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": "(" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "externalParam", // CHECK-REPLACEMENT4: "spelling": "_" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": " " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "internalParam", // CHECK-REPLACEMENT4: "spelling": "newElement" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": ": " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "typeIdentifier", // CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V", // CHECK-REPLACEMENT4: "spelling": "S1" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": ")" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "docComment": { // CHECK-REPLACEMENT4: "lines": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "text": "Adds a new element at the end of the array." // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: ] // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "functionSignature": { // CHECK-REPLACEMENT4: "parameters": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "declarationFragments": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "identifier", // CHECK-REPLACEMENT4: "spelling": "newElement" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": ": " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "typeIdentifier", // CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V", // CHECK-REPLACEMENT4: "spelling": "S1" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "name": "newElement" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "returns": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": "()" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ] // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "identifier": { // CHECK-REPLACEMENT4: "interfaceLanguage": "swift", // CHECK-REPLACEMENT4: "precise": "s:Sa6appendyyxnF" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "kind": { // CHECK-REPLACEMENT4: "displayName": "Instance Method", // CHECK-REPLACEMENT4: "identifier": "swift.method" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "names": { // CHECK-REPLACEMENT4: "subHeading": [ // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "keyword", // CHECK-REPLACEMENT4: "spelling": "func" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": " " // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "identifier", // CHECK-REPLACEMENT4: "spelling": "append" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": "(" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "typeIdentifier", // CHECK-REPLACEMENT4: "preciseIdentifier": "s:13cursor_stdlib2S1V", // CHECK-REPLACEMENT4: "spelling": "S1" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: { // CHECK-REPLACEMENT4: "kind": "text", // CHECK-REPLACEMENT4: "spelling": ")" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "title": "append(_:)" // CHECK-REPLACEMENT4: }, // CHECK-REPLACEMENT4: "pathComponents": [ // CHECK-REPLACEMENT4: "Array", // CHECK-REPLACEMENT4: "append(_:)" // CHECK-REPLACEMENT4: ], // CHECK-REPLACEMENT4: "swiftExtension": { // CHECK-REPLACEMENT4: "extendedModule": "Swift" // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: ] // CHECK-REPLACEMENT4: } // CHECK-REPLACEMENT4: SYMBOL GRAPH END // RUN: %sourcekitd-test -req=cursor -pos=21:10 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-MODULE-GROUP1 %s // CHECK-MODULE-GROUP1: MODULE GROUPS BEGIN // CHECK-MODULE-GROUP1-DAG: Math // CHECK-MODULE-GROUP1-DAG: Collection // CHECK-MODULE-GROUP1-DAG: Collection/Array // CHECK-MODULE-GROUP1: MODULE GROUPS END // RUN: %sourcekitd-test -req=cursor -pos=22:17 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-FLOAT1 %s // CHECK-FLOAT1: s:Sf // RUN: %sourcekitd-test -req=cursor -pos=22:25 %s -- %s -target %target-triple %clang-importer-sdk-nosource -I %t | %FileCheck -check-prefix=CHECK-BOOL1 %s // CHECK-BOOL1: s:Sb
apache-2.0
b6a5110162f8a690c07fd4e5dd869ee2
43.986667
196
0.603142
3.489142
false
false
false
false
pixyzehn/stodo
Sources/stodo/Commands/Add.swift
1
1330
// // Add.swift // stodo // // Created by Hiroki Nagasawa on 10/6/16. // Copyright © 2016 Hiroki Nagasawa. All rights reserved. // import Commandant import Result import StodoKit public struct AddOptions: OptionsProtocol { public typealias ClientError = StodoError let title: String let isDone: Bool static func add(_ title: String) -> (Bool) -> AddOptions { return { isDone in self.init(title: title, isDone: isDone) } } public static func evaluate(_ m: CommandMode) -> Result<AddOptions, CommandantError<ClientError>> { return add <*> m <| Argument(usage: "Task title to add") <*> m <| Switch(flag: "d", key: "done", usage: "Add new task with a status of done") } } public struct AddCommand: CommandProtocol { public typealias Options = AddOptions public typealias ClientError = StodoError public let verb = "add" public let function = "Create a new task" public func run(_ options: Options) -> Result<(), ClientError> { let title = options.title switch Todo.add(title: title, isDone: options.isDone) { case .success: _ = ListCommand().run(ListOptions()) return .success() case .failure(let error): return .failure(error) } } }
mit
2bb6c9218667bdc531a27caa175adc7a
26.6875
103
0.617758
4.153125
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/UIComponents/UIComponentsKit/Views/InfoView.swift
1
5587
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Extensions import SwiftUI public struct InfoView: View { public struct Model: Equatable, Codable { public struct Overlay: Equatable, Codable { public var media: Media? public var progress: Bool? public init(media: Media? = nil, progress: Bool? = nil) { self.media = media self.progress = progress } } public var media: Media public var overlay: Overlay? public var title: String public var subtitle: String public init(media: Media, overlay: InfoView.Model.Overlay? = nil, title: String, subtitle: String) { self.media = media self.overlay = overlay self.title = title self.subtitle = subtitle } public init(media: Media, overlay: Media, title: String, subtitle: String) { self.media = media self.overlay = .init(media: overlay) self.title = title self.subtitle = subtitle } } public struct Layout: Equatable, Codable { public var media: Size public var overlay: Size public var margin: Length public var spacing: Length public init( media: Size, overlay: Size, margin: Length, spacing: Length ) { self.media = media self.overlay = overlay self.margin = margin self.spacing = spacing } } public var model: Model public var layout: Layout public init( _ model: Model, layout: Layout = .init( media: Size(length: 20.vmin), overlay: Size(length: 7.5.vmin), margin: 6.vmin, spacing: LayoutConstants.VerticalSpacing.betweenContentGroups.pt ) ) { self.model = model self.layout = layout } private struct ComputedLayout: Equatable { var media: CGSize = .zero var overlay: CGSize = .zero var margin: CGFloat = .zero var spacing: CGFloat = .zero } @State private var computed: ComputedLayout = .init() public var body: some View { VStack(spacing: computed.spacing) { MediaView( model.media, failure: { Color.red .opacity(0.25) .clipShape(Circle()) .overlay( Image(systemName: "nosign") .resizable() .padding(computed.overlay.height / 2) .foregroundColor(Color.white) ) } ) .frame( width: computed.media.width + computed.overlay.height / 2, height: computed.media.height + computed.overlay.height / 2 ) .padding( EdgeInsets( top: computed.overlay.height / 2, leading: computed.overlay.width / 2, bottom: computed.overlay.height / 2, trailing: computed.overlay.width / 2 ) ) .overlay( ZStack { if model.overlay != nil { Circle() .foregroundColor(.semantic.background) .scaleEffect(1.3) overlayView } } .frame( width: computed.overlay.width, height: computed.overlay.height ) .offset(x: -7.5, y: 7.5), alignment: .topTrailing ) VStack { Text(model.title) .textStyle(.title) Text(model.subtitle) .textStyle(.body) } .multilineTextAlignment(.center) .padding([.leading, .trailing], computed.margin) }.background( GeometryReader { proxy in Color.clear.onAppear { computed = .init( media: layout.media.in(proxy), overlay: layout.overlay.in(proxy), margin: layout.margin.in(proxy), spacing: layout.spacing.in(proxy) ) } } ) } @ViewBuilder var overlayView: some View { if let icon = model.overlay?.media { MediaView(icon, failure: Color.clear) } else if model.overlay?.progress == true { ProgressView(value: 0.25) .progressViewStyle(IndeterminateProgressStyle()) } else { EmptyView() } } } #if DEBUG struct InfoView_Previews: PreviewProvider { static var previews: some View { VStack { Spacer() InfoView( .init( media: .image(systemName: "building.columns.fill"), overlay: .init(progress: true), title: "Taking you to Monzo", subtitle: "This could take up to 30 seconds. Please do not go back or close the app" ) ) Spacer() } } } #endif
lgpl-3.0
1b61bb1c2072172a669ce20ef87a504c
29.358696
108
0.469925
5.309886
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/ViewControllers/Core/Cloud Code/CloudCodeViewController.swift
1
11191
// // CloudCodeViewController.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 12/19/17. // import UIKit import AlertHUDKit import CoreData final class CloudCodeViewController: TableViewController { // MARK: - Properties override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } var functions: [CloudCode] = [] var jobs: [CloudCode] = [] let consoleView = ConsoleView() fileprivate var context: NSManagedObjectContext? { return (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() setupTableView() getSavedCloudCode() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavigationBar() setupConsoleView() } // MARK: - Data Storage private func getSavedCloudCode() { guard let context = context else { return } let request: NSFetchRequest<CloudCode> = CloudCode.fetchRequest() do { let codes = try context.fetch(request) functions.removeAll() jobs.removeAll() for code in codes { if code.isFunction == true { functions.append(code) } else { jobs.append(code) } } } catch let error { self.handleError(error.localizedDescription) } } // MARK: - Setup private func setupConsoleView() { guard let navView = navigationController?.view else { return } consoleView.layer.shadowColor = UIColor.black.cgColor navView.addSubview(consoleView) consoleView.anchor(nil, left: navView.leftAnchor, bottom: navView.bottomAnchor, right: navView.rightAnchor, heightConstant: view.frame.height / 5) } private func setupTableView() { tableView.contentInset.bottom = view.frame.height / 5 tableView.tableFooterView = UIView() let gradient: CAGradientLayer = CAGradientLayer() gradient.colors = [UIColor(white: 0.1, alpha: 1).cgColor, UIColor.darkGray.darker().cgColor] gradient.locations = [0.0, NSNumber(value: Float(tableView.contentInset.bottom))] gradient.frame = view.bounds tableView.backgroundView = UIView() tableView.backgroundView?.layer.insertSublayer(gradient, at: 0) } private func setupNavigationBar() { navigationController?.navigationBar.tintColor = .darkPurpleBackground navigationController?.navigationBar.barTintColor = UIColor(white: 0.1, alpha: 1) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissViewController)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addCloudCode)) navigationItem.backBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) title = "Cloud Code Executor" } // MARK: - User Actions @objc func dismissViewController() { dismiss(animated: true, completion: nil) } @objc func addCloudCode() { let object = CloudCode(entity: CloudCode.entity(), insertInto: nil) object.body = String() object.endpoint = "/functions" object.isFunction = true let vc = CloudCodeBuilderViewController(for: object) vc.delegate = self navigationController?.pushViewController(vc, animated: true) } // MARK: - UITableViewController override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 32 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UITableViewHeaderFooterView() header.contentView.backgroundColor = .darkPurpleBackground header.textLabel?.textColor = .white header.textLabel?.font = UIFont.boldSystemFont(ofSize: 12) let isFunctions = functions.count > 0 if section == 0 && isFunctions { header.textLabel?.text = "Cloud Functions" } else { header.textLabel?.text = "Background Jobs" } return header } override func numberOfSections(in tableView: UITableView) -> Int { let isFunctions = functions.count > 0 let isJobs = jobs.count > 0 return (isFunctions ? 1 : 0) + (isJobs ? 1 : 0) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let isFunctions = functions.count > 0 if section == 0 && isFunctions { return functions.count } else { return jobs.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil) cell.textLabel?.font = .boldSystemFont(ofSize: 15) cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.font = .systemFont(ofSize: 14) cell.detailTextLabel?.numberOfLines = 0 cell.accessoryType = .disclosureIndicator let isFunctions = functions.count > 0 if indexPath.section == 0 && isFunctions { cell.textLabel?.text = functions[indexPath.row].name cell.detailTextLabel?.text = functions[indexPath.row].body return cell } else { cell.textLabel?.text = jobs[indexPath.row].name cell.detailTextLabel?.text = jobs[indexPath.row].body return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cloudCode = indexPath.section == 0 ? functions[indexPath.row] : jobs[indexPath.row] guard let endpoint = cloudCode.endpoint, let name = cloudCode.name else { return } let data = cloudCode.body?.data(using: .utf8) handeLog("POST \(endpoint)/\(name)") ParseLite.shared.post("\(endpoint)/\(name)", data: data) { (result, json) in guard result.success, let json = json else { self.handeLog(result.error) return } let message = json["result"] as? String ?? String(describing: json) self.handeLog(message) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let editAction = UITableViewRowAction(style: .normal, title: "Edit") { _, indexPath in let cloudCode = indexPath.section == 0 ? self.functions[indexPath.row] : self.jobs[indexPath.row] let vc = CloudCodeBuilderViewController(for: cloudCode) vc.delegate = self self.navigationController?.pushViewController(vc, animated: true) } editAction.backgroundColor = .darkPurpleAccent let deleteAction = UITableViewRowAction(style: .destructive, title: Localizable.delete.localized) { _, indexPath in guard let context = self.context else { return } do { let isFunctions = self.functions.count > 0 if indexPath.section == 0 && isFunctions { let function = self.functions[indexPath.row] context.delete(function) try context.save() self.functions.remove(at: indexPath.row) self.handleSuccess("Cloud Function Removed") if self.functions.count == 0 { self.tableView.deleteSections([indexPath.section], with: .none) } else { self.tableView.deleteRows(at: [indexPath], with: .none) } } else { let job = self.jobs[indexPath.row] context.delete(job) try context.save() self.handleSuccess("Background Job Removed") self.jobs.remove(at: indexPath.row) if self.jobs.count == 0 { self.tableView.deleteSections([indexPath.section], with: .none) } else { self.tableView.deleteRows(at: [indexPath], with: .none) } } } catch let error { self.handleError(error.localizedDescription) } } return [deleteAction, editAction] } // MARK: - Logging func handeLog(_ message: String?) { let message = message ?? "..." consoleView.log(message: message) } } extension CloudCodeViewController: CloudCodeBuilderDelegate { func cloudCode(didEnterNew cloudCode: CloudCode) { guard let context = context else { return } if cloudCode.managedObjectContext == nil { context.insert(cloudCode) } do { try context.save() getSavedCloudCode() tableView.reloadData() } catch let error { self.handleError(error.localizedDescription) } } }
mit
ffe00a194e4100bf0c8c402ad94cd6bc
36.932203
154
0.597319
5.231417
false
false
false
false
mas-cli/mas
Sources/MasKit/Commands/Vendor.swift
1
2477
// // Vendor.swift // mas-cli // // Created by Ben Chatelain on 2018-12-29. // Copyright © 2016 mas-cli. All rights reserved. // import Commandant /// Opens vendor's app page in a browser. Uses the iTunes Lookup API: /// https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#lookup public struct VendorCommand: CommandProtocol { public typealias Options = VendorOptions public let verb = "vendor" public let function = "Opens vendor's app page in a browser" private let storeSearch: StoreSearch private var openCommand: ExternalCommand public init() { self.init( storeSearch: MasStoreSearch(), openCommand: OpenSystemCommand() ) } /// Designated initializer. init( storeSearch: StoreSearch = MasStoreSearch(), openCommand: ExternalCommand = OpenSystemCommand() ) { self.storeSearch = storeSearch self.openCommand = openCommand } /// Runs the command. public func run(_ options: VendorOptions) -> Result<Void, MASError> { do { guard let result = try storeSearch.lookup(app: options.appId).wait() else { return .failure(.noSearchResultsFound) } guard let vendorWebsite = result.sellerUrl else { throw MASError.noVendorWebsite } do { try openCommand.run(arguments: vendorWebsite) } catch { printError("Unable to launch open command") return .failure(.searchFailed) } if openCommand.failed { let reason = openCommand.process.terminationReason printError("Open failed: (\(reason)) \(openCommand.stderr)") return .failure(.searchFailed) } } catch { // Bubble up MASErrors if let error = error as? MASError { return .failure(error) } return .failure(.searchFailed) } return .success(()) } } public struct VendorOptions: OptionsProtocol { let appId: Int static func create(_ appId: Int) -> VendorOptions { VendorOptions(appId: appId) } public static func evaluate(_ mode: CommandMode) -> Result<VendorOptions, CommandantError<MASError>> { create <*> mode <| Argument(usage: "the app ID to show the vendor's website") } }
mit
f30be3dc341d89ed2af0c5b7b1e76794
28.831325
106
0.59895
4.671698
false
false
false
false
dreymonde/Alba
Sources/WeakSubscribe.swift
1
5903
/** * Alba * * Copyright (c) 2016 Oleg Dreyman. Licensed under the MIT license, as follows: * * 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. */ public struct WeakSubscribe<Object : AnyObject, Event> { public let proxy: Subscribe<Event> fileprivate let object: Object public init(proxy: Subscribe<Event>, object: Object) { self.proxy = proxy self.object = object } public func rawModify<OtherEvent>(subscribe: @escaping (Object, ObjectIdentifier, @escaping EventHandler<OtherEvent>) -> (), entry: ProxyPayload.Entry) -> WeakSubscribe<Object, OtherEvent> { let selfproxy = self.proxy let newProxy: Subscribe<OtherEvent> = selfproxy.rawModify(subscribe: { [weak object] (identifier, handle) in if let objecta = object { subscribe(objecta, identifier, handle) } else { selfproxy.manual.unsubscribe(objectWith: identifier) } }, entry: entry) return WeakSubscribe<Object, OtherEvent>(proxy: newProxy, object: object) } public func filter(_ condition: @escaping (Object) -> (Event) -> Bool) -> WeakSubscribe<Object, Event> { let sproxy = self.proxy return rawModify(subscribe: { (object, identifier, handle) in let handler: EventHandler<Event> = { [weak object] event in if let object = object { if condition(object)(event) { handle(event) } } else { sproxy.manual.unsubscribe(objectWith: identifier) } } sproxy.manual.subscribe(objectWith: identifier, with: handler) }, entry: .filtered) } public func map<OtherEvent>(_ transform: @escaping (Object) -> (Event) -> (OtherEvent)) -> WeakSubscribe<Object, OtherEvent> { let selfproxy = proxy return rawModify(subscribe: { (object, identifier, handle) in let handler: EventHandler<Event> = { [weak object] event in if let objecta = object { handle(transform(objecta)(event)) } else { selfproxy.manual.unsubscribe(objectWith: identifier) } } selfproxy.manual.subscribe(objectWith: identifier, with: handler) }, entry: .mapped(fromType: Event.self, toType: OtherEvent.self)) } public func flatMap<OtherEvent>(_ transform: @escaping (Object) -> (Event) -> (OtherEvent?)) -> WeakSubscribe<Object, OtherEvent> { let selfproxy = proxy return rawModify(subscribe: { (object, identifier, handle) in let handler: EventHandler<Event> = { [weak object] event in if let objecta = object { if let transformed = transform(objecta)(event) { handle(transformed) } } else { selfproxy.manual.unsubscribe(objectWith: identifier) } } selfproxy.manual.subscribe(objectWith: identifier, with: handler) }, entry: .mapped(fromType: Event.self, toType: OtherEvent.self)) } public func subscribe(with producer: @escaping (Object) -> EventHandler<Event>) { proxy.subscribe(object, with: producer) } public var flat: FlatWeakSubscribe<Object, Event> { return FlatWeakSubscribe(weakProxy: self) } } public struct FlatWeakSubscribe<Object : AnyObject, Event> { public let weakProxy: WeakSubscribe<Object, Event> public init(weakProxy: WeakSubscribe<Object, Event>) { self.weakProxy = weakProxy } public var proxy: Subscribe<Event> { return weakProxy.proxy } public func filter(_ condition: @escaping (Object, Event) -> Bool) -> FlatWeakSubscribe<Object, Event> { return weakProxy.filter(unfold(condition)).flat } public func map<OtherEvent>(_ transform: @escaping (Object, Event) -> OtherEvent) -> FlatWeakSubscribe<Object, OtherEvent> { return weakProxy.map(unfold(transform)).flat } public func flatMap<OtherEvent>(_ transform: @escaping (Object, Event) -> OtherEvent?) -> FlatWeakSubscribe<Object, OtherEvent> { return weakProxy.flatMap(unfold(transform)).flat } public func subscribe(with handler: @escaping (Object, Event) -> ()) { weakProxy.subscribe(with: unfold(handler)) } } internal func unfold<First, Second, Output>(_ function: @escaping (First, Second) -> Output) -> (First) -> (Second) -> Output { return { first in return { second in return function(first, second) } } } public prefix func ! <T>(boolFunc: @escaping (T) -> Bool) -> ((T) -> Bool) { return { return !boolFunc($0) } }
mit
fe0cb0ed6b6ea8e385fe95e8c5c71ff6
39.993056
194
0.6268
4.465204
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/YTime/controller/YTimeJobsViewController.swift
2
1534
// // YTimeJobsViewController.swift // byuSuite // // Created by Eric Romrell on 5/18/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit class YTimeJobsViewController: ByuViewController2, UITableViewDataSource { //Outlets @IBOutlet private weak var tableView: UITableView! //Public variables var jobs = [YTimeJob]() override func viewDidLoad() { super.viewDidLoad() tableView.hideEmptyCells() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRow() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showCalendar", let vc = segue.destination as? YTimeCalendarViewController, let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { vc.job = jobs[indexPath.row] } } //MARK: UITableViewDataSource callbacks func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return jobs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath, identifier: "JobTitleCell") cell.textLabel?.text = jobs[indexPath.row].jobCodeDescription return cell } //MARK: Listeners @IBAction func doneTapped(_ sender: Any) { dismiss(animated: true) } }
apache-2.0
9895aeb8480aa1434a6f424ac237eb89
28.480769
194
0.674494
4.805643
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Common/ErrorHandling/AlertInfo.swift
1
3120
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI /// A type that describes an alert to be shown to the user. /// /// The alert info can be added to the view state bindings and used as an alert's `item`: /// ``` /// MyView /// .alert(item: $viewModel.alertInfo) { $0.alert } /// ``` struct AlertInfo<T: Hashable>: Identifiable { /// An identifier that can be used to distinguish one error from another. let id: T /// The alert's title. let title: String /// The alert's message (optional). var message: String? = nil /// The alert's primary button title and action. Defaults to an Ok button with no action. var primaryButton: (title: String, action: (() -> Void)?) = (VectorL10n.ok, nil) /// The alert's secondary button title and action. var secondaryButton: (title: String, action: (() -> Void)?)? = nil } extension AlertInfo where T == Int { /// Initialises the type with the title and message from an `NSError` along with the default Ok button. init?(error: NSError? = nil) { guard error?.domain != NSURLErrorDomain && error?.code != NSURLErrorCancelled else { return nil } id = error?.code ?? -1 title = error?.userInfo[NSLocalizedFailureReasonErrorKey] as? String ?? VectorL10n.error message = error?.userInfo[NSLocalizedDescriptionKey] as? String ?? VectorL10n.errorCommonMessage } } @available(iOS 13.0, *) extension AlertInfo { private var messageText: Text? { guard let message = message else { return nil } return Text(message) } /// Returns a SwiftUI `Alert` created from this alert info, using default button /// styles for both primary and (if set) secondary buttons. var alert: Alert { if let secondaryButton = secondaryButton { return Alert(title: Text(title), message: messageText, primaryButton: alertButton(for: primaryButton), secondaryButton: alertButton(for: secondaryButton)) } else { return Alert(title: Text(title), message: messageText, dismissButton: alertButton(for: primaryButton)) } } private func alertButton(for buttonParameters: (title: String, action: (() -> Void)?)) -> Alert.Button { guard let action = buttonParameters.action else { return .default(Text(buttonParameters.title)) } return .default(Text(buttonParameters.title), action: action) } }
apache-2.0
e32b1f099a0946eab3b67af3b6ccf18d
38.493671
108
0.645833
4.469914
false
false
false
false
vector-im/vector-ios
Riot/Modules/Secrets/Reset/SecretsResetCoordinator.swift
1
4285
// File created from ScreenTemplate // $ createScreen.sh Secrets/Reset SecretsReset /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class SecretsResetCoordinator: SecretsResetCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private var secretsResetViewModel: SecretsResetViewModelType private let secretsResetViewController: SecretsResetViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SecretsResetCoordinatorDelegate? // MARK: - Setup init(session: MXSession) { self.session = session let secretsResetViewModel = SecretsResetViewModel(session: self.session) let secretsResetViewController = SecretsResetViewController.instantiate(with: secretsResetViewModel) self.secretsResetViewModel = secretsResetViewModel self.secretsResetViewController = secretsResetViewController } // MARK: - Public methods func start() { self.secretsResetViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.secretsResetViewController } // MARK: - Private private func showAuthentication(with request: AuthenticatedEndpointRequest) { let reauthenticationCoordinatorParameters = ReauthenticationCoordinatorParameters(session: self.session, presenter: self.toPresentable(), title: nil, message: VectorL10n.secretsResetAuthenticationMessage, authenticatedEndpointRequest: request) let coordinator = ReauthenticationCoordinator(parameters: reauthenticationCoordinatorParameters) coordinator.delegate = self coordinator.start() self.add(childCoordinator: coordinator) } } // MARK: - SecretsResetViewModelCoordinatorDelegate extension SecretsResetCoordinator: SecretsResetViewModelCoordinatorDelegate { func secretsResetViewModel(_ viewModel: SecretsResetViewModelType, needsToAuthenticateWith request: AuthenticatedEndpointRequest) { self.showAuthentication(with: request) } func secretsResetViewModelDidResetSecrets(_ viewModel: SecretsResetViewModelType) { self.delegate?.secretsResetCoordinatorDidResetSecrets(self) } func secretsResetViewModelDidCancel(_ viewModel: SecretsResetViewModelType) { self.delegate?.secretsResetCoordinatorDidCancel(self) } } // MARK: - ReauthenticationCoordinatorDelegate extension SecretsResetCoordinator: ReauthenticationCoordinatorDelegate { func reauthenticationCoordinatorDidComplete(_ coordinator: ReauthenticationCoordinatorType, withAuthenticationParameters authenticationParameters: [String: Any]?) { self.secretsResetViewModel.process(viewAction: .authenticationInfoEntered(authenticationParameters ?? [:])) } func reauthenticationCoordinatorDidCancel(_ coordinator: ReauthenticationCoordinatorType) { self.remove(childCoordinator: coordinator) } func reauthenticationCoordinator(_ coordinator: ReauthenticationCoordinatorType, didFailWithError error: Error) { self.secretsResetViewModel.update(viewState: .error(error)) self.remove(childCoordinator: coordinator) } }
apache-2.0
0db9e691cbb3b27a93ffad5a7da47d5a
38.311927
168
0.684247
6.165468
false
false
false
false
Jakobeha/lAzR4t
lAzR4t macOS/GameViewController.swift
1
621
// // GameViewController.swift // lAzR4t macOS // // Created by Jakob Hain on 9/29/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import Cocoa import SpriteKit import GameplayKit class GameViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() let controller = GameController() // Present the scene let skView = self.view as! SKView skView.presentScene(controller.scene) skView.ignoresSiblingOrder = true skView.showsFPS = true skView.showsNodeCount = true } }
mit
f6f2bc752c53abeda294aad8efd338b4
19.666667
53
0.629032
4.806202
false
false
false
false
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/ViewControllers/Presentations/MarqueePresentation.swift
1
7019
// // MarqueePresentation.swift // Created by Pierluigi Cifani on 13/08/2018. // #if canImport(UIKit) import UIKit public enum MarqueePresentation { public struct AnimationProperties { public let sizing: Sizing public let animationDuration: TimeInterval public let kind: Kind public let roundCornerRadius: CGFloat? public enum Kind { // swiftlint:disable:this nesting case dismissal case presentation } public enum Sizing { // swiftlint:disable:this nesting case insetFromPresenter(UIEdgeInsets) case fixedSize(CGSize) case constrainingWidth(CGFloat, offset: CGPoint? = nil) } public init(sizing: Sizing = .constrainingWidth(300), animationDuration: TimeInterval = 0.6, kind: Kind, roundCornerRadius: CGFloat? = nil) { self.sizing = sizing self.animationDuration = animationDuration self.kind = kind self.roundCornerRadius = roundCornerRadius } } /** This method will return a `UIViewControllerAnimatedTransitioning` with default `AnimationProperties` for the given `Kind` - Parameter kind: A value that represents the kind of transition you need. */ static public func transitioningFor(kind: AnimationProperties.Kind) -> UIViewControllerAnimatedTransitioning { return transitioningFor(properties: MarqueePresentation.AnimationProperties(kind: kind)) } /** This method will return a `UIViewControllerAnimatedTransitioning` with the given `AnimationProperties` - Parameter properties: The properties for the desired animation. */ static public func transitioningFor(properties: AnimationProperties) -> UIViewControllerAnimatedTransitioning { switch properties.kind { case .dismissal: return MarqueeDismissController(properties: properties) case .presentation: return MarqueePresentationController(properties: properties) } } } private class MarqueePresentationController: NSObject, UIViewControllerAnimatedTransitioning { let properties: MarqueePresentation.AnimationProperties init(properties: MarqueePresentation.AnimationProperties) { self.properties = properties super.init() } // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return properties.animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toViewController = transitionContext.viewController(forKey: .to) else { return } let containerView = transitionContext.containerView let duration = self.transitionDuration(using: transitionContext) // Add background view let bgView = PresentationBackgroundView(frame: containerView.bounds) bgView.context = .init(parentViewController: toViewController, position: nil, offset: nil) bgView.tag = Constants.BackgroundViewTag containerView.addSubview(bgView) // Add VC's view let vcView = toViewController.view! containerView.addSubview(vcView) if let radius = self.properties.roundCornerRadius { vcView.roundCorners(radius: radius) } switch self.properties.sizing { case .fixedSize(let size): vcView.centerInSuperview() NSLayoutConstraint.activate([ vcView.widthAnchor.constraint(equalToConstant: size.width), vcView.heightAnchor.constraint(equalToConstant: size.height), ]) case .insetFromPresenter(let edges): vcView.pinToSuperview(withEdges: edges) case .constrainingWidth(let width, let offset): guard let calculable = toViewController as? IntrinsicSizeCalculable else { fatalError() } let intrinsicHeight = calculable.heightConstrainedTo(width: width) // This makes sure that the height of the // view fits in the current context let height = min(intrinsicHeight, containerView.bounds.height - 20) NSLayoutConstraint.activate([ vcView.widthAnchor.constraint(equalToConstant: width), vcView.heightAnchor.constraint(equalToConstant: height), vcView.centerXAnchor.constraint(equalTo: vcView.superview!.centerXAnchor, constant: offset?.x ?? 0), vcView.centerYAnchor.constraint(equalTo: vcView.superview!.centerYAnchor, constant: offset?.y ?? 0) ]) vcView.translatesAutoresizingMaskIntoConstraints = false } toViewController.view.alpha = 0.0 bgView.alpha = 0.0 //Start slide up animation UIView.animate( withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5 / 1.0, options: [], animations: {() -> Void in toViewController.view.alpha = 1.0 bgView.alpha = 1.0 }, completion: {(_ finished: Bool) -> Void in transitionContext.completeTransition(true) }) } } private class MarqueeDismissController: NSObject, UIViewControllerAnimatedTransitioning { let properties: MarqueePresentation.AnimationProperties init(properties: MarqueePresentation.AnimationProperties) { self.properties = properties super.init() } // MARK: UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return properties.animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let fromViewController = transitionContext.viewController(forKey: .from) else { return } guard let bgView = containerView.subviews.first(where: { $0.tag == Constants.BackgroundViewTag}) else { return } UIView.animate( withDuration: properties.animationDuration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5 / 1.0, options: [], animations: {() -> Void in bgView.alpha = 0.0 fromViewController.view.alpha = 0.0 }, completion: {(_ finished: Bool) -> Void in fromViewController.view.removeFromSuperview() transitionContext.completeTransition(true) }) } } private enum Constants { static let BackgroundViewTag = 79 } #endif
mit
d45affbaf3f7b906f73bdea7674fbe54
37.994444
149
0.64995
5.824896
false
false
false
false
roambotics/swift
test/SILOptimizer/Inputs/cross-module/default-module.swift
2
792
import Submodule import PrivateCModule public func incrementByThree(_ x: Int) -> Int { return incrementByOne(x) + 2 } public func incrementByThreeWithCall(_ x: Int) -> Int { return incrementByOneNoCMO(x) + 2 } public func submoduleKlassMember() -> Int { let k = SubmoduleKlass() return k.i } public final class ModuleKlass { public var i: Int public init() { i = 27 } } public func moduleKlassMember() -> Int { let k = ModuleKlass() return k.i } public struct ModuleStruct { public static var publicFunctionPointer: (Int) -> (Int) = incrementByThree public static var privateFunctionPointer: (Int) -> (Int) = { $0 } } public func callPrivateCFunc() -> Int { return Int(privateCFunc()) } public func usePrivateCVar() -> Int { return Int(privateCVar); }
apache-2.0
d56ff3f17f737e2a9ccb5167a4e73f2a
17.857143
76
0.689394
3.52
false
false
false
false
LY-Coder/LYPlayer
LYPlayerExample/LYPlayer/LYPlayButton.swift
1
1375
// // LYPlayButton.swift // // Copyright © 2017年 ly_coder. All rights reserved. // // GitHub地址:https://github.com/LY-Coder/LYPlayer // import UIKit class LYPlayButton: UIControl { // 播放状态 enum PlayStatus { case play // 播放 case pause // 暂停 case stop } lazy var playStatusIcon: UIImageView = { let playStatusIcon = UIImageView() playStatusIcon.contentMode = .scaleAspectFit playStatusIcon.image = UIImage(named: "LYPlayer.bundle/LYPlayer_pause") return playStatusIcon }() // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) addSubview(playStatusIcon) playStatusIcon.snp.makeConstraints { (make) in make.size.equalTo(20) make.center.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var playStatus: PlayStatus = .pause { willSet { switch newValue { case .play: playStatusIcon.image = UIImage.init("LYPlayer_play") case .pause: playStatusIcon.image = UIImage.init("LYPlayer_pause") case .stop: break } } } }
mit
062263f513629c2775bb6266dbaff98d
23.107143
79
0.551111
4.5
false
false
false
false
tlax/GaussSquad
GaussSquad/View/LinearEquations/Plot/VLinearEquationsPlotMenuCellEquation.swift
1
2197
import UIKit class VLinearEquationsPlotMenuCellEquation:VLinearEquationsPlotMenuCell { private weak var imageView:UIImageView! private weak var label:UILabel! private let kImageWidth:CGFloat = 40 override init(frame:CGRect) { super.init(frame:frame) let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.image = #imageLiteral(resourceName: "assetGenericPoint").withRenderingMode( UIImageRenderingMode.alwaysTemplate) self.imageView = imageView let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.font = UIFont.bold(size:16) label.textColor = UIColor.black self.label = label addSubview(imageView) addSubview(label) NSLayoutConstraint.equalsVertical( view:imageView, toView:self) NSLayoutConstraint.leftToLeft( view:imageView, toView:self) NSLayoutConstraint.width( view:imageView, constant:kImageWidth) NSLayoutConstraint.equalsVertical( view:label, toView:self) NSLayoutConstraint.leftToRight( view:label, toView:imageView) NSLayoutConstraint.rightToRight( view:label, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: public override func config(model:MLinearEquationsPlotMenuItem) { super.config(model:model) guard let model:MLinearEquationsPlotMenuItemEquation = model as? MLinearEquationsPlotMenuItemEquation else { return } imageView.tintColor = model.color label.attributedText = model.title } }
mit
67b58f1057988915ef20e41f88bc256a
27.532468
107
0.619936
5.937838
false
false
false
false
rugheid/Swift-MathEagle
MathEagle/Permutation/Parity.swift
1
2549
// // Parity.swift // MathEagle // // Created by Rugen Heidbuchel on 01/06/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Foundation /** Defines either even or odd. */ public enum Parity: ExpressibleByIntegerLiteral, Addable, Subtractable, Multiplicable { /// Denotes an even parity. case even /// Denotes an odd parity. case odd // MARK: Initialisers /** Creates a parity from the given integer literal. */ public init(integerLiteral value: IntegerLiteralType) { self = Parity.fromMod2Remainder(value) } /** Returns a parity from the value modulo 2. */ public static func fromMod2Remainder(_ value: Int) -> Parity { return value % 2 == 0 ? .even : .odd } /** Returns a parity from the sign of the value. :exception: Throws an exception when the given value equals zero. */ public static func fromSign(_ value: Int) -> Parity { if value == 0 { NSException(name: NSExceptionName(rawValue: "Sign can't be 0."), reason: "The sign to initialise from can't be 0.", userInfo: nil).raise() } return value > 0 ? .even : .odd } // MARK: Properties /** Returns the remainder modulo 2. This is 0 when even and 1 when odd. */ public var mod2Remainder: Int { return self == .even ? 0 : 1 } /** Returns the sign of the parity. This is 1 when even and -1 when odd. */ public var sign: Int { return self == .even ? 1 : -1 } } // MARK: Addable /** Returns the sum of the two given parities. When they are equal `.Even` is returned, otherwise `.Odd`. */ public func + (left: Parity, right: Parity) -> Parity { return left == right ? .even : .odd } public func += (left: inout Parity, right: Parity) { left = left + right } // MARK: Subtractable /** Returns the difference of the two given parities. When they are equal `.Even` is returned, otherwise `.Odd`. */ public func - (left: Parity, right: Parity) -> Parity { return left + right } // MARK: Multiplicable /** Returns the product of the two given parities. When both parities are `.Odd`, `.Odd` is returned, otherwise `.Even`. */ public func * (left: Parity, right: Parity) -> Parity { return left == .odd && right == .odd ? .odd : .even }
mit
9061bc7f94a391536989f8e76c004848
20.066116
150
0.571989
4.084936
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PeerChannelMemberCategoriesContextsManager.swift
1
18560
// // PeerChannelMemberCategoriesContextsManager.swift // Telegram // // Created by Mikhail Filimonov on 02/01/2019. // Copyright © 2019 Telegram. All rights reserved. // import Foundation import Postbox import TelegramCore import SwiftSignalKit enum PeerChannelMemberContextKey: Equatable, Hashable { case recent case recentSearch(String) case mentions(threadId: MessageId?, query: String?) case admins(String?) case contacts(String?) case bots(String?) case restrictedAndBanned(String?) case restricted(String?) case banned(String?) } private final class PeerChannelMembersOnlineContext { let subscribers = Bag<(Int32) -> Void>() let disposable: Disposable var value: Int32? var emptyTimer: SwiftSignalKit.Timer? init(disposable: Disposable) { self.disposable = disposable } } private final class PeerChannelMemberCategoriesContextsManagerImpl { fileprivate var contexts: [PeerId: PeerChannelMemberCategoriesContext] = [:] fileprivate var onlineContexts: [PeerId: PeerChannelMembersOnlineContext] = [:] fileprivate var replyThreadHistoryContexts: [MessageId: ReplyThreadHistoryContext] = [:] fileprivate let engine: TelegramEngine fileprivate let account: Account init(_ engine: TelegramEngine, account: Account) { self.engine = engine self.account = account } func getContext(peerId: PeerId, key: PeerChannelMemberContextKey, requestUpdate: Bool, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl) { if let current = self.contexts[peerId] { return current.getContext(key: key, requestUpdate: requestUpdate, updated: updated) } else { var becameEmptyImpl: ((Bool) -> Void)? let context = PeerChannelMemberCategoriesContext(engine: engine, account: account, peerId: peerId, becameEmpty: { value in becameEmptyImpl?(value) }) becameEmptyImpl = { [weak self, weak context] value in assert(Queue.mainQueue().isCurrent()) if let strongSelf = self { if let current = strongSelf.contexts[peerId], current === context { strongSelf.contexts.removeValue(forKey: peerId) } } } self.contexts[peerId] = context return context.getContext(key: key, requestUpdate: requestUpdate, updated: updated) } } func recentOnline(peerId: PeerId, updated: @escaping (Int32) -> Void) -> Disposable { let context: PeerChannelMembersOnlineContext if let current = self.onlineContexts[peerId] { context = current } else { let disposable = MetaDisposable() context = PeerChannelMembersOnlineContext(disposable: disposable) self.onlineContexts[peerId] = context let signal = ( engine.peers.chatOnlineMembers(peerId: peerId) |> then( .complete() |> delay(30.0, queue: .mainQueue()) ) ) |> restart disposable.set(signal.start(next: { [weak context] value in guard let context = context else { return } context.value = value for f in context.subscribers.copyItems() { f(value) } })) } if let emptyTimer = context.emptyTimer { emptyTimer.invalidate() context.emptyTimer = nil } let index = context.subscribers.add({ next in updated(next) }) updated(context.value ?? 0) return ActionDisposable { [weak self, weak context] in Queue.mainQueue().async { guard let strongSelf = self else { return } if let current = strongSelf.onlineContexts[peerId], let context = context, current === context { current.subscribers.remove(index) if current.subscribers.isEmpty { if current.emptyTimer == nil { let timer = SwiftSignalKit.Timer(timeout: 60.0, repeat: false, completion: { [weak context] in if let current = strongSelf.onlineContexts[peerId], let context = context, current === context { if current.subscribers.isEmpty { strongSelf.onlineContexts.removeValue(forKey: peerId) current.disposable.dispose() } } }, queue: Queue.mainQueue()) current.emptyTimer = timer timer.start() } } } } } } func loadMore(peerId: PeerId, control: PeerChannelMemberCategoryControl) { if let context = self.contexts[peerId] { context.loadMore(control) } } } final class PeerChannelMemberCategoriesContextsManager { private let impl: QueueLocalObject<PeerChannelMemberCategoriesContextsManagerImpl> private let engine: TelegramEngine private let account: Account init(_ engine: TelegramEngine, account: Account) { self.engine = engine self.account = account self.impl = QueueLocalObject(queue: Queue.mainQueue(), generate: { return PeerChannelMemberCategoriesContextsManagerImpl(engine, account: account) }) } func loadMore(peerId: PeerId, control: PeerChannelMemberCategoryControl?) { if let control = control { self.impl.with { impl in impl.loadMore(peerId: peerId, control: control) } } } private func getContext(peerId: PeerId, key: PeerChannelMemberContextKey, requestUpdate: Bool, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { assert(Queue.mainQueue().isCurrent()) return self.impl.syncWith({ impl in return impl.getContext(peerId: peerId, key: key, requestUpdate: requestUpdate, updated: updated) }) } func transferOwnership(peerId: PeerId, memberId: PeerId, password: String) -> Signal<Void, ChannelOwnershipTransferError> { return engine.peers.updateChannelOwnership(channelId: peerId, memberId: memberId, password: password) |> map(Optional.init) |> deliverOnMainQueue |> beforeNext { [weak self] results in if let strongSelf = self, let results = results { strongSelf.impl.with { impl in for (contextPeerId, context) in impl.contexts { if peerId == contextPeerId { context.replayUpdates(results.map { ($0.0, $0.1, nil) }) } } } } } |> mapToSignal { _ -> Signal<Void, ChannelOwnershipTransferError> in return .complete() } } func externallyAdded(peerId: PeerId, participant: RenderedChannelParticipant) { self.impl.with { impl in for (contextPeerId, context) in impl.contexts { if contextPeerId == peerId { context.replayUpdates([(nil, participant, nil)]) } } } } func mentions(peerId: PeerId, threadMessageId: MessageId?, searchQuery: String? = nil, requestUpdate: Bool = true, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { let key: PeerChannelMemberContextKey = .mentions(threadId: threadMessageId, query: searchQuery) return self.getContext(peerId: peerId, key: key, requestUpdate: requestUpdate, updated: updated) } func recent(peerId: PeerId, searchQuery: String? = nil, requestUpdate: Bool = true, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { let key: PeerChannelMemberContextKey if let searchQuery = searchQuery { key = .recentSearch(searchQuery) } else { key = .recent } return self.getContext(peerId: peerId, key: key, requestUpdate: requestUpdate, updated: updated) } func recentOnline(peerId: PeerId) -> Signal<Int32, NoError> { return Signal { [weak self] subscriber in guard let strongSelf = self else { subscriber.putNext(0) subscriber.putCompletion() return EmptyDisposable } let disposable = strongSelf.impl.syncWith({ impl -> Disposable in return impl.recentOnline(peerId: peerId, updated: { value in subscriber.putNext(value) }) }) return disposable ?? EmptyDisposable } |> runOn(Queue.mainQueue()) } func recentOnlineSmall(peerId: PeerId) -> Signal<Int32, NoError> { let account = self.account return Signal { [weak self] subscriber in guard let strongSelf = self else { return EmptyDisposable } var previousIds: Set<PeerId>? let statusesDisposable = MetaDisposable() let disposableAndControl = self?.recent(peerId: peerId, updated: { state in var idList: [PeerId] = [] for item in state.list { idList.append(item.peer.id) if idList.count >= 200 { break } } let updatedIds = Set(idList) if previousIds != updatedIds { previousIds = updatedIds let key: PostboxViewKey = .peerPresences(peerIds: updatedIds) statusesDisposable.set((strongSelf.account.postbox.combinedView(keys: [key]) |> map { view -> Int32 in var count: Int32 = 0 let timestamp = CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970 if let presences = (view.views[key] as? PeerPresencesView)?.presences { for (_, presence) in presences { if let presence = presence as? TelegramUserPresence { let networkTime = account.network.globalTime > 0 ? account.network.globalTime - timestamp : 0 let relativeStatus = relativeUserPresenceStatus(presence, timeDifference: networkTime, relativeTo: Int32(timestamp)) sw: switch relativeStatus { case let .online(at: until): if until > Int32(timestamp) { count += 1 } default: break sw } } } } return count } |> distinctUntilChanged |> deliverOnMainQueue).start(next: { count in subscriber.putNext(count) })) } }) return ActionDisposable { disposableAndControl?.0.dispose() statusesDisposable.dispose() } } |> runOn(Queue.mainQueue()) } func admins(peerId: PeerId, searchQuery: String? = nil, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { return self.getContext(peerId: peerId, key: .admins(searchQuery), requestUpdate: true, updated: updated) } func restricted(peerId: PeerId, searchQuery: String? = nil, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { return self.getContext(peerId: peerId, key: .restricted(searchQuery), requestUpdate: true, updated: updated) } func contacts(peerId: PeerId, searchQuery: String? = nil, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { return self.getContext(peerId: peerId, key: .contacts(searchQuery), requestUpdate: true, updated: updated) } func banned(peerId: PeerId, searchQuery: String? = nil, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { return self.getContext(peerId: peerId, key: .banned(searchQuery), requestUpdate: true, updated: updated) } func restrictedAndBanned(peerId: PeerId, searchQuery: String? = nil, updated: @escaping (ChannelMemberListState) -> Void) -> (Disposable, PeerChannelMemberCategoryControl?) { return self.getContext(peerId: peerId, key: .restrictedAndBanned(searchQuery), requestUpdate: true, updated: updated) } func updateMemberBannedRights(peerId: PeerId, memberId: PeerId, bannedRights: TelegramChatBannedRights?) -> Signal<Void, NoError> { return engine.peers.updateChannelMemberBannedRights(peerId: peerId, memberId: memberId, rights: bannedRights) |> deliverOnMainQueue |> beforeNext { [weak self] (previous, updated, isMember) in if let strongSelf = self { strongSelf.impl.with { impl in for (contextPeerId, context) in impl.contexts { if peerId == contextPeerId { context.replayUpdates([(previous, updated, isMember)]) } } } } } |> mapToSignal { _ -> Signal<Void, NoError> in return .complete() } } func updateMemberAdminRights(peerId: PeerId, memberId: PeerId, adminRights: TelegramChatAdminRights?, rank: String?) -> Signal<PeerId, NoError> { return engine.peers.updateChannelAdminRights(peerId: peerId, adminId: memberId, rights: adminRights, rank: rank) |> map(Optional.init) |> `catch` { _ -> Signal<(ChannelParticipant?, RenderedChannelParticipant)?, NoError> in return .single(nil) } |> deliverOnMainQueue |> beforeNext { [weak self] result in if let strongSelf = self, let (previous, updated) = result { strongSelf.impl.with { impl in for (contextPeerId, context) in impl.contexts { if peerId == contextPeerId { context.replayUpdates([(previous, updated, nil)]) } } } } } |> mapToSignal { _ -> Signal<PeerId, NoError> in return .single(memberId) } } func addMember(peerId: PeerId, memberId: PeerId) -> Signal<Void, NoError> { return engine.peers.addChannelMember(peerId: peerId, memberId: memberId) |> map(Optional.init) |> `catch` { _ -> Signal<(ChannelParticipant?, RenderedChannelParticipant)?, NoError> in return .single(nil) } |> deliverOnMainQueue |> beforeNext { [weak self] result in if let strongSelf = self, let (previous, updated) = result { strongSelf.impl.with { impl in for (contextPeerId, context) in impl.contexts { if peerId == contextPeerId { context.replayUpdates([(previous, updated, nil)]) } } } } } |> mapToSignal { _ -> Signal<Void, NoError> in return .complete() } } func addMembers(peerId: PeerId, memberIds: [PeerId]) -> Signal<[PeerId], AddChannelMemberError> { let signals: [Signal<(ChannelParticipant?, RenderedChannelParticipant)?, AddChannelMemberError>] = memberIds.map({ memberId in return engine.peers.addChannelMember(peerId: peerId, memberId: memberId) |> map(Optional.init) |> `catch` { error -> Signal<(ChannelParticipant?, RenderedChannelParticipant)?, AddChannelMemberError> in if memberIds.count == 1 { return .fail(error) } else { return .single(nil) } } }) return combineLatest(signals) |> deliverOnMainQueue |> beforeNext { [weak self] results in if let strongSelf = self { strongSelf.impl.with { impl in for result in results { if let (previous, updated) = result { for (contextPeerId, context) in impl.contexts { if peerId == contextPeerId { context.replayUpdates([(previous, updated, nil)]) } } } } } } } |> mapToSignal { values -> Signal<[PeerId], AddChannelMemberError> in return .single(values.compactMap { $0?.1.peer.id }) } } func replyThread(account: Account, messageId: MessageId) -> Signal<MessageHistoryViewExternalInput, NoError> { return .complete() } }
gpl-2.0
6184e5a3a2ed834f6129eb84a51573bf
42.874704
224
0.538122
5.497334
false
false
false
false
cojoj/Find-My-Luggage
Find My Luggage/Find My Luggage/BeaconListVC.swift
1
3297
// // BeaconListVC.swift // Find My Luggage // // Created by Tomek Cejner on 16/11/14. // // import UIKit class BeaconListVC: UITableViewController { var beaconManager = BeaconManager() override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() self.tableView.reloadData() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return beaconManager.luggageBeacons.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BeaconCell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = beaconManager.luggageBeacons[indexPath.row].name return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source beaconManager.delete(beaconManager.luggageBeacons[indexPath.row]) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
7d91167f5fdc2fc03a0f54ff4b853ab4
33.34375
157
0.694268
5.495
false
false
false
false
OctMon/OMExtension
OMExtensionDemo/OMExtensionDemo/OMApplication/JumpOtherTVC.swift
1
3118
// // JumpOtherTVC.swift // OMExtensionDemo // // Created by OctMon on 2016/11/8. // Copyright © 2016年 OctMon. All rights reserved. // import UIKit class JumpOtherTVC: BaseTVC { let dataSource = [ ("检测是否安装微信", "canOpenWeixin"), ("打开微信", "openWeixin"), ("打电话", "callTelephone"), ("跳转到appStroe微信应用详情", "openAppStoreDetails"), ("跳转到appStroe微信应用评价", "openAppStoreReviews"), ("应用在appStroe中的地址", "getAppStoreURL"), ("应用在appStroe中的详情json的请求地址", "getAppStoreLookupURL"), ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @objc func showAlert(title: String) { let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil)) alert.om.show() } @objc func canOpenWeixin() { let canOpen = UIApplication.OM.canOpenURL(string: "weixin://") showAlert(title: "\(canOpen)") } @objc func openWeixin() { UIApplication.OM.openURL(string: "weixin://") } @objc func callTelephone() { UIApplication.OM.call(telephone: "112") } @objc func openAppStoreDetails() { UIApplication.OM.openAppStoreDetails(id: 414478124) } @objc func openAppStoreReviews() { UIApplication.OM.openAppStoreReviews(id: 414478124) } @objc func getAppStoreURL() { showAlert(title: UIApplication.OM.getAppStoreURL(id: 414478124)) } @objc func getAppStoreLookupURL() { showAlert(title: UIApplication.OM.getAppStoreLookupURL(id: 414478124)) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.omClassName, for: indexPath) cell.textLabel?.text = dataSource[(indexPath as NSIndexPath).row].0 return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) perform(Selector(dataSource[(indexPath as NSIndexPath).row].1), with: nil, afterDelay: 0) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
5c04a4e2e99d17b2056431eb7856d552
27.140187
109
0.619728
4.569044
false
false
false
false
bitjammer/swift
validation-test/compiler_crashers_fixed/00216-swift-unqualifiedlookup-unqualifiedlookup.swift
65
1275
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck ({}) var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ } } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) - = b =b as c=b func q(v: h) -> <r>(() -> r) -> h { n { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } protocol p { } protocol m : p { } protocol v : p { } protocol m { v = m } func s<s : m, v : m u v.v == s> (m: v) { } func s<v : m u v.v == v> (m: v) { } s( { ({}) } t func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> fu ^(a: Bo } }
apache-2.0
176cd3480586c6464111a1607dda9e3f
15.776316
79
0.49098
2.509843
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/HTMapsViewController.swift
1
4639
// // HTMapsViewController.swift // hackertracker // // Created by Seth Law on 5/11/15. // Copyright (c) 2015 Beezle Labs. All rights reserved. // import PDFKit import UIKit class HTMapsViewController: UIViewController, UIScrollViewDelegate { @IBOutlet private var mapSwitch: UISegmentedControl! var mapViews: [PDFView] = [] var mapView: PDFView? var roomDimensions: CGRect? var timeOfDay: TimeOfDay? var hotel: String? override func viewDidLoad() { super.viewDidLoad() mapSwitch.backgroundColor = .black // mapSwitch.tintColor = .gray mapSwitch.selectedSegmentTintColor = .white mapSwitch.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .selected) mapSwitch.setTitleTextAttributes([.foregroundColor: UIColor.lightGray], for: .normal) // self.navigationController?.navigationBar.backgroundColor = .black mapSwitch.removeAllSegments() var idx = 0 let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileManager = FileManager.default // let storageRef = FSConferenceDataController.shared.storage.reference() for map in AnonymousSession.shared.currentConference.maps { let path = "\(AnonymousSession.shared.currentConference.code)/\(map.file)" let mLocal = docDir.appendingPathComponent(path) // let mRef = storageRef.child(path) mapSwitch.insertSegment(withTitle: map.name, at: idx, animated: false) defer { idx += 1 } guard fileManager.fileExists(atPath: mLocal.path) else { NSLog("Don't have a local copy of the file at \(mLocal.path)") continue } let pdfView = PDFView() pdfView.backgroundColor = UIColor.black pdfView.autoScales = true pdfView.translatesAutoresizingMaskIntoConstraints = false pdfView.document = PDFDocument(url: mLocal) view.addSubview(pdfView) pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true mapViews.append(pdfView) pdfView.isHidden = true pdfView.isUserInteractionEnabled = false NSLog("Adding PDFView for \(mLocal.path)") } mapSwitch.apportionsSegmentWidthsByContent = true mapSwitch.sizeToFit() goToHotel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if hotel != nil { goToHotel() } applyDoneButtonIfNeeded() } func goToHotel() { var selectedIndex = 0 if let hotel = hotel { for index in 0..<mapSwitch.numberOfSegments { if let title = mapSwitch.titleForSegment(at: index) { if title.contains(hotel) { selectedIndex = index } } } } mapSwitch.selectedSegmentIndex = selectedIndex mapChanged(mapSwitch) } func applyDoneButtonIfNeeded() { guard self.navigationController?.parent as? HTHamburgerMenuViewController != nil else { let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed)) doneButton.tintColor = .white navigationItem.rightBarButtonItem = doneButton return } } @objc func doneButtonPressed() { self.dismiss(animated: true) } @IBAction private func mapChanged(_ sender: UISegmentedControl) { guard !mapViews.isEmpty else { return } for mapView in mapViews { mapView.isHidden = true mapView.isUserInteractionEnabled = false } /* for index in 0..<AnonymousSession.shared.currentConference.maps.count { mapViews[index].isHidden = true mapViews[index].isUserInteractionEnabled = false } */ NSLog("switching to segment \(sender.titleForSegment(at: sender.selectedSegmentIndex) ?? "")") mapViews[sender.selectedSegmentIndex].isHidden = false mapViews[sender.selectedSegmentIndex].isUserInteractionEnabled = true } }
gpl-2.0
34fee6740bda03bd51492ef1750df1c0
35.81746
124
0.641949
5.277588
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI/JsonAPI.swift
1
5049
// // JsonAPI.swift // VBVMI // // Created by Thomas Carey on 31/01/16. // Copyright © 2016 Tom Carey. All rights reserved. // import Foundation import Moya public enum JsonAPI { case core case lesson(identifier: String) case articlesP case articles case channels case events case qa case qAp } extension JsonAPI : TargetType { public var headers: [String : String]? { return nil } public var base: String { return "https://www.versebyverseministry.org/core/" } public var baseURL: URL { return URL(string: base)! } public var path: String { switch self { case .core: return "json" case .lesson(let identifier): return "json-lessons/\(identifier)" case .articlesP: return "json-articlesp" case .articles: return "json-articles" case .channels: return "json-channels" case .events: return "json-events" case .qa: return "json-qa" case .qAp: return "json-qap" } } public var parameters: [String: Any]? { switch self { default: return nil } } public var method: Moya.Method { switch self { default: return .get } } public var sampleData: Data { switch self { case .core: return stubbedResponse("core") case .lesson: return stubbedResponse("lesson") case .articlesP: return stubbedResponse("articlesP") case .articles: return stubbedResponse("articles") case .channels: return stubbedResponse("channels") case .events: return stubbedResponse("events") case .qa: return stubbedResponse("qa") case .qAp: return stubbedResponse("qap") } } public var task: Task { return .requestPlain } public var parameterEncoding: Moya.ParameterEncoding { if method == .get { return URLEncoding.default } switch self { default: return JSONEncoding.default } } } public func endpointResolver() -> ((_ endpoint: Endpoint<JsonAPI>) -> (URLRequest)) { return { (endpoint: Endpoint<JsonAPI>) -> (URLRequest) in let request: URLRequest = try! endpoint.urlRequest() return request } } public struct Provider { fileprivate static var endpointsClosure = { (target: JsonAPI) -> Endpoint<JsonAPI> in let sampleResponse : Endpoint.SampleResponseClosure = { return EndpointSampleResponse.networkResponse(200, target.sampleData) } var endpoint : Endpoint<JsonAPI> = Endpoint(url: url(target), sampleResponseClosure: sampleResponse, method: target.method, task: target.task, httpHeaderFields: nil) switch target { default: return endpoint } } public typealias ProviderRequest = ()->() public static func APIKeysBasedStubBehaviour(_ target: JsonAPI) -> Moya.StubBehavior { switch target { default: #if DEBUG return .never// .delayed(seconds: 0.2)// #else return .never #endif } } fileprivate static var ongoingRequestCount = 0 { didSet { #if os(iOS) UIApplication.shared.isNetworkActivityIndicatorVisible = ongoingRequestCount > 0 #endif } } public static func DefaultProvider() -> MoyaProvider<JsonAPI> { let networkActivityPlugin = NetworkActivityPlugin { (change, target) -> () in DispatchQueue.main.async { switch change { case .began: ongoingRequestCount += 1 case .ended: ongoingRequestCount -= 1 } } } let provider = MoyaProvider<JsonAPI>(endpointClosure: endpointsClosure, stubClosure: APIKeysBasedStubBehaviour, plugins: [networkActivityPlugin]) return provider } fileprivate struct SharedProvider { static var instance = Provider.DefaultProvider() } public static var sharedProvider: MoyaProvider<JsonAPI> { get { return SharedProvider.instance } set (newSharedProvider) { SharedProvider.instance = newSharedProvider } } } private func stubbedResponse(_ filename: String) -> Data! { @objc class TestClass : NSObject { } let bundle = Bundle(for: TestClass.self) if let path = bundle.path(forResource: filename, ofType: "json") { return (try? Data(contentsOf: URL(fileURLWithPath: path))) } return Data() } public func url(_ route: TargetType) -> String { return route.baseURL.appendingPathComponent(route.path).absoluteString }
mit
69210af27971768d31e0bd49bbfb25d3
25.851064
174
0.572306
4.953876
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Exchange/Controller/AlertViewController.swift
4
8745
// // AlertViewController.swift // iOSStar // // Created by MONSTER on 2017/5/27. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit // 屏幕宽高 private var kSCREEN_W : CGFloat = UIScreen.main.bounds.size.width private var kSCREEN_H : CGFloat = UIScreen.main.bounds.size.height class AlertViewController: UIViewController { // 对这个强引用 var strongSelf:AlertViewController? // 按钮动作 var completeAction:((_ button: UIButton) -> Void)? = nil // 内部控件 var contentView = UIView() var closeButton = UIButton() var picImageView = UIImageView() var titleLabel = UILabel() var subTitleTextView = UITextView(); var completeButton = UIButton() init() { super.init(nibName: nil, bundle: nil) self.view.frame = UIScreen.main.bounds self.view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0.7) self.view.addSubview(contentView) //强引用 不然按钮点击不能执行 strongSelf = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("AlertViewController --- deinit "); } // MARK : - 初始化UI fileprivate func setupContentView() { contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0); contentView.layer.cornerRadius = 3.0 contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 view.addSubview(contentView); contentView.addSubview(closeButton) contentView.addSubview(picImageView) contentView.addSubview(titleLabel) contentView.addSubview(subTitleTextView) contentView.addSubview(completeButton) } //关闭按钮 fileprivate func setupCloseButton() { closeButton.setImage((UIImage (named:"tangchuang_close")), for: .normal) self.closeButton.addTarget(self, action: #selector(closeButtonClick(_ :)), for: .touchUpInside); } // 图片 fileprivate func setupPicImageView() { picImageView.contentMode = .scaleAspectFit } // 标题 fileprivate func setupTitleLabel() { titleLabel.text = "" titleLabel.numberOfLines = 1 titleLabel.textAlignment = .center titleLabel.textColor = UIColor.colorFromRGB(0x333333) titleLabel.font = UIFont.systemFont(ofSize: 16.0) } // 文本 fileprivate func setupSubTitleTextView() { subTitleTextView.text = "" // subTitleTextView.textAlignment = .center subTitleTextView.font = UIFont.systemFont(ofSize: 14.0) // subTitleTextView.textColor = UIColor.colorFromRGB(0x999999) subTitleTextView.isEditable = false subTitleTextView.isScrollEnabled = false subTitleTextView.isSelectable = false } // 按钮 fileprivate func setupCompleteButton(){ completeButton.backgroundColor = UIColor.colorFromRGB(0x8C0808) completeButton.titleLabel?.textColor = UIColor.colorFromRGB(0xFAFAFA) completeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) completeButton.addTarget(self, action: #selector(completeButtonButtonClick(_ :)), for: .touchUpInside) } } // MARK: -布局 extension AlertViewController { fileprivate func resizeAndLayout() { let mainScreenBounds = UIScreen.main.bounds self.view.frame.size = mainScreenBounds.size var kLEFT_MARGIN :CGFloat = 0 var kTOP_MARGIN :CGFloat = 0 if kSCREEN_H == 568 { kLEFT_MARGIN = 19 kTOP_MARGIN = 59 } else { kLEFT_MARGIN = 37 kTOP_MARGIN = 118 } // let kLEFT_MARGIN :CGFloat = kSCREEN_W * 0.1 // let kTOP_MARGIN : CGFloat = kSCREEN_H * 0.085 contentView.frame = CGRect(x: kLEFT_MARGIN, y: kTOP_MARGIN, width: kSCREEN_W - (kLEFT_MARGIN * 2) , height: kSCREEN_H - (kTOP_MARGIN * 2)) closeButton.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(16) make.right.equalToSuperview().offset(-16) make.width.height.equalTo(16) } // picImageView.frame = CGRect(x: 69, y: 52, width: 164, height: 164) picImageView.snp.makeConstraints { (make) in make.top.equalTo(contentView.snp.top).offset(50) make.centerX.equalToSuperview() make.width.equalToSuperview() make.height.equalTo(160) } titleLabel.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.top.equalTo(picImageView.snp.bottom).offset(20) } subTitleTextView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.top.equalTo(titleLabel.snp.bottom).offset(25) } completeButton.snp.makeConstraints { (make) in make.left.bottom.right.equalTo(contentView).offset(0) make.height.equalTo(51) } contentView.transform = CGAffineTransform(translationX: 0, y: -kSCREEN_H / 2) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.contentView.transform = CGAffineTransform.identity }, completion: nil) } } // MARK: - show extension AlertViewController { // show func showAlertVc(imageName : String , titleLabelText : String , subTitleText : String , completeButtonTitle : String , action:@escaping ((_ completeButton: UIButton) -> Void)) { let window: UIWindow = UIApplication.shared.keyWindow! window.addSubview(view) window.bringSubview(toFront: view) view.frame = window.bounds completeAction = action; setupContentView() setupCloseButton() setupPicImageView() setupTitleLabel() setupSubTitleTextView() setupCompleteButton() self.picImageView.image = UIImage(named: "\(imageName)") self.titleLabel.text = titleLabelText // 设置行间距? let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 10 paragraphStyle.alignment = .center let attributes = [NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName:UIColor.colorFromRGB(0x999999)] self.subTitleTextView.attributedText = NSAttributedString(string: subTitleText, attributes: attributes) // self.subTitleTextView.text = subTitleText; self.completeButton.setTitle("\(completeButtonTitle)", for: .normal); resizeAndLayout() } // dismiss func dismissAlertVc() { UIView.animate(withDuration: 0, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.view.alpha = 0.0 self.contentView.transform = CGAffineTransform(translationX: 0, y: kSCREEN_H) }) { (Bool) -> Void in self.view.removeFromSuperview() self.contentView.removeFromSuperview() self.contentView = UIView() self.strongSelf = nil } } } // MARK: - AlertViewController 点击事件 extension AlertViewController { func closeButtonClick(_ sender: UIButton) { dismissAlertVc() } func completeButtonButtonClick(_ sender : UIButton) { if completeAction != nil { completeAction!(sender) } } } // MARK: - 点击任意位置退出dismiss extension AlertViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismissAlertVc() } } extension UIColor { class func colorFromRGB(_ rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
gpl-3.0
4dfb9e6343309eb4f363ae3551fa0f61
30.545788
181
0.602299
4.912721
false
false
false
false
aliceatlas/daybreak
Classes/SBTableCell.swift
1
6831
/* SBTableCell.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ enum SBTableCellStyle { case Gray, White } class SBTableCell: NSCell { var style: SBTableCellStyle = .Gray var showSelection = true var showRoundedPath: Bool = false private func setDefaultValues() { enabled = true lineBreakMode = .ByTruncatingTail } @objc(initImageCell:) override init(imageCell anImage: NSImage?) { super.init(imageCell: anImage) setDefaultValues() } @objc(initTextCell:) override init(textCell aString: String) { super.init(textCell: aString) setDefaultValues() } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } let side: CGFloat = 5.0 override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) { drawInteriorWithFrame(cellFrame, inView: controlView) drawTitleWithFrame(cellFrame, inView: controlView) } override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) { var backgroundColor: NSColor! var cellColor: NSColor! var selectedCellColor: NSColor! if style == .Gray { backgroundColor = SBBackgroundColor cellColor = SBTableCellColor selectedCellColor = SBSidebarSelectedCellColor } else if style == .White { backgroundColor = SBBackgroundLightGrayColor cellColor = SBTableLightGrayCellColor selectedCellColor = NSColor.alternateSelectedControlColor().colorUsingColorSpace(.genericRGBColorSpace())! } backgroundColor.set() NSRectFill(cellFrame) if showRoundedPath { cellColor.set() NSRectFill(NSInsetRect(cellFrame, 0.0, 0.5)) if highlighted && showSelection { let radius = (cellFrame.size.height - 0.5 * 2) / 2 var path = NSBezierPath(roundedRect: CGRectInset(cellFrame, 1.0, 0.5), xRadius: radius, yRadius: radius) selectedCellColor.set() path.fill() } } else { if highlighted && showSelection { selectedCellColor.set() } else { cellColor.set() } NSRectFill(NSInsetRect(cellFrame, 0.0, 0.5)) } } func drawTitleWithFrame(cellFrame: NSRect, inView controlView: NSView) { var textColor: NSColor! var sTextColor: NSColor! if style == .Gray { textColor = SBSidebarTextColor sTextColor = .blackColor() } else if style == .White { textColor = ((enabled ? .blackColor() : .grayColor()) as NSColor).colorUsingColorSpace(.genericRGBColorSpace())! sTextColor = highlighted ? .clearColor() : .whiteColor() } if let title: NSString = title.ifNotEmpty { var r = NSZeroRect var sr = NSZeroRect let side = self.side + (cellFrame.size.height - 0.5 * 2) / 2 let color = highlighted ? .whiteColor() : textColor let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode let attribute = [NSFontAttributeName: font!, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle] let sAttribute = [NSFontAttributeName: font!, NSForegroundColorAttributeName: sTextColor, NSParagraphStyleAttributeName: paragraphStyle] var size = title.sizeWithAttributes(attribute) size.width.constrain(max: cellFrame.size.width - side * 2) r.size = size r.origin.x = cellFrame.origin.x switch alignment { case .Left: r.origin.x += side case .Right: r.origin.x += side + ((cellFrame.size.width - side * 2) - size.width) case .Center: r.origin.x += ((cellFrame.size.width - side * 2) - size.width) / 2 default: break } r.origin.y = cellFrame.origin.y + (cellFrame.size.height - r.size.height) / 2 sr = r switch style { case .Gray: sr.origin.y -= 1.0 case .White: sr.origin.y += 1.0 } title.drawInRect(sr, withAttributes: sAttribute) title.drawInRect(r, withAttributes: attribute) } } } class SBIconDataCell: NSCell { var drawsBackground = true override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) { drawInteriorWithFrame(cellFrame, inView: controlView) drawImageWithFrame(cellFrame, inView: controlView) } override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) { if drawsBackground { SBBackgroundLightGrayColor.set() NSRectFill(cellFrame) SBTableLightGrayCellColor.set() NSRectFill(NSInsetRect(cellFrame, 0.0, 0.5)) } } func drawImageWithFrame(cellFrame: NSRect, inView controlView: NSView) { if image != nil { var r = NSZeroRect r.size = image!.size r.origin.x = cellFrame.origin.x + (cellFrame.size.width - r.size.width) / 2 r.origin.y = cellFrame.origin.y + (cellFrame.size.height - r.size.height) / 2 image!.drawInRect(r, operation: .CompositeSourceOver, fraction: 1.0, respectFlipped: true) } } }
bsd-2-clause
83c667f6ca134dd54e39007326062cfb
38.72093
148
0.641048
4.875803
false
false
false
false
TwoRingSoft/shared-utils
Sources/PippinAdapters/DefaultEnvironment.swift
1
1966
// // DefaultEnvironment.swift // PippinAdapters // // Created by Andrew McKnight on 9/21/19. // import Foundation import Pippin public extension Environment { /// Construct a new `Environment` with some default adapters. /// /// Currently provides default instances of these adapters: /// - `ActivityIndicator`: `JGProgressHUDAdapter` /// - `Alerter`: `SwiftMessagesAdapter` /// - `Logger`: `XCGLoggerAdapter` /// Any component may still be switched out afterwards as desired. /// /// TODO: add a `CountlyAdapter` default for `CrashReporter`. /// /// - Parameters: /// - bugReportRecipients: The email addresses to which bug reports should be sent. Optional; if provided, an instance of `PinpointKitAdapter` (`BugReporter`) is constructed. /// - touchVizRootVC: The root `UIViewController` that will be used to construct the app hierarchy to enable touch visualization. Optional; if provided, an instance of `COSTouchVisualizerAdapter` (`TouchVisualization`) is constructed. /// /// - Note: `CrashlyticsAdapter` may not be included due to it's static dependency and limitations of CocoaPods. static func `default`(bugReportRecipients: [String]? = nil, touchVizRootVC: UIViewController? = nil) -> Environment { let environment = Environment() environment.activityIndicator = JGProgressHUDAdapter() environment.logger = XCGLoggerAdapter(name: "\(environment.appName).log", logLevel: environment.logLevel()) environment.alerter = SwiftMessagesAdapter() if let touchVizRootVC = touchVizRootVC { environment.touchVisualizer = COSTouchVisualizerAdapter(rootViewController: touchVizRootVC) } if let bugReportRecipients = bugReportRecipients { environment.bugReporter = PinpointKitAdapter(recipients: bugReportRecipients) } environment.connectEnvironment() return environment } }
mit
0f5f4ae0d72cf496596f61b917bf1af7
41.73913
242
0.702442
4.842365
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Model/ElementStats.swift
1
516
// // MIT License // Copyright (c) Gathering Hall Studios // import Foundation import GRDB class Elements { var state: String? var fire = 0 var water = 0 var thunder = 0 var ice = 0 var dragon = 0 var poison = 0 } class Resistances: Elements, RowConvertible { required init(row: Row) { super.init() fire = row["fire_res"] water = row["water_res"] thunder = row["thunder_res"] ice = row["ice_res"] dragon = row["dragon_res"] } }
mit
43bbf8dcce519ae7dc348faa3223b28a
16.793103
45
0.567829
3.633803
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Models/Handler/UserModelHandler.swift
1
1308
// // UserModelHandler.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 16/01/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift import Realm extension User: ModelHandler { func add(_ values: JSON, realm: Realm) { map(values, realm: realm) realm.add(self, update: true) guard let identifier = self.identifier else { return } if let subscription = realm.objects(Subscription.self).filter("otherUserId = %@", identifier).first { subscription.otherUserId = identifier subscription.privateOtherUserStatus = privateStatus realm.add(subscription, update: true) } } func update(_ values: JSON, realm: Realm) { map(values, realm: realm) realm.add(self, update: true) guard let identifier = self.identifier else { return } if let subscription = realm.objects(Subscription.self).filter("otherUserId = %@", identifier).first { subscription.otherUserId = identifier realm.add(subscription, update: true) } } func remove(_ values: JSON, realm: Realm) { self.map(values, realm: realm) self.status = .offline realm.add(self, update: true) } }
mit
ed8327833824bf521850917d6612e98e
29.395349
109
0.639633
4.299342
false
false
false
false
1aurabrown/eidolon
Kiosk/App/Networking/XAppAuthentication.swift
1
1806
import Foundation /// Request to fetch and store new XApp token if the current token is missing or expired. private func XAppTokenRequest(defaults: NSUserDefaults) -> RACSignal { // I don't like an extension of a class referencing what is essentially a singleton of that class. var appToken = XAppToken(defaults: defaults) let newTokenSignal = Provider.sharedProvider.request(ArtsyAPI.XApp, parameters: ArtsyAPI.XApp.defaultParameters).filterSuccessfulStatusCodes().mapJSON().doNext({ (response) -> Void in if let dictionary = response as? NSDictionary { let formatter = ISO8601DateFormatter() appToken.token = dictionary["xapp_token"] as String? appToken.expiry = formatter.dateFromString(dictionary["expires_in"] as String?) } }).logError().ignoreValues() // Signal that returns whether our current token is valid let validTokenSignal = RACSignal.`return`(appToken.isValid) // If the token is valid, just return an empty signal, otherwise return a signal that fetches new tokens return RACSignal.`if`(validTokenSignal, then: RACSignal.empty(), `else`: newTokenSignal) } /// Request to fetch a given target. Ensures that valid XApp tokens exist before making request func XAppRequest(token: ArtsyAPI, provider: ReactiveMoyaProvider<ArtsyAPI> = Provider.sharedProvider, method: Moya.Method = Moya.DefaultMethod(), parameters: [String: AnyObject] = Moya.DefaultParameters(), defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()) -> RACSignal { // First perform XAppTokenRequest(). When it completes, then the signal returned from the closure will be subscribed to. return XAppTokenRequest(defaults).then { return provider.request(token, method: method, parameters: parameters) } }
mit
748da26aa47f9a83ce38aad1b3ec55b3
52.147059
287
0.741971
4.98895
false
false
false
false
3pillarlabs/ios-horizontalmenu
Sources/MenuItemSelectionOperation.swift
1
3236
// // MenuItemSelectionOperation.swift // TPGHorizontalMenu // // Created by David Livadaru on 17/03/2017. // Copyright © 2017 3Pillar Global. All rights reserved. // import UIKit /// An operation which perform the animation of menu item selection. class MenuItemSelectionOperation: Operation { override var isExecuting: Bool { return _isExecuting } override var isFinished: Bool { return _isFinished } private var _isExecuting: Bool = false private var _isFinished: Bool = false private let menuController: HorizontalMenuViewController private let index: Int private static let defaultSelectionAnimation = Animation(duration: 0.3) init(menuController: HorizontalMenuViewController, index: Int) { self.menuController = menuController self.index = index } override func start() { guard isCancelled == false else { finish() return } updateExecuting(true) performSelectionAnimation() } // MARK: Private functionality private func finish() { willChangeValue(forKey: "isFinished") _isFinished = true didChangeValue(forKey: "isFinished") } private func updateExecuting(_ executing: Bool) { willChangeValue(forKey: "isExecuting") _isExecuting = executing didChangeValue(forKey: "isExecuting") } private func performSelectionAnimation() { let delegateAnimation = menuController.delegate?.horizontalMenuViewController?(horizontalMenuViewController: menuController, animationForSelectionOf: index) let animation = delegateAnimation ?? MenuItemSelectionOperation.defaultSelectionAnimation animation.addAnimation({ [weak self] in guard let strongSelf = self else { return } let controller = strongSelf.menuController controller.paginationController.scroll(to: strongSelf.index) let transition = ScrollTransition(toIndex: strongSelf.index, progress: 1.0) controller.appearanceController.updateItemsScrollView(using: transition) if let scrollIndicator = controller.scrollIndicator { controller.layoutController.layout(scrollIndicator: scrollIndicator, transition: transition) scrollIndicator.backgroundColor = controller.items[strongSelf.index].indicatorColor } }) animation.addCompletion({ [weak self] (finished) in guard let strongSelf = self else { return } strongSelf.finishAnimation() strongSelf.finish() strongSelf.updateExecuting(false) }) prepareForAnimation() animation.animate() } private func prepareForAnimation() { menuController.paginationController.prepareForIndexSelection(index) } private func finishAnimation() { menuController.selectionOperation = nil menuController.paginationController.cleanupIndexSelection(index) } }
mit
346456d9aac17b7be51a4c2a10e2072d
32.350515
132
0.63864
5.881818
false
false
false
false
omiz/CarBooking
CarBooking/Classes/UI/Booking/Cell/BookingTimePickerCell.swift
1
2128
// // BookingTimePickerCell.swift // CarBooking // // Created by Omar Allaham on 10/19/17. // Copyright © 2017 Omar Allaham. All rights reserved. // import UIKit protocol BookingTimeDelegate { func bookingTime(changed date: Date) } class BookingTimePickerCell: UITableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var pickerTopLabel: UILabel! @IBOutlet weak var datePickerHeightConstraint: NSLayoutConstraint! var extended: Bool = false { didSet { datePickerHeightConstraint.constant = extended ? 200 : 0 datePicker.layoutIfNeeded() } } var delegate: BookingTimeDelegate? override func awakeFromNib() { super.awakeFromNib() dateLabel.adjustsFontSizeToFitWidth = true datePicker.addTarget(self, action: #selector(timeChanged(_:)), for: .valueChanged) pickerTopLabel.text = "You can not change the date for old Bookings".localized } @objc func timeChanged(_ picker: UIDatePicker) { setDateLabel(text: picker.date.formatted) delegate?.bookingTime(changed: picker.date) } func setup(_ booking: Booking?, delegate: BookingTimeDelegate?) { let date = booking?.date?.formatted ?? "" setDateLabel(text: date) let pickerDate = booking?.date ?? Booking.defaultDate check(isInPast: pickerDate) datePicker.setDate(booking?.date ?? Booking.defaultDate, animated: false) self.delegate = delegate } func setDateLabel(text: String) { dateLabel.text = text.isEmpty ? "Booking date is not available".localized : String(format: "Starting date: %@".localized, text) } func check(isInPast date: Date) { let isInTheFuture = date.timeIntervalSinceNow >= 0 datePicker.minimumDate = isInTheFuture ? Date() : nil datePicker.isEnabled = isInTheFuture pickerTopLabel.isHidden = isInTheFuture } }
mit
72d16fc5760159fad08f21248bb68c0c
27.743243
90
0.635637
4.992958
false
false
false
false
omiz/CarBooking
Pods/TRON/Source/UploadAPIRequest.swift
1
12226
// // UploadAPIRequest.swift // TRON // // Created by Denys Telezhkin on 11.09.16. // Copyright © 2015 - present MLSDev. 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 import Alamofire public enum UploadRequestType { /// Will create `NSURLSessionUploadTask` using `uploadTaskWithRequest(_:fromFile:)` method case uploadFromFile(URL) /// Will create `NSURLSessionUploadTask` using `uploadTaskWithRequest(_:fromData:)` method case uploadData(Data) /// Will create `NSURLSessionUploadTask` using `uploadTaskWithStreamedRequest(_)` method case uploadStream(InputStream) // Depending on resulting size of the payload will either stream from disk or from memory case multipartFormData((MultipartFormData) -> Void) /// Returns whether current request type is .multipartFormData. var isMultipartRequest: Bool { switch self { case .multipartFormData(_): return true default: return false } } } /** `UploadAPIRequest` encapsulates upload request creation logic, stubbing options, and response/error parsing. */ open class UploadAPIRequest<Model, ErrorModel>: BaseRequest<Model,ErrorModel> { /// UploadAPIRequest type let type: UploadRequestType /// Serializes received response into Result<Model> open var responseParser : ResponseParser /// Serializes received error into APIError<ErrorModel> open var errorParser : ErrorParser /// Closure that is applied to request before it is sent. open var validationClosure: (UploadRequest) -> UploadRequest = { $0.validate() } // Creates `UploadAPIRequest` with specified `type`, `path` and configures it with to be used with `tron`. public init<Serializer : ErrorHandlingDataResponseSerializerProtocol>(type: UploadRequestType, path: String, tron: TRON, responseSerializer: Serializer) where Serializer.SerializedObject == Model, Serializer.SerializedError == ErrorModel { self.type = type self.responseParser = { request,response, data, error in responseSerializer.serializeResponse(request,response,data,error) } self.errorParser = { result, request,response, data, error in return responseSerializer.serializeError(result,request, response, data, error) } super.init(path: path, tron: tron) } override func alamofireRequest(from manager: SessionManager) -> Request? { switch type { case .uploadFromFile(let url): return manager.upload(url, to: urlBuilder.url(forPath: path), method: method, headers: headerBuilder.headers(forAuthorizationRequirement: authorizationRequirement, including: headers)) case .uploadData(let data): return manager.upload(data, to: urlBuilder.url(forPath: path), method: method, headers: headerBuilder.headers(forAuthorizationRequirement: authorizationRequirement, including: headers)) case .uploadStream(let stream): return manager.upload(stream, to: urlBuilder.url(forPath: path), method: method, headers: headerBuilder.headers(forAuthorizationRequirement: authorizationRequirement, including: headers)) case .multipartFormData(_): return nil } } /** Send current request. - parameter successBlock: Success block to be executed when request finished - parameter failureBlock: Failure block to be executed if request fails. Nil by default. - returns: Alamofire.Request or nil if request was stubbed. */ @discardableResult open func perform(withSuccess successBlock: ((Model) -> Void)? = nil, failure failureBlock: ((APIError<ErrorModel>) -> Void)? = nil) -> UploadRequest? { guard !type.isMultipartRequest else { assertionFailure("TRON error: attempting to perform upload request, however current request type is UploadRequestType.multipartFormData. To send multipart requests, please use performMultipart(withSuccess:failure:encodingMemoryThreshold:encodingCompletion:) method.") return nil } if performStub(success: successBlock, failure: failureBlock) { return nil } return performAlamofireRequest { self.callSuccessFailureBlocks(successBlock, failure: failureBlock, response: $0) } } /** Perform current request with completion block, that contains Alamofire.Response. - parameter completion: Alamofire.Response completion block. - returns: Alamofire.Request or nil if request was stubbed. */ @discardableResult open func performCollectingTimeline(withCompletion completion: @escaping ((Alamofire.DataResponse<Model>) -> Void)) -> UploadRequest? { guard !type.isMultipartRequest else { assertionFailure("TRON error: attempting to perform upload request, however current request type is UploadRequestType.multipartFormData. To send multipart requests, please use performMultipart(withSuccess:failure:encodingMemoryThreshold:encodingCompletion:) method.") return nil } if performStub(completion: completion) { return nil } return performAlamofireRequest(completion) } /** Perform multipart form data upload. - parameter success: Success block to be executed when request finished - parameter failure: Failure block to be executed if request fails. Nil by default. - parameter encodingMemoryThreshold: If data size is less than `encodingMemoryThreshold` request will be streamed from memory, otherwise - from disk. - parameter encodingCompletion: Encoding completion block, that can be used to inspect encoding result. No action is required by default, default value for this block is nil. */ open func performMultipart(withSuccess successBlock: @escaping (Model) -> Void, failure failureBlock: ((APIError<ErrorModel>) -> Void)? = nil, encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)? = nil) { guard let manager = tronDelegate?.manager else { fatalError("Manager cannot be nil while performing APIRequest") } willSendRequest() guard case UploadRequestType.multipartFormData(let multipartFormDataBlock) = type else { assertionFailure("TRON: attempting to perform multipart request, however current request type is \(type). To send upload requests, that are not multipart, please use either `perform(withSuccess:failure:)` or `performCollectingTimeline(withCompletion:) method` ") return } if performStub(success: successBlock, failure: failureBlock) { return } let multipartConstructionBlock: (MultipartFormData) -> Void = { requestFormData in self.parameters.forEach { (key,value) in requestFormData.append(String(describing: value).data(using:.utf8) ?? Data(), withName: key) } multipartFormDataBlock(requestFormData) } let encodingCompletion: (SessionManager.MultipartFormDataEncodingResult) -> Void = { completion in if case .failure(let error) = completion { let apiError = APIError<ErrorModel>(request: nil, response: nil, data: nil, error: error) failureBlock?(apiError) } else if case .success(let request, _, _) = completion { self.willSendAlamofireRequest(request) _ = self.validationClosure(request).response(queue : self.resultDeliveryQueue, responseSerializer: self.dataResponseSerializer(with: request)) { self.callSuccessFailureBlocks(successBlock, failure: failureBlock, response: $0) } if !(self.tronDelegate?.manager.startRequestsImmediately ?? false){ request.resume() } self.didSendAlamofireRequest(request) encodingCompletion?(completion) } } manager.upload(multipartFormData: multipartConstructionBlock, usingThreshold: encodingMemoryThreshold, to: urlBuilder.url(forPath: path), method: method, headers: headerBuilder.headers(forAuthorizationRequirement: authorizationRequirement, including: headers), encodingCompletion: encodingCompletion) } private func performAlamofireRequest(_ completion : @escaping (DataResponse<Model>) -> Void) -> UploadRequest { guard let manager = tronDelegate?.manager else { fatalError("Manager cannot be nil while performing APIRequest") } willSendRequest() guard let request = alamofireRequest(from: manager) as? UploadRequest else { fatalError("Failed to receive UploadRequest") } willSendAlamofireRequest(request) if !tronDelegate!.manager.startRequestsImmediately { request.resume() } didSendAlamofireRequest(request) return validationClosure(request).response(queue: resultDeliveryQueue,responseSerializer: dataResponseSerializer(with: request), completionHandler: { dataResponse in self.didReceiveDataResponse(dataResponse, forRequest: request) completion(dataResponse) }) } internal func dataResponseSerializer(with request: Request) -> Alamofire.DataResponseSerializer<Model> { return DataResponseSerializer<Model> { urlRequest, response, data, error in self.willProcessResponse((urlRequest,response,data,error), for: request) var result : Alamofire.Result<Model> var apiError : APIError<ErrorModel>? var parsedModel : Model? if let error = error { apiError = self.errorParser(nil, urlRequest, response, data, error) result = .failure(apiError!) } else { result = self.responseParser(urlRequest, response, data, error) if let model = result.value { parsedModel = model result = .success(model) } else { apiError = self.errorParser(result, urlRequest, response, data, error) result = .failure(apiError!) } } if let error = apiError { self.didReceiveError(error, for: (urlRequest,response,data,error), request: request) } else if let model = parsedModel { self.didSuccessfullyParseResponse((urlRequest,response,data,error), creating: model, forRequest: request) } return result } } } @available(*,unavailable,renamed: "UploadAPIRequest") class MultipartAPIRequest {}
mit
edc1539d4039ecd2ace5a78dc1d4eebf
47.511905
324
0.671084
5.455154
false
false
false
false
AzenXu/Memo
Memo/Common/Extension/UIScrollView+Stec.swift
1
2195
// // UIScrollView+Stec.swift // JFoundation // // Created by kenneth wang on 16/8/26. // Copyright © 2016年 st. All rights reserved. // import Foundation import UIKit public extension UIScrollView { public var stec_isAtTop: Bool { return contentOffset.y == -contentInset.top } public func stec_scrollsToTop() { let topPoint = CGPoint(x: 0, y: -contentInset.top) setContentOffset(topPoint, animated: true) } private func stec_zoomRectWithZoomPoint(zoomPoint: CGPoint, scale: CGFloat) -> CGRect { var scale = min(scale, maximumZoomScale) scale = max(scale, minimumZoomScale) let zoomFactor = 1.0 / self.zoomScale let translatedZoomPoint = CGPoint( x: (zoomPoint.x + self.contentOffset.x) * zoomFactor, y: (zoomPoint.y + self.contentOffset.y) * zoomFactor ) let destinationRectWidth = self.bounds.width / scale let destinationRectHeight = self.bounds.height / scale let destinationRect = CGRect( x: translatedZoomPoint.x - destinationRectWidth * 0.5, y: translatedZoomPoint.y - destinationRectHeight * 0.5, width: destinationRectWidth, height: destinationRectHeight ) return destinationRect } public func stec_zoomToPoint(zoomPoint: CGPoint, withScale scale: CGFloat, animated: Bool) { let zoomRect = stec_zoomRectWithZoomPoint(zoomPoint, scale: scale) self.zoomToRect(zoomRect, animated: animated) } public func stec_zoomToPoint(zoomPoint: CGPoint, withScale scale: CGFloat, animationDuration: NSTimeInterval, animationCurve: UIViewAnimationCurve) { let zoomRect = stec_zoomRectWithZoomPoint(zoomPoint, scale: scale) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationCurve(animationCurve) self.zoomToRect(zoomRect, animated: false) UIView.commitAnimations() } }
mit
0f30614a398d9780b0d647c4165559b1
31.25
153
0.640967
4.936937
false
false
false
false
tnantoka/GameplayKitSandbox
GameplayKitSandbox/StateScene.swift
1
2572
// // StateScene.swift // GameplayKitSandbox // // Created by Tatsuya Tobioka on 2015/09/22. // Copyright © 2015年 tnantoka. All rights reserved. // import UIKit import SpriteKit import GameplayKit class StateScene: ExampleScene { var house: GKEntity! override func createSceneContents() { house = GKEntity() var points = [ CGPoint(x: 0, y: 40.0), CGPoint(x: -40.0, y: 0), CGPoint(x: -25.0, y: 0), CGPoint(x: -25.0, y: -40.0), CGPoint(x: 25.0, y: -40.0), CGPoint(x: 25.0, y: 0), CGPoint(x: 40.0, y: 0), ] let shapeNode = SKShapeNode(points: &points, count: points.count) shapeNode.position = center addChild(shapeNode) let burnableComponent = BurnableComponent(entity: house, shapeNode: shapeNode) house.addComponent(burnableComponent) burnableComponent.stateMachine.enter(HouseDryState.self) createLabel("Tap: Spark", color: SKColor.orange, order: 0) createLabel("Double Tap: Rain", color: SKColor.lightGray, order: 1) } func createSpark() { createParticle("spark", position: center, duration: 0.1) { if let burnableComponent = self.house.component(ofType: BurnableComponent.self) { burnableComponent.stateMachine.enter(HouseBurningState.self) } } } func createRain() { createParticle("rain", position: CGPoint(x: center.x + 50.0, y: center.y + 200.0), duration: 2.0) { if let burnableComponent = self.house.component(ofType: BurnableComponent.self) { burnableComponent.stateMachine.enter(HouseWetState.self) } } } func createParticle(_ name: String, position: CGPoint, duration: TimeInterval, callback: @escaping () -> Void) { if let particlePath = Bundle.main.path(forResource: name, ofType: "sks") { if let particle = NSKeyedUnarchiver.unarchiveObject(withFile: particlePath) as? SKEmitterNode { particle.position = position addChild(particle) let wait = SKAction.wait(forDuration: duration) let fadeOut = SKAction.fadeOut(withDuration: 1.0) let sequence = SKAction.sequence([wait, fadeOut]) particle.run(sequence, completion: callback) } } } override func update(_ currentTime: TimeInterval) { super.update(currentTime) house.update(deltaTime: deltaTime) } }
mit
fa751aad172c432401ffb1405aa6eb0b
32.363636
116
0.605294
4.170455
false
false
false
false
sebarina/BCUIImagePicker
BCImagePickerDemo/ViewController.swift
1
1811
// // ViewController.swift // BCImagePickerDemo // // Created by Sebarina Xu on 6/16/16. // Copyright © 2016 forzadata. All rights reserved. // import UIKit import Photos class ViewController: UIViewController, BCImagePickerControllerDelegate { @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView3: UIImageView! @IBOutlet weak var imageView2: UIImageView! var images : [UIImageView] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. images = [imageView1, imageView2, imageView3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pick(sender: AnyObject) { let vc = BCImagePickerController() vc.appearance.navBarColor = UIColor.purpleColor() vc.appearance.titleColor = UIColor.whiteColor() vc.appearance.customBackImage = UIImage(named: "Nav-返回") vc.imagePickerDelegate = self presentViewController(vc, animated: true, completion: nil) } func didFinishedPickImages(picker: BCImagePickerController, selectedAssets: [PHAsset]) { for i in 0 ..< selectedAssets.count { let asset = selectedAssets[i] ImageUtil.sharedInstance.loadImage(asset, imageView: images[i]) // let scale = UIScreen.mainScreen().scale // PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: CGSizeMake(scale*80, scale*80), contentMode: .AspectFill, options: nil, resultHandler: { [weak self](image, info) in // self?.images[i].image = image // }) } } }
mit
c83489099cdb72a6a06191a864101a0a
32.444444
202
0.6567
4.740157
false
false
false
false
jozsef-vesza/CustomTransitionsDemo
CustomTransitionsDemo/Data/PhotoStore.swift
1
887
// // PhotoStore.swift // CustomTransitionsDemo // // Created by Vesza Jozsef on 04/06/15. // Copyright (c) 2015 József Vesza. All rights reserved. // import UIKit struct PhotoStore { static let sharedInstance = PhotoStore() private static let titles = [ "Photo 1", "Photo 2", "Photo 3", ] private static let authors = [ "Anthony DELANOIX", "Modestas Urbonas", "Shlomit Wolf", ] private static let images = [ UIImage(named: "image-1"), UIImage(named: "image-2"), UIImage(named: "image-3"), ] let photos = [ Photo(title: titles[0], withAuthor: authors[0], withImage: images[0]), Photo(title: titles[1], withAuthor: authors[1], withImage: images[1]), Photo(title: titles[2], withAuthor: authors[2], withImage: images[2]), ] }
mit
3b56483e2939f05a02560da0e2750bcb
22.342105
78
0.573363
3.676349
false
false
false
false
ProjectDent/ARKit-CoreLocation
Node Demos/PickerViewController.swift
1
11729
// // PickerViewController.swift // Node Demos // // Created by Hal Mueller on 9/29/19. // Copyright © 2019 Project Dent. All rights reserved. // import UIKit import ARCL // swiftlint:disable:next type_body_length class PickerViewController: UITableViewController, UITextFieldDelegate { // Originally, the hard-coded factor to raise an annotation's label within the viewport was 1.1. var annotationHeightAdjustmentFactor = 1.1 var locationEstimateMethod = LocationEstimateMethod.mostRelevantEstimate var arTrackingType = SceneLocationView.ARTrackingType.worldTracking var scalingScheme = ScalingScheme.normal // I have absolutely no idea what reasonable values for these scaling parameters would be. var threshold1: Double = 100.0 var scale1: Float = 0.85 var threshold2: Double = 400.0 var scale2: Float = 0.5 var buffer: Double = 100.0 var continuallyAdjustNodePositionWhenWithinRange = true var continuallyUpdatePositionAndScale = true // MARK: - Outlets @IBOutlet weak var annoHeightAdjustFactorField: UITextField! @IBOutlet weak var locationEstimateMethodSegController: UISegmentedControl! @IBOutlet weak var trackingTypeSegController: UISegmentedControl! @IBOutlet weak var adjustNodePositionWithinRangeSwitch: UISwitch! @IBOutlet weak var updateNodePositionAndScaleSwitch: UISwitch! @IBOutlet weak var scalingSchemeSegController: UISegmentedControl! @IBOutlet weak var threshold1Field: UITextField! @IBOutlet weak var scale1Field: UITextField! @IBOutlet weak var threshold2Field: UITextField! @IBOutlet weak var scale2Field: UITextField! @IBOutlet weak var bufferField: UITextField! @IBOutlet var scalingParameterCells: [UITableViewCell]! @IBOutlet weak var threshold1Cell: UITableViewCell! @IBOutlet weak var scale1Cell: UITableViewCell! @IBOutlet weak var threshold2cell: UITableViewCell! @IBOutlet weak var scale2Cell: UITableViewCell! @IBOutlet weak var bufferCell: UITableViewCell! // MARK: - Lifecycle and text field delegate override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { annoHeightAdjustFactorField.text = "\(annotationHeightAdjustmentFactor)" updateLocationEstimateMethodSegController() updateTrackingTypeController() adjustNodePositionWithinRangeSwitch.isOn = continuallyAdjustNodePositionWhenWithinRange updateNodePositionAndScaleSwitch.isOn = continuallyUpdatePositionAndScale threshold1Field.text = "\(threshold1)" threshold2Field.text = "\(threshold2)" scale1Field.text = "\(scale1)" scale2Field.text = "\(scale2)" bufferField.text = "\(buffer)" updateScalingSchemeSegController() updateScalingParameterCells() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: - demo launch actions @IBAction func showJustOneNode(_ sender: Any) { performSegue(withIdentifier: "justOneNode", sender: sender) } @IBAction func showStackedNodes(_ sender: Any) { performSegue(withIdentifier: "stackOfNodes", sender: sender) } @IBAction func showFieldOfNodes(_ sender: Any) { performSegue(withIdentifier: "fieldOfNodes", sender: sender) } @IBAction func showFieldOflabels(_ sender: Any) { performSegue(withIdentifier: "fieldOfLabels", sender: sender) } @IBAction func showFieldOfRadii(_ sender: Any) { performSegue(withIdentifier: "fieldOfRadii", sender: sender) } @IBAction func showSpriteKitNodes(_ sender: Any) { performSegue(withIdentifier: "spriteKitNodes", sender: sender) } @IBAction func showLiveNodes(_ sender: Any) { performSegue(withIdentifier: "liveNodes", sender: sender) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? ARCLViewController { destination.annotationHeightAdjustmentFactor = annotationHeightAdjustmentFactor destination.scalingScheme = scalingScheme destination.locationEstimateMethod = locationEstimateMethod destination.arTrackingType = arTrackingType destination.continuallyUpdatePositionAndScale = continuallyUpdatePositionAndScale destination.continuallyAdjustNodePositionWhenWithinRange = continuallyAdjustNodePositionWhenWithinRange if segue.identifier == "justOneNode" { destination.demonstration = .justOneNode } else if segue.identifier == "stackOfNodes" { destination.demonstration = .stackOfNodes } else if segue.identifier == "fieldOfNodes" { destination.demonstration = .fieldOfNodes } else if segue.identifier == "fieldOfLabels" { destination.demonstration = .fieldOfLabels } else if segue.identifier == "fieldOfRadii" { destination.demonstration = .fieldOfRadii // } else if segue.identifier == "spriteKitNodes" { // destination.demonstration = .spriteKitNodes // } } else if segue.identifier == "liveNodes" { destination.demonstration = .dynamicNodes } } } // MARK: - Y annotation factor and some toggles @IBAction func yAnnoFactorChanged(_ sender: UITextField) { if let text = sender.text, let newValue = Double(text) { annotationHeightAdjustmentFactor = newValue } } @IBAction func locationEstimateMethodChanged(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: locationEstimateMethod = .coreLocationDataOnly case 1: locationEstimateMethod = .mostRelevantEstimate default: locationEstimateMethod = .mostRelevantEstimate } } @IBAction func continuallyAdjustNodePositionWhenWithinRangeChanged(_ sender: UISwitch) { continuallyAdjustNodePositionWhenWithinRange = sender.isOn } @IBAction func continuallyUpdatePositionAndScaleChanged(_ sender: UISwitch) { continuallyUpdatePositionAndScale = sender.isOn } fileprivate func updateLocationEstimateMethodSegController() { switch locationEstimateMethod { case .coreLocationDataOnly: locationEstimateMethodSegController.selectedSegmentIndex = 0 case .mostRelevantEstimate: locationEstimateMethodSegController.selectedSegmentIndex = 1 } } @IBAction func trackingTypeChanged(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: arTrackingType = SceneLocationView.ARTrackingType.worldTracking case 1: arTrackingType = SceneLocationView.ARTrackingType.orientationTracking default: arTrackingType = SceneLocationView.ARTrackingType.worldTracking } } fileprivate func updateTrackingTypeController() { switch arTrackingType { case .worldTracking: trackingTypeSegController.selectedSegmentIndex = 0 case .orientationTracking: trackingTypeSegController.selectedSegmentIndex = 1 } } // MARK: - Scaling scheme @IBAction func threshold1Changed(_ sender: UITextField) { if let text = sender.text, let newValue = Double(text) { threshold1 = newValue } recomputeScalingScheme() } @IBAction func threshold2Changed(_ sender: UITextField) { if let text = sender.text, let newValue = Double(text) { threshold2 = newValue } recomputeScalingScheme() } @IBAction func scale1Changed(_ sender: UITextField) { if let text = sender.text, let newValue = Float(text) { scale1 = newValue } recomputeScalingScheme() } @IBAction func scale2Changed(_ sender: UITextField) { if let text = sender.text, let newValue = Float(text) { scale2 = newValue } recomputeScalingScheme() } @IBAction func bufferChanged(_ sender: UITextField) { if let text = sender.text, let newValue = Double(text) { buffer = newValue } recomputeScalingScheme() } @IBAction func scalingSchemeChanged(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: scalingScheme = .normal case 1: scalingScheme = .tiered(threshold: threshold1, scale: scale1) case 2: scalingScheme = .doubleTiered(firstThreshold: threshold1, firstScale: scale1, secondThreshold: threshold2, secondScale: scale2) case 3: scalingScheme = .linear(threshold: threshold1) case 4: scalingScheme = .linearBuffer(threshold: threshold1, buffer: buffer) default: scalingScheme = .normal } updateScalingParameterCells() } /// Yes, this code is very repetitive of `scalingSchemeChanged`. I could make it more DRY by adding /// a computed property to `ScalingScheme`, but I don't want to mess with library code any more than /// necessary just for this demo. /// https://medium.com/@PhiJay/why-swift-enums-with-associated-values-cannot-have-a-raw-value-21e41d5ec11 /// has a good discussion. fileprivate func recomputeScalingScheme() { switch scalingScheme { case .normal: scalingScheme = .normal case .tiered: scalingScheme = .tiered(threshold: threshold1, scale: scale1) case .doubleTiered: scalingScheme = .doubleTiered(firstThreshold: threshold1, firstScale: scale1, secondThreshold: threshold2, secondScale: scale2) case .linear: scalingScheme = .linear(threshold: threshold1) case .linearBuffer: scalingScheme = .linearBuffer(threshold: threshold1, buffer: buffer) } } fileprivate func updateScalingParameterCells() { for cell in scalingParameterCells { cell.accessoryType = .none } switch scalingScheme { case .normal: break case .tiered: threshold1Cell.accessoryType = .checkmark scale1Cell.accessoryType = .checkmark case .doubleTiered: threshold1Cell.accessoryType = .checkmark scale1Cell.accessoryType = .checkmark threshold2cell.accessoryType = .checkmark scale2Cell.accessoryType = .checkmark case .linear: threshold1Cell.accessoryType = .checkmark case .linearBuffer: threshold1Cell.accessoryType = .checkmark bufferCell.accessoryType = .checkmark } } fileprivate func updateScalingSchemeSegController() { switch scalingScheme { case .normal: scalingSchemeSegController.selectedSegmentIndex = 0 case .tiered: scalingSchemeSegController.selectedSegmentIndex = 1 case .doubleTiered: scalingSchemeSegController.selectedSegmentIndex = 2 case .linear: scalingSchemeSegController.selectedSegmentIndex = 3 case .linearBuffer: scalingSchemeSegController.selectedSegmentIndex = 4 } } }
mit
c05bdc0c61e3a34c93f974105523849f
35.880503
115
0.664905
4.990638
false
false
false
false
tectijuana/iOS
VargasJuan/Ejercicios/6-21.swift
2
500
/* 21. Dada una lista de 30 números, reordenarlos en orden ascendente. Vargas Bañuelos Juan Samuel */ import Foundation print("Introduzca los numeros a orderan separados por comas, sin espacios") var entrada = readLine(strippingNewline: true)! // Divide la cadena en un arreglo var numeros_s = entrada.characters.split{ $0 == "," }.map(String.init) // Convierte a enteros var numeros = [Int]() for numero in numeros_s { numeros.append(Int(numero)!) } // Ordena numeros.sort() print(numeros)
mit
07db98db82e2231134a6942995a793b9
20.652174
75
0.732932
2.813559
false
false
false
false
justin999/gitap
NetworkFramework/ImgurRouter.swift
1
1351
// // ImgurRouter.swift // gitap // // Created by Koichi Sato on 2017/02/07. // Copyright © 2017 Koichi Sato. All rights reserved. // import Foundation import Alamofire enum ImgurRouter: URLRequestConvertible { case upload(Data) func asURLRequest() throws -> URLRequest { var method: HTTPMethod { switch self { case .upload: return .post } } let url: URL = { let relativePath: String switch self { case .upload(_): relativePath = "/image" } var url = URL(string: imgurBaseURLString)! url.appendPathComponent(relativePath) return url }() let params: ([String: Any]?) = { switch self { case .upload(let data): return ["image": data.base64EncodedString()] } }() var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue if let token = ImgurManager.shared.clientID { urlRequest.setValue("Client-ID \(token)", forHTTPHeaderField: "Authorization") } let encoding = JSONEncoding.default return try encoding.encode(urlRequest, with: params) } }
mit
06bc9abb8e0b25ff1302c8d8216620b8
24.961538
90
0.524444
5.232558
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/UIViewExtensions.swift
1
2747
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import CoreFoundation import Foundation import UIKit extension UIView{ var width: CGFloat { return self.frame.size.width } var height: CGFloat { return self.frame.size.height } var size: CGSize { return self.frame.size} var origin: CGPoint { return self.frame.origin } var x: CGFloat { return self.frame.origin.x } var y: CGFloat { return self.frame.origin.y } var centerX: CGFloat { return self.center.x } var centerY: CGFloat { return self.center.y } var left: CGFloat { return self.frame.origin.x } var right: CGFloat { return self.frame.origin.x + self.frame.size.width } var top: CGFloat { return self.frame.origin.y } var bottom: CGFloat { return self.frame.origin.y + self.frame.size.height } func setWidth(width:CGFloat) { self.frame.size.width = width } func setHeight(height:CGFloat) { self.frame.size.height = height } func setSize(size:CGSize) { self.frame.size = size } func setOrigin(point:CGPoint) { self.frame.origin = point } func setOriginX(x:CGFloat) { self.frame.origin = CGPointMake(x, self.frame.origin.y) } func setOriginY(y:CGFloat) { self.frame.origin = CGPointMake(self.frame.origin.x, y) } func setCenterX(x:CGFloat) { self.center = CGPointMake(x, self.center.y) } func setCenterY(y:CGFloat) { self.center = CGPointMake(self.center.x, y) } func roundCorner(radius:CGFloat) { self.layer.cornerRadius = radius } func setTop(top:CGFloat) { self.frame.origin.y = top } func setLeft(left:CGFloat) { self.frame.origin.x = left } func setRight(right:CGFloat) { self.frame.origin.x = right - self.frame.size.width } func setBottom(bottom:CGFloat) { self.frame.origin.y = bottom - self.frame.size.height } @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(CGColor: layer.borderColor!) } set { layer.borderColor = newValue?.CGColor } } }
epl-1.0
1b36e9becf1a7bf9987e8899a1e05fc7
20.793651
79
0.581937
4.104634
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/ToolKit/JSToolKit/JSFoundation/NSString+Size.swift
1
1983
// // String+Size.swift // LoveYou // // Created by WengHengcong on 2017/3/10. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit import Foundation extension NSString { // FIXME: 为什么无效??? /// 返回文本高度 /// /// - Parameters: /// - width: 文本占宽 /// - font: 文本字体 /// - Returns: 文本高度 func height(with width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width:width, height:.greatestFiniteMagnitude) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil) return boundingBox.height } /// 返回文本宽度 /// /// - Parameters: /// - height: 文本占高 /// - font: 文本字体 /// - Returns: 文本宽度 func width(with height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let attributes = [NSAttributedStringKey.font: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let boundingBox = boundingRect(with: constraintRect, options: option, attributes: attributes, context: nil) return boundingBox.width } } extension String { /// 返回文本高度 /// /// - Parameters: /// - width: 文本占宽 /// - font: 文本字体 /// - Returns: 文本高度 func height(with width: CGFloat, font: UIFont) -> CGFloat { let calString = self as NSString return calString.height(with: width, font: font) } /// 返回文本宽度 /// /// - Parameters: /// - height: 文本占高 /// - font: 文本字体 /// - Returns: 文本宽度 func width(with height: CGFloat, font: UIFont) -> CGFloat { let calString = self as NSString return calString.width(with: height, font: font) } }
mit
2b06f8e648d525d61b95e7315919e483
27.4375
156
0.612088
4.089888
false
false
false
false
sugar2010/arcgis-runtime-samples-ios
QueryTaskSample/swift/QueryTask/Controllers/RootViewController.swift
4
5948
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit import ArcGIS //constants for title, search bar placeholder text and data layer let kViewTitle = "US Counties Info" let kSearchBarPlaceholder = "Find Counties (e.g. Los Angeles)" let kMapServiceLayerURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/3" class RootViewController: UITableViewController, AGSQueryTaskDelegate, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { @IBOutlet weak var searchBar:UISearchBar! var queryTask:AGSQueryTask! var query:AGSQuery! var featureSet:AGSFeatureSet! var detailsViewController:DetailsViewController! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() //title for the navigation controller self.title = kViewTitle //text in search bar before user enters in query self.searchBar.placeholder = kSearchBarPlaceholder let countiesLayerURL = kMapServiceLayerURL //set up query task against layer, specify the delegate self.queryTask = AGSQueryTask(URL: NSURL(string: countiesLayerURL)) self.queryTask.delegate = self //return all fields in query self.query = AGSQuery() self.query.outFields = ["*"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Table view methods //one section in this table override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //the section in the table is as large as the number of fetaures returned from the query override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.featureSet == nil { return 0 } return self.featureSet.features.count ?? 0 } //called by table view when it needs to draw one of its rows override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //static instance to represent a single kind of cell. Used if the table has cells formatted differently let kRootViewControllerCellIdentifier = "RootViewControllerCellIdentifier" //as cells roll off screen get the reusable cell, if we can't create a new one var cell = tableView.dequeueReusableCellWithIdentifier(kRootViewControllerCellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: kRootViewControllerCellIdentifier) } //get selected feature and extract the name attribute //display name in cell //add detail disclosure button. This will allow user to see all the attributes in a different view let feature = self.featureSet.features[indexPath.row] as! AGSGraphic cell?.textLabel?.text = feature.attributeAsStringForKey("NAME") //The display field name for the service we are using cell?.accessoryType = .DisclosureIndicator return cell! } //when a user selects a row (i.e. cell) in the table display all the selected features //attributes in a separate view controller override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //if view controller not created, create it, set up the field names to display if nil == self.detailsViewController { let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) self.detailsViewController = storyboard.instantiateViewControllerWithIdentifier("DetailsViewController") as! DetailsViewController self.detailsViewController.fieldAliases = self.featureSet.fieldAliases self.detailsViewController.displayFieldName = self.featureSet.displayFieldName } //the details view controller needs to know about the selected feature to get its value self.detailsViewController.feature = self.featureSet.features[indexPath.row] as! AGSGraphic //display the feature attributes self.navigationController?.pushViewController(self.detailsViewController, animated:true) } //MARK: - UISearchBarDelegate //when the user searches func searchBarSearchButtonClicked(searchBar: UISearchBar) { //display busy indicator, get search string and execute query self.query.text = searchBar.text self.queryTask.executeWithQuery(self.query) searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } //MARK: - AGSQueryTaskDelegate //results are returned func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didExecuteWithFeatureSetResult featureSet: AGSFeatureSet!) { //get feature, and load in to table self.featureSet = featureSet self.tableView.reloadData() } //if there's an error with the query display it to the user func queryTask(queryTask: AGSQueryTask!, operation op: NSOperation!, didFailWithError error: NSError!) { UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok").show() } }
apache-2.0
f05605aff984745f5d5c788117d173a2
40.594406
142
0.702589
5.199301
false
false
false
false
AndyQ/C64Emulator
C64Emulator/SceneDelegate.swift
1
3598
// // SceneDelegate.swift // C64Emulator // // Created by Andy Qua on 26/12/2021. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { if let url = URLContexts.first?.url { // Handle URL print( "Requested to open URL - \(url)") let diskName = url.lastPathComponent let destPath = getUserGamesDirectory().appendingPathComponent(diskName) // Move file to user games folder let fm = FileManager.default do { try fm.moveItem(at: url, to: URL(fileURLWithPath: destPath)) let d64 = D64Image() d64.readDiskDirectory(destPath) DatabaseManager.sharedInstance.addDisk(diskName: diskName) NotificationCenter.default.post(name: Notif_GamesUpdated, object: nil) if let rnc = window?.rootViewController as? UINavigationController, let rvc = rnc.topViewController as? DiskViewController { rvc.showDisk( diskPath:destPath ) } } catch let error { print( "Can't move file as it already exists - \(diskName) - \(error)") try? fm.removeItem(at: url) } } } }
gpl-2.0
4427581e9999b1b99323c4d9bf6679f0
42.349398
147
0.640912
5.260234
false
false
false
false
kyouko-taiga/anzen
Sources/Utils/Sequence+Extensions.swift
1
1698
extension Sequence { /// Finds the duplicate in the sequence, using a closure to discriminate between values. public func duplicates<T>(groupedBy discriminator: (Element) -> T) -> [Element] where T: Hashable { var present: Set<T> = [] var result: [Element] = [] for element in self { let key = discriminator(element) if present.insert(key).inserted != true { result.append(element) } } return result } /// Evaluates whether or not all elements in the sequence satisfy a given predicate. public func all(satisfy predicate: (Element) throws -> Bool) rethrows -> Bool { for element in self { guard try predicate(element) else { return false } } return true } } extension Array { /// Adds a new element at the beginning of the array. public mutating func prepend(_ newElement: Element) { insert(newElement, at: 0) } } public struct Zip3Sequence<S1, S2, S3>: IteratorProtocol, Sequence where S1: Sequence, S2: Sequence, S3: Sequence { // swiftlint:disable:next large_tuple public mutating func next() -> (S1.Element, S2.Element, S3.Element)? { guard let e1 = i1.next(), let e2 = i2.next(), let e3 = i3.next() else { return nil } return (e1, e2, e3) } private var i1: S1.Iterator private var i2: S2.Iterator private var i3: S3.Iterator init(_ i1: S1.Iterator, _ i2: S2.Iterator, _ i3: S3.Iterator) { self.i1 = i1 self.i2 = i2 self.i3 = i3 } } public func zip<S1, S2, S3>(_ s1: S1, _ s2: S2, _ s3: S3) -> Zip3Sequence<S1, S2, S3> where S1: Sequence, S2: Sequence, S3: Sequence { return Zip3Sequence(s1.makeIterator(), s2.makeIterator(), s3.makeIterator()) }
apache-2.0
7853fddf100eeadd3e9c88ad9a15e13d
25.53125
90
0.64841
3.290698
false
false
false
false
cs-mateuscampos/LearningShotUIKit
LearningShotUIKit/LearningShotUIKit/UICollectionViewDelegateDatasource.swift
1
1437
// // UICollectionViewDelegateDatasource.swift // LearningShotUIKit // // Created by Mateus de Campos on 03/01/17. // Copyright © 2017 Mateus Campos. All rights reserved. // import UIKit class UICollectionViewDelegateDatasource: NSObject, UICollectionViewDelegate, UICollectionViewDataSource { var data:Array<AnyObject>? var selectionDelegate: SelectionProtocol? init(data:Array<AnyObject>?, selectionDelegate: SelectionProtocol?) { self.data = data self.selectionDelegate = selectionDelegate } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let count = self.data?.count { return count } return 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCustonCellIdentifier", for: indexPath) as? UICollectionViewCustonCell if let color = data?[indexPath.row]{ cell?.setup(color: color as! UIColor) } return cell! } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let color = data?[indexPath.row]{ self.selectionDelegate?.didSelectedColor(color: color as! UIColor) } } }
mit
10518f1401c63aaf4edf308c250806c8
32.395349
161
0.68663
5.279412
false
false
false
false
apple/swift-nio
Sources/NIOChatServer/main.swift
1
7902
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOPosix import Dispatch private let newLine = "\n".utf8.first! /// Very simple example codec which will buffer inbound data until a `\n` was found. final class LineDelimiterCodec: ByteToMessageDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = ByteBuffer public var cumulationBuffer: ByteBuffer? public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { let readable = buffer.withUnsafeReadableBytes { $0.firstIndex(of: newLine) } if let r = readable { context.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: r + 1)!)) return .continue } return .needMoreData } } /// This `ChannelInboundHandler` demonstrates a few things: /// * Synchronisation between `EventLoop`s. /// * Mixing `Dispatch` and SwiftNIO. /// * `Channel`s are thread-safe, `ChannelHandlerContext`s are not. /// /// As we are using an `MultiThreadedEventLoopGroup` that uses more then 1 thread we need to ensure proper /// synchronization on the shared state in the `ChatHandler` (as the same instance is shared across /// child `Channel`s). For this a serial `DispatchQueue` is used when we modify the shared state (the `Dictionary`). /// As `ChannelHandlerContext` is not thread-safe we need to ensure we only operate on the `Channel` itself while /// `Dispatch` executed the submitted block. final class ChatHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer public typealias OutboundOut = ByteBuffer // All access to channels is guarded by channelsSyncQueue. private let channelsSyncQueue = DispatchQueue(label: "channelsQueue") private var channels: [ObjectIdentifier: Channel] = [:] public func channelActive(context: ChannelHandlerContext) { let remoteAddress = context.remoteAddress! let channel = context.channel self.channelsSyncQueue.async { // broadcast the message to all the connected clients except the one that just became active. self.writeToAll(channels: self.channels, allocator: channel.allocator, message: "(ChatServer) - New client connected with address: \(remoteAddress)\n") self.channels[ObjectIdentifier(channel)] = channel } var buffer = channel.allocator.buffer(capacity: 64) buffer.writeString("(ChatServer) - Welcome to: \(context.localAddress!)\n") context.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) } public func channelInactive(context: ChannelHandlerContext) { let channel = context.channel self.channelsSyncQueue.async { if self.channels.removeValue(forKey: ObjectIdentifier(channel)) != nil { // Broadcast the message to all the connected clients except the one that just was disconnected. self.writeToAll(channels: self.channels, allocator: channel.allocator, message: "(ChatServer) - Client disconnected\n") } } } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let id = ObjectIdentifier(context.channel) var read = self.unwrapInboundIn(data) // 64 should be good enough for the ipaddress var buffer = context.channel.allocator.buffer(capacity: read.readableBytes + 64) buffer.writeString("(\(context.remoteAddress!)) - ") buffer.writeBuffer(&read) self.channelsSyncQueue.async { [buffer] in // broadcast the message to all the connected clients except the one that wrote it. self.writeToAll(channels: self.channels.filter { id != $0.key }, buffer: buffer) } } public func errorCaught(context: ChannelHandlerContext, error: Error) { print("error: ", error) // As we are not really interested getting notified on success or failure we just pass nil as promise to // reduce allocations. context.close(promise: nil) } private func writeToAll(channels: [ObjectIdentifier: Channel], allocator: ByteBufferAllocator, message: String) { let buffer = allocator.buffer(string: message) self.writeToAll(channels: channels, buffer: buffer) } private func writeToAll(channels: [ObjectIdentifier: Channel], buffer: ByteBuffer) { channels.forEach { $0.value.writeAndFlush(buffer, promise: nil) } } } /// access to the internal state is protected by `channelsSyncQueue` extension ChatHandler: @unchecked Sendable {} // We need to share the same ChatHandler for all as it keeps track of all // connected clients. For this ChatHandler MUST be thread-safe! let chatHandler = ChatHandler() let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) let bootstrap = ServerBootstrap(group: group) // Specify backlog and enable SO_REUSEADDR for the server itself .serverChannelOption(ChannelOptions.backlog, value: 256) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) // Set the handlers that are applied to the accepted Channels .childChannelInitializer { channel in // Add handler that will buffer data until a \n is received channel.pipeline.addHandler(ByteToMessageHandler(LineDelimiterCodec())).flatMap { v in // It's important we use the same handler for all accepted channels. The ChatHandler is thread-safe! channel.pipeline.addHandler(chatHandler) } } // Enable SO_REUSEADDR for the accepted Channels .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16) .childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator()) defer { try! group.syncShutdownGracefully() } // First argument is the program path let arguments = CommandLine.arguments let arg1 = arguments.dropFirst().first let arg2 = arguments.dropFirst(2).first let defaultHost = "::1" let defaultPort = 9999 enum BindTo { case ip(host: String, port: Int) case unixDomainSocket(path: String) } let bindTarget: BindTo switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { case (.some(let h), _ , .some(let p)): /* we got two arguments, let's interpret that as host and port */ bindTarget = .ip(host: h, port: p) case (let portString?, .none, _): // Couldn't parse as number, expecting unix domain socket path. bindTarget = .unixDomainSocket(path: portString) case (_, let p?, _): // Only one argument --> port. bindTarget = .ip(host: defaultHost, port: p) default: bindTarget = .ip(host: defaultHost, port: defaultPort) } let channel = try { () -> Channel in switch bindTarget { case .ip(let host, let port): return try bootstrap.bind(host: host, port: port).wait() case .unixDomainSocket(let path): return try bootstrap.bind(unixDomainSocketPath: path).wait() } }() guard let localAddress = channel.localAddress else { fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.") } print("Server started and listening on \(localAddress)") // This will never unblock as we don't close the ServerChannel. try channel.closeFuture.wait() print("ChatServer closed")
apache-2.0
662543484441c4de66d25e9aca1a9105
40.589474
163
0.692483
4.61296
false
false
false
false
glessard/swift-channels
concurrency/channel-semaphore/channel-semaphore-pool.swift
1
2526
// // channel-semaphore-pool.swift // Channels // // Created by Guillaume Lessard on 2015-07-13. // Copyright © 2015 Guillaume Lessard. All rights reserved. // import Darwin.libkern.OSAtomic /** An object reuse pool for `ChannelSemaphore`. A mach semaphore (obtained with `semaphore_create`) takes several microseconds to create. Without a reuse pool, this cost would be incurred every time a thread needs to stop in `QUnbufferedChan`, `QBufferedChan` and `select_chan()`. Reusing reduces the cost to much less than 1 microsecond. */ struct SemaphorePool { static private let capacity = 256 static private let buffer = UnsafeMutablePointer<ChannelSemaphore>.alloc(capacity) static private var cursor = 0 static private var lock = OS_SPINLOCK_INIT /** Return a `ChannelSemaphore` to the reuse pool. - parameter s: A `ChannelSemaphore` to return to the reuse pool. */ static func Return(s: ChannelSemaphore) { OSSpinLockLock(&lock) if cursor < capacity { buffer.advancedBy(cursor).initialize(s) cursor += 1 // assert(s.svalue == 0, "Non-zero user-space semaphore count of \(s.svalue) in \(#function)") // assert(s.seln == nil || s.state == .DoubleSelect, "Unexpectedly non-nil Selection in \(#function)") // assert(s.iptr == nil || s.state == .DoubleSelect, "Non-nil pointer \(s.iptr) in \(#function)") assert(s.state == .Done || s.state == .DoubleSelect || s.state == .Ready, "State \(s.state) is incorrect") } OSSpinLockUnlock(&lock) } /** Obtain a `ChannelSemaphore` from the object reuse pool. The returned `ChannelSemaphore` will be uniquely referenced. - returns: A uniquely-referenced `ChannelSemaphore`. */ static func Obtain() -> ChannelSemaphore { OSSpinLockLock(&lock) if cursor > 0 { cursor -= 1 for var i=cursor; i>=0; i-- { if isUniquelyReferencedNonObjC(&buffer[i]) { var s = buffer.advancedBy(cursor).move() if i < cursor { swap(&s, &buffer[i]) } OSSpinLockUnlock(&lock) // Expected state: // s.svalue = 0 // s.seln = nil // s.iptr = nil // s.currentState = ChannelSemaphore.State.Ready.rawValue guard s.setState(.Ready) else { fatalError("Bad state for a ChannelSemaphore in \(#function)") } return s } } cursor += 1 } OSSpinLockUnlock(&lock) return ChannelSemaphore() } }
mit
a2b4c9f21dd72892ae6e780e3d0630f5
29.059524
112
0.630099
4.05297
false
false
false
false
Kiandr/CrackingCodingInterview
Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Pages/2.4 Partition.xcplaygroundpage/Contents.swift
1
1624
import Foundation /*: 2.4 Partition a singly linked list around a value `x`, such that all nodes `< x` come before all nodes `>= x`. If x is contained in the list, x only needs to be after the elements less than x. The partition element can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions — e.g.: Input: `3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1` (partition = 5) \ Output: `3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8` */ extension List { func partition(isOrderedBefore: (Element) -> Bool) -> List { let (left, right) = partition(isOrderedBefore) return left ++ right } private func partition(_ isLeft: (Element) -> Bool) -> (List, List) { guard let head = head else { return (self, self) } let (left, right) = tail.partition(isLeft) if isLeft(head) { return (head ++ left, right) } else { return (left, head ++ right) } } } func testPartition(array: [Int], partitionValue: Int) { let list = List(array: array) let partitioned = list.partition(isOrderedBefore: { $0 < partitionValue } ) partitioned.reduce(false) { if $1 < partitionValue { assert($0 == false) return false } return true } } testPartition(array: [3,5,8,5,10,2,1], partitionValue: 5) ApplyConcurrently(iterations: 2.pow(5)).apply { let randomIntArray = Array<Int>(randomIntUpperBound: 100, randomIntCount: 2.pow(5)) testPartition(array: randomIntArray, partitionValue: 100.arc4random_uniform()) }
mit
7badaa4a4e5db3217b05b3057fb315f9
30.803922
141
0.60111
3.798595
false
true
false
false
navermaps/maps.ios
NMapSampleSwift/NMapSampleSwift/PolylinesViewController.swift
1
5910
// // PolylinesViewController.swift // NMapSampleSwift // // Created by Junggyun Ahn on 2016. 11. 14.. // Copyright © 2016년 Naver. All rights reserved. // import UIKit class PolylinesViewController: UIViewController, NMapViewDelegate, NMapPOIdataOverlayDelegate { var mapView: NMapView? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isTranslucent = false mapView = NMapView(frame: self.view.frame) if let mapView = mapView { // set the delegate for map view mapView.delegate = self // set the application api key for Open MapViewer Library mapView.setClientId("YOUR CLIENT ID") mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() mapView?.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapView?.viewWillAppear() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) mapView?.viewDidDisappear() } // MARK: - NMapViewDelegate Methods open func onMapView(_ mapView: NMapView!, initHandler error: NMapError!) { if (error == nil) { // success // set map center and level mapView.setMapCenter(NGeoPoint(longitude:126.978371, latitude:37.5666091), atLevel:11) // set for retina display mapView.setMapEnlarged(true, mapHD: true) // set map mode : vector/satelite/hybrid mapView.mapViewMode = .vector } else { // fail print("onMapView:initHandler: \(error.description)") } } // MARK: - PolylinesViewController override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) mapView?.viewDidAppear() addPolylines() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) clearOverlays() mapView?.viewWillDisappear() } func addPolylines() { if let mapOverlayManager = mapView?.mapOverlayManager { // set path data points if let pathData = NMapPathData.init(capacity: 9) { pathData.initPathData() pathData.addPathPointLongitude(127.108099, latitude: 37.366034, lineType: .solid) pathData.addPathPointLongitude(127.108088, latitude: 37.366043, lineType: .none) pathData.addPathPointLongitude(127.108079, latitude: 37.365619, lineType: .none) pathData.addPathPointLongitude(127.107458, latitude: 37.365608, lineType: .none) pathData.addPathPointLongitude(127.107232, latitude: 37.365608, lineType: .none) pathData.addPathPointLongitude(127.106904, latitude: 37.365624, lineType: .none) pathData.addPathPointLongitude(127.105933, latitude: 37.365621, lineType: .dash) pathData.addPathPointLongitude(127.105929, latitude: 37.366378, lineType: .none) pathData.addPathPointLongitude(127.106279, latitude: 37.366380, lineType: .none) pathData.end() // create path data overlay if let pathDataOverlay = mapOverlayManager.newPathDataOverlay(pathData) { if let pathData = NMapPathData.init(capacity: 7) { pathData.initPathData() pathData.addPathPointLongitude(127.108099, latitude: 37.367034, lineType: .solid) pathData.addPathPointLongitude(127.108088, latitude: 37.367043, lineType: .none) pathData.addPathPointLongitude(127.108079, latitude: 37.366619, lineType: .none) pathData.addPathPointLongitude(127.107458, latitude: 37.366608, lineType: .none) pathData.addPathPointLongitude(127.107232, latitude: 37.366608, lineType: .none) pathData.addPathPointLongitude(127.106904, latitude: 37.366624, lineType: .dash) pathData.addPathPointLongitude(127.106904, latitude: 37.367721, lineType: .none) pathData.end() let pathLineStyle = NMapPathLineStyle() pathLineStyle.lineColor = .green pathData.pathLineStyle = pathLineStyle pathDataOverlay.add(pathData) } pathDataOverlay.showAllPathData() } } } } func clearOverlays() { if let mapOverlayManager = mapView?.mapOverlayManager { mapOverlayManager.clearOverlays() } } // MARK: - NMapPOIdataOverlayDelegate Methods open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForOverlayItem poiItem: NMapPOIitem!, selected: Bool) -> UIImage! { return NMapViewResources.imageWithType(poiItem.poiFlagType, selected: selected); } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, anchorPointWithType poiFlagType: NMapPOIflagType) -> CGPoint { return NMapViewResources.anchorPoint(withType: poiFlagType) } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, calloutOffsetWithType poiFlagType: NMapPOIflagType) -> CGPoint { return CGPoint.zero } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForCalloutOverlayItem poiItem: NMapPOIitem!, constraintSize: CGSize, selected: Bool, imageForCalloutRightAccessory: UIImage!, calloutPosition: UnsafeMutablePointer<CGPoint>!, calloutHit calloutHitRect: UnsafeMutablePointer<CGRect>!) -> UIImage! { return nil } }
apache-2.0
d54a1ffeb4357f04565fcc73f7b22c7e
36.865385
317
0.639749
4.56139
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/helper/RxTripKit/TKLocationManager+rx.swift
1
4030
// // TKLocationManager+rx.swift // TripKit // // Created by Adrian Schoenig on 20/7/17. // // import Foundation import CoreLocation import RxSwift import RxCocoa import TripKit public extension Reactive where Base : TKLocationManager { /// Fetches the user's current location and fires observable /// exactly ones, if successful, and then completes. /// /// The observable can error out, e.g., if permission was /// not granted to the device's location services, or if /// no location could be fetched within the alloted time. /// /// - Parameter seconds: Maximum time to give GPS /// - Returns: Observable of user's current location; can error out func fetchCurrentLocation(within seconds: TimeInterval) -> Single<CLLocation> { guard base.isAuthorized else { return tryAuthorization().flatMap { authorized -> Single<CLLocation> in if authorized { return self.fetchCurrentLocation(within: seconds) } else { throw TKLocationManager.LocalizationError.authorizationDenied } } } return Single.create { observer in self.base.fetch(within: seconds) { observer($0) } return Disposables.create() } } /// Continuously observes the user's current location and fires /// observable whenever the user moved more than a minimum /// threshold. /// /// The observable can error out, e.g., if permission was /// not granted to the device's location services. /// /// - Returns: Observable of user's current location; can error out var currentLocation: Observable<CLLocation> { return Observable.create { subscriber in let date = Date() let calendar = Calendar.current let components = calendar.dateComponents([.minute, .second], from: date) let identifier: NSString = "subscription-\(components.minute!)-\(components.second!)" as NSString if self.base.isAuthorized { self.base.subscribe(id: identifier) { location in subscriber.onNext(location) } } else { subscriber.onError(TKLocationManager.LocalizationError.authorizationDenied) } return Disposables.create { self.base.unsubscribe(id: identifier) } } } #if os(iOS) /// Observes the device's heading /// /// The observable does not error out and not terminate /// by itself. /// /// - Note: Internally, each subscription creates a new /// observable, and a new location manager, so you're /// encouraged to share a single subscription. var deviceHeading: Observable<CLHeading> { return Observable.create { subscriber in var manager: CLLocationManager! = CLLocationManager() var delegate: Delegate! = Delegate() manager.startUpdatingHeading() manager.delegate = delegate delegate.onNewHeading = { heading in subscriber.onNext(heading) } return Disposables.create { manager.stopUpdatingHeading() manager = nil delegate = nil } } } #endif func tryAuthorization() -> Single<Bool> { if !base.featureIsAvailable { return .error(TKLocationManager.LocalizationError.featureNotAvailable) } switch base.authorizationStatus { case .restricted, .denied: return .error(TKLocationManager.LocalizationError.authorizationDenied) case .authorized: return .just(true) case .notDetermined: return Single.create { observer in self.base.askForPermission { success in observer(.success(success)) } return Disposables.create() } } } } #if os(iOS) fileprivate class Delegate: NSObject, CLLocationManagerDelegate { var onNewHeading: ((CLHeading) -> ())? = nil override init() { super.init() } func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { onNewHeading?(newHeading) } } #endif
apache-2.0
d8591b07560ff5648b57436ea5314216
25.339869
103
0.653846
4.809069
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Rank/Views/RankSongCell.swift
1
803
// // RankSongCell.swift // MusicApp // // Created by Hưng Đỗ on 6/30/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit class RankSongCell: SongCell { @IBOutlet weak var rankTitleLabel: UILabel! @IBOutlet weak var rankView: UIView! override func prepareForReuse() { super.prepareForReuse() rankTitleLabel.text = nil } var rank: Int = 0 { didSet { rankTitleLabel.text = "\(rank)" switch rank { case 1: rankView.backgroundColor = kRankColorFirst case 2: rankView.backgroundColor = kRankColorSecond case 3: rankView.backgroundColor = kRankColorThird default: rankView.backgroundColor = kRankColorNormal } } } }
mit
1f7c28548c5b29cd4d65984b6f90f93d
22.470588
64
0.597744
4.433333
false
false
false
false
mohamede1945/quran-ios
Pods/SQLite.swift/Sources/SQLite/Core/Connection.swift
2
27556
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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.NSUUID import Dispatch #if SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #elseif SWIFT_PACKAGE || COCOAPODS import CSQLite #endif /// A connection to SQLite. public final class Connection { /// The location of a SQLite database. public enum Location { /// An in-memory database (equivalent to `.URI(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case inMemory /// A temporary, file-backed database (equivalent to `.URI("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case uri(String) } /// An SQL operation passed to update callbacks. public enum Operation { /// An INSERT operation. case insert /// An UPDATE operation. case update /// A DELETE operation. case delete fileprivate init(rawValue:Int32) { switch rawValue { case SQLITE_INSERT: self = .insert case SQLITE_UPDATE: self = .update case SQLITE_DELETE: self = .delete default: fatalError("unhandled operation code: \(rawValue)") } } } public var handle: OpaquePointer { return _handle! } fileprivate var _handle: OpaquePointer? = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.InMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. public init(_ location: Location = .inMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) queue.setSpecific(key: Connection.queueKey, value: queueContext) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. public convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.uri(filename), readonly: readonly) } deinit { sqlite3_close(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64 { return sqlite3_last_insert_rowid(handle) } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. public func execute(_ SQL: String) throws { _ = try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: Binding?...) throws -> Statement { if !bindings.isEmpty { return try prepare(statement, bindings) } return try Statement(self, statement) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: Binding?...) throws -> Statement { return try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(statement).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: Binding?...) throws -> Binding? { return try scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [Binding?]) throws -> Binding? { return try prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [String: Binding?]) throws -> Binding? { return try prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. public enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.Deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. public func transaction(_ mode: TransactionMode = .deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. public func savepoint(_ name: String = UUID().uuidString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } fileprivate func transaction(_ begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() } catch { try self.run(rollback) throw error } try self.run(commit) } } /// Interrupts any long-running queries. public func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). public var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. public func busyHandler(_ callback: ((_ tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, to: BusyHandler.self)(tries) }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) busyHandler = box } fileprivate typealias BusyHandler = @convention(block) (Int32) -> Int32 fileprivate var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } public func trace(_ callback: ((String) -> Void)?) { #if SQLITE_SWIFT_SQLCIPHER trace_v1(callback) #else if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { trace_v2(callback) } else { trace_v1(callback) } #endif } fileprivate func trace_v1(_ callback: ((String) -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil /* xCallback */, nil /* pCtx */) trace = nil return } let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } sqlite3_trace(handle, { (C: UnsafeMutableRawPointer?, SQL: UnsafePointer<Int8>?) in if let C = C, let SQL = SQL { unsafeBitCast(C, to: Trace.self)(SQL) } }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self) ) trace = box } fileprivate typealias Trace = @convention(block) (UnsafeRawPointer) -> Void fileprivate var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. public func updateHook(_ callback: ((_ operation: Operation, _ db: String, _ table: String, _ rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( Operation(rawValue: $0), String(cString: $1), String(cString: $2), $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, to: UpdateHook.self)(operation, db!, table!, rowid) }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) updateHook = box } fileprivate typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void fileprivate var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. public func commitHook(_ callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, to: CommitHook.self)() }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) commitHook = box } fileprivate typealias CommitHook = @convention(block) () -> Int32 fileprivate var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. public func rollbackHook(_ callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, to: RollbackHook.self)() }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) rollbackHook = box } fileprivate typealias RollbackHook = @convention(block) () -> Void fileprivate var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). public func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: @escaping (_ args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..<Int(argc)).map { idx in let value = argv![idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String(cString: UnsafePointer(sqlite3_value_text(value))) case let type: fatalError("unsupported value type: \(type)") } } let result = block(arguments) if let result = result as? Blob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(String(describing: result))") } } var flags = SQLITE_UTF8 if deterministic { flags |= SQLITE_DETERMINISTIC } sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { context, argc, value in let function = unsafeBitCast(sqlite3_user_data(context), to: Function.self) function(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } fileprivate typealias Function = @convention(block) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void fileprivate var functions = [String: [Int: Function]]() /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. public func createCollation(_ collation: String, _ block: @escaping (_ lhs: String, _ rhs: String) -> ComparisonResult) throws { let box: Collation = { (lhs: UnsafeRawPointer, rhs: UnsafeRawPointer) in let lstr = String(cString: lhs.assumingMemoryBound(to: UInt8.self)) let rstr = String(cString: rhs.assumingMemoryBound(to: UInt8.self)) return Int32(block(lstr, rstr).rawValue) } try check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { (callback: UnsafeMutableRawPointer?, _, lhs: UnsafeRawPointer?, _, rhs: UnsafeRawPointer?) in /* xCompare */ if let lhs = lhs, let rhs = rhs { return unsafeBitCast(callback, to: Collation.self)(lhs, rhs) } else { fatalError("sqlite3_create_collation_v2 callback called with NULL pointer") } }, nil /* xDestroy */)) collations[collation] = box } fileprivate typealias Collation = @convention(block) (UnsafeRawPointer, UnsafeRawPointer) -> Int32 fileprivate var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(_ block: () throws -> T) rethrows -> T { var success: T? var failure: Error? func execute(_ block: () throws -> T, success: inout T?, failure: inout Error?) { do { success = try block() } catch { failure = error } } if DispatchQueue.getSpecific(key: Connection.queueKey) == queueContext { execute(block, success: &success, failure: &failure) } else { queue.sync(execute: { execute(block, success: &success, failure: &failure) }) // FIXME: rdar://problem/21389236 } if let failure = failure { try { () -> Void in throw failure }() } return success! } @discardableResult func check(_ resultCode: Int32, statement: Statement? = nil) throws -> Int32 { guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else { return resultCode } throw error } fileprivate var queue = DispatchQueue(label: "SQLite.Database", attributes: []) fileprivate static let queueKey = DispatchSpecificKey<Int>() fileprivate lazy var queueContext: Int = unsafeBitCast(self, to: Int.self) } extension Connection : CustomStringConvertible { public var description: String { return String(cString: sqlite3_db_filename(handle, nil)) } } extension Connection.Location : CustomStringConvertible { public var description: String { switch self { case .inMemory: return ":memory:" case .temporary: return "" case .uri(let URI): return URI } } } public enum Result : Error { fileprivate static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] case error(message: String, code: Int32, statement: Statement?) init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } let message = String(cString: sqlite3_errmsg(connection.handle)) self = .error(message: message, code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { public var description: String { switch self { case let .error(message, errorCode, statement): if let statement = statement { return "\(message) (\(statement)) (code: \(errorCode))" } else { return "\(message) (code: \(errorCode))" } } } } #if !SQLITE_SWIFT_SQLCIPHER @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) extension Connection { fileprivate func trace_v2(_ callback: ((String) -> Void)?) { guard let callback = callback else { // If the X callback is NULL or if the M mask is zero, then tracing is disabled. sqlite3_trace_v2(handle, 0 /* mask */, nil /* xCallback */, nil /* pCtx */) trace = nil return } let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } sqlite3_trace_v2(handle, UInt32(SQLITE_TRACE_STMT) /* mask */, { // A trace callback is invoked with four arguments: callback(T,C,P,X). // The T argument is one of the SQLITE_TRACE constants to indicate why the // callback was invoked. The C argument is a copy of the context pointer. // The P and X arguments are pointers whose meanings depend on T. (T: UInt32, C: UnsafeMutableRawPointer?, P: UnsafeMutableRawPointer?, X: UnsafeMutableRawPointer?) in if let P = P, let expandedSQL = sqlite3_expanded_sql(OpaquePointer(P)) { unsafeBitCast(C, to: Trace.self)(expandedSQL) sqlite3_free(expandedSQL) } return Int32(0) // currently ignored }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self) /* pCtx */ ) trace = box } } #endif
gpl-3.0
a53a11074353609cbe89549981e470d4
35.33905
162
0.594482
4.553645
false
false
false
false
perwyl/SCLAlertView-Swift
Example/SCLAlertViewExample/ViewController.swift
1
5080
// // ViewController.swift // SCLAlertViewExample // // Created by Viktor Radchenko on 6/6/14. // Copyright (c) 2014 Viktor Radchenko. All rights reserved. // import UIKit import SCLAlertView let kSuccessTitle = "Congratulations" let kErrorTitle = "Connection error" let kNoticeTitle = "Notice" let kWarningTitle = "Warning" let kInfoTitle = "Info" let kSubtitle = "You've just displayed this awesome Pop Up View" let kDefaultAnimationDuration = 2.0 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showSuccess(sender: AnyObject) { let alert = SCLAlertView() alert.addButton("First Button", target:self, selector:#selector(ViewController.firstButton)) alert.addButton("Second Button") { print("Second button tapped") } alert.showSuccess(kSuccessTitle, subTitle: kSubtitle) } @IBAction func showError(sender: AnyObject) { SCLAlertView().showError("Hold On...", subTitle:"You have not saved your Submission yet. Please save the Submission before accessing the Responses list. Blah de blah de blah, blah. Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.", closeButtonTitle:"OK") // SCLAlertView().showError(self, title: kErrorTitle, subTitle: kSubtitle) } @IBAction func showNotice(sender: AnyObject) { SCLAlertView().showNotice(kNoticeTitle, subTitle: kSubtitle) } @IBAction func showWarning(sender: AnyObject) { SCLAlertView().showWarning(kWarningTitle, subTitle: kSubtitle) } @IBAction func showInfo(sender: AnyObject) { SCLAlertView().showInfo(kInfoTitle, subTitle: kSubtitle) } @IBAction func showEdit(sender: AnyObject) { let appearance = SCLAlertView.SCLAppearance(showCloseButton: true) let alert = SCLAlertView(appearance: appearance) let txt = alert.addTextField("Enter your name") alert.addButton("Show Name") { print("Text value: \(txt.text)") } alert.showEdit(kInfoTitle, subTitle:kSubtitle) } @IBAction func showCustomSubview(sender: AnyObject) { // Create custom Appearance Configuration let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: "HelveticaNeue", size: 20)!, kTextFont: UIFont(name: "HelveticaNeue", size: 14)!, kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 14)!, showCloseButton: false ) // Initialize SCLAlertView using custom Appearance let alert = SCLAlertView(appearance: appearance) // Creat the subview let subview = UIView(frame: CGRectMake(0,0,216,70)) let x = (subview.frame.width - 180) / 2 // Add textfield 1 let textfield1 = UITextField(frame: CGRectMake(x,10,180,25)) textfield1.layer.borderColor = UIColor.greenColor().CGColor textfield1.layer.borderWidth = 1.5 textfield1.layer.cornerRadius = 5 textfield1.placeholder = "Username" textfield1.textAlignment = NSTextAlignment.Center subview.addSubview(textfield1) // Add textfield 2 let textfield2 = UITextField(frame: CGRectMake(x,textfield1.frame.maxY + 10,180,25)) textfield2.secureTextEntry = true textfield2.layer.borderColor = UIColor.blueColor().CGColor textfield2.layer.borderWidth = 1.5 textfield2.layer.cornerRadius = 5 textfield1.layer.borderColor = UIColor.blueColor().CGColor textfield2.placeholder = "Password" textfield2.textAlignment = NSTextAlignment.Center subview.addSubview(textfield2) // Add the subview to the alert's UI property alert.customSubview = subview alert.addButton("Login") { print("Logged in") } // Add Button with Duration Status and custom Colors alert.addButton("Duration Button", backgroundColor: UIColor.brownColor(), textColor: UIColor.yellowColor(), showDurationStatus: true) { print("Duration Button tapped") } alert.showInfo("Login", subTitle: "", duration: 10) } @IBAction func showCustomAlert(sender: AnyObject) { let alert = SCLAlertView() alert.addButton("First Button", target:self, selector:#selector(ViewController.firstButton)) alert.addButton("Second Button") { print("Second button tapped") } let icon = UIImage(named:"custom_icon.png") let color = UIColor.orangeColor() alert.showCustom("Custom Color", subTitle: "Custom color", color: color, icon: icon!) } func firstButton() { print("First button tapped") } }
mit
3d1f3f8bd483140db40e37298a5a1f62
35.546763
343
0.662402
4.64351
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Data Models/Preference Option Models/RefreshOnAppStartOption.swift
1
1121
// // RefreshOnAppStartOption.swift // NearbyWeather // // Created by Erik Maximilian Martens on 10.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import Foundation enum RefreshOnAppStartOptionValue: Int, CaseIterable, Codable, Equatable { case no case yes var boolValue: Bool { switch self { case .no: return false case .yes: return true } } } struct RefreshOnAppStartOption: Codable, Equatable, PreferencesOption { static let availableOptions = [RefreshOnAppStartOption(value: .no), RefreshOnAppStartOption(value: .yes)] typealias PreferencesOptionType = RefreshOnAppStartOptionValue private lazy var count = { RefreshOnAppStartOptionValue.allCases.count } var value: RefreshOnAppStartOptionValue init(value: RefreshOnAppStartOptionValue) { self.value = value } init?(rawValue: Int) { guard let value = RefreshOnAppStartOptionValue(rawValue: rawValue) else { return nil } self.init(value: value) } var rawRepresentableValue: Bool { value.boolValue } }
mit
48c9a208d8815258df18aa2ccc758b14
21.857143
77
0.696429
4.357977
false
false
false
false
LinDing/Positano
Positano/Extensions/CGImage+Yep.swift
1
1343
// // CGImage+Yep.swift // Yep // // Created by nixzhu on 16/1/27. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import UIKit extension CGImage { var yep_extendedCanvasCGImage: CGImage { let width = self.width let height = self.height guard width > 0 && height > 0 else { return self } func hasAlpha() -> Bool { let alpha = self.alphaInfo switch alpha { case .first, .last, .premultipliedFirst, .premultipliedLast: return true default: return false } } var bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue if hasAlpha() { bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue } else { bitmapInfo |= CGImageAlphaInfo.noneSkipFirst.rawValue } guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo) else { return self } context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) guard let newCGImage = context.makeImage() else { return self } return newCGImage } }
mit
948432fc00e1e0dcd357c797bd3b7f27
24.283019
184
0.576119
4.872727
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/FancyModelMaker.swift
1
22444
// // FancyModelMaker.swift // ZeeQL3 // // Created by Helge Hess on 19/05/17. // Copyright © 2017-2019 ZeeZide GmbH. All rights reserved. // import struct Foundation.URL /** * `FancyModelMaker` is here to make plain models (fetched from the DB) fancy. * * (there is `ModelSQLizer` which is the reverse to the `FancyModelMaker`. It * takes a model with no (or partial) external names assigned, and fills them * in w/ SQL conventions). * * The core idea is that you keep your SQL schema SQL-ish but your Swift model * Swifty. * * Example SQL: * * CREATE TABLE person ( * person_id SERIAL PRIMARY KEY NOT NULL, * firstname VARCHAR NULL, * lastname VARCHAR NOT NULL * office_location VARCHAR * ) * * Derived Entity: * * class Entity : CodeEntity<Person> { * let id : Int = 0 * * let firstname : String? = nil * let lastname : String = "" * * let officeLocation : String? = nil * * let addresses = ToMany<Address>() * } * * In addition the maker can: * - detect primary keys (if none are explicitly marked) * - that is `id` and `table_id` * - detect relationships * - e.g. the `address` entity has a `person_id` and there is a `person` table * - create reverse relationships * - e.g. the `address` above would create a to-many in the `person` entity * * Extra Rules: * - by default only lowercase names are considered for camel-casing * - if the externalName/columnName is already different to the name, * we don't touch it */ open class FancyModelMaker { public struct Options { var detectIdAsPrimaryKey = true var detectTableIdAsPrimaryKey = true var detectRelationships = true var createInverseRelationships = true var fancyUpRelshipNames = true var onlyLowerCase = true var capCamelCaseEntityNames = true // person_address => PersonAddress var camelCaseAttributeNames = true // company_id => companyId var useIdForPrimaryKey = true // person_id pkey => id var boolValueTypePrefixes = [ "is_", "can_" ] var urlSuffix : String? = nil // "_url" var keyColumnSuffix = "_id" public init() {} } public final let model : Model public final let options : Options // processing state public final var newModel : Model? = nil public final var renamedEntities = [ String : String ]() public final var renamedAttributesByNewEntityNames = [ String : [ String: String ]]() public final var modelRelationships = [ ModelRelationship ]() public init(model: Model, options: Options = Options()) { self.model = model self.options = options } // MARK: - Fancyfy func clear() { renamedEntities.removeAll() renamedAttributesByNewEntityNames.removeAll() modelRelationships.removeAll() newModel = nil } open func fancyfyModel(reconnect: Bool = true) -> Model { clear() newModel = Model(entities: [], tag: model.tag) // Phase 1 conversion of entities for entity in model.entities { newModel!.entities.append(fancyfyEntity(entity)) } // Patch references to renamed names :-) for mrs in modelRelationships { // TBD: what about `relationshipPath`? Stop if set? let renamedDestAttributes : [ String : String ]? let renamedSourceAttributes = renamedAttributesByNewEntityNames[mrs.entity.name] if let dn = mrs.destinationEntityName { if let newDestName = renamedEntities[dn] { mrs.destinationEntityName = newDestName mrs.destinationEntity = nil // Hm } renamedDestAttributes = renamedAttributesByNewEntityNames[mrs.destinationEntityName!] } else { assert(mrs.destinationEntityName != nil, "relship w/o dest name?") renamedDestAttributes = nil } if renamedSourceAttributes != nil || renamedDestAttributes != nil { // value objects var newJoins = [ Join ]() newJoins.reserveCapacity(mrs.joins.count) for join in mrs.joins { guard let sn = join.sourceName, let dn = join.destinationName else { assert(false, "join misses source or destination name!") continue } newJoins.append(Join(source: renamedSourceAttributes?[sn] ?? sn, destination: renamedDestAttributes? [dn] ?? dn)) } mrs.joins = newJoins } } // improve names of relationships // - for schema fetches the names will contain the name of the constraint // (or the key of the constraint in SQLite). That is usually ugly ;-> if options.fancyUpRelshipNames { for entity in newModel!.entities { for relship in entity.relationships { // we only auto-create toOne relships from SQL databases or by the // auto-detection above. guard !relship.isToMany else { continue } guard let mrs = relship as? ModelRelationship else { continue } // this is our trigger guard relship.isNameConstraintName else { continue } // the name of the relationship really depends on the name of // the foreign key (the source in here) // e.g.: // - owner_id => owner (connecting person.person_id) // - person_id => person (connecting person.person_id) // or use 'toOwner' etc. Makes clashes less likely guard let fkeyAttrName = relship.foreignKey1 else { continue } guard let baseName = fkeyAttrName.withoutId else { continue } // check whether a similar entity already exists ... guard let rsName = entity.availableName(baseName, baseName.toName) else { continue } // assign nicer name // TODO: use 'to' entity.name for exact attr matches, use // 'creator'Id for others // e.g. source: 'creatorId' => 'creator' mrs.name = rsName } } } if options.detectRelationships { // detect relationships // ... if the database schema has no proper constraints setup ..., like, // in the common OGo PostgreSQL schema ... ;-> // collect available tables var tableToEntity = [ String : Entity ]() var tableToPrimaryKeyColumNames = [ String : Set<String> ]() for entity in newModel!.entities { let tableName = entity.externalName ?? entity.name tableToEntity[tableName] = entity if let pkeys = entity.primaryKeyAttributeNames, !pkeys.isEmpty { var columns = Set<String>() for pkey in pkeys { guard let attr = entity[attribute: pkey] else { continue } columns.insert(attr.columnName ?? pkey) } tableToPrimaryKeyColumNames[tableName] = columns } } for entity in newModel!.entities { // skip entities which have constraints. If they have one, we assume // they do all ;-> // // Note: this only works for simple cases, but better than nothing. // e.g. an 'owner_id' pointing to a 'person' table doesn't work. // TBD: maybe we could add additional conventions for such '_id' // tables. guard entity.relationships.isEmpty else { continue } guard let newEntity = entity as? ModelEntity else { continue } let pkeyColumns = tableToPrimaryKeyColumNames[newEntity.externalName ?? newEntity.name] ?? Set<String>() for attr in newEntity.attributes { let colname = attr.columnName ?? attr.name guard !pkeyColumns.contains(colname) else { continue } guard colname.hasSuffix(options.keyColumnSuffix) else { continue } guard colname.count > 3 else { continue } // OK, e.g. person_id. Now check whether there is a person table let endIdx = colname.index(colname.endIndex, offsetBy: -3) let tableName = String(colname[colname.startIndex..<endIdx]) // This only works for target entities which have a single pkey // (currently, we could match multi-keys as well) guard let pkeyColumnNames = tableToPrimaryKeyColumNames[tableName], pkeyColumnNames.count == 1 else { //print("skip key: \(colname) from \(newEntity) to \(tableName))") continue } // primary key columnName doesn't match this foreign key guard pkeyColumnNames.contains(colname) else { continue } // OK, seems to be a match! guard let destEntity = tableToEntity[tableName] else { continue } // TODO: this generates the 'toCompany' guard let sourceAttribute = newEntity [columnName: colname], let destAttribute = destEntity[columnName: colname] else { continue } guard let baseName = sourceAttribute.name.withoutId else { continue } // check whether a similar entity already exists ... guard let rsName = entity.availableName(baseName, baseName.toName) else { continue } let relship = ModelRelationship(name: rsName, isToMany: false, source: newEntity, destination: destEntity) let join = Join(source: sourceAttribute, destination: destAttribute) relship.joins.append(join) newEntity.relationships.append(relship) } } } if options.createInverseRelationships { /* what to do: - scan for toOne relationships - look whether the target has a reverse relationship already - create one otherwise */ for entity in newModel!.entities { for relship in entity.relationships { // we only auto-create toOne relships from SQL databases or by the // auto-detection above. guard !relship.isToMany else { continue } guard let mrs = relship as? ModelRelationship else { continue } guard let destEntityName = mrs.destinationEntityName else { continue } guard let destEntity = newModel![entity: destEntityName] as? ModelEntity else { continue } // - so we have our relationship // - we need to check whether the target already has an inverse var hasInverse = false; for destRelship in destEntity.relationships { // this could be either toMany or toOne. guard relship.isReciprocalTo(relationship: destRelship) else { continue } hasInverse = true } if hasInverse { continue } // create inverse relationship // name is 'creator' or 'owner' or 'company' // we want the reverse, like 'creatorOfAddress' - plural, really // also: 'to' fallback // TODO: if we refer to the primary key, we want just the plurals, // e.g. instead of 'companyOfAddress'(es), use just 'addresses' let baseName = relship.name + "Of" + entity.name // TODO: use 'to' entity.name for exact attr matches, use // 'creator'Id for others // e.g. source: 'creatorId' => 'person.companyId' // -> creatorOf? or creatorOfAppointments? // or base this off the other relship-name? // check whether a similar entity already exists ... guard let rsName = entity.availableName(entity.name.decapitalized.pluralized, baseName, baseName.toName) else { continue } let newRelship = ModelRelationship(name: rsName, isToMany: true, source: destEntity, destination: entity) newRelship.joinSemantic = .leftOuterJoin // TBD for join in relship.joins { // TODO: fix `!` // TBD: can't we use join.inverse? let inverseJoin = Join(source: join.destinationName!, destination: join.sourceName!) newRelship.joins.append(inverseJoin) } destEntity.relationships.append(newRelship) } } } // TODO: fixup relationship names // reconnect model if reconnect { newModel!.connectRelationships() } let result = newModel! clear() return result } open func fancyfyEntity(_ entity: Entity) -> Entity { let newEntity = ModelEntity(entity: entity, deep: true) // map entity name if options.capCamelCaseEntityNames, !newEntity.hasExplicitExternalName, !options.onlyLowerCase || newEntity.name.isLowerCase { let oldName = entity.name if newEntity.externalName == nil { newEntity.externalName = oldName } newEntity.name = newEntity.name.capCamelCase renamedEntities[oldName] = newEntity.name } // map attribute names // TBD: classPropertyNames. Hm. for now assume they are calculated. // to implement this, we need to compare the sets var oldSinglePrimaryKeyName : String? if let pkeys = newEntity.primaryKeyAttributeNames, pkeys.count == 1, options.useIdForPrimaryKey { oldSinglePrimaryKeyName = pkeys[0] } else { oldSinglePrimaryKeyName = nil } var renamedAttributes = [ String : String ]() if options.camelCaseAttributeNames { for attr in newEntity.attributes { guard let ma = attr as? ModelAttribute else { assert(attr is ModelAttribute) // we copied deep, should be all model continue } guard !attr.hasExplicitExternalName else { continue } guard !options.onlyLowerCase || attr.name.isLowerCase else { continue } if options.camelCaseAttributeNames || oldSinglePrimaryKeyName != nil { let oldName = attr.name if attr.columnName == nil { ma.columnName = oldName } // TODO: special case: 'id' for single primary key if let pk = oldSinglePrimaryKeyName, oldName == pk { ma.name = "id" } else { ma.name = oldName.camelCase } renamedAttributes[oldName] = ma.name } } } if !renamedAttributes.isEmpty { renamedAttributesByNewEntityNames[newEntity.name] = renamedAttributes } // map primary key names if let oldPKeys = newEntity.primaryKeyAttributeNames, !oldPKeys.isEmpty { newEntity.primaryKeyAttributeNames = oldPKeys.map { renamedAttributes[$0] ?? $0 } } assignPrimaryKeyIfMissing(newEntity) patchValueTypesOfAttributes(newEntity) recordRelationshipsOfNewEntity(newEntity) return newEntity } func assignPrimaryKeyIfMissing(_ newEntity: ModelEntity) { // there is also a simpler Entity.lookupPrimaryKeyAttributeNames() guard newEntity.primaryKeyAttributeNames?.count ?? 0 == 0 else { return } if options.detectIdAsPrimaryKey && newEntity[attribute: "id"] != nil { newEntity.primaryKeyAttributeNames = [ "id" ] } else if options.detectTableIdAsPrimaryKey { let keyname = (newEntity.externalName ?? newEntity.name) + options.keyColumnSuffix if let attr = newEntity[columnName: keyname] { newEntity.primaryKeyAttributeNames = [ attr.name ] } } } func patchValueTypesOfAttributes(_ newEntity: Entity) { // TBD: maybe value-type assignment shaould be always done in here? // convert Value type to bool type, e.g. of the column name starts with an // 'is_' guard !options.boolValueTypePrefixes.isEmpty else { return } for attr in newEntity.attributes { let cn = attr.columnName ?? attr.name guard !options.onlyLowerCase || cn.isLowerCase else { continue } guard let ma = attr as? ModelAttribute else { assert(attr is ModelAttribute) // we copied deep, should be all model continue } if let urlSuffix = options.urlSuffix, cn.hasSuffix(urlSuffix) { if let oldVT = ma.valueType { if oldVT.isOptional { if oldVT.optionalBaseType == String.self { ma.valueType = Optional<URL>.self } } else { if oldVT == String.self { ma.valueType = URL.self } } } else { ma.valueType = (ma.allowsNull ?? true) ? Optional<URL>.self : URL.self } continue } for prefix in options.boolValueTypePrefixes { if cn.hasPrefix(prefix) { // Note: this includes NULL columns in a special way! // TBD: only certain types of valueTypes? ma.valueType = Bool.self } } } } /// process relationships, record for later patching func recordRelationshipsOfNewEntity(_ newEntity: Entity) { for rs in newEntity.relationships { guard let mrs = rs as? ModelRelationship else { assert(rs is ModelRelationship) // we copied deep, should be all model continue } modelRelationships.append(mrs) } } } // MARK: - String Helpers #if os(Linux) import func Glibc.isupper #else import func Darwin.isupper #endif import struct Foundation.CharacterSet fileprivate extension Entity { var hasExplicitExternalName : Bool { guard let en = externalName else { return false } return en != name } func availableName(_ names: String...) -> String? { for name in names { if self[relationship: name] == nil && self[attribute: name] == nil { return name } } return nil } } fileprivate extension Attribute { var hasExplicitExternalName : Bool { guard let en = columnName else { return false } return en != name } } fileprivate extension Relationship { var foreignKey1 : String? { guard joins.count == 1 else { return nil } let join = joins[0] return join.sourceName ?? join.source?.name } var isNameConstraintName : Bool { guard let en = constraintName else { return false } return en == name } func isReciprocalTo(relationship: Relationship) -> Bool { if let dmrs = relationship as? ModelRelationship, let destDestEntityName = dmrs.destinationEntityName { guard destDestEntityName == entity.name else { return false } } else if let destEntity = relationship.destinationEntity { // TBD: compare just names? Hm. if entity !== destEntity { return false } } else { // no target entity? return false } return areJoinsReciprocalTo(relationship: relationship) } func areJoinsReciprocalTo(relationship: Relationship) -> Bool { guard joins.count == relationship.joins.count else { return false } // FIXME: ordering doesn't have to be the same?! for i in 0..<joins.count { let baseJoin = joins[i] let destJoin = relationship.joins[i] guard baseJoin.isReciprocalTo(join: destJoin) else { return false } } return true } } extension String { var toName : String { return "to" + capitalized } var withoutId : String? { guard hasSuffix("Id") else { return nil } guard count > 2 else { return nil } let endIdx = self.index(endIndex, offsetBy: -2) return String(self[startIndex..<endIdx]) } var decapitalized : String { guard !isEmpty else { return "" } let idx = self.index(after: self.startIndex) let c0 = self[self.startIndex..<idx].lowercased() return c0 + self[idx..<self.endIndex] } func makeCamelCase(upperFirst: Bool) -> String { guard !self.isEmpty else { return "" } var newChars = [ Character ]() var upperNext = upperFirst for c in self { switch c { case " ", "_": // skip and upper next // FIXME: wrong behaviour for columns starting with _ upperNext = true continue case "a"..."z": if upperNext { let s = String(c).uppercased() newChars.append(s[s.startIndex]) upperNext = false } else { newChars.append(c) } default: upperNext = false newChars.append(c) } } guard !newChars.isEmpty else { return self } return String(newChars) } var capCamelCase : String { return makeCamelCase(upperFirst: true) } var camelCase : String { return makeCamelCase(upperFirst: false) } var isLowerCase : Bool { guard !isEmpty else { return false } let upper = CharacterSet.uppercaseLetters for c in self.unicodeScalars { if upper.contains(c) { return false } } return true } var isMixedCase : Bool { guard !isEmpty else { return false } let upper = CharacterSet.uppercaseLetters let lower = CharacterSet.lowercaseLetters var hadUpper = false var hadLower = false for c in self.unicodeScalars { if upper.contains(c) { if hadLower { return true } hadUpper = true } else if lower.contains(c) { if hadUpper { return true } hadLower = true } } return false } }
apache-2.0
33ba77956e995f9fa00d04a0e9ceda4a
31.338617
80
0.585528
4.635068
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift
132
2400
// // SingleAssignmentDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /** Represents a disposable resource which only allows a single assignment of its underlying disposable resource. If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. */ public final class SingleAssignmentDisposable : DisposeBase, Cancelable { fileprivate enum DisposeState: UInt32 { case disposed = 1 case disposableSet = 2 } // Jeej, swift API consistency rules fileprivate enum DisposeStateInt32: Int32 { case disposed = 1 case disposableSet = 2 } // state private var _state: AtomicInt = 0 private var _disposable = nil as Disposable? /// - returns: A value that indicates whether the object is disposed. public var isDisposed: Bool { return AtomicFlagSet(DisposeState.disposed.rawValue, &_state) } /// Initializes a new instance of the `SingleAssignmentDisposable`. public override init() { super.init() } /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. /// /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** public func setDisposable(_ disposable: Disposable) { _disposable = disposable let previousState = AtomicOr(DisposeState.disposableSet.rawValue, &_state) if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { rxFatalError("oldState.disposable != nil") } if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { disposable.dispose() _disposable = nil } } /// Disposes the underlying disposable. public func dispose() { let previousState = AtomicOr(DisposeState.disposed.rawValue, &_state) if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { return } if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { guard let disposable = _disposable else { rxFatalError("Disposable not set") } disposable.dispose() _disposable = nil } } }
mit
fe33e18b236cff48903120e37b4f85ba
30.565789
141
0.65569
5.071882
false
false
false
false
lnakamura/heroku-toolbelt-ios
Toolbelt/RootViewController.swift
1
4362
// // ViewController.swift // Toolbelt // // Created by Liane Nakamura on 12/24/15. // Copyright © 2015 lianenakamura. All rights reserved. // import UIKit class RootViewController: UIViewController { let repoCellIdentifier: String = "repoCellIdentifier" var dataSource: [Repo] = [Repo]() lazy var tableView: UITableView = { var tableView = UITableView() tableView.dataSource = self tableView.delegate = self return tableView }() override func loadView() { super.loadView() view.backgroundColor = UIColor.whiteColor() view.addSubview(tableView) setupConstraints() } override func viewDidLoad() { super.viewDidLoad() title = "Apps" navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) // Table view tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: repoCellIdentifier) getAccessToken() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setupConstraints() { tableView.translatesAutoresizingMaskIntoConstraints = false let views: [String : UIView] = [ "tableView": tableView, ] let metrics: [String : String] = ["": ""] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[tableView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) } private func getAccessToken() { HerokuClient.sharedInstance.getAccessToken( { [weak self] (response) -> Void in self?.getApps() }, failure: { [weak self] (response) -> Void in print(response) let alert: UIAlertController = UIAlertController(title: "Error", message: "Did not receive response from Heroku.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(okAction) self?.presentViewController(alert, animated: true, completion: nil) } ) } private func getApps() { HerokuClient.sharedInstance.getApps( { [weak self] (repos) -> Void in self?.dataSource = repos self?.tableView.reloadData() }, failure: { (response) -> Void in print(response) } ) } } extension RootViewController: UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(repoCellIdentifier, forIndexPath: indexPath) cell.accessoryView = nil if (dataSource.count > indexPath.row) { let repo: Repo = dataSource[indexPath.row] cell.textLabel?.text = repo.name } cell.textLabel?.numberOfLines = 1 cell.textLabel?.adjustsFontSizeToFitWidth = true cell.selectionStyle = UITableViewCellSelectionStyle.Default return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } } extension RootViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if (dataSource.count > indexPath.row) { let repo: Repo = dataSource[indexPath.row] let repoDetailViewController = RepoDetailViewController() repoDetailViewController.repo = repo navigationController?.pushViewController(repoDetailViewController, animated: true) } } }
mit
919099aea6a494ecdf2d7a8a3a46d262
31.789474
171
0.625545
5.569604
false
false
false
false
tanhuiya/ThPullRefresh
ThPullRefresh/UIScrollView+Extension.swift
2
1547
// // File.swift // PullRefresh // // Created by tanhui on 15/12/27. // Copyright © 2015年 tanhui. All rights reserved. // import Foundation import UIKit extension UIScrollView{ var th_offsetX : CGFloat { set { self.contentOffset = CGPointMake(newValue, self.contentOffset.x) } get{ return self.contentOffset.x } } var th_offsetY : CGFloat { set { self.contentOffset = CGPointMake(self.contentOffset.x, newValue) } get{ return self.contentOffset.y } } var th_insetL : CGFloat { set{ var inset = self.contentInset inset.left = newValue self.contentInset = inset } get{ return self.contentInset.left } } var th_insetT : CGFloat { set{ var inset = self.contentInset inset.top = newValue self.contentInset = inset } get{ return self.contentInset.top } } var th_insetR : CGFloat { set{ var inset = self.contentInset inset.right = newValue self.contentInset = inset } get{ return self.contentInset.right } } var th_insetB : CGFloat { set{ var inset = self.contentInset inset.bottom = newValue self.contentInset = inset } get{ return self.contentInset.bottom } } }
mit
0552b4c814e686b232d23160fd3721df
21.057143
76
0.509067
4.664653
false
false
false
false
roambotics/swift
test/SILGen/indirect_enum.swift
2
25345
// RUN: %target-swift-emit-silgen -module-name indirect_enum -Xllvm -sil-print-debuginfo %s | %FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () { func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $TreeA<T>, [[ARG3:%.*]] : @guaranteed $TreeA<T>): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[ARG1]] to [init] [[T_BUF]] : $*T // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr [take] [[T_BUF]] to [init] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK-NEXT: dealloc_stack [[T_BUF]] : $*T let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeA<T>.Branch(left: l, right: r) } // CHECK: // end sil function '$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () { func TreeA_reabstract(_ f: @escaping (Int) -> Int) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: [[THUNK:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]]) // CHECK-NEXT: [[FNC:%.*]] = convert_function [[FN]] // CHECK-NEXT: store [[FNC]] to [init] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK: return let _ = TreeA<(Int) -> Int>.Leaf(f) } // CHECK: } // end sil function '$s13indirect_enum16TreeA_reabstractyyS2icF' enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [init] [[T_BUF]] // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: copy_addr [take] [[T_BUF]] to [init] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] // CHECK-NEXT: dealloc_stack [[T_BUF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[ARG1_COPY:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: copy_addr %1 to [init] [[ARG1_COPY]] : $*TreeB<T> // CHECK-NEXT: [[ARG2_COPY:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: copy_addr %2 to [init] [[ARG2_COPY]] : $*TreeB<T> // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr [take] [[ARG1_COPY]] to [init] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr [take] [[ARG2_COPY]] to [init] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] // CHECK-NEXT: dealloc_stack [[ARG2_COPY]] // CHECK-NEXT: dealloc_stack [[ARG1_COPY]] let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> () func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) { // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed $TreeInt, [[ARG3:%.*]] : @guaranteed $TreeInt): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt, [[ARG1]] // CHECK-NOT: destroy_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $TreeInt // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] : $TreeInt // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeInt.Branch(left: l, right: r) } // CHECK: } // end sil function '$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF' enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(_ x: T) {} func c<T>(_ x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () { func switchTreeA<T>(_ x: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): // -- x +0 // CHECK: switch_enum [[ARG]] : $TreeA<T>, // CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]], // CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE:bb2]], // CHECK: case #TreeA.Branch!enumelt: [[BRANCH_CASE:bb3]], switch x { // CHECK: [[NIL_CASE]]: // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [init] [[X:%.*]] : $*T // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +0 // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : @guaranteed $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]] // CHECK: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: switch_enum [[LEFT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE_LEFT:bb[0-9]+]], // CHECK: default [[FAIL_LEFT:bb[0-9]+]] // CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: switch_enum [[RIGHT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE_RIGHT:bb[0-9]+]], // CHECK: default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_RIGHT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_LEFT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +0 default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 } // CHECK: } // end sil function '$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F func switchTreeB<T>(_ x: TreeB<T>) { // CHECK: copy_addr %0 to [init] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [init] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [init] [[LEAF:%.*]] : // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [init] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [init] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [init] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [init] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [init] [[Y:%.*]] : // CHECK: function_ref @$s13indirect_enum1c{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // -- box +0 // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[RIGHT_FAIL]]: // CHECK: destroy_addr [[LEFT_LEAF]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: function_ref @$s13indirect_enum1dyyF // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: return } // Make sure that switchTreeInt obeys ownership invariants. // // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F func switchTreeInt(_ x: TreeInt) { switch x { case .Nil: a() case .Leaf(let x): b(x) case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) default: d() } } // CHECK: } // end sil function '$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F func guardTreeA<T>(_ tree: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO1:bb[0-9]+]] // CHECK: [[YES]]: guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack [lexical] $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [init] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [init] [[X]] // CHECK: destroy_value [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO4:bb[0-9]+]] // CHECK: [[NO4]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]: // CHECK: br if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack [lexical] $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO5:bb[0-9]+]] // CHECK: [[NO5]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [init] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [init] [[X]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO2]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO1]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F func guardTreeB<T>(_ tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [init] [[TMP1:%.*]] : // CHECK: switch_enum_addr [[TMP1]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP1]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack [lexical] $T // CHECK: copy_addr %0 to [init] [[TMP2:%.*]] : // CHECK: switch_enum_addr [[TMP2]] : $*TreeB<T>, case #TreeB.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP2]] // CHECK: copy_addr [take] [[VALUE]] to [init] [[X]] // CHECK: dealloc_stack [[TMP2]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack [lexical] $TreeB // CHECK: [[R:%.*]] = alloc_stack [lexical] $TreeB // CHECK: copy_addr %0 to [init] [[TMP3:%.*]] : // CHECK: switch_enum_addr [[TMP3]] : $*TreeB<T>, case #TreeB.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP3]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [init] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [init] [[L]] // CHECK: copy_addr [take] [[R_COPY]] to [init] [[R]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [init] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack [lexical] $T // CHECK: copy_addr %0 to [init] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [init] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack [lexical] $TreeB // CHECK: [[R:%.*]] = alloc_stack [lexical] $TreeB // CHECK: copy_addr %0 to [init] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [init] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [init] [[L]] // CHECK: copy_addr [take] [[R_COPY]] to [init] [[R]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]: // CHECK: destroy_addr [[TMP3]] // CHECK: [[NO2]]: // CHECK: destroy_addr [[TMP2]] // CHECK: [[NO1]]: // CHECK: destroy_addr [[TMP1]] } // Just run guardTreeInt through the ownership verifier // // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum12guardTreeInt{{[_0-9a-zA-Z]*}}F func guardTreeInt(_ tree: TreeInt) { do { guard case .Nil = tree else { return } guard case .Leaf(let x) = tree else { return } guard case .Branch(left: let l, right: let r) = tree else { return } } do { if case .Nil = tree { } if case .Leaf(let x) = tree { } if case .Branch(left: let l, right: let r) = tree { } } } // SEMANTIC ARC TODO: This test needs to be made far more comprehensive. // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () { func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TrivialButIndirect): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt: [[NO:bb[0-9]+]] // guard case .Direct(let foo) = x else { return } // CHECK: [[YES]]({{%.*}} : $Int): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt: [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[BOX]] // CHECK: [[NO2]]({{%.*}} : $Int): // CHECK-NOT: destroy_value // CHECK: [[NO]]([[PAYLOAD:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[PAYLOAD]] guard case .Indirect(let bar) = x else { return } } // CHECK: } // end sil function '$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF' // Make sure that in these cases we do not break any ownership invariants. class Box<T> { var value: T init(_ inputValue: T) { value = inputValue } } enum ValueWithInlineStorage<T> { case inline(T) indirect case box(Box<T>) } func switchValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) { switch v { case .inline: return case .box(let box): return } } func guardValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) { do { guard case .inline = v else { return } guard case .box(let box) = v else { return } } do { if case .inline = v { return } if case .box(let box) = v { return } } }
apache-2.0
4b42712e42bd93f0d5924117d7e23eeb
42.201365
184
0.541239
3.044618
false
false
false
false
shmidt/ContactsPro
ContactsPro/FormCells/EditLongTextTableViewCell.swift
1
3671
// // LongTextTableViewCell.swift // // Created by Dmitry Shmidt on 25/12/14. // Copyright (c) 2014 Dmitry Shmidt. All rights reserved. // import UIKit class EditLongTextTableViewCell: UITableViewCell { typealias PickLongTextCompletionHandler = (longText:String) -> Void var completionHandler:PickLongTextCompletionHandler? = nil func pick(completion:PickLongTextCompletionHandler) { completionHandler = completion } var label:String{ get { return labelLabel.text! } set{ labelLabel.text = newValue } } /// Custom setter so we can initialise the height of the text view var longText:String{ get { return textView.text } set { textView.text = newValue textViewDidChange(textView) } } @IBOutlet weak var labelLabel: UILabel! @IBOutlet weak var textView: UITextView! override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Disable scrolling inside the text view so we enlarge to fitted size textView.scrollEnabled = false textView.delegate = self textView.textContainer.widthTracksTextView = true textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { textView.becomeFirstResponder() } else { textView.resignFirstResponder() } } func textViewDidEndEditing(textView: UITextView) { let text = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if let c = completionHandler{ c(longText:text) } } } extension EditLongTextTableViewCell: UITextViewDelegate { func textViewDidChange(textView: UITextView) { var bounds = textView.bounds let maxSize = CGSize(width: bounds.size.width, height: CGFloat(MAXFLOAT)) var newSize = textView.sizeThatFits(maxSize) // Minimum size is 50 newSize.height = max(50.0, newSize.height) bounds.size = newSize textView.bounds = bounds // Only way found to make table view update layout of cell // More efficient way? if let tableView = tableView { tableView.beginUpdates() tableView.endUpdates() } } } //extension EditLongTextTableViewCell: UITextViewDelegate { // func textViewDidChange(textView: UITextView) { // // let size = textView.bounds.size // let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.max)) // // // Resize the cell only when cell's size is changed // if size.height != newSize.height { // UIView.setAnimationsEnabled(false) // tableView?.beginUpdates() // tableView?.endUpdates() // UIView.setAnimationsEnabled(true) // // if let thisIndexPath = tableView?.indexPathForCell(self) { // tableView?.scrollToRowAtIndexPath(thisIndexPath, atScrollPosition: .Bottom, animated: false) // } // } // } //}
mit
884b3458669bc341d449240aea5f0e55
29.591667
115
0.613457
5.251788
false
false
false
false
ivanfoong/SniPository
SniPository/Git.swift
1
13899
// // Git.swift // SniPository // // Created by Ivan Foong Kwok Keong on 17/7/17. // Copyright © 2017 ivanfoong. All rights reserved. // protocol FileType { var filename: String { get } } protocol GitFileType: FileType { var status: GitFileStatus { get } } struct File: FileType { let filename: String } struct GitFile: GitFileType { let filename: String let status: GitFileStatus } enum GitFileStatus { case notUpdated, updatedInIndex, addedToIndex, deletedFromIndex, renamedInIndex, copiedInIndex, unmergedBothDeleted, unmergedAddedByUs, unmergedDeletedByThem, unmergedAddedByThem, unmergedDeletedByUs, unmergedBothAdded, unmergedBothModified } enum GitFileStatusCode: String { case unmodified = " " case modified = "M" case added = "A" case deleted = "D" case renamed = "R" case copied = "C" case updatedAndUnmerged = "U" } struct GitStatus { var files: [GitFile] var untrackedFiles: [File] var ignoredFiles: [File] } class Git { typealias GitPath = String typealias GitRemoteURL = String typealias GitRemoteName = String typealias GitBranchName = String typealias GitResult = (command: String, output: CommandLine.Output) @discardableResult func initialize(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git init" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (true, (command, output)) } func status(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (status: GitStatus?, result: GitResult) { let command = "git status --porcelain --ignored" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) if output.exitCode != 0 { return (nil, (command, output)) } var files: [GitFile] = [] var untrackedFiles: [File] = [] var ignoredFiles: [File] = [] for line in output.output { let stagedStatusCode = line.substring(to: line.index(line.startIndex, offsetBy: 1)) let unstagedStatusCode = line.substring(with: line.index(line.startIndex, offsetBy: 1)..<line.index(line.startIndex, offsetBy: 2)) let filename = line.substring(from: line.index(line.startIndex, offsetBy: 3)) if stagedStatusCode == "!" && unstagedStatusCode == "!" { // ignored file ignoredFiles.append(File(filename: filename)) } else if stagedStatusCode == "?" && unstagedStatusCode == "?" { // untracked file untrackedFiles.append(File(filename: filename)) } else if let stagedStatus = GitFileStatusCode.init(rawValue: stagedStatusCode), let unstagedStatus = GitFileStatusCode.init(rawValue: unstagedStatusCode) { switch(stagedStatus, unstagedStatus) { case (.unmodified, .modified), (.unmodified, .deleted): // not updated files.append(GitFile(filename: filename, status: .notUpdated)) case (.modified, .unmodified), (.modified, .modified), (.modified, .deleted): // updated in index files.append(GitFile(filename: filename, status: .updatedInIndex)) case (.added, .unmodified), (.added, .modified), (.added, .deleted): // added to index files.append(GitFile(filename: filename, status: .addedToIndex)) case (.deleted, .unmodified), (.deleted, .modified): // deleted from index files.append(GitFile(filename: filename, status: .deletedFromIndex)) case (.renamed, .unmodified), (.renamed, .modified), (.renamed, .deleted): // renamed in index files.append(GitFile(filename: filename, status: .renamedInIndex)) case (.copied, .unmodified), (.copied, .modified), (.copied, .deleted): // copied in index files.append(GitFile(filename: filename, status: .copiedInIndex)) case (.deleted, .deleted): // unmerged, both deleted files.append(GitFile(filename: filename, status: .unmergedBothDeleted)) case (.added, .updatedAndUnmerged): // unmerged, added by us files.append(GitFile(filename: filename, status: .unmergedAddedByUs)) case (.updatedAndUnmerged, .deleted): // unmerged, deleted by them files.append(GitFile(filename: filename, status: .unmergedDeletedByThem)) case (.updatedAndUnmerged, .added): // unmerged, added by them files.append(GitFile(filename: filename, status: .unmergedAddedByThem)) case (.deleted, .updatedAndUnmerged): // unmerged, deleted by us files.append(GitFile(filename: filename, status: .unmergedDeletedByUs)) case (.added, .added): // unmerged, both added files.append(GitFile(filename: filename, status: .unmergedBothAdded)) case (.updatedAndUnmerged, .updatedAndUnmerged): // unmerged, both modified files.append(GitFile(filename: filename, status: .unmergedBothModified)) default: // TODO assertionFailure("Unexpected XY combination: \(stagedStatusCode), \(unstagedStatusCode)") } } } let status = GitStatus(files: files, untrackedFiles: untrackedFiles, ignoredFiles: ignoredFiles) return (status, (command, output)) } @discardableResult func add(file: String, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git add \(file)" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode==0, (command, output)) } @discardableResult func addAllFiles(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git add --all" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode==0, (command, output)) } @discardableResult func commit(with message: String, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "commit", "-m \(message)"] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func add(remote url: GitRemoteURL, for name: GitRemoteName, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git remote add \(name) \(url)" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } func listRemote(for name: GitRemoteName, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (remoteUrl: GitRemoteURL?, result: GitResult) { let command = "git ls-remote --get-url \(name)" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) var remoteUrl: GitRemoteURL? if output.exitCode == 0 && output.output.count > 0 && output.output[0] != "" { remoteUrl = output.output[0] } return (remoteUrl, (command, output)) } @discardableResult func pull(branch: GitBranchName, from remoteName: GitRemoteName, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "pull", remoteName, branch, "--rebase", "-X ours"] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func push(branch: GitBranchName, for remoteName: GitRemoteName, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "push", remoteName, branch] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func checkout(file: String, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "checkout", "--theirs", file] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func create(branch: String, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "branch", branch] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func checkout(branch: String, at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let commands = ["git", "checkout", branch] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (commands.joined(separator: " "), output)) } @discardableResult func rebaseContinue(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git rebase --continue" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } @discardableResult func reset(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git reset HEAD~1" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } @discardableResult func stashSave(at path: GitPath, includeUntracked: Bool = true, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git stash save -u" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } @discardableResult func stashApply(at path: GitPath, for index: Int = 0, includeUntracked: Bool = true, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git stash apply stash@{\(index)}" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } @discardableResult func stashDrop(at path: GitPath, for index: Int = 0, includeUntracked: Bool = true, with environment: [String: String] = [:], verbose: Bool = false) -> (success: Bool, result: GitResult) { let command = "git stash drop stash@{\(index)}" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) return (output.exitCode == 0, (command, output)) } func updatedFiles(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (updatedFiles: [String]?, result: GitResult) { let commands = ["git", "diff", "--name-only", "--diff-filter=U"] let output = CommandLine().exec(commands: commands, at: path, with: environment, verbose: verbose) if output.exitCode != 0 { return (nil, (commands.joined(separator: " "), output)) } let filenames = output.output.flatMap { line -> String? in if line != "" { return line } return nil } return (filenames, (commands.joined(separator: " "), output)) } func currentBranch(at path: GitPath, with environment: [String: String] = [:], verbose: Bool = false) -> (currentBranchName: GitBranchName?, result: GitResult) { let command = "git rev-parse --abbrev-ref HEAD" let output = CommandLine().exec(command: command, at: path, with: environment, verbose: verbose) if output.exitCode != 0 { return (nil, (command, output)) } var currentBranchName: GitBranchName? if output.output.count > 0 && output.output[0] != "" { currentBranchName = output.output[0] } return (currentBranchName, (command, output)) } }
mit
a826d1ee279891893bc0cedd13945691
50.284133
244
0.614045
4.276308
false
false
false
false
raysarebest/Meghann
Bucket Game/Bucket Game/MHMasterViewController.swift
1
3595
// // MasterViewController.swift // Bucket Game // // Created by Michael Hulet on 5/22/15. // Copyright (c) 2015 Michael Hulet. All rights reserved. // import UIKit import CoreData class MHMasterViewController: UITableViewController, NSFetchedResultsControllerDelegate{ //MARK: - Global Variables lazy var results: NSFetchedResultsController = { let request = NSFetchRequest(entityName: MHGameSerializationKeys.GameClassName.rawValue) request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: MHCoreDataStack.defaultStack.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) controller.delegate = self return controller }() //MARK: - View Controller Lifecycle override func viewDidLoad() -> Void{ super.viewDidLoad() do{ try results.performFetch() } catch let error as NSError{ print(error) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) -> Void{ if segue.identifier == "showDetail"{ let selectedIndexPath = tableView.indexPathForSelectedRow! tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true) (segue.destinationViewController as! MHDetailViewController).game = results.objectAtIndexPath(selectedIndexPath) as? MHGame } super.prepareForSegue(segue, sender: sender) } //MARK: - UITableViewDataSource Functions override func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return results.sections!.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return (results.sections![section] as NSFetchedResultsSectionInfo).numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let formatter = NSDateFormatter() let game = results.objectAtIndexPath(indexPath) as! MHGame formatter.dateStyle = .ShortStyle formatter.timeStyle = .ShortStyle let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel!.text = formatter.stringFromDate(game.date) cell.detailTextLabel!.text = "\(game.score)" return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) -> Void{ if editingStyle == .Delete{ MHCoreDataStack.defaultStack.managedObjectContext!.deleteObject(results.objectAtIndexPath(indexPath) as! NSManagedObject) MHCoreDataStack.defaultStack.saveContext() } } //MARK: - NSFetchedResultsControllerDelegate Functions func controllerDidChangeContent(controller: NSFetchedResultsController) -> Void{ tableView.reloadData() } //MARK: - IBActions @IBAction func newGame() -> Void{ let newGame = NSEntityDescription.insertNewObjectForEntityForName(MHGameSerializationKeys.GameClassName.rawValue, inManagedObjectContext: MHCoreDataStack.defaultStack.managedObjectContext!) as! MHGame newGame.date = NSDate() MHCoreDataStack.defaultStack.saveContext() tableView.selectRowAtIndexPath(results.indexPathForObject(newGame), animated: true, scrollPosition: .Top) performSegueWithIdentifier("showDetail", sender: self) } }
gpl-3.0
4669ea1d41bdc4c6dc8a0f14e9467cba
48.260274
208
0.726008
5.798387
false
false
false
false
norio-nomura/RxSwift
RxSwift/Concurrency/ScheduledItem.swift
1
1582
// // ScheduledItem.swift // RxSwift // // Created by 野村 憲男 on 4/20/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation public protocol IScheduledItem: class { typealias AbsoluteTime var dueTime: AbsoluteTime {get} func invoke() } public class ScheduledItemBase<TAbsolute: Comparable>: IScheduledItem { // MARK: IScheduledItem typealias AbsoluteTime = TAbsolute public let dueTime: AbsoluteTime public func invoke() { if !_disposable.isDisposed { _disposable.disposable = invokeCore() } } // MARK: public public func cancel() { _disposable.dispose() } public var isCanceled: Bool { return _disposable.isDisposed } // MARK: internal init(dueTime: AbsoluteTime) { self.dueTime = dueTime } func invokeCore() -> IDisposable? { fatalError("Abstract method \(__FUNCTION__)") } // MARK: private let _disposable = SingleAssignmentDisposable() } public final class ScheduledItem<TAbsolute: Comparable>: ScheduledItemBase<TAbsolute> { public init(scheduler: IScheduler, action: IScheduler -> IDisposable?, dueTime: TAbsolute) { self.scheduler = scheduler self.action = action super.init(dueTime: dueTime) } // MARK: internal override func invokeCore() -> IDisposable? { return action(scheduler) } // MARK: private private let scheduler: IScheduler private let action: IScheduler -> IDisposable? }
mit
27399496a4b6db0e59df8b360eefbf29
22.848485
96
0.634689
4.536023
false
false
false
false
rporzuc/FindFriends
FindFriends/FindFriends/Reachability.swift
1
1102
// // Reachability.swift // FindFriends // // Created by MacOSXRAFAL on 04/01/18. // Copyright © 2018 MacOSXRAFAL. All rights reserved. // import Foundation import SystemConfiguration public class Reachability{ public func isConnectedToNetwork() -> Bool{ var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags){ return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } }
gpl-3.0
133df10fdc856918e9ac2cb5ecab5011
27.973684
82
0.621253
5.14486
false
false
false
false
chrisjmendez/swift-exercises
Games/GameProgressTimer/GameProgressTimer/GameScene.swift
1
1622
// // GameScene.swift // Positioning // // Created by Tommy Trojan on 10/8/15. // Copyright (c) 2015 Chris Mendez. All rights reserved. // import SpriteKit class GameScene: SKScene { let countDown = 3.0 var progress:ProgressNode? func checkDimensions(){ let frameW = self.frame.width let frameH = self.frame.height print( "frame width:", frameW, "frame height:", frameH ) } override func didMoveToView(view: SKView) { progress = ProgressNode() progress?.name = "progress" progress?.radius = CGRectGetWidth(self.frame) * 0.25 progress?.width = 15.0 progress?.color = SKColor.blueColor() progress?.backgroundColor = SKColor(red: 120, green: 153, blue: 185, alpha: 1) progress?.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) progress?.countdown(countDown, progressHandler: onProgress, completionHandler: onProgressComplete) self.addChild(progress!) checkDimensions() } func onProgress(){ //print("onProgress") } func onProgressComplete(){ //print("onProgressComplete") progress?.removeFromParent() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { let location = touch.locationInNode(self) print(location) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
2e8ed83cd0f30f680802123dd77802eb
27.45614
106
0.61529
4.607955
false
false
false
false
bamboostick/MIKMIDI
Examples/iOS/MIDI to Audio iOS/MIDI to Audio iOS/ViewController.swift
1
4582
// // ViewController.swift // MIDI to Audio iOS // // Created by Sasha Ivanov on 2016-12-24. // Copyright © 2016 madebysasha. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit import AVFoundation import MIKMIDI class ViewController: UIViewController { var midiUrl:URL? var soundfontUrl:URL? var sequencer:MIKMIDISequencer? var audioUrl:URL? var audioPlayer:AVPlayer? @IBOutlet weak var playOriginalButton: UIButton! @IBOutlet weak var convertToAudioFileButton: UIButton! @IBOutlet weak var playConvertedAudioFileButton: UIButton! @IBAction func playOriginalButtonPressed(_ sender: Any) { // Play the sequencer sequencer?.startPlayback() } @IBAction func convertToAudioFileButtonPressed(_ sender: Any) { // Create the MIKMIDI Audio Exporter let audioExporter = MIKMIDIToAudioExporter(midiFileAt: midiUrl) // Add the soundfont to the Audio Exporter (NEW from macOS Example) audioExporter?.addSoundfont(soundfontUrl) // Render the MIDI file as a CAF file with the added soundfont audioExporter?.exportWithSoundfontToAudioFile(completionHandler: { (audioOutputUrl, error) in // Check if there was an error durring the export if (audioOutputUrl == nil){ if((error) != nil){ NSLog(error as! String) print("Audio Conversion Failed") } } // Otherwise save the output url and enable the Play Converted Audio button else{ self.audioUrl = audioOutputUrl self.playConvertedAudioFileButton.isEnabled = true } }) } @IBAction func playConvertedButtonPressed(_ sender: Any) { // Create an AV Audio Player to playback the converted file audioPlayer = AVPlayer(url: audioUrl!) // Play the converted file audioPlayer?.play() } override func viewDidLoad() { super.viewDidLoad() // 1. Disable the Play Converted Audio button. (Will enable when the convert button is pressed) playConvertedAudioFileButton.isEnabled = false // 2. Set the URLs of the files we want to use for playback (midi file and soundfont file) midiUrl = Bundle.main.url(forResource: "TheOriginal", withExtension: "mid") soundfontUrl = Bundle.main.url(forResource: "Stereo Piano", withExtension: ".sf2") // 3. Setup the MIKMIDI Sequencer for Playing Back Original Midi File do{ // Create a MIKMIDI Sequence from the midi file let sequence = try MIKMIDISequence(fileAt: midiUrl!) // Create a MIKMIDI Sequencer from the sequence sequencer = MIKMIDISequencer(sequence: sequence) // Use the Soundfont File to set the Synth for each Track in the Sequence. for track in sequence.tracks{ let synth = sequencer?.builtinSynthesizer(for: track) try synth!.loadSoundfontFromFile(at: soundfontUrl!) } } catch{ print("Unable to Create Sequencer") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
d0f5488396107b1d0fa967f180832a13
34.238462
103
0.642873
4.8579
false
false
false
false
lastobelus/eidolon
Kiosk/Bid Fulfillment/BidDetailsPreviewView.swift
5
3482
import UIKit import Artsy_UILabels import Artsy_UIButtons import UIImageViewAligned import Swift_RAC_Macros class BidDetailsPreviewView: UIView { dynamic var bidDetails: BidDetails? dynamic let artworkImageView = UIImageViewAligned() dynamic let artistNameLabel = ARSansSerifLabel() dynamic let artworkTitleLabel = ARSerifLabel() dynamic let currentBidPriceLabel = ARSerifLabel() override func awakeFromNib() { self.backgroundColor = .whiteColor() artistNameLabel.numberOfLines = 1 artworkTitleLabel.numberOfLines = 1 currentBidPriceLabel.numberOfLines = 1 artworkImageView.alignRight = true artworkImageView.alignBottom = true artworkImageView.contentMode = .ScaleAspectFit artistNameLabel.font = UIFont.sansSerifFontWithSize(14) currentBidPriceLabel.font = UIFont.serifBoldFontWithSize(14) RACObserve(self, "bidDetails.saleArtwork.artwork").subscribeNext { [weak self] (artwork) -> Void in if let url = (artwork as? Artwork)?.defaultImage?.thumbnailURL() { self?.bidDetails?.setImage(url: url, imageView: self!.artworkImageView) } else { self?.artworkImageView.image = nil } } RAC(self, "artistNameLabel.text") <~ RACObserve(self, "bidDetails.saleArtwork.artwork").map({ (artwork) -> AnyObject! in return (artwork as? Artwork)?.artists?.first?.name }).mapNilToEmptyString() RAC(self, "artworkTitleLabel.attributedText") <~ RACObserve(self, "bidDetails.saleArtwork.artwork").map({ (artwork) -> AnyObject! in if let artwork = artwork as? Artwork { return artwork.titleAndDate } else { return nil } }).mapNilToEmptyAttributedString() RAC(self, "currentBidPriceLabel.text") <~ RACObserve(self, "bidDetails").map({ (bidDetails) -> AnyObject! in if let cents = (bidDetails as? BidDetails)?.bidAmountCents { return "Your bid: " + NSNumberFormatter.currencyStringForCents(cents) } return nil }).mapNilToEmptyString() for subview in [artworkImageView, artistNameLabel, artworkTitleLabel, currentBidPriceLabel] { self.addSubview(subview) } self.constrainHeight("60") artworkImageView.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: self) artworkImageView.constrainWidth("84") artworkImageView.constrainHeight("60") artistNameLabel.alignAttribute(.Top, toAttribute: .Top, ofView: self, predicate: "0") artistNameLabel.constrainHeight("16") artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artistNameLabel, predicate: "8") artworkTitleLabel.constrainHeight("16") currentBidPriceLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkTitleLabel, predicate: "4") currentBidPriceLabel.constrainHeight("16") UIView.alignAttribute(.Leading, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], toAttribute:.Trailing, ofViews: [artworkImageView, artworkImageView, artworkImageView], predicate: "20") UIView.alignAttribute(.Trailing, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], toAttribute:.Trailing, ofViews: [self, self, self], predicate: "0") } }
mit
502fb75c993a18eabbf9fbbfba0c8584
43.075949
213
0.668868
5.283763
false
false
false
false
ajrosario08/Psychologist
Psychologist/PsychologistViewController.swift
1
1067
// // ViewController.swift // Psychologist // // Created by Anthony Rosario on 11/2/15. // Copyright © 2015 Anthony Rosario. All rights reserved. // import UIKit class PsychologistViewController: UIViewController { @IBAction func nothing(sender: UIButton) { performSegueWithIdentifier("nothing", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destination = segue.destinationViewController if let navCon = destination as? UINavigationController { destination = navCon.visibleViewController! } if let hvc = destination as? HappinessViewController { if let identifier = segue.identifier { switch identifier { case "sad": hvc.happiness = 0 case "happy": hvc.happiness = 100 case "nothing": hvc.happiness = 25 default: hvc.happiness = 50 } } } } }
gpl-2.0
6925202911db3846a224da9e35d22336
27.810811
81
0.572233
5.581152
false
false
false
false
kshin/Jet
Source/RequestParameters.swift
1
1220
// // Created by Ivan Lisovyi on 3/26/17. // Copyright (c) 2017 Ivan Lisovyi. All rights reserved. // import Foundation import Alamofire public typealias ParameterEncoding = Alamofire.ParameterEncoding public struct RequestParameters { public let encoding: ParameterEncoding public private(set) var values: [String: Any] public init(encoding: ParameterEncoding, values: [String: Any]) { self.encoding = encoding self.values = values } public subscript(key: String) -> Any? { get { return values[key] } set { values[key] = newValue } } } extension RequestParameters: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let values = elements.reduce([String: Any]()) { dictionary, element in var result = dictionary result[element.0] = element.1 return result } self.init(encoding: URLEncoding(), values: values) } } infix operator => public func => (encoding: ParameterEncoding, values: [String: Any]) -> RequestParameters { return RequestParameters(encoding: encoding, values: values) }
mit
480f99d1f465672119f33d50ab75e71b
24.957447
90
0.639344
4.656489
false
false
false
false
TsuiOS/LoveFreshBeen
LoveFreshBeenX/Class/View/Home/XNHomeHotView.swift
1
2408
// // XNHomeHotView.swift // LoveFreshBeenX // // Created by xuning on 16/6/15. // Copyright © 2016年 hus. All rights reserved. // import UIKit private extension Selector { static let iconClick = #selector(XNHomeHotView.iconClick(_:)) } class XNHomeHotView: UIView { private let iconW = (ScreenWidth - 2 * HotViewMargin) * 0.25 private let iconH: CGFloat = 80; override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: 模型的set方法 var headData: HeadData? { didSet { if headData?.icons?.count > 0 { if (headData?.icons?.count)! % 4 != 0 { self.rows = (headData?.icons?.count)! / 4 + 1 } else { self.rows = (headData?.icons?.count)! / 4 } var iconX: CGFloat = 0 var iconY: CGFloat = 0 for i in 0..<headData!.icons!.count { iconX = CGFloat(i % 4) * iconW + HotViewMargin iconY = iconH * CGFloat(i / 4) let activitie: Activities = headData!.icons![i] let icon = XNCustomButton(title: headData!.icons![i].name!, color: UIColor.blackColor(), fontSize: 13, imageWithURL: NSURL(string: activitie.img!)!, placeholderImageName: "icon_icons_holder") icon.frame = CGRectMake(iconX, iconY, iconW, iconH-20) let sizeWh = icon.currentImage?.size icon.sd_setImageWithURL(NSURL(string: activitie.img!)!, forState: UIControlState.Normal) icon.imageView?.frame = CGRectMake(0, 0, (sizeWh?.width)!, (sizeWh?.height)!) icon.tag = i icon.addTarget(self, action: .iconClick, forControlEvents: .TouchUpInside) addSubview(icon) } } } } // MARK: rows数量 private var rows: Int = 0 { willSet { bounds = CGRectMake(0, 0, ScreenWidth, iconH * CGFloat(newValue)) } } func iconClick(button: UIButton) { print(button.tag) } }
mit
6270cc32b318b4baefefc7eb436d4ff3
27.807229
211
0.505228
4.411439
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/PushNotification/GMSPushNotification.swift
1
10675
// // GlobalMessageService+PushNotification.swift // Pods // // Created by Vitalii Budnik on 12/14/15. // // import Foundation import UIKit // swiftlint:disable line_length /** Apple Remote Push-notification presenter - SeeAlso: [The Remote Notification Payload](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html) */ public struct GlobalMessageServicePushNotification { // swiftlint:enable line_length /** Stores shared `NSNumberFormatter` */ static private let numberFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() return formatter }() /** `UInt64` Global Message Services message identifier */ public let gmsMessageID: UInt64 /** `String` Google Cloud Messaging message identifier */ public let gcmMessageID: String? /** `String` representing senders alpha name. Can be `nil` */ public let alphaName: String /** The number to display as the app’s icon badge. */ public let bage: Int? /** The name of the file containing the sound to play when an alert is displayed. */ public let sound: String? /** Provide this key with a value of `true` to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed `application:didReceiveRemoteNotification:fetchCompletionHandler:` is called. */ public let contentAvailable: Bool // swiftlint:disable line_length /** Provide this key with a string value that represents the identifier property of the `UIMutableUserNotificationCategory` object you created to define custom actions. To learn more about using custom actions. - SeeAlso: [Registering Your Actionable Notification Types](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW26). */ public let category: String? // swiftlint:enable line_length /// The text of the alert message. public let body: String? /** A short string describing the purpose of the notification. Apple Watch displays this string as part of the notification interface. This string is displayed only briefly and should be crafted so that it can be understood quickly. This key was added in iOS 8.2. */ public let title: String? /** The key to a title string in the `Localizable.strings` file for the current localization. The key string can be formatted with `%@` and `%n$@` specifiers to take the variables specified in the `titleLocalizationArguments` array. */ public let titleLocalizationKey: String? /** Variable string values to appear in place of the format specifiers in `titleLocalizationKey`. */ public let titleLocalizationArguments: [String]? /** If a string is specified, the system displays an alert that includes the Close and View buttons. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”. */ public let actionLocalizationKey: String? /** A key to an alert-message string in a `Localizable.strings` file for the current localization (which is set by the user’s language preference). The key string can be formatted with `%@` and `%n$@` specifiers to take the variables specified in the `localizationArguments` array. */ public let localizationKey: String? /** Variable string values to appear in place of the format specifiers in `localizationKey` */ public let localizationArguments: [String]? /** The filename of an image file in the app bundle; it may include the extension or omit it. The image is used as the launch image when users tap the action button or move the action slider. If this property is not specified, the system either uses the previous snapshot,uses the image identified by the `UILaunchImageFile` key in the app’s `Info.plist` file, or falls back to `Default.png`. */ public let launchImage: String? /// `Bool` that indicates user allowed alert- or sound-notifications for this application is Settings public let notificationsAllowed: Bool public let deliveredDate: NSDate // swiftlint:disable valid_docs /** Initalizes `GlobalMessageServicePushNotification` with - Parameter withNotificationInfo: `[NSObject : AnyObject]` with modified payload, where `"data"` dictionary shifted to root - Parameter gmsMessageID: `UInt64` Global Message Services message identifier - Parameter gcmMessageID: `String` Google Cloud Messaging message identifier. Can be `nil` - Parameter alphaName: `String` representing senders alpha name. Can be `nil` - Parameter notificationsAllowed: `Bool` that indicates user allowed alert- or sound-notifications for this application is Settings - Returns: Initalizated `struct` */ private init( withNotificationInfo notifictionInfo: [String : AnyObject], gmsMessageID: UInt64, gcmMessageID: String?, alphaName: String, notificationsAllowed: Bool = true) // swiftlint:disable:this opening_brace { // swiftlint:enable valid_docs let tmpSound: String self.gmsMessageID = gmsMessageID self.gcmMessageID = gcmMessageID self.alphaName = alphaName self.notificationsAllowed = notificationsAllowed tmpSound = notifictionInfo["sound"] as? String ?? UILocalNotificationDefaultSoundName contentAvailable = (notifictionInfo["content-available"] as? Int ?? 0) == 1 ? true : false category = notifictionInfo["category"] as? String sound = tmpSound == "default" ? UILocalNotificationDefaultSoundName : tmpSound bage = notifictionInfo["bage"] as? Int ?? 0 if let alert = notifictionInfo["alert"] as? [String: AnyObject] { body = alert["body"] as? String title = alert["title"] as? String titleLocalizationKey = alert["title-loc-key"] as? String titleLocalizationArguments = alert["title-loc-args"] as? [String] actionLocalizationKey = alert["action-loc-key"] as? String localizationKey = alert["loc-key"] as? String localizationArguments = alert["loc-args"] as? [String] launchImage = alert["launch-image"] as? String } else { body = notifictionInfo["alert"] as? String ?? notifictionInfo["body"] as? String title = notifictionInfo["title"] as? String titleLocalizationKey = notifictionInfo["title-loc-key"] as? String titleLocalizationArguments = notifictionInfo["title-loc-args"] as? [String] actionLocalizationKey = notifictionInfo["action-loc-key"] as? String localizationKey = notifictionInfo["loc-key"] as? String localizationArguments = notifictionInfo["loc-args"] as? [String] launchImage = notifictionInfo["launch-image"] as? String } deliveredDate = NSDate() } /** Returns `UInt64` Global Message Services message identifier, stored in push-notification payload. Can return `0` - Parameter withUserInfo: `[NSObject : AnyObject]` with modified payload, where `"data"` dictionary shifted to root - Returns: `UInt64` with Global Message Services message identifier. Can be `0` if key not found, or can't be typecasted */ private static func getGMSMessageID( withUserInfo userInfo: [NSObject : AnyObject]) -> UInt64 // swiftlint:disable:this opnening_brace { let gmsMessageID: UInt64 if let incomeMessageID = userInfo["msg_gms_uniq_id"] { if let incomeMessageID = incomeMessageID as? String { if let incomeMessageIDFromString = GlobalMessageServicePushNotification.numberFormatter .numberFromString(incomeMessageID)?.unsignedLongLongValue { gmsMessageID = incomeMessageIDFromString } else { gmsLog.error("String incomeMessageID not convertible to UInt64") gmsMessageID = 0 } } else if let incomeMessageID = incomeMessageID as? Double { gmsMessageID = UInt64(incomeMessageID) } else { gmsLog.error("unexpected userInfo[\"uniqAppDeviceId\"] type: \(incomeMessageID.dynamicType)") gmsMessageID = 0 } } else { gmsMessageID = 0 } return gmsMessageID } // swiftlint:disable valid_docs /** Initalizes `GlobalMessageServicePushNotification` with push-notification payload - Parameter withNotificationInfo: `[NSObject : AnyObject]` with modified payload, where `"data"` dictionary shifted to root - Parameter notificationsAllowed: `Bool` that indicates user allowed alert- or sound-notifications for this application is Settings - Returns: Initalizated `struct` if sucessfully parsed `userInfo` parameter, otherwise returns `nil` */ internal init?(withUserInfo userInfo: [NSObject : AnyObject], notificationsAllowed: Bool = true) { // swiftlint:enable valid_docs let gmsMessageID = GlobalMessageServicePushNotification.getGMSMessageID(withUserInfo: userInfo) let gcmMessageID: String? if let _gcmMessageID = userInfo["gcm.message_id"] as? String { gcmMessageID = _gcmMessageID if gmsMessageID == 0 { gmsLog.debug("recieved message from GCM, that was not sended by GSM (no msg_gms_uniq_id key)") } } else { gmsLog.verbose("No Google, no cry") gcmMessageID = .None } guard let notifictionString = userInfo["notification"] as? String, let notifictionData = notifictionString.dataUsingEncoding(NSUTF8StringEncoding), let json = try? NSJSONSerialization.JSONObjectWithData( notifictionData, options: NSJSONReadingOptions.AllowFragments), let notifictionInfo = json as? [String: NSObject] else { gmsLog.error("no 'notification' data ") return nil } self = GlobalMessageServicePushNotification( withNotificationInfo: notifictionInfo, gmsMessageID: gmsMessageID, gcmMessageID: gcmMessageID, alphaName: userInfo["alpha"] as? String ?? GMSInboxAlphaName.unknownAlphaNameString, notificationsAllowed: notificationsAllowed) } }
apache-2.0
02d3a7d28fb4aba2dcd143bd097261e9
36.15331
244
0.689393
4.760268
false
false
false
false
nakajijapan/UIColor-Hex
ColorHex_macOSTests/ColorHex_macOSTests.swift
1
1325
// // ColorHex_macOSTests.swift // ColorHex_macOSTests // // Created by nakajijapan on 2018/01/07. // Copyright © 2018年 nakajijapan. All rights reserved. // import XCTest import ColorHex class ColorHex_macOSTests: XCTestCase { func testWhiteColor() { let color = NSColor(red: 1, green: 1, blue: 1, alpha: 1) XCTAssert(color.isEqual(NSColor(hex:0xffffff)), "White") let calibratedColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 1) XCTAssert(calibratedColor.isEqual(NSColor(calibratedHex: 0xffffff)), "White") } func testBlackColor() { let color = NSColor(red: 0, green: 0, blue: 0, alpha: 1) XCTAssert(color.isEqual(NSColor(hex:0x000000)), "Black") let calibratedColor = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 1) XCTAssert(calibratedColor.isEqual(NSColor(calibratedHex: 0x000000)), "Black") } func testOpacity() { let color = NSColor(red: 0, green: 0, blue: 0, alpha: 0.5) XCTAssert(color.isEqual(NSColor(hex:0x000000, alpha:0.5)), "Black & Opacity") let calibratedColor = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 0.5) XCTAssert(calibratedColor.isEqual(NSColor(calibratedHex: 0x000000, alpha:0.5)), "Black & Opacity") } }
mit
0b83aa224c37113b7e24aba61c3c797b
33.789474
106
0.645234
3.651934
false
true
false
false
sammyd/Concurrency-VideoSeries
projects/006_NSOperationInPractice/006_DemoStarter/TiltShift/TiltShift/ImageDecompressionOperation.swift
4
2212
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit protocol ImageDecompressionOperationDataProvider { var compressedData: NSData? { get } } class ImageDecompressionOperation: NSOperation { private let inputData: NSData? private let completion: ((UIImage?) -> ())? private var outputImage: UIImage? init(data: NSData?, completion: ((UIImage?) -> ())? = nil) { inputData = data self.completion = completion super.init() } override func main() { let compressedData: NSData? if let inputData = inputData { compressedData = inputData } else { let dataProvider = dependencies .filter { $0 is ImageDecompressionOperationDataProvider } .first as? ImageDecompressionOperationDataProvider compressedData = dataProvider?.compressedData } guard let data = compressedData else { return } if let decompressedData = Compressor.decompressData(data) { outputImage = UIImage(data: decompressedData) } completion?(outputImage) } } extension ImageDecompressionOperation: ImageFilterDataProvider { var image: UIImage? { return outputImage } }
mit
8daa6aa947110b8ac0e0984a1ab68908
33.030769
79
0.733725
4.819172
false
false
false
false
stripe/stripe-ios
StripePaymentSheet/StripePaymentSheet/Internal/Link/Components/PaymentMethodPicker/LinkPaymentMethodPicker-RadioButton.swift
1
3539
// // LinkPaymentMethodPicker-RadioButton.swift // StripePaymentSheet // // Created by Ramon Torres on 11/15/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import UIKit extension LinkPaymentMethodPicker { final class RadioButton: UIView { struct Constants { static let diameter: CGFloat = 20 static let innerDiameter: CGFloat = 8 static let borderWidth: CGFloat = 1 } public var isOn: Bool = false { didSet { update() } } public var borderColor: UIColor = .linkControlBorder { didSet { applyStyling() } } /// Layer for the "off" state. private let offLayer: CALayer = { let layer = CALayer() layer.bounds = CGRect(x: 0, y: 0, width: Constants.diameter, height: Constants.diameter) layer.cornerRadius = Constants.diameter / 2 layer.borderWidth = Constants.borderWidth layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) return layer }() /// Layer for the "on" state. private let onLayer: CALayer = { let layer = CALayer() layer.bounds = CGRect(x: 0, y: 0, width: Constants.diameter, height: Constants.diameter) layer.cornerRadius = Constants.diameter / 2 layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) let innerCircle = CALayer() innerCircle.backgroundColor = UIColor.white.cgColor innerCircle.cornerRadius = Constants.innerDiameter / 2 innerCircle.bounds = CGRect(x: 0, y: 0, width: Constants.innerDiameter, height: Constants.innerDiameter) innerCircle.anchorPoint = CGPoint(x: 0.5, y: 0.5) // Add and center inner circle layer.addSublayer(innerCircle) innerCircle.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY) return layer }() override var intrinsicContentSize: CGSize { return CGSize(width: Constants.diameter, height: Constants.diameter) } init() { super.init(frame: .zero) layer.addSublayer(offLayer) layer.addSublayer(onLayer) update() applyStyling() } required init?(coder: NSCoder) { super.init(coder: coder) applyStyling() } override func layoutSubviews() { offLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) onLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) } override func tintColorDidChange() { super.tintColorDidChange() applyStyling() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) applyStyling() } // MARK: - Private methods private func update() { CATransaction.begin() CATransaction.setDisableActions(true) offLayer.isHidden = isOn onLayer.isHidden = !isOn CATransaction.commit() } private func applyStyling() { CATransaction.begin() CATransaction.setDisableActions(true) offLayer.borderColor = borderColor.cgColor onLayer.backgroundColor = tintColor.cgColor CATransaction.commit() } } }
mit
1c3b0222e3e2360ccc543c4ea1c2a10d
30.035088
116
0.57377
5.07604
false
false
false
false
mpclarkson/StravaSwift
Sources/StravaSwift/SwiftyJSON.swift
1
850
// // SwiftJSON.swift // Pods // // Created by MATTHEW CLARKSON on 28/05/2016. // // import SwiftyJSON extension RawRepresentable { init?(o rawValue: RawValue?) { guard let rawValue = rawValue, let value = Self(rawValue: rawValue) else { return nil } self = value } } extension JSON { public func strava<T: Strava>(_ type: T.Type?) -> T? { return type?.init(self) } public func strava<T: RawRepresentable>(_ type: T.Type?) -> T? where T.RawValue == Int { return type?.init(optionalRawValue: self.int) } public func strava<T: RawRepresentable>(_ type: T.Type?) -> T? where T.RawValue == String { return type?.init(optionalRawValue: self.string) } public func strava<T: Strava>(_ type: T.Type?) -> [T]? { return self.arrayValue.compactMap { T($0) } } }
mit
f0e54c19c01f66a68032b05e39a8d48b
24
95
0.608235
3.526971
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/IntroducePage/QSLastIntroduceCell.swift
1
2339
// // QSLastIntroduceCell.swift // zhuishushenqi // // Created by yung on 2017/6/11. // Copyright © 2017年 QS. All rights reserved. // import UIKit typealias Completion = ()->Void class QSLastIntroduceCell: UITableViewCell { var sinaLogin:Completion? var qqLoginAction:Completion? var noAccountCompletion:Completion? @IBAction func weiboLogin(_ sender: Any) { if let sina = sinaLogin { sina() } } @IBAction func qqLogin(_ sender: Any) { if let qq = qqLoginAction { qq() } } var noAccount: UIButton? @IBOutlet weak var qqLoginBtn: UIButton! @IBOutlet weak var sinaLoginBtn: UIButton! @objc func noAccountAction(_ sender: Any) { if let noAcc = noAccountCompletion { noAcc() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code // QSLog(noAccount.frame) // (102.0, 451.0, 118.0, 30.0) noAccount = UIButton(frame: CGRect(x: self.bounds.size.width/2 - 118/2, y: self.qqLoginBtn.frame.maxY + 44, width: 118, height: 30)) let dict = [NSAttributedString.Key.underlineStyle:1,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15)] as [NSAttributedString.Key : Any] let attr = NSMutableAttributedString(string: "没有帐号怎么办?", attributes: dict) noAccount?.setAttributedTitle(attr, for: .normal) noAccount?.titleLabel?.textAlignment = .center noAccount?.titleLabel?.textColor = UIColor.white noAccount?.addTarget(self, action: #selector(noAccountAction(_:)), for: .touchUpInside) contentView.addSubview(noAccount!) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func layoutSubviews() { super.layoutSubviews() noAccount?.frame = CGRect(x: self.bounds.size.height/2 - 118/2, y: self.qqLoginBtn.frame.maxY + 44, width: 118, height: 30) } } class QSLoginButton: UIButton { override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = CGRect(x: 15, y: 11, width: 20, height: 20) // NSUnderlineStyle.styleSingle } }
mit
194439a6e7c5792f9828ce76821280b5
30.378378
152
0.637382
4.073684
false
false
false
false
fdzsergio/Reductio
Source/Search.swift
1
777
/** This file is part of the Reductio package. (c) Sergio Fernández <[email protected]> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ import Foundation internal struct Search { static func binary<T: Comparable>(_ array: [T], target: T) -> Bool { var left = 0 var right = array.count - 1 while left <= right { let mid = (left + right) / 2 let value = array[mid] if value == target { return true } if value < target { left = mid + 1 } if value > target { right = mid - 1 } } return false } }
mit
c37fd5c1ad171d522c7f159c932ddd02
21.171429
72
0.511598
4.384181
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/SearchVC/WaitingScreen/WaitingVC.swift
1
8815
import Appodeal @objcMembers class WaitingVC: HLCommonVC, HLVariantsManagerDelegate, HLCityInfoLoadingProtocol, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, HLDeceleratingProgressAnimatorDelegate, AppodealInterstitialDelegate { @IBOutlet var collectionView: UICollectionView! @IBOutlet var waitingActivityIndicator: UIActivityIndicatorView! @IBOutlet var progressView: UIProgressView! let kAverageSearchDuration: TimeInterval = 10.0 let kCollectionViewFadeDuration: TimeInterval = 0.5 let kFinishingSearchDuration: TimeInterval = 0.5 let cellFactory = WaitingCellFactory() let variantsManager = HLVariantsManager() let citiesByPointDetector = HLCitiesByPointDetector() var gateItemsMap: [String: GateItem] = [:] var waitingItems: [WaitingLoadingItem] = [] var sections: [WaitingSection] = [] var searchInfo: HLSearchInfo! let progressAnimator = HLDeceleratingProgressAnimator() private var showErrorAction: (() -> Void)? private var canShowError = true { didSet { if canShowError { showErrorAction?() showErrorAction = nil } } } override func viewDidLoad() { super.viewDidLoad() title = searchInfo.city?.name collectionView.backgroundColor = JRColorScheme.mainBackgroundColor() cellFactory.registerNibs(collectionView) var insets = collectionView.contentInset insets.bottom += 10.0 + kNavBarHeight if iPad() { insets.bottom += 30.0 } collectionView.contentInset = insets waitingActivityIndicator.startAnimating() tryStartSearch() addLongSearchSection() addSearchInfoView(searchInfo) Appodeal.setInterstitialDelegate(self) Appodeal.showAd(.interstitial, rootViewController: self.navigationController ?? self) progressView.trackTintColor = UIColor.clear progressView.progressTintColor = JRColorScheme.actionColor() progressAnimator.delegate = self startProgress() } override func goBack() { navigationController?.popViewController(animated: true) } private func addLongSearchSection() { let longSearchSection = WaitingSection() longSearchSection.items = [WaitingLongSearchItem()] sections.append(longSearchSection) } func tryStartSearch() { let canStartImmediatelly = !searchInfo.isSearchByLocation() && searchInfo.searchInfoType != .userLocation if canStartImmediatelly { startSearch() } else { citiesByPointDetector.detectNearbyCitiesForSearchInfo(searchInfo, onCompletion: { [weak self](nearbyCities: [HDKCity]) in guard nearbyCities.count > 0 else { self?.onSearchError(NSError(serverWith: HLErrorCode.noNearbyCitiesError)) return } self?.searchInfo.locationPoint?.nearbyCities = nearbyCities self?.startSearch() }, onError: { [weak self](error) in self?.onSearchError(error) }) } } // MARK: - AppodealInterstitialDelegate func interstitialWillPresent() { canShowError = false } func interstitialDidDismiss() { canShowError = true } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let section = sections[indexPath.section] let item = section.items[indexPath.row] return item.accept(cellFactory, collectionView: collectionView, indexPath: indexPath) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sections[section].items.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let section = sections[indexPath.section] let item = section.items[indexPath.item] let width = collectionView.bounds.size.width return CGSize(width: width, height: item.cellHeight(containerWidth: width)) } // MARK: - HLDeceleratingProgressAnimatorDelegate func progressChanged(_ progress: CGFloat) { progressView.progress = Float(progress) } // MARK: - HLCityInfoLoadingProtocol func variantsManagerSearchRoomsStarted(with gates: [HDKGate]) { waitingItems = gates.map { return GateItem(gate: $0) } waitingItems.append(OtherGatesItem()) gateItemsMap = waitingItems.hdk_toDictionary { (element: WaitingItem) -> (key: String, value: GateItem)? in guard let gateItem = element as? GateItem else { return nil } return (gateItem.gate.gateId, gateItem) } let section = WaitingSection() section.items = waitingItems.map { $0 as WaitingItem } sections.append(section) hl_dispatch_main_sync_safe {() -> Void in self.waitingActivityIndicator.stopAnimating() self.collectionView.reloadData() UIView.animate(withDuration: self.kCollectionViewFadeDuration, animations: { self.collectionView.alpha = 1.0 }) } } func variantsManagerSearchRoomsDidReceiveData(fromGatesIds gateIds: [String]) { hl_dispatch_main_sync_safe { for gateId in gateIds { self.gateItemsMap[gateId]?.isLoaded = true } for cell in self.collectionView.visibleCells { if let gateCell = cell as? WaitingGateCell, let gateItem = gateCell.gateItem { gateCell.configureForGateItem(gateItem) } } } } func variantsManagerFinished(_ searchResult: SearchResult) { goToResults(searchResult) } fileprivate func goToResults(_ searchResult: SearchResult) { hl_dispatch_main_async_safe { self.progressAnimator.stop(withDuration: self.kFinishingSearchDuration) self.markAllCellsAsLoaded() let dispatchTime = DispatchTime.now() + self.kFinishingSearchDuration DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: { self.moveToResultsVCVariants(searchResult) }) } } func markAllCellsAsLoaded() { for var item in waitingItems { item.isLoaded = true } collectionView.reloadData() } func variantsManagerFailedWithError(_ error: Error) { hl_dispatch_main_async_safe { self.waitingActivityIndicator.stopAnimating() self.progressAnimator.stop(withDuration: 0) self.onSearchError(error) } } func variantsManagerCancelled() { } // MARK: - Private methods private func onSearchError(_ error: Error) { let showErrorAction: (() -> Void)? = { hl_dispatch_main_sync_safe { HLAlertsFabric.showSearchAlertViewWithError(error, handler: { _ in self.goBack() }) } } if canShowError { showErrorAction?() } else { self.showErrorAction = showErrorAction } } private func citiesForSearchInfo(_ searchInfo: HLSearchInfo) -> [HDKCity] { if let city = searchInfo.city { return [city] } return searchInfo.locationPoint?.nearbyCities ?? [] } private func startSearch() { variantsManager.delegate = self variantsManager.searchInfo = searchInfo variantsManager.startCitySearch() } private func startProgress() { progressView.progress = 0.0 progressAnimator.start(withDuration: kAverageSearchDuration) } private func moveToResultsVCVariants(_ searchResult: SearchResult) { let resultsVC = iPad() ? HLIpadResultsVC(nibName: "HLIpadResultsVC", bundle: nil) : HLIphoneResultsVC(nibName: "HLIphoneResultsVC", bundle: nil) resultsVC.searchInfo = (searchInfo.copy() as! HLSearchInfo) resultsVC.setSearchResult(searchResult: searchResult) if let navController = navigationController { var controllers = navController.viewControllers let lastIndex = controllers.count - 1 controllers[lastIndex] = resultsVC navController.setViewControllers(controllers, animated: true) } } }
mit
58a8858fa94f80ce49f8c66802ce43d9
32.645038
160
0.649575
5.083622
false
false
false
false
masters3d/xswift
exercises/phone-number/Sources/PhoneNumberExample.swift
1
1172
import Foundation private extension String { subscript (range: CountableClosedRange<Int>) -> String { get { let start = characters.index(startIndex, offsetBy: range.lowerBound) let end = characters.index(start, offsetBy: range.upperBound - range.lowerBound) return self[start...end] } } var onlyDigits: String { return String(characters.filter { $0.isDigit }) } } private extension Character { var isDigit: Bool { return "0123456789".characters.contains(self) } } struct PhoneNumber: CustomStringConvertible { let number: String init(_ startingNumber: String) { let digits = startingNumber.onlyDigits switch digits.characters.count { case 10: number = digits case 11 where digits.hasPrefix("1"): number = digits[1...10] default: number = "0000000000" } } var areaCode: String { return number[0...2] } var description: String { let prefix = number[3...5] let final = number[6...9] return "(\(areaCode)) \(prefix)-\(final)" } }
mit
aa5967e3f9d5736744c94331abf66919
22.918367
92
0.584471
4.525097
false
false
false
false
zmeyc/SQLite.swift
Sources/SQLite/Typed/CoreFunctions.swift
1
24647
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 ExpressionType where UnderlyingType : Number { /// Builds a copy of the expression wrapped with the `abs` function. /// /// let x = Expression<Int>("x") /// x.absoluteValue /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. public var absoluteValue : Expression<UnderlyingType> { return "abs".wrap(self) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number { /// Builds a copy of the expression wrapped with the `abs` function. /// /// let x = Expression<Int?>("x") /// x.absoluteValue /// // abs("x") /// /// - Returns: A copy of the expression wrapped with the `abs` function. public var absoluteValue : Expression<UnderlyingType> { return "abs".wrap(self) } } extension ExpressionType where UnderlyingType == Double { /// Builds a copy of the expression wrapped with the `round` function. /// /// let salary = Expression<Double>("salary") /// salary.round() /// // round("salary") /// salary.round(2) /// // round("salary", 2) /// /// - Returns: A copy of the expression wrapped with the `round` function. @warn_unused_result public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> { guard let precision = precision else { return wrap([self]) } return wrap([self, Int(precision)]) } } extension ExpressionType where UnderlyingType == Double? { /// Builds a copy of the expression wrapped with the `round` function. /// /// let salary = Expression<Double>("salary") /// salary.round() /// // round("salary") /// salary.round(2) /// // round("salary", 2) /// /// - Returns: A copy of the expression wrapped with the `round` function. @warn_unused_result public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> { guard let precision = precision else { return wrap(self) } return wrap([self, Int(precision)]) } } extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 { /// Builds an expression representing the `random` function. /// /// Expression<Int>.random() /// // random() /// /// - Returns: An expression calling the `random` function. @warn_unused_result public static func random() -> Expression<UnderlyingType> { return "random".wrap([]) } } extension ExpressionType where UnderlyingType == NSData { /// Builds an expression representing the `randomblob` function. /// /// Expression<Int>.random(16) /// // randomblob(16) /// /// - Parameter length: Length in bytes. /// /// - Returns: An expression calling the `randomblob` function. @warn_unused_result public static func random(_ length: Int) -> Expression<UnderlyingType> { return "randomblob".wrap([]) } /// Builds an expression representing the `zeroblob` function. /// /// Expression<Int>.allZeros(16) /// // zeroblob(16) /// /// - Parameter length: Length in bytes. /// /// - Returns: An expression calling the `zeroblob` function. @warn_unused_result public static func allZeros(_ length: Int) -> Expression<UnderlyingType> { return "zeroblob".wrap([]) } /// Builds a copy of the expression wrapped with the `length` function. /// /// let data = Expression<NSData>("data") /// data.length /// // length("data") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int> { return wrap(self) } } extension ExpressionType where UnderlyingType == NSData? { /// Builds a copy of the expression wrapped with the `length` function. /// /// let data = Expression<NSData?>("data") /// data.length /// // length("data") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int?> { return wrap(self) } } extension ExpressionType where UnderlyingType == String { /// Builds a copy of the expression wrapped with the `length` function. /// /// let name = Expression<String>("name") /// name.length /// // length("name") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int> { return wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. /// /// let name = Expression<String>("name") /// name.lowercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression<UnderlyingType> { return "lower".wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. /// /// let name = Expression<String>("name") /// name.uppercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression<UnderlyingType> { return "upper".wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// /// let email = Expression<String>("email") /// email.like("%@example.com") /// // "email" LIKE '%@example.com' /// email.like("99\\%@%", escape: "\\") /// // "email" LIKE '99\%@%' ESCAPE '\' /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - escape: An (optional) character designated for escaping /// pattern-matching characters (*i.e.*, the `%` and `_` characters). /// /// - Returns: A copy of the expression appended with a `LIKE` query against /// the given pattern. @warn_unused_result public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> { guard let character = character else { return "LIKE".infix(self, pattern) } return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)]) } /// Builds a copy of the expression appended with a `GLOB` query against the /// given pattern. /// /// let path = Expression<String>("path") /// path.glob("*.png") /// // "path" GLOB '*.png' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. @warn_unused_result public func glob(_ pattern: String) -> Expression<Bool> { return "GLOB".infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against /// the given pattern. /// /// let title = Expression<String>("title") /// title.match("swift AND programming") /// // "title" MATCH 'swift AND programming' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. @warn_unused_result public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against /// the given pattern. /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. @warn_unused_result public func regexp(_ pattern: String) -> Expression<Bool> { return "REGEXP".infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with /// the given sequence. /// /// let name = Expression<String>("name") /// name.collate(.Nocase) /// // "name" COLLATE NOCASE /// /// - Parameter collation: A collating sequence. /// /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. @warn_unused_result public func collate(_ collation: Collation) -> Expression<UnderlyingType> { return "COLLATE".infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. /// /// let name = Expression<String>("name") /// name.ltrim() /// // ltrim("name") /// name.ltrim([" ", "\t"]) /// // ltrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `ltrim` function. @warn_unused_result public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `rtrim` function. /// /// let name = Expression<String>("name") /// name.rtrim() /// // rtrim("name") /// name.rtrim([" ", "\t"]) /// // rtrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `rtrim` function. @warn_unused_result public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `trim` function. /// /// let name = Expression<String>("name") /// name.trim() /// // trim("name") /// name.trim([" ", "\t"]) /// // trim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `trim` function. @warn_unused_result public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap([self]) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `replace` function. /// /// let email = Expression<String>("email") /// email.replace("@mac.com", with: "@icloud.com") /// // replace("email", '@mac.com', '@icloud.com') /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - replacement: The replacement string. /// /// - Returns: A copy of the expression wrapped with the `replace` function. @warn_unused_result public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> { return "replace".wrap([self, pattern, replacement]) } @warn_unused_result public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> { guard let length = length else { return "substr".wrap([self, location]) } return "substr".wrap([self, location, length]) } public subscript(range: Range<Int>) -> Expression<UnderlyingType> { return substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } extension ExpressionType where UnderlyingType == String? { /// Builds a copy of the expression wrapped with the `length` function. /// /// let name = Expression<String?>("name") /// name.length /// // length("name") /// /// - Returns: A copy of the expression wrapped with the `length` function. public var length: Expression<Int?> { return wrap(self) } /// Builds a copy of the expression wrapped with the `lower` function. /// /// let name = Expression<String?>("name") /// name.lowercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `lower` function. public var lowercaseString: Expression<UnderlyingType> { return "lower".wrap(self) } /// Builds a copy of the expression wrapped with the `upper` function. /// /// let name = Expression<String?>("name") /// name.uppercaseString /// // lower("name") /// /// - Returns: A copy of the expression wrapped with the `upper` function. public var uppercaseString: Expression<UnderlyingType> { return "upper".wrap(self) } /// Builds a copy of the expression appended with a `LIKE` query against the /// given pattern. /// /// let email = Expression<String?>("email") /// email.like("%@example.com") /// // "email" LIKE '%@example.com' /// email.like("99\\%@%", escape: "\\") /// // "email" LIKE '99\%@%' ESCAPE '\' /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - escape: An (optional) character designated for escaping /// pattern-matching characters (*i.e.*, the `%` and `_` characters). /// /// - Returns: A copy of the expression appended with a `LIKE` query against /// the given pattern. @warn_unused_result public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> { guard let character = character else { return "LIKE".infix(self, pattern) } return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)]) } /// Builds a copy of the expression appended with a `GLOB` query against the /// given pattern. /// /// let path = Expression<String?>("path") /// path.glob("*.png") /// // "path" GLOB '*.png' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `GLOB` query against /// the given pattern. @warn_unused_result public func glob(_ pattern: String) -> Expression<Bool?> { return "GLOB".infix(self, pattern) } /// Builds a copy of the expression appended with a `MATCH` query against /// the given pattern. /// /// let title = Expression<String?>("title") /// title.match("swift AND programming") /// // "title" MATCH 'swift AND programming' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `MATCH` query /// against the given pattern. @warn_unused_result public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(self, pattern) } /// Builds a copy of the expression appended with a `REGEXP` query against /// the given pattern. /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression appended with a `REGEXP` query /// against the given pattern. @warn_unused_result public func regexp(_ pattern: String) -> Expression<Bool?> { return "REGEXP".infix(self, pattern) } /// Builds a copy of the expression appended with a `COLLATE` clause with /// the given sequence. /// /// let name = Expression<String?>("name") /// name.collate(.Nocase) /// // "name" COLLATE NOCASE /// /// - Parameter collation: A collating sequence. /// /// - Returns: A copy of the expression appended with a `COLLATE` clause /// with the given sequence. @warn_unused_result public func collate(_ collation: Collation) -> Expression<UnderlyingType> { return "COLLATE".infix(self, collation) } /// Builds a copy of the expression wrapped with the `ltrim` function. /// /// let name = Expression<String?>("name") /// name.ltrim() /// // ltrim("name") /// name.ltrim([" ", "\t"]) /// // ltrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `ltrim` function. @warn_unused_result public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `rtrim` function. /// /// let name = Expression<String?>("name") /// name.rtrim() /// // rtrim("name") /// name.rtrim([" ", "\t"]) /// // rtrim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `rtrim` function. @warn_unused_result public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `trim` function. /// /// let name = Expression<String?>("name") /// name.trim() /// // trim("name") /// name.trim([" ", "\t"]) /// // trim("name", ' \t') /// /// - Parameter characters: A set of characters to trim. /// /// - Returns: A copy of the expression wrapped with the `trim` function. @warn_unused_result public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> { guard let characters = characters else { return wrap(self) } return wrap([self, String(characters)]) } /// Builds a copy of the expression wrapped with the `replace` function. /// /// let email = Expression<String?>("email") /// email.replace("@mac.com", with: "@icloud.com") /// // replace("email", '@mac.com', '@icloud.com') /// /// - Parameters: /// /// - pattern: A pattern to match. /// /// - replacement: The replacement string. /// /// - Returns: A copy of the expression wrapped with the `replace` function. @warn_unused_result public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> { return "replace".wrap([self, pattern, replacement]) } /// Builds a copy of the expression wrapped with the `substr` function. /// /// let title = Expression<String?>("title") /// title.substr(-100) /// // substr("title", -100) /// title.substr(0, length: 100) /// // substr("title", 0, 100) /// /// - Parameters: /// /// - location: The substring’s start index. /// /// - length: An optional substring length. /// /// - Returns: A copy of the expression wrapped with the `substr` function. @warn_unused_result public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> { guard let length = length else { return "substr".wrap([self, location]) } return "substr".wrap([self, location, length]) } /// Builds a copy of the expression wrapped with the `substr` function. /// /// let title = Expression<String?>("title") /// title[0..<100] /// // substr("title", 0, 100) /// /// - Parameter range: The character index range of the substring. /// /// - Returns: A copy of the expression wrapped with the `substr` function. public subscript(range: Range<Int>) -> Expression<UnderlyingType> { return substring(range.lowerBound, length: range.upperBound - range.lowerBound) } } extension Collection where Iterator.Element : Value, IndexDistance == Int { /// Builds a copy of the expression prepended with an `IN` check against the /// collection. /// /// let name = Expression<String>("name") /// ["alice", "betty"].contains(name) /// // "name" IN ('alice', 'betty') /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression prepended with an `IN` check against /// the collection. @warn_unused_result public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> { let templates = [String](repeating: "?", count: count).joined(separator: ", ") return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue })) } /// Builds a copy of the expression prepended with an `IN` check against the /// collection. /// /// let name = Expression<String?>("name") /// ["alice", "betty"].contains(name) /// // "name" IN ('alice', 'betty') /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A copy of the expression prepended with an `IN` check against /// the collection. @warn_unused_result public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> { let templates = [String](repeating: "?", count: count).joined(separator: ", ") return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue })) } } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let name = Expression<String?>("name") /// name ?? "An Anonymous Coward" /// // ifnull("name", 'An Anonymous Coward') /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback value for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(_ optional: Expression<V?>, defaultValue: V) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let nick = Expression<String?>("nick") /// let name = Expression<String>("name") /// nick ?? name /// // ifnull("nick", "name") /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback expression for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(_ optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) } /// Builds a copy of the given expressions wrapped with the `ifnull` function. /// /// let nick = Expression<String?>("nick") /// let name = Expression<String?>("name") /// nick ?? name /// // ifnull("nick", "name") /// /// - Parameters: /// /// - optional: An optional expression. /// /// - defaultValue: A fallback expression for when the optional expression is /// `nil`. /// /// - Returns: A copy of the given expressions wrapped with the `ifnull` /// function. public func ??<V : Value>(_ optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> { return "ifnull".wrap([optional, defaultValue]) }
mit
9eab09fc00325c8fcf7e81a775bebabd
35.134897
120
0.595561
4.267359
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/Project.swift
1
3526
// // Project.swift // TranslationEditor // // Created by Mikko Hilpinen on 27.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // A project combines multiple associated resources together // Some resources under a project will require specific project level authorization final class Project: Storable { // ATTRIBUTES ---------------- static let type = "project" static let idIndexMap: IdIndexMap = ["project_uid": 0] let uid: String let created: TimeInterval let languageId: String var name: String var ownerId: String // Id of the owner CB user var contributorIds: [String] // Ids of the contributing CB users var defaultBookIdentifier: String var sharedAccountId: String? // COMPUTED PROPERTIES -------- var idProperties: [Any] { return [uid] } var properties: [String : PropertyValue] { return ["owner": ownerId.value, "contributors": contributorIds.value, "name": name.value, "language": languageId.value, "shared_account": sharedAccountId.value, "default_book_identifier": defaultBookIdentifier.value, "created": created.value] } // INIT ------------------------ init(name: String, languageId: String, ownerId: String, contributorIds: [String], defaultBookIdentifier: String, sharedAccountId: String? = nil, uid: String = UUID().uuidString.lowercased(), created: TimeInterval = Date().timeIntervalSince1970) { self.uid = uid self.created = created self.languageId = languageId self.name = name self.ownerId = ownerId self.sharedAccountId = sharedAccountId self.defaultBookIdentifier = defaultBookIdentifier self.contributorIds = contributorIds if !contributorIds.contains(ownerId) { self.contributorIds = contributorIds + ownerId } if let sharedAccountId = sharedAccountId { if !contributorIds.contains(sharedAccountId) { self.contributorIds.append(sharedAccountId) } } } static func create(from properties: PropertySet, withId id: Id) -> Project { return Project(name: properties["name"].string(), languageId: properties["language"].string(), ownerId: properties["owner"].string(), contributorIds: properties["contributors"].array({ $0.string }), defaultBookIdentifier: properties["default_book_identifier"].string(), sharedAccountId: properties["shared_account"].string, uid: id["project_uid"].string(), created: properties["created"].time()) } // IMPLEMENTED METHODS ------- func update(with properties: PropertySet) { if let name = properties["name"].string { self.name = name } if let ownerId = properties["owner"].string { self.ownerId = ownerId } if let defaultBookIdentifier = properties["default_book_identifier"].string { self.defaultBookIdentifier = defaultBookIdentifier } if let contributorData = properties["contributors"].array { self.contributorIds = contributorData.compactMap { $0.string } } if let sharedAccountId = properties["shared_account"].string { self.sharedAccountId = sharedAccountId } } // OTHER METHODS ---------- // Creates a query for the target translations of this project // By providing the bookCode parameter, you can limit the translations to certain book func targetTranslationQuery(bookCode: BookCode? = nil) -> Query<ProjectBooksView> { return ProjectBooksView.instance.booksQuery(projectId: idString, languageId: languageId, code: bookCode) } /* static func projectsAvailableForAccount(withId accountId: String) throws -> [Project] { let query = return [] }*/ }
mit
8bafe3536ed01552023a687a5bd92908
29.128205
397
0.717447
3.886439
false
false
false
false
jzucker2/SwiftyKit
Example/Tests/StackingViewTestCase.swift
1
5132
// // StackingViewTestCase.swift // SwiftyKit_Tests // // Created by Jordan Zucker on 8/4/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import SwiftyKit class StackingViewTestCase: XCTestCase { struct TestScreen: Screen { var bounds: CGRect { return CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0) } } class TestStackedView: UIViewController, StackingView { let stackView = UIStackView(frame: .zero) let testScreen: Screen required init(screen: TestScreen) { self.testScreen = screen super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { self.view = loadedView(and: self.testScreen) } } class TestNonDefaultOptionsStackedView: UIViewController, StackingView { let stackView = UIStackView(frame: .zero) let testScreen: Screen required init(screen: TestScreen) { self.testScreen = screen super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { self.view = loadedView(and: self.testScreen) } static var stackViewOptions: StackViewOptions { return StackViewOptions(axis: .horizontal, alignment: .center, distribution: .equalCentering, backgroundColor: .red) } } let testScreen = TestScreen() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testStackViewExistsWithLoadViewConvenience() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let testStackedView = TestStackedView(screen: self.testScreen) XCTAssertNotNil(testStackedView) testStackedView.loadViewIfNeeded() testStackedView.view.layoutIfNeeded() print(testStackedView.view.frame) print(testStackedView.stackView.frame) XCTAssertNotNil(testStackedView.stackView) XCTAssertEqual(testScreen.bounds, testStackedView.view.frame) XCTAssertEqual(testScreen.bounds, testStackedView.stackView.frame) XCTAssertEqual(testStackedView.view, testStackedView.stackView.superview!) } func testDefaultOptions() { let defaultOptions = StackViewOptions.defaultOptions() XCTAssertEqual(defaultOptions.axis, .vertical) XCTAssertEqual(defaultOptions.alignment, .fill) XCTAssertEqual(defaultOptions.distribution, .fill) XCTAssertEqual(defaultOptions.backgroundColor, .white) } func testStackingAppliesDefaultOptions() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let testStackedView = TestStackedView(screen: self.testScreen) XCTAssertNotNil(testStackedView) testStackedView.loadViewIfNeeded() testStackedView.view.layoutIfNeeded() XCTAssertNotNil(testStackedView.stackView) let defaultOptions = StackViewOptions.defaultOptions() XCTAssertEqual(testStackedView.stackView.axis, defaultOptions.axis) XCTAssertEqual(testStackedView.stackView.distribution, defaultOptions.distribution) XCTAssertEqual(testStackedView.stackView.alignment, defaultOptions.alignment) XCTAssertEqual(testStackedView.view.backgroundColor, defaultOptions.backgroundColor) } func testAppliesSubclassOverrideStackViewOptions() { let testStackedView = TestNonDefaultOptionsStackedView(screen: self.testScreen) XCTAssertNotNil(testStackedView) testStackedView.loadViewIfNeeded() testStackedView.view.layoutIfNeeded() let stackView = testStackedView.stackView XCTAssertNotNil(stackView) let differentOptions = TestNonDefaultOptionsStackedView.stackViewOptions XCTAssertEqual(stackView.axis, .horizontal) XCTAssertEqual(stackView.axis, differentOptions.axis) XCTAssertEqual(stackView.distribution, .equalCentering) XCTAssertEqual(stackView.distribution, differentOptions.distribution) XCTAssertEqual(stackView.alignment, .center) XCTAssertEqual(stackView.alignment, differentOptions.alignment) XCTAssertEqual(testStackedView.view.backgroundColor, .red) XCTAssertEqual(testStackedView.view.backgroundColor, differentOptions.backgroundColor) } }
mit
920ea6b7db4334011bc789f138e2e8e0
37.871212
128
0.680374
5.105473
false
true
false
false
JadenGeller/Chemical
Sources/Reaction.swift
1
2351
// // Reaction.swift // Chemical // // Created by Jaden Geller on 2/20/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import Handbag import Stochastic import Orderly #if os(Linux) import Glibc #else import Darwin.C #endif public struct Reaction<Molecule: Hashable> { public var reactants: Bag<Molecule> public var products: Bag<Molecule> public var rate: Float public init(reactants: Bag<Molecule>, products: Bag<Molecule>, rate: Float = 1) { self.reactants = reactants self.products = products self.rate = rate } } extension Interaction where Molecule: Hashable { public init(_ reaction: Reaction<Molecule>) { self.init(moleculeCount: reaction.reactants.count) { molecules in guard reaction.reactants == Bag(molecules) else { return nil } return Array(reaction.products) } } } extension Behavior where Molecule: Hashable { public init(_ reactions: [Reaction<Molecule>]) { let sortedReactions = SortedArray(unsorted: reactions, isOrderedBefore: { $0.rate < $1.rate }) let _integratedReactions = sortedReactions.reduce((0, [])) { pair, element in return (pair.0 + element.rate, pair.1 + [Reaction(reactants: element.reactants, products: element.products, rate: element.rate + pair.0)]) } // GROSS^^^ let integratedReactions = SortedArray(unsafeSorted: _integratedReactions.1, isOrderedBefore: { $0.rate < $1.rate }) let integral = _integratedReactions.0 self.init { let value = Float.random(between: 0...integral) let index = integratedReactions.insertionIndexOf(Reaction(reactants: [], products: [], rate: value)) // ^This is gross.. :P return Interaction(sortedReactions[index]) } } public init(_ reactions: Reaction<Molecule>...) { self.init(reactions) } } // MARK: Helpers extension Float { private static func random() -> Float { #if os(Linux) return Float(rand()) / Float(RAND_MAX) #else return Float(arc4random()) / Float(UInt32.max) #endif } private static func random(between between: ClosedInterval<Float>) -> Float { return between.start + (between.end - between.start) * random() } }
mit
8f699701b93238b031ea69afeb698802
29.519481
150
0.634468
3.827362
false
false
false
false