repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
kcome/SwiftIB
HistoryDataDump/main.swift
1
7884
// // main.swift // HistoryDataDump // // Created by Harry Li on 10/01/2015. // Copyright (c) 2014-2019 Hanfei Li. 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 SwiftIB // constants let EXT = "history_raw" let HEADER_LEN = 19 var conf = HDDConfig(arg_array: CommandLine.arguments) var tickers = conf.tickers var fman = FileManager.default var wrapper = HistoryDataWrapper() var client = EClientSocket(p_eWrapper: wrapper, p_anyWrapper: wrapper) func getLastestDate(filename: String) -> Int64 { let fcontent = try! NSString(contentsOfFile: filename, encoding: String.Encoding.utf8.rawValue) var count = 0 fcontent.enumerateLines({ (line: String!, p: UnsafeMutablePointer<ObjCBool>) -> Void in count += 1 }) var ret: Int64 = -1 fcontent.enumerateLines({ (line: String!, p: UnsafeMutablePointer<ObjCBool>) -> Void in count -= 1 if count == 0 { let datestr = (line as NSString).substring(with: NSRange(location: 0, length: HEADER_LEN)) ret = HDDUtil.fastStrToTS(timestamp: datestr, tz_name: wrapper.timezone) } }) return ret } func downloadHistoryData(filename: String, ticker: String, requestId: Int, append: Bool = false, secType: String = "STK", currency: String = "USD", multiplier: String = "", expire: String = "", exchange: String = "SMART", pexchange: String = "ISLAND") { var loc = ticker var wts = "TRADES" if exchange == "IDEALPRO" { loc = "\(ticker).\(currency)" wts = "BID_ASK" } if (conf.sleepInterval < 20.0) && (wts == "BID_ASK") { conf.sleepInterval = 20.0 } let con = Contract(p_conId: 0, p_symbol: ticker, p_secType: secType, p_expiry: expire, p_strike: 0.0, p_right: "", p_multiplier: multiplier, p_exchange: exchange, p_currency: currency, p_localSymbol: loc, p_tradingClass: "", p_comboLegs: nil, p_primaryExch: pexchange, p_includeExpired: false, p_secIdType: "", p_secId: "") var lf: FileHandle? if append { let next = getLastestDate(filename: filename) if next != -1 { wrapper.currentStart = next } if wrapper.currentStart <= wrapper.sinceTS { print("\t[\(ticker)] fully downloaded. Skip.") return } print("\tAppending \(filename), starting date [\(HDDUtil.tsToStr(timestamp: wrapper.currentStart, api: false, tz_name: wrapper.timezone))]") lf = FileHandle(forUpdatingAtPath: filename) if lf != nil { lf?.seekToEndOfFile() } } else { fman.createFile(atPath: filename, contents: nil, attributes: nil) lf = FileHandle(forWritingAtPath: filename) } wrapper.currentTicker = ticker while wrapper.currentStart > wrapper.sinceTS { let begin = NSDate().timeIntervalSinceReferenceDate let localStart = wrapper.currentStart wrapper.currentStart = -1 wrapper.contents.removeAll(keepingCapacity: true) wrapper.reqComplete = false wrapper.broken = false let sdt = conf.sinceDatetime.components(separatedBy: " ")[0] if HDDUtil.equalsDaystart(timestamp: localStart, tz_name: wrapper.timezone, daystart: conf.dayStart, datestart: sdt) { print("(reaching day start \(conf.dayStart), continue next)") break } let ut = HDDUtil.tsToStr(timestamp: localStart, api: true, tz_name: wrapper.timezone) client.reqHistoricalData(requestId, contract: con, endDateTime: "\(ut) \(wrapper.timezone)", durationStr: conf.duration, barSizeSetting: conf.barsize, whatToShow: wts, useRTH: conf.rth, formatDate: 2, chartOptions: nil) print("request (\(conf.duration)) (\(conf.barsize)) bars, until \(ut) \(wrapper.timezone)") while (wrapper.reqComplete == false) && (wrapper.broken == false) && (wrapper.extraSleep <= 0.0) { Thread.sleep(forTimeInterval: TimeInterval(0.05)) } if wrapper.broken { Thread.sleep(forTimeInterval: TimeInterval(2.0)) wrapper.currentStart = localStart client = EClientSocket(p_eWrapper: wrapper, p_anyWrapper: wrapper) client.eConnect(conf.host, p_port: conf.port) wrapper.closing = false continue } if let file = lf { for c in wrapper.contents { file.write(c.data(using: String.Encoding.utf8, allowLossyConversion: true)!) } file.synchronizeFile() } print("(sleep for \(conf.sleepInterval + wrapper.extraSleep) secs)...") Thread.sleep(until: NSDate(timeIntervalSinceReferenceDate: begin + conf.sleepInterval + wrapper.extraSleep) as Date) if wrapper.extraSleep > 0 { wrapper.currentStart = localStart wrapper.extraSleep = 0 } } if lf != nil { lf?.closeFile() } } conf.printConf() print("Connecting to IB API...") client.eConnect(conf.host, port: Int(conf.port), clientId: conf.clientID) wrapper.closing = false for i in 0 ..< tickers.count { var ticker = tickers[i] var ex = conf.exchange var pex = conf.primaryEx let cmp = tickers[i].components(separatedBy: ",") var ins = "STK" var currency = "USD" var multiplier = "" var expire = "" if cmp.count >= 5 { ticker = cmp[0] currency = cmp[1] ins = cmp[2] ex = cmp[3] pex = cmp[4] if cmp.count >= 7 { multiplier = cmp[5] expire = cmp[6] } } wrapper.timezone = "America/New_York" wrapper.sinceTS = HDDUtil.strToTS(timestamp: conf.sinceDatetime, api: true, tz_name: wrapper.timezone) wrapper.currentStart = HDDUtil.strToTS(timestamp: conf.untilDatetime, api: true, tz_name: wrapper.timezone) var lticker = ticker if ins == "CASH" { lticker = "\(ticker).\(currency)" } let fn = conf.outputDir.appending("[\(lticker)][\(ex)-\(pex)][\(conf.sinceDatetime)]-[\(conf.untilDatetime)][\(conf.barsize)].\(EXT)") let fname = conf.normal_filename ? fn.replacingOccurrences(of: ":", with: "") : fn if fman.fileExists(atPath: fname) { if conf.append { downloadHistoryData(filename: fname, ticker: ticker, requestId: i, append: true, secType: ins, currency: currency, multiplier: multiplier, expire: expire, exchange: ex, pexchange: pex) continue } else { print("Skip \(ticker) : File exists") continue } } else { downloadHistoryData(filename: fname, ticker: ticker, requestId: i, secType: ins, currency: currency, multiplier: multiplier, expire: expire, exchange: ex, pexchange: pex) } } Thread.sleep(forTimeInterval: TimeInterval(3.0)) wrapper.closing = true client.eDisconnect() client.close()
mit
86da70c658f1374f05d78d952419008d
41.616216
253
0.647514
4.004063
false
false
false
false
fluidsonic/JetPack
Sources/UI/TextInputView.swift
1
6134
import UIKit open class TextInputView: View { public typealias Delegate = _TextInputViewDelegate private var lastLayoutedSize = CGSize.zero private var lastMeasuredNativeHeight = CGFloat(0) private let nativeView = NativeView() private var placeholderView: Label? public weak var delegate: Delegate? public override init() { super.init() setUp() } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open var attributedText: NSAttributedString { get { return nativeView.attributedText ?? NSAttributedString() } set { nativeView.attributedText = newValue } } @discardableResult open override func becomeFirstResponder() -> Bool { return nativeView.becomeFirstResponder() } private func checkIntrinsicContentSize() { let measuredNativeHeight = nativeView.heightThatFitsWidth(nativeView.bounds.width) guard measuredNativeHeight != lastMeasuredNativeHeight else { return } lastMeasuredNativeHeight = measuredNativeHeight invalidateIntrinsicContentSize() } @discardableResult open override func endEditing(_ force: Bool) -> Bool { return nativeView.endEditing(force) } open var font: UIFont { get { return nativeView.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize) } set { nativeView.font = newValue placeholderView?.font = newValue } } open var isScrollEnabled: Bool { get { return nativeView.isScrollEnabled } set { nativeView.isScrollEnabled = newValue } } open override func layoutSubviews() { super.layoutSubviews() let bounds = self.bounds nativeView.frame = CGRect(size: bounds.size) placeholderView?.frame = CGRect(size: bounds.size) if bounds.size != lastLayoutedSize { lastLayoutedSize = bounds.size lastMeasuredNativeHeight = nativeView.heightThatFitsWidth(nativeView.bounds.width) } } open override func measureOptimalSize(forAvailableSize availableSize: CGSize) -> CGSize { return nativeView.sizeThatFitsSize(availableSize) } fileprivate func nativeViewDidChange() { updatePlaceholderView() checkIntrinsicContentSize() delegate?.textInputViewDidChange(self) } fileprivate func nativeViewDidEndEditing() { checkIntrinsicContentSize() } open var padding: UIEdgeInsets { get { return nativeView.textContainerInset } set { nativeView.textContainerInset = newValue } } open var placeholder = "" { didSet { guard placeholder != oldValue else { return } updatePlaceholderView() } } open var placeholderTextColor = UIColor(rgb: 0xC7C7CD) { didSet { placeholderView?.textColor = placeholderTextColor } } @discardableResult open override func resignFirstResponder() -> Bool { return nativeView.resignFirstResponder() } private func setUp() { setUpNativeView() } private func setUpNativeView() { let child = nativeView child.backgroundColor = nil child.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) child.parent = self child.textContainer.lineFragmentPadding = 0 addSubview(child) } private func setUpPlaceholderView() -> Label { if let child = placeholderView { return child } let child = Label() child.font = font child.maximumNumberOfLines = nil child.padding = padding child.textColor = placeholderTextColor placeholderView = child addSubview(child) return child } open override func subviewDidInvalidateIntrinsicContentSize(_ view: UIView) { super.subviewDidInvalidateIntrinsicContentSize(view) guard view !== nativeView else { return // FIXME only text editing } setNeedsLayout() if !isScrollEnabled { invalidateIntrinsicContentSize() } } open var text: String { get { return nativeView.text ?? "" } set { nativeView.text = newValue } } open var textColor: UIColor { get { return nativeView.textColor ?? UIColor.darkText } set { nativeView.textColor = newValue } } open var typingAttributes: [NSAttributedString.Key : Any] { get { return nativeView.typingAttributes } set { nativeView.typingAttributes = newValue } } private func updatePlaceholderView() { if placeholder.isEmpty || !text.isEmpty { placeholderView?.removeFromSuperview() placeholderView = nil } else { let placeholderView = setUpPlaceholderView() placeholderView.text = placeholder } } } public protocol _TextInputViewDelegate: class { func textInputViewDidChange (_ inputView: TextInputView) } private final class NativeView: UITextView { weak var parent: TextInputView? init() { super.init(frame: .zero, textContainer: nil) delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var attributedText: NSAttributedString? { get { return super.attributedText } set { guard newValue != attributedText else { return } super.attributedText = textIncludingDefaultAttributes(for: newValue ?? NSAttributedString()) } } private func textIncludingDefaultAttributes(for attributedText: NSAttributedString) -> NSAttributedString { let defaultAttributes: [NSAttributedString.Key : Any] = [ .font: font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize), .foregroundColor: textColor ?? .darkText ] let textIncludingDefaultAttributes = NSMutableAttributedString(string: attributedText.string, attributes: defaultAttributes) textIncludingDefaultAttributes.beginEditing() attributedText.enumerateAttributes(in: NSRange(forString: attributedText.string), options: [.longestEffectiveRangeNotRequired]) { attributes, range, _ in textIncludingDefaultAttributes.addAttributes(attributes, range: range) } textIncludingDefaultAttributes.endEditing() return textIncludingDefaultAttributes } override var text: String? { get { return super.text } set { attributedText = newValue.map(NSAttributedString.init(string:)) } } } extension NativeView: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { parent?.nativeViewDidChange() } func textViewDidEndEditing(_ textView: UITextView) { parent?.nativeViewDidEndEditing() } }
mit
7e19e4aaa76030945c09ac5bd2e69c80
20.522807
155
0.744539
4.338048
false
false
false
false
lkzhao/Hero
LegacyExamples/LegacyExampleViewController.swift
1
2211
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Hero class LegacyExampleViewController: UITableViewController { var storyboards: [[String]] = [ [], ["Basic", "Navigation", "MusicPlayer", "Menu", "BuiltInTransitions"], ["CityGuide", "ImageViewer", "VideoPlayer"], ["AppleHomePage", "ListToGrid", "ImageGallery"] ] override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomLayoutGuide.length, right: 0) tableView.scrollIndicatorInsets = tableView.contentInset } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.item < storyboards[indexPath.section].count { let storyboardName = storyboards[indexPath.section][indexPath.item] let vc = viewController(forStoryboardName: storyboardName) // iOS bug: https://github.com/lkzhao/Hero/issues/106 https://github.com/lkzhao/Hero/issues/79 DispatchQueue.main.async { self.present(vc, animated: true, completion: nil) } } } }
mit
e383093704fc3d8527dff58c7691449f
41.519231
102
0.736318
4.568182
false
false
false
false
satorun/designPattern
Singleton/Singleton/ViewController.swift
1
843
// // ViewController.swift // Singleton // // Created by satorun on 2016/01/30. // Copyright © 2016年 satorun. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print("Start.") let obj1 = Singleton.getInstance() let obj2 = Singleton.getInstance() if obj1 === obj2 { print("obj1とobj2は同じインスタンスです。") } else { print("obj1とobj2は同じインスタンスではありません。") } print("End.") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
071560d89183f89474dcd6447d76bbd1
21.882353
80
0.611825
4.322222
false
false
false
false
mogol/centrifugo-ios
CentrifugeiOS/Classes/Centrifuge.swift
2
1210
// // Centrifugal.swift // Pods // // Created by German Saprykin on 18/04/16. // // import Foundation import CentrifugeiOS.CommonCryptoBridge public let CentrifugeErrorDomain = "com.Centrifuge.error.domain" public let CentrifugeWebSocketErrorDomain = "com.Centrifuge.error.domain.websocket" public let CentrifugeErrorMessageKey = "com.Centrifuge.error.messagekey" public let CentrifugePrivateChannelPrefix = "$" public enum CentrifugeErrorCode: Int { case CentrifugeMessageWithError } public typealias CentrifugeMessageHandler = (CentrifugeServerMessage?, Error?) -> Void public class Centrifuge { public class func client(url: String, creds: CentrifugeCredentials, delegate: CentrifugeClientDelegate) -> CentrifugeClient { let client = CentrifugeClientImpl() client.builder = CentrifugeClientMessageBuilderImpl() client.parser = CentrifugeServerMessageParserImpl() client.creds = creds client.url = url client.delegate = delegate return client } public class func createToken(string: String, key: String) -> String { return CentrifugeCommonCryptoBridge.hexHMACSHA256(forData: string, withKey: key) } }
mit
e541141e915cc5f4e77096c658d8cc80
30.025641
129
0.739669
4.60076
false
false
false
false
doronkatz/firefox-ios
Client/Frontend/Home/ReaderPanel.swift
2
22492
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import ReadingList import Shared import XCGLogger private let log = Logger.browserLogger private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44) static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035) static let DeleteButtonTitleColor = UIColor.white static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1) static let MarkAsReadButtonTitleColor = UIColor.white static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenHeaderTextColor = UIColor.darkGray static let WelcomeScreenItemTextColor = UIColor.gray static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: UITableViewCell { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url: URL = URL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor updateAccessibilityLabel() } } let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = UIEdgeInsets.zero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = UIViewContentMode.scaleAspectFit readStatusImageView.snp.makeConstraints { (make) -> Void in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.centerY.equalTo(self.contentView) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) contentView.addSubview(hostnameLabel) titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor titleLabel.numberOfLines = 2 titleLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000) } hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor hostnameLabel.numberOfLines = 1 hostnameLabel.snp.makeConstraints { (make) -> Void in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.leading.trailing.equalTo(self.titleLabel) } setupDynamicFonts() } func setupDynamicFonts() { titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight } override func prepareForReuse() { super.prepareForReuse() setupDynamicFonts() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return hostname.substring(from: hostname.characters.index(hostname.startIndex, offsetBy: prefix.characters.count)) } } return hostname } fileprivate func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, let title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string as AnyObject } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? var profile: Profile! fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(ReadingListPanel.longPress(_:))) }() fileprivate lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() fileprivate var records: [ReadingListClientRecord]? init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ReadingListPanel.notificationReceived(_:)), name: NotificationDynamicFontChanged, object: nil) } required init!(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "ReadingTable" tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorColor = UIConstants.SeparatorColor tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() view.backgroundColor = UIConstants.PanelBackgroundColor if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue // If no records have been added yet, we display the empty state if records?.count == 0 { tableView.isScrollEnabled = false view.addSubview(emptyStateOverlayView) } } } deinit { NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { context in self.presentedViewController?.dismiss(animated: true, completion: nil) }, completion: nil) } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged: refreshReadingList() break case NotificationDynamicFontChanged: if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverview() refreshReadingList() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } func refreshReadingList() { let prevNumberOfRecords = records?.count if let result = profile.readingList?.getAvailableRecords(), result.isSuccess { records = result.successValue if records?.count == 0 { tableView.isScrollEnabled = false if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) } } else { if prevNumberOfRecords == 0 { tableView.isScrollEnabled = true emptyStateOverlayView.removeFromSuperview() } } self.tableView.reloadData() } } fileprivate func createEmptyStateOverview() -> UIView { let overlayView = UIScrollView(frame: tableView.bounds) overlayView.backgroundColor = UIColor.white // Unknown why this does not work with autolayout overlayView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] let containerView = UIView() overlayView.addSubview(containerView) let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel")) containerView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).priority(1000) // Sets proper top constraint for iPhone 6 in portait and iPads. make.centerY.equalTo(overlayView.snp.centerY).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView.snp.top).offset(50).priority(1000) } let welcomeLabel = UILabel() containerView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = NSTextAlignment.center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(containerView) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) make.top.equalTo(logoImageView.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) // Sets proper center constraint for iPhones in landscape. make.centerY.lessThanOrEqualTo(overlayView.snp.centerY).offset(-40).priority(1000) } let readerModeLabel = UILabel() containerView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readerModeLabel.numberOfLines = 0 readerModeLabel.snp.makeConstraints { make in make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) } let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) containerView.addSubview(readerModeImageView) readerModeImageView.snp.makeConstraints { make in make.centerY.equalTo(readerModeLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } let readingListLabel = UILabel() containerView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readingListLabel.numberOfLines = 0 readingListLabel.snp.makeConstraints { make in make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.leading.equalTo(welcomeLabel.snp.leading) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) make.bottom.equalTo(overlayView).offset(-20) // making AutoLayout compute the overlayView's contentSize } let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) containerView.addSubview(readingListImageView) readingListImageView.snp.makeConstraints { make in make.centerY.equalTo(readingListLabel) make.trailing.equalTo(welcomeLabel.snp.trailing) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(logoImageView.snp.top) make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset) make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(overlayView) } return overlayView } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell if let record = records?[indexPath.row] { cell.title = record.title cell.url = URL(string: record.url)! cell.unread = record.unread } return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let record = records?[indexPath.row] else { return [] } let delete = UITableViewRowAction(style: .normal, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in self?.deleteItem(atIndex: index) } delete.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in self?.toggleItem(atIndex: index) } unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor return [unreadToggle, delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { // Mark the item as read profile.readingList?.updateRecord(record, unread: false) // Reading list items are closest in concept to bookmarks. let visitType = VisitType.bookmark homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType) } } fileprivate func deleteItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.deleteRecord(record), result.isSuccess { records?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) // reshow empty state if no records left if records?.count == 0 { view.addSubview(emptyStateOverlayView) } } } } fileprivate func toggleItem(atIndex indexPath: IndexPath) { if let record = records?[indexPath.row] { if let result = profile.readingList?.updateRecord(record, unread: !record.unread), result.isSuccess { // TODO This is a bit odd because the success value of the update is an optional optional Record if let successValue = result.successValue, let updatedRecord = successValue { records?[indexPath.row] = updatedRecord tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } } } } extension ReadingListPanel: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let record = records?[indexPath.row] else { return nil } return Site(url: record.url, title: record.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? { guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil } let removeAction: ActionOverlayTableViewAction = ActionOverlayTableViewAction(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { action in self.deleteItem(atIndex: indexPath) }) actions.append(removeAction) return actions } }
mpl-2.0
e20c1d7f7fc9386fb7f77647767f3be5
45.858333
333
0.697404
5.770139
false
false
false
false
shajrawi/swift
test/Constraints/operator.swift
2
4960
// RUN: %target-typecheck-verify-swift // Test constraint simplification of chains of binary operators. // <https://bugs.swift.org/browse/SR-1122> do { let a: String? = "a" let b: String? = "b" let c: String? = "c" let _: String? = a! + b! + c! let x: Double = 1 _ = x + x + x let sr3483: Double? = 1 _ = sr3483! + sr3483! + sr3483! let sr2636: [String: Double] = ["pizza": 10.99, "ice cream": 4.99, "salad": 7.99] _ = sr2636["pizza"]! _ = sr2636["pizza"]! + sr2636["salad"]! _ = sr2636["pizza"]! + sr2636["salad"]! + sr2636["ice cream"]! } // Use operators defined within a type. struct S0 { static func +(lhs: S0, rhs: S0) -> S0 { return lhs } } func useS0(lhs: S0, rhs: S0) { _ = lhs + rhs } // Use operators defined within a generic type. struct S0b<T> { static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() } } func useS0b(s1i: S0b<Int>, s: String) { var s1s = s1i + s s1s = S0b<String>() _ = s1s } // Use operators defined within a protocol extension. infix operator %%% infix operator %%%% protocol P1 { static func %%%(lhs: Self, rhs: Self) -> Bool } extension P1 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP1Directly<T : P1>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1 : P1 { static func %%%(lhs: S1, rhs: S1) -> Bool { return false } } func useP1Model(lhs: S1, rhs: S1) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1b<T> : P1 { static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false } } func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Use operators defined within a protocol extension to satisfy a requirement. protocol P2 { static func %%%(lhs: Self, rhs: Self) -> Bool static func %%%%(lhs: Self, rhs: Self) -> Bool } extension P2 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP2Directly<T : P2>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2 : P2 { static func %%%(lhs: S2, rhs: S2) -> Bool { return false } } func useP2Model(lhs: S2, rhs: S2) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2b<T> : P2 { static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false } } func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Using an extension of one protocol to satisfy another conformance. protocol P3 { } extension P3 { static func ==(lhs: Self, rhs: Self) -> Bool { return true } } struct S3 : P3, Equatable { } // rdar://problem/30220565 func shrinkTooFar(_ : Double, closure : ()->()) {} func testShrinkTooFar() { shrinkTooFar(0*0*0) {} } // rdar://problem/33759839 enum E_33759839 { case foo case bar(String) } let foo_33759839 = ["a", "b", "c"] let bar_33759839 = ["A", "B", "C"] let _: [E_33759839] = foo_33759839.map { .bar($0) } + bar_33759839.map { .bar($0) } + [E_33759839.foo] // Ok // rdar://problem/28688585 class B_28688585 { var value: Int init(value: Int) { self.value = value } func add(_ other: B_28688585) -> B_28688585 { return B_28688585(value: value + other.value) } } class D_28688585 : B_28688585 { } func + (lhs: B_28688585, rhs: B_28688585) -> B_28688585 { return lhs.add(rhs) } let var_28688585 = D_28688585(value: 1) _ = var_28688585 + var_28688585 + var_28688585 // Ok // rdar://problem/35740653 - Fix `LinkedExprAnalyzer` greedy operator linking struct S_35740653 { var v: Double = 42 static func value(_ value: Double) -> S_35740653 { return S_35740653(v: value) } static func / (lhs: S_35740653, rhs: S_35740653) -> Double { return lhs.v / rhs.v } } func rdar35740653(val: S_35740653) { let _ = 0...Int(val / .value(1.0 / 42.0)) // Ok } protocol P_37290898 {} struct S_37290898: P_37290898 {} func rdar37290898(_ arr: inout [P_37290898], _ element: S_37290898?) { arr += [element].compactMap { $0 } // Ok } // SR-8221 infix operator ??= func ??= <T>(lhs: inout T?, rhs: T?) {} var c: Int = 0 c ??= 5 // expected-error{{binary operator '??=' cannot be applied to two 'Int' operands}} // expected-note@-1{{expected an argument list of type '(inout T?, T?)'}} func rdar46459603() { enum E { case foo(value: String) } let e = E.foo(value: "String") var arr = ["key": e] _ = arr.values == [e] // expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'Dictionary<String, E>.Values' and '[E]'}} // expected-note@-2 {{expected an argument list of type '(Self, Self)'}} _ = [arr.values] == [[e]] // expected-error@-1 {{protocol type 'Any' cannot conform to 'Equatable' because only concrete types can conform to protocols}} }
apache-2.0
08476fc234ed7e75fc6d1912d2d44497
21.044444
129
0.584073
2.86871
false
false
false
false
segmentio/analytics-swift
Sources/Segment/Plugins/Context.swift
1
4006
// // Context.swift // Segment // // Created by Brandon Sneed on 2/23/21. // import Foundation public class Context: PlatformPlugin { public let type: PluginType = .before public weak var analytics: Analytics? internal var staticContext = staticContextData() internal static var device = VendorSystem.current public func execute<T: RawEvent>(event: T?) -> T? { guard var workingEvent = event else { return event } var context = staticContext insertDynamicPlatformContextData(context: &context) // if this event came in with context data already // let it take precedence over our values. if let eventContext = workingEvent.context?.dictionaryValue { context.merge(eventContext) { (_, new) in new } } do { workingEvent.context = try JSON(context) } catch { analytics?.reportInternalError(error) } return workingEvent } internal static func staticContextData() -> [String: Any] { var staticContext = [String: Any]() // library name staticContext["library"] = [ "name": "analytics-swift", "version": __segment_version ] // app info let info = Bundle.main.infoDictionary let localizedInfo = Bundle.main.localizedInfoDictionary var app = [String: Any]() if let info = info { app.merge(info) { (_, new) in new } } if let localizedInfo = localizedInfo { app.merge(localizedInfo) { (_, new) in new } } if app.count != 0 { staticContext["app"] = [ "name": app["CFBundleDisplayName"] ?? "", "version": app["CFBundleShortVersionString"] ?? "", "build": app["CFBundleVersion"] ?? "", "namespace": Bundle.main.bundleIdentifier ?? "" ] } insertStaticPlatformContextData(context: &staticContext) return staticContext } internal static func insertStaticPlatformContextData(context: inout [String: Any]) { // device let device = Self.device // "token" handled in DeviceToken.swift context["device"] = [ "manufacturer": device.manufacturer, "type": device.type, "model": device.model, "name": device.name, "id": device.identifierForVendor ?? "" ] // os context["os"] = [ "name": device.systemName, "version": device.systemVersion ] // screen let screen = device.screenSize context["screen"] = [ "width": screen.width, "height": screen.height ] // user-agent let userAgent = device.userAgent context["userAgent"] = userAgent // locale if Locale.preferredLanguages.count > 0 { context["locale"] = Locale.preferredLanguages[0] } // timezone context["timezone"] = TimeZone.current.identifier } internal func insertDynamicPlatformContextData(context: inout [String: Any]) { let device = Self.device // network let status = device.connection var cellular = false var wifi = false var bluetooth = false switch status { case .online(.cellular): cellular = true case .online(.wifi): wifi = true case .online(.bluetooth): bluetooth = true default: break } // network connectivity context["network"] = [ "bluetooth": bluetooth, // not sure any swift platforms support this currently "cellular": cellular, "wifi": wifi ] // other stuff?? ... } }
mit
f27f82bb833c473124e7e0b27b27b342
28.240876
90
0.532451
5.175711
false
false
false
false
ifLab/WeCenterMobile-iOS
WeCenterMobile/View/Comment/CommentCell.swift
3
2432
// // CommentCell.swift // WeCenterMobile // // Created by Darren Liu on 15/2/3. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class CommentCell: UITableViewCell { @IBOutlet weak var userAvatarView: MSRRoundedImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var userButton: UIButton! @IBOutlet weak var commentButton: UIButton! @IBOutlet weak var separator: UIView! @IBOutlet weak var userContainerView: UIView! @IBOutlet weak var commentContainerView: UIView! @IBOutlet weak var containerView: UIView! override func awakeFromNib() { super.awakeFromNib() let theme = SettingsManager.defaultManager.currentTheme msr_scrollView?.delaysContentTouches = false containerView.msr_borderColor = theme.borderColorA separator.backgroundColor = theme.borderColorA for v in [userContainerView, commentContainerView] { v.backgroundColor = theme.backgroundColorB } for v in [userButton, commentButton] { v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } userNameLabel.textColor = theme.titleTextColor } func update(comment comment: Comment) { msr_userInfo = comment userAvatarView.wc_updateWithUser(comment.user) userNameLabel.text = comment.user?.name let attributedString = NSMutableAttributedString() let theme = SettingsManager.defaultManager.currentTheme if comment.atUser?.name != nil { attributedString.appendAttributedString(NSAttributedString( string: "@\(comment.atUser!.name!) ", attributes: [ NSForegroundColorAttributeName: theme.footnoteTextColor, NSFontAttributeName: bodyLabel.font])) } attributedString.appendAttributedString(NSAttributedString( string: (comment.body ?? ""), attributes: [ NSForegroundColorAttributeName: theme.bodyTextColor, NSFontAttributeName: bodyLabel.font])) bodyLabel.attributedText = attributedString userButton.msr_userInfo = comment.user commentButton.msr_userInfo = comment setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
8a8836074009b43f0948f898459573ac
37.571429
99
0.673663
5.799523
false
false
false
false
VirgilSecurity/virgil-sdk-keys-x
Source/JsonWebToken/AccessProviders/CachingJwtProvider.swift
2
5220
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> // import Foundation // swiftlint:disable trailing_closure /// Implementation of AccessTokenProvider which provides AccessToken using cache+renew callback @objc(VSSCachingJwtProvider) open class CachingJwtProvider: NSObject, AccessTokenProvider { /// Cached Jwt public private(set) var jwt: Jwt? /// Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public let renewJwtCallback: (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void private let semaphore = DispatchSemaphore(value: 1) /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewJwtCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public init(initialJwt: Jwt? = nil, renewJwtCallback: @escaping (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void) { self.jwt = initialJwt self.renewJwtCallback = renewJwtCallback super.init() } /// Typealias for callback used below public typealias JwtStringCallback = (String?, Error?) -> Void /// Typealias for callback used below public typealias RenewJwtCallback = (TokenContext, @escaping JwtStringCallback) -> Void /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewTokenCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT String, or Error @objc public convenience init(initialJwt: Jwt? = nil, renewTokenCallback: @escaping RenewJwtCallback) { self.init(initialJwt: initialJwt, renewJwtCallback: { ctx, completion in renewTokenCallback(ctx) { string, error in do { guard let string = string, error == nil else { completion(nil, error) return } completion(try Jwt(stringRepresentation: string), nil) } catch { completion(nil, error) } } }) } /// Typealias for callback used below public typealias AccessTokenCallback = (AccessToken?, Error?) -> Void /// Provides access token using callback /// /// - Parameters: /// - tokenContext: `TokenContext` provides context explaining why token is needed /// - completion: completion closure @objc public func getToken(with tokenContext: TokenContext, completion: @escaping AccessTokenCallback) { let expirationTime = Date().addingTimeInterval(5) if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { completion(jwt, nil) return } self.semaphore.wait() if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { self.semaphore.signal() completion(jwt, nil) return } self.renewJwtCallback(tokenContext) { token, err in guard let token = token, err == nil else { self.semaphore.signal() completion(nil, err) return } self.jwt = token self.semaphore.signal() completion(token, nil) } } } // swiftlint:enable trailing_closure
bsd-3-clause
56b425588da89aeedc8261257c772de0
38.545455
109
0.650766
4.980916
false
false
false
false
sschiau/swift
stdlib/public/Darwin/Accelerate/vDSP_Arithmetic.swift
8
128736
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // Vector-vector and vector-scalar arithmetic @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: c[i] = a[i] + b vDSP_vsadd /// Returns the elementwise sum of `vector` and `scalar`, /// single-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Returns: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` and `scalar`, /// single-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Parameter result: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsadd(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise sum of `vector` and `scalar`, /// double-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Returns: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` and `scalar`, /// double-precision. /// /// - Parameter scalar: the `b` in `c[i] = a[i] + b`. /// - Parameter vector: the `a` in `c[i] = a[i] + b`. /// - Parameter result: The `c` in `c[i] = a[i] + b`. @inlinable public static func add<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsaddD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] + b[i] vDSP_vadd /// Returns the elementwise sum of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Returns: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in add(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vadd(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise sum of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Returns: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in add(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise sum of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] + b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] + b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] + b[i]`. @inlinable public static func add<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vaddD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] - b[i] vDSP_vsub /// Returns the elementwise difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Returns: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U>(_ vectorA: U, _ vectorB: T) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in subtract(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U, V>(_ vectorA: U, _ vectorB: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorB.withUnsafeBufferPointer { b in vectorA.withUnsafeBufferPointer { a in vDSP_vsub(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Returns: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U>(_ vectorA: U, _ vectorB: T) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in subtract(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] - b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] - b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] - b[i]`. @inlinable public static func subtract<T, U, V>(_ vectorA: U, _ vectorB: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorB.withUnsafeBufferPointer { b in vectorA.withUnsafeBufferPointer { a in vDSP_vsubD(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] * b vDSP_vsmul /// Returns the elementwise product of `vector` and `scalar /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Returns: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of `vector` and `scalar /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Parameter result: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsmul(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise product of `vector` and `scalar /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Returns: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of `vector` and `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] * b`. /// - Parameter scalar: the `b` in `c[i] = a[i] * b`. /// - Parameter result: The `c` in `c[i] = a[i] * b`. @inlinable public static func multiply<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsmulD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] * b[i] vDSP_vmul /// Returns the elementwise product of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in multiply(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmul(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise product of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in multiply(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise product of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] * b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] * b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] * b[i]`. @inlinable public static func multiply<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vmulD(a.baseAddress!, 1, b.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] / b vDSP_vsdiv /// Returns the elementwise division of `vector` by `scalar`, /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Returns: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U>(_ vector: U, _ scalar: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(vector, scalar, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `vector` by `scalar`, /// single-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Parameter result: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U, V>(_ vector: U, _ scalar: Float, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsdiv(v.baseAddress!, 1, [scalar], r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `vector` by `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Returns: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U>(_ vector: U, _ scalar: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(vector, scalar, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `vector` by `scalar`, /// double-precision. /// /// - Parameter vector: the `a` in `c[i] = a[i] / b`. /// - Parameter scalar: the `b` in `c[i] = a[i] / b`. /// - Parameter result: The `c` in `c[i] = a[i] / b` @inlinable public static func divide<U, V>(_ vector: U, _ scalar: Double, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_vsdivD(v.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a / b[i] vDSP_svdiv /// Returns the elementwise division of `scalar` by `vector`, /// single-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Returns: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U>(_ scalar: Float, _ vector: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `scalar` by `vector`, /// single-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Parameter result: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U, V>(_ scalar: Float, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_svdiv(s, v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `scalar` by `vector`, /// double-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Returns: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U>(_ scalar: Double, _ vector: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in divide(scalar, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise division of `scalar` by `vector`, /// double-precision. /// /// - Parameter scalar: the `a` in `c[i] = a / b[i]`. /// - Parameter vector: the `b` in `c[i] = a / b[i]`. /// - Parameter result: The `c` in `c[i] = a / b[i]`. @inlinable public static func divide<U, V>(_ scalar: Double, _ vector: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in vector.withUnsafeBufferPointer { v in withUnsafePointer(to: scalar) { s in vDSP_svdivD(s, v.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: c[i] = a[i] / b[i] vDSP_vdiv /// Returns the elementwise division of `vectorA` by `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Returns: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U>(_ vectorA: T, _ vectorB: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in divide(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vdiv(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } /// Returns the elementwise division of `vectorA` by `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Returns: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U>(_ vectorA: T, _ vectorB: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in divide(vectorA, vectorB, result: &buffer) initializedCount = vectorA.count } return result } /// Populates `result` with the elementwise division of `vectorA` by `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `a` in `c[i] = a[i] / b[i]`. /// - Parameter vectorB: the `b` in `c[i] = a[i] / b[i]`. /// - Parameter result: The `c` in `c[i] = a[i] / b[i]`. @inlinable public static func divide<T, U, V>(_ vectorA: T, _ vectorB: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vectorA.count == n && vectorB.count == n) result.withUnsafeMutableBufferPointer { r in vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in vDSP_vdivD(b.baseAddress!, 1, a.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } // MARK: o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i] vDSP_vaddsub /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, /// single-precision. /// /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. @inlinable public static func addSubtract<S, T, U, V>(_ vectorA: S, _ vectorB: T, addResult: inout U, subtractResult: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateMutableBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = addResult.count precondition(vectorA.count == n && vectorB.count == n && subtractResult.count == n) addResult.withUnsafeMutableBufferPointer { o0 in subtractResult.withUnsafeMutableBufferPointer { o1 in vectorA.withUnsafeBufferPointer { i1 in vectorB.withUnsafeBufferPointer { i0 in vDSP_vaddsub(i0.baseAddress!, 1, i1.baseAddress!, 1, o0.baseAddress!, 1, o1.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Calculates elementwise sum and difference of `vectorA` and `vectorB`, /// double-precision. /// /// - Parameter vectorA: the `i1` in `o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter vectorB: the `i0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter addResult: The `o0` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. /// - Parameter subtractResult: The `o1` in o0[i] = i1[i] + i0[i]; o1[i] = i1[i] - i0[i]`. @inlinable public static func addSubtract<S, T, U, V>(_ vectorA: S, _ vectorB: T, addResult: inout U, subtractResult: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateMutableBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = addResult.count precondition(vectorA.count == n && vectorB.count == n && subtractResult.count == n) addResult.withUnsafeMutableBufferPointer { o0 in subtractResult.withUnsafeMutableBufferPointer { o1 in vectorA.withUnsafeBufferPointer { i1 in vectorB.withUnsafeBufferPointer { i0 in vDSP_vaddsubD(i0.baseAddress!, 1, i1.baseAddress!, 1, o0.baseAddress!, 1, o1.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] + b[i]) * c vDSP_vasm /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U>(addition: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, scalar, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U, V>(addition: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vasm(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the sum of the vectors in `addition` and `scalar`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U>(addition: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, scalar, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `scalar`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] + b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] + b[i]) * c`. @inlinable public static func multiply<T, U, V>(addition: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vasmD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] + b[i]) * c[i] vDSP_vam /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(addition: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(addition: addition, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, /// single-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(addition: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vam(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the sum of the vectors in `addition` and `vector`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(addition: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(addition: addition, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the sum of the vectors in `addition` and `vector`, /// double-precision. /// /// - Parameter addition: the `a` and `b` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] + b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = (a[i] + b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(addition: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vamD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] - b[i]) * c vDSP_vsbsm /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U>(subtraction: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: subtraction.a.count) { buffer, initializedCount in multiply(subtraction: subtraction, scalar, result: &buffer) initializedCount = subtraction.a.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U, V>(subtraction: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vsbsm(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U>(subtraction: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: subtraction.a.count) { buffer, initializedCount in multiply(subtraction: subtraction, scalar, result: &buffer) initializedCount = subtraction.a.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `scalar`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c`. /// - Parameter scalar: the `c` in `d[i] = `(a[i] - b[i]) * c`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c`. @inlinable public static func multiply<T, U, V>(subtraction: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vsbsmD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] - b[i]) * c[i] vDSP_vsbm /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(subtraction: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(subtraction: subtraction, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// single-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(subtraction: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vsbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Returns: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U>(subtraction: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in multiply(subtraction: subtraction, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise product of the difference of the vectors in `subtraction` and `vector`, /// double-precision. /// /// - Parameter subtraction: the `a` and `b` in `d[i] = (a[i] - b[i]) * c[i]`. /// - Parameter vector: the `c` in `d[i] = `(a[i] - b[i]) * c[i]`. /// - Parameter result: The `d` in `d[i] = `(a[i] - b[i]) * c[i]`. @inlinable public static func multiply<S, T, U, V>(subtraction: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtraction.a.count == n && subtraction.b.count == n) result.withUnsafeMutableBufferPointer { r in subtraction.a.withUnsafeBufferPointer { a in subtraction.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vsbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = a[i]*b[i] + c; vDSP_vmsa /// Returns the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U>(multiplication: (a: T, b: U), _ scalar: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: U), _ scalar: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vmsa(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Returns: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U>(multiplication: (a: T, b: U), _ scalar: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of `scalar` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = a[i]*b[i] + c`. /// - Parameter scalar: the `c` in `d[i] = a[i]*b[i] + c`. /// - Parameter result: the `d` in `d[i] = a[i]*b[i] + c`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: U), _ scalar: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in withUnsafePointer(to: scalar) { s in vDSP_vmsaD(a.baseAddress!, 1, b.baseAddress!, 1, s, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b) + c[i] vDSP_vsma /// Returns the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U>(multiplication: (a: T, b: Float), _ vector: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: Float), _ vector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in vector.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplication.b) { b in vDSP_vsma(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U>(multiplication: (a: T, b: Double), _ vector: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b) + c[i]`. @inlinable public static func add<T, U, V>(multiplication: (a: T, b: Double), _ vector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in vector.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplication.b) { b in vDSP_vsmaD(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b[i]) + c[i] vDSP_vma /// Returns the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U>(multiplication: (a: S, b: T), _ vector: U) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U, V>(multiplication: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vma(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U>(multiplication: (a: S, b: T), _ vector: U) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in add(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise sum of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) + c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) + c[i]`. @inlinable public static func add<S, T, U, V>(multiplication: (a: S, b: T), _ vector: U, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmaD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: d[i] = (a[i] * b[i]) - c[i] vDSP_vmsb /// Returns the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U>(multiplication: (a: T, b: U), _ vector: S) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U, V>(multiplication: (a: T, b: U), _ vector: S, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmsb(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Returns: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U>(multiplication: (a: T, b: U), _ vector: S) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the two vectors in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter vector: the `c` in `d[i] = (a[i] * b[i]) - c[i]`. /// - Parameter result: the `d` in `d[i] = (a[i] * b[i]) - c[i]`. @inlinable public static func subtract<S, T, U, V>(multiplication: (a: T, b: U), _ vector: S, result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n && multiplication.b.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in multiplication.b.withUnsafeBufferPointer { b in vector.withUnsafeBufferPointer { c in vDSP_vmsbD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: e[i] = (a[i] * b) + (c[i] * d) vDSP_vsmsma /// Returns the elementwise sum of two elementwise /// vector-scalar products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U>(multiplication multiplicationAB: (a: T, b: Float), multiplication multiplicationCD: (c: U, d: Float)) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-scalar products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U, V>(multiplication multiplicationAB: (a: T, b: Float), multiplication multiplicationCD: (c: U, d: Float), result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationCD.c.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationCD.c.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplicationAB.b) { b in withUnsafePointer(to: multiplicationCD.d) { d in vDSP_vsmsma(a.baseAddress!, 1, b, c.baseAddress!, 1, d, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise sum of two elementwise /// vector-scalar products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Returns: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U>(multiplication multiplicationAB: (a: T, b: Double), multiplication multiplicationCD: (c: U, d: Double)) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-scalar products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b) + (c[i] * d)`. /// - Parameter result: the `e` in `e[i] = (a[i] * b) + (c[i] * d)`. @inlinable public static func add<T, U, V>(multiplication multiplicationAB: (a: T, b: Double), multiplication multiplicationCD: (c: U, d: Double), result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationCD.c.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationCD.c.withUnsafeBufferPointer { c in withUnsafePointer(to: multiplicationAB.b) { b in withUnsafePointer(to: multiplicationCD.d) { d in vDSP_vsmsmaD(a.baseAddress!, 1, b, c.baseAddress!, 1, d, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] * b[i]) + (c[i] * d[i]) vDSP_vmma /// Returns the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U, V>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmma(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise sum of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in add(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise sum of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) + (c[i] * d[i])`. @inlinable public static func add<R, S, T, U, V>(multiplication multiplicationAB: (a: R, b: S), multiplication multiplicationCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmaD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] + b[i]) * (c[i] + d[i]) vDSP_vaam /// Returns the elementwise product of two elementwise /// vector-vector sums, single-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U)) -> [Float] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: additionAB.a.count) { buffer, initializedCount in multiply(addition: additionAB, addition: additionCD, result: &buffer) initializedCount = additionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector sums, single-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U, V>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U), result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(additionAB.a.count == n && additionAB.b.count == n && additionCD.c.count == n && additionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in additionAB.a.withUnsafeBufferPointer { a in additionAB.b.withUnsafeBufferPointer { b in additionCD.c.withUnsafeBufferPointer { c in additionCD.d.withUnsafeBufferPointer { d in vDSP_vaam(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of two elementwise /// vector-vector sums, double-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U)) -> [Double] where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: additionAB.a.count) { buffer, initializedCount in multiply(addition: additionAB, addition: additionCD, result: &buffer) initializedCount = additionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector sums, double-precision. /// /// - Parameter additionAB: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter additionCD: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] + d[i])`. @inlinable public static func multiply<S, T, U, V>(addition additionAB: (a: S, b: T), addition additionCD: (c: U, d: U), result: inout V) where S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(additionAB.a.count == n && additionAB.b.count == n && additionCD.c.count == n && additionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in additionAB.a.withUnsafeBufferPointer { a in additionAB.b.withUnsafeBufferPointer { b in additionCD.c.withUnsafeBufferPointer { c in additionCD.d.withUnsafeBufferPointer { d in vDSP_vaamD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] * b[i]) - (c[i] * d[i]) vDSP_vmmsb /// Returns the elementwise difference of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in subtract(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise difference of two elementwise /// vector-vector products, single-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U, V>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmsb(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise difference of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Returns: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplicationAB.a.count) { buffer, initializedCount in subtract(multiplication: multiplicationAB, multiplication: multiplicationCD, result: &buffer) initializedCount = multiplicationAB.a.count } return result } /// Populates `result` with the elementwise difference of two elementwise /// vector-vector products, double-precision. /// /// - Parameter multiplicationAB: the `a` and `b` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter multiplicationCD: the `c` and `d` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] * b[i]) - (c[i] * d[i])`. @inlinable public static func subtract<R, S, T, U, V>(multiplication multiplicationAB: (a: T, b: U), multiplication multiplicationCD: (c: R, d: S), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplicationAB.a.count == n && multiplicationAB.b.count == n && multiplicationCD.c.count == n && multiplicationCD.d.count == n) result.withUnsafeMutableBufferPointer { r in multiplicationAB.a.withUnsafeBufferPointer { a in multiplicationAB.b.withUnsafeBufferPointer { b in multiplicationCD.c.withUnsafeBufferPointer { c in multiplicationCD.d.withUnsafeBufferPointer { d in vDSP_vmmsbD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] - b[i]) * (c[i] - d[i]) vDSP_vsbsbm /// Returns the elementwise product of two elementwise /// vector-vector differences, single-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: subtractionAB.a.count) { buffer, initializedCount in multiply(subtraction: subtractionAB, subtraction: subtractionCD, result: &buffer) initializedCount = subtractionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector differences, single-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(subtractionAB.a.count == n && subtractionAB.b.count == n && subtractionCD.c.count == n && subtractionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in subtractionAB.a.withUnsafeBufferPointer { a in subtractionAB.b.withUnsafeBufferPointer { b in subtractionCD.c.withUnsafeBufferPointer { c in subtractionCD.d.withUnsafeBufferPointer { d in vDSP_vsbsbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of two elementwise /// vector-vector differences, double-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: subtractionAB.a.count) { buffer, initializedCount in multiply(subtraction: subtractionAB, subtraction: subtractionCD, result: &buffer) initializedCount = subtractionAB.a.count } return result } /// Populates `result` with the elementwise product of two elementwise /// vector-vector differences, double-precision. /// /// - Parameter subtractionAB: the `a` and `b` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter subtractionCD: the `c` and `d` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] - b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(subtraction subtractionAB: (a: R, b: S), subtraction subtractionCD: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(subtractionAB.a.count == n && subtractionAB.b.count == n && subtractionCD.c.count == n && subtractionCD.d.count == n) result.withUnsafeMutableBufferPointer { r in subtractionAB.a.withUnsafeBufferPointer { a in subtractionAB.b.withUnsafeBufferPointer { b in subtractionCD.c.withUnsafeBufferPointer { c in subtractionCD.d.withUnsafeBufferPointer { d in vDSP_vsbsbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: e[i] = (a[i] + b[i]) * (c[i] - d[i]) vDSP_vasbm /// Returns the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, single-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(addition: (a: R, b: S), subtraction: (c: T, d: U)) -> [Float] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, subtraction: subtraction, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, single-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(addition: (a: R, b: S), subtraction: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Float, S.Element == Float, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(addition.a.count == n && addition.b.count == n && subtraction.c.count == n && subtraction.d.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in subtraction.c.withUnsafeBufferPointer { c in subtraction.d.withUnsafeBufferPointer { d in vDSP_vasbm(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } /// Returns the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, double-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Returns: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U>(addition: (a: R, b: S), subtraction: (c: T, d: U)) -> [Double] where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: addition.a.count) { buffer, initializedCount in multiply(addition: addition, subtraction: subtraction, result: &buffer) initializedCount = addition.a.count } return result } /// Populates `result` with the elementwise product of an elementwise /// vector-vector sum and an elementwise vector-vector sum, double-precision. /// /// - Parameter addition: the `a` and `b` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter subtraction: the `c` and `d` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. /// - Parameter result: the `e` in `e[i] = (a[i] + b[i]) * (c[i] - d[i])`. @inlinable public static func multiply<R, S, T, U, V>(addition: (a: R, b: S), subtraction: (c: T, d: U), result: inout V) where R: AccelerateBuffer, S: AccelerateBuffer, T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, R.Element == Double, S.Element == Double, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(addition.a.count == n && addition.b.count == n && subtraction.c.count == n && subtraction.d.count == n) result.withUnsafeMutableBufferPointer { r in addition.a.withUnsafeBufferPointer { a in addition.b.withUnsafeBufferPointer { b in subtraction.c.withUnsafeBufferPointer { c in subtraction.d.withUnsafeBufferPointer { d in vDSP_vasbmD(a.baseAddress!, 1, b.baseAddress!, 1, c.baseAddress!, 1, d.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } } // MARK: d[n] = a[n]*b + c vDSP_vsmsa /// Returns the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Returns: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U>(multiplication: (a: U, b: Float), _ scalar: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, single-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U, V>(multiplication: (a: U, b: Float), _ scalar: Float, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in withUnsafePointer(to: scalar) { c in vDSP_vsmsa(a.baseAddress!, 1, b, c, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c` in `d[n] = a[n]*b + c`. /// - Returns: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U>(multiplication: (a: U, b: Double), _ scalar: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: multiplication.a.count) { buffer, initializedCount in add(multiplication: multiplication, scalar, result: &buffer) initializedCount = multiplication.a.count } return result } /// Populates `result` with the elementwise sum of an elementwise /// vector-scalar product and aa scalar value, double-precision. /// /// - Parameter multiplication: the `a` and `b` in `d[n] = a[n]*b + c`. /// - Parameter scalar: the `c`in `d[n] = a[n]*b + c`. /// - Parameter result: the `e` in `d[n] = a[n]*b + c`. @inlinable public static func add<U, V>(multiplication: (a: U, b: Double), _ scalar: Double, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in withUnsafePointer(to: scalar) { c in vDSP_vsmsaD(a.baseAddress!, 1, b, c, r.baseAddress!, 1, vDSP_Length(n)) } } } } } // MARK: D[n] = A[n]*B - C[n]; vDSP_vsmsb /// Returns the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U>(multiplication: (a: U, b: Float), _ vector: T) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// single-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U, V>(multiplication: (a: U, b: Float), _ vector: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(multiplication.a.count == n) precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in vector.withUnsafeBufferPointer { c in vDSP_vsmsb(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } /// Returns the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Returns: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U>(multiplication: (a: U, b: Double), _ vector: T) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in subtract(multiplication: multiplication, vector, result: &buffer) initializedCount = vector.count } return result } /// Populates `result` with the elementwise difference of `vector` /// and the product of the vector and scalar in `multiplication`, /// double-precision. /// /// - Parameter vector: the `c` in `D[n] = A[n]*B - C[n]`. /// - Parameter multiplication: the `a` and `b` in `D[n] = A[n]*B - C[n]`. /// - Parameter result: the `d` in `D[n] = A[n]*B - C[n]`. @inlinable public static func subtract<T, U, V>(multiplication: (a: U, b: Double), _ vector: T, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(multiplication.a.count == n) precondition(vector.count == n) result.withUnsafeMutableBufferPointer { r in multiplication.a.withUnsafeBufferPointer { a in withUnsafePointer(to: multiplication.b) { b in vector.withUnsafeBufferPointer { c in vDSP_vsmsbD(a.baseAddress!, 1, b, c.baseAddress!, 1, r.baseAddress!, 1, vDSP_Length(n)) } } } } } }
apache-2.0
804db0baf5bfd3a90052b9393336ff9f
39.15471
119
0.443924
4.659789
false
false
false
false
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/Promise.swift
111
1271
//===--- Promise.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 Boilerplate import Result import ExecutionContext public class Promise<V> : MutableFutureType { public typealias Value = V private let _future:MutableFuture<V> public var future:Future<V> { get { return _future } } public init() { _future = MutableFuture(context: immediate) } public func tryComplete<E : ErrorProtocol>(result:Result<Value, E>) -> Bool { return _future.tryComplete(result) } }
mit
aecffe98bf3a59524efcefd305c17d29
30.8
82
0.616837
4.8327
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/Settings/LoginDetailViewController.swift
2
15344
/* 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 Storage import Shared import SwiftKeychainWrapper enum InfoItem: Int { case websiteItem = 0 case usernameItem = 1 case passwordItem = 2 case lastModifiedSeparator = 3 case deleteItem = 4 var indexPath: IndexPath { return IndexPath(row: rawValue, section: 0) } } private struct LoginDetailUX { static let InfoRowHeight: CGFloat = 58 static let DeleteRowHeight: CGFloat = 44 static let SeparatorHeight: CGFloat = 44 } class LoginDetailViewController: SensitiveViewController { fileprivate let profile: Profile fileprivate let tableView = UITableView() fileprivate var login: Login { didSet { tableView.reloadData() } } fileprivate var editingInfo: Bool = false { didSet { if editingInfo != oldValue { tableView.reloadData() } } } fileprivate let LoginCellIdentifier = "LoginCell" fileprivate let DefaultCellIdentifier = "DefaultCellIdentifier" fileprivate let SeparatorIdentifier = "SeparatorIdentifier" // Used to temporarily store a reference to the cell the user is showing the menu controller for fileprivate var menuControllerCell: LoginTableViewCell? fileprivate weak var websiteField: UITextField? fileprivate weak var usernameField: UITextField? fileprivate weak var passwordField: UITextField? fileprivate var deleteAlert: UIAlertController? weak var settingsDelegate: SettingsDelegate? init(profile: Profile, login: Login) { self.login = login self.profile = profile super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(dismissAlertController), name: .UIApplicationDidEnterBackground, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(SELedit)) tableView.register(LoginTableViewCell.self, forCellReuseIdentifier: LoginCellIdentifier) tableView.register(UITableViewCell.self, forCellReuseIdentifier: DefaultCellIdentifier) tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SeparatorIdentifier) view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.separatorColor = SettingsUX.TableViewSeparatorColor tableView.backgroundColor = SettingsUX.TableViewHeaderBackgroundColor tableView.accessibilityIdentifier = "Login Detail List" tableView.delegate = self tableView.dataSource = self // Add empty footer view to prevent seperators from being drawn past the last item. tableView.tableFooterView = UIView() // Add a line on top of the table view so when the user pulls down it looks 'correct'. let topLine = UIView(frame: CGRect(width: tableView.frame.width, height: 0.5)) topLine.backgroundColor = SettingsUX.TableViewSeparatorColor tableView.tableHeaderView = topLine // Normally UITableViewControllers handle responding to content inset changes from keyboard events when editing // but since we don't use the tableView's editing flag for editing we handle this ourselves. KeyboardHelper.defaultHelper.addDelegate(self) } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // The following hacks are to prevent the default cell seperators from displaying. We want to // hide the default seperator for the website/last modified cells since the last modified cell // draws its own separators. The last item in the list draws its seperator full width. // Prevent seperators from showing by pushing them off screen by the width of the cell let itemsToHideSeperators: [InfoItem] = [.passwordItem, .lastModifiedSeparator] itemsToHideSeperators.forEach { item in let cell = tableView.cellForRow(at: IndexPath(row: item.rawValue, section: 0)) cell?.separatorInset = UIEdgeInsets(top: 0, left: cell?.bounds.width ?? 0, bottom: 0, right: 0) } // Rows to display full width seperator let itemsToShowFullWidthSeperator: [InfoItem] = [.deleteItem] itemsToShowFullWidthSeperator.forEach { item in let cell = tableView.cellForRow(at: IndexPath(row: item.rawValue, section: 0)) cell?.separatorInset = .zero cell?.layoutMargins = .zero cell?.preservesSuperviewLayoutMargins = false } } } // MARK: - UITableViewDataSource extension LoginDetailViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch InfoItem(rawValue: indexPath.row)! { case .usernameItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("username", tableName: "LoginManager", comment: "Label displayed above the username row in Login Detail View.") loginCell.descriptionLabel.text = login.username loginCell.descriptionLabel.keyboardType = .emailAddress loginCell.descriptionLabel.returnKeyType = .next loginCell.editingDescription = editingInfo usernameField = loginCell.descriptionLabel usernameField?.accessibilityIdentifier = "usernameField" return loginCell case .passwordItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("password", tableName: "LoginManager", comment: "Label displayed above the password row in Login Detail View.") loginCell.descriptionLabel.text = login.password loginCell.descriptionLabel.returnKeyType = .default loginCell.displayDescriptionAsPassword = true loginCell.editingDescription = editingInfo passwordField = loginCell.descriptionLabel passwordField?.accessibilityIdentifier = "passwordField" return loginCell case .websiteItem: let loginCell = dequeueLoginCellForIndexPath(indexPath) loginCell.style = .noIconAndBothLabels loginCell.highlightedLabelTitle = NSLocalizedString("website", tableName: "LoginManager", comment: "Label displayed above the website row in Login Detail View.") loginCell.descriptionLabel.text = login.hostname websiteField = loginCell.descriptionLabel websiteField?.accessibilityIdentifier = "websiteField" return loginCell case .lastModifiedSeparator: let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: SeparatorIdentifier) as! SettingsTableSectionHeaderFooterView footer.titleAlignment = .top let lastModified = NSLocalizedString("Last modified %@", tableName: "LoginManager", comment: "Footer label describing when the current login was last modified with the timestamp as the parameter.") let formattedLabel = String(format: lastModified, Date.fromMicrosecondTimestamp(login.timePasswordChanged).toRelativeTimeString()) footer.titleLabel.text = formattedLabel let cell = wrapFooter(footer, withCellFromTableView: tableView, atIndexPath: indexPath) return cell case .deleteItem: let deleteCell = tableView.dequeueReusableCell(withIdentifier: DefaultCellIdentifier, for: indexPath) deleteCell.textLabel?.text = NSLocalizedString("Delete", tableName: "LoginManager", comment: "Label for the button used to delete the current login.") deleteCell.textLabel?.textAlignment = .center deleteCell.textLabel?.textColor = UIConstants.DestructiveRed deleteCell.accessibilityTraits = UIAccessibilityTraitButton return deleteCell } } fileprivate func dequeueLoginCellForIndexPath(_ indexPath: IndexPath) -> LoginTableViewCell { let loginCell = tableView.dequeueReusableCell(withIdentifier: LoginCellIdentifier, for: indexPath) as! LoginTableViewCell loginCell.selectionStyle = .none loginCell.delegate = self return loginCell } fileprivate func wrapFooter(_ footer: UITableViewHeaderFooterView, withCellFromTableView tableView: UITableView, atIndexPath indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DefaultCellIdentifier, for: indexPath) cell.selectionStyle = .none cell.addSubview(footer) footer.snp.makeConstraints { make in make.edges.equalTo(cell) } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } } // MARK: - UITableViewDelegate extension LoginDetailViewController: UITableViewDelegate { private func showMenuOnSingleTap(forIndexPath indexPath: IndexPath) { guard let item = InfoItem(rawValue: indexPath.row) else { return } if ![InfoItem.passwordItem, InfoItem.websiteItem, InfoItem.usernameItem].contains(item) { return } guard let cell = tableView.cellForRow(at: indexPath) as? LoginTableViewCell else { return } cell.becomeFirstResponder() let menu = UIMenuController.shared menu.setTargetRect(cell.frame, in: self.tableView) menu.setMenuVisible(true, animated: true) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath == InfoItem.deleteItem.indexPath { deleteLogin() } else if !editingInfo { showMenuOnSingleTap(forIndexPath: indexPath) } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch InfoItem(rawValue: indexPath.row)! { case .usernameItem, .passwordItem, .websiteItem: return LoginDetailUX.InfoRowHeight case .lastModifiedSeparator: return LoginDetailUX.SeparatorHeight case .deleteItem: return LoginDetailUX.DeleteRowHeight } } } // MARK: - KeyboardHelperDelegate extension LoginDetailViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(tableView) tableView.contentInset.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } } // MARK: - Selectors extension LoginDetailViewController { @objc func dismissAlertController() { self.deleteAlert?.dismiss(animated: false, completion: nil) } func deleteLogin() { profile.logins.hasSyncedLogins().uponQueue(.main) { yes in self.deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in self.profile.logins.removeLoginByGUID(self.login.guid).uponQueue(.main) { _ in _ = self.navigationController?.popViewController(animated: true) } }, hasSyncedLogins: yes.successValue ?? true) self.present(self.deleteAlert!, animated: true, completion: nil) } } func SELonProfileDidFinishSyncing() { // Reload details after syncing. profile.logins.getLoginDataForGUID(login.guid).uponQueue(.main) { result in if let syncedLogin = result.successValue { self.login = syncedLogin } } } func SELedit() { editingInfo = true let cell = tableView.cellForRow(at: InfoItem.usernameItem.indexPath) as! LoginTableViewCell cell.descriptionLabel.becomeFirstResponder() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(SELdoneEditing)) } func SELdoneEditing() { editingInfo = false navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(SELedit)) defer { // Required to get UI to reload with changed state tableView.reloadData() } // We only care to update if we changed something guard let username = usernameField?.text, let password = passwordField?.text, username != login.username || password != login.password else { return } // Keep a copy of the old data in case we fail and need to revert back let oldPassword = login.password let oldUsername = login.username login.update(password: password, username: username) if login.isValid.isSuccess { profile.logins.updateLoginByGUID(login.guid, new: login, significant: true) } else if let oldUsername = oldUsername { login.update(password: oldPassword, username: oldUsername) } } } // MARK: - Cell Delegate extension LoginDetailViewController: LoginTableViewCellDelegate { fileprivate func cellForItem(_ item: InfoItem) -> LoginTableViewCell? { return tableView.cellForRow(at: item.indexPath) as? LoginTableViewCell } func didSelectOpenAndFillForCell(_ cell: LoginTableViewCell) { guard let url = (self.login.formSubmitURL?.asURL ?? self.login.hostname.asURL) else { return } navigationController?.dismiss(animated: true, completion: { self.settingsDelegate?.settingsOpenURLInNewTab(url) }) } func shouldReturnAfterEditingDescription(_ cell: LoginTableViewCell) -> Bool { let usernameCell = cellForItem(.usernameItem) let passwordCell = cellForItem(.passwordItem) if cell == usernameCell { passwordCell?.descriptionLabel.becomeFirstResponder() } return false } func infoItemForCell(_ cell: LoginTableViewCell) -> InfoItem? { if let index = tableView.indexPath(for: cell), let item = InfoItem(rawValue: index.row) { return item } return nil } }
mpl-2.0
c859e2172a8fa7db1d944f7af313cad6
40.026738
209
0.688803
5.664083
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Modules/Checkout/Sources/FeatureCheckoutUI/CountdownView.swift
1
2010
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainUI import SwiftUI import SwiftUIExtensions @MainActor struct CountdownView: View { private var deadline: Date private let formatter: DateComponentsFormatter = .shortCountdownFormatter @Environment(\.scheduler) private var scheduler @State private var remaining: String? @State private var progress: Double = 0.0 @State private var opacity: Double = 1 init(deadline: Date) { self.deadline = deadline } var body: some View { HStack(spacing: 0) { Spacer() ProgressView(value: progress) .progressViewStyle(.determinate) .frame(width: 14.pt, height: 14.pt) .padding(.trailing, 8.pt) Text(LocalizationConstants.Checkout.Label.countdown) ZStack(alignment: .leading) { if let remaining = remaining { Text(remaining) } Text("MM:SS").opacity(0) // hack to fix alignment of the counter } Spacer() } .typography(.caption2) .task(id: deadline, priority: .userInitiated) { let start = deadline.timeIntervalSinceNow for seconds in stride(from: start, to: 0, by: -1) where seconds > 0 { withAnimation { remaining = formatter.string(from: seconds) progress = min(1 - seconds / start, 1) } do { try await scheduler.sleep(for: .seconds(1)) } catch /* a */ { break } } } } } extension DateComponentsFormatter { static var shortCountdownFormatter: DateComponentsFormatter { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.minute, .second] formatter.unitsStyle = .positional formatter.zeroFormattingBehavior = .pad return formatter } }
lgpl-3.0
a431b136f5c7df7a1a4f6dfd711cc6f4
29.907692
81
0.577402
5.098985
false
false
false
false
ddgold/Cathedral
Cathedral/Model/Building.swift
1
9356
// // Building.swift // Cathedral // // Created by Doug Goldstein on 1/29/19. // Copyright © 2019 Doug Goldstein. All rights reserved. // import Foundation /// A building type. enum Building: UInt8 { //MARK: - Values case tavern case stable case inn case bridge case square case abbey case manor case tower case infirmary case castle case academy case cathedral //MARK: - Properties /// Set of all player buildings. static var playerBuildings: Set<Building> { return [self.tavern, self.stable, self.inn, self.bridge, self.square, self.abbey, self.manor, self.tower, self.infirmary, self.castle, self.academy] } /// The number if tiles wide this building type covers. private var width: UInt8 { switch self { case .tavern: return 1 case .stable: return 1 case .inn: return 2 case .bridge: return 1 case .square: return 2 case .abbey: return 2 case .manor: return 2 case .tower: return 3 case .infirmary: return 3 case .castle: return 2 case .academy: return 3 case .cathedral: return 3 } } /// The number of tiles tall this building type covers. private var height: UInt8 { switch self { case .tavern: return 1 case .stable: return 2 case .inn: return 2 case .bridge: return 3 case .square: return 2 case .abbey: return 3 case .manor: return 3 case .tower: return 3 case .infirmary: return 3 case .castle: return 3 case .academy: return 3 case .cathedral: return 4 } } /// The number of tiles this building type covers. var size: UInt8 { switch self { case .tavern: return 1 case .stable: return 2 case .inn: return 3 case .bridge: return 3 case .square: return 4 case .abbey: return 4 case .manor: return 4 case .tower: return 5 case .infirmary: return 5 case .castle: return 5 case .academy: return 5 case .cathedral: return 6 } } /// The log entry for this building. var log: String { switch self { case .tavern: return "TA" case .stable: return "ST" case .inn: return "IN" case .bridge: return "BR" case .square: return "SQ" case .abbey: return "AB" case .manor: return "MA" case .tower: return "TO" case .infirmary: return "IF" case .castle: return "CS" case .academy: return "AC" case .cathedral: return "CA" } } //MARK: - Initialization /// Initializes a building from a log entry. /// /// - Parameter log: The log entry. init?(_ log: String) { switch log { case "TA": self = .tavern case "ST": self = .stable case "IN": self = .inn case "BR": self = .bridge case "SQ": self = .square case "AB": self = .abbey case "MA": self = .manor case "TO": self = .tower case "IF": self = .infirmary case "CS": self = .castle case "AC": self = .academy case "CA": self = .cathedral default: return nil } } //MARK: - Functions /// Builds the blueprints for this building type based on owner, direction, and address. /// /// - Parameters: /// - owner: The owner of the building. /// - direction: The direction of the building. /// - address: The origin of the building. Defaults to (0, 0). /// - Returns: A set of addresses that make up the blueprint. func blueprint(owner: Owner, facing direction: Direction, at address: Address = Address(0, 0)) -> Set<Address> { assert(owner.isChurch == (self == .cathedral), "Can't get blueprint for \(owner) \(self)") // Get the base blueprint base on owner and building type let base: Set<Address> switch self { case .tavern: base = [Address(0, 0)] case .stable: base = [Address(0, 0), Address(0, 1)] case .inn: base = [Address(0, 0), Address(0, 1), Address(1, 0)] case .bridge: base = [Address(0, 0), Address(0, 1), Address(0, 2)] case .square: base = [Address(0, 0), Address(0, 1), Address(1, 0), Address(1, 1)] case .abbey: if (owner == .light) { base = [Address(0, 0), Address(0, 1), Address(1, 1), Address(1, 2)] } else { base = [Address(0, 1), Address(0, 2), Address(1, 0), Address(1, 1)] } case .manor: base = [Address(0, 0), Address(0, 1), Address(0, 2), Address(1, 1)] case .tower: base = [Address(0, 0), Address(0, 1), Address(1, 1), Address(1, 2), Address(2, 2)] case .infirmary: base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 1)] case .castle: base = [Address(0, 0), Address(0, 1), Address(0, 2), Address(1, 0), Address(1, 2)] case .academy: if (owner == .light) { base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 2)] } else { base = [Address(0, 2), Address(1, 0), Address(1, 1), Address(1, 2), Address(2, 1)] } case .cathedral: base = [Address(0, 1), Address(1, 0), Address(1, 1), Address(1, 2), Address(1, 3), Address(2, 1)] } // Rotate and translate blueprint based on direction and origin var final = Set<Address>() base.forEach { (offset) in let rotated = offset.rotated(direction) final.insert(Address(address.col + rotated.col, address.row + rotated.row)) } return final } /// Get the tile width and height for this building facing a given direction. /// /// - Parameter direction: The direction. /// - Returns: A tuple, where the fist element is the width, and the second element is the height. func dimensions(direction: Direction) -> (width: Int8, height: Int8) { let width: Int8 let height: Int8 if (direction == .north) || (direction == .south) { width = Int8(self.width) height = Int8(self.height) } else { width = Int8(self.height) height = Int8(self.width) } return (width: width, height: height) } //MARK: - Descriptions /// Description of the building enum. static var description: String { return "Building" } /// Description of a particular building. var description: String { switch self { case .tavern: return "Tavern" case .stable: return "Stable" case .inn: return "Inn" case .bridge: return "Bridge" case .square: return "Square" case .abbey: return "Abbey" case .manor: return "Manor" case .tower: return "Tower" case .infirmary: return "Infirmary" case .castle: return "Castle" case .academy: return "Academy" case .cathedral: return "Cathedral" } } }
apache-2.0
a4f4926146683aeb73b7f13defe78201
24.080429
156
0.426403
4.67984
false
false
false
false
Jnosh/swift
test/SILOptimizer/devirt_materializeForSet.swift
6
1352
// RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s // Check that compiler does not crash on the devirtualization of materializeForSet methods // and produces a correct code. // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T024devirt_materializeForSet7BaseFooCAA0F0A2aDP3barSSfmTW // CHECK: checked_cast_br [exact] %{{.*}} : $BaseFoo to $ChildFoo // CHECK: thin_function_to_pointer %{{.*}} : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout ChildFoo, @thick ChildFoo.Type) -> () to $Builtin.RawPointer // CHECK: enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, %{{.*}} : $Builtin.RawPointer // CHECK: tuple (%{{.*}} : $Builtin.RawPointer, %{{.*}} : $Optional<Builtin.RawPointer>) public protocol Foo { var bar: String { get set } } open class BaseFoo: Foo { open var bar: String = "hello" } open class ChildFoo: BaseFoo { private var _bar: String = "world" override open var bar: String { get { return _bar } set { _bar = newValue } } } @inline(never) public func test1(bf: BaseFoo) { bf.bar = "test1" print(bf.bar) } @inline(never) public func test2(f: Foo) { var f = f f.bar = "test2" print(f.bar) } //test1(BaseFoo()) //test1(ChildFoo()) //test2(BaseFoo()) //test2(ChildFoo())
apache-2.0
61e137a4f78c01088a1c3911ec4b09cc
25
188
0.64497
3.346535
false
true
false
false
martinomamic/CarBooking
CarBooking/Helpers/Extensions/UIExtensions.swift
1
9177
// // UIExtensions.swift // CarBooking // // Created by Martino Mamic on 29/07/2017. // Copyright © 2017 Martino Mamic. All rights reserved. // import UIKit //MARK: CarBooking colors extension UIColor { class var primaryColor: UIColor { return UIColor(red: 172.0, green: 207.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0) } class var secondaryColor: UIColor { return UIColor(red: 89.0 / 255.0, green: 82.0 / 255.0, blue: 65.0 / 255.0, alpha: 1.0) } class var accentColor: UIColor { return UIColor(red: 138.0 / 255.0, green: 9.0 / 255.0, blue: 23.0 / 255.0, alpha: 1.0) } } //MARK: Storyboard enum, used in custom initializer enum Storyboard: String { // Current storyboard name case Main } //MARK: UIStoryboard extension - custom storyboard init, and generic controller instatiation extension UIStoryboard { /// Convenience init used with Storyboard enum to shorten syntax. /// /// - Parameters: /// - storyboard: Storyboard enum value. /// - bundle: Bundle containing the storyboard, optional - defaults to nil. convenience init(storyboard: Storyboard, bundle: Bundle? = nil) { self.init(name: storyboard.rawValue, bundle: bundle) } /// Generic UIViewController initializer /// /// - Returns: StoryboardIdentifiable view controller func instantiateVC<T: UIViewController>() -> T where T: StoryboardIdentifiable { let optionalViewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) guard let vc = optionalViewController as? T else { fatalError("Couldn’t instantiate view controller with identifier \(T.storyboardIdentifier)") } return vc } } //MARK: StoryboardIdentifiable initializers, alert handling. extension UIViewController : StoryboardIdentifiable { /// Instantiates generic controller from storyboard. /// Extracts storyboard identifier from view controller class. /// View controller class has to be implicit. /// /// - Parameters: /// - type: Controller class. /// - storyboard: Parent storyboard. /// - Returns: Generic view controller. func instantiateFromStoryboard<T>(type: T.Type, storyboard: UIStoryboard) -> T? { let controllerIdentifier = String(describing: type) return storyboard.instantiateViewController(withIdentifier: controllerIdentifier) as? T } /// Generic view controller initializer /// Uses generic instantiation method convenience init<T>(type: T.Type, storyboard: UIStoryboard) { self.init() _ = self.instantiateFromStoryboard(type: type, storyboard: storyboard) } /// Creates alert view controller and displays it on self /// Only dismiss action is currently provided /// /// - Parameters: /// - title: Alert title. /// - message: Alert message. func showAlert(title: String, message: String) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Alert.dismiss".localized, style: .default, handler: nil) alertVC.addAction(dismissAction) DispatchQueue.main.async { self.present(alertVC, animated: true, completion: nil) } } } //MARK: Generic cell and nib registration, generic dequeueing with and without indexpath or identifier. extension UITableView { /// Registers cell class for table view /// /// - Parameter cellClass: UITableViewCell type func register<T: UITableViewCell>(cellClass: T.Type) where T: Reusable { register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } /// Register cell view class For UITableView /// /// - Parameter _: class type func registerNib<T: UITableViewCell>(_: T.Type) where T: Reusable, T: NibLoadable { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } /// Dequeues generic table view cell type for optional indexPath and/or identifier /// If no identifier is provided idenitfier is extracted from immplicit cell type(defaultReuseIdentifier) /// /// - Parameters: /// - indexPath: IndexPath of current cell, optional - defaults to nil /// - identifier: String identifier, optional - defaults to nil, if nil defaultReuseIdentifier is used /// - Returns: Generic reusable cell func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath? = nil, identifier: String? = nil) -> T where T: Reusable { guard let indexPth = indexPath else { guard let idt = identifier else { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } guard let cell = dequeueReusableCell(withIdentifier: idt) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(idt)") } return cell } guard let idt = identifier else { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPth) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } guard let cell = dequeueReusableCell(withIdentifier: idt, for: indexPth) as? T else { fatalError("Couldn’t dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } /// Used just to conform to Reusable and NibLoadable protocols extension UITableViewCell:Reusable, NibLoadable {} //MARK: UIImageView extension, handling image download extension UIImageView { /// Checks if image string is valid, then adds encoding, creates URL and starts download /// /// - Parameter imageString: Absolute URL string func loadImage(imageString: String?) { guard var imgURLString = imageString, imageString != "" else { return } imgURLString = imgURLString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)! print(imgURLString) guard let imgURL = URL(string: imgURLString) else { return } fetchImageFromURL(url: imgURL) } /// Checks if image exists in cache and returns it /// If it doesn't exist in cache attempts download /// /// - Parameter url: Image URL private func fetchImageFromURL(url: URL) { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.center = self.center activityIndicator.startAnimating() DispatchQueue.main.async { [unowned self] in self.addSubview(activityIndicator) } if let image = url.cachedImage { DispatchQueue.main.async { [unowned self] in activityIndicator.removeFromSuperview() self.image = image } } else { url.fetchImage(completion: { (image) in DispatchQueue.main.async { [unowned self] in activityIndicator.removeFromSuperview() self.image = image } }) } } } /// UIWindow extenison, activity indicator handling during requests extension UIApplication { /// Checks if window contains a view with tag 137 /// If it doesnt, creates shadow view for background and activity indicator /// If status is provided, a status label is shown under activity indicator /// /// - Parameter status: optional status string, defaults to nil func addActivityIndicator(status: String? = nil) { if let act = self.keyWindow?.subviews.filter({ $0.tag == 42 }) { if act.count == 0 { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true let shadowView = UIView(frame: self.keyWindow!.frame) shadowView.tag = 42 shadowView.backgroundColor = UIColor(red: 0.003, green: 0.003, blue: 0.003, alpha: 0.4) let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) shadowView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() activityIndicatorView.center = shadowView.center self.keyWindow!.addSubview(shadowView) } } } } /// Filters window subview for viewwith tag 137 and removes the view if it exists func removeActivityIndicator() { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.keyWindow?.subviews.filter({ $0.tag == 42 }).first?.removeFromSuperview() } } }
mit
ec2b12e1b42e1869bc37477c43680976
40.288288
118
0.646738
5.095053
false
false
false
false
MarioIannotta/SplitViewDragAndDrop
SplitViewDragAndDrop/SplitViewDragAndDrop+Dragger.swift
1
8151
// // SplitViewDragAndDrop+Dragger.swift // DragAndDropDemo // // Created by Mario on 26/05/2017. // Copyright © 2017 Mario. All rights reserved. // import UIKit extension SplitViewDragAndDrop { internal class Dragger: NSObject { private struct StoreKeys { static let draggingValidation = "storeKeysDraggingValidation" struct DraggingValidation { static let result = "storeKeysDraggingValidationResult" static let initialDragPoint = "storeKeysDraggingValidationInitialDragPoint" } } private var dragAndDropManager: SplitViewDragAndDrop private var initialDragPoint: CGPoint! private var viewToDragSnapshotImageView = UIImageView(frame: CGRect.zero) private var updateTriggered = false private var updateTriggeredToRight = false private var dataToTransfers = [UIView: Data]() private var identifiers = [UIView: String]() internal var draggingEndedClosure: ((_ isValid: Bool) -> Void)? internal init(dragAndDropManager: SplitViewDragAndDrop) { self.dragAndDropManager = dragAndDropManager super.init() dragAndDropManager.groupDefaults.addObserver(self, forKeyPath: StoreKeys.draggingValidation, options: .new, context: nil) } func notifyDraggingValidationResult(_ result: Bool, initialDragPoint: CGPoint) { let draggingValidationDictionary: [String: Any] = [ StoreKeys.DraggingValidation.result: result, StoreKeys.DraggingValidation.initialDragPoint: initialDragPoint ] dragAndDropManager.groupDefaults.set(NSKeyedArchiver.archivedData(withRootObject: draggingValidationDictionary), forKey: StoreKeys.draggingValidation) dragAndDropManager.groupDefaults.synchronize() } deinit { dragAndDropManager.groupDefaults.removeObserver(self, forKeyPath: StoreKeys.draggingValidation) } private func setupViewToDragSnapshotImageView(from view: UIView, centerPoint: CGPoint) { let image = view.getSnapshot() viewToDragSnapshotImageView.frame = view.frame viewToDragSnapshotImageView.center = centerPoint viewToDragSnapshotImageView.image = image UIApplication.shared.keyWindow?.addSubview(viewToDragSnapshotImageView) } internal func handleDrag(viewToDrag: UIView, identifier: String, dataToTransfer: Data? = nil) { viewToDrag.addGestureRecognizer( UIPanGestureRecognizer(target: self, action: #selector(handleGestureRecognizer(_:))) ) self.dataToTransfers[viewToDrag] = dataToTransfer self.identifiers[viewToDrag] = identifier } @objc private func handleGestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) { guard let draggedView = gestureRecognizer.view, let keyWindow = UIApplication.shared.keyWindow else { return } let dragPoint = gestureRecognizer.location(in: keyWindow) switch gestureRecognizer.state { case .began: initialDragPoint = dragPoint updateTriggered = false updateTriggeredToRight = false setupViewToDragSnapshotImageView(from: draggedView, centerPoint: dragPoint) if let viewToDragSnapshotImage = viewToDragSnapshotImageView.image { dragAndDropManager.prepareForDraggingUpdate( identifier: identifiers[draggedView] ?? "", viewToDragSnapshotImage: viewToDragSnapshotImage, dataToTransfer: dataToTransfers[draggedView] ) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .began, isTriggeredToRight: updateTriggeredToRight) case .ended: if !updateTriggered { SplitViewDragAndDrop.completeDragging(isFallBack: true, draggingView: self.viewToDragSnapshotImageView, targetCenterPoint: self.initialDragPoint, completion: nil) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .ended, isTriggeredToRight: updateTriggeredToRight) default: let isToRight = gestureRecognizer.velocity(in: keyWindow).x > 0 viewToDragSnapshotImageView.center = dragPoint let shouldTriggerUpdate = isToRight ? viewToDragSnapshotImageView.frame.origin.x + viewToDragSnapshotImageView.frame.size.width >= UIWindow.width : viewToDragSnapshotImageView.frame.origin.x <= 0 if updateTriggered || shouldTriggerUpdate { if updateTriggered == false { updateTriggeredToRight = isToRight } updateTriggered = true let frame = CGRect( x: SplitViewDragAndDrop.transformXCoordinate(viewToDragSnapshotImageView.frame.origin.x, updateTriggeredToRight: updateTriggeredToRight), y: viewToDragSnapshotImageView.frame.origin.y, width: viewToDragSnapshotImageView.frame.size.width, height: viewToDragSnapshotImageView.frame.size.height ) var initialDragPoint = self.initialDragPoint ?? .zero initialDragPoint.x = SplitViewDragAndDrop.transformXCoordinate(initialDragPoint.x, updateTriggeredToRight: updateTriggeredToRight) dragAndDropManager.notifyDraggingUpdate(frame: frame, initialDragPoint: initialDragPoint) } dragAndDropManager.notifyGestureRecognizerUpdate(state: .changed, isTriggeredToRight: updateTriggeredToRight) } } internal override func observeValue( forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath, let changedData = change?[.newKey] as? Data else { return } switch keyPath { case StoreKeys.draggingValidation: if let draggingValidation = NSKeyedUnarchiver.unarchiveObject(with: changedData) as? [String: Any], let validationResult = draggingValidation[StoreKeys.DraggingValidation.result] as? Bool, validationResult == false, let initialDragPoint = draggingValidation[StoreKeys.DraggingValidation.initialDragPoint] as? CGPoint, initialDragPoint.x > 0, initialDragPoint.x < UIWindow.width { SplitViewDragAndDrop.completeDragging(isFallBack: true, draggingView: self.viewToDragSnapshotImageView, targetCenterPoint: initialDragPoint, completion: nil) dragAndDropManager.groupDefaults.removeObject(forKey: StoreKeys.draggingValidation) } default: break } } } }
mit
68cd95c380a897d2376f162faa056703
41.010309
182
0.571779
7.4977
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/Views/FilterSliderViewModel.swift
1
1979
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// This class represents the view model for a slider filter view class FilterSliderViewModel: NSObject { var filterTitle: String! private var unitLabel: String! var minimumValue: Int! var maximumValue: Int! private var stepAmount: Int! dynamic var currentValue: NSNumber! var minimumValueText: String { return String(minimumValue) + unitLabel } var maximumValueText: String { return String(maximumValue) + unitLabel } var currentValueText: String { return currentValue.stringValue + unitLabel } var acceptedValues : [Int] = [] required init(filterTitle: String, unitLabel: String, minimumValue: Int, maximumValue: Int, stepAmount: Int, startingValue: Int) { super.init() self.filterTitle = filterTitle self.unitLabel = unitLabel self.minimumValue = minimumValue self.maximumValue = maximumValue self.stepAmount = stepAmount self.currentValue = startingValue self.calculateAcceptedValues() } /** Based on the minimum, maximum, and step amount values, this calculates the number of accepted values on the slider */ private func calculateAcceptedValues() { for var i = minimumValue; i <= maximumValue; i = i + self.stepAmount { acceptedValues.append(i) } } /** Based on the current amount, round to the nearest accepted value - parameter value: The current value of the slider */ func updateCurrentAmount(value: Float) { let roundedValue = Int(floor(value)) let remainder = roundedValue % stepAmount let middleValue = stepAmount / 2 if remainder <= middleValue { currentValue = roundedValue - remainder } else { currentValue = roundedValue + stepAmount - remainder } } }
epl-1.0
05c0b47f413ab98335059c6f432ddd73
31.966667
134
0.662285
5.097938
false
false
false
false
trujillo138/MyExpenses
MyExpenses/MyExpenses/Scenes/ExpensePeriod/ExpensesDataSource.swift
1
2119
// // ExpensesDataSource.swift // MyExpenses // // Created by Tomas Trujillo on 6/27/17. // Copyright © 2017 TOMApps. All rights reserved. // import UIKit class ExpensesDataSource: NSObject, UITableViewDataSource { //MARK: Properties var expensePeriod: ExpensePeriod var cellIdentifier: String var expenses: [Expense] { if let filterAtt = filterAttribute, let sortAtt = sortAttribute { return expensePeriod.filterAndSortExpensesBy(filter: filterAtt, fromValue: ascendingValue, toValue: descendingValue, option: sortAtt, ascending: ascending) } else if let filterAtt = filterAttribute { return expensePeriod.filterExpensesBy(filter: filterAtt, fromValue: ascendingValue, toValue: descendingValue) } else if let sortAtt = sortAttribute { return expensePeriod.sortExpensesBy(option: sortAtt, ascending: ascending) } else { return expensePeriod.expenses } } var sortAttribute: ExpensePeriodSortOption? var ascending = true var filterAttribute: ExpensePeriodFilterOption? var ascendingValue: Any? var descendingValue: Any? //MARK: Initializers init(expensePeriod: ExpensePeriod, cellIdentifier: String) { self.expensePeriod = expensePeriod self.cellIdentifier = cellIdentifier } //MARK: Tableview datasource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return expenses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let expenseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? ExpenseCell else { return UITableViewCell() } let expense = expenses[indexPath.row] let expenseCellModel = ExpenseCellModel(expense: expense) expenseCell.model = expenseCellModel return expenseCell } }
apache-2.0
c95191337147f91077914c489486a2f9
30.147059
167
0.675165
5.203931
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/URLBarView.swift
1
24956
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit import XCGLogger private let log = Logger.browserLogger struct URLBarViewUX { static let TextFieldContentInset = UIOffsetMake(9, 5) static let LocationLeftPadding = 5 static let LocationHeight = 34 static let LocationInset = 5 static let LocationContentOffset: CGFloat = 8 static let TextFieldCornerRadius: CGFloat = 6 static let TextFieldBorderWidth: CGFloat = 0 // offset from edge of tabs button static let URLBarCurveOffset: CGFloat = 46 static let URLBarCurveOffsetLeft: CGFloat = -10 // buffer so we dont see edges when animation overshoots with spring static let URLBarCurveBounceBuffer: CGFloat = 8 static let ProgressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1) static let TabsButtonRotationOffset: CGFloat = 1.5 static let TabsButtonHeight: CGFloat = 18.0 static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.tintColor = UIConstants.PrivateModePurple theme.textColor = .white theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor theme.backgroundColor = BraveUX.LocationContainerBackgroundColor_PrivateMode themes[Theme.PrivateMode] = theme theme = Theme() theme.tintColor = URLBarViewUX.ProgressTintColor theme.textColor = BraveUX.LocationBarTextColor theme.buttonTintColor = BraveUX.ActionButtonTintColor theme.backgroundColor = BraveUX.LocationContainerBackgroundColor themes[Theme.NormalMode] = theme return themes }() static func backgroundColorWithAlpha(_ alpha: CGFloat) -> UIColor { return UIConstants.AppBackgroundColor.withAlphaComponent(alpha) } } protocol URLBarDelegate: class { func urlBarDidPressTabs(_ urlBar: URLBarView) func urlBarDidPressReaderMode(_ urlBar: URLBarView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool func urlBarDidPressStop(_ urlBar: URLBarView) func urlBarDidPressReload(_ urlBar: URLBarView) func urlBarDidEnterSearchMode(_ urlBar: URLBarView) func urlBarDidLeaveSearchMode(_ urlBar: URLBarView) func urlBarDidLongPressLocation(_ urlBar: URLBarView) func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? func urlBarDidPressScrollToTop(_ urlBar: URLBarView) func urlBar(_ urlBar: URLBarView, didEnterText text: String) func urlBar(_ urlBar: URLBarView, didSubmitText text: String) func urlBarDisplayTextForURL(_ url: URL?) -> String? } class URLBarView: UIView { weak var delegate: URLBarDelegate? weak var browserToolbarDelegate: BrowserToolbarDelegate? var helper: BrowserToolbarHelper? var isTransitioning: Bool = false { didSet { if isTransitioning { } } } fileprivate var currentTheme: String = Theme.NormalMode var bottomToolbarIsHidden = false var locationTextField: ToolbarTextField? /// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown, /// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode /// is *not* tied to the location text field's editing state; for instance, when selecting /// a panel, the first responder will be resigned, yet the overlay mode UI is still active. var inSearchMode = false lazy var locationView: BrowserLocationView = { let locationView = BrowserLocationView() locationView.translatesAutoresizingMaskIntoConstraints = false locationView.readerModeState = ReaderModeState.Unavailable locationView.delegate = self return locationView }() lazy var locationContainer: UIView = { let locationContainer = UIView() locationContainer.translatesAutoresizingMaskIntoConstraints = false // Enable clipping to apply the rounded edges to subviews. locationContainer.clipsToBounds = true locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth return locationContainer }() lazy var tabsButton: TabsButton = { let tabsButton = TabsButton() tabsButton.titleLabel.text = "0" tabsButton.addTarget(self, action: #selector(URLBarView.SELdidClickAddTab), for: UIControlEvents.touchUpInside) tabsButton.accessibilityIdentifier = "URLBarView.tabsButton" tabsButton.accessibilityLabel = Strings.Show_Tabs return tabsButton }() lazy var cancelButton: UIButton = { let cancelButton = InsetButton() cancelButton.setTitleColor(BraveUX.GreyG, for: .normal) let cancelTitle = Strings.Cancel cancelButton.setTitle(cancelTitle, for: UIControlState.normal) cancelButton.titleLabel?.font = UIConstants.DefaultChromeFont cancelButton.addTarget(self, action: #selector(URLBarView.SELdidClickCancel), for: UIControlEvents.touchUpInside) cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12) cancelButton.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: UILayoutConstraintAxis.horizontal) cancelButton.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: UILayoutConstraintAxis.horizontal) cancelButton.alpha = 0 return cancelButton }() lazy var scrollToTopButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(URLBarView.SELtappedScrollToTopArea), for: UIControlEvents.touchUpInside) return button }() // TODO: After protocol removal, check what is necessary here lazy var shareButton: UIButton = { return UIButton() }() lazy var pwdMgrButton: UIButton = { return UIButton() }() lazy var forwardButton: UIButton = { return UIButton() }() lazy var backButton: UIButton = { return UIButton() }() // Required solely for protocol conforming lazy var addTabButton = { return UIButton() }() var actionButtons: [UIButton] { return [self.shareButton, self.forwardButton, self.backButton, self.pwdMgrButton, self.addTabButton] } // Used to temporarily store the cloned button so we can respond to layout changes during animation fileprivate weak var clonedTabsButton: TabsButton? fileprivate var rightBarConstraint: Constraint? fileprivate let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer var currentURL: URL? { get { return locationView.url } set(newURL) { locationView.url = newURL } } func updateTabsBarShowing() {} override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { backgroundColor = BraveUX.ToolbarsBackgroundSolidColor addSubview(scrollToTopButton) addSubview(tabsButton) addSubview(cancelButton) addSubview(shareButton) addSubview(pwdMgrButton) addSubview(forwardButton) addSubview(backButton) locationContainer.addSubview(locationView) addSubview(locationContainer) helper = BrowserToolbarHelper(toolbar: self) setupConstraints() // Make sure we hide any views that shouldn't be showing in non-overlay mode. updateViewsForSearchModeAndToolbarChanges() } func setupConstraints() {} override func updateConstraints() { super.updateConstraints() } func createLocationTextField() { guard locationTextField == nil else { return } locationTextField = ToolbarTextField() guard let locationTextField = locationTextField else { return } locationTextField.translatesAutoresizingMaskIntoConstraints = false locationTextField.autocompleteDelegate = self locationTextField.keyboardType = UIKeyboardType.webSearch locationTextField.keyboardAppearance = .dark locationTextField.autocorrectionType = UITextAutocorrectionType.no locationTextField.autocapitalizationType = UITextAutocapitalizationType.none locationTextField.returnKeyType = UIReturnKeyType.go locationTextField.clearButtonMode = UITextFieldViewMode.whileEditing locationTextField.font = UIConstants.DefaultChromeFont locationTextField.accessibilityIdentifier = "address" locationTextField.accessibilityLabel = Strings.Address_and_Search locationTextField.attributedPlaceholder = NSAttributedString(string: self.locationView.placeholder.string, attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray]) locationContainer.addSubview(locationTextField) locationTextField.snp.makeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } locationTextField.applyTheme(currentTheme) } func removeLocationTextField() { locationTextField?.removeFromSuperview() locationTextField = nil } // Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without // However, switching views dynamically at runtime is a difficult. For now, we just use one view // that can show in either mode. func hideBottomToolbar(_ isHidden: Bool) { bottomToolbarIsHidden = isHidden setNeedsUpdateConstraints() // when we transition from portrait to landscape, calling this here causes // the constraints to be calculated too early and there are constraint errors if !bottomToolbarIsHidden { updateConstraintsIfNeeded() } updateViewsForSearchModeAndToolbarChanges() } func updateAlphaForSubviews(_ alpha: CGFloat) { self.tabsButton.alpha = alpha self.locationContainer.alpha = alpha self.actionButtons.forEach { $0.alpha = alpha } } func updateTabCount(_ count: Int, animated: Bool = true) { URLBarView.updateTabCount(tabsButton, clonedTabsButton: &clonedTabsButton, count: count, animated: animated) } class func updateTabCount(_ tabsButton: TabsButton, clonedTabsButton: inout TabsButton?, count: Int, animated: Bool = true) { let newCount = "\(getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.count)" tabsButton.accessibilityValue = newCount tabsButton.titleLabel.text = newCount } func updateProgressBar(_ progress: Float, dueToTabChange: Bool = false) { return // use Brave override only } func updateReaderModeState(_ state: ReaderModeState) { locationView.readerModeState = state // Brave uses custom reader mode toolbar attached to the bottom of URL bar, // after each reader mode change the toolbar needs to be toggled (self as! BraveURLBarView).readerModeToolbar.isHidden = state != .Active } func setAutocompleteSuggestion(_ suggestion: String?) { locationTextField?.setAutocompleteSuggestion(suggestion) } func enterSearchMode(_ locationText: String?, pasted: Bool) { createLocationTextField() // Show the overlay mode UI, which includes hiding the locationView and replacing it // with the editable locationTextField. animateToSearchState(searchMode: true) delegate?.urlBarDidEnterSearchMode(self) // Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens // won't take the initial frame of the label into consideration, which makes the label // look squished at the start of the animation and expand to be correct. As a workaround, // we becomeFirstResponder as the next event on UI thread, so the animation starts before we // set a first responder. if pasted { // Clear any existing text, focus the field, then set the actual pasted text. // This avoids highlighting all of the text. self.locationTextField?.text = "" DispatchQueue.main.async { self.locationTextField?.becomeFirstResponder() self.locationTextField?.text = locationText } } else { // Copy the current URL to the editable text field, then activate it. self.locationTextField?.text = locationText // something is resigning the first responder immediately after setting it. A short delay for events to process fixes it. postAsyncToMain(0.1) { self.locationTextField?.becomeFirstResponder() } } } func leaveSearchMode(didCancel cancel: Bool = false) { locationTextField?.resignFirstResponder() animateToSearchState(searchMode: false, didCancel: cancel) delegate?.urlBarDidLeaveSearchMode(self) } func prepareSearchAnimation() { // Make sure everything is showing during the transition (we'll hide it afterwards). self.bringSubview(toFront: self.locationContainer) self.cancelButton.isHidden = false self.shareButton.isHidden = !self.bottomToolbarIsHidden self.forwardButton.isHidden = !self.bottomToolbarIsHidden self.backButton.isHidden = !self.bottomToolbarIsHidden } func transitionToSearch(_ didCancel: Bool = false) { self.cancelButton.alpha = inSearchMode ? 1 : 0 self.shareButton.alpha = inSearchMode ? 0 : 1 self.forwardButton.alpha = inSearchMode ? 0 : 1 self.backButton.alpha = inSearchMode ? 0 : 1 if inSearchMode { self.cancelButton.transform = CGAffineTransform.identity let tabsButtonTransform = CGAffineTransform(translationX: self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, y: 0) self.tabsButton.transform = tabsButtonTransform self.clonedTabsButton?.transform = tabsButtonTransform self.rightBarConstraint?.update(offset: URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width) // Make the editable text field span the entire URL bar, covering the lock and reader icons. self.locationTextField?.snp.remakeConstraints { make in make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset) make.top.bottom.trailing.equalTo(self.locationContainer) } } else { self.tabsButton.transform = CGAffineTransform.identity self.clonedTabsButton?.transform = CGAffineTransform.identity self.cancelButton.transform = CGAffineTransform(translationX: self.cancelButton.frame.width, y: 0) self.rightBarConstraint?.update(offset: defaultRightOffset) // Shrink the editable text field back to the size of the location view before hiding it. self.locationTextField?.snp.remakeConstraints { make in make.edges.equalTo(self.locationView.urlTextField) } } } func updateViewsForSearchModeAndToolbarChanges() { self.cancelButton.isHidden = !inSearchMode self.shareButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode self.forwardButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode self.backButton.isHidden = !self.bottomToolbarIsHidden || inSearchMode } func animateToSearchState(searchMode search: Bool, didCancel cancel: Bool = false) { prepareSearchAnimation() layoutIfNeeded() inSearchMode = search if !search { removeLocationTextField() } UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { self.transitionToSearch(cancel) self.setNeedsUpdateConstraints() self.layoutIfNeeded() }, completion: { _ in self.updateViewsForSearchModeAndToolbarChanges() }) } @objc func SELdidClickAddTab() { delegate?.urlBarDidPressTabs(self) } @objc func SELdidClickCancel() { leaveSearchMode(didCancel: true) } @objc func SELtappedScrollToTopArea() { delegate?.urlBarDidPressScrollToTop(self) } } extension URLBarView: BrowserToolbarProtocol { func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } @objc func updateBookmarkStatus(_ isBookmarked: Bool) { getApp().braveTopViewController.updateBookmarkStatus(isBookmarked) } func updateReloadStatus(_ isLoading: Bool) { locationView.stopReloadButtonIsLoading(isLoading) } func updatePageStatus(_ isWebPage: Bool) { locationView.stopReloadButton.isEnabled = isWebPage shareButton.isEnabled = isWebPage } override var accessibilityElements: [Any]? { get { if inSearchMode { guard let locationTextField = locationTextField else { return nil } return [locationTextField, cancelButton] } else { if bottomToolbarIsHidden { return [backButton, forwardButton, locationView, shareButton, tabsButton] } else { return [locationView, tabsButton] } } } set { super.accessibilityElements = newValue } } } extension URLBarView: BrowserLocationViewDelegate { func browserLocationViewDidLongPressReaderMode(_ browserLocationView: BrowserLocationView) -> Bool { return delegate?.urlBarDidLongPressReaderMode(self) ?? false } func browserLocationViewDidTapLocation(_ browserLocationView: BrowserLocationView) { let locationText = delegate?.urlBarDisplayTextForURL(locationView.url) enterSearchMode(locationText, pasted: false) } func browserLocationViewDidLongPressLocation(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidLongPressLocation(self) } func browserLocationViewDidTapReload(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReload(self) } func browserLocationViewDidTapStop(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressStop(self) } func browserLocationViewDidTapReaderMode(_ browserLocationView: BrowserLocationView) { delegate?.urlBarDidPressReaderMode(self) } func browserLocationViewLocationAccessibilityActions(_ browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? { return delegate?.urlBarLocationAccessibilityActions(self) } } extension URLBarView: AutocompleteTextFieldDelegate { func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool { guard let text = locationTextField?.text else { return true } delegate?.urlBar(self, didSubmitText: text) return true } func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) { delegate?.urlBar(self, didEnterText: text) } func autocompleteTextFieldDidBeginEditing(_ autocompleteTextField: AutocompleteTextField) { autocompleteTextField.highlightAll() } func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool { delegate?.urlBar(self, didEnterText: "") return true } } // MARK: UIAppearance extension URLBarView { @objc dynamic var cancelTextColor: UIColor? { get { return cancelButton.titleColor(for: .normal) } set { return cancelButton.setTitleColor(newValue, for: .normal) } } @objc dynamic var actionButtonTintColor: UIColor? { get { return helper?.buttonTintColor } set { guard let value = newValue else { return } helper?.buttonTintColor = value } } } extension URLBarView: Themeable { func applyTheme(_ themeName: String) { locationView.applyTheme(themeName) locationTextField?.applyTheme(themeName) guard let theme = URLBarViewUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } currentTheme = themeName cancelTextColor = theme.textColor actionButtonTintColor = theme.buttonTintColor locationContainer.backgroundColor = theme.backgroundColor tabsButton.applyTheme(themeName) } } /* Code for drawing the urlbar curve */ class CurveView: UIView {} class ToolbarTextField: AutocompleteTextField { static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.backgroundColor = BraveUX.LocationBarEditModeBackgroundColor_Private theme.textColor = BraveUX.LocationBarEditModeTextColor_Private theme.buttonTintColor = UIColor.white theme.highlightColor = UIConstants.PrivateModeTextHighlightColor themes[Theme.PrivateMode] = theme theme = Theme() theme.backgroundColor = BraveUX.LocationBarEditModeBackgroundColor theme.textColor = BraveUX.LocationBarEditModeTextColor theme.highlightColor = AutocompleteTextFieldUX.HighlightColor themes[Theme.NormalMode] = theme return themes }() @objc dynamic var clearButtonTintColor: UIColor? { didSet { // Clear previous tinted image that's cache and ask for a relayout tintedClearImage = nil setNeedsLayout() } } fileprivate var tintedClearImage: UIImage? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // Since we're unable to change the tint color of the clear image, we need to iterate through the // subviews, find the clear button, and tint it ourselves. Thanks to Mikael Hellman for the tip: // http://stackoverflow.com/questions/27944781/how-to-change-the-tint-color-of-the-clear-button-on-a-uitextfield for view in subviews as [UIView] { if let button = view as? UIButton { if let image = button.image(for: .normal) { if tintedClearImage == nil { tintedClearImage = tintImage(image, color: clearButtonTintColor) } if button.imageView?.image != tintedClearImage { button.setImage(tintedClearImage, for: .normal) } } } } } fileprivate func tintImage(_ image: UIImage, color: UIColor?) -> UIImage { guard let color = color else { return image } let size = image.size UIGraphicsBeginImageContextWithOptions(size, false, 2) let context = UIGraphicsGetCurrentContext() image.draw(at: CGPoint.zero, blendMode: CGBlendMode.normal, alpha: 1.0) context!.setFillColor(color.cgColor) context!.setBlendMode(CGBlendMode.sourceIn) context!.setAlpha(1.0) let rect = CGRect( x: CGPoint.zero.x, y: CGPoint.zero.y, width: image.size.width, height: image.size.height) UIGraphicsGetCurrentContext()!.fill(rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage! } } extension ToolbarTextField: Themeable { func applyTheme(_ themeName: String) { guard let theme = ToolbarTextField.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } backgroundColor = theme.backgroundColor textColor = theme.textColor clearButtonTintColor = theme.buttonTintColor highlightColor = theme.highlightColor! } }
mpl-2.0
a595e3278aa31264a807b99c58174e7e
37.453005
181
0.688852
5.754208
false
false
false
false
brave/browser-ios
brave/src/frontend/PicklistSetting.swift
1
5359
/* 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 Shared protocol PicklistSettingOptionsViewDelegate { func picklistSetting(_ setting: PicklistSettingOptionsView, pickedOptionId: Int) } class PicklistSettingOptionsView: UITableViewController { var options = [(displayName: String, id: Int)]() var headerTitle = "" var delegate: PicklistSettingOptionsViewDelegate? var initialIndex = -1 var footerMessage = "" convenience init(options: [(displayName: String, id: Int)], title: String, current: Int, footerMessage: String) { self.init(style: UITableViewStyle.grouped) self.options = options self.headerTitle = title self.initialIndex = current self.footerMessage = footerMessage } override init(style: UITableViewStyle) { super.init(style: style) } // Here due to 8.x bug: https://openradar.appspot.com/23709930 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.textLabel?.text = options[indexPath.row].displayName // cell.tag = options[indexPath.row].uniqueId --> if we want to decouple row order from option order in future if initialIndex == indexPath.row { cell.accessoryType = .checkmark } return cell } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return footerMessage } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return headerTitle } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { navigationController?.popViewController(animated: true) delegate?.picklistSetting(self, pickedOptionId: options[indexPath.row].id) return nil } // Don't show delete button on the left. override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.none } // Don't reserve space for the delete button on the left. override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } } //typealias PicklistSettingChoice = (displayName: String, internalObject: AnyObject, optionId: Int) struct Choice<T> { let item: (Void) -> (displayName: String, object: T, optionId: Int) } class PicklistSettingMainItem<T>: Setting, PicklistSettingOptionsViewDelegate { let profile: Profile let prefName: String let displayName: String let options: [Choice<T>] var picklistFooterMessage = "" override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { let currentId = getCurrent() let option = lookupOptionById(Int(currentId)) return NSAttributedString(string: option?.item(()).displayName ?? "", attributes: [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13)]) } func lookupOptionById(_ id: Int) -> Choice<T>? { for option in options { if option.item(()).optionId == id { return option } } return nil } func getCurrent() -> Int { return Int(BraveApp.getPrefs()?.intForKey(prefName) ?? 0) } init(profile: Profile, displayName: String, prefName: String, options: [Choice<T>]) { self.profile = profile self.displayName = displayName self.prefName = prefName self.options = options super.init(title: NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.foregroundColor: UIConstants.TableViewRowTextColor])) } var picklist: PicklistSettingOptionsView? // on iOS8 there is a crash, seems like it requires this to be retained override func onClick(_ navigationController: UINavigationController?) { picklist = PicklistSettingOptionsView(options: options.map { ($0.item(()).displayName, $0.item(()).optionId) }, title: displayName, current: getCurrent(), footerMessage: picklistFooterMessage) navigationController?.pushViewController(picklist!, animated: true) picklist!.delegate = self } func picklistSetting(_ setting: PicklistSettingOptionsView, pickedOptionId: Int) { profile.prefs.setInt(Int32(pickedOptionId), forKey: prefName) } }
mpl-2.0
06d4b8a44a0d28f8019c4f38f8a9b642
39.598485
201
0.696025
5.065217
false
false
false
false
gvzq/iOS-Twitter
Twitter/ComposeViewController.swift
1
4048
// // ComposeViewController.swift // Twitter // // Created by Gerardo Vazquez on 2/23/16. // Copyright © 2016 Gerardo Vazquez. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var charsLeftLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.barTintColor = UIColor(red: 0.5, green: 0.8, blue: 1.0, alpha: 1.0) self.navigationController!.navigationBar.tintColor = UIColor.whiteColor() self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] textView.delegate = self if (textView.text == "") { textViewDidEndEditing(textView) } let tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard") self.view.addGestureRecognizer(tapDismiss) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard(){ textView.resignFirstResponder() } func textViewDidEndEditing(textView: UITextView) { if (textView.text == "") { textView.text = "Tweet something!" textView.textColor = UIColor.lightGrayColor() } textView.resignFirstResponder() } func textViewDidBeginEditing(textView: UITextView){ if (textView.textColor == UIColor.lightGrayColor()){ textView.text = "" textView.textColor = UIColor.blackColor() } textView.becomeFirstResponder() } func textViewDidChange(textView: UITextView) { checkRemainingCharacters() } func checkRemainingCharacters() { let allowedChars = 140 let charsInTextView = textView.text.characters.count let remainingChars = allowedChars - charsInTextView charsLeftLabel.text = "\(remainingChars)" if remainingChars <= 10 { charsLeftLabel.textColor = UIColor.redColor() } else if remainingChars <= 20 { charsLeftLabel.textColor = UIColor.orangeColor() } else { charsLeftLabel.textColor = UIColor.blackColor() } } @IBAction func onCancelButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onTweetButton(sender: AnyObject) { let allowedChars = 140 let charsInTextView = textView.text.characters.count let remainingChars = allowedChars - charsInTextView if remainingChars < 0 { let alert = UIAlertController(title: "Too many words in this tweet.", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { var message = textView.text!.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) message = message.stringByReplacingOccurrencesOfString("#", withString: "%23", options: NSStringCompareOptions.LiteralSearch, range: nil) message = message.stringByReplacingOccurrencesOfString("'", withString: "%27", options: NSStringCompareOptions.LiteralSearch, range: nil) TwitterClient.sharedInstance.tweet(message) dismissViewControllerAnimated(true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
789c84486304bedabeed9a0eadffed71
37.179245
160
0.664443
5.55144
false
false
false
false
welbesw/BigcommerceApi
Example/BigcommerceApi/EditInvetoryViewController.swift
1
2518
// // EditInvetoryViewController.swift // BigcommerceApi // // Created by William Welbes on 10/1/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import BigcommerceApi class EditInvetoryViewController: UIViewController { @IBOutlet weak var textField:UITextField! var product:BigcommerceProduct! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let inventoryLevel = product.inventoryLevel { self.textField.text = inventoryLevel.stringValue } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapSaveButton() { if let newLevelString = self.textField.text { if let newLevel = Int(newLevelString) { if let productIdString = self.product.productId?.stringValue { if let inventoryTrackingType = InventoryTrackingType(rawValue: self.product.inventoryTracking) { BigcommerceApi.sharedInstance.updateProductInventory(productIdString, trackInventory: inventoryTrackingType, newInventoryLevel: newLevel, newLowLevel: nil, completion: { (error) -> () in DispatchQueue.main.async(execute: { () -> Void in //Handle error if(error == nil) { self.product.inventoryLevel = NSNumber(value: newLevel) self.dismiss(animated: true, completion: nil) } else { print("Error updating inventory level: \(error!.localizedDescription)") } }) }) } } } } } @IBAction func didTapCancelButton() { self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
179f978b11c27e97f9ee2229d03f6900
33.013514
210
0.566945
5.605791
false
false
false
false
appsembler/edx-app-ios
Test/SnapshotTestCase.swift
1
5243
// // SnapshotTestCase // edX // // Created by Akiva Leffert on 5/14/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation private let StandardTolerance : CGFloat = 0.005 protocol SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws var snapshotSize : CGSize { get } } extension UIView : SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfView(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } var snapshotSize : CGSize { return bounds.size } } extension CALayer : SnapshotTestable { func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfLayer(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } var snapshotSize : CGSize { return bounds.size } } extension UIViewController : SnapshotTestable { func prepareForSnapshot() { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = self window.makeKeyAndVisible() } func snapshotTestWithCase(testCase: FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws { try testCase.compareSnapshotOfView(self.view, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance) } func finishSnapshot() { view.window?.removeFromSuperview() } var snapshotSize : CGSize { return view.bounds.size } } class SnapshotTestCase : FBSnapshotTestCase { override func setUp() { super.setUp() // Run "./gradlew recordSnapshots --continue" to regenerate all snapshots #if RECORD_SNAPSHOTS recordMode = true #endif } var screenSize : CGSize { // Standardize on a size so we don't have to worry about different simulators // etc. // Pick a non standard width so we can catch width assumptions. return CGSizeMake(380, 568) } private var majorVersion : Int { return NSProcessInfo.processInfo().operatingSystemVersion.majorVersion } private final func qualifyIdentifier(identifier : String?, content : SnapshotTestable) -> String { let rtl = UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft ? "_rtl" : "" let suffix = "ios\(majorVersion)\(rtl)_\(Int(content.snapshotSize.width))x\(Int(content.snapshotSize.height))" if let identifier = identifier { return identifier + suffix } else { return suffix } } // Asserts that a snapshot matches expectations // This is similar to the objc only FBSnapshotTest macros // But works in swift func assertSnapshotValidWithContent(content : SnapshotTestable, identifier : String? = nil, message : String? = nil, file : StaticString = #file, line : UInt = #line) { let qualifiedIdentifier = qualifyIdentifier(identifier, content : content) do { try content.snapshotTestWithCase(self, referenceImagesDirectory: SNAPSHOT_TEST_DIR, identifier: qualifiedIdentifier) } catch let error as NSError { let unknownError = "Unknown Error" XCTFail("Snapshot comparison failed (\(qualifiedIdentifier)): \(error.localizedDescription ?? unknownError)", file : file, line : line) if let message = message { XCTFail(message, file : file, line : line) } else { XCTFail(file : file, line : line) } } XCTAssertFalse(recordMode, "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file : file, line : line) } func inScreenNavigationContext(controller : UIViewController, @noescape action : () -> ()) { let container = UINavigationController(rootViewController: controller) inScreenDisplayContext(container, action: action) } /// Makes a window and adds the controller to it /// to ensure that our controller actually loads properly /// Otherwise, sometimes viewWillAppear: type methods don't get called func inScreenDisplayContext(controller : UIViewController, @noescape action : () -> ()) { let window = UIWindow(frame: CGRectZero) window.rootViewController = controller window.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height) window.makeKeyAndVisible() controller.view.frame = window.bounds controller.view.updateConstraintsIfNeeded() controller.view.setNeedsLayout() controller.view.layoutIfNeeded() action() window.removeFromSuperview() } }
apache-2.0
63a9bc3ccc3ce21eafd5878f55b53d68
35.929577
180
0.670608
5.438797
false
true
false
false
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-014/Trax MapKit/Trax/ImageViewController.swift
5
3985
// // ImageViewController.swift // Trax // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { // our Model // publicly settable // when it changes (but only if we are on screen) // we'll fetch the image from the imageURL // if we're off screen when this happens (view.window == nil) // viewWillAppear will get it for us later var imageURL: NSURL? { didSet { image = nil if view.window != nil { fetchImage() } } } // fetches the image at imageURL // does so off the main thread // then puts a closure back on the main queue // to handle putting the image in the UI // (since we aren't allowed to do UI anywhere but main queue) private func fetchImage() { if let url = imageURL { spinner?.startAnimating() let qos = Int(QOS_CLASS_USER_INITIATED.value) dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in let imageData = NSData(contentsOfURL: url) // this blocks the thread it is on dispatch_async(dispatch_get_main_queue()) { // only do something with this image // if the url we fetched is the current imageURL we want // (that might have changed while we were off fetching this one) if url == self.imageURL { // the variable "url" is capture from above if imageData != nil { // this might be a waste of time if our MVC is out of action now // which it might be if someone hit the Back button // or otherwise removed us from split view or navigation controller // while we were off fetching the image self.image = UIImage(data: imageData!) } else { self.image = nil } } } } } } @IBOutlet private weak var spinner: UIActivityIndicatorView! @IBOutlet private weak var scrollView: UIScrollView! { didSet { scrollView.contentSize = imageView.frame.size // critical to set this! scrollView.delegate = self // required for zooming scrollView.minimumZoomScale = 0.03 // required for zooming scrollView.maximumZoomScale = 1.0 // required for zooming } } // UIScrollViewDelegate method // required for zooming func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } private var imageView = UIImageView() // convenience computed property // lets us get involved every time we set an image in imageView // we can do things like resize the imageView, // set the scroll view's contentSize, // and stop the spinner private var image: UIImage? { get { return imageView.image } set { imageView.image = newValue imageView.sizeToFit() scrollView?.contentSize = imageView.frame.size spinner?.stopAnimating() } } // put our imageView into the view hierarchy // as a subview of the scrollView // (will install it into the content area of the scroll view) override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(imageView) } // for efficiency, we will only actually fetch the image // when we know we are going to be on screen override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if image == nil { fetchImage() } } }
apache-2.0
0aa1331b8a3527c089edc6a42ef2197e
35.227273
95
0.566123
5.306258
false
false
false
false
heitara/swift-3
playgrounds/Lecture7.playground/Contents.swift
1
8168
//: Playground - noun: a place where people can play import UIKit /* Какво е playground? Това вид проект, който се изпозлва от xCode. Интерактивно показва какво е състоянието на паметта на компютъра във всеки един ред на изпълнение на код-а. Позволява лесно онагледяване на примерния код. Много по-лесно може да се анализира кода. Можем да скицираме проблеми и техните решения, които да използваме за напред. */ //: # Въпроси от лекция №6 //: 1. Какво е ```mutating``` и кога се ползва? //: 2. Какво е read–only пропърти? //: 3. Какво е наследяване? //: 4. Кога можем да използваме запазената дума super? //: 5. Кога изпозлваме ```override```? //: ## След контролното ще разглеждаме проектите и прогреса по тях //: # Лекция 7: Протоколи (Класове и Структури) //: ## курс: Увод в прогрмаирането със Swift //: Наследяване - преговор //: Предефиниране (overriding) //: Достъп до базовите методи, пропъртита и subscript-s, става чрез ```super``` //: - Note: //: В Swift, изпозлваме запазената дума ```override``` за да обозначим, че предефинираме дадена функци, пропърти (get & set). //: Можем да обявим функция или пропърти, че няма да се променят. За целта използваме ```final```. //: Можем да обявим дори и цял клас. ```final class``` - класът няма да може да бъде наследяван. //: Инициализатори (init методи) //: наследяване на инициализаторите инициализатори //: ```required``` инициализатори //: init? инициализатори struct StructBook { var pageCount = 0 var title = "no title" var publishDate:Date? = nil init(title:String) { self.title = title } } extension StructBook { init() { self.init(title: "No title") } } class Book { var pageCount = 0 var title = "no title" var publishDate:Date? = nil convenience init(pages:Int) { self.init() self.pageCount = pages } convenience init(pages:Int, title:String) { self.init(pages:pages) self.title = title } } class TechnicalBook:Book { var isBlackAndWhite = true } class CartoonBook : Book { var isBlackAndWhite = true } extension Book { convenience init(title:String) { self.init() self.title = title } convenience init(pages:Int, title:String, date: Date?) { self.init(pages:pages, title:title) self.publishDate = date } } //var tb = TechnicalBook( //var book = Book() //book.pageCount = 100 var book100 = Book(pages: 100) //var book2 = StructBook(pageCount: 1000, title: "Swift 3", publishDate: nil) //var doc = TechnicalBook( //: ## Протоколи //: Какво са протоколите? //: - Note: //: Протокола е "договор", който всеки тип се съгласява да удволетвори. "Договор", е списък от изисквания, който определят начина по който ще изгледжа даденият тип. //: ### Синтаксис protocol Sellable { var pricePerUnit: Double { get } var isAvailable: Bool { set get } mutating func updatePrice(newPrice: Double) } protocol TechnicalDocumented { //конструктори init(documentation:Book) var technicalDocumentation: Book { get } func getTechnicalDocs() -> Book } protocol Printable { var description: String { get } static var version: String { get set} init() init(a:Int, b:Int) } extension Printable { //default version var description: String { return "No descriprion." } //default version static var version: String { return "v. 1.0" } } //extension Int:Printable { // var description: String { // return "седем" // } // //} //var i = 7 //print(i.description) //пример за клас, който имплементира техникал интерфейс class Machine: Printable { var powerConsumption = 0 var name = "Missing name" //имаме неявен конструкту по подразбиране // var description: String { // return "Machine" // } static var version: String = "v. 2.0" required init() { } required init(a:Int, b:Int) { print("Machine") } } var m = Machine() print(m.description) //struct StructBook2:Printable { // var pageCount = 0 // var title = "no title" // var publishDate:Date? = nil // // var description: String { // return "Structure Book!" // } //} class WashingMachine : Machine, TechnicalDocumented { var technicalDocumentation: Book func getTechnicalDocs() -> Book { return TechnicalBook() } required init() { technicalDocumentation = TechnicalBook() super.init() } required init(documentation: Book) { technicalDocumentation = documentation super.init() } required init(a:Int, b:Int) { technicalDocumentation = TechnicalBook() print("W.Machine") super.init() } // override var description: String { // // return " W Machine" // } // var technicalDocumentation: CartoonBook } protocol PersonalComputer: class { func getRamSize() -> Int /** * Convert X bytes to "KB" or "MB" or "GB" or "TB" **/ static func convert(bytes: Int, to:String) -> Double } class MacBookPro : PersonalComputer { func getRamSize() -> Int { return 1024 } static func convert(bytes: Int, to:String) -> Double { return 0 } } //: ## Задачи: //: ### Да се направи модел на по следното задание: // //Задание 1 // //Да се имплементира мобилно приложение, което //представя информация за времето. Времето да има две представяния //- по целзии, по фаренхайт. Да може да се съставя списък от //градове, който да представя информация за времето в //определените локации. // //Задание 2 // //Да се имплементира мобилно приложение, което //представя списък от снимки, които всеки потребител може да upload-ва. //Всеки потребител да има списък от снимки, които се формира от снимките на всички //потребители, на които е последовател. Всеки да може да стане //последвател на друг потребител, но да може и да се откаже да е последовател. //Под всяка снимка потребителите да могат да коментират. Да я отбелязват като любима. //Или да я споделят с други потребители. Всеки потребител да има списък с //последователи. Да има вход в системата с потребителско име и парола.
mit
90e6f81bbdf1b70cfd69a71d421e1fd1
20.18
320
0.643689
3.084466
false
false
false
false
airbnb/lottie-ios
Example/iOS/Views/AnimatedSwitchRow.swift
2
3379
// Created by Cal Stephens on 1/4/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import Epoxy import Lottie import UIKit // MARK: - AnimatedSwitchRow final class AnimatedSwitchRow: UIView, EpoxyableView { // MARK: Lifecycle init() { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false layoutMargins = UIEdgeInsets(top: 16, left: 24, bottom: 16, right: 24) group.install(in: self) group.constrainToMarginsWithHighPriorityBottom() backgroundColor = .systemBackground } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal struct Content: Equatable { var animationName: String var title: String var onTimeRange: ClosedRange<CGFloat> var offTimeRange: ClosedRange<CGFloat> var colorValueProviders: [String: [Keyframe<LottieColor>]] = [:] } func setContent(_ content: Content, animated _: Bool) { self.content = content updateGroup() } // MARK: Private private enum DataID { case animatedSwitch case title } private var content: Content? private let group = HGroup(alignment: .fill, spacing: 24) private var isEnabled = false { didSet { updateGroup() } } private func updateGroup() { guard let content = content else { return } group.setItems { if let animationName = content.animationName { GroupItem<AnimatedSwitch>( dataID: DataID.animatedSwitch, content: content, make: { let animatedSwitch = AnimatedSwitch() animatedSwitch.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ animatedSwitch.widthAnchor.constraint(equalToConstant: 80), animatedSwitch.heightAnchor.constraint(equalToConstant: 80), ]) animatedSwitch.addTarget(self, action: #selector(self.switchWasToggled), for: .touchUpInside) return animatedSwitch }, setContent: { context, content in context.constrainable.animation = .named(animationName) context.constrainable.contentMode = .scaleAspectFit context.constrainable.setProgressForState( fromProgress: content.offTimeRange.lowerBound, toProgress: content.offTimeRange.upperBound, forOnState: false) context.constrainable.setProgressForState( fromProgress: content.onTimeRange.lowerBound, toProgress: content.onTimeRange.upperBound, forOnState: true) for (keypath, color) in content.colorValueProviders { context.constrainable.animationView.setValueProvider( ColorValueProvider(color), keypath: AnimationKeypath(keypath: keypath)) } }) } GroupItem<UILabel>( dataID: DataID.title, content: isEnabled, make: { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }, setContent: { context, _ in context.constrainable.text = "\(content.title): \(self.isEnabled ? "On" : "Off")" }) } } @objc private func switchWasToggled(_ sender: AnimatedSwitch) { isEnabled = sender.isOn } }
apache-2.0
ace6a2da4c82f34371b674ba11e6f0f5
27.386555
105
0.642096
5.019316
false
false
false
false
andreacremaschi/GEOSwift
GEOSwift/GEOS/GeometryConvertible+GEOS.swift
1
15571
import geos public extension GeometryConvertible { // MARK: - Misc Functions func length() throws -> Double { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var length: Double = 0 // returns 0 on exception guard GEOSLength_r(context.handle, geosObject.pointer, &length) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return length } func distance(to geometry: GeometryConvertible) throws -> Double { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) var dist: Double = 0 // returns 0 on exception guard GEOSDistance_r(context.handle, geosObject.pointer, otherGeosObject.pointer, &dist) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return dist } func area() throws -> Double { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var area: Double = 0 // returns 0 on exception guard GEOSArea_r(context.handle, geosObject.pointer, &area) != 0 else { throw GEOSError.libraryError(errorMessages: context.errors) } return area } func nearestPoints(with geometry: GeometryConvertible) throws -> [Point] { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let coordSeq = GEOSNearestPoints_r( context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSCoordSeq_destroy_r(context.handle, coordSeq) } var point0 = Point(x: 0, y: 0) GEOSCoordSeq_getX_r(context.handle, coordSeq, 0, &point0.x) GEOSCoordSeq_getY_r(context.handle, coordSeq, 0, &point0.y) var point1 = Point(x: 0, y: 0) GEOSCoordSeq_getX_r(context.handle, coordSeq, 1, &point1.x) GEOSCoordSeq_getY_r(context.handle, coordSeq, 1, &point1.y) return [point0, point1] } // MARK: - Unary Predicates internal typealias UnaryPredicate = (GEOSContextHandle_t, OpaquePointer) -> Int8 internal func evaluateUnaryPredicate(_ predicate: UnaryPredicate) throws -> Bool { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = predicate(context.handle, geosObject.pointer) guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func isEmpty() throws -> Bool { try evaluateUnaryPredicate(GEOSisEmpty_r) } func isRing() throws -> Bool { try evaluateUnaryPredicate(GEOSisRing_r) } func isValid() throws -> Bool { try evaluateUnaryPredicate(GEOSisValid_r) } func isValidReason() throws -> String { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) guard let cString = GEOSisValidReason_r(context.handle, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSFree_r(context.handle, cString) } return String(cString: cString) } func isValidDetail(allowSelfTouchingRingFormingHole: Bool = false) throws -> IsValidDetailResult { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let flags: Int32 = allowSelfTouchingRingFormingHole ? Int32(GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE.rawValue) : 0 var optionalReason: UnsafeMutablePointer<Int8>? var optionalLocation: OpaquePointer? switch GEOSisValidDetail_r( context.handle, geosObject.pointer, flags, &optionalReason, &optionalLocation) { case 1: // Valid if let reason = optionalReason { GEOSFree_r(context.handle, reason) } if let location = optionalLocation { GEOSGeom_destroy_r(context.handle, location) } return .valid case 0: // Invalid let reason = optionalReason.map { (reason) -> String in defer { GEOSFree_r(context.handle, reason) } return String(cString: reason) } let location = try optionalLocation.map { (location) -> Geometry in let locationGEOSObject = GEOSObject(context: context, pointer: location) return try Geometry(geosObject: locationGEOSObject) } return .invalid(reason: reason, location: location) default: // Error throw GEOSError.libraryError(errorMessages: context.errors) } } // MARK: - Binary Predicates private typealias BinaryPredicate = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> Int8 private func evaluateBinaryPredicate(_ predicate: BinaryPredicate, with geometry: GeometryConvertible) throws -> Bool { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = predicate(context.handle, geosObject.pointer, otherGeosObject.pointer) guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func isTopologicallyEquivalent(to geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSEquals_r, with: geometry) } func isDisjoint(with geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSDisjoint_r, with: geometry) } func touches(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSTouches_r, with: geometry) } func intersects(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSIntersects_r, with: geometry) } func crosses(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCrosses_r, with: geometry) } func isWithin(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSWithin_r, with: geometry) } func contains(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSContains_r, with: geometry) } func overlaps(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSOverlaps_r, with: geometry) } func covers(_ geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCovers_r, with: geometry) } func isCovered(by geometry: GeometryConvertible) throws -> Bool { try evaluateBinaryPredicate(GEOSCoveredBy_r, with: geometry) } // MARK: - Dimensionally Extended 9 Intersection Model Functions /// Parameter mask: A DE9-IM mask pattern func relate(_ geometry: GeometryConvertible, mask: String) throws -> Bool { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) // returns 2 on exception, 1 on true, 0 on false let result = mask.withCString { GEOSRelatePattern_r(context.handle, geosObject.pointer, otherGeosObject.pointer, $0) } guard result != 2 else { throw GEOSError.libraryError(errorMessages: context.errors) } return result == 1 } func relate(_ geometry: GeometryConvertible) throws -> String { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let cString = GEOSRelate_r(context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { GEOSFree_r(context.handle, cString) } return String(cString: cString) } // MARK: - Topology Operations internal typealias UnaryOperation = (GEOSContextHandle_t, OpaquePointer) -> OpaquePointer? internal func performUnaryTopologyOperation<T>(_ operation: UnaryOperation) throws -> T where T: GEOSObjectInitializable { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) guard let pointer = operation(context.handle, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try T(geosObject: GEOSObject(context: context, pointer: pointer)) } private typealias BinaryOperation = (GEOSContextHandle_t, OpaquePointer, OpaquePointer) -> OpaquePointer? private func performBinaryTopologyOperation(_ operation: BinaryOperation, geometry: GeometryConvertible) throws -> Geometry { let context = try GEOSContext() let geosObject = try self.geometry.geosObject(with: context) let otherGeosObject = try geometry.geometry.geosObject(with: context) guard let pointer = operation(context.handle, geosObject.pointer, otherGeosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: GEOSObject(context: context, pointer: pointer)) } func envelope() throws -> Envelope { let geometry: Geometry = try performUnaryTopologyOperation(GEOSEnvelope_r) switch geometry { case let .point(point): return Envelope(minX: point.x, maxX: point.x, minY: point.y, maxY: point.y) case let .polygon(polygon): var minX = Double.nan var maxX = Double.nan var minY = Double.nan var maxY = Double.nan for point in polygon.exterior.points { minX = .minimum(minX, point.x) maxX = .maximum(maxX, point.x) minY = .minimum(minY, point.y) maxY = .maximum(maxY, point.y) } return Envelope(minX: minX, maxX: maxX, minY: minY, maxY: maxY) default: throw GEOSwiftError.unexpectedEnvelopeResult(geometry) } } func intersection(with geometry: GeometryConvertible) throws -> Geometry? { do { return try performBinaryTopologyOperation(GEOSIntersection_r, geometry: geometry) } catch GEOSwiftError.tooFewPoints { return nil } catch { throw error } } func makeValid() throws -> Geometry { try performUnaryTopologyOperation(GEOSMakeValid_r) } func normalized() throws -> Geometry { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // GEOSNormalize_r returns -1 on exception guard GEOSNormalize_r(context.handle, geosObject.pointer) != -1 else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: geosObject) } func convexHull() throws -> Geometry { try performUnaryTopologyOperation(GEOSConvexHull_r) } func minimumRotatedRectangle() throws -> Geometry { try performUnaryTopologyOperation(GEOSMinimumRotatedRectangle_r) } func minimumWidth() throws -> LineString { try performUnaryTopologyOperation(GEOSMinimumWidth_r) } func difference(with geometry: GeometryConvertible) throws -> Geometry? { do { return try performBinaryTopologyOperation(GEOSDifference_r, geometry: geometry) } catch GEOSwiftError.tooFewPoints { return nil } catch { throw error } } func union(with geometry: GeometryConvertible) throws -> Geometry { try performBinaryTopologyOperation(GEOSUnion_r, geometry: geometry) } func unaryUnion() throws -> Geometry { try performUnaryTopologyOperation(GEOSUnaryUnion_r) } func pointOnSurface() throws -> Point { try performUnaryTopologyOperation(GEOSPointOnSurface_r) } func centroid() throws -> Point { try performUnaryTopologyOperation(GEOSGetCentroid_r) } func minimumBoundingCircle() throws -> Circle { let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) var radius: Double = 0 var optionalCenterPointer: OpaquePointer? guard let geometryPointer = GEOSMinimumBoundingCircle_r( context.handle, geosObject.pointer, &radius, &optionalCenterPointer) else { // if we somehow end up with a non-null center and a null geometry, // we must still destroy the center before throwing an error if let centerPointer = optionalCenterPointer { GEOSGeom_destroy_r(context.handle, centerPointer) } throw GEOSError.libraryError(errorMessages: context.errors) } // For our purposes, we only care about the center and radius. GEOSGeom_destroy_r(context.handle, geometryPointer) guard let centerPointer = optionalCenterPointer else { throw GEOSError.noMinimumBoundingCircle } let center = try Point(geosObject: GEOSObject(context: context, pointer: centerPointer)) return Circle(center: center, radius: radius) } func polygonize() throws -> GeometryCollection { try [self].polygonize() } // MARK: - Buffer Functions func buffer(by width: Double) throws -> Geometry { guard width >= 0 else { throw GEOSwiftError.negativeBufferWidth } let context = try GEOSContext() let geosObject = try geometry.geosObject(with: context) // returns nil on exception guard let resultPointer = GEOSBuffer_r(context.handle, geosObject.pointer, width, 0) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try Geometry(geosObject: GEOSObject(context: context, pointer: resultPointer)) } } public extension Collection where Element: GeometryConvertible { func polygonize() throws -> GeometryCollection { let context = try GEOSContext() let geosObjects = try map { try $0.geometry.geosObject(with: context) } guard let pointer = GEOSPolygonize_r( context.handle, geosObjects.map { $0.pointer }, UInt32(geosObjects.count)) else { throw GEOSError.libraryError(errorMessages: context.errors) } return try GeometryCollection(geosObject: GEOSObject(context: context, pointer: pointer)) } } public enum IsValidDetailResult: Equatable { case valid case invalid(reason: String?, location: Geometry?) }
mit
5568f3ada7f4748ab832f283f1355610
39.444156
109
0.650504
4.941606
false
false
false
false
rebeloper/SwiftyPlistManager
SwiftyPlistManager/ViewController.swift
1
22312
/** MIT License Copyright (c) 2017 Alex Nagy 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 //////////////////////////////////////////////////////////////////////////////////// // // For a detailed tutorial with images visit: // // http://rebeloper.com/read-write-plist-file-swift/ // //////////////////////////////////////////////////////////////////////////////////// // First of all drag and drop these 2 helper files into your project: // MyData.plist // MySecondPlist.plist // //////////////////////////////////////////////////////////////////////////////////// // // INSTALATION: // // I. CocoaPods: // // 1. run in Terminal on the root of your project: pod init // 2. add to your Podfile: pod 'SwiftyPlistManager' // 3. run in Terminal on the root of your project: pod install // 4. import SwiftyPlistManager by commenting out the line below //import SwiftyPlistManager // or II. Manualy: // // Drag and drop SwiftyPlistManager.swift into your project //////////////////////////////////////////////////////////////////////////////////// class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //////////////////////////////////////////////////////////////////////////////////// // Now let's start coding! // It is always a good practice to make our keys typo-proof // Comment out the lines below by deleting the '/*' and '*/' // For now don't worry about Xcode complaining about them /* let dataPlistName = "Data" let otherDataPlistName = "OtherData" let nonExistentPlistName = "NonExistent" let newKey = "newKey" let firstKey = "firstKey" let secondKey = "secondKey" let thirdKey = "thirdKey" let fourthKey = "fourthKey" let nonExistentKey = "nonExistentKey" let helloNewValue = "Hello New Value" let rebeloperValue = "Rebeloper" let intValue = 17 let boolValue = true let anotherIntValue = 28 let stringValue = "Alex" var dict = ["name": "John", "age": 34] as [String : Any]*/ //////////////////////////////////////////////////////////////////////////////////// // Now go to 'Data.plist' and add a new item with this key: 'newKey' and with // a String value: 'Hello SwiftyPlistManager' // // IMPORTANT: You always have to "start" SwiftyPlistManager on every launch of your app. // Add the next line of code to your 'application(_:didFinishLaunchingWithOptions:)' function // in AppDelegate.swift // // For the sake of this tutorial let's just add it here. This is fine too, as long as it is fired on every launch. // // Set 'logging' to 'true' if you want to log what's going on under the hood. Optionaly set it to 'false' // before release or when you are fed up with too much text in the console. //SwiftyPlistManager.shared.start(plistNames: [dataPlistName], logging: true) // Bulid & Run. Stop. Never comment back this line of code. // What this did is copy your existing Data.plist file into the app's Documents directory. // From now on the app will interact with this newly created file and NOT with the plist file you see in Xcode. // This is why if you change a value (or add a new item) to your plist now (after the first launch) // than changes will not be reflected in the MyData.plist file you see in Xcode. Instead changes // will be saved to the plist file created in the Documents directory. Consider this Data.plist // file (that one you see in Xcode) as a 'starting' file in witch you set up all of your needed // keys with some default values. // // IMPORTANT: After you first launch your app and than add/remove items in the Data.plist file the changes // will not be reflected in the file in the Documents directory. To add more key-value pairs // to your Data.plist file or change the value of any key-value pair do the following steps: // // 1. Add your desired new items to the Data.plist file // 2. Delete your app from the simulator/device // 3. Build & Run the app // // You will always have to repeat these steps if you wish to add new key-value pairs through // the Data.plist file. You can easily skip these steps if you add key-value pair through code. // The downside of this is that you can't actually see or edit the key-value pairs in the file // you see in Xcode. //////////////////////////////////////////////////////////////////////////////////// // You can 'start' as many plist files as you'd like as long as you have them in your project bundle already. // Of course if the plist does not exist SwiftyPlistManger will gently warn you in the log. // Try starting SwiftyPlistManager with these 3 items: "Data", "OtherData" and "NonExistent". // Of course, use the constants that you have set up above. //SwiftyPlistManager.shared.start(plistNames: [dataPlistName, otherDataPlistName, nonExistentPlistName], logging: true) //////////////////////////////////////////////////////////////////////////////////// // Comment the line back again. In this example we will work on the 'Data.plist' file only. //////////////////////////////////////////////////////////////////////////////////// // Let's test if the item with the 'newKey' key exits and print it out in the Log. // SwiftyPlistManager uses completion handlers. You'll get back your 'result' as an Any? object. // For now let's just check if the error is nil. We'll talk about in depth error handling later on. // After adding the call Build and Run your app again. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------------> The Value for Key '\(newKey)' actually exists in the '\(dataPlistName).plist' file. It is: '\(result ?? "No Value Fetched")'") } }*/ // Hurray! Comment back that call. //////////////////////////////////////////////////////////////////////////////////// // Now let's change the value of this item. We want to avoid the cumbersome 3 step process detailed above, // so we are going to do it in code. /* SwiftyPlistManager.shared.save(helloNewValue, forKey: newKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------------> Value '\(helloNewValue)' successfully saved at Key '\(newKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run. Stop. // Note that you don't see any changes in the Data.plist file. This is how it should be, because the app // saved the new value to the file in the Documents directory, remember? So now let's get back the changed // value. Comment out the call below. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result!)'") } }*/ // Build & Run and take a look at the Log. Stop. Comment back the lines from above. // Note that the value you get back is an optional. Retrieveng it with the 'bang operator' (!) is quite risky // because you might get back nil and that would crash your app! My suggestion is to never ever use the // 'bang operator'. It's risky, crash-prone and shouts that you are a lazy, clueless (or both) developer. // There are better ways to write code. For a start let's add a default value. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result ?? "No Value")'") } }*/ // Build & Run and take a look at the Log. Stop. Comment back the lines from above. // At this point the optional value will default to the "No Value" Sting. I personally hate working with default // values because they might pop up and would ruin the user experience of any app. To enhance your code let's // unwrap the 'result' with a guard-let statement. /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { guard let result = result else { print("-------------> The Value for Key '\(newKey)' does not exists.") return } print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result)'") } }*/ // Or you can unwrap it with an if-let statement if you do not wish to return from the completion handler right away /* SwiftyPlistManager.shared.getValue(for: newKey, fromPlistWithName: dataPlistName) { (result, err) in if err == nil { if let result = result { print("-------------> The Value for Key '\(newKey)' actually exists. It is: '\(result)'") } else { print("-------------> The Value for Key '\(newKey)' does not exists.") } print("-------------> This line will be printed out regardless if the Value for Key '\(newKey)' exists or not.") } }*/ // Congratulations! You have learned how and when to use (or not to use) the 'bang operator', 'guard-let statements' // and 'if-let' statements. You now have solid knowledge of how to deal with optionals. // Most of the times you want to cast your result into a constant right away and not wait for the // completion handler to finish. You can use the following call to do just that. For this example we'll // unwrap it with a guard-let statement. /* guard let fetchedValue = SwiftyPlistManager.shared.fetchValue(for: newKey, fromPlistWithName: dataPlistName) else { return } print("-------------> The Fetched Value for Key '\(newKey)' actually exists. It is: '\(fetchedValue)'")*/ //////////////////////////////////////////////////////////////////////////////////// // Of course if you try to fetch a value with a non-existent key, 'SwiftyPlistManager' has your back. // It will show a WARNING in the log that the key does not exist AND it will not crash the app. Sweet! /* guard let nonExistentValue = SwiftyPlistManager.shared.fetchValue(for: nonExistentKey, fromPlistWithName: dataPlistName) else { print("-------------> The Value does not exist so going to return now!") return } print("-------------> This line will never be executed because the Key is: '\(nonExistentKey)' so the Value is '\(nonExistentValue)'")*/ //////////////////////////////////////////////////////////////////////////////////// // Now let's take a look at some other awesome powers that come with SwiftyPlistManager. // You can add a new key-value pair like so: /* SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(rebeloperValue)' successfully added at Key '\(firstKey)' into '\(dataPlistName).plist'") } }*/ // Now Build & Run your project... Congratulations! You have just created and saved your first // key-value pair into your plist file. Stop the project from running. //////////////////////////////////////////////////////////////////////////////////// // Now add a next value with an Int /* SwiftyPlistManager.shared.addNew(intValue, key: secondKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(intValue)' successfully added at Key '\(secondKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run again. Take a look at your progress in the Log. Stop. //////////////////////////////////////////////////////////////////////////////////// // And finally add an item that has a Bool value /* SwiftyPlistManager.shared.addNew(boolValue, key: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(boolValue)' successfully added at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ // Build & Run again. Take a look at your progress in the Log. Notice that 'true' is represented // with a '1' and 'false' is represented with a '0'. Stop your project from running. // As in real life examples you just can't comment out these 3 calls after the first launch of the // app, but you don't have to. 'SwiftyPlistManager' takes care of not creating a new item for the same key. // Do not comment out this last call and Build & Run again. Take a look at the Log. //////////////////////////////////////////////////////////////////////////////////// // Remember, you don't have to add your items through code at all. // You can add them into the Data.plist file; it's much easier, but it has a downside: // Once you run and test your code for the first time you cannot add or delete any entries using the plist file. // Changes made will not be reflected. You will have to delete your app from the simulator, // Clean your project (Product/Clean) and Build & Run again to see your changes. However adding/saving/deleting will // work when done in code. //////////////////////////////////////////////////////////////////////////////////// // Great! So now you know that 'adding' a new key-value pair is not the same as 'updating'/'saving a new value' // for a key. Let's do that now. // Change and at the same time Save the second key's value to '28' (anotherIntValue) /* SwiftyPlistManager.shared.save(anotherIntValue, forKey: secondKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(anotherIntValue)' successfully saved at Key '\(secondKey)' into '\(dataPlistName).plist'") } }*/ // Of course, Build & Run again. And after you take a look at your progress. Stop. // And comment back the line. From now on do it on every new task. :) // Awesome! //////////////////////////////////////////////////////////////////////////////////// // 'SwiftyPlistManager' is Semi Type Safe. What this means is that for example if you try to save // a String value for a non-String value, let's say to save 'Alex' (stringValue) for the 'thirdKey' // witch already has a Bool value, than 'SwiftyPlistManager' will give you a Warning but let you // make the save anyway. It is your responsibility that you save the right types of values. Try it out. /* SwiftyPlistManager.shared.save(stringValue, forKey: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(stringValue)' successfully saved at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ //////////////////////////////////////////////////////////////////////////////////// // Better change back the value to a Bool for the Item with key 'thirdKey' before you forget it. /* SwiftyPlistManager.shared.save(boolValue, forKey: thirdKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(boolValue)' successfully saved at Key '\(thirdKey)' into '\(dataPlistName).plist'") } }*/ // The warning will come up this time too, but now you know that it is set back the way you need it. //////////////////////////////////////////////////////////////////////////////////// // Of course, you may add Dictionaries, Arrays, Dates and Data items too. Try it out // by adding a new dictionary. /* SwiftyPlistManager.shared.addNew(dict, key: fourthKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(dict)' successfully saved at Key '\(fourthKey)' into '\(dataPlistName).plist'") } }*/ //////////////////////////////////////////////////////////////////////////////////// // Now just to have some fun with it, change the age of John to 56. /* dict["age"] = 56 SwiftyPlistManager.shared.save(dict, forKey: fourthKey, toPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Value '\(dict)' successfully saved at Key '\(fourthKey)' into '\(dataPlistName).plist'") } }*/ // Well done! Now comment back the calls. //////////////////////////////////////////////////////////////////////////////////// // Once in a while you might want to remove a value-key pair /* SwiftyPlistManager.shared.removeKeyValuePair(for: thirdKey, fromPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Key-Value pair successfully removed at Key '\(thirdKey)' from '\(dataPlistName).plist'") } }*/ // Of course, if this line is executed several times 'SwiftyPlistManager' realises that the item // was already removed and does not exist. Try it out! //////////////////////////////////////////////////////////////////////////////////// // Or you might want to delete all the data from your plist file /* SwiftyPlistManager.shared.removeAllKeyValuePairs(fromPlistWithName: dataPlistName) { (err) in if err == nil { print("-------------> Successfully removed all Key-Value pairs from '\(dataPlistName).plist'") } }*/ // Of course, if this line is executed several times 'SwiftyPlistManager' realises that the plist // is empty and cancels the operation. Try it out. //////////////////////////////////////////////////////////////////////////////////// // Remember: Your plist file is saved and updated inside the application's Documents folder // This is why you will not see any changes at all in the MyData.plist file that you see in the // Xcode project. That file is there as a 'starter' file. Once you start the app and make // the 'startPlistManager()' call a copy is created in the app's Documents folder and from that new file is used // for all your data till you delete your app from simulator/device and Clean (Product/Clean) your project. //////////////////////////////////////////////////////////////////////////////////// // Let's talk about error-handling. When performing calls with 'SwiftyPlistManager' you get access // to possible errors in the completion handlers. Let's dive deep into learning all about them. // // For a start let's write a function that interprets the error types you might get. We will simply log the error, // but you can do whatever you want. /* func logSwiftyPlistManager(_ error: SwiftyPlistManagerError?) { guard let err = error else { return } print("-------------> SwiftyPlistManager error: '\(err)'") }*/ //////////////////////////////////////////////////////////////////////////////////// // Now let's take a look at the most common use cases and their errors //////////////////////////////////////////////////////////////////////////////////// // fileUnavailable /* SwiftyPlistManager.shared.addNew(helloNewValue, key: newKey, toPlistWithName: nonExistentPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // fileAlreadyEmpty /* SwiftyPlistManager.shared.removeAllKeyValuePairs(fromPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // keyValuePairAlreadyExists /* SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } else { print("-------------> Value '\(rebeloperValue)' successfully added at Key '\(firstKey)' into '\(dataPlistName).plist'") } } SwiftyPlistManager.shared.addNew(rebeloperValue, key: firstKey, toPlistWithName: dataPlistName) { (err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// // keyValuePairDoesNotExist /* SwiftyPlistManager.shared.getValue(for: nonExistentKey, fromPlistWithName: dataPlistName) { (result, err) in if err != nil { logSwiftyPlistManager(err) } }*/ //////////////////////////////////////////////////////////////////////////////////// } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
78a47cd8d94dd8f3b3776a957b1dea00
46.879828
162
0.574668
5.187631
false
false
false
false
relayrides/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/Tweak.swift
1
5729
// // Tweak.swift // KATweak // // Created by Bryan Clark on 11/4/15. // Copyright © 2015 Khan Academy. All rights reserved. // import Foundation import CoreGraphics import UIKit /// Tweaks let you adjust things on the fly. /// Because each T needs a UI component, we have to restrict what T can be - hence T: TweakableType. /// If T: SignedNumberType, you can declare a min / max for a Tweak. public struct Tweak<T: TweakableType> { internal let collectionName: String internal let groupName: String internal let tweakName: String internal let defaultValue: T internal let minimumValue: T? // Only supported for T: SignedNumberType internal let maximumValue: T? // Only supported for T: SignedNumberType internal let stepSize: T? // Only supported for T: SignedNumberType internal init(tweakName: String, defaultValue: T, minimumValue: T? = nil, maximumValue: T? = nil, stepSize: T? = nil, collectionName: String = "Mixpanel", groupName: String = "Mixpanel") { [collectionName, groupName, tweakName].forEach { if $0.contains(TweakIdentifierSeparator) { assertionFailure("The substring `\(TweakIdentifierSeparator)` can't be used in a tweak name, group name, or collection name.") } } self.collectionName = collectionName self.groupName = groupName self.tweakName = tweakName self.defaultValue = defaultValue self.minimumValue = minimumValue self.maximumValue = maximumValue self.stepSize = stepSize } } internal let TweakIdentifierSeparator = "|" extension Tweak { /** Initializer for a Tweak for A/B Testing - parameter tweakName: name of the tweak - parameter defaultValue: the default value set for the tweak - parameter collectionName: the collection name of the tweak (do not set, optional) - parameter groupName: the group name of the tweak (do not set, optional) */ public init(tweakName: String, defaultValue: T, _ collectionName: String = "Mixpanel", _ groupName: String = "Mixpanel") { self.init( tweakName: tweakName, defaultValue: defaultValue, collectionName: collectionName, groupName: groupName ) } } extension Tweak where T: SignedNumber { /** Creates a Tweak<T> where T: SignedNumberType You can optionally provide a min / max / stepSize to restrict the bounds and behavior of a tweak. - parameter tweakName: name of the tweak - parameter defaultValue: the default value set for the tweak - parameter minimumValue: minimum value to allow for the tweak - parameter maximumValue: maximum value to allow for the tweak - parameter stepSize: step size for the tweak (do not set, optional) - parameter collectionName: the collection name of the tweak (do not set, optional) - parameter groupName: the group name of the tweak (do not set, optional) */ public init(tweakName: String, defaultValue: T, min minimumValue: T? = nil, max maximumValue: T? = nil, stepSize: T? = nil, _ collectionName: String = "Mixpanel", _ groupName: String = "Mixpanel") { // Assert that the tweak's defaultValue is between its min and max (if they exist) if clip(defaultValue, minimumValue, maximumValue) != defaultValue { assertionFailure("A tweak's default value must be between its min and max. Your tweak \"\(tweakName)\" doesn't meet this requirement.") } self.init( tweakName: tweakName, defaultValue: defaultValue, minimumValue: minimumValue, maximumValue: maximumValue, stepSize: stepSize, collectionName: collectionName, groupName: groupName ) } } extension Tweak: TweakType { var tweak: TweakType { return self } var tweakDefaultData: TweakDefaultData { switch T.tweakViewDataType { case .boolean: return .boolean(defaultValue: (defaultValue as! Bool)) case .integer: return .integer( defaultValue: defaultValue as! Int, min: minimumValue as? Int, max: maximumValue as? Int, stepSize: stepSize as? Int ) case .cgFloat: return .float( defaultValue: defaultValue as! CGFloat, min: minimumValue as? CGFloat, max: maximumValue as? CGFloat, stepSize: stepSize as? CGFloat ) case .double: return .doubleTweak( defaultValue: defaultValue as! Double, min: minimumValue as? Double, max: maximumValue as? Double, stepSize: stepSize as? Double ) case .uiColor: return .color(defaultValue: defaultValue as! UIColor) case .string: return .string(defaultValue: defaultValue as! String) } } var tweakViewDataType: TweakViewDataType { return T.tweakViewDataType } } extension Tweak: Hashable { /** Hashing for a Tweak for A/B Testing in order for it to be stored. */ public var hashValue: Int { return tweakIdentifier.hashValue } } /** Comparator between two tweaks for A/B Testing. - parameter lhs: the left hand side tweak to compare - parameter rhs: the right hand side tweak to compare - returns: a boolean telling if both tweaks are equal */ public func == <T>(lhs: Tweak<T>, rhs: Tweak<T>) -> Bool { return lhs.tweakIdentifier == rhs.tweakIdentifier } /// Extend Tweak to support identification in bindings extension Tweak: TweakIdentifiable { var persistenceIdentifier: String { return tweakIdentifier } } /// Extend Tweak to support easy initialization of a TweakStore extension Tweak: TweakClusterType { public var tweakCluster: [AnyTweak] { return [AnyTweak.init(tweak: self)] } }
apache-2.0
702f39c39cd7bf926fbed3f520914072
31.179775
138
0.679993
4.323019
false
false
false
false
prot3ct/Ventio
Ventio/Ventio/Controllers/CreateEventViewController.swift
1
1976
import UIKit import RxSwift class CreateEventViewController: UIViewController { @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextField! @IBOutlet weak var timeTextField: UITextField! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var isPublicSwitch: UISwitch! internal var eventData: EventDataProtocol! private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onCreateClicked(_ sender: UIButton) { self.startLoading() let title = self.titleTextField.text let description = self.descriptionTextField.text let time = self.timeTextField.text let date = self.dateTextField.text //let isPublic = self.isPublicSwitch.isOn eventData .create(title: title!, description: description!, date: date!, time: time!) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default)) .observeOn(MainScheduler.instance) .subscribe(onNext: { res in self.changeInitialViewController(identifier: "eventsTableViewController") self.showSuccess(withStatus: "You have saved your event successfully.") }, onError: { error in print(error) self.showError(withStatus: "Saving event ran into problem. Please try again later.") }) .disposed(by: disposeBag) } private func changeInitialViewController(identifier: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard .instantiateViewController(withIdentifier: identifier) UIApplication.shared.keyWindow?.rootViewController = initialViewController }}
apache-2.0
65b506490cc4d69508ac331dad5f594a
36.283019
100
0.660425
5.777778
false
false
false
false
CocoaheadsSaar/Treffen
Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/AppDelegate.swift
1
1703
// // AppDelegate.swift // AutolayoutTests // // Created by Markus Schmitt on 11.01.16. // Copyright © 2016 Insecom - Markus Schmitt. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let tabBarController = UITabBarController() let mainViewController = MainViewController() mainViewController.title = "Simple" let mainWithAnchorsViewController = MainWithAnchorsViewController() mainWithAnchorsViewController.title = "Anchors" let mainVisualViewController = MainVisualViewController() mainVisualViewController.title = "Visual" let mainStackViewController = MainStackViewController() mainStackViewController.title = "Stacks" let mainStackButtonsViewController = MainStackButtonsViewController() mainStackButtonsViewController.title = "Buttons" tabBarController.viewControllers = [ UINavigationController(rootViewController: mainViewController), UINavigationController(rootViewController: mainWithAnchorsViewController), UINavigationController(rootViewController: mainVisualViewController), UINavigationController(rootViewController: mainStackViewController), UINavigationController(rootViewController: mainStackButtonsViewController) ] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } }
gpl-2.0
2c77a75a6e2ad3952cd6f45782880110
36.822222
127
0.735605
6.422642
false
false
false
false
apple/swift-nio
IntegrationTests/tests_04_performance/test_01_resources/test_1000000_asyncwriter.swift
1
1228
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 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 DequeModule @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) fileprivate struct Delegate: NIOAsyncWriterSinkDelegate, Sendable { typealias Element = Int func didYield(contentsOf sequence: Deque<Int>) {} func didTerminate(error: Error?) {} } func run(identifier: String) { guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else { return } measure(identifier: identifier) { let delegate = Delegate() let newWriter = NIOAsyncWriter<Int, Delegate>.makeWriter(isWritable: true, delegate: delegate) let writer = newWriter.writer for i in 0..<1000000 { try! await writer.yield(i) } return 1000000 } }
apache-2.0
4374a5c2867c838c8fab541aa9412bc7
28.238095
102
0.587948
4.723077
false
false
false
false
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/protoc-gen-swiftgrpc/io.swift
1
1684
/* * Copyright 2017, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation // The I/O code below is derived from Apple's swift-protobuf project. // https://github.com/apple/swift-protobuf // BEGIN swift-protobuf derivation #if os(Linux) import Glibc #else import Darwin.C #endif enum PluginError: Error { /// Raised for any errors reading the input case readFailure } // Alias clib's write() so Stdout.write(bytes:) can call it. private let _write = write class Stdin { static func readall() throws -> Data { let fd: Int32 = 0 let buffSize = 32 var buff = [UInt8]() while true { var fragment = [UInt8](repeating: 0, count: buffSize) let count = read(fd, &fragment, buffSize) if count < 0 { throw PluginError.readFailure } if count < buffSize { buff += fragment[0..<count] return Data(bytes: buff) } buff += fragment } } } class Stdout { static func write(bytes: Data) { bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> Void in _ = _write(1, p, bytes.count) } } } // END swift-protobuf derivation
mit
02c4e4e32888795aab6e1597a15e02ee
25.3125
75
0.671615
3.835991
false
false
false
false
tryswift/trySwiftData
TrySwiftData/ViewModels/SessionViewModel/SessionTypeViewModels/SessionDisplayableTypes/OfficeHoursSessionViewModel.swift
1
1728
// // OfficeHoursSessionViewModel.swift // Pods // // Created by Natasha Murashev on 3/23/17. // // struct OfficeHoursSessionViewModel: SessionDisplayable { private let session: Session private let dataDefaults: SessionDataDefaults init?(_ session: Session) { if session.type == .officeHours { self.session = session dataDefaults = SessionDataDefaults(session: session) } else { return nil } } var title: String { guard let speaker = session.presentation?.speaker?.localizedName else { return "Office Hours".localized() } return String(format: "Office Hours with %@".localized(), speaker) } var presenter: String { if let presentation = session.presentation { return presentation.speaker?.localizedName ?? "⁉️" } return "⁉️" } var imageURL: URL { if let imageURL = dataDefaults.customImageAssetURL { return imageURL } if let speakerImage = session.presentation?.speaker?.imageURL { return speakerImage } return dataDefaults.imageURL } var location: String { return dataDefaults.location } var shortDescription: String { return "Q&A".localized() } var longDescription: String { return session.presentation?.speaker?.localizedBio ?? dataDefaults.longDescription } var selectable: Bool { return true } var twitter: String { let twitter = session.presentation?.speaker?.twitter ?? dataDefaults.twitter return "@\(twitter)" } }
mit
9f99403f538e90090a8290e1d452288f
23.571429
90
0.587791
5.196375
false
false
false
false
SafeCar/iOS
Pods/CameraEngine/CameraEngine/CameraEngineDeviceInput.swift
1
1590
// // CameraEngineDeviceInput.swift // CameraEngine2 // // Created by Remi Robert on 01/02/16. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit import AVFoundation public enum CameraEngineDeviceInputErrorType: ErrorType { case UnableToAddCamera case UnableToAddMic } class CameraEngineDeviceInput { private var cameraDeviceInput: AVCaptureDeviceInput? private var micDeviceInput: AVCaptureDeviceInput? func configureInputCamera(session: AVCaptureSession, device: AVCaptureDevice) throws { let possibleCameraInput: AnyObject? = try AVCaptureDeviceInput(device: device) if let cameraInput = possibleCameraInput as? AVCaptureDeviceInput { if let currentDeviceInput = self.cameraDeviceInput { session.removeInput(currentDeviceInput) } self.cameraDeviceInput = cameraInput if session.canAddInput(self.cameraDeviceInput) { session.addInput(self.cameraDeviceInput) } else { throw CameraEngineDeviceInputErrorType.UnableToAddCamera } } } func configureInputMic(session: AVCaptureSession, device: AVCaptureDevice) throws { if self.micDeviceInput != nil { return } try self.micDeviceInput = AVCaptureDeviceInput(device: device) if session.canAddInput(self.micDeviceInput) { session.addInput(self.micDeviceInput) } else { throw CameraEngineDeviceInputErrorType.UnableToAddMic } } }
mit
7dd0dbbd18c4bbde1371ce5e957a6189
30.8
90
0.67275
5.386441
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerDemo/Pods/SnapKit/Source/ConstraintMaker.swift
31
7210
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public class ConstraintMaker { public var left: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.left) } public var top: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.top) } public var bottom: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.bottom) } public var right: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.right) } public var leading: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.leading) } public var trailing: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.trailing) } public var width: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.width) } public var height: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.height) } public var centerX: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerX) } public var centerY: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerY) } @available(*, deprecated:3.0, message:"Use lastBaseline instead") public var baseline: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.lastBaseline) } public var lastBaseline: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.lastBaseline) } @available(iOS 8.0, OSX 10.11, *) public var firstBaseline: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.firstBaseline) } @available(iOS 8.0, *) public var leftMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.leftMargin) } @available(iOS 8.0, *) public var rightMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.rightMargin) } @available(iOS 8.0, *) public var topMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.topMargin) } @available(iOS 8.0, *) public var bottomMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.bottomMargin) } @available(iOS 8.0, *) public var leadingMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.leadingMargin) } @available(iOS 8.0, *) public var trailingMargin: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.trailingMargin) } @available(iOS 8.0, *) public var centerXWithinMargins: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerXWithinMargins) } @available(iOS 8.0, *) public var centerYWithinMargins: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerYWithinMargins) } public var edges: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.edges) } public var size: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.size) } public var center: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.center) } @available(iOS 8.0, *) public var margins: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.margins) } @available(iOS 8.0, *) public var centerWithinMargins: ConstraintMakerExtendable { return self.makeExtendableWithAttributes(.centerWithinMargins) } private let item: LayoutConstraintItem private var descriptions = [ConstraintDescription]() internal init(item: LayoutConstraintItem) { self.item = item self.item.prepare() } internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable { let description = ConstraintDescription(item: self.item, attributes: attributes) self.descriptions.append(description) return ConstraintMakerExtendable(description) } internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { let maker = ConstraintMaker(item: item) closure(maker) var constraints: [Constraint] = [] for description in maker.descriptions { guard let constraint = description.constraint else { continue } constraints.append(constraint) } return constraints } internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { let constraints = prepareConstraints(item: item, closure: closure) for constraint in constraints { constraint.activateIfNeeded(updatingExisting: false) } } internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { self.removeConstraints(item: item) self.makeConstraints(item: item, closure: closure) } internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { guard item.constraints.count > 0 else { self.makeConstraints(item: item, closure: closure) return } let constraints = prepareConstraints(item: item, closure: closure) for constraint in constraints { constraint.activateIfNeeded(updatingExisting: true) } } internal static func removeConstraints(item: LayoutConstraintItem) { let constraints = item.constraints for constraint in constraints { constraint.deactivateIfNeeded() } } }
mit
c36182f6323b8fc39972436d2924a8e2
34.343137
133
0.694175
5.699605
false
false
false
false
tomterror666/MyLotto
MyLotto/MyLotto/Model/Win.swift
1
2703
// // Win.swift // MyLotto // // Created by Andre Heß on 17/04/16. // Copyright © 2016 Andre Heß. All rights reserved. // import UIKit class Win: NSObject { var winningDrawingRate:DrawingRate? var winningNumbers:NSArray? var winningZusatzZahl:NSInteger var winningSuperZahl:NSInteger var guess:Guess var drawing:Drawing static func winWithGuessAndDrawing(guess:Guess, drawing:Drawing) -> Win { let me = Win(guess: guess, drawing: drawing) return me } init(guess:Guess, drawing:Drawing) { self.guess = guess self.drawing = drawing self.winningSuperZahl = -1 self.winningZusatzZahl = -1 self.winningDrawingRate = nil self.winningNumbers = nil super.init() self.checkForWinning() } func checkForWinning() { self.calcWinningNumbers() self.checkDrawingType() self.examineWinningDrawingRate() } func calcWinningNumbers() { let winningNumbers = NSMutableArray.init(capacity: 6) for drawingNumber in self.drawing.drawingNumbers { if (self.guess.numbers.containsObject(drawingNumber)) { winningNumbers.addObject(drawingNumber) } } self.winningNumbers = winningNumbers } func checkDrawingType() { if (self.drawing.drawingType == DrawingType.drawingTypeZusatzZahl) { self.winningSuperZahl = -1 self.winningZusatzZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.zusatzZahl!)) ? self.drawing.zusatzZahl! : -1 } else if (self.drawing.drawingType == DrawingType.drawingTypeSuperZahl) { self.winningSuperZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.superZahl!)) ? self.drawing.superZahl! : -1 self.winningZusatzZahl = -1 } else if (self.drawing.drawingType == DrawingType.drawingTypeZusatzZahlUndSuperZahl) { self.winningSuperZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.superZahl!)) ? self.drawing.superZahl! : -1 self.winningZusatzZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.zusatzZahl!)) ? self.drawing.zusatzZahl! : -1 } else { self.winningSuperZahl = -1 self.winningZusatzZahl = -1 } } func examineWinningDrawingRate() { let numberOfWinnings = self.winningNumbers != nil ? self.winningNumbers!.count : 0 for object:AnyObject in self.drawing.rates { let rate:DrawingRate = object as! DrawingRate if ((rate.winningConditions == numberOfWinnings) && ((rate.winningConditions.needsZusatzZahl && (self.winningZusatzZahl > -1)) || !rate.winningConditions.needsZusatzZahl) && ((rate.winningConditions.needsSuperZahl && (self.winningSuperZahl > -1)) || !rate.winningConditions.needsSuperZahl)) { self.winningDrawingRate = rate return } } } }
mit
408e152f02206701f70d41c8580a432e
31.926829
143
0.741111
3.653586
false
false
false
false
xwu/swift
test/Generics/sr14580.swift
1
1474
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on // RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s public protocol ScalarProtocol: ScalarMultiplicative where Self == Scalar { } public protocol ScalarMultiplicative { associatedtype Scalar: ScalarProtocol } public protocol MapReduceArithmetic: ScalarMultiplicative, Collection where Element: ScalarMultiplicative {} public protocol Tensor: MapReduceArithmetic where Element == Scalar { } // CHECK-LABEL: sr14580.(file).ColorModel@ // CHECK-LABEL: Requirement signature: <Self where Self : Tensor, Self == Self.Float16Components.Model, Self.Element == Double, Self.Float16Components : ColorComponents, Self.Float32Components : ColorComponents, Self.Float16Components.Element == Double, Self.Float16Components.Model == Self.Float32Components.Model, Self.Float32Components.Element == Double> public protocol ColorModel: Tensor where Scalar == Double { associatedtype Float16Components: ColorComponents where Float16Components.Model == Self, Float16Components.Scalar == Double associatedtype Float32Components: ColorComponents where Float32Components.Model == Self, Float32Components.Scalar == Double } public protocol ColorComponents: Tensor { associatedtype Model: ColorModel } extension Double : ScalarMultiplicative {} extension Double : ScalarProtocol { public typealias Scalar = Self }
apache-2.0
0740c61325c69ff5b935d2bc97ae898c
48.133333
357
0.803935
4.73955
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemProjectKit/StemGroup.swift
1
3065
// // StemGroup.swift // StemCode // // Created by David Evans on 20/04/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import Foundation import Signals struct StemGroupCodable: Decodable, Hashable { let identifier: String let name: String let isFolder: Bool let childGroups: Set<StemGroupCodable> let childFiles: [String] } public final class StemGroup: StemItem, Encodable { public let identifier: String public let parentProject: Stem private(set) public var name: String private(set) public var isFolder: Bool private var childFileIdentifiers: [String] private(set)public var childGroups: Set<StemGroup> public var childFiles: [StemFile] { return parentProject.files(for: childFileIdentifiers) } private(set) public var parentGroup: StemGroup? public let nameChanged = Signal<(StemGroup, String)>() public let fileAdded = Signal<StemFile>() public let groupAdded = Signal<StemGroup>() public let removedFromParentGroup = Signal<StemGroup>() public init(project: Stem, name: String, isFolder: Bool) { self.parentProject = project self.name = name self.isFolder = isFolder self.childFileIdentifiers = [String]() self.childGroups = Set<StemGroup>() self.identifier = NSUUID().uuidString } public func addChild(_ child: StemFile) { child.removeFromParentGroup() if self.childFileIdentifiers.firstIndex(of: child.identifier) != nil { return } child.parentGroup = self childFileIdentifiers.append(child.identifier) child.removedFromParentGroup.subscribe(with: self) { (file) in let index = self.childFileIdentifiers.firstIndex(of: file.identifier)! self.childFileIdentifiers.remove(at: index) child.removedFromParentGroup.cancelSubscription(for: self) } fileAdded.fire(child) } public func addChild(_ child: StemGroup) { child.removeFromParentGroup() if childGroups.contains(child) { return } childGroups.insert(child) child.removedFromParentGroup.subscribe(with: self) { (group) in self.childGroups.remove(child) child.removedFromParentGroup.cancelSubscription(for: self) } child.parentGroup = self groupAdded.fire(child) } public func removeFromParentGroup() { parentGroup = nil removedFromParentGroup.fire(self) } // MARK: - Codable enum CodingKeys: String, CodingKey { case identifier case name case isFolder case childGroups case childFileIdentifiers = "childFiles" } init(codableData: StemGroupCodable, parentGroup: StemGroup?, parentProject: Stem) { self.identifier = codableData.identifier self.name = codableData.name self.isFolder = codableData.isFolder self.parentProject = parentProject self.childFileIdentifiers = codableData.childFiles childGroups = Set<StemGroup>() childGroups = Set<StemGroup>(codableData.childGroups.map { StemGroup(codableData: $0, parentGroup: self, parentProject: parentProject) }) parentProject.files(for: childFileIdentifiers).forEach { (file) in file.parentGroup = self } } }
mit
3066bd63e34ca76877a2d2ab7dfe38a9
24.747899
139
0.735966
3.963777
false
false
false
false
PandaraWen/DJIDemoKit
DJIDemoKit/DDKTableSectionHeader.swift
1
1557
// // DDKStartTableSectionHeader.swift // DJIDemoKitDemo // // Created by Pandara on 2017/9/1. // Copyright © 2017年 Pandara. All rights reserved. // import UIKit import SnapKit class DDKTableSectionHeader: UITableViewHeaderFooterView { var titleLabel: UILabel! override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: UI fileprivate extension DDKTableSectionHeader { func setupSubviews() { let bgView = UIView() bgView.backgroundColor = UIColor.white self.addSubview(bgView) bgView.snp.makeConstraints { (make) in make.edges.equalTo(self) } let headerView = UIView() headerView.backgroundColor = UIColor(r: 0, g: 140, b: 255, a: 1) self.addSubview(headerView) headerView.snp.makeConstraints({ (make) in make.left.top.bottom.equalTo(self) make.width.equalTo(4) }) self.titleLabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 18) label.textColor = UIColor.ddkVIBlue self.addSubview(label) label.snp.makeConstraints({ (make) in make.left.equalTo(headerView.snp.right).offset(8) make.top.right.bottom.equalTo(self) }) return label }() } }
mit
481b9c271f8321ab82563f9989350f73
27.254545
72
0.60296
4.42735
false
false
false
false
kazuhiro49/StringStylizer
StringStylizer/StringStylizer.swift
1
18974
// // StringSerializer.swift // // Copyright (c) 2016 Kazuhiro Hayashi // // 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 /** Type safely builder class for NSAttributedString. It makes NSAttributedString more intitive by wrapping method chains and operators. #### Usage when you convert String to NSAttributedString which has some colors, sizes and fonts, you can write it in a linear manner. ``` let label = UILabel(frame: CGRectMake(0, 0, 100, 50)) // build NSAttributedString. let greed = "Hi, ".stylize().color(0x2200ee).size(12).font(.HelveticaNeue).attr // build NSAttributedString with ranges. let msg = "something happened ".stylize() .range(0..<9) .color(0x009911).size(12).font(.HelveticaNeue) .range(10..<UInt.max).color(0xaa22cc).size(14).font(.HelveticaNeue_Bold).attr // build NSAttributedString objects and join them. let name = "to ".stylize().color(0x23abfc).size(12).font(.HelveticaNeue).attr + "you".stylize().color(0x123456).size(14).font(.HelveticaNeue_Italic).underline(.StyleDouble).attr label.attributedText = greed + msg + name ``` This sample code generates the following styled label. <img width="261" src="https://cloud.githubusercontent.com/assets/18266814/14254571/49882d08-facb-11e5-9e3d-c37cbef6a003.png"> */ public class StringStylizer<T: StringStylizerStatus>: StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = String public typealias UnicodeScalarLiteralType = String private var _attrString: NSAttributedString private var _attributes = [String: AnyObject]() private var _range: Range<UInt> // MARK:- Initializer init(string: String, range: Range<UInt>? = nil, attributes: [String: AnyObject] = [String: AnyObject]()) { let range = range ?? 0..<UInt(string.characters.count) _attrString = NSAttributedString(string: string) _attributes = attributes _range = range } init(attributedString: NSAttributedString, range: Range<UInt>, attributes: [String: AnyObject] = [String: AnyObject]()) { _attrString = attributedString _attributes = attributes _range = range } public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { _attrString = NSMutableAttributedString(string: value) _range = 0..<UInt(_attrString.string.characters.count) } public required init(stringLiteral value: StringLiteralType) { _attrString = NSMutableAttributedString(string: value) _range = 0..<UInt(_attrString.string.characters.count) } public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { _attrString = NSMutableAttributedString(string: value) _range = 0..<UInt(_attrString.string.characters.count) } // MARK:- Attributes // https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/index.html#//apple_ref/doc/c_ref/NSLinkAttributeName /** The value of NSForegroundColorAttributeName - parameter rgb:UInt - parameter alpha:Double (default: 1.0) - returns: StringStylizer<Styling> */ public func color(rgb: UInt, alpha: Double = 1.0) -> StringStylizer<Styling> { _attributes[NSForegroundColorAttributeName] = self.rgb(rgb, alpha: alpha) let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSForegroundColorAttributeName - parameter color:UIColor - returns: StringStylizer<Styling> */ public func color(color: UIColor) -> StringStylizer<Styling> { _attributes[NSForegroundColorAttributeName] = color let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSFontAttributeName - parameter font:UIFont - returns: StringStylizer<Styling> */ public func font(font: UIFont) -> StringStylizer<Styling> { _attributes[NSFontAttributeName] = font let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The name value of NSFontAttributeName - parameter name:String - returns: StringStylizer<Styling> */ public func font(name: String) -> StringStylizer<Styling> { let font: UIFont if let currentFont = _attributes[NSFontAttributeName] as? UIFont { font = UIFont(name: name, size: currentFont.pointSize) ?? UIFont() } else { font = UIFont(name: name, size: UIFont.systemFontSize()) ?? UIFont() } _attributes[NSFontAttributeName] = font let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The name value of NSFontAttributeName - parameter name:StringStylizerFontName - returns: StringStylizer<Styling> */ public func font(name: StringStylizerFontName) -> StringStylizer<Styling> { let font: UIFont if let currentFont = _attributes[NSFontAttributeName] as? UIFont { font = UIFont(name: name.rawValue, size: currentFont.pointSize) ?? UIFont() } else { font = UIFont(name: name.rawValue, size: UIFont.systemFontSize()) ?? UIFont() } _attributes[NSFontAttributeName] = font let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The size value of NSFontAttributeName - parameter size:Double - returns: StringStylizer<Styling> */ public func size(size: Double) -> StringStylizer<Styling> { let font: UIFont if let currentFont = _attributes[NSFontAttributeName] as? UIFont { font = UIFont(name: currentFont.fontName, size: CGFloat(size)) ?? UIFont() } else { font = UIFont.systemFontOfSize(CGFloat(size)) } _attributes[NSFontAttributeName] = font let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSBackgroundColorAttributeName - parameter rgb:UInt - parameter alpha:Double (default:1.0) - returns: StringStylizer<Styling> */ public func background(rgb: UInt, alpha: Double = 1.0) -> StringStylizer<Styling> { _attributes[NSBackgroundColorAttributeName] = self.rgb(rgb, alpha: alpha) let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSKernAttributeName - parameter value:Double - returns: StringStylizer<Styling> */ public func karn(value: Double) -> StringStylizer<Styling> { _attributes[NSKernAttributeName] = value let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The values of NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName - parameter style:NSUnderlineStyle... - parameter rgb:UInt? (default:nil) - parameter alpha:Double (default:1.0) - returns: StringStylizer<Styling> */ public func underline(style: NSUnderlineStyle..., rgb: UInt? = nil, alpha: Double = 1) -> StringStylizer<Styling> { let _style: [NSUnderlineStyle] = style.isEmpty ? [.StyleSingle] : style let value = _style.reduce(0) { (sum, elem) -> Int in return sum | elem.rawValue } _attributes[NSUnderlineStyleAttributeName] = value _attributes[NSUnderlineColorAttributeName] = rgb.flatMap { self.rgb($0, alpha: alpha) } let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The values of NSStrokeWidthAttributeName and NSStrokeColorAttributeName - parameter rgb:UInt? (default:nil) - parameter alpha:Double (default:1.0) - returns: StringStylizer<Styling> */ public func stroke(rgb rgb: UInt, alpha: Double = 1.0, width: Double = 1) -> StringStylizer<Styling> { _attributes[NSStrokeWidthAttributeName] = width _attributes[NSStrokeColorAttributeName] = self.rgb(rgb, alpha: alpha) let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The values of NSStrokeWidthAttributeName and NSStrokeColorAttributeName - parameter color:UIColor - parameter alpha:Double (default:1.0) - parameter width:Double (default:1.0) - returns: StringStylizer<Styling> */ public func stroke(color color: UIColor, alpha: Double = 1.0, width: Double = 1) -> StringStylizer<Styling> { _attributes[NSStrokeWidthAttributeName] = width _attributes[NSStrokeColorAttributeName] = color let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The values of NSStrikethroughStyleAttributeName and NSStrikethroughColorAttributeName - parameter style:NSUnderlineStyle... - parameter rgb:UInt? (default:nil) - parameter alpha:Double (default:1.0) - returns: StringStylizer<Styling> */ public func strokeThrogh(style: NSUnderlineStyle..., rgb: UInt? = nil, alpha: Double = 1) -> StringStylizer<Styling> { let _style: [NSUnderlineStyle] = style.isEmpty ? [.StyleSingle] : style let value = _style.reduce(0) { (sum, elem) -> Int in return sum | elem.rawValue } _attributes[NSStrikethroughStyleAttributeName] = value _attributes[NSStrikethroughColorAttributeName] = rgb.flatMap { self.rgb($0, alpha: alpha) } let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSShadowAttributeName - parameter value:NSShadow - returns: StringStylizer<Styling> */ public func shadow(value: NSShadow) -> StringStylizer<Styling> { _attributes[NSShadowAttributeName] = value let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSLigatureAttributeName - parameter value:Int - returns: StringStylizer<Styling> */ public func ligeture(value: Int) -> StringStylizer<Styling> { _attributes[NSLigatureAttributeName] = value let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSLinkAttributeName - parameter url:NSURL - returns: StringStylizer<Styling> */ public func link(url: NSURL) -> StringStylizer<Styling> { _attributes[NSLinkAttributeName] = url let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } /** The value of NSBaselineOffsetAttributeName - parameter value:Double - returns: StringStylizer<Styling> */ public func baselineOffset(value: Double) -> StringStylizer<Styling> { _attributes[NSBaselineOffsetAttributeName] = value let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } private func rgb(rgb: UInt, alpha: Double) -> UIColor { return UIColor( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: CGFloat(alpha) ) } } public extension StringStylizer { public func paragraph(style: NSParagraphStyle) -> StringStylizer<Styling> { _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphAlignment(alignment: NSTextAlignment) -> StringStylizer<Styling> { let style: NSMutableParagraphStyle if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle { currentStyle.alignment = alignment style = currentStyle } else { style = NSMutableParagraphStyle() style.alignment = alignment } _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphIndent(firstLineHead firstLineHead: CGFloat? = nil, tail: CGFloat? = nil, otherHead: CGFloat? = nil) -> StringStylizer<Styling> { let style = getParagraphStyle() if let firstLineHead = firstLineHead { style.firstLineHeadIndent = firstLineHead } if let otherHead = otherHead { style.headIndent = otherHead } if let tail = tail { style.tailIndent = tail } _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphLineBreak(lineBreakMode: NSLineBreakMode) -> StringStylizer<Styling> { let style = getParagraphStyle() style.lineBreakMode = lineBreakMode _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphLineHeight(maximum maximum: CGFloat? = nil, minimum: CGFloat? = nil, multiple: CGFloat? = nil) -> StringStylizer<Styling> { let style = getParagraphStyle() if let maximum = maximum { style.maximumLineHeight = maximum } if let minimum = minimum { style.minimumLineHeight = minimum } if let multiple = multiple { style.lineHeightMultiple = multiple } _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphLineSpacing(after after: CGFloat? = nil, before: CGFloat? = nil) -> StringStylizer<Styling> { let style = getParagraphStyle() if let after = after { style.lineSpacing = after } if let before = before { style.paragraphSpacingBefore = before } _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public func paragraphBaseWritingDirection(baseWritingDirection: NSWritingDirection) -> StringStylizer<Styling> { let style: NSMutableParagraphStyle if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle { style = currentStyle } else { style = NSMutableParagraphStyle() } style.baseWritingDirection = baseWritingDirection _attributes[NSParagraphStyleAttributeName] = style let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes) return stylizer } public var count: Int { return _attrString.length } private func getParagraphStyle() -> NSMutableParagraphStyle { if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle { return currentStyle } else { return NSMutableParagraphStyle() } } } public extension StringStylizer where T: Styling { /// generates NSAttributedString public var attr: NSAttributedString { let range = Int(_range.startIndex)..<Int(_range.endIndex) let attrString = NSMutableAttributedString(attributedString: _attrString) attrString.setAttributes(_attributes, range: NSRange(range)) return attrString } /** set range to assign attributes - parameter range:Range (default: nil) - returns: StringStylizer<NarrowDown> */ public func range(range: Range<UInt>? = nil) -> StringStylizer<NarrowDown> { let attrString = NSMutableAttributedString(attributedString: _attrString) attrString.setAttributes(_attributes, range: NSRange(Int(_range.startIndex)..<Int(_range.endIndex))) let range = range ?? 0..<UInt(attrString.length) let endIndex = min(range.endIndex, UInt(_attrString.length)) let validRange = range.startIndex..<endIndex return StringStylizer<NarrowDown>(attributedString: attrString, range: validRange) } }
mit
dbae0abfad9588aef534d0c61e8be22a
37.963039
173
0.664119
5.095059
false
false
false
false
tbaranes/IncrementableLabel
IncrementableLabel Example/Example/tvOS Example/ViewController.swift
2
1772
// // ViewController.swift // IncrementableLabel // // Created by Tom Baranes on 20/01/16. // Copyright © 2016 Recisio. All rights reserved. // import UIKit import IncrementableLabel class ViewController: UIViewController { // MARK: Properties @IBOutlet weak var label1: IncrementableLabel! @IBOutlet weak var label2: IncrementableLabel! @IBOutlet weak var label3: IncrementableLabel! @IBOutlet weak var label4: IncrementableLabel! @IBOutlet weak var label5: IncrementableLabel! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() } // MARK: IBAction @IBAction func startIncrementationPressed(sender: AnyObject) { label1.increment(fromValue: 0, toValue: 100, duration: 3) label2.format = "%f" label2.increment(fromValue: 0.0, toValue: 100.0, duration: 3) label3.option = .easeInOut label3.stringFormatter = { value in return String(format: "EaseInOutAnimation: %d", Int(value)) } label3.increment(fromValue: 0.0, toValue: 100.0, duration: 3) label4.option = .easeOut label4.attributedTextFormatter = { value in let string = String(format: "EaseOutAnimation + attributedString: %d", Int(value)) let attributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0)]) return attributedString } label4.incrementFromZero(toValue: 1000, duration: 1) label5.textColor = UIColor.black label5.incrementFromZero(toValue: 1000, duration: 1) { self.label5.textColor = UIColor.green } } }
mit
7e819c1f69cb8795028bff21714a337a
29.534483
156
0.645398
4.541026
false
false
false
false
Oscareli98/Moya
Demo/DemoTests/MoyaProviderSpec.swift
2
20953
import Quick import Moya import Nimble import ReactiveCocoa import RxSwift class MoyaProviderSpec: QuickSpec { override func spec() { describe("valid endpoints") { describe("with stubbed responses") { describe("a provider", { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns stubbed data for user profile request") { var message: String? let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns equivalent Endpoint instances for the same target") { let target: GitHub = .Zen let endpoint1 = provider.endpoint(target) let endpoint2 = provider.endpoint(target) expect(endpoint1).to(equal(endpoint2)) } it("returns a cancellable object when a request is made") { let target: GitHub = .UserProfile("ashfurrow") let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in } expect(cancellable).toNot(beNil()) } }) it("notifies at the beginning of network requests") { var called = false var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in if change == .Began { called = true } }) let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } it("notifies at the end of network requests") { var called = false var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in if change == .Ended { called = true } }) let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } describe("a provider with lazy data", { () -> () in var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } }) it("delays execution when appropriate") { let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2)) let startDate = NSDate() var endDate: NSDate? let target: GitHub = .Zen waitUntil(timeout: 3) { done in provider.request(target) { (data, statusCode, response, error) in endDate = NSDate() done() } return } expect{ return endDate?.timeIntervalSinceDate(startDate) }.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) ) } describe("a provider with a custom endpoint resolver") { () -> () in var provider: MoyaProvider<GitHub>! var executed = false let newSampleResponse = "New Sample Response" beforeEach { executed = false let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in executed = true return endpoint.urlRequest } provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("executes the endpoint resolver") { let target: GitHub = .Zen provider.request(target, completion: { (data, statusCode, response, error) in }) let sampleData = target.sampleData as NSData expect(executed).to(beTruthy()) } } describe("a reactive provider", { () -> () in var provider: ReactiveCocoaMoyaProvider<GitHub>! beforeEach { provider = ReactiveCocoaMoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns a MoyaResponse object") { var called = false provider.request(.Zen).subscribeNext { (object) -> Void in if let response = object as? MoyaResponse { called = true } } expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target).subscribeNext { (object) -> Void in if let response = object as? MoyaResponse { message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).toNot(beNil()) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .UserProfile("ashfurrow") provider.request(target).subscribeNext { (object) -> Void in if let response = object as? MoyaResponse { receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary } } let sampleData = target.sampleData as NSData let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary expect(receivedResponse).toNot(beNil()) } it("returns identical signals for inflight requests") { let target: GitHub = .Zen var response: MoyaResponse! // The synchronous nature of stubbed responses makes this kind of tricky. We use the // subscribeNext closure to get the provider into a state where the signal has been // added to the inflightRequests dictionary. Then we ask for an identical request, // which should return the same signal. We can't *test* those signals equivalency // due to the use of RACSignal.defer, but we can check if the number of inflight // requests went up or not. let outerSignal = provider.request(target) outerSignal.subscribeNext { (object) -> Void in response = object as? MoyaResponse expect(provider.inflightRequests.count).to(equal(1)) // Create a new signal and force subscription, so that the inflightRequests dictionary is accessed. let innerSignal = provider.request(target) innerSignal.subscribeNext { (object) -> Void in // nop } expect(provider.inflightRequests.count).to(equal(1)) } expect(provider.inflightRequests.count).to(equal(0)) } }) describe("a RxSwift provider", { () -> () in var provider: RxMoyaProvider<GitHub>! beforeEach { provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns a MoyaResponse object") { var called = false provider.request(.Zen) >- subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target) >- subscribeNext { (response) -> Void in message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String } let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding) expect(message).to(equal(sampleString)) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .UserProfile("ashfurrow") provider.request(target) >- subscribeNext { (response) -> Void in receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary } let sampleData = target.sampleData as NSData let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary expect(receivedResponse).toNot(beNil()) } it("returns identical signals for inflight requests") { let target: GitHub = .Zen var response: MoyaResponse! let outerSignal = provider.request(target) outerSignal >- subscribeNext { (response) -> Void in expect(provider.inflightRequests.count).to(equal(1)) let innerSignal = provider.request(target) innerSignal >- subscribeNext { (object) -> Void in expect(provider.inflightRequests.count).to(equal(1)) } } expect(provider.inflightRequests.count).to(equal(0)) } }) describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") { struct TestCancellable: Cancellable { static var cancelled = false func cancel() { TestCancellable.cancelled = true } } class TestProvider<T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> { override init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) { super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } override func request(token: T, completion: MoyaCompletion) -> Cancellable { return TestCancellable() } } var provider: ReactiveCocoaMoyaProvider<GitHub>! beforeEach { TestCancellable.cancelled = false provider = TestProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(1)) } it("cancels network request when subscription is cancelled") { var called = false let target: GitHub = .Zen let disposable = provider.request(target).subscribeCompleted { () -> Void in // Should never be executed fail() } disposable.dispose() expect(TestCancellable.cancelled).to( beTrue() ) } } } describe("with stubbed errors") { describe("a provider") { () -> () in var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var errored = false let target: GitHub = .Zen provider.request(target) { (object, statusCode, response, error) in if error != nil { errored = true } } let sampleData = target.sampleData as NSData expect(errored).toEventually(beTruthy()) } it("returns stubbed data for user profile request") { var errored = false let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (object, statusCode, response, error) in if error != nil { errored = true } } let sampleData = target.sampleData as NSData expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1) } it("returns stubbed error data when present") { var errorMessage = "" let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (object, statusCode, response, error) in if let object = object { errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String } } expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1) } } describe("a reactive provider", { () -> () in var provider: ReactiveCocoaMoyaProvider<GitHub>! beforeEach { provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var errored = false let target: GitHub = .Zen provider.request(target).subscribeError { (error) -> Void in errored = true } expect(errored).to(beTruthy()) } it("returns correct data for user profile request") { var errored = false let target: GitHub = .UserProfile("ashfurrow") provider.request(target).subscribeError { (error) -> Void in errored = true } expect(errored).to(beTruthy()) } }) describe("a failing reactive provider") { var provider: ReactiveCocoaMoyaProvider<GitHub>! beforeEach { provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns the HTTP status code as the error code") { var code: Int? provider.request(.Zen).subscribeError { (error) -> Void in code = error.code } expect(code).toNot(beNil()) expect(code).to(equal(401)) } } } } } }
mit
39076b7a996e5058d0e3bc7e34c4dee7
47.727907
327
0.440414
7.372625
false
false
false
false
ashleymills/Keychain.swift
Example/Simple-KeychainSwift/Keychain.swift
1
5545
// // KeychainWrapper.swift // Keychain sample app // // Created by Ashley Mills on 17/04/2015. // Copyright (c) 2015 Joylord Systems Ltd. All rights reserved. // import Foundation // MARK: - *** Public methods *** public class Keychain { public class func set(_ value:String, forKey key:String) -> Bool { if valueExists(forKey: key) { return update(value, forKey: key) } else { return create(value, forKey: key) } } public class func set(_ bool:Bool, forKey key:String) -> Bool { let value = bool ? "true" : "false" return set(value, forKey: key) } public class func value(forKey key: String) -> String? { guard let valueData = valueData(forKey: key) else { return nil } return NSString(data: valueData, encoding: String.Encoding.utf8.rawValue) as String? } public class func bool(forKey key: String) -> Bool { return value(forKey: key) == "true" } public class func removeValue(forKey key:String) -> Bool { return deleteValue(forKey: key) } public class func reset() -> Bool { let searchDictionary = basicDictionary() let status = SecItemDelete(searchDictionary as CFDictionary) return status == errSecSuccess } public class func allValues() -> [[String: String]]? { var searchDictionary = basicDictionary() searchDictionary[kSecMatchLimit as String] = kSecMatchLimitAll searchDictionary[kSecReturnAttributes as String] = kCFBooleanTrue searchDictionary[kSecReturnData as String] = kCFBooleanTrue var retrievedAttributes: AnyObject? var retrievedData: AnyObject? var status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedAttributes) if status != errSecSuccess { return nil } status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedData) if status != errSecSuccess { return nil } guard let attributeDicts = retrievedAttributes as? [[String: AnyObject]] else { return nil } var allValues = [[String : String]]() for attributeDict in attributeDicts { guard let keyData = attributeDict[kSecAttrAccount as String] as? Data else { continue } guard let valueData = attributeDict[kSecValueData as String] as? Data else { continue } guard let key = NSString(data: keyData, encoding: String.Encoding.utf8.rawValue) as String? else { continue } guard let value = NSString(data: valueData, encoding: String.Encoding.utf8.rawValue) as String? else { continue } allValues.append([key: value]) } return allValues } } // MARK: - *** Private methods *** fileprivate extension Keychain { class func valueExists(forKey key: String) -> Bool { return valueData(forKey: key) != nil } class func create(_ value: String, forKey key: String) -> Bool { var dictionary = newSearchDictionary(forKey: key) dictionary[kSecValueData as String] = value.data(using: String.Encoding.utf8, allowLossyConversion: false) as AnyObject? let status = SecItemAdd(dictionary as CFDictionary, nil) return status == errSecSuccess } class func update(_ value: String, forKey key: String) -> Bool { let searchDictionary = newSearchDictionary(forKey: key) var updateDictionary = [String: AnyObject]() updateDictionary[kSecValueData as String] = value.data(using: String.Encoding.utf8, allowLossyConversion: false) as AnyObject? let status = SecItemUpdate(searchDictionary as CFDictionary, updateDictionary as CFDictionary) return status == errSecSuccess } class func deleteValue(forKey key: String) -> Bool { let searchDictionary = newSearchDictionary(forKey: key) let status = SecItemDelete(searchDictionary as CFDictionary) return status == errSecSuccess } class func valueData(forKey key: String) -> Data? { var searchDictionary = newSearchDictionary(forKey: key) searchDictionary[kSecMatchLimit as String] = kSecMatchLimitOne searchDictionary[kSecReturnData as String] = kCFBooleanTrue var retrievedData: AnyObject? let status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedData) var data: Data? if status == errSecSuccess { data = retrievedData as? Data } return data } class func newSearchDictionary(forKey key: String) -> [String: AnyObject] { let encodedIdentifier = key.data(using: String.Encoding.utf8, allowLossyConversion: false) var searchDictionary = basicDictionary() searchDictionary[kSecAttrGeneric as String] = encodedIdentifier as AnyObject? searchDictionary[kSecAttrAccount as String] = encodedIdentifier as AnyObject? return searchDictionary } class func basicDictionary() -> [String: AnyObject] { let serviceName = Bundle(for: self).infoDictionary![kCFBundleIdentifierKey as String] as! String return [kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : serviceName as AnyObject] } }
mit
b93cd1b40edb070b38ade208cec463c3
35.24183
134
0.637151
5.352317
false
false
false
false
elegion/ios-Flamingo
Framework/FlamingoTests/NetworkClientReporterCallTests.swift
1
3389
// // NetworkClientReporterCallTests.swift // FlamingoTests // // Created by Nikolay Ischuk on 23.01.2018. // Copyright © 2018 ELN. All rights reserved. // import Foundation import XCTest import Flamingo private class MockLogger: Logger { private(set) var logSended: Bool = false public func log(_ message: String, context: [String: Any]?) { self.logSended = true } } private class MockReporter: LoggingClient { var willSendCallClosure: (() -> Void)? private(set) var willSendCalled: Bool = false private(set) var didRecieveCalled: Bool = false override func willSendRequest<Request>(_ networkRequest: Request) where Request: NetworkRequest { willSendCalled = true willSendCallClosure?() super.willSendRequest(networkRequest) } override func didRecieveResponse<Request>(for request: Request, context: NetworkContext) where Request: NetworkRequest { didRecieveCalled = true super.didRecieveResponse(for: request, context: context) } } class NetworkClientReporterCallTests: XCTestCase { var client: NetworkClient! override func setUp() { super.setUp() let configuration = NetworkDefaultConfiguration(baseURL: "http://www.mocky.io/") client = NetworkDefaultClient(configuration: configuration, session: .shared) } override func tearDown() { client = nil super.tearDown() } func test_reporterCalls() { let logger1 = MockLogger() let reporter1 = MockReporter(logger: logger1) let reporter2 = MockReporter(logger: SimpleLogger(appName: #file)) client.addReporter(reporter1, storagePolicy: .weak) client.addReporter(reporter2, storagePolicy: .weak) let asyncExpectation = expectation(description: #function) let request = RealFailedTestRequest() client.removeReporter(reporter2) client.sendRequest(request) { _, _ in asyncExpectation.fulfill() } waitForExpectations(timeout: 10) { _ in XCTAssertTrue(reporter1.willSendCalled) XCTAssertTrue(reporter1.didRecieveCalled) XCTAssertFalse(reporter2.willSendCalled) XCTAssertFalse(reporter2.didRecieveCalled) XCTAssertTrue(logger1.logSended, "Logs are not sended") } } func test_storagePolicy() { var wasCalled1 = false var wasCalled2 = false var reporter1: MockReporter! = MockReporter(logger: SimpleLogger(appName: #file)) var reporter2: MockReporter! = MockReporter(logger: SimpleLogger(appName: #file)) let configuration = NetworkDefaultConfiguration(baseURL: "http://www.mocky.io/", parallel: false) let networkClient = NetworkDefaultClient(configuration: configuration, session: .shared) networkClient.addReporter(reporter1, storagePolicy: .weak) networkClient.addReporter(reporter2, storagePolicy: .strong) reporter1.willSendCallClosure = { wasCalled1 = true } reporter2.willSendCallClosure = { wasCalled2 = true } reporter1 = nil reporter2 = nil let stubRequest = StubRequest() networkClient.sendRequest(stubRequest, completionHandler: nil) XCTAssertFalse(wasCalled1) XCTAssertTrue(wasCalled2) } }
mit
ccc7908fcc9234a8153c5439231d8867
31.576923
124
0.670307
4.87482
false
true
false
false
Boss-XP/ChatToolBar
BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatViewController/view/BXPChatMessageCell.swift
1
9833
// // BXPChatMessageCell.swift // BXPChatToolBar // // Created by 向攀 on 17/1/5. // Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved. // import UIKit class BXPChatMessageCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } let averterList = ["demo_avatar_jobs","demo_avatar_cook","demo_avatar_woz"] var messageWidth: CGFloat = 66 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor(red: 222/255, green: 222/255, blue: 222/255, alpha: 1.0) selectionStyle = UITableViewCellSelectionStyle.none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() contentView.addSubview(leftAvatarImageView) leftAvatarImageView.image = UIImage(named: averterList[Int(arc4random_uniform(2))]) contentView.addSubview(rightAvatarImageView) rightAvatarImageView.image = UIImage(named: averterList[Int(arc4random_uniform(2))]) contentView.addSubview(leftMessageBackView) contentView.addSubview(rightMessageBackView) leftMessageBackView.addSubview(leftMessageTextLabel) rightMessageBackView.addSubview(rightMessageTextLabel) setupLeft() setupRight() } func setupLeft() -> Void { /*let constraintLeft = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 66) let constraintTop = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0) let constraintBottom = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0) let constraintWidth = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 72) let constraintHeight = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 50) contentView.addConstraints([constraintLeft, constraintTop, constraintBottom]) leftMessageBackView.addConstraints([constraintWidth, constraintHeight]) */ let constraintLeft1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10) let constraintRight1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -10) let constraintTop1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10) let constraintBottom1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10) leftMessageBackView.addConstraints([constraintLeft1, constraintTop1, constraintBottom1, constraintRight1]) } func setupRight() -> Void { /*let constraintRight = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -66) let constraintTop = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0) let constraintBottom = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0) let constraintWidth = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: messageWidth) contentView.addConstraints([constraintRight, constraintTop, constraintBottom]) rightMessageBackView.addConstraints([constraintWidth]) */ let constraintLeft1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10) let constraintRight1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -10) let constraintTop1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10) let constraintBottom1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10) rightMessageBackView.addConstraints([constraintLeft1, constraintTop1, constraintBottom1, constraintRight1]) } lazy var leftAvatarImageView: UIImageView = { let tempImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 50, height: 50)) tempImageView.layer.cornerRadius = 6 tempImageView.layer.masksToBounds = true return tempImageView }() lazy var leftMessageBackView: UIImageView = { let tempImageView = UIImageView()//(frame: CGRect(x: 66, y: 10, width: 50, height: 50)) tempImageView.image = UIImage(named: "chat_bubble_common_left") // tempImageView.layer.cornerRadius = 6 // tempImageView.layer.masksToBounds = true return tempImageView }() lazy var rightAvatarImageView: UIImageView = { let tempImageView = UIImageView(frame: CGRect(x: UIScreen.main.bounds.size.width - 60, y: 10, width: 50, height: 50)) tempImageView.layer.cornerRadius = 6 tempImageView.layer.masksToBounds = true return tempImageView }() lazy var rightMessageBackView: UIImageView = { let tempImageView = UIImageView()//(frame: CGRect(x: 66, y: 10, width: 50, height: 50)) tempImageView.image = UIImage(named: "chat_bubble_common_right") return tempImageView }() lazy var leftMessageTextLabel: UILabel = { let textLabel = UILabel() textLabel.numberOfLines = 0 textLabel.font = UIFont.systemFont(ofSize: 16) textLabel.textColor = UIColor.black // self.contentView.addSubview(textLabel) return textLabel }() lazy var rightMessageTextLabel: UILabel = { let textLabel = UILabel() textLabel.numberOfLines = 0 textLabel.font = UIFont.systemFont(ofSize: 16) textLabel.textColor = UIColor.black textLabel.textAlignment = NSTextAlignment.right // self.contentView.addSubview(textLabel) return textLabel }() func setLeftMessageText(attributeString: NSAttributedString, width: CGFloat) -> Void { rightAvatarImageView.isHidden = true rightMessageBackView.isHidden = true var frame = CGRect(x: 62, y: 10, width: 240, height: 80) leftMessageBackView.frame = frame//CGRect(x: 62, y: 10, width: 240, height: 80) frame.origin.x = 15 frame.origin.y = 10 frame.size.width -= 25 frame.size.height -= 20 leftMessageTextLabel.frame = frame leftMessageTextLabel.attributedText = attributeString if width > 66 { messageWidth = width } // layoutIfNeeded() // layoutSubviews() } func setRightMessageText(attributeString: NSAttributedString, width: CGFloat) -> Void { leftAvatarImageView.isHidden = true leftMessageBackView.isHidden = true let width: CGFloat = 200 var frame = CGRect(x: UIScreen.main.bounds.size.width - width - 62, y: 10, width: width, height: 80) rightMessageBackView.frame = frame//CGRect(x: UIScreen.main.bounds.size.width - 240 - 62, y: 10, width: 240, height: 80) frame.origin.x = 10 frame.origin.y = 10 frame.size.width -= 25 frame.size.height -= 20 rightMessageTextLabel.frame = frame rightMessageTextLabel.attributedText = attributeString if width > 66 { messageWidth = width } // layoutIfNeeded() } }
apache-2.0
4822b017a4f75eee58afd9da9991cfea
51.545455
250
0.710157
5.308482
false
false
false
false
AaoIi/AAAlertController
FMAlertController/FMAlertController/FMAlertController.swift
1
14659
// // FMAlertController.swift // FMAlertController // // Created by AaoIi on 4/13/16. // Copyright © 2016 Saad Albasha. All rights reserved. // import UIKit public class FMAlertController: UIViewController { public enum animationType{ case `default` case shake case slideDown case slideUp case slideRight case slideLeft case fade } enum type { case single case double case triple } //* create alert with one cancel button @IBOutlet fileprivate var viewOneButton: UIView! @IBOutlet fileprivate var viewOneHeight: NSLayoutConstraint! @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var titleLabelHeight: NSLayoutConstraint! @IBOutlet fileprivate var messageLabel: UILabel! @IBOutlet fileprivate var cancelButton: UIButton! //* create alert with cancel and action button @IBOutlet fileprivate var viewWithTwoButtons: UIView! @IBOutlet fileprivate var viewTwoHeight: NSLayoutConstraint! @IBOutlet fileprivate var titleLabel2: UILabel! @IBOutlet fileprivate var titleLabel2Height: NSLayoutConstraint! @IBOutlet fileprivate var messageLabel2: UILabel! @IBOutlet fileprivate var cancelButton2: UIButton! @IBOutlet fileprivate var okButton: UIButton! //* create alert with cancel and two action buttons @IBOutlet fileprivate var viewWithThreeButtons: UIView! @IBOutlet fileprivate var viewThreeHeight: NSLayoutConstraint! @IBOutlet fileprivate var titleLabel3: UILabel! @IBOutlet fileprivate var titleLabel3Height: NSLayoutConstraint! @IBOutlet fileprivate var messageLabel3: UILabel! @IBOutlet fileprivate var firstButton: UIButton! @IBOutlet fileprivate var secondButton: UIButton! @IBOutlet fileprivate var cancelButton3: UIButton! //* local variables fileprivate var titleText : String? fileprivate var messageText : String? fileprivate var cancelButtonTitle : String? fileprivate var firstButtonTitle : String? fileprivate var secondButtonTitle : String? fileprivate var viewType : type = .single fileprivate var firstActionCompletion : () -> (Void) = {} fileprivate var secondActionCompletion : () -> (Void) = {} fileprivate var cancelCompletionBlock : () -> (Void) = {} fileprivate var animationStyle : animationType! //MARK:- Life Cycle override required init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @available(*,unavailable) override public func viewDidLoad() { super.viewDidLoad() self.setupView() } @available(*,unavailable) override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch viewType { case .single: self.performAnimation(viewOneButton) break; case .double: self.performAnimation(viewWithTwoButtons) break; case .triple: self.performAnimation(viewWithThreeButtons) break; } } //MARK:- Core init fileprivate func setupView(){ switch viewType { case .single: //* setup for alert with cancel button self.viewWithTwoButtons.isHidden = true self.viewOneButton.isHidden = false self.viewWithThreeButtons.isHidden = true self.titleLabel.text = titleText self.messageLabel.text = messageText self.cancelButton.setTitle(cancelButtonTitle, for: UIControl.State()) self.cancelButton.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside) caclulateAlertHeight(viewOneHeight, view: viewOneButton, messageLabel: messageLabel, titleHeightConstraint: titleLabelHeight, titleLabel: titleLabel) break; case .double: //* setup for alert with action and cancel button self.viewWithTwoButtons.isHidden = false self.viewOneButton.isHidden = true self.viewWithThreeButtons.isHidden = true self.titleLabel2.text = titleText self.messageLabel2.text = messageText self.cancelButton2.setTitle(cancelButtonTitle, for: UIControl.State()) self.cancelButton2.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside) self.okButton.setTitle(firstButtonTitle, for: UIControl.State()) self.okButton.addTarget(self, action: #selector(self.okAlertController(_:)), for: UIControl.Event.touchUpInside) caclulateAlertHeight(viewTwoHeight, view: viewWithTwoButtons, messageLabel: messageLabel2, titleHeightConstraint: titleLabel2Height, titleLabel: titleLabel2) break; case .triple: //* Setup for alert with two buttons and cancel button self.viewWithTwoButtons.isHidden = true self.viewOneButton.isHidden = true self.viewWithThreeButtons.isHidden = false self.titleLabel3.text = titleText self.messageLabel3.text = messageText self.cancelButton3.setTitle(cancelButtonTitle, for: UIControl.State()) self.cancelButton3.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside) self.firstButton.setTitle(firstButtonTitle, for: UIControl.State()) self.firstButton.addTarget(self, action: #selector(self.okAlertController(_:)), for: UIControl.Event.touchUpInside) self.secondButton.setTitle(secondButtonTitle, for: UIControl.State()) self.secondButton.addTarget(self, action: #selector(self.okAlertController1(_:)), for: UIControl.Event.touchUpInside) caclulateAlertHeight(viewThreeHeight, view: viewWithThreeButtons, messageLabel: messageLabel, titleHeightConstraint: titleLabel3Height, titleLabel: titleLabel3) break; } } fileprivate func FMAlertController(_ title:String,message:String,cancelButtonTitle:String,animationStyle:animationType,completionBlock: @escaping () -> (Void)){ self.titleText = title self.messageText = message self.cancelButtonTitle = cancelButtonTitle self.viewType = .single self.cancelCompletionBlock = completionBlock self.animationStyle = animationStyle } fileprivate func FMAlertController(_ title:String,message:String,cancelButtonTitle:String,firstButtonTitle:String,animationStyle:animationType,firstActionCompletion: @escaping () -> (Void),cancelCompletionBlock: @escaping () -> (Void)){ self.titleText = title self.messageText = message self.cancelButtonTitle = cancelButtonTitle self.firstButtonTitle = firstButtonTitle self.viewType = .double self.firstActionCompletion = firstActionCompletion self.cancelCompletionBlock = cancelCompletionBlock self.animationStyle = animationStyle } fileprivate func FMAlertController(_ title:String,message:String,firstButtonTitle:String,secondButtonTitle:String,cancelButtonTitle:String,animationStyle:animationType,firstActionCompletion: @escaping () -> (Void),secondActionCompletion: @escaping () -> (Void),cancelCompletionBlock: @escaping () -> (Void)){ self.titleText = title self.messageText = message self.cancelButtonTitle = cancelButtonTitle self.firstButtonTitle = firstButtonTitle self.secondButtonTitle = secondButtonTitle self.viewType = .triple self.firstActionCompletion = firstActionCompletion self.secondActionCompletion = secondActionCompletion self.cancelCompletionBlock = cancelCompletionBlock self.animationStyle = animationStyle } //MARK:- Handlers @objc fileprivate func cancelAlertController(_ cancelButtonSender :UIButton) { //* cancel alert Controller self.cancelCompletionBlock() self.dismiss(animated: true, completion: nil) } @objc fileprivate func okAlertController(_ okButtonSender :UIButton){ //* executue completion block and cancel alert controller self.firstActionCompletion() self.dismiss(animated: true, completion: nil) } @objc fileprivate func okAlertController1(_ okButtonSender :UIButton){ //* executue completion block and cancel alert controller self.secondActionCompletion() self.dismiss(animated: true, completion: nil) } //MARK:- View Animation fileprivate func performAnimation(_ view:UIView){ guard let animationStyle = animationStyle else {return} switch animationStyle { case .default: view.performDefaultAnimation() break; case .shake: view.performShakeAnimation() break; case .slideDown: view.performSlideDownAnimation() break; case .slideUp: view.performSlideUpAnimation() break; case .slideRight: view.performSlideRightAnimation() break; case .slideLeft: view.performSlideLeftAnimation() break; case .fade: view.performFadeAnimation() break; } } //MARK:- Alert Calculator fileprivate func caclulateAlertHeight(_ viewHeightConstraint:NSLayoutConstraint,view:UIView,messageLabel:UILabel,titleHeightConstraint:NSLayoutConstraint,titleLabel:UILabel){ //* extend message to take title top if titleLabel.text == "" { titleHeightConstraint.constant = 0 } //* calculate message height let actualMessageSize = calculateTextHeight(messageLabel) let messageSizeDifferance = actualMessageSize - 53 //* calculate title height let actualTitleSize = calculateTextHeight(titleLabel) let titleSizeDifferance = actualTitleSize - 21 if actualTitleSize > 21 { titleHeightConstraint.constant += titleSizeDifferance } if actualMessageSize > 53 { viewHeightConstraint.constant += messageSizeDifferance + titleHeightConstraint.constant }else { viewHeightConstraint.constant += titleHeightConstraint.constant - 20 } self.view.layoutIfNeeded() } fileprivate func calculateTextHeight(_ LabelText:UILabel) -> CGFloat{ let labelWidth = LabelText.frame.width let maxLabelSize = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude) let actualLabelSize = LabelText.text?.boundingRect(with: maxLabelSize, options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: LabelText.font ?? UIFont.systemFontSize], context: nil) return actualLabelSize?.height ?? 0 } } // MARK: - Responsible to Show Alert public extension FMAlertController { class func show(_ title:String?,message:String?,cancelButtonTitle:String,completionBlock: @escaping ()->(Void),animationStyle:animationType = .default){ let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!) let alertView = self.init(nibName: "FMAlertController", bundle: bundle) alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve alertView.FMAlertController(title ?? "", message: message ?? "", cancelButtonTitle: cancelButtonTitle,animationStyle:animationStyle, completionBlock:completionBlock) alertView.show(animated: true) } class func show(_ title:String?,message:String?,firstButtonTitle:String,firstActionCompletion: @escaping ()->(Void),cancelButtonTitle:String,cancelCompletionBlock: @escaping ()->(Void),animationStyle:animationType = .default){ let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!) let alertView = self.init(nibName: "FMAlertController", bundle: bundle) alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve alertView.FMAlertController(title ?? "", message: message ?? "", cancelButtonTitle: cancelButtonTitle, firstButtonTitle: firstButtonTitle,animationStyle:animationStyle, firstActionCompletion: firstActionCompletion, cancelCompletionBlock: cancelCompletionBlock) alertView.show(animated: true) } class func show(_ title:String?,message:String?,firstButtonTitle:String,firstButtonCompletionBlock: @escaping ()->(Void),secondButtonTitle:String,secondButtonCompletionBlock: @escaping ()->(Void),cancelButtonTitle:String,cancelCompletionBlock: @escaping ()->(Void),animationStyle:animationType = .default){ let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!) let alertView = self.init(nibName: "FMAlertController", bundle: bundle) alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve alertView.FMAlertController(title ?? "", message: message ?? "", firstButtonTitle: firstButtonTitle, secondButtonTitle: secondButtonTitle, cancelButtonTitle: cancelButtonTitle, animationStyle: animationStyle, firstActionCompletion: firstButtonCompletionBlock, secondActionCompletion: secondButtonCompletionBlock, cancelCompletionBlock: cancelCompletionBlock) alertView.show(animated: true) } }
mit
b54d20b9428e97b321e0239182abe698
39.830084
366
0.669873
6
false
false
false
false
HotCocoaTouch/DeclarativeLayout
Example/DeclarativeLayout/READMEExample/READMEExample.swift
1
2896
import UIKit import DeclarativeLayout class READMEExample: UIViewController { private lazy var viewLayout = ViewLayout(view: view) private lazy var stackView = UIStackView() private lazy var redView = UIView() private lazy var orangeView = UIView() private lazy var yellowView = UIView() private lazy var greenView = UIView() private lazy var blueView = UIView() private lazy var purpleView = UIView() override func viewDidLoad() { super.viewDidLoad() title = "README Example" layoutAllViews() configureAllViews() animationLoop() } private func animationLoop() { Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true, block: { timer in UIView.animate(withDuration: 1.0, animations: { self.layoutAllViews() self.stackView.layoutIfNeeded() }) }) } private func layoutAllViews() { let views = [redView, orangeView, yellowView, greenView, blueView, purpleView] viewLayout.updateLayoutTo { (com) in com.stackView(self.stackView) { (com) in com.constraints( com.ownedView.leadingAnchor.constraint(equalTo: com.superview.leadingAnchor), com.ownedView.trailingAnchor.constraint(equalTo: com.superview.trailingAnchor), com.ownedView.topAnchor.constraint(equalTo: com.superview.safeAreaLayoutGuide.topAnchor, constant: 35) ) com.ownedView.axis = .vertical for view in views.shuffled() { com.arrangedView(view) { (com) in let random = CGFloat(Int.random(in: 20..<100)) com.constraints( com.ownedView.heightAnchor.constraint(equalToConstant: random) ) } com.space(CGFloat(Int.random(in: 0..<50))) } } } } // Don't worry about this below here private func configureAllViews() { view.backgroundColor = .white redView.backgroundColor = .red orangeView.backgroundColor = .orange yellowView.backgroundColor = .yellow greenView.backgroundColor = .green blueView.backgroundColor = .blue purpleView.backgroundColor = .purple redView.accessibilityLabel = "red" orangeView.accessibilityLabel = "orange" yellowView.accessibilityLabel = "yellow" greenView.accessibilityLabel = "green" blueView.accessibilityLabel = "blue" purpleView.accessibilityLabel = "purple" redView.accessibilityLabel = "red" } }
mit
ec0810dbc1d3b249cb67fee5804c67f5
33.47619
108
0.566989
5.645224
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift
3
2628
// // UInt128.swift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // import Foundation struct UInt128: Equatable, ExpressibleByIntegerLiteral { let i: (a: UInt64, b: UInt64) typealias IntegerLiteralType = UInt64 init(integerLiteral value: IntegerLiteralType) { self = UInt128(value) } init(_ raw: Array<UInt8>) { self = raw.prefix(MemoryLayout<UInt128>.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in let arr = rawBufferPointer.bindMemory(to: UInt64.self) return UInt128((arr[0].bigEndian, arr[1].bigEndian)) }) } init(_ raw: ArraySlice<UInt8>) { self.init(Array(raw)) } init(_ i: (a: UInt64, b: UInt64)) { self.i = i } init(a: UInt64, b: UInt64) { self.init((a, b)) } init(_ b: UInt64) { self.init((0, b)) } // Bytes var bytes: Array<UInt8> { var at = self.i.a.bigEndian var bt = self.i.b.bigEndian let ar = Data(bytes: &at, count: MemoryLayout.size(ofValue: at)) let br = Data(bytes: &bt, count: MemoryLayout.size(ofValue: bt)) var result = Data() result.append(ar) result.append(br) return result.bytes } static func ^ (n1: UInt128, n2: UInt128) -> UInt128 { UInt128((n1.i.a ^ n2.i.a, n1.i.b ^ n2.i.b)) } static func & (n1: UInt128, n2: UInt128) -> UInt128 { UInt128((n1.i.a & n2.i.a, n1.i.b & n2.i.b)) } static func >> (value: UInt128, by: Int) -> UInt128 { var result = value for _ in 0..<by { let a = result.i.a >> 1 let b = result.i.b >> 1 + ((result.i.a & 1) << 63) result = UInt128((a, b)) } return result } // Equatable. static func == (lhs: UInt128, rhs: UInt128) -> Bool { lhs.i == rhs.i } static func != (lhs: UInt128, rhs: UInt128) -> Bool { !(lhs == rhs) } }
gpl-3.0
60266858a779fd2fb4ffb25b4604aef1
28.188889
217
0.64941
3.385309
false
false
false
false
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/ViewController.swift
1
20081
// // ViewController.swift // uoat // // Created by Pyro User on 4/5/16. // Copyright © 2016 Zed. All rights reserved. // import UIKit class ViewController: UIViewController, LoginSignupDelegate, ProfileDelegate { var user:User! required init?(coder aDecoder: NSCoder) { //Detectar idioma. let langId = NSLocale.preferredLanguages()[0].split("-")[0]; print("Idioma device: \(langId)"); print("Scale:\(UIScreen.mainScreen().scale)") print("VIEW:\(UIScreen.mainScreen().bounds)") LanguageMgr.getInstance.setId( langId ); //Create library with books in device. Library.create( langId, isHD: ( UIScreen.mainScreen().scale > 1.0 ) ) var bookIds:[String] = [String]() for book in Library.getInstance().currentBooks() { print("Tale detected in device: \(book.id) - \(book.title)") bookIds.append(book.id) } let pos = Int(arc4random_uniform( UInt32(bookIds.count) ) ) self.bgImgPath = Library.getInstance().getFirstImageToPresentation( bookIds[pos] ) self.user = User() self.wellcomeMsg = "" super.init(coder: aDecoder); //Init kuasars. self.initKuasars(); //Load accesories to show in game. AccesoriesMgr.create( ( UIScreen.mainScreen().scale > 1.0 ) ) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.networkStatusChanged(_:)), name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Set background image from any book if( self.bgMainImage.image == nil ) { self.bgMainImage.image = UIImage( contentsOfFile: self.bgImgPath )! let blurEffectView:UIVisualEffectView = Utils.blurEffectView(self.bgMainImage, radius: 6) //3 self.bgMainImage.addSubview( blurEffectView ) } //buttons animations. self.originalPosTaleModeButton = self.taleModeButton.frame self.originalPosFreeModeButton = self.freeModeButton.frame self.originalPosBottomGrpView = self.bottomGrpView.frame self.originalPosJoinSessionGrpView = self.joinSessionGrpView.frame //invite notifications. //self.invitesButton.enabled = false self.joinSessionGrpView.hidden = true self.bgNotificationImage.hidden = true self.notificationCountLabel.text = "" //friendship notifications. self.bgFriendshipNotificationImage.hidden = true self.friendshipNotificationCountLabel.text = "" } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //Main buttons. if( hasSetAnimationValuesNow ) { self.taleModeButton.frame.origin.x = self.view.bounds.width self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width self.bottomGrpView.frame.origin.y = self.view.bounds.height self.joinSessionGrpView.frame.origin.x = self.view.bounds.width } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) dispatch_async(dispatch_get_main_queue(), { [unowned self] in self.hasSetAnimationValuesNow = false UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.taleModeButton.frame = self.originalPosTaleModeButton self.freeModeButton.frame = self.originalPosFreeModeButton self.bottomGrpView.frame = self.originalPosBottomGrpView if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.frame = self.originalPosJoinSessionGrpView } }) { [unowned self] (finished:Bool) in self.showNotificationsInfo() } }) self.showUserInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { self.hasSetAnimationValuesNow = true if( segue.identifier == "showLoginSignupView" ) { //let navigationController = segue.destinationViewController as! UINavigationController //let controller = navigationController.viewControllers.first as! LoginSignupViewController let controller = segue.destinationViewController as! LoginSignupViewController controller.user = self.user controller.delegate = self } else if( segue.identifier == "showProfileView" ) { let controller = segue.destinationViewController as! ProfileViewController controller.user = self.user controller.delegate = self } else if( segue.identifier == "showFriendsManagerView" ) { let controller = segue.destinationViewController as! FriendsManagerViewController controller.user = self.user controller.notificationsByType = self.notificationsByType } else if( segue.identifier == "showModeLobbyView" ) { //let navigationController = segue.destinationViewController as! UINavigationController //let controller = navigationController.viewControllers.first as! TaleModeLobbyViewController let controller = segue.destinationViewController as! TaleModeLobbyViewController controller.user = self.user controller.bgImagePath = self.bgImgPath } else if( segue.identifier == "showInviteNotificationsManagerView" ) { let controller = segue.destinationViewController as! InviteNotificationsManagerViewController controller.user = self.user controller.bgImagePath = self.bgImgPath controller.notificationsByType = self.notificationsByType } } func willShowFriends(sender:UIButton) { if( NetworkWatcher.internetAvailabe ) { UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.taleModeButton.frame.origin.x = self.view.frame.width self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width self.bottomGrpView.frame.origin.y = self.view.frame.height if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.frame.origin.x = self.view.frame.width } }) { [unowned self] (finished:Bool) in self.performSegueWithIdentifier( "showFriendsManagerView", sender:nil ) } } else { Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil ) } } func willShowInvites(sender:UIButton) { if( NetworkWatcher.internetAvailabe ) { UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.taleModeButton.frame.origin.x = self.view.frame.width self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width self.bottomGrpView.frame.origin.y = self.view.frame.height if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.frame.origin.x = self.view.frame.width } }) { [unowned self] (finished:Bool) in self.performSegueWithIdentifier( "showInviteNotificationsManagerView", sender:nil ) } } else { Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil ) } } func networkStatusChanged(notification:NSNotification) { print("ViewController::networkStatusChanged was called...") let userInfo:Dictionary<String,Bool!> = notification.userInfo as! Dictionary<String,Bool!> let isAvailable:Bool = userInfo["isAvailable"]! if( !isAvailable ) { Utils.alertMessage( self, title:"Attention", message:"Internet connection lost!", onAlertClose:nil ) } self.notificationsErrorMessageShowed = false } /*=============================================================*/ /* From LoginSignupDelegate */ /*=============================================================*/ func onLoginSignupReady() { hasSetAnimationValuesNow = false self.showUserInfo() self.showNotificationsInfo() } /*=============================================================*/ /* From ProfileDelegate */ /*=============================================================*/ func onProfileReady() { hasSetAnimationValuesNow = false self.showUserInfo() self.showNotificationsInfo() } /*=============================================================*/ /* UI Section */ /*=============================================================*/ @IBOutlet weak var bgMainImage: UIImageView! @IBOutlet weak var helloLabel: UILabel! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var taleModeButton: UIButton! @IBOutlet weak var freeModeButton: UIButton! @IBOutlet weak var joinSessionGrpView: UIView! @IBOutlet weak var invitesButton: UIButton! @IBOutlet weak var bgNotificationImage: UIImageView! @IBOutlet weak var notificationCountLabel: UILabel! @IBOutlet weak var bottomGrpView: UIView! @IBOutlet weak var friendsButton: UIButton! @IBOutlet weak var bgFriendshipNotificationImage: UIImageView! @IBOutlet weak var friendshipNotificationCountLabel: UILabel! //--------------------------------------------------------------- // UI Actions //--------------------------------------------------------------- @IBAction func login(sender: UIButton) { if( NetworkWatcher.internetAvailabe ) { if( !self.user.isLogged() ) { self.performSegueWithIdentifier("showLoginSignupView", sender: nil) } else { self.performSegueWithIdentifier("showProfileView", sender: nil) } } else { Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil ) } } @IBAction func starTaleMode(sender: UIButton) { UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.taleModeButton.frame.origin.x = self.view.frame.width self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width self.bottomGrpView.frame.origin.y = self.view.frame.height if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.frame.origin.x = self.view.frame.width } }) { [unowned self] (finished:Bool) in self.user.lobby = .Tale self.performSegueWithIdentifier("showModeLobbyView", sender: nil ) } } @IBAction func starFreeMode(sender: UIButton) { if( NetworkWatcher.internetAvailabe ) { UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.taleModeButton.frame.origin.x = self.view.frame.width self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width self.bottomGrpView.frame.origin.y = self.view.frame.height if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.frame.origin.x = self.view.frame.width } }) { [unowned self] (finished:Bool) in self.user.lobby = .Free self.performSegueWithIdentifier("showModeLobbyView", sender: nil ) } } else { Utils.alertMessage(self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil ) } } @IBAction func showCredits(sender: UIButton) { performSegueWithIdentifier("showInformationView", sender: nil) } @IBAction func showGallery(sender: UIButton) { performSegueWithIdentifier("showGalleryView", sender: nil ) } @IBAction func unwindToMainView(segue: UIStoryboardSegue) { //Back from TaleModeViewController or FreeModeViewController if( segue.sourceViewController.isKindOfClass( FreeModeViewController ) ) { let controller:FreeModeViewController = segue.sourceViewController as! FreeModeViewController self.user = controller.user controller.user = nil } else if( segue.sourceViewController.isKindOfClass( TaleModeViewController ) ) { let controller:TaleModeViewController = segue.sourceViewController as! TaleModeViewController self.user = controller.user controller.user = nil } } /*=============================================================*/ /* Private Section */ /*=============================================================*/ private func initKuasars() { KuasarsCore.setAppId( "560ab6e3e4b0b185810131aa" ); KuasarsCore.setEnvironment( KuasarsEnvironmentPRO ); KuasarsCore.setDebuggerEnabled( true ); } private func showUserInfo() { if( self.user.isLogged() ) { //Hi message and change login button title. let hiName = self.wellcomeMsg + self.user.name; helloLabel.text = hiName; helloLabel.hidden = false; loginButton.setTitle( "Profile", forState: .Normal ); //Friends button. self.friendsButton.enabled = true self.friendsButton.addTarget( self, action:#selector(ViewController.willShowFriends(_:)), forControlEvents:.TouchUpInside ) } else { if( self.wellcomeMsg.isEmpty ) { self.wellcomeMsg = helloLabel.text! } helloLabel.text = self.wellcomeMsg helloLabel.hidden = true loginButton.setTitle( "Registrarse", forState: .Normal ) //Friends button. self.friendsButton.enabled = false self.friendsButton.removeTarget( self, action:#selector(ViewController.willShowFriends(_:)), forControlEvents:.TouchUpInside ) } } private func showNotificationsInfo() { //Invite button is showed when notifications for playingroom and readingroom are received. if( self.user.isLogged() ) { if( NetworkWatcher.internetAvailabe ) { NotificationModel.getAllByUser( self.user.id, onNotificationsReady:{[unowned self](notifications) in //Show var invitesCount:Int = 0 var friendshipRequestCount:Int = 0 if let invitesPlayingRoom = notifications[NotificationType.PlayingRoom] { invitesCount += invitesPlayingRoom.count } else if let invitesReadingRoom = notifications[NotificationType.ReadingRoom] { invitesCount += invitesReadingRoom.count } else if let friendship = notifications[NotificationType.FriendShip] { friendshipRequestCount += friendship.count } //Show invites to room notifications. if( invitesCount > 0 ) { //self.invitesButton.enabled = true self.notificationCountLabel.text = "\(invitesCount)" if( self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.hidden = false self.bgNotificationImage.hidden = false self.invitesButton.addTarget( self, action:#selector(ViewController.willShowInvites(_:)), forControlEvents:.TouchUpInside ) self.joinSessionGrpView.alpha = 0.0 UIView.animateWithDuration( 0.5, animations:{ [unowned self] in self.joinSessionGrpView.alpha = 1.0 }) } } else { //self.invitesButton.enabled = false self.joinSessionGrpView.hidden = true self.bgNotificationImage.hidden = true self.notificationCountLabel.text = "" } //Show friendship notifications. if( friendshipRequestCount > 0 ) { self.bgFriendshipNotificationImage.hidden = false self.friendshipNotificationCountLabel.text = "\(friendshipRequestCount)" } else { self.bgFriendshipNotificationImage.hidden = true self.friendshipNotificationCountLabel.text = "" } self.notificationsByType = notifications }) } else { if( !self.notificationsErrorMessageShowed ) { Utils.alertMessage(self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil ) self.notificationsErrorMessageShowed = true } } } else { //self.invitesButton.enabled = false if( !self.joinSessionGrpView.hidden ) { self.joinSessionGrpView.alpha = 1.0 UIView.animateWithDuration( 0.2, animations:{ [unowned self] in self.joinSessionGrpView.alpha = 0.0 }){ [unowned self] (finished:Bool) in self.joinSessionGrpView.hidden = true self.bgNotificationImage.hidden = true self.notificationCountLabel.text = "" } } self.bgFriendshipNotificationImage.hidden = true self.friendshipNotificationCountLabel.text = "" } } private var hasSetAnimationValuesNow:Bool = true private var originalPosTaleModeButton:CGRect = CGRect.zero private var originalPosFreeModeButton:CGRect = CGRect.zero private var originalPosBottomGrpView:CGRect = CGRect.zero private var originalPosJoinSessionGrpView:CGRect = CGRect.zero private var wellcomeMsg:String private var bgImgPath:String private var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]() private var notificationsErrorMessageShowed:Bool = false }
apache-2.0
2023385c44c885a3199cd715fcf0586f
39.07984
197
0.564094
5.711035
false
false
false
false
mcdappdev/Vapor-Template
Sources/App/Controllers/API/LoginController.swift
1
1580
import Vapor import Foundation import BCrypt import AuthProvider import MySQL final class LoginController: RouteCollection { func build(_ builder: RouteBuilder) throws { builder.version() { build in build.post("login", handler: login) } } //MARK: - POST /api/v1/login func login(_ req: Request) throws -> ResponseRepresentable { let invalidCredentials = Abort(.badRequest, reason: "Invalid credentials") guard let json = req.json else { throw Abort.badRequest } //TODO: - When Swift 4 is released add a generic subscript to `StructuredDataWrapper` so that `.rawValue` doesn't have to be used. See: https://github.com/apple/swift-evolution/blob/master/proposals/0148-generic-subscripts.md guard let email = json[User.Field.email.rawValue]?.string else { throw Abort.badRequest } guard let password = json[User.Field.password.rawValue]?.string else { throw Abort.badRequest } guard let user = try User.makeQuery().filter(User.Field.email, email).first() else { throw invalidCredentials } if try BCryptHasher().verify(password: password, matches: user.password) { if try user.token() == nil { let newToken = Token(token: UUID().uuidString, user_id: user.id!) try newToken.save() } return try user.makeJSON() } else { throw invalidCredentials } } } //MARK: - EmptyInitializable extension LoginController: EmptyInitializable { }
mit
e3399672d1536b9106dcaf87972d645a
38.5
233
0.639873
4.744745
false
false
false
false
PJayRushton/stats
Stats/AddGamesToCalendar.swift
1
1689
// // AddGamesToCalendar.swift // Stats // // Created by Parker Rushton on 8/15/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import Foundation import EventKit struct AddGamesToCalendar: Command { var games: [Game] init(_ games: [Game]) { self.games = games } func execute(state: AppState, core: Core<AppState>) { do { try games.forEach { game in let calendarEvent = game.calendarEvent() try CalendarService.eventStore.save(calendarEvent, span: .thisEvent) core.fire(command: UpdateGame(game, calendarId: calendarEvent.eventIdentifier)) } } catch { print("error saving event") } } } struct EditCalendarEventForGames: Command { var games: [Game] init(_ games: [Game]) { self.games = games } func execute(state: AppState, core: Core<AppState>) { games.forEach { game in guard let calendarId = game.calendarId, let event = CalendarService.eventStore.event(withIdentifier: calendarId) else { return } let updatedEvent = game.calendarEvent(from: event) do { try CalendarService.eventStore.save(updatedEvent, span: .thisEvent) } catch { print("error saving event to calendar") } } } } extension EKEvent: Diffable { func isSame(as other: EKEvent) -> Bool { return startDate == other.startDate && location == other.location && calendar == other.calendar && endDate == other.endDate && title == other.title } }
mit
248b1cf38ee5f886221ba927808f84f6
24.575758
140
0.577014
4.418848
false
false
false
false
jaylyerly/XLForm
Examples/Swift/Examples/CustomRows/Rating/XLFormRatingCell.swift
2
2165
// XLFormRatingCell.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. let XLFormRowDescriptorTypeRate = "XLFormRowDescriptorTypeRate" @objc class XLFormRatingCell : XLFormBaseCell { @IBOutlet weak var rateTitle: UILabel! @IBOutlet weak var ratingView: XLRatingView! override func configure() { super.configure() self.selectionStyle = UITableViewCellSelectionStyle.None self.ratingView.addTarget(self, action: "rateChanged:", forControlEvents:UIControlEvents.ValueChanged) } override func update() { super.update() self.ratingView.value = self.rowDescriptor.value.floatValue self.rateTitle.text = self.rowDescriptor.title self.ratingView.alpha = self.rowDescriptor.isDisabled() ? 0.6 : 1 self.rateTitle.alpha = self.rowDescriptor.isDisabled() ? 0.6 : 1 } //MARK: Events func rateChanged(ratingView : XLRatingView){ self.rowDescriptor.value = ratingView.value } }
mit
58b9904398dc009387ca4b7d14a2e659
37.660714
110
0.721478
4.557895
false
false
false
false
jjacobson93/RethinkDBSwift
Sources/RethinkDB/Error.swift
1
3832
public enum ReqlError: Error { case authError(String) case compileError(String, [Any], [Any]) case cursorEmpty case driverError(String) case typeError(Any, String) public var localizedDescription: String { switch self { case .authError(let e): return e case .driverError(let e): return e case .compileError(let e, let term, let backtrace): let queryPrinter = QueryPrinter(root: term, backtrace: backtrace) return "\(e)\n\(queryPrinter.printQuery())\n\(queryPrinter.printCarrots())" case .cursorEmpty: return "Cursor is empty" case .typeError(let value, let type): return "Cannot coerce value \(value) to suggested type \(type)." } } } public struct QueryPrinter { let root: [Any] let backtrace: [Any] init(root: [Any], backtrace: [Any]) { self.root = root self.backtrace = backtrace } func printQuery() -> String { return self.composeTerm(self.root) } func printCarrots() -> String { return self.composeCarrots(self.root, self.backtrace) } func composeTerm(_ term: [Any]) -> String { guard let typeValue = term[0] as? Int else { return "EXPECTED INT, FOUND ARRAY: \(term[0])" } guard let termType = ReqlTerm(rawValue: typeValue), let termArgs = term[1] as? [Any] else { return "" } let args = termArgs.map({ self.composeTerm($0) }) var optargs = [String: String]() if term.count > 2, let dict = term[2] as? [String: Any] { for (k, v) in dict { optargs[k] = self.composeTerm(v) } } return self.composeTerm(termType, args, optargs) } func composeTerm(_ term: Any) -> String { if let term = term as? [Any] { return self.composeTerm(term) } return "\(term)" } func composeTerm(_ termType: ReqlTerm, _ args: [String], _ optargs: [String: String]) -> String { let term = termType.description let argsString = args.joined(separator: ", ") if optargs.isEmpty { return "\(term)(\(argsString))" } return "\(term)(\(argsString), \(optargs))" } func composeCarrots(_ term: [Any], _ backtrace: [Any]) -> String { guard let typeValue = term[0] as? Int, let termType = ReqlTerm(rawValue: typeValue), let termArgs = term[1] as? [Any] else { return "" } if backtrace.isEmpty { return String(repeating: "^", count: self.composeTerm(term).characters.count) } let currFrame = backtrace[0] let args = termArgs.enumerated().map { (i, arg) -> String in if let currFrameInt = currFrame as? Int64, Int(currFrameInt) == i { return self.composeCarrots(arg, Array(backtrace[1..<backtrace.count]))//self.composeCarrots(arg, backtrace[1..<backtrace.count]) } return self.composeTerm(arg) } var optargs = [String: String]() if term.count > 2, let dict = term[2] as? [String: Any] { for (k, v) in dict { if let currFrameKey = currFrame as? String, currFrameKey == k { optargs[k] = self.composeCarrots(v, Array(backtrace[1..<backtrace.count])) } else { optargs[k] = self.composeTerm(v) } } } return self.composeTerm(termType, args, optargs).characters.map({ (c: Character) -> String in return c != "^" ? " " : "^" }).joined() } func composeCarrots(_ term: Any, _ backtrace: [Any]) -> String { return "" } }
mit
84c6f102e93bb0d9540bf8a8a49b9d7a
33.522523
144
0.543319
4.234254
false
false
false
false
CD1212/Doughnut
Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeed.swift
2
8632
// // AtomFeed.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// Data model for the XML DOM of the Atom Specification /// See https://tools.ietf.org/html/rfc4287 /// /// The "atom:feed" element is the document (i.e., top-level) element of /// an Atom Feed Document, acting as a container for metadata and data /// associated with the feed. Its element children consist of metadata /// elements followed by zero or more atom:entry child elements. open class AtomFeed { /// The "atom:title" element is a Text construct that conveys a human- /// readable title for an entry or feed. public var title: String? /// The "atom:subtitle" element is a Text construct that conveys a human- /// readable description or subtitle for a feed. public var subtitle: AtomFeedSubtitle? /// The "atom:link" element defines a reference from an entry or feed to /// a Web resource. This specification assigns no meaning to the content /// (if any) of this element. public var links: [AtomFeedLink]? /// The "atom:updated" element is a Date construct indicating the most /// recent instant in time when an entry or feed was modified in a way /// the publisher considers significant. Therefore, not all /// modifications necessarily result in a changed atom:updated value. public var updated: Date? /// The "atom:category" element conveys information about a category /// associated with an entry or feed. This specification assigns no /// meaning to the content (if any) of this element. public var categories: [AtomFeedCategory]? /// The "atom:author" element is a Person construct that indicates the /// author of the entry or feed. /// /// If an atom:entry element does not contain atom:author elements, then /// the atom:author elements of the contained atom:source element are /// considered to apply. In an Atom Feed Document, the atom:author /// elements of the containing atom:feed element are considered to apply /// to the entry if there are no atom:author elements in the locations /// described above. public var authors: [AtomFeedAuthor]? /// The "atom:contributor" element is a Person construct that indicates a /// person or other entity who contributed to the entry or feed. public var contributors: [AtomFeedContributor]? /// The "atom:id" element conveys a permanent, universally unique /// identifier for an entry or feed. /// /// Its content MUST be an IRI, as defined by [RFC3987]. Note that the /// definition of "IRI" excludes relative references. Though the IRI /// might use a dereferencable scheme, Atom Processors MUST NOT assume it /// can be dereferenced. /// /// When an Atom Document is relocated, migrated, syndicated, /// republished, exported, or imported, the content of its atom:id /// element MUST NOT change. Put another way, an atom:id element /// pertains to all instantiations of a particular Atom entry or feed; /// revisions retain the same content in their atom:id elements. It is /// suggested that the atom:id element be stored along with the /// associated resource. /// /// The content of an atom:id element MUST be created in a way that /// assures uniqueness. /// /// Because of the risk of confusion between IRIs that would be /// equivalent if they were mapped to URIs and dereferenced, the /// following normalization strategy SHOULD be applied when generating /// atom:id elements: /// /// - Provide the scheme in lowercase characters. /// - Provide the host, if any, in lowercase characters. /// - Only perform percent-encoding where it is essential. /// - Use uppercase A through F characters when percent-encoding. /// - Prevent dot-segments from appearing in paths. /// - For schemes that define a default authority, use an empty /// authority if the default is desired. /// - For schemes that define an empty path to be equivalent to a path /// of "/", use "/". /// - For schemes that define a port, use an empty port if the default /// is desired. /// - Preserve empty fragment identifiers and queries. /// - Ensure that all components of the IRI are appropriately character /// normalized, e.g., by using NFC or NFKC. public var id: String? /// The "atom:generator" element's content identifies the agent used to /// generate a feed, for debugging and other purposes. /// /// The content of this element, when present, MUST be a string that is a /// human-readable name for the generating agent. Entities such as /// "&amp;" and "&lt;" represent their corresponding characters ("&" and /// "<" respectively), not markup. /// /// The atom:generator element MAY have a "uri" attribute whose value /// MUST be an IRI reference [RFC3987]. When dereferenced, the resulting /// URI (mapped from an IRI, if necessary) SHOULD produce a /// representation that is relevant to that agent. /// /// The atom:generator element MAY have a "version" attribute that /// indicates the version of the generating agent. public var generator: AtomFeedGenerator? /// The "atom:icon" element's content is an IRI reference [RFC3987] that /// identifies an image that provides iconic visual identification for a /// feed. /// /// The image SHOULD have an aspect ratio of one (horizontal) to one /// (vertical) and SHOULD be suitable for presentation at a small size. public var icon: String? /// The "atom:logo" element's content is an IRI reference [RFC3987] that /// identifies an image that provides visual identification for a feed. /// /// The image SHOULD have an aspect ratio of 2 (horizontal) to 1 /// (vertical). public var logo: String? /// The "atom:rights" element is a Text construct that conveys /// information about rights held in and over an entry or feed. /// /// The atom:rights element SHOULD NOT be used to convey machine-readable /// licensing information. /// /// If an atom:entry element does not contain an atom:rights element, /// then the atom:rights element of the containing atom:feed element, if /// present, is considered to apply to the entry. public var rights: String? /// The "atom:entry" element represents an individual entry, acting as a /// container for metadata and data associated with the entry. This /// element can appear as a child of the atom:feed element, or it can /// appear as the document (i.e., top-level) element of a stand-alone /// Atom Entry Document. public var entries: [AtomFeedEntry]? } // MARK: - Equatable extension AtomFeed: Equatable { public static func ==(lhs: AtomFeed, rhs: AtomFeed) -> Bool { return lhs.title == rhs.title && lhs.subtitle == rhs.subtitle && lhs.links == rhs.links && lhs.updated == rhs.updated && lhs.categories == rhs.categories && lhs.authors == rhs.authors && lhs.contributors == rhs.contributors && lhs.id == rhs.id && lhs.generator == rhs.generator && lhs.icon == rhs.icon && lhs.logo == rhs.logo && lhs.rights == rhs.rights && lhs.entries == rhs.entries } }
gpl-3.0
2c3994814e3abecf7cb33075a8573282
44.914894
82
0.673424
4.562368
false
false
false
false
ECLabs/CareerUp
CareerUp/SettingSelectTableViewController.swift
1
3117
import UIKit class SettingSelectTableViewController: UITableViewController { var selectedIndex = 0 var loadDelay:NSTimer? var loadedContent = -1; var eventArray:[Event] = [] override func viewDidLoad() { super.viewDidLoad() EventHandler.sharedInstance().get() } func reloadTable(timer: NSTimer){ let loadingCount = EventHandler.sharedInstance().loadingCount let reloaded = EventHandler.sharedInstance().reloaded if reloaded { loadedContent = -1 EventHandler.sharedInstance().reloaded = false } if loadedContent != 0 { println("load \(loadingCount)") self.tableView.reloadData() loadedContent = loadingCount loadDelay = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "reloadTable:", userInfo: nil, repeats: false) } else { loadDelay = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "reloadTable:", userInfo: nil, repeats: false) EventHandler.sharedInstance().count() } } override func viewWillDisappear(animated: Bool) { loadDelay?.invalidate() } override func viewDidAppear(animated: Bool) { loadDelay = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "reloadTable:", userInfo: nil, repeats: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func viewWillAppear(animated: Bool) { self.tableView.reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { eventArray = EventHandler.sharedInstance().events + EventHandler.sharedInstance().localEvents return eventArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell let setting = eventArray[indexPath.row] cell.textLabel.text = setting.name cell.detailTextLabel?.text = setting.details return cell } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { selectedIndex = indexPath.row as Int return indexPath } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let settingDetail: SettingsTableViewController = segue.destinationViewController as SettingsTableViewController let selectedEvent = eventArray[selectedIndex] settingDetail.eventSetting = selectedEvent } @IBAction func AddSettings(AnyObject) { let event = Event() event.name = "New Event" EventHandler.sharedInstance().save(event) self.tableView.reloadData() } }
mit
b2c1b1f889eae9c5a815aa6a08fbcdac
33.633333
138
0.66795
5.870056
false
false
false
false
somedev/DribbbleAPI
Sources/DribbbleAPI/Models/DBTeam.swift
1
2963
// // DBTeam.swift // DribbbleAPI // // Created by Eduard Panasiuk on 11/6/16. // Copyright © 2016 somedev. All rights reserved. // import Foundation public struct DBTeam { public let id: String public let name: String public let username: String public let htmlURL: URL? public let avatarUrl: URL? public let bio: String public let location: String public let links: [DBLink]? public let bucketsCount: UInt public let commentsReceivedCount: UInt public let followersCount: UInt public let followingsCount: UInt public let likesCount: UInt public let likesReceived_count: UInt public let projectsCount: UInt public let reboundsReceivedCount: UInt public let shotsСount: UInt public let canUpload: Bool public let type: String public let isPro: Bool public let created: Date public let updated: Date } // MARK: - custom initializer extension DBTeam { public init?(dictionary: [String: Any] = [:]) { guard let id: String = dictionary.JSONValueForKey("id") else { return nil } self.id = id name = dictionary.JSONValueForKey("name") ?? "" username = dictionary.JSONValueForKey("username") ?? "" avatarUrl = dictionary.JSONValueForKey("avatar_url") htmlURL = dictionary.JSONValueForKey("html_url") bio = dictionary.JSONValueForKey("bio") ?? "" location = dictionary.JSONValueForKey("location") ?? "" bucketsCount = dictionary.JSONValueForKey("buckets_count") ?? 0 commentsReceivedCount = dictionary.JSONValueForKey("comments_received_count") ?? 0 followersCount = dictionary.JSONValueForKey("followers_count") ?? 0 followingsCount = dictionary.JSONValueForKey("followings_count") ?? 0 likesCount = dictionary.JSONValueForKey("likes_count") ?? 0 likesReceived_count = dictionary.JSONValueForKey("likes_received_count") ?? 0 projectsCount = dictionary.JSONValueForKey("projects_count") ?? 0 reboundsReceivedCount = dictionary.JSONValueForKey("rebounds_received_count") ?? 0 shotsСount = dictionary.JSONValueForKey("shots_count") ?? 0 canUpload = dictionary.JSONValueForKey("can_upload_shot") ?? false type = dictionary.JSONValueForKey("type") ?? "" isPro = dictionary.JSONValueForKey("pro") ?? false created = dictionary.JSONValueForKey("created_at") ?? Date() updated = dictionary.JSONValueForKey("updated_at") ?? Date() if let linksDict = dictionary["links"] as? [String: String] { links = DBLink.links(from: linksDict) } else { links = nil } } } // MARK: - JSONValueType extension DBTeam: JSONValueType { public static func JSONValue(_ object: Any) -> DBTeam? { guard let dict = object as? [String: Any], let team = DBTeam(dictionary: dict) else { return nil } return team } }
mit
5bc7d46ca5d98f658dcfa8b846984413
35.54321
90
0.659797
4.683544
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/ToolboxSpec.swift
1
36917
// // ToolboxSpec.swift // SwiftyEcharts // // Created by Pluto Y on 13/08/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble @testable import SwiftyEcharts class ToolboxSpec: QuickSpec { override func spec() { describe("For Toolbox.Feature.SaveAsImage.Type") { let pngString = "png" let jpegString = "jpeg" let pngType = Toolbox.Feature.SaveAsImage.Type.png let jpegType = Toolbox.Feature.SaveAsImage.Type.jpeg it("needs to check the enum case jsonString") { expect(pngType.jsonString).to(equal(pngString.jsonString)) expect(jpegType.jsonString).to(equal(jpegString.jsonString)) } } let colorIconStyleContentValue = Color.rgba(128, 128, 128, 0.3) let borderColorIconStyleContentValue = Color.hexColor("#abcdef") let borderWidthIconStyleContentValue: Float = 8.427 let borderTypeIconStyleContentValue = LineType.solid let shadowBlurIconStyleContentValue: Float = 87234.23872 let shadowColorIconStyleContentValue = Color.array([Color.red, Color.hexColor("#2746ff"), Color.rgba(0, 0, 128, 0.77)]) let shadowOffsetXIconStyleContentValue: Float = 85.34874 let shadowOffsetYIconStyleContentValue: Float = 0.88873 let opacityIconStyleContentValue: Float = 0.74623 let textPositionIconStyleContentValue = Position.top let textAlignIconStyleContentValue = Align.right let iconStyleContent = Toolbox.IconStyleContent() iconStyleContent.color = colorIconStyleContentValue iconStyleContent.borderColor = borderColorIconStyleContentValue iconStyleContent.borderWidth = borderWidthIconStyleContentValue iconStyleContent.borderType = borderTypeIconStyleContentValue iconStyleContent.shadowBlur = shadowBlurIconStyleContentValue iconStyleContent.shadowColor = shadowColorIconStyleContentValue iconStyleContent.shadowOffsetX = shadowOffsetXIconStyleContentValue iconStyleContent.shadowOffsetY = shadowOffsetYIconStyleContentValue iconStyleContent.opacity = opacityIconStyleContentValue iconStyleContent.textPosition = textPositionIconStyleContentValue iconStyleContent.textAlign = textAlignIconStyleContentValue describe("For Toolbox.IconStyleContent") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "color": colorIconStyleContentValue, "borderColor": borderColorIconStyleContentValue, "borderWidth": borderWidthIconStyleContentValue, "borderType": borderTypeIconStyleContentValue, "shadowBlur": shadowBlurIconStyleContentValue, "shadowColor": shadowColorIconStyleContentValue, "shadowOffsetX": shadowOffsetXIconStyleContentValue, "shadowOffsetY": shadowOffsetYIconStyleContentValue, "opacity": opacityIconStyleContentValue, "textPosition": textPositionIconStyleContentValue, "textAlign": textAlignIconStyleContentValue ] expect(iconStyleContent.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let iconStyleContentByEnums = Toolbox.IconStyleContent( .color(colorIconStyleContentValue), .borderColor(borderColorIconStyleContentValue), .borderWidth(borderWidthIconStyleContentValue), .borderType(borderTypeIconStyleContentValue), .shadowBlur(shadowBlurIconStyleContentValue), .shadowColor(shadowColorIconStyleContentValue), .shadowOffsetX(shadowOffsetXIconStyleContentValue), .shadowOffsetY(shadowOffsetYIconStyleContentValue), .opacity(opacityIconStyleContentValue), .textPosition(textPositionIconStyleContentValue), .textAlign(textAlignIconStyleContentValue) ) expect(iconStyleContentByEnums.jsonString).to(equal(iconStyleContentByEnums.jsonString)) } } let normalIconStyleValue = iconStyleContent let emphasisIconStyleValue = Toolbox.IconStyleContent( .opacity(0.47623), .color(Color.yellow), .borderWidth(8745.28374), .textAlign(Align.left), .textPosition(Position.left) ) let iconStyle = Toolbox.IconStyle() iconStyle.normal = normalIconStyleValue iconStyle.emphasis = emphasisIconStyleValue describe("For IconStyle") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "normal": normalIconStyleValue, "emphasis": emphasisIconStyleValue ] expect(iconStyle.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let iconStyleByEnums = Toolbox.IconStyle( .normal(normalIconStyleValue), .emphasis(emphasisIconStyleValue) ) expect(iconStyleByEnums.jsonString).to(equal(iconStyle.jsonString)) } } let typeSaveAsImageValue = Toolbox.Feature.SaveAsImage.Type.jpeg let nameSaveAsImageValue = "saveAsImageNameValue" let backgroundColorSaveAsImageValue = Color.hexColor("#873abc") let excludeComponentsSaveAsImageValue: [String] = ["excludeComponent1", "excludeComponent2"] let showSaveAsImageValue = false let titleSaveAsImageValue = "saveAsImageTitleValue" let iconSaveAsImageValue = "saveAsImageIconValue" let iconStyleSaveAsImageValue = iconStyle let pixelRatioSaveAsImageValue: Float = 2 let saveAsImage = Toolbox.Feature.SaveAsImage() saveAsImage.type = typeSaveAsImageValue saveAsImage.name = nameSaveAsImageValue saveAsImage.backgroundColor = backgroundColorSaveAsImageValue saveAsImage.excludeComponents = excludeComponentsSaveAsImageValue saveAsImage.show = showSaveAsImageValue saveAsImage.title = titleSaveAsImageValue saveAsImage.icon = iconSaveAsImageValue saveAsImage.iconStyle = iconStyleSaveAsImageValue saveAsImage.pixelRatio = pixelRatioSaveAsImageValue describe("For Toolbox.Feature.SaveAsImage") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeSaveAsImageValue, "name": nameSaveAsImageValue, "backgroundColor": backgroundColorSaveAsImageValue, "excludeComponents": excludeComponentsSaveAsImageValue, "show": showSaveAsImageValue, "title": titleSaveAsImageValue, "icon": iconSaveAsImageValue, "iconStyle": iconStyleSaveAsImageValue, "pixelRatio": pixelRatioSaveAsImageValue ] expect(saveAsImage.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let saveAsImageByEnums = Toolbox.Feature.SaveAsImage( .type(typeSaveAsImageValue), .name(nameSaveAsImageValue), .backgroundColor(backgroundColorSaveAsImageValue), .excludeComponents(excludeComponentsSaveAsImageValue), .show(showSaveAsImageValue), .title(titleSaveAsImageValue), .icon(iconSaveAsImageValue), .iconStyle(iconStyleSaveAsImageValue), .pixelRatio(pixelRatioSaveAsImageValue) ) expect(saveAsImageByEnums.jsonString).to(equal(saveAsImage.jsonString)) } } let showRestoreValue = false let titleRestoreValue = "restoreTitleValue" let iconRestoreValue = "restoreIconValue" let iconStyleRestoreValue = Toolbox.IconStyle( .emphasis(Toolbox.IconStyleContent( .color(Color.hexColor("#77fba7")), .textPosition(Position.top), .shadowBlur(7.2736) )) ) let restore = Toolbox.Feature.Restore() restore.show = showRestoreValue restore.title = titleRestoreValue restore.icon = iconRestoreValue restore.iconStyle = iconStyleRestoreValue describe("For Toolbox.Feature.Restore") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showRestoreValue, "title": titleRestoreValue, "icon": iconRestoreValue, "iconStyle": iconStyleRestoreValue ] expect(restore.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let restoreByEnums = Toolbox.Feature.Restore( .show(showRestoreValue), .title(titleRestoreValue), .icon(iconRestoreValue), .iconStyle(iconStyleRestoreValue) ) expect(restoreByEnums.jsonString).to(equal(restore.jsonString)) } } let showDataViewValue = true let titleDataViewValue = "dataViewTitleValue" let iconDataViewValue = "dataViewIconValue" let iconStyleDataViewValue = Toolbox.IconStyle( .normal(Toolbox.IconStyleContent( .borderWidth(0.00001), .opacity(0.99999999), .shadowOffsetY(100.01), .shadowOffsetX(999.0001) )) ) let readOnlyDataViewValue = false let langDataViewValue: [String] = ["数据视图", "关闭", "刷新"] let backgroundColorDataViewValue = Color.array([Color.hexColor("#123abc"), Color.red, rgba(200, 19, 67, 0.888888)]) let textareaColorDataViewValue = Color.hexColor("#667788") let textareaBorderColorDataViewValue = Color.rgb(99, 100, 101) let textColorDataViewValue = Color.red let buttonColorDataViewValue = Color.auto let buttonTextColorDataViewValue = rgba(0, 0, 0, 0) let dataView = Toolbox.Feature.DataView() dataView.show = showDataViewValue dataView.title = titleDataViewValue dataView.icon = iconDataViewValue dataView.iconStyle = iconStyleDataViewValue dataView.readOnly = readOnlyDataViewValue dataView.lang = langDataViewValue dataView.backgroundColor = backgroundColorDataViewValue dataView.textareaColor = textareaColorDataViewValue dataView.textareaBorderColor = textareaBorderColorDataViewValue dataView.textColor = textColorDataViewValue dataView.buttonColor = buttonColorDataViewValue dataView.buttonTextColor = buttonTextColorDataViewValue describe("For ToolboxFeature.DataView") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showDataViewValue, "title": titleDataViewValue, "icon": iconDataViewValue, "iconStyle": iconStyleDataViewValue, "readOnly": readOnlyDataViewValue, "lang": langDataViewValue, "backgroundColor": backgroundColorDataViewValue, "textareaColor": textareaColorDataViewValue, "textareaBorderColor": textareaBorderColorDataViewValue, "textColor": textColorDataViewValue, "buttonColor": buttonColorDataViewValue, "buttonTextColor": buttonTextColorDataViewValue ] expect(dataView.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let dataViewByEnums = Toolbox.Feature.DataView( .show(showDataViewValue), .title(titleDataViewValue), .icon(iconDataViewValue), .iconStyle(iconStyleDataViewValue), .readOnly(readOnlyDataViewValue), .lang(langDataViewValue), .backgroundColor(backgroundColorDataViewValue), .textareaColor(textareaColorDataViewValue), .textareaBorderColor(textareaBorderColorDataViewValue), .textColor(textColorDataViewValue), .buttonColor(buttonColorDataViewValue), .buttonTextColor(buttonTextColorDataViewValue) ) expect(dataViewByEnums.jsonString).to(equal(dataView.jsonString)) } } describe("For Toolbox.Feature.DataZoom.AxisIndexSelector") { let trueValue = true let falseValue = false let allString = "all" let noneString = "none" let intValue: UInt = UInt.max let arrayValue: [UInt] = [UInt.min, 0, 255, 8, 89] let trueAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(trueValue) let falseAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(falseValue) let intAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.int(intValue) let arrayAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.array(arrayValue) it("needs to check the enum case jsonString") { expect(trueAxisIndexSelector.jsonString).to(equal(allString.jsonString)) expect(falseAxisIndexSelector.jsonString).to(equal(noneString.jsonString)) expect(intAxisIndexSelector.jsonString).to(equal(intValue.jsonString)) expect(arrayAxisIndexSelector.jsonString).to(equal(arrayValue.jsonString)) } it("needs to check the ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByArrayLiteral") { let trueLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = true let falseLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = false let intLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = 18446744073709551615 let arrayLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = [UInt.min, UInt(0), UInt(255), UInt(8), UInt(89)] expect(trueLiteral.jsonString).to(equal(trueAxisIndexSelector.jsonString)) expect(falseLiteral.jsonString).to(equal(falseAxisIndexSelector.jsonString)) expect(intLiteral.jsonString).to(equal(intAxisIndexSelector.jsonString)) expect(arrayLiteral.jsonString).to(equal(arrayAxisIndexSelector.jsonString)) } } let zoomTitleValue = "dataZoomTitleZoomValue" let backTitleValue = "dataZoomTitleBackValue" let title = Toolbox.Feature.DataZoom.Title() title.zoom = zoomTitleValue title.back = backTitleValue describe("For Toolbox.Feature.DataZoom.Title") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "zoom": zoomTitleValue, "back": backTitleValue ] expect(title.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let titleByEnums = Toolbox.Feature.DataZoom.Title( .zoom(zoomTitleValue), .back(backTitleValue) ) expect(titleByEnums.jsonString).to(equal(title.jsonString)) } } let zoomIconValue = "dataZoomIconZoomValue" let backIconValue = "dataZoomIconBackValue" let icon = Toolbox.Feature.DataZoom.Icon() icon.zoom = zoomIconValue icon.back = backIconValue describe("For Toolbox.Feature.DataZoom.Icon") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "zoom": zoomIconValue, "back": backIconValue ] expect(icon.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let iconByEnums = Toolbox.Feature.DataZoom.Icon( .zoom(zoomIconValue), .back(backIconValue) ) expect(iconByEnums.jsonString).to(equal(icon.jsonString)) } } let showDataZoomValue = false let titleDataZoomValue = title let iconDataZoomValue = icon let iconStyleDataZoomValue = Toolbox.IconStyle( .emphasis(Toolbox.IconStyleContent( .opacity(0.576), .color(Color.auto), .borderType(LineType.dashed) )) ) let xAxisIndexDataZoomValue = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(false) let yAxisIndexDataZoomValue = Toolbox.Feature.DataZoom.AxisIndexSelector.int(77) let dataZoom = Toolbox.Feature.DataZoom() dataZoom.show = showDataZoomValue dataZoom.title = titleDataZoomValue dataZoom.icon = iconDataZoomValue dataZoom.iconStyle = iconStyleDataZoomValue dataZoom.xAxisIndex = xAxisIndexDataZoomValue dataZoom.yAxisIndex = yAxisIndexDataZoomValue describe("For Toolbox.Feature.DataZoom") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showDataZoomValue, "title": titleDataZoomValue, "icon": iconDataZoomValue, "iconStyle": iconStyleDataZoomValue, "xAxisIndex": xAxisIndexDataZoomValue, "yAxisIndex": yAxisIndexDataZoomValue ] expect(dataZoom.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let dataZoomByEnums = Toolbox.Feature.DataZoom( .show(showDataZoomValue), .title(titleDataZoomValue), .icon(iconDataZoomValue), .iconStyle(iconStyleDataZoomValue), .xAxisIndex(xAxisIndexDataZoomValue), .yAxisIndex(yAxisIndexDataZoomValue) ) expect(dataZoomByEnums.jsonString).to(equal(dataZoom.jsonString)) } } describe("For Toolbox.Feature.MagicType.Type") { let lineString = "line" let barString = "bar" let stackString = "stack" let tiledString = "tiled" let lineType = Toolbox.Feature.MagicType.Type.line let barType = Toolbox.Feature.MagicType.Type.bar let stackType = Toolbox.Feature.MagicType.Type.stack let tiledType = Toolbox.Feature.MagicType.Type.tiled it("needs to check the enum case jsonString") { expect(lineType.jsonString).to(equal(lineString.jsonString)) expect(barType.jsonString).to(equal(barString.jsonString)) expect(stackType.jsonString).to(equal(stackString.jsonString)) expect(tiledType.jsonString).to(equal(tiledString.jsonString)) } } let lineTitleValue = "magicTypeTitleLineValue" let barTitleValue = "magicTypeTitleBarValue" let stackTitleValue = "magicTypeTitleStatckValue" let tiledTitleValue = "magicTypeTitleTiledValue" let magicTypeTitle = Toolbox.Feature.MagicType.Title() magicTypeTitle.line = lineTitleValue magicTypeTitle.bar = barTitleValue magicTypeTitle.stack = stackTitleValue magicTypeTitle.tiled = tiledTitleValue describe("For Toolbox.Feature.MagicType.Title") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "line": lineTitleValue, "bar": barTitleValue, "stack": stackTitleValue, "tiled": tiledTitleValue ] expect(magicTypeTitle.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let magicTypeTitleByEnums = Toolbox.Feature.MagicType.Title( .line(lineTitleValue), .bar(barTitleValue), .stack(stackTitleValue), .tiled(tiledTitleValue) ) expect(magicTypeTitleByEnums.jsonString).to(equal(magicTypeTitle.jsonString)) } } let lineIconValue = "magicTypeIconLineValue" let barIconValue = "magicTypeIconBarValue" let stackIconValue = "magicTypeIconStatckValue" let tiledIconValue = "magicTypeIconTiledValue" let magicTypeIcon = Toolbox.Feature.MagicType.Icon() magicTypeIcon.line = lineIconValue magicTypeIcon.bar = barIconValue magicTypeIcon.stack = stackIconValue magicTypeIcon.tiled = tiledIconValue describe("For Toolbox.Feature.MagicType.Icon") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "line": lineIconValue, "bar": barIconValue, "stack": stackIconValue, "tiled": tiledIconValue ] expect(magicTypeIcon.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let magicTypeIconByEnums = Toolbox.Feature.MagicType.Icon( .line(lineIconValue), .bar(barIconValue), .stack(stackIconValue), .tiled(tiledIconValue) ) expect(magicTypeIconByEnums.jsonString).to(equal(magicTypeIcon.jsonString)) } } let showMagicTypeValue = true let typeMagicTypeValue = [Toolbox.Feature.MagicType.Type.line, Toolbox.Feature.MagicType.Type.bar, Toolbox.Feature.MagicType.Type.stack, Toolbox.Feature.MagicType.Type.tiled] let titleMagicTypeValue = magicTypeTitle let iconMaigcTypeValue = magicTypeIcon let magicType = Toolbox.Feature.MagicType() magicType.show = showMagicTypeValue magicType.type = typeMagicTypeValue magicType.title = titleMagicTypeValue magicType.icon = iconMaigcTypeValue describe("For Toolbox.Feature.MagicType") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showMagicTypeValue, "type": typeMagicTypeValue, "title": titleMagicTypeValue, "icon": iconMaigcTypeValue ] expect(magicType.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let magicTypeByEnums = Toolbox.Feature.MagicType( .show(showMagicTypeValue), .type(typeMagicTypeValue), .title(titleMagicTypeValue), .icon(iconMaigcTypeValue) ) expect(magicTypeByEnums.jsonString).to(equal(magicType.jsonString)) } } describe("For Toolbox.Feature.Brush.Type") { let rectString = "rect" let polygonString = "polygon" let lineXString = "lineX" let lineYString = "lineY" let keepString = "keep" let clearString = "clear" let rectBrush = Toolbox.Feature.Brush.Type.rect let polygonBrush = Toolbox.Feature.Brush.Type.polygon let lineXBrush = Toolbox.Feature.Brush.Type.lineX let lineYBrush = Toolbox.Feature.Brush.Type.lineY let keepBrush = Toolbox.Feature.Brush.Type.keep let clearBrush = Toolbox.Feature.Brush.Type.clear it("needs to check enum case jsonString") { expect(rectBrush.jsonString).to(equal(rectString.jsonString)) expect(polygonBrush.jsonString).to(equal(polygonString.jsonString)) expect(lineXBrush.jsonString).to(equal(lineXString.jsonString)) expect(lineYBrush.jsonString).to(equal(lineYString.jsonString)) expect(keepBrush.jsonString).to(equal(keepString.jsonString)) expect(clearBrush.jsonString).to(equal(clearString.jsonString)) } } let rectBrushIconValue = "brushIconRectValue" let polygonBrushIconValue = "brushIconPolygonValue" let lineXBrushIconValue = "brushIconLineXValue" let lineYBrushIconValue = "brushIconLineYValue" let keepBrushIconValue = "brushIconKeepValue" let clearBrushIconValue = "brushIconClearValue" let brushIcon = Toolbox.Feature.Brush.Icon() brushIcon.rect = rectBrushIconValue brushIcon.polygon = polygonBrushIconValue brushIcon.lineX = lineXBrushIconValue brushIcon.lineY = lineYBrushIconValue brushIcon.keep = keepBrushIconValue brushIcon.clear = clearBrushIconValue describe("For Toolbox.Feature.Brush.Icon") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "rect": rectBrushIconValue, "polygon": polygonBrushIconValue, "lineX": lineXBrushIconValue, "lineY": lineYBrushIconValue, "keep": keepBrushIconValue, "clear": clearBrushIconValue ] expect(brushIcon.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let brushIconByEnums = Toolbox.Feature.Brush.Icon( .rect(rectBrushIconValue), .polygon(polygonBrushIconValue), .lineX(lineXBrushIconValue), .lineY(lineYBrushIconValue), .keep(keepBrushIconValue), .clear(clearBrushIconValue) ) expect(brushIconByEnums.jsonString).to(equal(brushIcon.jsonString)) } } let rectBrushTitleValue = "brushTitleRectValue" let polygonBrushTitleValue = "brushTitlePolygonValue" let lineXBrushTitleValue = "brushTitleLineXValue" let lineYBrushTitleValue = "brushTitleLineYValue" let keepBrushTitleValue = "brushTitleKeepValue" let clearBrushTitleValue = "brushTitleClearValue" let brushTitle = Toolbox.Feature.Brush.Title() brushTitle.rect = rectBrushTitleValue brushTitle.polygon = polygonBrushTitleValue brushTitle.lineX = lineXBrushTitleValue brushTitle.lineY = lineYBrushTitleValue brushTitle.keep = keepBrushTitleValue brushTitle.clear = clearBrushTitleValue describe("For Toolbox.Feature.Brush.Title") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "rect": rectBrushTitleValue, "polygon": polygonBrushTitleValue, "lineX": lineXBrushTitleValue, "lineY": lineYBrushTitleValue, "keep": keepBrushTitleValue, "clear": clearBrushTitleValue ] expect(brushTitle.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let brushTitleByEnums = Toolbox.Feature.Brush.Title( .rect(rectBrushTitleValue), .polygon(polygonBrushTitleValue), .lineX(lineXBrushTitleValue), .lineY(lineYBrushTitleValue), .keep(keepBrushTitleValue), .clear(clearBrushTitleValue) ) expect(brushTitleByEnums.jsonString).to(equal(brushTitle.jsonString)) } } let typeBrushValue = [Toolbox.Feature.Brush.Type.rect, Toolbox.Feature.Brush.Type.polygon, Toolbox.Feature.Brush.Type.lineX, Toolbox.Feature.Brush.Type.lineY, Toolbox.Feature.Brush.Type.keep, Toolbox.Feature.Brush.Type.clear] let iconBrushValue = brushIcon let titleBrushValue = brushTitle let brush = Toolbox.Feature.Brush() brush.type = typeBrushValue brush.icon = iconBrushValue brush.title = titleBrushValue describe("For Toolbox.Feature.Brush") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeBrushValue, "icon": iconBrushValue, "title": titleBrushValue ] expect(brush.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let brushByEnums = Toolbox.Feature.Brush( .type(typeBrushValue), .icon(iconBrushValue), .title(titleBrushValue) ) expect(brushByEnums.jsonString).to(equal(brush.jsonString)) } } let saveAsImageFeatureValue = saveAsImage let restoreFeatureValue = restore let dataViewFeatureValue = dataView let dataZoomFeatureValue = dataZoom let magicTypeFeatureValue = magicType let brushFeatureValue = brush let feature = Toolbox.Feature() feature.saveAsImage = saveAsImageFeatureValue feature.restore = restoreFeatureValue feature.dataView = dataViewFeatureValue feature.dataZoom = dataZoomFeatureValue feature.magicType = magicTypeFeatureValue feature.brush = brushFeatureValue describe("For Toolbox.Feature") { it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "saveAsImage": saveAsImageFeatureValue, "restore": restoreFeatureValue, "dataView": dataViewFeatureValue, "dataZoom": dataZoomFeatureValue, "magicType": magicTypeFeatureValue, "brush": brushFeatureValue ] expect(feature.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let featureByEnums = Toolbox.Feature( .saveAsImage(saveAsImageFeatureValue), .restore(restoreFeatureValue), .dataView(dataViewFeatureValue), .dataZoom(dataZoomFeatureValue), .magicType(magicTypeFeatureValue), .brush(brushFeatureValue) ) expect(featureByEnums.jsonString).to(equal(feature.jsonString)) } } describe("For Toolbox") { let showValue = false let orientValue = Orient.vertical let itemSizeValue: Float = 0.57236 let itemGapValue: Float = 85.347 let showTitleValue = true let featureValue = feature let iconStyleValue = Toolbox.IconStyle() let zlevelValue: Float = 10 let zValue: Float = -1 let leftValue = Position.right let rightValue = Position.left let topValue = Position.bottom let bottomValue = Position.top let widthValue: Float = 100 let heightValue: Float = 8.34764 let toolbox = Toolbox() toolbox.show = showValue toolbox.orient = orientValue toolbox.itemSize = itemSizeValue toolbox.itemGap = itemGapValue toolbox.showTitle = showTitleValue toolbox.feature = featureValue toolbox.iconStyle = iconStyleValue toolbox.zlevel = zlevelValue toolbox.z = zValue toolbox.left = leftValue toolbox.top = topValue toolbox.right = rightValue toolbox.bottom = bottomValue toolbox.width = widthValue toolbox.height = heightValue it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "show": showValue, "orient": orientValue, "itemSize": itemSizeValue, "itemGap": itemGapValue, "showTitle": showTitleValue, "feature": featureValue, "iconStyle": iconStyleValue, "zlevel": zlevelValue, "z": zValue, "left": leftValue, "top": topValue, "right": rightValue, "bottom": bottomValue, "width": widthValue, "height": heightValue ] expect(toolbox.jsonString).to(equal(resultDic.jsonString)) } it("needs to check the Enumable") { let toolboxByEnums = Toolbox( .show(showValue), .orient(orientValue), .itemSize(itemSizeValue), .itemGap(itemGapValue), .showTitle(showTitleValue), .feature(featureValue), .iconStyle(iconStyleValue), .zlevel(zlevelValue), .z(zValue), .left(leftValue), .top(topValue), .right(rightValue), .bottom(bottomValue), .width(widthValue), .height(heightValue) ) expect(toolboxByEnums.jsonString).to(equal(toolbox.jsonString)) } } context("For the action of Toolbox") { describe("For ToolboxRestoreAction") { let typeValue = EchartsActionType.restore let restoreAction = ToolboxRestoreAction() it("needs to check the typeValue") { expect(restoreAction.type.jsonString).to(equal(typeValue.jsonString)) } it("needs to check the jsonString") { let resultDic: [String: Jsonable] = [ "type": typeValue ] expect(restoreAction.jsonString).to(equal(resultDic.jsonString)) } } } } }
mit
744f1880cd2bef74775b8d3fd7fc2d72
42.720379
233
0.566965
6.134663
false
false
false
false
KazmaStudio/Feeding
CODE/iOS/Feeding/Feeding/ArticleListModel.swift
1
668
// // ArticleListModel.swift // Feeding // // Created by zhaochenjun on 2017/5/8. // Copyright © 2017年 com.kazmastudio. All rights reserved. // import Foundation class ArticleListModel: NSObject { var articleType: String = CELL_ARTICLE_LIST_TYPE_A var imageList: Array<String> = [] var title: String = STRING_EMPTY var authorInfo: AuthorInfoModel = AuthorInfoModel() var targeted = false override func setValue(_ value: Any?, forUndefinedKey key: String) { } override init() { super.init() } init(dict: [String: AnyObject]) { super.init() self.setValuesForKeys(dict) } }
mit
9324a889149c5d6ef8dacd4921d5784c
21.166667
72
0.634586
3.843931
false
false
false
false
attackFromCat/LivingTVDemo
LivingTVDemo/LivingTVDemo/Classes/Home/Controller/GameViewController.swift
1
4966
// // GameViewController.swift // LivingTVDemo // // Created by 李翔 on 2017/1/9. // Copyright © 2017年 Lee Xiang. All rights reserved. // import UIKit private let kEdgeMargin : CGFloat = 10 private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3 private let kItemH : CGFloat = kItemW * 6 / 5 private let kHeaderViewH : CGFloat = 50 private let kGameViewH : CGFloat = 90 private let kGameCellID = "kGameCellID" private let kHeaderViewID = "kHeaderViewID" class GameViewController: LoadingViewController { // MARK: 懒加载属性 fileprivate lazy var gameVM : GameViewModel = GameViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.dataSource = self return collectionView }() fileprivate lazy var topHeaderView : CollectionHeaderView = { let headerView = CollectionHeaderView.collectionHeaderView() headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH) headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.titleLabel.text = "常见" headerView.moreBtn.isHidden = true return headerView }() fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK:- 设置UI界面 extension GameViewController { override func setupUI() { // 0.给ContentView进行赋值 contentView = collectionView // 1.添加UICollectionView view.addSubview(collectionView) // 2.添加顶部的HeaderView collectionView.addSubview(topHeaderView) // 3.将常用游戏的View,添加到collectionView中 collectionView.addSubview(gameView) // 设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0) super.setupUI() } } // MARK:- 请求数据 extension GameViewController { fileprivate func loadData() { gameVM.loadAllGameData { // 1.展示全部游戏 self.collectionView.reloadData() // 2.展示常用游戏 self.gameView.groups = Array(self.gameVM.games[0..<10]) // 3.数据请求完成 self.loadDataFinished() } } } // MARK:- 遵守UICollectionView的数据源&代理 extension GameViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.games.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = gameVM.games[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给HeaderView设置属性 headerView.titleLabel.text = "全部" headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.moreBtn.isHidden = true return headerView } }
mit
368a2c4f0a3d95b20dc7777aa746888c
34.4
186
0.673153
5.43686
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/NSPredicate.swift
1
856
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSPredicate { // + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; public convenience init(format predicateFormat: __shared String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: predicateFormat, arguments: va_args) } }
apache-2.0
99dd4174f9af8439d08f16d1b3a5de8e
37.909091
81
0.589953
5.095238
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
chapter-26/silver-challenge/VocalTextEdit/VocalTextEdit/Document.swift
1
1840
// // Document.swift // VocalTextEdit // // Created by Hans Yelek on 1/28/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import Cocoa class Document: NSDocument { var contents: String = "" override class func autosavesInPlace() -> Bool { return true } override func makeWindowControllers() { // Returns the Storyboard that contains your Document window. let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController let viewController = windowController.contentViewController as! ViewController viewController.contents = contents self.addWindowController(windowController) } override func dataOfType(typeName: String) throws -> NSData { let windowController = windowControllers[0] let viewController = windowController.contentViewController as! ViewController let contents = viewController.contents ?? "" if let data = contents.dataUsingEncoding(NSUTF8StringEncoding) { return data } else { let userInfo = [NSLocalizedRecoverySuggestionErrorKey: "File cannot be encoded in UTF-8."] throw NSError(domain: "com.hny.VocalTextEdit", code: 0, userInfo: userInfo) } } override func readFromData(data: NSData, ofType typeName: String) throws { if let contents = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { self.contents = contents } else { let userInfo = [NSLocalizedRecoverySuggestionErrorKey: "File is not valid UTF-8."] throw NSError(domain: "com.hny.VocalTextEdit", code: 0, userInfo: userInfo) } } }
mit
5d6c061b531ad77123dfec759d66ebf3
33.698113
130
0.663404
5.239316
false
false
false
false
anzfactory/TwitterClientCLI
Sources/TwitterClientCore/APIType/SearchTweetType.swift
1
1031
// // SearchTweetType.swift // Spectre // // Created by shingo asato on 2017/09/21. // import Foundation import APIKit struct SearchTweetType: TwitterAPIType { typealias Response = SearchTweets var oauth: TwitterOAuth var q: String var count: Int = 30 var sinceId: Int? var maxId: Int? var method: HTTPMethod { return .get } var path: String { return "/1.1/search/tweets.json" } var parameters: Any? { var params: [String: Any] = ["q": self.q, "count": self.count] if let sinceId = self.sinceId, sinceId > 0 { params["since_id"] = sinceId } if let maxId = self.maxId, maxId > 0 { params["max_id"] = maxId } return params } var queryParameters: [String : Any]? { return self.parameters as? [String: Any] } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> SearchTweets { return try SearchTweets(object) } }
mit
427476d49b9887178d094283afcaeb81
20.93617
90
0.57517
3.87594
false
false
false
false
hughbe/ui-components
src/Bordered/SideBorderedView.swift
1
1231
// // SideBorderedView.swift // UIComponents // // Created by Hugh Bellamy on 14/06/2015. // Copyright (c) 2015 Hugh Bellamy. All rights reserved. // @IBDesignable public class SideBorderedView: UIView { @IBInspectable public var borderWidth: CGFloat = 0 @IBInspectable public var borderColor: UIColor = UIColor.blackColor() @IBInspectable public var showsTopBorder: Bool = false @IBInspectable public var showsBottomBorder: Bool = false @IBInspectable public var showsLeftBorder: Bool = false @IBInspectable public var showsRightBorder: Bool = false public override func awakeFromNib() { super.awakeFromNib() if (showsTopBorder || showsBottomBorder || showsLeftBorder || showsRightBorder) && borderWidth == 0 { borderWidth = 1 } if showsTopBorder { addTopBorder(borderWidth, color: borderColor) } if showsBottomBorder { addBottomBorder(borderWidth, color: borderColor) } if showsLeftBorder { addLeftBorder(borderWidth, color: borderColor) } if showsRightBorder { addRightBorder(borderWidth, color: borderColor) } } }
mit
c57d94b6fed204a1b32c37339f756de5
31.394737
109
0.65069
5.129167
false
false
false
false
CMP-Studio/TheWarholOutLoud
ios/CMSBeaconManager.swift
2
5951
// // CMSBeaconManager.swift // AndyWarholAccessibilityProject // // Created by Ruben Niculcea on 5/24/16. // Copyright © 2016 Carnegie Museums of Pittsburgh Innovation Studio. // All rights reserved. // import Foundation enum CMSBeaconManagerEvents:String { case BeaconManagerBeaconPing case BluetoothStatusChanged case LocationServicesAllowedChanged } enum CMSBeaconManagerLocationServicesStatus:String { case NotDetermined = "LOCATION_SERVICES_STATUS_NOTDETERMINED" case Denied = "LOCATION_SERVICES_STATUS_DENIED" case Authorized = "LOCATION_SERVICES_STATUS_AUTHORIZED" } @objc(CMSBeaconManager) class CMSBeaconManager: RCTEventEmitter { var beaconManager = ESTBeaconManager() var beaconRegion:CLBeaconRegion? var locationManager: CLLocationManager! var bluetoothPeripheralManager: CBPeripheralManager? var jsResolveCallback:RCTPromiseResolveBlock? var jsRejectCallback:RCTPromiseRejectBlock? override init() { super.init() beaconManager.delegate = self beaconManager.avoidUnknownStateBeacons = true } override func constantsToExport() -> [String: Any] { let BeaconManagerBeaconPing = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue let BluetoothStatusChanged = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue let LocationServicesAllowedChanged = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue return [ "Events": [ BeaconManagerBeaconPing: BeaconManagerBeaconPing, BluetoothStatusChanged: BluetoothStatusChanged, LocationServicesAllowedChanged: LocationServicesAllowedChanged, ] ] } override func supportedEvents() -> [String] { let BeaconManagerBeaconPing = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue let BluetoothStatusChanged = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue let LocationServicesAllowedChanged = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue return [ BeaconManagerBeaconPing, BluetoothStatusChanged, LocationServicesAllowedChanged, ] } @objc func beginBluetoothAndLocationServicesEvents() { let options = [CBCentralManagerOptionShowPowerAlertKey: 0] // Don't show bluetooth popover bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options) self.locationManager = CLLocationManager() self.locationManager.delegate = self } @objc func requestLocationServicesAuthorization() { locationManager.requestWhenInUseAuthorization() } @objc func startTracking(_ uuid: String, identifier: String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) { if let nsuuid = UUID(uuidString: uuid) { beaconRegion = CLBeaconRegion(proximityUUID: nsuuid, identifier: identifier) if beaconManager.rangedRegions.contains(beaconRegion!) { resolve(nil) return } jsRejectCallback = reject jsResolveCallback = resolve beaconManager.startRangingBeacons(in: beaconRegion!) } else { reject("Beacon Scanning failed", "uuidString is invalid", nil) } } @objc func stopTracking() { if let _beaconRegion = beaconRegion { beaconManager.stopRangingBeacons(in: _beaconRegion) } } func clearJSCallbacks() { jsResolveCallback = nil jsRejectCallback = nil } } extension CMSBeaconManager: ESTBeaconManagerDelegate { func beaconManager(_ manager: Any, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { if let resolve = jsResolveCallback { clearJSCallbacks() resolve(nil) } var beaconsJSON = [String]() for beacon in beacons { beaconsJSON.append("\(beacon.major):\(beacon.minor)") } let eventName = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue self.sendEvent(withName: eventName, body: beaconsJSON) } func beaconManager(_ manager: Any, rangingBeaconsDidFailFor region: CLBeaconRegion?, withError error: Error) { if let reject = jsRejectCallback { clearJSCallbacks() reject("Beacon Scanning failed", error.localizedDescription, nil) } } } extension CMSBeaconManager: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { var bluetoothActive = false switch peripheral.state { case .unknown, .resetting, .poweredOff: bluetoothActive = false case .unsupported: // This is never hit as every modern iOS device has bluetooth break case .unauthorized: // This is never hit as we only use bluetooth for location break case .poweredOn: bluetoothActive = true } sendBluetoothStatusEvent(bluetoothActive) } func sendBluetoothStatusEvent(_ bluetoothOn: Bool) { let eventName = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue self.sendEvent(withName: eventName, body: ["bluetoothOn": bluetoothOn]) } } extension CMSBeaconManager: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { let locationServicesStatus:CMSBeaconManagerLocationServicesStatus switch status { case .notDetermined: locationServicesStatus = .NotDetermined case .restricted, .denied: locationServicesStatus = .Denied case .authorizedAlways, .authorizedWhenInUse: locationServicesStatus = .Authorized } sendLocationServicesEvent(locationServicesStatus) } func sendLocationServicesEvent(_ status: CMSBeaconManagerLocationServicesStatus) { let eventName = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue self.sendEvent(withName: eventName, body: ["locationServicesStatus": status.rawValue]) } }
mit
ed88198b69a7cb230d177123a6878d59
30.989247
112
0.73395
5.672069
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/Common/PaintArtwork.swift
1
3853
// // PaintArtwork.swift // SwiftGL // // Created by jerry on 2015/5/21. // Copyright (c) 2015年 Jerry Chan. All rights reserved. // enum ArtworkType:String{ case Artwork = "Artwork" case Tutorial = "Tutorial" case Trace = "Trace" } import Foundation import GLFramework class PaintArtwork { var artworkType:ArtworkType = .Artwork var canvasWidth:Int var canvasHeight:Int fileprivate var _masterClip:PaintClip fileprivate var _revisionClips:[Int:PaintClip] = [Int:PaintClip]() var revisionClips:[Int:PaintClip]{ get{ return _revisionClips } } var lastClip:PaintClip var currentClip:PaintClip { willSet(newClip) { if newClip != currentClip { lastClip = currentClip //unbind the stroke change event if the clip has changed //newClip.onStrokeIDChanged = currentClip.onStrokeIDChanged //currentClip.onStrokeIDChanged = nil } } } var currentRevisionID:Int! var isFileExist:Bool = false var currentNoteIndex:Int = 0 var currentNote:SANote! init(width:Int,height:Int) { _masterClip = PaintClip(name: "master",branchAt: 0) _masterClip.currentTime = 0 currentClip = _masterClip lastClip = currentClip canvasWidth = width canvasHeight = height } func setReplayer(_ paintView:PaintView,type:ArtworkType = .Artwork) { self.artworkType = type var buffer:GLContextBuffer = paintView.paintBuffer if type == .Tutorial { buffer = paintView.tutorialBuffer } else if type == .Trace { buffer = paintView.tutorialBuffer } masterReplayer = PaintReplayer(paintView:paintView,context: buffer) revisionReplayer = PaintReplayer(paintView:paintView,context: buffer) currentReplayer = masterReplayer } func setUpClips() { masterReplayer.loadClip(_masterClip) } func drawAll() { masterReplayer.drawAll() } func drawClip(_ clip:PaintClip) { _masterClip = clip masterReplayer.loadClip(clip) masterReplayer.drawAll() } func setArtworkMode() { } func loadCurrentClip() { masterReplayer.loadClip(currentClip) currentReplayer = masterReplayer } func loadClip(_ clip:PaintClip) { currentClip = clip masterReplayer.loadClip(clip) revisionReplayer.stopPlay() currentReplayer = masterReplayer masterReplayer.drawAll() } func loadMasterClip() { currentClip = _masterClip masterReplayer.loadClip(_masterClip) revisionReplayer.stopPlay() currentReplayer = masterReplayer } func loadCurrentRevisionClip() { loadRevisionClip(currentRevisionID) } func loadRevisionClip(_ stroke:Int) { currentRevisionID = stroke revisionReplayer.loadClip(_revisionClips[stroke]!) masterReplayer.pause() currentReplayer = revisionReplayer } func useClip(_ clip:PaintClip)->PaintClip { currentClip = clip return currentClip } func useMasterClip()->PaintClip { return useClip(_masterClip) } func useRevisionClip(_ id:Int)->PaintClip { return useClip(revisionClips[id]!) } func addRevisionClip(_ atStroke:Int) { let newClip = PaintClip(name: "revision",branchAt: atStroke) //newClip.strokeDelegate = _masterClip.strokeDelegate _revisionClips[atStroke] = newClip } var masterReplayer:PaintReplayer! var revisionReplayer:PaintReplayer! var currentReplayer:PaintReplayer! }
mit
3cbfb7e6119ef8eb720deb770c91fa92
25.197279
77
0.618541
4.80774
false
false
false
false
lanserxt/teamwork-ios-sdk
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Permissions.swift
1
8669
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func addNewUserToProject(projectId: String, peopleId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addNewUserToProject.path, projectId, peopleId), method: HTTPMethod.post, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.addNewUserToProject.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func addNewUsers(projectId: String, parameters: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addNewUsers.path, projectId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.addNewUsers.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteUserFromProject(projectId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteUserFromProject.path, projectId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteUserFromProject.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } //CHECK that multiple response func getUserPermissions(projectId: String, peopleId: String, _ responseBlock: @escaping (Bool, Int, [PersonDetails]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getUserPermissions.path, projectId, peopleId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<PersonDetails>.init(rootObjectName: TWApiClientConstants.APIPath.getUserPermissions.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func updateUserPermissions(personId: String, peopleId: String, permissions: [String : Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["permissions" : permissions] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateUserPermissions.path, personId, peopleId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<PersonDetails>.init(rootObjectName: TWApiClientConstants.APIPath.updateUserPermissions.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } }
mit
4b0c2363a627bff698f1230b137c6eed
51.853659
227
0.538071
6.187009
false
false
false
false
DataBreweryIncubator/StructuredQuery
Sources/Types/Signature.swift
1
1267
public class FunctionSignature: CustomStringConvertible { public let arguments: [DataType] public let returnType: DataType public init(arguments: [DataType], returnType: DataType) { self.arguments = arguments self.returnType = returnType } // TODO: Variadic matching is not supported yet public func matches(arguments: [DataType]) -> Bool { if arguments.count != self.arguments.count { return false } else { return self.arguments.elementsEqual(arguments) { (this, other) in this == DataType.ANY || this == other } } } public var description: String { let strings = arguments.map { $0.description } let fullString = strings.joined(separator:", ") return "[\(fullString)] -> \(returnType.description)" } } infix operator |^|: AdditionPrecedence public func |^|(lhs: DataType, rhs: DataType) -> FunctionSignature { return FunctionSignature( arguments: [lhs], returnType: rhs ) } public func |^|(lhs: (DataType, DataType), rhs: DataType) -> FunctionSignature { return FunctionSignature( arguments: [lhs.0, lhs.1], returnType: rhs ) }
mit
d3fbe655ee2c5c13fbe826d2fcaffe5b
25.957447
80
0.603788
4.854406
false
false
false
false
JBerendes/react-native-video-processing
ios/RNVideoProcessing/RNTrimmerView/RNTrimmerView.swift
1
6948
// // RNTrimmerView.swift // RNVideoProcessing // import UIKit import AVKit @objc(RNTrimmerView) class RNTrimmerView: RCTView, ICGVideoTrimmerDelegate { var trimmerView: ICGVideoTrimmerView? var asset: AVAsset! var rect: CGRect = CGRect.zero var mThemeColor = UIColor.clear var bridge: RCTBridge! var onChange: RCTBubblingEventBlock? var onTrackerMove: RCTBubblingEventBlock? var _minLength: CGFloat? = nil var _maxLength: CGFloat? = nil var _thumbWidth: CGFloat? = nil var _trackerColor: UIColor = UIColor.clear var _trackerHandleColor: UIColor = UIColor.clear var _showTrackerHandle = false var source: NSString? { set { setSource(source: newValue) } get { return nil } } var showTrackerHandle: NSNumber? { set { if newValue == nil { return } let _nVal = newValue! == 1 ? true : false if _showTrackerHandle != _nVal { print("CHANGED: showTrackerHandle \(newValue!)"); _showTrackerHandle = _nVal self.updateView() } } get { return nil } } var trackerHandleColor: NSString? { set { if newValue != nil { let color = NumberFormatter().number(from: newValue! as String) let formattedColor = RCTConvert.uiColor(color) if formattedColor != nil { print("CHANGED: trackerHandleColor: \(newValue!)") self._trackerHandleColor = formattedColor! self.updateView(); } } } get { return nil } } var height: NSNumber? { set { self.rect.size.height = RCTConvert.cgFloat(newValue) + 40 self.updateView() } get { return nil } } var width: NSNumber? { set { self.rect.size.width = RCTConvert.cgFloat(newValue) self.updateView() } get { return nil } } var themeColor: NSString? { set { if newValue != nil { let color = NumberFormatter().number(from: newValue! as String) self.mThemeColor = RCTConvert.uiColor(color) self.updateView() } } get { return nil } } var maxLength: NSNumber? { set { if newValue != nil { self._maxLength = RCTConvert.cgFloat(newValue!) self.updateView() } } get { return nil } } var minLength: NSNumber? { set { if newValue != nil { self._minLength = RCTConvert.cgFloat(newValue!) self.updateView() } } get { return nil } } var thumbWidth: NSNumber? { set { if newValue != nil { self._thumbWidth = RCTConvert.cgFloat(newValue!) self.updateView() } } get { return nil } } var currentTime: NSNumber? { set { print("CHANGED: [TrimmerView]: currentTime: \(newValue)") if newValue != nil && self.trimmerView != nil { let convertedValue = newValue as! CGFloat self.trimmerView?.seek(toTime: convertedValue) // self.trimmerView } } get { return nil } } var trackerColor: NSString? { set { if newValue == nil { return } print("CHANGED: trackerColor \(newValue!)") let color = NumberFormatter().number(from: newValue! as String) let formattedColor = RCTConvert.uiColor(color) if formattedColor != nil { self._trackerColor = formattedColor! self.updateView() } } get { return nil } } func updateView() { self.frame = rect if trimmerView != nil { trimmerView!.frame = rect trimmerView!.themeColor = self.mThemeColor trimmerView!.trackerColor = self._trackerColor trimmerView!.trackerHandleColor = self._trackerHandleColor trimmerView!.showTrackerHandle = self._showTrackerHandle trimmerView!.maxLength = _maxLength == nil ? CGFloat(self.asset.duration.seconds) : _maxLength! self.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height + 20) if _minLength != nil { trimmerView!.minLength = _minLength! } if _thumbWidth != nil { trimmerView!.thumbWidth = _thumbWidth! } self.trimmerView!.resetSubviews() // Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateTrimmer), userInfo: nil, repeats: false) } } func updateTrimmer() { self.trimmerView!.resetSubviews() } func setSource(source: NSString?) { if source != nil { let pathToSource = NSURL(string: source! as String) self.asset = AVURLAsset(url: pathToSource! as URL, options: nil) trimmerView = ICGVideoTrimmerView(frame: rect, asset: self.asset) trimmerView!.showsRulerView = false trimmerView!.hideTracker(false) trimmerView!.delegate = self trimmerView!.trackerColor = self._trackerColor self.addSubview(trimmerView!) self.updateView() } } init(frame: CGRect, bridge: RCTBridge) { super.init(frame: frame) self.bridge = bridge } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func onTrimmerPositionChange(startTime: CGFloat, endTime: CGFloat) { if self.onChange != nil { let event = ["startTime": startTime, "endTime": endTime] self.onChange!(event) } } func trimmerView(_ trimmerView: ICGVideoTrimmerView, didChangeLeftPosition startTime: CGFloat, rightPosition endTime: CGFloat) { onTrimmerPositionChange(startTime: startTime, endTime: endTime) } public func trimmerView(_ trimmerView: ICGVideoTrimmerView, currentPosition currentTime: CGFloat) { print("current", currentTime) if onTrackerMove == nil { return } let event = ["currentTime": currentTime] self.onTrackerMove!(event) } }
mit
e2947b906f80385633b5ec0829bfd660
28.07113
145
0.522596
5.150482
false
false
false
false
mikekavouras/Glowb-iOS
Glowb/Utility/Router.swift
1
8261
// // Router.swift // Glowb // // Created by Michael Kavouras on 12/6/16. // Copyright © 2016 Michael Kavouras. All rights reserved. // import Foundation import Alamofire typealias JSON = [String: Any] enum APIError: Error { case keyNotFound } enum Router: URLRequestConvertible { // auth case createOAuthToken case refreshOAuthToken case revokeOAuthToken // devices case getDevices case getDevice(Int) case updateDevice(Int, String) case createDevice(String, String) case deleteDevice(Int) case resetDevice(Int) // interactions case getInteractions case getInteraction(Int) case createInteraction(Interaction) case updateInteraction(Interaction) case deleteInteraction(Int) case createEvent(Interaction) // invites case createInvite(Int, Date, Int) case claimInvite(String, String) // photos case getPhotos case createPhoto case updatePhoto(Photo) // shares case createShare(Int) case deleteShare(Share) fileprivate static let apiRoot: String = Plist.Config.APIRoot fileprivate static let appID: String = Plist.Config.appId } extension Router { func asURLRequest() throws -> URLRequest { switch self { case .createOAuthToken: return try JSONEncoding.default.encode(request, with: [:]) case .refreshOAuthToken: return try JSONEncoding.default.encode(request, with: [:]) case .revokeOAuthToken: return try JSONEncoding.default.encode(request, with: [:]) case .getDevices: return try URLEncoding.default.encode(request, with: [:]) case .getDevice(let deviceId): let params = [ "device_id" : deviceId ] return try URLEncoding.default.encode(request, with: params) case .updateDevice(_, let name): let params = [ "name" : name ] return try JSONEncoding.default.encode(request, with: params) case .createDevice(let deviceId, let name): let params = [ "particle_id" : deviceId, "name" : name ] return try JSONEncoding.default.encode(request, with: params) case .deleteDevice: return try JSONEncoding.default.encode(request, with: [:]) case .resetDevice: return try JSONEncoding.default.encode(request, with: [:]) case .getInteractions: return try URLEncoding.default.encode(request, with: [:]) case .getInteraction: return try URLEncoding.default.encode(request, with: [:]) case .createInteraction(let interaction): let params = interaction.asJSON return try JSONEncoding.default.encode(request, with: params) case .updateInteraction(let interaction): let params = interaction.asJSON return try JSONEncoding.default.encode(request, with: params) case .deleteInteraction: return try URLEncoding.default.encode(request, with: [:]) case .createEvent: return try JSONEncoding.default.encode(request, with: [:]) case .createInvite(let deviceId, let expiresAt, let limit): let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let dateString = formatter.string(from: expiresAt) let params: JSON = [ "device_id" : deviceId, "expires_at" : dateString, "usage_limit" : limit ] return try JSONEncoding.default.encode(request, with: params) case .claimInvite(let name, let token): let params = [ "name" : name, "token" : token ] return try JSONEncoding.default.encode(request, with: params) case .getPhotos: return try URLEncoding.default.encode(request, with: [:]) case .createPhoto: return try JSONEncoding.default.encode(request, with: [:]) case .updatePhoto(let photo): let params = photo.toJSON() return try JSONEncoding.default.encode(request, with: params) case .createShare(let interactionId): let params = [ "interaction_id" : interactionId ] return try JSONEncoding.default.encode(request, with: params) case .deleteShare: return try URLEncoding.default.encode(request, with: [:]) } } private var method: Alamofire.HTTPMethod { switch self { case .createOAuthToken: return .post case .refreshOAuthToken: return .post case .revokeOAuthToken: return .post case .getDevices: return .get case .getDevice: return .get case .updateDevice: return .patch case .createDevice: return .post case .deleteDevice: return .delete case .resetDevice: return .post case .createInteraction: return .post case .getInteractions: return .get case .getInteraction: return .get case .updateInteraction: return .patch case .deleteInteraction: return .delete case .createEvent: return .post case .createInvite: return .post case .claimInvite: return .post case .getPhotos: return .get case .createPhoto: return .post case .updatePhoto: return .patch case .createShare: return .post case .deleteShare: return .delete } } private var path: String { switch self { case .createOAuthToken: return "/api/v1/oauth" case .refreshOAuthToken: return "/api/v1/oauth/token" case .revokeOAuthToken: return "/api/v1/oauth/revoke" case .getDevices: return "/api/v1/devices" case .getDevice(let deviceID): return "/api/v1/devices/\(deviceID)" case .updateDevice(let deviceID, _): return "/api/v1/devices/\(deviceID)" case .createDevice: return "/api/v1/devices" case .deleteDevice(let deviceID): return "/api/v1/devices/\(deviceID)" case .resetDevice(let deviceID): return "/api/v1/devices/reset/\(deviceID)" case .createInteraction: return "/api/v1/interactions" case .getInteractions: return "/api/v1/interactions" case .getInteraction(let interactionId): return "/api/v1/interactions/\(interactionId)" case .updateInteraction(let interaction): return "/api/v1/interactions/\(interaction.id!)" case .deleteInteraction(let interactionId): return "/api/v1/interactions/\(interactionId)" case .createEvent(let interaction): return "/api/v1/interactions/\(interaction.id!)" case .createInvite: return "/api/v1/invites" case .claimInvite: return "/api/v1/invites/accept" case .getPhotos: return "/api/v1/photos" case .createPhoto: return "/api/v1/photos" case .updatePhoto(let photo): return "/api/v1/photos/\(photo.id!)" case .createShare: return "/api/v1/shares" case .deleteShare(let share): return "/api/v1/shares/\(share.id)" } } private var request: URLRequest { let url = URL(string: "\(Router.apiRoot)")! var request = URLRequest(url: url.appendingPathComponent(path)) request.httpMethod = method.rawValue request.setValue(Router.appID, forHTTPHeaderField: "X-Application-Id") if let token = User.current.accessToken { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } return request } }
mit
06f8b4dcc1a169cfd4b2ec26928ead2a
32.04
107
0.579903
4.870283
false
false
false
false
alisidd/iOS-WeJ
WeJ/Add Tracks/MusicLibrarySelectionViewController.swift
1
5896
// // MusicLibrarySelectionViewController.swift // WeJ // // Created by Mohammad Ali Siddiqui on 8/9/17. // Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved. // import UIKit import RKNotificationHub import NVActivityIndicatorView class MusicLibrarySelectionViewController: UIViewController, ViewControllerAccessDelegate { private weak var delegate: AddTracksTabBarController! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var myLibraryLabel: UILabel! @IBOutlet weak var doneButton: UIButton! private var badge: RKNotificationHub! private var totalTracksCount: Int { let controller = tabBarController! as! AddTracksTabBarController return controller.tracksSelected.count + controller.libraryTracksSelected.count } @IBOutlet weak var spotifyLibraryButton: UIButton! @IBOutlet weak var spotifyActivityIndicator: NVActivityIndicatorView! @IBOutlet weak var appleMusicLibraryButton: UIButton! private var libraryMusicService: MusicService! private var authorizationManager: AuthorizationManager! var processingLogin = false { didSet { DispatchQueue.main.async { if self.processingLogin && self.libraryMusicService == .spotify { self.spotifyActivityIndicator.startAnimating() } else if self.libraryMusicService == .spotify { self.spotifyActivityIndicator.stopAnimating() } } } } @IBOutlet weak var playlistsButton: UIButton! @IBOutlet weak var tracksTableView: UITableView! @IBOutlet weak var playlistsActivityIndicator: NVActivityIndicatorView! private let fetcher: Fetcher = Party.musicService == .spotify ? SpotifyFetcher() : AppleMusicFetcher() var tracksList = [Track]() { didSet { DispatchQueue.main.async { self.tracksTableView.reloadData() self.playlistsActivityIndicator.stopAnimating() self.fetchArtworkForRestOfTracks() } } } func setBadge(to count: Int) { badge.count = Int32(count) badge.pop() } override func viewDidLoad() { super.viewDidLoad() hideNavigationBar() initializeBadge() initializeVariables() setDelegates() adjustViews() adjustFontSizes() getTrending() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setBadge(to: totalTracksCount) } private func hideNavigationBar() { navigationController?.navigationBar.isHidden = true } private func initializeBadge() { badge = RKNotificationHub(view: doneButton.titleLabel) badge.count = Int32(totalTracksCount) badge.moveCircleBy(x: CGFloat(Float(NSLocalizedString("DoneBadgeConstraint", comment: "")) ?? 51.0), y: 0) badge.scaleCircleSize(by: 0.7) badge.setCircleColor(AppConstants.orange, label: .white) } private func initializeVariables() { SpotifyAuthorizationManager.storyboardSegue = "Show Spotify Library" AppleMusicAuthorizationManager.storyboardSegue = "Show Apple Music Library" } private func setDelegates() { delegate = navigationController?.tabBarController! as! AddTracksTabBarController SpotifyAuthorizationManager.delegate = self AppleMusicAuthorizationManager.delegate = self tracksTableView.delegate = delegate tracksTableView.dataSource = delegate } private func adjustViews() { tracksTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0) } private func adjustFontSizes() { if UIDevice.deviceType == .iPhone4_4s || UIDevice.deviceType == .iPhone5_5s_SE { myLibraryLabel.changeToSmallerFont() doneButton.changeToSmallerFont() spotifyLibraryButton.changeToSmallerFont() appleMusicLibraryButton.changeToSmallerFont() playlistsButton.changeToSmallerFont() } } private func getTrending() { playlistsActivityIndicator.startAnimating() fetcher.getMostPlayed { [weak self] in self?.tracksList = self?.fetcher.tracksList ?? [] } } private func fetchArtworkForRestOfTracks() { let tracksCaptured = tracksList for track in tracksList where tracksList == tracksCaptured && track.lowResArtwork == nil { DispatchQueue.global(qos: .userInitiated).async { track.fetchImage(fromURL: track.lowResArtworkURL) { [weak self, weak track] (image) in track?.lowResArtwork = image self?.tracksTableView.reloadData() } } } } // MARK: - Navigation @IBAction func showSpotifyLibrary() { guard !processingLogin else { return } authorizationManager = SpotifyAuthorizationManager() libraryMusicService = .spotify authorizationManager.requestAuthorization() } @IBAction func showAppleMusicLibrary() { guard !processingLogin else { return } authorizationManager = AppleMusicAuthorizationManager() libraryMusicService = .appleMusic authorizationManager.requestAuthorization() } func tryAgain() { if libraryMusicService == .spotify { showSpotifyLibrary() } else { showAppleMusicLibrary() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? PlaylistSelectionViewController { controller.musicService = libraryMusicService } } }
gpl-3.0
da0f61bda7c88e6d17802ad5d40f8a41
33.075145
114
0.651739
5.493942
false
false
false
false
Mikhepls/ios-notes
accountnotes/accountnotes/copyableLabel.swift
1
1393
// // copyableLabel.swift // accountnotes // // Created by Tom Lagerbom on 04/02/16. // Copyright © 2016 Mikael's apps. All rights reserved. // import UIKit class copyableLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) sharedInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } override func canBecomeFirstResponder() -> Bool { return true } override func copy(sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() board.string = text let menu = UIMenuController.sharedMenuController() menu.setMenuVisible(false, animated: true) } func sharedInit() { userInteractionEnabled = true addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "showMenu:")) } func showMenu(sender: AnyObject?) { becomeFirstResponder() let menu = UIMenuController.sharedMenuController() if !menu.menuVisible { menu.setTargetRect(bounds, inView: self) menu.setMenuVisible(true, animated: true) } } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "copy:" { return true } return false } }
mit
ff34a49b449f0109179edd8cc128efe1
24.327273
93
0.611351
4.901408
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/Pods/AcknowList/Source/AcknowParser.swift
1
4352
// // AcknowParser.swift // // Copyright (c) 2015-2016 Vincent Tourraine (http://www.vtourraine.net) // // 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 /// Responsible for parsing a CocoaPods acknowledgements plist file. public class AcknowParser { /** The root dictionary from the loaded plist file. */ let rootDictionary: [String: AnyObject] /** Initializes the `AcknowParser` instance with a plist path. - parameter plistPath: The path to the acknowledgements plist file. - returns: The new `AcknowParser` instance. */ public init(plistPath: String) { let root = NSDictionary(contentsOfFile: plistPath) if let root = root where root is [String: AnyObject] { self.rootDictionary = root as! [String: AnyObject] } else { self.rootDictionary = Dictionary() } } /** Parses the header and footer values. - return: a tuple with the header and footer values. */ public func parseHeaderAndFooter() -> (header: String?, footer: String?) { let preferenceSpecifiers: AnyObject? = self.rootDictionary["PreferenceSpecifiers"] if let preferenceSpecifiers = preferenceSpecifiers where preferenceSpecifiers is [AnyObject] { let preferenceSpecifiersArray = preferenceSpecifiers as! [AnyObject] if let headerItem = preferenceSpecifiersArray.first, let footerItem = preferenceSpecifiersArray.last, let headerText = headerItem["FooterText"] where headerItem is [String: String], let footerText = footerItem["FooterText"] where footerItem is [String: String] { return (headerText as! String?, footerText as! String?) } } return (nil, nil) } /** Parses the array of acknowledgements. - return: an array of `Acknow` instances. */ public func parseAcknowledgements() -> [Acknow] { let preferenceSpecifiers: AnyObject? = self.rootDictionary["PreferenceSpecifiers"] if let preferenceSpecifiers = preferenceSpecifiers where preferenceSpecifiers is [AnyObject] { let preferenceSpecifiersArray = preferenceSpecifiers as! [AnyObject] // Remove the header and footer let ackPreferenceSpecifiers = preferenceSpecifiersArray.filter({ (object: AnyObject) -> Bool in if let firstObject = preferenceSpecifiersArray.first, let lastObject = preferenceSpecifiersArray.last { return (object.isEqual(firstObject) == false && object.isEqual(lastObject) == false) } return true }) let acknowledgements = ackPreferenceSpecifiers.map({ (preferenceSpecifier: AnyObject) -> Acknow in if let title = preferenceSpecifier["Title"] as! String?, text = preferenceSpecifier["FooterText"] as! String? { return Acknow( title: title, text: text) } else { return Acknow(title: "", text: "") } }) return acknowledgements } return [] } }
mit
3a76b95c3ac33d9a1234aef6ff8d94e8
38.563636
108
0.642004
5.339877
false
false
false
false
iawtav/Simple-Weather
Weather/SearchCell.swift
1
1077
// // SearchCell.swift // Weather // // Created by TUANANH VUONG on 2016/10/10. // Copyright © 2016 TUANANH VUONG. All rights reserved. // import UIKit class SearchCell: UITableViewCell { @IBOutlet weak var weatherTypeIcon: UIImageView! @IBOutlet weak var weatherType: UILabel! @IBOutlet weak var currentTemp: UILabel! @IBOutlet weak var highTemp: UILabel! @IBOutlet weak var lowTemp: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var summary: UILabel! @IBOutlet weak var tomorow: UILabel! func configCell(moreLocations: MoreLocation) { weatherTypeIcon.image = UIImage(named: moreLocations.currentWeatherIcon) weatherType.text = moreLocations.currentWeatherType currentTemp.text = "\(moreLocations.currentTemp)˚" highTemp.text = "High: \(moreLocations.highTemp)˚" lowTemp.text = "Low: \(moreLocations.lowTemp)˚" location.text = moreLocations.location summary.text = moreLocations.summary tomorow.text = "Tomorrow: \(moreLocations.tomorrow)" } }
apache-2.0
c9e14b800c7cf8e232b7a5d5c20e03c8
32.53125
80
0.700839
4.142857
false
false
false
false
eduarenas/GithubClient
Sources/GitHubClient/Models/Response/User.swift
1
1680
// // RepositoriesClient.swift // GithubClient // // Created by Eduardo Arenas on 8/5/17. // Copyright © 2017 GameChanger. All rights reserved. // import Foundation public struct User: Decodable { public let login: String public let id: Int public let avatarUrl: String? public let url: String? public let htmlUrl: String? public let type: UserType public let siteAdmin: Bool? public let name: String? public let company: String? public let blog: String? public let location: String? public let email: String? public let hireable: Bool? public let bio: String? public let publicRepos: Int? public let publicGists: Int? public let followers: Int? public let following: Int? public let createdAt: Date? public let updatedAt: Date? public let totalPrivateRepos: Int? public let ownedPrivateRepos: Int? public let privateGists: Int? public let diskUsage: Int? public let collaborators: Int? // TODO: let plan: Plan? } extension User { enum CodingKeys: String, CodingKey { case login case id case avatarUrl = "avatar_url" case url case htmlUrl = "html_url" case type case siteAdmin = "site_admin" case name case company case blog case location case email case hireable case bio case publicRepos = "public_repos" case publicGists = "public_gists" case followers case following case createdAt = "created_at" case updatedAt = "updated_at" case totalPrivateRepos = "total_private_repos" case ownedPrivateRepos = "owned_private_repos" case privateGists = "private_gists" case diskUsage = "disk_usage" case collaborators } }
mit
269bf269b006b2be7689f676b9929092
22.985714
54
0.696248
3.950588
false
false
false
false
MrAlek/JSQDataSourcesKit
Source/DataSourceProvider.swift
1
4769
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://jessesquires.com/JSQDataSourcesKit // // // GitHub // https://github.com/jessesquires/JSQDataSourcesKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation import UIKit public final class DataSourceProvider<SectionInfo: SectionInfoProtocol, CellFactory: CellFactoryProtocol where CellFactory.Item == SectionInfo.Item>: CustomStringConvertible { public var sections: [SectionInfo] public let cellFactory: CellFactory private var bridgedDataSource: BridgedDataSource? public init(sections: [SectionInfo], cellFactory: CellFactory) { self.sections = sections self.cellFactory = cellFactory } public subscript (index: Int) -> SectionInfo { get { return sections[index] } set { sections[index] = newValue } } public subscript (indexPath: NSIndexPath) -> SectionInfo.Item { get { return sections[indexPath.section].items[indexPath.item] } set { sections[indexPath.section].items[indexPath.item] = newValue } } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { return "<\(DataSourceProvider.self): sections=\(sections)>" } } } public extension DataSourceProvider where CellFactory.Cell: UITableViewCell { public var tableViewDataSource: UITableViewDataSource { if bridgedDataSource == nil { bridgedDataSource = tableViewBridgedDataSource() } return bridgedDataSource! } private func tableViewBridgedDataSource() -> BridgedDataSource { let dataSource = BridgedDataSource( numberOfSections: { [unowned self] () -> Int in return self.sections.count }, numberOfItemsInSection: { [unowned self] (section) -> Int in return self.sections[section].items.count }) dataSource.tableCellForRowAtIndexPath = { [unowned self] (tableView, indexPath) -> UITableViewCell in let item = self.sections[indexPath.section].items[indexPath.row] return self.cellFactory.cellFor(item: item, parentView: tableView, indexPath: indexPath) } dataSource.tableTitleForHeaderInSection = { [unowned self] (section) -> String? in return self.sections[section].headerTitle } dataSource.tableTitleForFooterInSection = { [unowned self] (section) -> String? in return self.sections[section].footerTitle } return dataSource } } public extension DataSourceProvider where CellFactory.Cell: UICollectionViewCell { public var collectionViewDataSource: UICollectionViewDataSource { if bridgedDataSource == nil { bridgedDataSource = collectionViewBridgedDataSource() } return bridgedDataSource! } private func collectionViewBridgedDataSource() -> BridgedDataSource { let dataSource = BridgedDataSource( numberOfSections: { [unowned self] () -> Int in return self.sections.count }, numberOfItemsInSection: { [unowned self] (section) -> Int in return self.sections[section].items.count }) dataSource.collectionCellForItemAtIndexPath = { [unowned self] (collectionView, indexPath) -> UICollectionViewCell in let item = self.sections[indexPath.section].items[indexPath.row] return self.cellFactory.cellFor(item: item, parentView: collectionView, indexPath: indexPath) } // TODO: figure out supplementary views // dataSource.collectionSupplementaryViewAtIndexPath = { [unowned self] (collectionView, kind, indexPath) -> UICollectionReusableView in // let factory = self.supplementaryViewFactory! // var item: Item? // if indexPath.section < self.sections.count { // if indexPath.item < self.sections[indexPath.section].items.count { // item = self.sections[indexPath.section].items[indexPath.item] // } // } // // let view = factory.supplementaryViewFor(item: item, kind: kind, collectionView: collectionView, indexPath: indexPath) // return factory.configureSupplementaryView(view, item: item, kind: kind, collectionView: collectionView, indexPath: indexPath) // } return dataSource } }
mit
db63fed55a39a24093e10b2ea10552aa
32.111111
151
0.632341
5.405896
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/ProViewController.swift
1
1718
// // ProViewController.swift // TeacherTools // // Created by Parker Rushton on 12/2/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class ProViewController: UIViewController, AutoStoryboardInitializable { @IBOutlet weak var upgradeBorderView: UIView! fileprivate var sharedStore = TTProducts.store var core = App.core override func viewDidLoad() { super.viewDidLoad() preferredContentSize = CGSize(width: view.bounds.width * 0.6, height: view.bounds.height * 0.6) AnalyticsHelper.logEvent(.proLaunched) upgradeBorderView.layer.cornerRadius = 5 upgradeBorderView.backgroundColor = .appleBlue } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) core.remove(subscriber: self) } @IBAction func dismissButtonPressed(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func upgradeViewPressed(_ sender: UITapGestureRecognizer) { AnalyticsHelper.logEvent(.proPressed) core.fire(command: GoPro()) } @IBAction func restoreButtonPressed(_ sender: UIButton) { AnalyticsHelper.logEvent(.restorePressed) sharedStore.restorePurchases() } } // MARK: - Subscriber extension ProViewController: Subscriber { func update(with state: AppState) { guard let user = state.currentUser else { return } if user.isPro { dismiss(animated: true, completion: nil) } } }
mit
caa71ab5b1e707d37845b20e5075b68e
25.415385
103
0.661037
4.743094
false
false
false
false
kdawgwilk/Autobahn
Sources/AutobahnDescription/AutobahnDescription.swift
1
4840
#if os(Linux) import Glibc #else import Darwin.C #endif import Foundation @_exported import Actions private extension Array { var second: Element? { guard count > 1 else { return nil } return self[1] } } /// Highway is the protocol which every highway should follow. /// /// We suggest defining the highways as an enum like this: /// /// ```Swift /// enum MyHighways { /// case build, test, deploy, release /// /// var usage: String { /// switch self { /// case .build: return "This is how you should use build:…" /// // … handle all cases /// } /// } /// ``` public protocol Highway: RawRepresentable, Hashable where RawValue == String { var usage: String { get } } public extension Highway { var usage: String { return "No usage specified for \(self)" } } public final class Autobahn<H: Highway> { public let version = "0.1.0" private var highwayStart: Date private var highwayEnd: Date? private var beforeAllHandler: ((H) throws -> Void)? private var highways = [H: () throws -> Void]() private var dependings = [H: [H]]() private var afterAllHandler: ((H) throws -> Void)? private var onErrorHandler: ((String, Error) -> Void)? // MARK: - Possible errors public enum HighwayError: Error { case noHighwaySpecified case noValidHighwayName(String) case highwayNotDefined(String) } // MARK: - Public Functions public init(_ highwayType: H.Type) { self.highwayStart = Date() } public func beforeAll(handler: @escaping (H) throws -> Void) -> Autobahn<H> { precondition(beforeAllHandler == nil, "beforeAll declared more than once") beforeAllHandler = handler return self } public func highway(_ highway: H, dependsOn highways: [H], handler: @escaping () throws -> Void) -> Autobahn<H> { return self.addHighway(highway, dependsOn: highways, handler: handler) } public func highway(_ highway: H, handler: @escaping () throws -> Void) -> Autobahn<H> { return self.addHighway(highway, handler: handler) } public func highway(_ highway: H, dependsOn highways: [H]) -> Autobahn<H> { return self.addHighway(highway, dependsOn: highways) } public func afterAll(handler: @escaping (H) throws -> Void) -> Autobahn<H> { precondition(afterAllHandler == nil, "afterAll declared more than once") afterAllHandler = handler return self } public func onError(handler: @escaping (String, Error) -> Void) -> Autobahn<H> { precondition(onErrorHandler == nil, "onError declared more than once") onErrorHandler = handler return self } public func drive() { let args = CommandLine.arguments let secondArg = args.second do { guard let raw = secondArg else { throw HighwayError.noHighwaySpecified } guard let currentHighway = H(rawValue: raw) else { throw HighwayError.noValidHighwayName(raw) } try self.beforeAllHandler?(currentHighway) try self.driveHighway(currentHighway) try self.afterAllHandler?(currentHighway) } catch { self.onErrorHandler?(secondArg ?? "", error) } highwayEnd = Date() let duration = highwayEnd!.timeIntervalSince(highwayStart) let rounded = Double(round(100 * duration) / 100) print("Duration: \(rounded)s") } // MARK: - Private private func addHighway(_ highway: H, dependsOn highways: [H]? = nil, handler: (() throws -> Void)? = nil) -> Autobahn<H> { self.highways[highway] = handler dependings[highway] = highways return self } private func driveHighway(_ highway: H) throws { if let dependings = self.dependings[highway] { for dependingHighway in dependings { guard let d = self.highways[dependingHighway] else { throw HighwayError.highwayNotDefined(dependingHighway.rawValue) } printHeader(for: dependingHighway) try d() } } if let handler = highways[highway] { printHeader(for: highway) try handler() } } private func printHeader(for highway: H) { let count = highway.rawValue.count print("-------------\(String(repeating: "-", count: count))----") print("--- Highway: \(highway.rawValue) ---") print("-------------\(String(repeating: "-", count: count))----") } } public func sh(_ cmd: String, _ args: String...) throws { try ShellCommand.run(cmd, args: args) }
mit
5c53df2377b3240369c0f83032dbe949
29.802548
127
0.58995
4.42452
false
false
false
false
toddkramer/EmojiTools
EmojiTools/EmojiTools.swift
1
4394
// // EmojiTools.swift // EmojiTools // // Copyright © 2016 Todd Kramer. // // 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 String { public func emojiString() -> String { return String.emojiStringFromString(self) } public static func emojiStringFromString(inputString: String) -> String { var token: dispatch_once_t = 0 var regex: NSRegularExpression? = nil dispatch_once(&token) { let pattern = "(:[a-z0-9-+_]+:)" regex = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive) } var resultText = inputString let matchRange = NSMakeRange(0, resultText.characters.count) regex?.enumerateMatchesInString(resultText, options: .ReportCompletion, range: matchRange, usingBlock: { (result, _, _) -> Void in guard let range = result?.range else { return } if range.location != NSNotFound { let emojiCode = (inputString as NSString).substringWithRange(range) if let emojiCharacter = emojiShortCodes[emojiCode] { resultText = resultText.stringByReplacingOccurrencesOfString(emojiCode, withString: emojiCharacter) } } }) return resultText } public func containsEmoji() -> Bool { return String.containsEmoji(self) } public static func containsEmoji(string: String) -> Bool { for scalar in string.unicodeScalars { if scalar.isEmoji() { return true } } return false } public func containsEmojiOnly(allowWhitespace: Bool = true) -> Bool { return String.containsEmojiOnly(self, allowWhitespace: allowWhitespace) } public static func containsEmojiOnly(string: String, allowWhitespace: Bool = true) -> Bool { var inputString = string if allowWhitespace { inputString = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("") } for scalar in inputString.unicodeScalars { if !scalar.isEmoji() { return false } } return true } } extension UnicodeScalar { public func isEmoji() -> Bool { return UnicodeScalar.isEmoji(self) } public static func isEmoji(scalar: UnicodeScalar) -> Bool { return emojis.unicodeScalars.contains(scalar) } } public struct EmojiCodeSuggestion { let code: String let character: String } public struct EmojiTools { public static func emojiCodeSuggestionsForSearchTerm(searchTerm: String) -> [EmojiCodeSuggestion] { let keys = Array(emojiShortCodes.keys) let filteredKeys = keys.filter { (key) -> Bool in return key.containsString(searchTerm) }.sort() let unicodeCharacters = filteredKeys.map({ emojiShortCodes[$0]! }) var suggestions = [EmojiCodeSuggestion]() if filteredKeys.count == 0 { return suggestions } for index in 0...(filteredKeys.count - 1) { let suggestion = EmojiCodeSuggestion(code: filteredKeys[index], character: unicodeCharacters[index]) suggestions.append(suggestion) } return suggestions } }
mit
3fa3f82b740fb2f40ac37265a137f7fc
35.016393
142
0.660141
5.026316
false
false
false
false
luanlzsn/EasyPass
EasyPass/Classes/Mine/Controller/MyAccountController.swift
1
11137
// // MyAccountController.swift // EasyPass // // Created by luan on 2017/7/5. // Copyright © 2017年 luan. All rights reserved. // import UIKit class MyAccountController: AntController,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MyAccountTextField_Delegate { @IBOutlet weak var tableView: UITableView! var titleArray = ["个人头像","用户名","性别","专业","电话","邮箱"] var contentArray = ["","","","","",""] let placeholderArray = ["","","请选择性别","请选择专业","请输入手机号","请输入邮箱"] override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveAccountInfo)) if AntManage.userModel?.nickName != nil { contentArray.replaceSubrange(Range(1..<2), with: [AntManage.userModel?.nickName?.removingPercentEncoding ?? ""]) } if AntManage.userModel?.sexStr != nil { contentArray.replaceSubrange(Range(2..<3), with: [AntManage.userModel?.sexStr ?? ""]) } if AntManage.userModel?.majorName != nil { contentArray.replaceSubrange(Range(3..<4), with: [AntManage.userModel?.majorName ?? ""]) } if AntManage.userModel?.phone != nil { contentArray.replaceSubrange(Range(4..<5), with: [AntManage.userModel?.phone ?? ""]) } if AntManage.userModel?.email != nil { contentArray.replaceSubrange(Range(5..<6), with: [AntManage.userModel?.email ?? ""]) } } // MARK: - 保存个人信息 func saveAccountInfo() { kWindow?.endEditing(true) weak var weakSelf = self var params = ["token":AntManage.userModel!.token!, "headImg":AntManage.userModel?.headImg ?? "", "userName":AntManage.userModel?.userName ?? "", "nickName":AntManage.userModel?.nickName ?? "", "phone":contentArray[4], "email":contentArray[5]] as [String : Any] if !contentArray[2].isEmpty { params["sex"] = (contentArray[2] == "男") ? 1 : 2 } if !contentArray[3].isEmpty { for model in AntManage.classifyList { if model.name == contentArray[3] { params["major"] = model.id! break } } } AntManage.postRequest(path: "appAuth/updateAppUser", params: params, successResult: { (response) in AntManage.userModel?.sexStr = weakSelf?.contentArray[2] AntManage.userModel?.majorName = weakSelf?.contentArray[3] AntManage.userModel?.phone = weakSelf?.contentArray[4] AntManage.userModel?.email = weakSelf?.contentArray[5] NotificationCenter.default.post(name: NSNotification.Name(kLoginStatusUpdate), object: nil) UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: AntManage.userModel!), forKey: kUserInfo) UserDefaults.standard.synchronize() AntManage.showDelayToast(message: "保存成功") weakSelf?.navigationController?.popViewController(animated: true) }, failureResult: {}) } func uploadImage(image: UIImage) { weak var weakSelf = self AntManage.uploadWithPath(path: "upload/uploadImg", params: ["token":AntManage.userModel!.token!, "dir":"avators"], file: UIImageJPEGRepresentation(image, 0.1)!, successResult: { (response) in AntManage.userModel?.headImg = response["url"] as? String NotificationCenter.default.post(name: NSNotification.Name(kLoginStatusUpdate), object: nil) UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: AntManage.userModel!), forKey: kUserInfo) UserDefaults.standard.synchronize() weakSelf?.tableView.reloadData() }, failureResult: {}) } // MARK: - 选择图片 func selectPhoto() { let sheet = UIAlertController(title: "选择图片来源", message: nil, preferredStyle: .actionSheet) weak var weakSelf = self sheet.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in weakSelf?.takingPictures(sourceType: .camera) })) sheet.addAction(UIAlertAction(title: "相册", style: .default, handler: { (_) in weakSelf?.takingPictures(sourceType: .photoLibrary) })) sheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) present(sheet, animated: true, completion: nil) } // MARK: - 选择性别 func selectSex() { let actionSheet = UIAlertController(title: "选择性别", message: nil, preferredStyle: .actionSheet) weak var weakSelf = self actionSheet.addAction(UIAlertAction(title: "男", style: .default, handler: { (_) in weakSelf?.contentArray.replaceSubrange(Range(2..<3), with: ["男"]) weakSelf?.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: "女", style: .default, handler: { (_) in weakSelf?.contentArray.replaceSubrange(Range(2..<3), with: ["女"]) weakSelf?.tableView.reloadData() })) actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } // MARK: - 选择专业 func selectMajor() { let actionSheet = UIAlertController(title: "选择专业", message: nil, preferredStyle: .actionSheet) weak var weakSelf = self for model in AntManage.classifyList { actionSheet.addAction(UIAlertAction(title: model.name, style: .default, handler: { (_) in weakSelf?.contentArray.replaceSubrange(Range(3..<4), with: [model.name!]) weakSelf?.tableView.reloadData() })) } actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } // MARK: - MyAccountTextField_Delegate func textFieldEndEditing(string: String, row: Int) { contentArray.replaceSubrange(Range(row..<(row + 1)), with: [string]) tableView.reloadData() } // MARK: - UITableViewDelegate,UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 75 } else { return 45 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell: MyAccountHeadCell = tableView.dequeueReusableCell(withIdentifier: "MyAccountHeadCell", for: indexPath) as! MyAccountHeadCell if AntManage.userModel?.headImg != nil { cell.headImage.sd_setImage(with: URL(string: AntManage.userModel!.headImg!), placeholderImage: UIImage(named: "default_image")) } else { cell.headImage.image = UIImage(named: "head_defaults") } return cell } else if indexPath.row < 4 { var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "UITableViewCell") cell?.selectionStyle = .none cell?.textLabel?.font = UIFont.systemFont(ofSize: 14) cell?.detailTextLabel?.font = UIFont.boldSystemFont(ofSize: 14) } cell?.textLabel?.text = titleArray[indexPath.row] if contentArray[indexPath.row].isEmpty { cell?.detailTextLabel?.text = placeholderArray[indexPath.row] cell?.detailTextLabel?.textColor = UIColor(rgb: 0xcccccc) } else { cell?.detailTextLabel?.text = contentArray[indexPath.row] cell?.detailTextLabel?.textColor = UIColor.black } return cell! } else { let cell: MyAccountTextFieldCell = tableView.dequeueReusableCell(withIdentifier: "MyAccountTextFieldCell", for: indexPath) as! MyAccountTextFieldCell cell.delegate = self cell.tag = indexPath.row cell.titleLabel.text = titleArray[indexPath.row] cell.textField.text = contentArray[indexPath.row] cell.textField.placeholder = placeholderArray[indexPath.row] return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { selectPhoto() } else if indexPath.row == 2 { selectSex() } else if indexPath.row == 3 { selectMajor() } } func takingPictures(sourceType: UIImagePickerControllerSourceType) { if sourceType == .camera { if !UIImagePickerController.isSourceTypeAvailable(sourceType) { let alert = UIAlertController(title: "提示", message: "无法访问摄像头!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) return; } } let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.sourceType = sourceType navigationController?.present(picker, animated: true, completion: nil) } //MARK: UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { weak var weakSelf = self picker.dismiss(animated: true) { let image = info[UIImagePickerControllerEditedImage] weakSelf?.uploadImage(image: image as! UIImage) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) { } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ae648294bcf6ea1fa811ef7490954416
43.803279
268
0.62596
5.01698
false
false
false
false
DevZheng/LeetCode
Array/FirstMissingPositive.swift
1
1052
// // FirstMissingPositive.swift // A // // Created by zyx on 2017/6/29. // Copyright © 2017年 bluelive. All rights reserved. // import Foundation /** Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. */ class FirstMissingPositive { func firstMissingPositive(_ nums: [Int]) -> Int { var i = 0, nums = nums while i < nums.count { let num = nums[i] guard (num > 0 && num < nums.count) && nums[num - 1] != num else { i += 1 continue } let temp = nums[num - 1] nums[i] = temp nums[num - 1] = num } for (i, value) in nums.enumerated() { if i != value - 1 { return i + 1 } } return nums.count + 1 } }
mit
4c7693a1f2b27acf46a9d5084dbbc777
19.568627
79
0.466158
3.988593
false
false
false
false
mkoehnke/WKZombie
Example/Example iOS/ProfileViewController.swift
1
2180
// // ViewController.swift // // Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.de) // // 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 WKZombie class ProfileViewController: UITableViewController { var items : [HTMLTableColumn]? var snapshots : [Snapshot]? override func viewDidLoad() { super.viewDidLoad() navigationItem.hidesBackButton = true } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let item = items?[indexPath.row].children()?.first as HTMLElement? cell.textLabel?.text = item?.text return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "snapshotSegue" { let vc = segue.destination as? SnapshotViewController vc?.snapshots = snapshots } } }
mit
0dde02508e741cb68f3867db1442d0e8
38.636364
109
0.715138
4.833703
false
false
false
false
FirasAKAK/FInAppNotifications
FNotificationManager.swift
1
12574
// // FNotificationManager.swift // FInAppNotification // // Created by Firas Al Khatib Al Khalidi on 7/4/17. // Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved. // import UIKit class FNotificationManager: NSObject { static let shared = FNotificationManager() fileprivate var dismissalPanGestureRecognizer: UIPanGestureRecognizer! fileprivate var tapGestureRecognizer : UITapGestureRecognizer! private var notificationTimer : Timer! private var settings : FNotificationSettings! var pauseBetweenNotifications : TimeInterval = 1 private var notificationView : FNotificationView = UINib(nibName: "FNotificationView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! FNotificationView private var tapCompletion : (()-> Void)? private var notificationQueue : [(FNotification, FNotificationExtensionView?)] = [] private override init(){ super.init() set(newSettings: .defaultStyle) dismissalPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:))) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:))) dismissalPanGestureRecognizer.delegate = self tapGestureRecognizer.delegate = self notificationView.addGestureRecognizer(dismissalPanGestureRecognizer) notificationView.addGestureRecognizer(tapGestureRecognizer) } @objc func handlePan(gesture: UIPanGestureRecognizer){ switch gesture.state { case .began: if notificationTimer != nil{ notificationTimer.invalidate() notificationTimer = nil } case .changed: var translation = gesture.translation(in: notificationView) if notificationView.extensionView != nil && !notificationView.isExtended{ translation.y = translation.y - FNotificationView.bounceOffset notificationView.frame.origin.y = translation.y <= 0 ? translation.y : 0 if translation.y > 0{ var notificationHeight = FNotificationView.heightWithStatusBar if UIApplication.shared.isStatusBarHidden{ notificationHeight = FNotificationView.heightWithoutStatusBar } let extensionViewHeight: CGFloat = notificationView.extensionView!.height let fullHeight: CGFloat = notificationHeight + translation.y notificationView.frame.size.height = fullHeight <= notificationHeight + extensionViewHeight + 16 ? fullHeight : notificationHeight + extensionViewHeight + 16 } } else{ translation.y = translation.y - FNotificationView.bounceOffset notificationView.frame.origin.y = translation.y <= 0 ? translation.y : 0 } case .ended: if gesture.velocity(in: notificationView).y < 0{ notificationTimerExpired() } else{ notificationView.isExtended = true notificationView.moveToFinalPosition(animated: true, completion: nil) } default: break } } @objc func handleTap(gesture: UITapGestureRecognizer){ guard notificationView.frame.origin.y == -20 else{ return } tapCompletion?() notificationTimerExpired() } func set(newSettings settings: FNotificationSettings){ notificationView.backgroundView = settings.backgroundView notificationView.titleLabel.textColor = settings.titleTextColor notificationView.subtitleLabel.textColor = settings.subtitleTextColor notificationView.imageView.layer.cornerRadius = settings.imageViewCornerRadius notificationView.titleLabel.font = settings.titleFont notificationView.subtitleLabel.font = settings.subtitleFont notificationView.backgroundColor = settings.backgroundColor } func show(audioPlayerNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, extensionAudioUrl: String, notificationWasTapped: (()-> Void)?, didPlayRecording: (()-> Void)?){ let audioPlayerExtension = UINib(nibName: "FNotificationVoicePlayerExtensionView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! FNotificationVoicePlayerExtensionView audioPlayerExtension.dataUrl = extensionAudioUrl audioPlayerExtension.didPlayRecording = didPlayRecording guard notificationView.superview == nil else{ notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), audioPlayerExtension)) return } notificationView.extensionView = audioPlayerExtension defaultShow(withTitleText: titleText, subtitleText: subtitleText, image: image, andDuration: duration, notificationWasTapped: notificationWasTapped) } func show(imageNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, extensionImage: UIImage, notificationWasTapped: (()-> Void)?){ let imageViewExtentionView = FNotificationImageExtensionView() imageViewExtentionView.imageView.image = extensionImage guard notificationView.superview == nil else{ notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), imageViewExtentionView)) return } notificationView.extensionView = imageViewExtentionView defaultShow(withTitleText: titleText, subtitleText: subtitleText, image: image, andDuration: duration, notificationWasTapped: notificationWasTapped) } func show(textFieldNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?, accessoryTextFieldButtonPressed: ((_ text: String)-> Void)?){ let textFieldExtensionView = UINib(nibName: "FNotificationTextFieldExtensionView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! FNotificationTextFieldExtensionView textFieldExtensionView.sendButtonPressed = accessoryTextFieldButtonPressed guard notificationView.superview == nil else{ notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), textFieldExtensionView)) return } notificationView.extensionView = textFieldExtensionView defaultShow(withTitleText: titleText, subtitleText: subtitleText, image: image, andDuration: duration, notificationWasTapped: notificationWasTapped) } func show(withTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?){ guard notificationView.superview == nil else{ notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), nil)) return } notificationView.extensionView = nil defaultShow(withTitleText: titleText, subtitleText: subtitleText, image: image, andDuration: duration, notificationWasTapped: notificationWasTapped) } func show(notification: FNotification, withExtensionView extensionView: FNotificationExtensionView, notificationWasTapped: (()-> Void)?, extensionViewInteractionHandlers:(()-> Void)...){ guard notificationView.superview == nil else{ notificationQueue.append((notification, nil)) return } notificationView.extensionView = extensionView defaultShow(withTitleText: notification.titleText, subtitleText: notification.subtitleText, image: notification.image, andDuration: notification.duration, notificationWasTapped: notificationWasTapped) } func defaultShow(withTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?){ notificationView.moveToInitialPosition(animated: false, completion: nil) notificationView.titleLabel.text = titleText notificationView.subtitleLabel.text = subtitleText notificationView.imageView.image = image tapCompletion = notificationWasTapped if notificationTimer != nil{ self.notificationTimer.invalidate() self.notificationTimer = nil } if UIApplication.shared.isStatusBarHidden{ notificationView.topConstraint.constant = FNotificationView.topConstraintWithoutStatusBar notificationView.frame.size.height = FNotificationView.heightWithoutStatusBar notificationView.layoutIfNeeded() } else{ notificationView.topConstraint.constant = FNotificationView.topConstraintWithStatusBar notificationView.frame.size.height = FNotificationView.heightWithStatusBar notificationView.layoutIfNeeded() } guard case let window?? = UIApplication.shared.delegate?.window else{ return } window.addSubview(notificationView) notificationView.moveToFinalPosition(animated: true) { if self.notificationTimer != nil{ self.notificationTimer.invalidate() self.notificationTimer = nil } self.notificationTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(self.notificationTimerExpired), userInfo: nil, repeats: false) } } private func dequeueAndDisplayNotification(){ guard notificationQueue.count != 0 else{ return } let notificationTuple = notificationQueue.removeFirst() notificationView.extensionView = notificationTuple.1 defaultShow(withTitleText: notificationTuple.0.titleText, subtitleText: notificationTuple.0.subtitleText, image: notificationTuple.0.image, andDuration: notificationTuple.0.duration, notificationWasTapped: notificationTuple.0.notificationWasTapped) } @objc private func notificationTimerExpired(){ notificationView.moveToInitialPosition(animated: true){ self.notificationView.removeFromSuperview() self.notificationView.extensionView = nil DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + FNotificationManager.shared.pauseBetweenNotifications, execute: { self.dequeueAndDisplayNotification() }) } } func removeCurrentNotification(){ notificationTimerExpired() } func removeAllNotifications(){ notificationQueue = [] notificationTimerExpired() } } extension FNotificationManager: UIGestureRecognizerDelegate{ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } }
mit
e3bf255456ec0a8a60f86e56e977ba4e
53.665217
261
0.65068
6.655903
false
false
false
false
SocialObjects-Software/AMSlideMenu
AMSlideMenu/Animation/Animators/AMSlidingBlurAnimator.swift
1
2657
// // AMSlidingBlureAnimator.swift // AMSlideMenu // // The MIT License (MIT) // // Created by : arturdev // Copyright (c) 2020 arturdev. 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 open class AMSlidingBlurAnimator: AMSlidingAnimatorProtocol { open var duration: TimeInterval = 0.25 open var maxBlurRadius: CGFloat = 0.2 let effectsView: BlurryOverlayView = { let view = BlurryOverlayView(effect: UIBlurEffect(style: .light)) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.isUserInteractionEnabled = false return view }() open func animate(leftMenuView: UIView, contentView: UIView, progress: CGFloat, animated: Bool, completion: (() -> Void)?) { if effectsView.superview == nil { effectsView.frame = contentView.bounds contentView.addSubview(effectsView) } self.effectsView.blur(amount: progress * maxBlurRadius, duration: animated ? duration : 0) DispatchQueue.main.asyncAfter(deadline: .now() + duration) { completion?() } } open func animate(rightMenuView: UIView, contentView: UIView, progress: CGFloat = 1, animated: Bool = true, completion: (() -> Void)? = nil) { if effectsView.superview == nil { effectsView.frame = contentView.bounds contentView.addSubview(effectsView) } self.effectsView.blur(amount: progress * maxBlurRadius, duration: animated ? duration : 0) DispatchQueue.main.asyncAfter(deadline: .now() + duration) { completion?() } } }
mit
c4adc8fd12e1cb50a2f4e34a63b043a1
41.854839
143
0.699661
4.588946
false
false
false
false
nguyenantinhbk77/practice-swift
Notifications/Listening Notifications/Listening Notifications/AppDelegate.swift
2
1933
// // AppDelegate.swift // Listening Notifications // // Created by Domenico Solazzo on 15/05/15. // License MIT // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? /* The name of the notification that we are going to send */ class func notificationName() -> String{ return "SetPersonInfoNotification" } /* The first-name key in the user-info dictionary of our notification */ class func personInfoKeyFirstName () -> String{ return "firstName" } /* The last-name key in the user-info dictionary of our notification */ class func personInfoKeyLastName() -> String{ return "lastName" } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let person = Person() // Dictionary to be sent with the notification let additionalInfo = [ self.classForCoder.personInfoKeyFirstName(): "Domenico", self.classForCoder.personInfoKeyLastName(): "Solazzo" ] // Notification let notification = NSNotification(name: self.classForCoder.notificationName(), object: self, userInfo: additionalInfo) /* The person class is currently listening for this notification. That class will extract the first name and last name from it and set its own first name and last name based on the userInfo dictionary of the notification. */ NSNotificationCenter.defaultCenter().postNotification(notification) if let firstName = person.firstName{ println("Person's first name is: \(firstName)") } if let lastName = person.lastName{ println("Person's last name is: \(lastName)") } return true } }
mit
b700cba4918ec0162037b62dac4b49f1
31.216667
128
0.638903
5.384401
false
false
false
false
digitalsurgeon/SwiftWebSocket
websocketserver/handler.swift
1
2639
// // handler.swift // websocketserver // // Created by Ahmad Mushtaq on 17/05/15. // Copyright (c) 2015 Ahmad Mushtaq. All rights reserved. // import Foundation @objc(Handler) class Handler : GCDAsyncSocketDelegate { var socket: GCDAsyncSocket? = nil func handle(var request:Request, var socket: GCDAsyncSocket) { self.socket = socket; socket.synchronouslySetDelegate(self) } func disconnect() { socket?.disconnect() } } @objc(HttpHandler) class HttpHandler : Handler { let folderPath : String let webRoot : String init (webRoot: String, folderPath: String) { self.webRoot = webRoot self.folderPath = folderPath } override func handle(var request:Request, var socket: GCDAsyncSocket) { super.handle(request, socket: socket) Swell.info("Http request for " + request.path) request.path.removeRange(webRoot.startIndex...webRoot.endIndex.predecessor()) if request.path.isEmpty { request.path = "index.html" } let filePath = folderPath + request.path let fileExists = NSFileManager.defaultManager() .fileExistsAtPath(filePath) var response = Response(socket: socket) response.setCode( fileExists ? .Ok : .NotFound ) if fileExists { response.setCode(.Ok) if request.path == "index.html" { var err: NSError if let data = NSMutableString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) { data.replaceOccurrencesOfString("$IP", withString: Server.getIFAddresses().first!, options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, data.length)) response.set(data: data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)) } } else { response.set(data:NSData(contentsOfFile: filePath)) } } else { response.setCode(.NotFound) } response.generateResponse() disconnect() } } @objc(DefaultHttpHandler) class DefaultHttpHandler:HttpHandler { init () { super.init(webRoot: "", folderPath: "") } override func handle(request: Request, socket: GCDAsyncSocket) { Swell.info("DefaultHttpHandler - handle") let response = Response(socket:socket) response.setCode(.NotFound) response.generateResponse() disconnect() } }
mit
b24323e7528233369fceace89efa6420
29.697674
185
0.599848
4.95122
false
false
false
false
sarahspins/Loop
WatchApp Extension/Models/CarbEntryUserInfo.swift
2
2068
// // CarbEntryUserInfo.swift // Naterade // // Created by Nathan Racklyeft on 1/23/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation enum AbsorptionTimeType { case Fast case Medium case Slow } struct CarbEntryUserInfo { let value: Double let absorptionTimeType: AbsorptionTimeType let startDate: NSDate init(value: Double, absorptionTimeType: AbsorptionTimeType, startDate: NSDate) { self.value = value self.absorptionTimeType = absorptionTimeType self.startDate = startDate } } extension AbsorptionTimeType: RawRepresentable { typealias RawValue = Int init?(rawValue: RawValue) { switch rawValue { case 0: self = .Fast case 1: self = .Medium case 2: self = .Slow default: return nil } } var rawValue: RawValue { switch self { case .Fast: return 0 case .Medium: return 1 case .Slow: return 2 } } } extension CarbEntryUserInfo: RawRepresentable { typealias RawValue = [String: AnyObject] static let version = 1 static let name = "CarbEntryUserInfo" init?(rawValue: RawValue) { guard rawValue["v"] as? Int == self.dynamicType.version && rawValue["name"] as? String == CarbEntryUserInfo.name, let value = rawValue["cv"] as? Double, absorptionTimeRaw = rawValue["ca"] as? Int, absorptionTime = AbsorptionTimeType(rawValue: absorptionTimeRaw), startDate = rawValue["sd"] as? NSDate else { return nil } self.value = value self.startDate = startDate self.absorptionTimeType = absorptionTime } var rawValue: RawValue { return [ "v": self.dynamicType.version, "name": CarbEntryUserInfo.name, "cv": value, "ca": absorptionTimeType.rawValue, "sd": startDate ] } }
apache-2.0
a9fa48366f314a7d5b71f2ff230743de
21.966667
121
0.58297
4.818182
false
false
false
false
lllyyy/LY
U17-master/U17/Pods/HandyJSON/Source/HexColorTransform.swift
1
3043
// // HexColorTransform.swift // ObjectMapper // // Created by Vitaliy Kuzmenko on 10/10/16. // Copyright © 2016 hearst. All rights reserved. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #else import Cocoa #endif open class HexColorTransform: TransformType { #if os(iOS) || os(tvOS) || os(watchOS) public typealias Object = UIColor #else public typealias Object = NSColor #endif public typealias JSON = String var prefix: Bool = false var alpha: Bool = false public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { alpha = alphaToJSON prefix = prefixToJSON } open func transformFromJSON(_ value: Any?) -> Object? { if let rgba = value as? String { if rgba.hasPrefix("#") { let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = String(rgba[index...]) return getColor(hex: hex) } else { return getColor(hex: rgba) } } return nil } open func transformToJSON(_ value: Object?) -> JSON? { if let value = value { return hexString(color: value) } return nil } fileprivate func hexString(color: Object) -> String { let comps = color.cgColor.components! let r = Int(comps[0] * 255) let g = Int(comps[1] * 255) let b = Int(comps[2] * 255) let a = Int(comps[3] * 255) var hexString: String = "" if prefix { hexString = "#" } hexString += String(format: "%02X%02X%02X", r, g, b) if alpha { hexString += String(format: "%02X", a) } return hexString } fileprivate func getColor(hex: String) -> Object? { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 return nil } } else { // "Scan hex error return nil } #if os(iOS) || os(tvOS) || os(watchOS) return UIColor(red: red, green: green, blue: blue, alpha: alpha) #else return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) #endif } }
mit
a8227ea68bd25aa4a865073012b84907
25.452174
87
0.612755
3.023857
false
false
false
false
danielhour/DINC
DINC WatchKit Extension/NSDateExtensions.swift
1
711
// // NSDateExtensions.swift // DINC // // Created by dhour on 4/17/16. // Copyright © 2016 DHour. All rights reserved. // import Foundation extension Date { /** Gets the short weekday symbol for given date - returns: String */ func dayOfWeek() -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let symbols = formatter.shortWeekdaySymbols let myCalendar = Calendar(identifier: Calendar.Identifier.gregorian) let myComponents = (myCalendar as NSCalendar).components(.weekday, from: self) let weekDayIndex = myComponents.weekday!-1 return symbols![weekDayIndex] } }
mit
b64041372e607dd54abb06ee8a699106
22.666667
86
0.632394
4.465409
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/InputFormatter.swift
1
13202
// // InputFormatter.swift // Alfredo // // Created by Eric Kunz on 9/15/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation /// Formatting style options public enum InputFormattingType { /// Use with custom validation case none /// e.g. $00.00. Valid with any value greater than $0. case dollarAmount /// e.g. 00/00/0000 case date /// e.g. 00/00 case creditCardExpirationDate /// e.g. 0000 0000 0000 0000 - VISA/MASTERCARD case creditCardSixteenDigits /// e.g. 0000 000000 00000 - AMEX case creditCardFifteenDigits /// e.g. 000 case creditCardCVVThreeDigits /// e.g. 0000 case creditCardCVVFourDigits /// Allows any characters. Limits the character count and valid only when at limit case limitNumberOfCharacters(Int) /// Limits the count of numbers entered. Valid only at set limit case limitNumberOfDigits(Int) /// Only allows characters from the NSCharacterSet to be entered case limitToCharacterSet(CharacterSet) /// Any input with more than zero characters case anyLength } class InputFormatter { typealias inputTextFormatter = ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int))? typealias validChecker = ((_ input: String) -> Bool)? var formattingType = InputFormattingType.none fileprivate lazy var numberFormatter = NumberFormatter() fileprivate lazy var currencyFormatter = NumberFormatter() fileprivate lazy var dateFormatter = DateFormatter() init(type: InputFormattingType) { formattingType = type } var textFormatter: inputTextFormatter { switch self.formattingType { case .none: return nil case .dollarAmount: return formatCurrency case .date: return formatDate case .creditCardExpirationDate: return formatCreditCardExpirationDate case .creditCardSixteenDigits: return formatCreditCardSixteenDigits case .creditCardFifteenDigits: return formatCreditCardFifteenDigits case .creditCardCVVThreeDigits: return formatCreditCardCVVThreeDigits case .creditCardCVVFourDigits: return formatCreditCardCVVFourDigits case .limitNumberOfCharacters(let length): return limitToLength(length) case .limitNumberOfDigits(let length): return limitToDigitsWithLength(length) case .limitToCharacterSet(let characterSet): return limitToCharacterSet(characterSet) case .anyLength: return nil } } var validityChecker: validChecker { switch self.formattingType { case .none: return nil case .dollarAmount: return validateCurrency case .date: return isLength(10) case .creditCardExpirationDate: return isLength(5) case .creditCardSixteenDigits: return isLength(19) case .creditCardFifteenDigits: return isLength(17) case .creditCardCVVThreeDigits: return isLength(3) case .creditCardCVVFourDigits: return isLength(4) case .limitNumberOfCharacters(let numberOfCharacters): return isLength(numberOfCharacters) case .limitNumberOfDigits(let length): return isLength(length) case .limitToCharacterSet: return nil case .anyLength: return hasLength } } // MARK:- Formatters fileprivate func formatCurrency(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 21 else { return (text, cursorPosition) } } let (noSpecialsString, newCursorPosition) = removeNonDigits(text, cursorPosition: cursorPosition) let removedCharsCorrectedRange = NSRange(location: range.location + (newCursorPosition - cursorPosition), length: range.length) let (newText, _) = resultingString(noSpecialsString, newInput: newInput, range: removedCharsCorrectedRange, cursorPosition: newCursorPosition) currencyFormatter.numberStyle = .decimal let number = currencyFormatter.number(from: newText) ?? 0 let newValue = NSNumber(value: number.doubleValue / 100.0 as Double) currencyFormatter.numberStyle = .currency if let currencyString = currencyFormatter.string(from: newValue) { return (currencyString, cursorPosition + (currencyString.length - text.length)) } return (text, cursorPosition) } fileprivate func formatDate(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 10 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(2, "\\"), (4, "\\")]) } fileprivate func formatCreditCardExpirationDate(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 5 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(2, "\\")]) } fileprivate func formatCreditCardSixteenDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 19 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(4, " "), (8, " "), (12, " ")]) } fileprivate func formatCreditCardFifteenDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < 17 else { return (text, cursorPosition) } } return removeNonDigitsAndAddCharacters(text, newInput: newInput, range: range, cursorPosition: cursorPosition, characters: [(4, " "), (10, " ")]) } fileprivate func formatCreditCardCVVThreeDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { return limitToDigitsAndLength(3, text: text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func formatCreditCardCVVFourDigits(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { return limitToDigitsAndLength(4, text: text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func limitToDigitsAndLength(_ length: Int, text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { if text.length == length { return (text, cursorPosition) } else if !isDigit(Character(newInput)) { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } fileprivate func limitToLength(_ limit: Int) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitText(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if text.length == limit && newInput != "" { return (text, cursorPosition) } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitText } fileprivate func limitToDigitsWithLength(_ limit: Int) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitText(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard isDigit(Character(newInput)) && text.length < limit else { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitText } fileprivate func limitToCharacterSet(_ set: CharacterSet) -> ((_ text: String, _ newInput: String, _ range: NSRange, _ cursorPosition: Int) -> (String, Int)) { func limitToSet(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { if newInput != "" { guard newInput.rangeOfCharacter(from: set) != nil else { return (text, cursorPosition) } } return resultingString(text, newInput: newInput, range: range, cursorPosition: cursorPosition) } return limitToSet } // MARK: Validators fileprivate func validateCurrency(_ text: String) -> Bool { currencyFormatter.numberStyle = .currency let number = currencyFormatter.number(from: text) ?? 0 return number.doubleValue > 0.0 } fileprivate func isLength(_ length: Int) -> ((_ text: String) -> Bool) { func checkLength(_ text: String) -> Bool { return text.length == length } return checkLength } fileprivate func hasLength(_ text: String) -> Bool { return text.length > 0 } // MARK:- Characters fileprivate func isDigit(_ character: Character) -> Bool { return isDigitOrCharacter("", character: character) } fileprivate func isDigitOrCharacter(_ additionalCharacters: String, character: Character) -> Bool { let digits = CharacterSet.decimalDigits let fullSet = NSMutableCharacterSet(charactersIn: additionalCharacters) fullSet.formUnion(with: digits) if isCharacter(character, aMemberOf: fullSet as CharacterSet) { return true } return false } func resultingString(_ text: String, newInput: String, range: NSRange, cursorPosition: Int) -> (String, Int) { guard range.location >= 0 else { return (text, cursorPosition) } let newText = (text as NSString).replacingCharacters(in: range, with: newInput) return (newText, cursorPosition + (newText.length - text.length)) } fileprivate func removeNonDigits(_ text: String, cursorPosition: Int) -> (String, Int) { var originalCursorPosition = cursorPosition let theText = text var digitsOnlyString = "" for i in 0 ..< theText.length { let characterToAdd = theText[i] if isDigit(characterToAdd) { let stringToAdd = String(characterToAdd) digitsOnlyString.append(stringToAdd) } else if i < cursorPosition { originalCursorPosition -= 1 } } return (digitsOnlyString, originalCursorPosition) } func insertCharactersAtIndexes(_ text: String, characters: [(Int, Character)], cursorPosition: Int) -> (String, Int) { var stringWithAddedChars = "" var newCursorPosition = cursorPosition for i in 0 ..< text.length { for (index, char) in characters { if index == i { stringWithAddedChars.append(char) if i < cursorPosition { newCursorPosition += 1 } } } let characterToAdd = text[i] let stringToAdd = String(characterToAdd) stringWithAddedChars.append(stringToAdd) } return (stringWithAddedChars, newCursorPosition) } func isCharacter(_ c: Character, aMemberOf set: CharacterSet) -> Bool { return set.contains(UnicodeScalar(String(c).utf16.first!)!) } fileprivate func removeNonDigitsAndAddCharacters(_ text: String, newInput: String, range: NSRange, cursorPosition: Int, characters: [(Int, Character)]) -> (String, Int) { let (onlyDigitsText, cursorPos) = removeNonDigits(text, cursorPosition: cursorPosition) let correctedRange = NSRange(location: range.location + (cursorPos - cursorPosition), length: range.length) let (newText, cursorAfterEdit) = resultingString(onlyDigitsText, newInput: newInput, range: correctedRange, cursorPosition: cursorPos) let (withCharacters, newCursorPosition) = insertCharactersAtIndexes(newText, characters: characters, cursorPosition: cursorAfterEdit) return (withCharacters, newCursorPosition) } }
mit
93390bd3fba630555549f2040ab67637
38.526946
174
0.634828
5.037009
false
false
false
false
Anviking/Tentacle
Tentacle/Client.swift
1
8633
// // Client.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Argo import Foundation import ReactiveCocoa import Result extension Decodable { internal static func decode(JSON: NSDictionary) -> Result<DecodedType, DecodeError> { switch decode(.parse(JSON)) { case let .Success(object): return .Success(object) case let .Failure(error): return .Failure(error) } } } extension DecodeError: Hashable { public var hashValue: Int { switch self { case let .TypeMismatch(expected: expected, actual: actual): return expected.hashValue ^ actual.hashValue case let .MissingKey(string): return string.hashValue case let .Custom(string): return string.hashValue } } } public func ==(lhs: DecodeError, rhs: DecodeError) -> Bool { switch (lhs, rhs) { case let (.TypeMismatch(expected: expected1, actual: actual1), .TypeMismatch(expected: expected2, actual: actual2)): return expected1 == expected2 && actual1 == actual2 case let (.MissingKey(string1), .MissingKey(string2)): return string1 == string2 case let (.Custom(string1), .Custom(string2)): return string1 == string2 default: return false } } extension NSJSONSerialization { internal static func deserializeJSON(data: NSData) -> Result<NSDictionary, NSError> { return Result(try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary) } } extension NSURLRequest { internal static func create(server: Server, _ endpoint: Client.Endpoint, _ credentials: Client.Credentials?) -> NSURLRequest { let URL = NSURL(string: server.endpoint)!.URLByAppendingPathComponent(endpoint.path) let request = NSMutableURLRequest(URL: URL) request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept") if let userAgent = Client.userAgent { request.setValue(userAgent, forHTTPHeaderField: "User-Agent") } if let credentials = credentials { request.setValue(credentials.authorizationHeader, forHTTPHeaderField: "Authorization") } return request } } /// A GitHub API Client public final class Client { /// An error from the Client. public enum Error: Hashable, ErrorType { /// An error occurred in a network operation. case NetworkError(NSError) /// An error occurred while deserializing JSON. case JSONDeserializationError(NSError) /// An error occurred while decoding JSON. case JSONDecodingError(DecodeError) /// A status code and error that was returned from the API. case APIError(Int, GitHubError) /// The requested object does not exist. case DoesNotExist public var hashValue: Int { switch self { case let .NetworkError(error): return error.hashValue case let .JSONDeserializationError(error): return error.hashValue case let .JSONDecodingError(error): return error.hashValue case let .APIError(statusCode, error): return statusCode.hashValue ^ error.hashValue case .DoesNotExist: return 4 } } } /// Credentials for the GitHub API. internal enum Credentials { case Token(String) case Basic(username: String, password: String) var authorizationHeader: String { switch self { case let .Token(token): return "token \(token)" case let .Basic(username, password): let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! let encodedString = data.base64EncodedStringWithOptions([]) return "Basic \(encodedString)" } } } /// A GitHub API endpoint. internal enum Endpoint: Hashable { case ReleaseByTagName(owner: String, repository: String, tag: String) var path: String { switch self { case let .ReleaseByTagName(owner, repo, tag): return "/repos/\(owner)/\(repo)/releases/tags/\(tag)" } } var hashValue: Int { switch self { case let .ReleaseByTagName(owner, repo, tag): return owner.hashValue ^ repo.hashValue ^ tag.hashValue } } } /// The user-agent to use for API requests. public static var userAgent: String? /// The Server that the Client connects to. public let server: Server /// The Credentials for the API. private let credentials: Credentials? /// Create an unauthenticated client for the given Server. public init(_ server: Server) { self.server = server self.credentials = nil } /// Create an authenticated client for the given Server with a token. public init(_ server: Server, token: String) { self.server = server self.credentials = .Token(token) } /// Create an authenticated client for the given Server with a username and password. public init(_ server: Server, username: String, password: String) { self.server = server self.credentials = .Basic(username: username, password: password) } /// Fetch the release corresponding to the given tag in the given repository. /// /// If the tag exists, but there's not a correspoding GitHub Release, this method will return a /// `.DoesNotExist` error. This is indistinguishable from a nonexistent tag. public func releaseForTag(tag: String, inRepository repository: Repository) -> SignalProducer<Release, Error> { precondition(repository.server == server) return fetchOne(Endpoint.ReleaseByTagName(owner: repository.owner, repository: repository.name, tag: tag)) } /// Fetch an object from the API. internal func fetchOne<Object: Decodable where Object.DecodedType == Object>(endpoint: Endpoint) -> SignalProducer<Object, Error> { return NSURLSession .sharedSession() .rac_dataWithRequest(NSURLRequest.create(server, endpoint, credentials)) .mapError(Error.NetworkError) .flatMap(.Concat) { data, response -> SignalProducer<Object, Error> in let response = response as! NSHTTPURLResponse return SignalProducer .attempt { return NSJSONSerialization.deserializeJSON(data).mapError(Error.JSONDeserializationError) } .attemptMap { JSON in if response.statusCode == 404 { return .Failure(.DoesNotExist) } if response.statusCode >= 400 && response.statusCode < 600 { return GitHubError.decode(JSON) .mapError(Error.JSONDecodingError) .flatMap { .Failure(Error.APIError(response.statusCode, $0)) } } return Object.decode(JSON).mapError(Error.JSONDecodingError) } } } } public func ==(lhs: Client.Error, rhs: Client.Error) -> Bool { switch (lhs, rhs) { case let (.NetworkError(error1), .NetworkError(error2)): return error1 == error2 case let (.JSONDeserializationError(error1), .JSONDeserializationError(error2)): return error1 == error2 case let (.JSONDecodingError(error1), .JSONDecodingError(error2)): return error1 == error2 case let (.APIError(statusCode1, error1), .APIError(statusCode2, error2)): return statusCode1 == statusCode2 && error1 == error2 case (.DoesNotExist, .DoesNotExist): return true default: return false } } internal func ==(lhs: Client.Endpoint, rhs: Client.Endpoint) -> Bool { switch (lhs, rhs) { case let (.ReleaseByTagName(owner1, repo1, tag1), .ReleaseByTagName(owner2, repo2, tag2)): return owner1 == owner2 && repo1 == repo2 && tag1 == tag2 } }
mit
a65e43d006e1df5221604f1d5a57d3b6
33.947368
135
0.593373
5.181273
false
false
false
false
Suninus/SwiftFilePath
SwiftFilePath/Path.swift
1
3090
// // Path.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // public class Path { // MARK: - Class methods public class func isDir(path:NSString) -> Bool { var isDirectory: ObjCBool = false let isFileExists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory:&isDirectory) return isDirectory ? true : false } // MARK: - Instance properties and initializer lazy var fileManager = NSFileManager.defaultManager() public let path_string:String public init(_ p: String) { self.path_string = p } // MARK: - Instance val public var attributes:NSDictionary?{ get { return self.loadAttributes() } } public var asString: String { return path_string } public var exists: Bool { return fileManager.fileExistsAtPath(path_string) } public var isDir: Bool { return Path.isDir(path_string); } public var basename:NSString { return path_string.lastPathComponent } public var parent: Path{ return Path( path_string.stringByDeletingLastPathComponent ) } // MARK: - Instance methods public func toString() -> String { return path_string } public func remove() -> Result<Path,NSError> { assert(self.exists,"To remove file, file MUST be exists") var error: NSError? let result = fileManager.removeItemAtPath(path_string, error:&error) return result ? Result(success: self) : Result(failure: error!); } public func copyTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To copy file, file MUST be exists") var error: NSError? let result = fileManager.copyItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } public func moveTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To move file, file MUST be exists") var error: NSError? let result = fileManager.moveItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } private func loadAttributes() -> NSDictionary? { assert(self.exists,"File must be exists to load file.< \(path_string) >") var loadError: NSError? let result = self.fileManager.attributesOfItemAtPath(path_string, error: &loadError) if let error = loadError { println("Error< \(error.localizedDescription) >") } return result } } // MARK: - extension Path: Printable { public var description: String { return "\(NSStringFromClass(self.dynamicType))<path:\(path_string)>" } }
mit
9af407d0a51d2486ddc1f7a7a483c349
25.852174
106
0.593264
4.664653
false
false
false
false
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/SelfSizingSectionController.swift
4
3116
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class SelfSizingSectionController: ListSectionController { private var model: SelectionModel! override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 40, right: 0) minimumLineSpacing = 4 minimumInteritemSpacing = 4 } override func numberOfItems() -> Int { return model.options.count } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { let text = model.options[index] let cell: UICollectionViewCell switch model.type { case .none: guard let manualCell = collectionContext?.dequeueReusableCell(of: ManuallySelfSizingCell.self, for: self, at: index) as? ManuallySelfSizingCell else { fatalError() } manualCell.text = text cell = manualCell case .fullWidth: guard let manualCell = collectionContext?.dequeueReusableCell(of: FullWidthSelfSizingCell.self, for: self, at: index) as? FullWidthSelfSizingCell else { fatalError() } manualCell.text = text cell = manualCell case .nib: guard let nibCell = collectionContext?.dequeueReusableCell(withNibName: "NibSelfSizingCell", bundle: nil, for: self, at: index) as? NibSelfSizingCell else { fatalError() } nibCell.contentLabel.text = text cell = nibCell } return cell } override func didUpdate(to object: Any) { self.model = object as? SelectionModel } }
mit
a2648d5eb61d80e1cd3d9cacc105b620
41.108108
119
0.519576
6.438017
false
false
false
false
frootloops/swift
stdlib/public/core/CString.swift
1
8164
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, this /// initializer replaces them with the Unicode replacement character /// (`"\u{FFFD}"`). /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Café" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Caf�" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. @_inlineable // FIXME(sil-serialize-all) public init(cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len) { _decodeCString( $0, as: UTF8.self, length: len, repairingInvalidCodeUnits: true)! } self = result } /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// This is identical to init(cString: UnsafePointer<CChar> but operates on an /// unsigned sequence of bytes. @_inlineable // FIXME(sil-serialize-all) public init(cString: UnsafePointer<UInt8>) { self = String.decodeCString( cString, as: UTF8.self, repairingInvalidCodeUnits: true)!.result } /// Creates a new string by copying and validating the null-terminated UTF-8 /// data referenced by the given pointer. /// /// This initializer does not try to repair ill-formed UTF-8 code unit /// sequences. If any are found, the result of the initializer is `nil`. /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "Optional(Café)" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "nil" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. @_inlineable // FIXME(sil-serialize-all) public init?(validatingUTF8 cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) guard let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len, { _decodeCString($0, as: UTF8.self, length: len, repairingInvalidCodeUnits: false) }) else { return nil } self = result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// When you pass `true` as `isRepairing`, this method replaces ill-formed /// sequences with the Unicode replacement character (`"\u{FFFD}"`); /// otherwise, an ill-formed sequence causes this method to stop decoding /// and return `nil`. /// /// The following example calls this method with pointers to the contents of /// two different `CChar` arrays---the first with well-formed UTF-8 code /// unit sequences and the second with an ill-formed sequence at the end. /// /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Café, false))" /// /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Caf�, true))" /// /// - Parameters: /// - cString: A pointer to a null-terminated code sequence encoded in /// `encoding`. /// - encoding: The Unicode encoding of the data referenced by `cString`. /// - isRepairing: Pass `true` to create a new string, even when the data /// referenced by `cString` contains ill-formed sequences. Ill-formed /// sequences are replaced with the Unicode replacement character /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new /// string if an ill-formed sequence is detected. /// - Returns: A tuple with the new string and a Boolean value that indicates /// whether any repairs were made. If `isRepairing` is `false` and an /// ill-formed sequence is detected, this method returns `nil`. @_inlineable // FIXME(sil-serialize-all) public static func decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { guard let cString = cString else { return nil } var end = cString while end.pointee != 0 { end += 1 } let len = end - cString return _decodeCString( cString, as: encoding, length: len, repairingInvalidCodeUnits: isRepairing) } } /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. @_inlineable // FIXME(sil-serialize-all) public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// This internal helper takes the string length as an argument. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, length: Int, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { let buffer = UnsafeBufferPointer<Encoding.CodeUnit>( start: cString, count: length) let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits( buffer, encoding: encoding, repairIllFormedSequences: isRepairing) return stringBuffer.map { (result: String(_storage: $0), repairsMade: hadError) } }
apache-2.0
8148066400ac7ee8b2607ae11efd4543
38.790244
81
0.622533
4.263983
false
false
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallSpinFadeLoader.swift
2
3771
// // NVActivityIndicatorAnimationBallSpinFadeLoader.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallSpinFadeLoader: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = -2 let circleSize = (size.width - 4 * circleSpacing) / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84] // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.4, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimaton = CAKeyframeAnimation(keyPath: "opacity") opacityAnimaton.keyTimes = [0, 0.5, 1] opacityAnimaton.values = [1, 0.3, 1] opacityAnimaton.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimaton] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 8 { let circle = circleAt(angle: CGFloat(M_PI_4 * Double(i)), size: circleSize, origin: CGPoint(x: x, y: y), containerSize: size, color: color) animation.beginTime = beginTime + beginTimes[i] circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } func circleAt(angle: CGFloat, size: CGFloat, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer { let radius = containerSize.width / 2 - size / 2 let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect( x: origin.x + radius * (cos(angle) + 1), y: origin.y + radius * (sin(angle) + 1), width: size, height: size) circle.frame = frame return circle } }
mit
e3249b44e0d03f688ee921e03d83c8d1
40.43956
117
0.636436
4.834615
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/CouponAnnotationView.swift
1
2212
// // CouponAnnotationView.swift // Wakup // // Created by Guillermo Gutiérrez on 7/1/16. // Copyright © 2016 Yellow Pineapple. All rights reserved. // import Foundation import MapKit @objc open class ColorForTags: NSObject { public let tags: Set<String> public let color: UIColor public let mapIcon: String public init(tags: Set<String>, mapIcon: String, color: UIColor) { self.tags = tags self.color = color self.mapIcon = mapIcon } } open class CouponAnnotationView: MKAnnotationView { @objc open dynamic var mapPinSize = CGSize(width: 46, height: 60) @objc open dynamic var iconAndColorForTags: [ColorForTags] = [ ColorForTags(tags: ["restaurants"], mapIcon: "map-restaurant-pin", color: StyleKit.restaurantCategoryColor), ColorForTags(tags: ["leisure"], mapIcon: "map-leisure-pin", color: StyleKit.leisureCategoryColor), ColorForTags(tags: ["services"], mapIcon: "map-services-pin", color: StyleKit.servicesCategoryColor), ColorForTags(tags: ["shopping"], mapIcon: "map-shopping-pin", color: StyleKit.shoppingCategoryColor), ColorForTags(tags: [], mapIcon: "map-pin", color: StyleKit.corporateDarkColor) // Empty tag list for default pin and color ] func mapIconId(forOffer offer: Coupon) -> (String, UIColor) { let offerTags = Set(offer.tags) for element in iconAndColorForTags { if !offerTags.intersection(element.tags).isEmpty || element.tags.isEmpty { return (element.mapIcon, element.color) } } return ("map-pin", StyleKit.corporateDarkColor) } open override func layoutSubviews() { super.layoutSubviews() guard let couponAnnotation = annotation as? CouponAnnotation else { return } let iconFrame = CGRect(x: 0, y: 0, width: mapPinSize.width, height: mapPinSize.height) let (mapPinId, pinColor) = mapIconId(forOffer: couponAnnotation.coupon) let iconImage = CodeIcon(iconIdentifier: mapPinId).getImage(iconFrame, color: pinColor) image = iconImage centerOffset = CGPoint(x: 0, y: (-mapPinSize.height / 2) + 1) } }
mit
e26a3392bdd9fc13f62b623770e89a1e
37.103448
130
0.665158
4.233716
false
false
false
false
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Renderers/CandleStickChartRenderer.swift
20
9754
// // CandleStickChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class CandleStickChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: CandleChartDataProvider? public init(dataProvider: CandleChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } for set in candleData.dataSets as! [CandleChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint()) private var _bodyRect = CGRect() private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(context context: CGContext, dataSet: CandleChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency) else { return } let phaseX = _animator.phaseX let phaseY = _animator.phaseY let bodySpace = dataSet.bodySpace var entries = dataSet.yVals as! [CandleChartDataEntry] let minx = max(_minX, 0) let maxx = min(_maxX + 1, entries.count) CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.shadowWidth) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { // get the entry let e = entries[j] if (e.xIndex < _minX || e.xIndex > _maxX) { continue } // calculate the shadow _shadowPoints[0].x = CGFloat(e.xIndex) _shadowPoints[0].y = CGFloat(e.high) * phaseY _shadowPoints[1].x = CGFloat(e.xIndex) _shadowPoints[1].y = CGFloat(e.low) * phaseY trans.pointValuesToPixel(&_shadowPoints) // draw the shadow var shadowColor: UIColor! = nil if (dataSet.shadowColorSameAsCandle) { if (e.open > e.close) { shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j) } else if (e.open < e.close) { shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j) } } if (shadowColor === nil) { shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j); } CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeLineSegments(context, _shadowPoints, 2) // calculate the body _bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace _bodyRect.origin.y = CGFloat(e.close) * phaseY _bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x _bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y trans.rectValueToPixel(&_bodyRect) // draw body differently for increasing and decreasing entry if (e.open > e.close) { let color = dataSet.decreasingColor ?? dataSet.colorAt(j) if (dataSet.isDecreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else if (e.open < e.close) { let color = dataSet.increasingColor ?? dataSet.colorAt(j) if (dataSet.isIncreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else { CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeRect(context, _bodyRect) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } // if values are drawn if (candleData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { var dataSets = candleData.dataSets for (var i = 0; i < dataSets.count; i++) { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor let formatter = dataSet.valueFormatter let trans = dataProvider.getTransformer(dataSet.axisDependency) var entries = dataSet.yVals as! [CandleChartDataEntry] let minx = max(_minX, 0) let maxx = min(_maxX + 1, entries.count) var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY) let lineHeight = valueFont.lineHeight let yOffset: CGFloat = lineHeight + 5.0 for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++) { let x = positions[j].x let y = positions[j].y if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y)) { continue } let val = entries[j].high ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, candleData = dataProvider.candleData else { return } CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { let xIndex = indices[i].xIndex; // get the x-position let set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } let e = set.entryForXIndex(xIndex) as! CandleChartDataEntry! if (e === nil || e.xIndex != xIndex) { continue } let trans = dataProvider.getTransformer(set.axisDependency) CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let low = CGFloat(e.low) * _animator.phaseY let high = CGFloat(e.high) * _animator.phaseY let y = (low + high) / 2.0 _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
2688e7a8960859f20709f0c81a004519
34.863971
246
0.524093
5.840719
false
false
false
false
michael-yuji/spartanX
Sources/SXService.swift
2
4445
// Copyright (c) 2016, Yuji // 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 9/5/16. // Copyright © 2016 yuuji. All rights reserved. // import struct Foundation.Data public typealias ShouldProceed = Bool public let YES = true public let NO = false /// a SXService is a protocol to define a service that can use in spartanX public protocol SXService { // this is here to support low-level optimization, for example, if we are sending pure http content with // static files, it is much less expensive to use sendfile() instead of send(), since it can implement by // both sendfile() and send(), the supportingMethods should include both. // when the service is nested in another service, for example TLS, sendfile is no longer available // but send() is still available, this supporting method here hints what kind of optimazation is available // in the end var supportingMethods: SendMethods { get set } /// What to do when a package is received /// /// - Parameters: /// - data: The payload received /// - connection: in which connection /// - Returns: depends on the payload, should the server retain this connection(true) or disconnect(false) /// - Throws: Raise an exception and handle with exceptionRaised() func received(data: Data, from connection: SXConnection) throws -> ShouldProceed /// Handle Raised exceptions raised in received() /// /// - Parameters: /// - exception: Which exception raised /// - connection: in which connection /// - Returns: should the server retain this connection(true) or disconnect(false) func exceptionRaised(_ exception: Error, on connection: SXConnection) -> ShouldProceed } /// a SXStreamService is smaliar to SXService that slightly powerful but can only use on stream connections /// a SXSrreamService can perform actions when a new connection is accepted, when a connection is going to /// terminate, and when a connection has terminated public protocol SXStreamService : SXService { func accepted(socket: SXClientSocket, as connection: SXConnection) throws func connectionWillTerminate(_ connection: SXConnection) func connectionDidTerminate(_ connection: SXConnection) } /// a simple data transfer service open class SXConnectionService: SXService { open func exceptionRaised(_ exception: Error, on connection: SXConnection) -> ShouldProceed { return false } open var supportingMethods: SendMethods = [.send, .sendfile, .sendto] open func received(data: Data, from connection: SXConnection) throws -> ShouldProceed { return try self.dataHandler(data, connection) } open var dataHandler: (Data, SXConnection) throws -> ShouldProceed public init(handler: @escaping (Data, SXConnection) throws -> ShouldProceed) { self.dataHandler = handler } }
bsd-2-clause
d87cb4bd377a2d6196dc4a9660f39206
42.145631
110
0.731323
4.712619
false
false
false
false