repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
halonsoluis/MiniRev
MiniRev/MiniRev/ReviewManager/RateFlowViewController.swift
1
1932
// // RateFlowViewController.swift // MiniRev // // Created by Hugo on 12/22/15. // Copyright © 2015 Hugo Alonso. All rights reserved. // import Foundation import UIKit class RateFlowViewController: UIViewController { @IBOutlet weak var firstPageTitle: UILabel! @IBOutlet weak var giveAReviewTitle: UILabel! @IBOutlet weak var sendMailTitle: UILabel! @IBOutlet weak var appNamed: UILabel! override func viewDidLoad() { appNamed?.text = RateDataManager.getAppName() } @IBAction func prepareForFeedBack(sender: AnyObject) { guard let parentViewController = self.parentViewController?.parentViewController else { return } removeReview() { let receipt = SocialAccounts.getEmailReceipt() let receipts = [receipt] let subject = NSLocalizedString(SubjectOptions.WhatIDontLike.rawValue, comment: "Subject") let mail = MailHandler(receipts: receipts, subject: subject, messageBody: "") mail.sendMail(parentViewController) { RateHandler.neverRate() } } } @IBAction func goToAppStore(sender: AnyObject) { removeReview(){ RateHandler.goToRate() } } @IBAction func remindmeLater(sender: AnyObject) { removeReview() } func removeReview(doneCallBack: (()->Void)?=nil) { UIView.animateWithDuration(0.35, animations: { () -> Void in self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, -110) }) { (_) -> Void in //self.view.removeFromSuperview() if let parent = self.parentViewController { parent.removeFromParentViewController() } //self.removeFromParentViewController() doneCallBack?() } } }
mit
6d9808d8e6fbca8a5005e16509ea2796
29.650794
98
0.601761
5.094987
false
false
false
false
ivlevAstef/DITranquillity
Sources/Core/API/DIModificators.swift
1
3833
// // DIModificators.swift // DITranquillity // // Created by Alexander Ivlev on 25/08/2017. // Copyright © 2017 Alexander Ivlev. All rights reserved. // /// Short syntax for get object by tag /// Using: /// ``` /// let object: YourType = by(tag: YourTag.self, on: *container) /// ``` /// also can using in injection or init: /// ``` /// .injection{ $0.property = by(tag: YourTag.self, on: $1) } /// ``` /// /// - Parameters: /// - tag: a tag /// - obj: resolving object /// - Returns: resolved object public func by<Tag,T>(tag: Tag.Type, on obj: DIByTag<Tag,T>) -> T { return obj._object } /// Short syntax for get object by two tags /// Using: /// ``` /// let object: YourType = by(tags: YourTag.self, YourTag2.self, on: *container) /// ``` /// also can using in injection or init: /// ``` /// .injection{ $0.property = by(tags: YourTag.self, YourTag2.self, on: $1) } /// ``` /// /// - Parameters: /// - tag: a tag /// - obj: resolving object /// - Returns: resolved object public func by<Tag1, Tag2, T>(tags: Tag1.Type, _ t: Tag2.Type, on obj: DIByTag<Tag1, DIByTag<Tag2,T>>) -> T { return obj._object._object } /// Short syntax for get object by three tags /// Using: /// ``` /// let object: YourType = by(tags: YourTag.self, YourTag2.self, YourTag3.self, on: *container) /// ``` /// also can using in injection or init: /// ``` /// .injection{ $0.property = by(tags: YourTag.self, YourTag2.self, YourTag3.self, on: $1) } /// ``` /// /// - Parameters: /// - tag: a tag /// - obj: resolving object /// - Returns: resolved object public func by<Tag1, Tag2, Tag3, T>(tags: Tag1.Type, _ t2: Tag2.Type, _ t3: Tag3.Type, on obj: DIByTag<Tag1, DIByTag<Tag2, DIByTag<Tag3,T>>>) -> T { return obj._object._object._object } /// Special class for resolve object by type with tag. see method: `byTag` public final class DIByTag<Tag, T>: InternalByTag<Tag, T> {} /// Short syntax for get many objects /// Using: /// ``` /// let objects: [YourType] = many(*container) /// ``` /// also can using in injection or init: /// ``` /// .injection{ $0.property = many($1) } /// ``` /// /// - Parameter obj: resolving objects /// - Returns: resolved objects public func many<T>(_ obj: DIMany<T>) -> [T] { return obj._objects } /// Short syntax for get many objects in framework /// Using: /// ``` /// let objects: [YourType] = manyInFramework(*container) /// ``` /// also can using in injection or init: /// ``` /// .injection{ $0.property = manyInFramework($1) } /// ``` /// /// - Parameter obj: resolving objects /// - Returns: resolved objects public func manyInFramework<T>(_ obj: DIManyInFramework<T>) -> [T] { return obj._objects } /// Special class for resolve many object. see method: `many` public final class DIMany<T>: InternalByMany<T> {} /// Special class for resolve many object in framework. see method: `manyInFramework` public final class DIManyInFramework<T>: InternalByManyInFramework<T> {} /// Short syntax for get object use arguments /// Simple using: /// ``` /// container.register{ YourClass(p1: $0, p2: arg($1)) } /// .injection{ $0.property = arg($1) } /// ... /// container.extension(for: YourClass.self).setArgs(15, "it's work!") /// let yourClass = *container // p1 - injected, p2 = 15, property = "it's work!" /// ``` /// Also your forward parameters at any depth /// Warning: not use with cycle injection `.injection(cycle: true...` - it's not good /// Warning: Unsafe type - if you pass an object of wrong type, The library will fall. Exception: type of optional /// /// - Parameters: /// - name: The external name for the argument /// - obj: resolving object /// - Returns: resolved object public func arg<T>(_ obj: DIArg<T>) -> T { return obj._object } /// Special class for resolve object use arguments. see method: `arg` public final class DIArg<T>: InternalArg<T> {}
mit
1be46266017f0eede4096de2186c5eb6
28.705426
148
0.63596
3.21207
false
false
false
false
LouXiaXiaoHei/LXMagicRecordCamera
LXMagicRecordCamera/Classes/LXMagicRecordCameraConfig.swift
1
1429
// // LXMagicRecordCameraConfig.swift // Pods // // Created by 邓小涛 on 2017/7/13. // // import Foundation import AVFoundation class LXMagicRecordCameraConfig:NSObject { //Max Recording Video Time public static let maxRecordingTime:TimeInterval = 30 //Min Recording Video Time public static let minRecordingTime:TimeInterval = 3 //最大镜头焦距 public static let maxVideoZoomFactor:CGFloat = 20 //Video Setting public static let videoSetting:[String : Any] = [ AVVideoCodecKey : AVVideoCodecH264, AVVideoWidthKey : 720, AVVideoHeightKey: 1280, AVVideoCompressionPropertiesKey: [ AVVideoProfileLevelKey : AVVideoProfileLevelH264Main31, AVVideoAllowFrameReorderingKey : false, //码率 AVVideoAverageBitRateKey : 720 * 1280 * 3 ] ] //audio Setting public static let audioSetting:[String : Any] = [ AVFormatIDKey : kAudioFormatMPEG4AAC, AVNumberOfChannelsKey : 2, AVSampleRateKey : 16000, AVEncoderBitRateKey : 32000 ] //Video Path public static let videoPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/Video") //Video OutPut Size public static let outputVideoSize:CGSize = CGSize.init(width: 720, height: 1280) }
mit
3719bbd9064af6f6c5898d5bd2dcc702
27.14
139
0.655295
4.885417
false
false
false
false
GreenBeanD/LCTool
LCTool/Main/AppDelegate.swift
1
2494
// // AppDelegate.swift // LCTool // // Created by 懒猫 on 2017/10/16. // Copyright © 2017年 懒猫. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow.init(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.white let homeVC = HomeViewController() let nav = UINavigationController.init(rootViewController: homeVC) self.window?.rootViewController = nav self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
2a497518334620349a47a705a475e136
41.084746
285
0.741845
5.505543
false
false
false
false
visenze/visearch-sdk-swift
Example/Example/Lib/ALCameraViewController/Utilities/UIButtonExtensions.swift
2
1390
// // UIButtonExtensions.swift // ALCameraViewController // // Created by Alex Littlejohn on 2016/03/26. // Copyright © 2016 zero. All rights reserved. // import UIKit typealias ButtonAction = () -> Void extension UIButton { private struct AssociatedKeys { static var ActionKey = "ActionKey" } private class ActionWrapper { let action: ButtonAction init(action: @escaping ButtonAction) { self.action = action } } var action: ButtonAction? { set(newValue) { removeTarget(self, action: #selector(performAction), for: .touchUpInside) var wrapper: ActionWrapper? = nil if let newValue = newValue { wrapper = ActionWrapper(action: newValue) addTarget(self, action: #selector(performAction), for: .touchUpInside) } objc_setAssociatedObject(self, &AssociatedKeys.ActionKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { guard let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.ActionKey) as? ActionWrapper else { return nil } return wrapper.action } } @objc func performAction() { guard let action = action else { return } action() } }
mit
70bb667955cd97fba3d71483549b6a46
24.722222
114
0.574514
5.106618
false
false
false
false
DivineDominion/mac-multiproc-code
RelocationManager/BoxAndItemData.swift
1
1257
// // BoxAndItemData.swift // RelocationManager // // Created by Christian Tietze on 02/12/14. // Copyright (c) 2014 Christian Tietze. All rights reserved. // import Foundation public protocol HandlesItemListEvents: class { func createBox() func createItem() func changeBoxTitle(boxId: BoxId, title: String) func changeItemTitle(itemId: ItemId, title: String, inBox boxId: BoxId) func removeBox(boxId: BoxId) func removeItem(itemId: ItemId, fromBox boxId: BoxId) } public struct BoxData { let boxId: BoxId let title: String let itemData: [ItemData] public init(boxId: BoxId, title: String) { self.init(boxId: boxId, title: title, itemData: []) } public init(boxId: BoxId, title: String, itemData: [ItemData]) { self.boxId = boxId self.title = title self.itemData = itemData } } public struct ItemData { let itemId: ItemId let title: String var boxId: BoxId? public init(itemId: ItemId, title: String) { self.itemId = itemId self.title = title } public init(itemId: ItemId, title: String, boxId: BoxId) { self.itemId = itemId self.title = title self.boxId = boxId } }
mit
c0024b576609830d98bec18b8e49b664
22.716981
75
0.634845
3.675439
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/CHPageCardView/CHPageCardView/Classes/CHPageCardView.swift
2
9585
// // CHPageCardView.swift // Pods // // Created by Chance on 2017/2/27. // // import UIKit /// 组件委托代理方法 @objc public protocol CHPageCardViewDelegate: class { /// 卡片单元总数量 /// /// - Parameter pageCardView: 卡片切换组件 /// - Returns: 委托的卡片的数量 func numberOfCards(in pageCardView: CHPageCardView) -> Int /// 卡片的样式配置 /// /// - Parameters: /// - pageCardView: 卡片切换组件 /// - row: 索引 /// - Returns: 布局样式对象 func pageCardView(_ pageCardView: CHPageCardView, cellForIndexAt index: Int) -> UICollectionViewCell /// 选择卡片方法 /// /// - Parameters: /// - pageCardView: 卡片切换组件 /// - row: 选中的索引 func pageCardView(_ pageCardView: CHPageCardView, didSelectIndexAt index: Int) } /// 横向切换的卡片选择组件 /* 实现原理: 1.初始化后,注册用户自定义的Cell视图到组件的collectionView 2.建立所有View,通过委托方法获取数据源,实现UICollectionView的代理方法 3.滑动过程响应相关委托方法,返回数据 */ public class CHPageCardView: UIView { /// 卡片控制的主视图 public var collectionView: UICollectionView! /// 页面数显示 public var pageControl: UIPageControl! //单元格之间的间距 @IBInspectable public var fixLineSpace: CGFloat = 0 { didSet { if self.layout != nil { self.layout.minimumLineSpacing = self.fixLineSpace } } } //单元格的固定大小 @IBInspectable public var fixCellSize: CGSize = CGSize.zero { didSet { if self.layout != nil { self.layout.itemSize = self.fixCellSize } } } /// 单元格固定内间距,如果使用了fixPadding,则fixCellSize不起效果 @IBInspectable public var fixPadding: UIEdgeInsets = UIEdgeInsets.zero @IBInspectable public var bgImage: UIImage? { didSet { self.backgroundView.image = self.bgImage! self.backgroundView.isHidden = false } } /// 布局控制 var layout: CHPageCardFlowLayout! var backgroundView: UIImageView! @IBOutlet public weak var delegate: CHPageCardViewDelegate? override public init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // self.setupUI() } public override func awakeFromNib() { super.awakeFromNib() self.setupUI() } public override func layoutSubviews() { super.layoutSubviews() if self.fixPadding != .zero { //如果设置了固定内间距,重新计算cell的尺寸 let vPadding = self.fixPadding.top > self.fixPadding.bottom ? self.fixPadding.top : self.fixPadding.bottom let hPadding = self.fixPadding.left > self.fixPadding.right ? self.fixPadding.left : self.fixPadding.right let height = self.bounds.size.height - vPadding * 2 let width = self.bounds.size.width - (hPadding + self.fixLineSpace) * 2 self.fixCellSize = CGSize(width: width, height: height) } } /// 初始化布局 func setupUI() { /********* 初始化 *********/ self.layout = CHPageCardFlowLayout() self.layout.delegate = self self.layout.itemSize = self.fixCellSize self.layout.minimumLineSpacing = self.fixLineSpace self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.layout) self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.collectionView) self.collectionView.decelerationRate = 0; self.collectionView.showsHorizontalScrollIndicator = false; self.collectionView.delegate = self self.collectionView.dataSource = self self.collectionView.backgroundColor = UIColor.clear self.pageControl = UIPageControl() self.pageControl.translatesAutoresizingMaskIntoConstraints = false self.pageControl.pageIndicatorTintColor = UIColor(white: 1, alpha: 0.3) self.addSubview(self.pageControl) self.backgroundView = UIImageView() self.backgroundView.translatesAutoresizingMaskIntoConstraints = false self.backgroundView.isHidden = true self.addSubview(self.backgroundView) /********* 约束布局 *********/ let views: [String : Any] = [ "collectionView": self.collectionView, "pageControl": self.pageControl, "backgroundView": self.backgroundView ] self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[pageControl]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views:views)) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:[pageControl(30)]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views:views)) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views:views)) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[collectionView]-0-[pageControl]", options: NSLayoutFormatOptions(), metrics: nil, views:views)) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[backgroundView]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views:views)) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[backgroundView]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views:views)) } /// 获取一个可重用的单元格 /// /// - Parameters: /// - identifier: /// - index: /// - Returns: public func dequeueReusableCell(withReuseIdentifier identifier: String, for index: Int) -> UICollectionViewCell { return self.collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: IndexPath(row: index, section: 0)) } /// 注册一个可重用的识别名 public func register(cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) { self.collectionView.register(cellClass, forCellWithReuseIdentifier: identifier) } /// 注册一个可重用的识别名 public func register(nib: UINib?, forCellWithReuseIdentifier identifier: String) { self.collectionView.register(nib, forCellWithReuseIdentifier: identifier) } /// 滚动到某个位置 /// /// - Parameters: /// - index: 滚动的目标索引未 /// - animated: 是否动画 open func scroll(toIndex index: Int, animated animated: Bool) { let indexPath = IndexPath(row: index, section: 0) let attr = self.collectionView.layoutAttributesForItem(at: indexPath) self.collectionView.scrollToItem(at: attr!.indexPath, at: .centeredHorizontally, animated: animated) self.layout.previousOffsetX = CGFloat(index) * (self.fixCellSize.width + self.fixLineSpace) self.pageControl.currentPage = index } /// 重新加载 open func reloadData() { if self.collectionView != nil { self.collectionView.reloadData() } } /// 更新索引位单元格对象 /// /// - Parameter index: 索引位 open func reloadItems(at index: Int, animated animated: Bool = true) { let indexPath = IndexPath(row: index, section: 0) if animated { self.collectionView.reloadItems(at: [indexPath]) } else { UIView.performWithoutAnimation { self.collectionView.reloadItems(at: [indexPath]) } } } } // MARK: - 实现布局控制委托方法 extension CHPageCardView: CHPageCardFlowLayoutDelegate { func scrollToPageIndex(index: Int) { self.pageControl.currentPage = index self.delegate?.pageCardView(self, didSelectIndexAt: index) } } // MARK: - 实现CollectionView的委托方法 extension CHPageCardView: UICollectionViewDelegate, UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = self.delegate?.numberOfCards(in: self) ?? 0 self.pageControl.numberOfPages = count return count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return self.delegate!.pageCardView(self, cellForIndexAt: indexPath.row) } }
mit
f1560a4457588958d4552a27f2f39e4b
29.07047
128
0.608414
4.907448
false
false
false
false
lzpfmh/actor-platform
actor-apps/app-ios/ActorCore/Conversions.swift
1
4608
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation extension NSData { func toJavaBytes() -> IOSByteArray { return IOSByteArray(bytes: UnsafePointer<jbyte>(self.bytes), count: UInt(self.length)) } func readUInt8() -> UInt8 { var raw: UInt8 = 0; self.getBytes(&raw, length: 1) return raw } func readUInt8(offset: Int) -> UInt8 { var raw: UInt8 = 0; self.getBytes(&raw, range: NSMakeRange(offset, 1)) return raw } func readUInt32() -> UInt32 { var raw: UInt32 = 0; self.getBytes(&raw, length: 4) return raw.bigEndian } func readUInt32(offset: Int) -> UInt32 { var raw: UInt32 = 0; self.getBytes(&raw, range: NSMakeRange(offset, 4)) return raw.bigEndian } func readNSData(offset: Int, len: Int) -> NSData { return self.subdataWithRange(NSMakeRange(Int(offset), Int(len))) } } extension ACMessage { var isOut: Bool { get { return Actor.myUid() == self.senderId } } } //extension ACAuthStateEnum { // //} // ////public func ==(lhs: ACAuthStateEnum, rhs: ACAuthStateEnum) -> Bool { //// return lhs.ordinal() == rhs.ordinal() ////} extension JavaUtilAbstractCollection : SequenceType { public func generate() -> NSFastGenerator { return NSFastGenerator(self) } } extension ACPeer { var isGroup: Bool { get { return UInt(self.peerType.ordinal()) == ACPeerType.GROUP.rawValue } } } extension NSMutableData { func appendUInt32(value: UInt32) { var raw = value.bigEndian self.appendBytes(&raw, length: 4) } func appendByte(value: UInt8) { var raw = value self.appendBytes(&raw, length: 1) } } extension jlong { func toNSNumber() -> NSNumber { return NSNumber(longLong: self) } } extension jint { func toNSNumber() -> NSNumber { return NSNumber(int: self) } } extension JavaLangLong { func toNSNumber() -> NSNumber { return NSNumber(longLong: self.longLongValue()) } } extension ARListEngineRecord { func dbQuery() -> AnyObject { if (self.getQuery() == nil) { return NSNull() } else { return self.getQuery().lowercaseString } } } extension NSMutableData { /** Convenient way to append bytes */ internal func appendBytes(arrayOfBytes: [UInt8]) { self.appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } extension NSData { public func checksum() -> UInt16 { var s:UInt32 = 0; var bytesArray = self.bytes(); for (var i = 0; i < bytesArray.count; i++) { s = s + UInt32(bytesArray[i]) } s = s % 65536; return UInt16(s); } } extension JavaUtilArrayList { func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.size() { res.append(self.getWithInt(i) as! T) } return res } func toSwiftArray() -> [AnyObject] { var res = [AnyObject]() for i in 0..<self.size() { res.append(self.getWithInt(i)) } return res } } extension IOSObjectArray { func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.length() { res.append(self.objectAtIndex(UInt(i)) as! T) } return res } func toSwiftArray() -> [AnyObject] { var res = [AnyObject]() for i in 0..<self.length() { res.append(self.objectAtIndex(UInt(i))) } return res } } extension NSData { public var hexString: String { return self.toHexString() } func toHexString() -> String { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) var s:String = ""; for byte in bytesArray { s = s + (NSString(format:"%02X", byte) as String) } return s; } func bytes() -> [UInt8] { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) return bytesArray } class public func withBytes(bytes: [UInt8]) -> NSData { return NSData(bytes: bytes, length: bytes.count) } }
mit
fa1835e03cb8896be59f6b9714f4e47b
21.930348
94
0.551649
4.024454
false
false
false
false
brunodlz/Couch
Couch/Couch/View/Show/ShowView.swift
1
2481
import UIKit import SnapKit class ShowView: UIView { let containerView: UIView = { let view = UIView(frame: .zero) view.backgroundColor = ColorPalette.black return view }() let banner: UIImageView = { let image = UIImageView(frame: .zero) image.backgroundColor = ColorPalette.blue return image }() let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium) label.textColor = ColorPalette.white label.numberOfLines = 0 return label }() let yearLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12) label.textColor = ColorPalette.white return label }() override init(frame: CGRect) { super.init(frame: frame) self.setupViewConfiguration() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ShowView: ViewConfiguration { func setupConstraints() { containerView.snp.makeConstraints { (make) in make.top.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.bottom.equalTo(self) } banner.snp.makeConstraints { (make) in make.top.equalTo(self).offset(4) make.left.equalTo(self).offset(16) make.bottom.equalTo(self).offset(-4) make.width.equalTo(80) } titleLabel.snp.makeConstraints { (make) in make.top.equalTo(banner.snp.top) make.left.equalTo(banner.snp.right).offset(8) make.right.equalTo(self).offset(-4) } yearLabel.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom) make.left.equalTo(titleLabel.snp.left) make.right.equalTo(titleLabel.snp.right) } } func buildViewHierarchy() { containerView.addSubview(banner) containerView.addSubview(titleLabel) containerView.addSubview(yearLabel) self.addSubview(containerView) } func configureViews() { banner.clipsToBounds = true banner.layer.borderWidth = 0.5 banner.layer.cornerRadius = 4 banner.layer.borderColor = ColorPalette.gray.cgColor } }
mit
f58d65e6d674b39326f6bbc87645dbdd
27.193182
78
0.588069
4.663534
false
false
false
false
arslanbilal/cryptology-project
Cryptology Project/Cryptology Project/Classes/Models/ActiveUser.swift
1
3274
// // ActiveUser.swift // Cryptology Project // // Created by Bilal Arslan on 17/03/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import UIKit import RealmSwift class ActiveUser: NSObject { private let realm = try! Realm() var user = RealmUser() var chatList = [MessageList]() var userList = [RealmUser]() private var manInTheMiddle = [CipherMessage]() static let sharedInstance = ActiveUser() func setActiveUser(user: RealmUser) { self.user = user let users = realm.objects(RealmUser).filter("id != \(self.user.id)") for otherUser in users { userList.append(otherUser) } userList.sortInPlace({ $0.0.name < $0.1.name }) loadUserChatData() } func loadUserChatData() { self.chatList = [MessageList]() let chats = realm.objects(RealmChat).filter("fromUser.id = \(self.user.id) OR toUser.id = \(self.user.id)") for chat in chats { let selectedUser = chat.fromUser != user ? chat.fromUser : chat.toUser let messageType = chat.fromUser != user ? MessageType.IncomingMessage : MessageType.OutgoingMessage let realmMessage = realm.objects(RealmMessage).filter("id = \(chat.message!.id)").first! let otherUser = realm.objects(RealmUser).filter("id = \(selectedUser!.id)").first! let result = chatList.filter { $0.otherUser.id == otherUser.id }.first let message = Message(message: realmMessage, type: messageType) if result != nil { result?.messages.append(message) } else { chatList.append(MessageList(otherUser: otherUser, message: message, messageType: messageType, messageKey: chat.key!)) } } chatList.sortInPlace({ $0.0.messages.last?.message.date.timeIntervalSince1970 > $0.1.messages.last?.message.date.timeIntervalSince1970}) } func loadManInTheMiddleData() -> [CipherMessage]{ self.manInTheMiddle = [CipherMessage]() let chats = realm.objects(RealmChat) for chat in chats { let message: String! if chat.message?.isImageMassage == true { message = "Image Message" } else { message = chat.message?.text } let owners = (chat.fromUser?.username)! + " => " + (chat.toUser?.username)! let date = chat.message?.date let cipherMessage = CipherMessage(message: message!, owners: owners, date: date!) manInTheMiddle.append(cipherMessage) } manInTheMiddle.sortInPlace({ $0.0.date.timeIntervalSince1970 > $0.1.date.timeIntervalSince1970}) return manInTheMiddle } func getMesageListFromUserId(userId: Int) -> MessageList? { let messageList = chatList.filter { $0.otherUser.id == userId }.first return messageList } func exitUser() { self.user = RealmUser() self.chatList = [] self.userList = [] } }
mit
74a4195b7781c2e3e5892a8c10cb49e6
31.405941
145
0.568286
4.571229
false
false
false
false
hadiariawan/iOS-Simple-Weather-App
MyWeather/DetailViewController.swift
1
2465
// // DetailViewController.swift // MyWeather // // Created by Hadi Ariawan on 5/19/17. // Copyright © 2017 Niltava Media. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var labelCityName: UILabel! @IBOutlet weak var weatherImageView: UIImageView! @IBOutlet weak var labelWeatherMain: UILabel! @IBOutlet weak var labelWeatherDescription: UILabel! @IBOutlet weak var labelWeatherTemperature: UILabel! var weatherItem : WeatherItem? var cityName : String? var countryCode : String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. showWeatherDetail() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backBarButtonPressed(_ sender: Any) { navigationController?.popViewController(animated: true) } func showWeatherDetail() { labelCityName.text = "\(String(describing: self.cityName!)), \(String(describing: self.countryCode!))" labelWeatherMain.text = weatherItem?.wMain labelWeatherDescription.text = weatherItem?.wDescription labelWeatherTemperature.text = "\(String(describing: weatherItem?.wTempMin.description)) - \(String(describing: weatherItem?.wTempMax.description))" if weatherItem?.wDescription == "sky is clear" { weatherImageView.image = UIImage(named: "weather-sunny") }else if weatherItem?.wDescription == "light rain" { weatherImageView.image = UIImage(named: "weather-rainy") }else if weatherItem?.wDescription == "moderate rain" { weatherImageView.image = UIImage(named: "weather-rainy") }else if weatherItem?.wDescription == "few clouds" { weatherImageView.image = UIImage(named: "weather-cloudy") }else { weatherImageView.image = UIImage(named: "weather-question") } } /* // 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
48e9dbd45be4efe677d81189e49f609c
34.2
156
0.668425
4.756757
false
false
false
false
Eonil/EditorLegacy
Modules/EditorUIComponents/EditorUIComponents/EditorCommonWindowController3.swift
1
4174
// // EditorCommonWindowController3.swift // EditorUIComponents // // Created by Hoon H. on 2015/02/21. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation import AppKit /// A window controller which fixes some insane behaviors. /// /// - This creates and binds `contentViewController` itself. You can override instantiation of it. /// - This creates and binds `window` by calling `loadWindow` and that calls `instantiateWindow` method. /// - This sends `windowDidLoad` message after loading window. /// - So, `window` is always a non-`nil` value. And also you cannot set `nil` to `window`. /// /// Do not override any initialiser. Instead, override `windowDidLoad` to setup thigns. /// This is intentional design to prevent weird OBJC instance replacement behavior. /// /// **Notice** /// /// This class does not support use in Interface Builder public class EditorCommonWindowController3 : NSWindowController { /// Designated initialiser. public required init() { super.init(window: nil) loadWindow() // This doesn't being called automatically. Need to be called manually. windowDidLoad() // This doesn't being called automatically. Need to be called manually. } @availability(*,unavailable) public required init?(coder: NSCoder) { fatalError("This class `\(EditorCommonWindowController3.self)` does not support IB.") } @availability(*,unavailable) override convenience init(window: NSWindow?) { fatalError("This class `\(EditorCommonWindowController3.self)` does not support setting window object.") } @availability(*,unavailable) public convenience init(windowNibName:String) { fatalError("This initializer is not supported.") } @availability(*,unavailable) public convenience init(windowNibName:String, owner:AnyObject) { fatalError("This initializer is not supported.") } @availability(*,unavailable) public convenience init(windowNibPath:String, owner:AnyObject) { fatalError("This initializer is not supported.") } public override var window:NSWindow! { get { assert(super.window !== nil, "Current `window` is `nil` which means logic bug.") return super.window } set(v) { precondition(v != nil, "`nil` is not allowed for `window`.") } } /// Don't call this. Intended for internal use only. // @availability(*,unavailable) public final override func loadWindow() { super.window = instantiateWindow() } /// Designed to be overridable. /// You must call super-implementation. /// `window` property is always be non-`nil` at this point. public override func windowDidLoad() { super.windowDidLoad() super.window!.contentViewController = instantiateContentViewController() } /// Unsupported. @availability(*,unavailable) public override var windowNibPath:String! { get { fatalError("`windowNibPath` property is not supported.") } } /// Unsupported. @availability(*,unavailable) public override var windowNibName:String! { get { fatalError("`windowNibName` property is not supported.") } } /// Intended to be overriden. /// Override if you want to provide custom subclass window object. public func instantiateWindow() -> NSWindow { let w1 = NSWindow() w1.styleMask |= NSResizableWindowMask | NSTitledWindowMask | NSMiniaturizableWindowMask | NSClosableWindowMask return w1 } /// Intended to be overriden. /// Override if you want to provide custom subclass view-controller object. public func instantiateContentViewController() -> NSViewController { return EmptyViewController(nibName: nil, bundle: nil)! } public final override var contentViewController:NSViewController? { get { return super.window!.contentViewController } @availability(*,unavailable) set(v) { fatalError("You cannot set `contentViewController` directly. Instead, override `instantiateContentViewController` method to customise its class.") } } } private extension EditorCommonWindowController3 { /// A view controller to suppress NIB searching error. @objc private class EmptyViewController: NSViewController { private override func loadView() { super.view = NSView() } } }
mit
d191c16f9e0daca20c43afc8c4ef15e9
25.929032
149
0.727599
3.952652
false
false
false
false
ilyahal/VKMusic
VkPlaylist/SettingsTableViewController.swift
1
5890
// // SettingsTableViewController.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // 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 SettingsTableViewController: UITableViewController { /// Кнопка "Авторизоваться" @IBOutlet weak var loginButton: UIButton! /// Кнопка "Деавторизоваться" @IBOutlet weak var logoutButton: UIButton! /// Переключатель настройки "Предупреждать о наличии" @IBOutlet weak var warningWhenDeletingOfExistenceInPlaylistsSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() tabBarController!.tabBar.hidden = true tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension warningWhenDeletingOfExistenceInPlaylistsSwitch.on = DataManager.sharedInstance.isWarningWhenDeletingOfExistenceInPlaylists updateAuthorizationButtonsStatus(VKAPIManager.isAuthorized) // Наблюдатели за авторизацией пользователя NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidAutorize), name: VKAPIManagerDidAutorizeNotification, object: nil) // Добавляем слушаетля для события успешной авторизации NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDidUnautorize), name: VKAPIManagerDidUnautorizeNotification, object: nil) // Добавляем слушателя для события деавторизации NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userAutorizationFailed), name: VKAPIManagerAutorizationFailedNotification, object: nil) // Добавляем слушаетля для события успешной авторизации } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Скрываем мини-плеер при открытии настроек PlayerManager.sharedInstance.hideMiniPlayerAnimated(false) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) // Отображаем мини-плеер при закрытии настроек PlayerManager.sharedInstance.showMiniPlayerAnimated(true) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } /// Обновление состояния кнопок авторизации func updateAuthorizationButtonsStatus(state: Bool) { if state { dispatch_async(dispatch_get_main_queue()) { self.loginButton.enabled = false self.logoutButton.enabled = true } } else { dispatch_async(dispatch_get_main_queue()) { self.loginButton.enabled = true self.logoutButton.enabled = false } } } // MARK: Кнопки /// Вызывается при тапе по кнопке "Войти в аккаунт" @IBAction func loginTapped(sender: UIButton) { loginButton.enabled = false VKAPIManager.autorize() } /// Вызывается при тапе по кнопке "Выход из аккаунта" @IBAction func logoutTapped(sender: UIButton) { logoutButton.enabled = false VKAPIManager.logout() } /// Вызывается при изменении переключателя предупреждения о наличии в других плейлистах при удалении @IBAction func warningWhenDeletingOfExistenceInPlaylistsSwitchChanged(sender: UISwitch) { if sender.on { DataManager.sharedInstance.warningWhenDeletingOfExistenceInPlaylistsEnabled() } else { DataManager.sharedInstance.warningWhenDeletingOfExistenceInPlaylistsDisabled() } } // MARK: Авторизация пользователя /// Пользователь авторизовался func userDidAutorize() { updateAuthorizationButtonsStatus(true) } /// Пользователь деавторизовался func userDidUnautorize() { updateAuthorizationButtonsStatus(false) } /// При авторизации пользователя произошла ошибка func userAutorizationFailed() { updateAuthorizationButtonsStatus(false) } }
mit
10ad210a42ed9651f9d8930cd45bf67c
36.963504
226
0.703519
4.449102
false
false
false
false
southfox/jfwindguru
JFWindguru/Classes/Model/TimeWeather.swift
1
3214
// // TimeWeather.swift // Xoshem-watch // // Created by Javier Fuchs on 10/7/15. // Copyright © 2015 Fuchs. All rights reserved. // import Foundation /* * TimeWeather * * Discussion: * Represents a model information of the weather schedule every 3 hours from the time of * recovering. * Here the information could come as Int, Double, String. A convenient AnyObject helps to * reduce code for now. * * TODO: the best thing to do here is to remove all the interminable attributes and use directly * an array :) * * Example: information of temperature in celsius. * { * "0": -1, * "3": -1.4, * "6": 0.1, * "9": 2.7, * "12": 3.3, * "15": 2, * "18": -3.1, * "21": -4.3, * "24": -5, * "27": -5.5, * "30": -0.7, * "33": 4.7, * "36": 6.3, * "39": 4.9, * "42": -1.4, * "45": -1.7, * "48": -1.7, * "51": -1.5, * "54": 2.8, * "57": 6, * "60": 7.6, * "63": 7.2, * "66": 1.2, * "69": 0.6, * "72": -0.3, * "75": -0.8, * "78": 2.9, * "81": 6.3, * "84": 8.2, * "87": 7.3, * "90": 2.2, * "93": 1.3, * "96": -0.1, * "99": 1.3, * "102": 2.1, * "105": 5, * "108": 6.5, * "111": 7.1, * "114": 2.5, * "117": 1.6, * "120": 1.7, * "123": 1.8, * "126": 4.1, * "129": 7.2, * "132": 8.2, * "135": 6, * "138": 3.6, * "141": 3.2, * "144": 3.1, * "147": 3, * "150": 3.3, * "153": 4.7, * "156": 3.8, * "159": 2.3, * "162": -1.5, * "165": -1.5, * "168": -2.6, * "171": -2.9, * "174": -1.1, * "177": 2.4, * "180": 3.9 * } * */ public class TimeWeather: Object, Mappable { var keys = [String]() var strings = [String]() var floats = [Float]() required public convenience init(map: [String:Any]) { self.init() mapping(map: map) } public func mapping(map: [String:Any]) { for (k,v) in map { keys.append(k) if let str = v as? String { strings.append(str) } else if let str = v as? Float { floats.append(str) } } } public var description : String { var aux : String = "\(type(of:self)): " let orderkeys = keys.sorted { (a, b) -> Bool in return a < b } for k in orderkeys { let key = k guard let index = keys.index(of: k) else { return "" } aux += "\(key): " if strings.count >= 0 && index < strings.count { aux += strings[index] } else if floats.count > 0 && index < floats.count { let v = floats[index] aux += "\(v)" } aux += ", " } return aux } }
mit
0e9c6bd1cd9ab91e2f75cf82c0777912
22.282609
99
0.372549
2.997201
false
false
false
false
Zewo/Reflection
Sources/Reflection/Construct.swift
1
2801
/// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T { return try constructGenericType(constructor: constructor) } func constructGenericType<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T { if Metadata(type: T.self)?.kind == .struct { return try constructValueType(constructor) } else { throw ReflectionError.notStruct(type: T.self) } } /// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct(_ type: Any.Type, constructor: (Property.Description) throws -> Any) throws -> Any { return try extensions(of: type).construct(constructor: constructor) } private func constructValueType<T>(_ constructor: (Property.Description) throws -> Any) throws -> T { guard Metadata(type: T.self)?.kind == .struct else { throw ReflectionError.notStruct(type: T.self) } let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) defer { pointer.deallocate() } var values: [Any] = [] try constructType(storage: UnsafeMutableRawPointer(pointer), values: &values, properties: properties(T.self), constructor: constructor) return pointer.move() } private func constructType(storage: UnsafeMutableRawPointer, values: inout [Any], properties: [Property.Description], constructor: (Property.Description) throws -> Any) throws { var errors = [Error]() for property in properties { do { let value = try constructor(property) values.append(value) try property.write(value, to: storage) } catch { errors.append(error) } } if errors.count > 0 { throw ConstructionErrors(errors: errors) } } /// Create a struct from a dictionary. public func construct<T>(_ type: T.Type = T.self, dictionary: [String: Any]) throws -> T { return try constructGenericType(constructor: constructorForDictionary(dictionary)) } /// Create a struct from a dictionary. public func construct(_ type: Any.Type, dictionary: [String: Any]) throws -> Any { return try construct(type, constructor: constructorForDictionary(dictionary)) } private func constructorForDictionary(_ dictionary: [String: Any]) -> (Property.Description) throws -> Any { return { property in if let value = dictionary[property.key] { return value } else if let expressibleByNilLiteral = property.type as? ExpressibleByNilLiteral.Type { return expressibleByNilLiteral.init(nilLiteral: ()) } else { throw ReflectionError.requiredValueMissing(key: property.key) } } }
mit
4bc917c33e8c21122602d3662419fb69
42.765625
177
0.68904
4.296012
false
false
false
false
suragch/aePronunciation-iOS
aePronunciation/IpaKeyboard.swift
1
13590
import UIKit // View Controllers must adopt this protocol protocol KeyboardDelegate: class { func keyWasTapped(_ character: String) func keyBackspace() } class IpaKeyboard: UIView, KeyboardKeyDelegate { private let numberKeysDouble = 43 private let numberKeysSingle = 47 var mode = SoundMode.single { didSet { if mode == SoundMode.single && subviews.count == numberKeysDouble { addSpecialKeysBackIn() self.setNeedsLayout() } else if mode == SoundMode.double && subviews.count == numberKeysSingle { removeSpecialKeys() self.setNeedsLayout() } } } weak var delegate: KeyboardDelegate? // probably the view controller // Keyboard Keys // Row 1 private let key_i = KeyboardTextKey() private let key_i_short = KeyboardTextKey() private let key_e_short = KeyboardTextKey() private let key_ae = KeyboardTextKey() private let key_a = KeyboardTextKey() private let key_c_backwards = KeyboardTextKey() private let key_u_short = KeyboardTextKey() private let key_u = KeyboardTextKey() private let key_v_upsidedown = KeyboardTextKey() private let key_shwua = KeyboardTextKey() // Row 2 private let key_ei = KeyboardTextKey() private let key_ai = KeyboardTextKey() private let key_au = KeyboardTextKey() private let key_oi = KeyboardTextKey() private let key_ou = KeyboardTextKey() // Row 3 private let key_er_stressed = KeyboardTextKey() private let key_er_unstressed = KeyboardTextKey() private let key_ar = KeyboardTextKey() private let key_er = KeyboardTextKey() private let key_ir = KeyboardTextKey() private let key_or = KeyboardTextKey() // Row 4 private let key_p = KeyboardTextKey() private let key_t = KeyboardTextKey() private let key_k = KeyboardTextKey() private let key_ch = KeyboardTextKey() private let key_f = KeyboardTextKey() private let key_th_voiceless = KeyboardTextKey() private let key_s = KeyboardTextKey() private let key_sh = KeyboardTextKey() // Row 5 private let key_b = KeyboardTextKey() private let key_d = KeyboardTextKey() private let key_g = KeyboardTextKey() private let key_dzh = KeyboardTextKey() private let key_v = KeyboardTextKey() private let key_th_voiced = KeyboardTextKey() private let key_z = KeyboardTextKey() private let key_zh = KeyboardTextKey() // Row 6 private let key_m = KeyboardTextKey() private let key_n = KeyboardTextKey() private let key_ng = KeyboardTextKey() private let key_l = KeyboardTextKey() private let key_w = KeyboardTextKey() private let key_j = KeyboardTextKey() private let key_h = KeyboardTextKey() private let key_r = KeyboardTextKey() private let key_glottal_stop = KeyboardTextKey() private let key_flap_t = KeyboardTextKey() // MARK:- keyboard initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } private func setup() { addSubviews() setPrimaryKeyStrings() assignDelegates() } private func addSubviews() { // Row 1 self.addSubview(key_i) self.addSubview(key_i_short) self.addSubview(key_e_short) self.addSubview(key_ae) self.addSubview(key_a) self.addSubview(key_c_backwards) self.addSubview(key_u_short) self.addSubview(key_u) self.addSubview(key_v_upsidedown) self.addSubview(key_shwua) // Row 2 self.addSubview(key_ei) self.addSubview(key_ai) self.addSubview(key_au) self.addSubview(key_oi) self.addSubview(key_ou) // Row 3 self.addSubview(key_er_stressed) self.addSubview(key_er_unstressed) self.addSubview(key_ar) self.addSubview(key_er) self.addSubview(key_ir) self.addSubview(key_or) // Row 4 self.addSubview(key_p) self.addSubview(key_t) self.addSubview(key_k) self.addSubview(key_ch) self.addSubview(key_f) self.addSubview(key_th_voiceless) self.addSubview(key_s) self.addSubview(key_sh) // Row 5 self.addSubview(key_b) self.addSubview(key_d) self.addSubview(key_g) self.addSubview(key_dzh) self.addSubview(key_v) self.addSubview(key_th_voiced) self.addSubview(key_z) self.addSubview(key_zh) // Row 6 self.addSubview(key_m) self.addSubview(key_n) self.addSubview(key_ng) self.addSubview(key_l) self.addSubview(key_w) self.addSubview(key_j) self.addSubview(key_h) self.addSubview(key_r) self.addSubview(key_glottal_stop) self.addSubview(key_flap_t) } private func setPrimaryKeyStrings() { // Row 1 key_i.primaryString = Ipa.i key_i_short.primaryString = Ipa.i_short key_e_short.primaryString = Ipa.e_short key_ae.primaryString = Ipa.ae key_a.primaryString = Ipa.a key_c_backwards.primaryString = Ipa.c_backwards key_u_short.primaryString = Ipa.u_short key_u.primaryString = Ipa.u key_v_upsidedown.primaryString = Ipa.v_upsidedown key_shwua.primaryString = Ipa.schwa // Row 2 key_ei.primaryString = Ipa.ei key_ai.primaryString = Ipa.ai key_au.primaryString = Ipa.au key_oi.primaryString = Ipa.oi key_ou.primaryString = Ipa.ou // Row 3 key_er_stressed.primaryString = Ipa.er_stressed key_er_unstressed.primaryString = Ipa.er_unstressed key_ar.primaryString = Ipa.ar key_er.primaryString = Ipa.er key_ir.primaryString = Ipa.ir key_or.primaryString = Ipa.or // Row 4 key_p.primaryString = Ipa.p key_t.primaryString = Ipa.t key_k.primaryString = Ipa.k key_ch.primaryString = Ipa.ch key_f.primaryString = Ipa.f key_th_voiceless.primaryString = Ipa.th_voiceless key_s.primaryString = Ipa.s key_sh.primaryString = Ipa.sh // Row 5 key_b.primaryString = Ipa.b key_d.primaryString = Ipa.d key_g.primaryString = Ipa.g key_dzh.primaryString = Ipa.dzh key_v.primaryString = Ipa.v key_th_voiced.primaryString = Ipa.th_voiced key_z.primaryString = Ipa.z key_zh.primaryString = Ipa.zh // Row 6 key_m.primaryString = Ipa.m key_n.primaryString = Ipa.n key_ng.primaryString = Ipa.ng key_l.primaryString = Ipa.l key_w.primaryString = Ipa.w key_j.primaryString = Ipa.j key_h.primaryString = Ipa.h key_r.primaryString = Ipa.r key_glottal_stop.primaryString = Ipa.glottal_stop key_flap_t.primaryString = Ipa.flap_t } private func assignDelegates() { // Row 1 key_i.delegate = self key_i_short.delegate = self key_e_short.delegate = self key_ae.delegate = self key_a.delegate = self key_c_backwards.delegate = self key_u_short.delegate = self key_u.delegate = self key_v_upsidedown.delegate = self key_shwua.delegate = self // Row 2 key_ei.delegate = self key_ai.delegate = self key_au.delegate = self key_oi.delegate = self key_ou.delegate = self // Row 3 key_er_stressed.delegate = self key_er_unstressed.delegate = self key_ar.delegate = self key_er.delegate = self key_ir.delegate = self key_or.delegate = self // Row 4 key_p.delegate = self key_t.delegate = self key_k.delegate = self key_ch.delegate = self key_f.delegate = self key_th_voiceless.delegate = self key_s.delegate = self key_sh.delegate = self // Row 5 key_b.delegate = self key_d.delegate = self key_g.delegate = self key_dzh.delegate = self key_v.delegate = self key_th_voiced.delegate = self key_z.delegate = self key_zh.delegate = self // Row 6 key_m.delegate = self key_n.delegate = self key_ng.delegate = self key_l.delegate = self key_w.delegate = self key_j.delegate = self key_h.delegate = self key_r.delegate = self key_glottal_stop.delegate = self key_flap_t.delegate = self } override func layoutSubviews() { // | i | i | e | ae| a | c | u | u | v | e | Row 1 // | ei | ai | au | oi | ou | Row 2 // | er | er | ar | er | ir | or | Row 3 // | p | t | k | ch | f | th | s | sh | Row 4 // | b | d | g | dzh| v | th | z | zh | Row 5 // | m | n | ng| l | w | j | h | r | ? | r | Row 6 let numberOfKeysPerRow = getNumberOfKeysPerRow() // each row should sum to 1 let keyWeights = getKeyWeights() let numberOfRows = numberOfKeysPerRow.count let totalWidth = self.bounds.width let totalHeight = self.bounds.height var x: CGFloat = 0 var y: CGFloat = 0 var keyIndex = 0 for rowIndex in 0..<numberOfRows { let start = keyIndex let end = keyIndex + numberOfKeysPerRow[rowIndex] for _ in start..<end { let key = subviews[keyIndex] let keyWidth = totalWidth * keyWeights[keyIndex] let keyHeight = totalHeight / CGFloat(numberOfRows) key.frame = CGRect(x: x, y: y, width: keyWidth, height: keyHeight) x += keyWidth keyIndex += 1 } x = 0 y += totalHeight / CGFloat(numberOfRows) } } private func getNumberOfKeysPerRow() -> [Int] { if mode == SoundMode.single { return [10, 5, 6, 8, 8, 10] // 47 total } else { // double return [9, 5, 5, 8, 8, 8] // 43 total } } private func getKeyWeights() -> [CGFloat] { // each row should sum to 1 let eighth: CGFloat = 1/8 if mode == SoundMode.single { let sixth: CGFloat = 1/6 return [ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, sixth, sixth, sixth, sixth, sixth, sixth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] } else { // excluding special sounds for double keyboard let ninth: CGFloat = 1/9 return [ ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth, eighth] } } private func addSpecialKeysBackIn() { self.insertSubview(key_shwua, aboveSubview: key_v_upsidedown) self.insertSubview(key_er_unstressed, aboveSubview: key_er_stressed) self.addSubview(key_glottal_stop) self.addSubview(key_flap_t) } private func removeSpecialKeys() { for myView in subviews { guard let key = myView as? KeyboardTextKey else {continue} if Ipa.isSpecial(ipa: key.primaryString) { key.removeFromSuperview() } } } // MARK: - KeyboardKeyDelegate protocol func keyTextEntered(sender: KeyboardKey, keyText: String) { // pass the input up to the Keyboard delegate self.delegate?.keyWasTapped(keyText) } func keyBackspaceTapped() { self.delegate?.keyBackspace() } // MARK: - Public update methods func updateKeyAppearanceFor(selectedSounds: [String]?) { guard let selected = selectedSounds else {return} for myView in subviews { guard let key = myView as? KeyboardTextKey else {continue} var isEnabled = false innerLoop: for sound in selected { if sound == key.primaryString { isEnabled = true break innerLoop } } key.isEnabled = isEnabled } } func getEnabledKeys() -> [String] { var enabledKeys = [String]() for myView in subviews { guard let key = myView as? KeyboardTextKey else {continue} if key.isEnabled { enabledKeys.append(key.primaryString) } } return enabledKeys } }
unlicense
c466ca41fe998019f7aa05485b806f67
31.12766
82
0.561001
3.941415
false
false
false
false
UIKonf/uikonf-app
UIKonfApp/UIKonfApp/Bouncer.swift
1
1312
import Foundation /** Creates and returns a new debounced version of the passed block which will postpone its execution until after wait seconds have elapsed since the last time it was invoked. It is like a bouncer at a discotheque. He will act only after you shut up for some time. This technique is important if you have action wich should fire on update, however the updates are to frequent. Inspired by debounce function from underscore.js ( http://underscorejs.org/#debounce ) */ public func dispatch_debounce_block(wait : NSTimeInterval, queue : dispatch_queue_t = dispatch_get_main_queue(), block : dispatch_block_t) -> dispatch_block_t { var cancelable : dispatch_block_t! return { cancelable?() cancelable = dispatch_after_cancellable(wait, queue, block) } } // Big thanks to Claus Höfele for this function // https://gist.github.com/choefele/5e5a981ed731472b80d9 func dispatch_after_cancellable(wait: NSTimeInterval, queue: dispatch_queue_t, block: dispatch_block_t) -> dispatch_block_t { let when = dispatch_time(DISPATCH_TIME_NOW, Int64(wait * Double(NSEC_PER_SEC))) var isCancelled = false dispatch_after(when, queue) { if !isCancelled { block() } } return { isCancelled = true } }
mit
16782ad12b96b155ee0ecb4decb3bc94
38.757576
175
0.700229
3.960725
false
false
false
false
grandiere/box
box/Model/GridVisor/Render/Main/MGridVisorRenderVertexes.swift
1
1092
import UIKit import MetalKit class MGridVisorRenderVertexes { let vertexStandby:MTLBuffer let vertexTargeted:MTLBuffer init(device:MTLDevice) { let imageStandby:UIImage = #imageLiteral(resourceName: "assetTextureAidStandBy") let imageTargeted:UIImage = #imageLiteral(resourceName: "assetTextureAidTargeted0") let standbyWidth:Float = Float(imageStandby.size.width) let standbyHeight:Float = Float(imageStandby.size.height) let targetedWidth:Float = Float(imageTargeted.size.width) let targetedHeight:Float = Float(imageTargeted.size.height) let standBy:MetalSpatialShapeSquarePositive = MetalSpatialShapeSquarePositive( device:device, width:standbyWidth, height:standbyHeight) let targeted:MetalSpatialShapeSquarePositive = MetalSpatialShapeSquarePositive( device:device, width:targetedWidth, height:targetedHeight) vertexStandby = standBy.vertexBuffer vertexTargeted = targeted.vertexBuffer } }
mit
f1e61247148cec6332e4e16f0ed793fd
35.4
91
0.699634
4.810573
false
false
false
false
ali-zahedi/AZViewer
AZViewer/AZPhotoCollectionViewCell.swift
1
2280
// // AZPhotoCollectionViewCell.swift // AZViewer // // Created by Ali Zahedi on 7/22/17. // Copyright © 2017 Ali Zahedi. All rights reserved. // import UIKit class AZPhotoCollectionViewCell: AZCollectionViewCell { // MARK: Public // MARK: Internal static var size: CGSize{ let wh: CGFloat = (UIScreen.main.bounds.width / 4 ) - (AZPhotoCollectionView.spacing * 1.5) return CGSize(width: wh, height: wh) } var object: AZModelPhoto! { didSet{ self.updateUI() } } // MARK: Private fileprivate var imageView: AZImageView = AZImageView() // MARK: Init override init(frame: CGRect) { super.init(frame: frame) self.defaultInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.defaultInit() } // MARK: Function fileprivate func defaultInit(){ for v in [imageView] as [UIView]{ v.translatesAutoresizingMaskIntoConstraints = false self.addSubview(v) } self.prepareImageView() } // update fileprivate func updateUI(){ self.imageView.image = self.object.image self.prepareBorder() } // update border func selected(){ self.object.selected = !self.object.selected self.prepareBorder() } fileprivate func prepareBorder(){ if self.object.selected{ self.setBorder() }else{ self.clearBorder() } } fileprivate func setBorder(){ self.imageView.layer.borderColor = AZStyle.shared.sectionPhotoViewControllerImageSelectedTintColor.cgColor self.imageView.layer.borderWidth = 2 } fileprivate func clearBorder(){ self.imageView.layer.borderWidth = 0 } } // prepare extension AZPhotoCollectionViewCell{ // image view fileprivate func prepareImageView(){ _ = self.imageView.aZConstraints.parent(parent: self).top().right().left().bottom() self.imageView.contentMode = .scaleAspectFill self.imageView.clipsToBounds = true } }
apache-2.0
d4ab48339902eff238b171af3f86cbdc
21.79
114
0.580079
4.848936
false
false
false
false
colemancda/Pedido
Pedido Admin/Pedido Admin/NewMenuItemViewController.swift
1
2759
// // NewMenuItemViewController.swift // Pedido Admin // // Created by Alsey Coleman Miller on 12/27/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import UIKit class NewMenuItemViewController: NewManagedObjectViewController { // MARK: - IB Outlets @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var priceTextfield: UITextField! @IBOutlet weak var currencySymbolLabel: UILabel! // MARK: - Properties override var entityName: String { return "MenuItem" } var currencyLocale: NSLocale = NSLocale.currentLocale() { didSet { // update UI self.currencySymbolLabel.text = currencyLocale.objectForKey(NSLocaleCurrencySymbol) as? String // set locale on number formatter self.numberFormatter.locale = self.currencyLocale } } // MARK: - Private Properties lazy var numberFormatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle numberFormatter.locale = self.currencyLocale numberFormatter.currencySymbol = "" return numberFormatter }() // MARK: - Methods override func getNewValues() -> [String : AnyObject]? { // attributes let name = self.nameTextField.text let price = self.numberFormatter.numberFromString(self.priceTextfield.text) // invalid price text if price == nil { self.showErrorAlert(NSLocalizedString("Invalid value for price.", comment: "Invalid value for price.")) return nil } return ["name": name, "price": price!, "currencyLocaleIdentifier": self.currencyLocale.localeIdentifier] } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch MainStoryboardSegueIdentifier(rawValue: segue.identifier!)! { case .NewMenuItemPickCurrencyLocale: let currencyLocalePickerVC = segue.destinationViewController as CurrencyLocalePickerViewController currencyLocalePickerVC.selectedCurrencyLocale = self.currencyLocale // set handler currencyLocalePickerVC.selectionHandler = { self.currencyLocale = currencyLocalePickerVC.selectedCurrencyLocale! } default: return } } }
mit
6c1adf7f4a8086515ee0f99fdc654390
26.6
115
0.595143
6.2
false
false
false
false
designbychemisax/cordova-plugin-cbeacon
src/ios/Cbeacon.swift
2
4849
// // CBeacon.swift // // Created by José María Campaña Rojas on 14/11/15. // // import Foundation import CoreLocation import CoreBluetooth @objc(CBeacon) class CBeacon : CDVPlugin, CLLocationManagerDelegate, CBCentralManagerDelegate { var centralManager:CBCentralManager! let locationManager = CLLocationManager() var callbackId = "" var status : [String:Bool] = ["permission" : false, "bluetooth" : false] override func pluginInitialize () { locationManager.delegate = self centralManager = CBCentralManager(delegate: self, queue: nil, options: nil) } func register (command: CDVInvokedUrlCommand) { print ("\n\ncBeacon by José María Campaña Rojas,\ndesign by chemisax,\nwww.chemisax.com\n\n") self.callbackId = command.callbackId let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) pluginResult.setKeepCallbackAsBool(true) print (command.callbackId) commandDelegate?.sendPluginResult(pluginResult, callbackId:self.callbackId) } func getBeaconStatus (command: CDVInvokedUrlCommand) { print ("Requesting beacon status") self.status["permission"] = CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: self.status) commandDelegate?.sendPluginResult(pluginResult, callbackId:command.callbackId) } func requestAuthorization (command: CDVInvokedUrlCommand) { print ("Requesting authorization") if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate?.sendPluginResult(pluginResult, callbackId:command.callbackId) } func centralManagerDidUpdateState(central: CBCentralManager) { //Call callback to tell ble state changed; switch (central.state) { case .PoweredOff: print("CoreBluetooth BLE hardware is powered off") self.status["bluetooth"] = false case .PoweredOn: print("CoreBluetooth BLE hardware is powered on and ready") self.status["bluetooth"] = true case .Resetting: print("CoreBluetooth BLE hardware is resetting") self.status["bluetooth"] = false case .Unauthorized: print("CoreBluetooth BLE state is unauthorized") self.status["bluetooth"] = false case .Unknown: print("CoreBluetooth BLE state is unknown") self.status["bluetooth"] = false case .Unsupported: print("CoreBluetooth BLE hardware is unsupported on this platform") self.status["bluetooth"] = false } } func startRangingBeaconsInRegion (command: CDVInvokedUrlCommand) { let UUID = command.arguments[0] as! String; let identifier = command.arguments[1] as! String; let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: UUID)!, identifier: identifier) print ("start ranging beacons for \(identifier) (\(UUID))") locationManager.startRangingBeaconsInRegion(region) } func stopRangingBeaconsInRegion (command: CDVInvokedUrlCommand) { let UUID = command.arguments[0] as! String; let identifier = command.arguments[1] as! String; let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: UUID)!, identifier: identifier) locationManager.stopRangingBeaconsInRegion(region) } func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) { var _beacons : [[String:AnyObject]] = []; for beacon in beacons { var proximity = "" switch beacon.proximity { case CLProximity.Immediate: proximity = "immediate" case CLProximity.Near: proximity = "near" case CLProximity.Far: proximity = "far" case CLProximity.Unknown: proximity = "unknown" } _beacons.append(["major":beacon.major, "minor":beacon.minor, "proximity" : proximity]) } let command : [String:AnyObject] = ["command" : "range", "beacons" : _beacons] let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsDictionary: command) pluginResult.setKeepCallbackAsBool(true) commandDelegate?.sendPluginResult(pluginResult, callbackId:self.callbackId) } }
mit
60a37dded7d6debdfcc204d7e67c08c2
40.042373
124
0.649804
5.534857
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift
6
3600
// // BarHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(BarChartHighlighter) open class BarHighlighter: ChartHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { guard let barData = (self.chart as? BarChartDataProvider)?.barData, let high = super.getHighlight(x: x, y: y) else { return nil } let pos = getValsForTouch(x: x, y: y) if let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet, set.isStacked { return getStackedHighlight(high: high, set: set, xValue: Double(pos.x), yValue: Double(pos.y)) } else { return high } } internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return abs(x1 - x2) } internal override var data: ChartData? { return (chart as? BarChartDataProvider)?.barData } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. /// - parameter high: the Highlight to work with looking for stacked values /// - parameter set: /// - parameter xIndex: /// - parameter yValue: /// - returns: @objc open func getStackedHighlight(high: Highlight, set: IBarChartDataSet, xValue: Double, yValue: Double) -> Highlight? { guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider, let entry = set.entryForXValue(xValue, closestToY: yValue) as? BarChartDataEntry else { return nil } // Not stacked if entry.yValues == nil { return high } guard let ranges = entry.ranges, ranges.count > 0 else { return nil } let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue) let pixel = chart .getTransformer(forAxis: set.axisDependency) .pixelForValues(x: high.x, y: ranges[stackIndex].to) return Highlight(x: entry.x, y: entry.y, xPx: pixel.x, yPx: pixel.y, dataSetIndex: high.dataSetIndex, stackIndex: stackIndex, axis: high.axis) } /// - returns: The index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter. /// - parameter entry: /// - parameter value: /// - returns: @objc open func getClosestStackIndex(ranges: [Range]?, value: Double) -> Int { guard let ranges = ranges else { return 0 } var stackIndex = 0 for range in ranges { if range.contains(value) { return stackIndex } else { stackIndex += 1 } } let length = max(ranges.count - 1, 0) return (value > ranges[length].to) ? length : 0 } }
apache-2.0
e06eba818169c5e85f565ffe00440071
29.508475
136
0.524444
5.034965
false
false
false
false
louisdh/lioness
Sources/Lioness/Config.swift
1
752
// // Config.swift // Lioness // // Created by Louis D'hauwe on 06/05/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation #if NUMBER_TYPE_DECIMAL public typealias NumberType = Decimal extension Decimal { var intValue: Int { return NSDecimalNumber(decimal: self).intValue } init?(_ string: String) { if string == "-" || string == "e" || string == "." { return nil } let decNum = NSDecimalNumber(string: string) self = decNum.decimalValue } } /// Please note: can't raise to a decimal (`rhs` will be rounded down) func pow(_ lhs: Decimal, _ rhs: Decimal) -> Decimal { return pow(lhs, rhs.intValue) } #else public typealias NumberType = Double #endif
mit
0bd2153154de635d57dbde5fffe06c24
15.688889
71
0.631158
3.460829
false
false
false
false
appdev-academy/DuckDate
DuckDate/Classes/Date.swift
1
16520
// // Date.swift // App Dev Academy // // Created by App Dev Academy on 09.05.2016 // Copyright © 2016 App Dev Academy. All rights reserved. // import Foundation // MARK: - DuckDate class /// Class for setting first day of the week open class DuckDate { /// Weekday enum Monday-Sunday public enum Weekday: Int { case monday = 2 case tuesday = 3 case wednesday = 4 case thursday = 5 case friday = 6 case saturday = 7 case sunday = 1 } /// First day of the week, be default is Monday public static var firstDayOfTheWeek: Weekday = .monday } // MARK: - Calendar extension public extension Calendar { /// Returns Gregorian NSCalendar instance static var gregorianCalendar: Calendar { var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.firstWeekday = DuckDate.firstDayOfTheWeek.rawValue return calendar } } // MARK: - Date extension /// NSDate extension with handy helpers to work with dates /// WARNING: This library works only with Gregorian calendar public extension Date { /// Enumeration of available date components internal enum DateComponent { case second case minute case hour case day case week case month case year } // MARK: Date to Int /// Digit of current month var month: Int { return Calendar.gregorianCalendar.component(.month, from: self) } /// Represents current year as Int var year: Int { return Calendar.gregorianCalendar.component(.year, from: self) } // MARK: Date to String /// String representation of date with format "dd" var dayNumberString: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd" return dateFormatter.string(from: self) } /// String representation of date with format "yyyy" var yearString: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy" return dateFormatter.string(from: self) } /// String representation of date with format "MM" var monthNumberString: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM" return dateFormatter.string(from: self) } /// String representation of date with format "LLLL" var monthName: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "LLLL" return dateFormatter.string(from: self) } /// String representation of date with format "yyyy-MM-dd" var shortDateString: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: self) } /// Get suffix of the day for date var daySuffix: String { let calendar = Calendar.current let dayOfMonth = calendar.component(.day, from: self) switch dayOfMonth { case 1, 21, 31: return "st" case 2, 22: return "nd" case 3, 23: return "rd" default: return "th" } } // MARK: NSCalendar.Unit /// Get Date at the start of calendar unit /// /// - parameter calendarUnit: NSCalendar.Unit value /// /// - returns: Date func startOfCalendarUnit(_ calendarUnit: NSCalendar.Unit) -> Date { var startDate: NSDate? (Calendar.gregorianCalendar as NSCalendar).range(of: calendarUnit, start: &startDate, interval: nil, for: self) return startDate! as Date } /// Get Date at the end of calendar unit /// /// - parameter calendarUnit: NSCalendar.Unit value /// /// - returns: Date func endOfCalendarUnit(_ calendarUnit: NSCalendar.Unit) -> Date { var startDate: NSDate? var timeInterval: TimeInterval = 0 (Calendar.gregorianCalendar as NSCalendar).range(of: calendarUnit, start: &startDate, interval: &timeInterval, for: self) return startDate!.addingTimeInterval(timeInterval) as Date } /// Add date component to current date /// /// - parameter component: DateComponent to add (e.g. week) /// - parameter count: number of DateComponents to add (e.g 3 weeks) /// /// - returns: New date with added component internal func addDateComponent(_ component: DateComponent, count: Int) -> Date { let calendar = Calendar.gregorianCalendar var components = DateComponents() switch component { case .second: components.second = count case .minute: components.minute = count case .hour: components.hour = count case .day: components.day = count case .week: components.weekOfYear = count case .month: components.month = count case .year: components.year = count } return (calendar as NSCalendar).date(byAdding: components, to: self, options: [])! } // MARK: Add or remove DateComponent /// One second after current date var plusOneSecond: Date { return self.addDateComponent(.second, count: 1) } /// Increase current date by multiple seconds /// /// - Parameter numberOfSeconds: Number of seconds to increase current date /// - Returns: Updated date func plusSeconds(_ numberOfSeconds: Int) -> Date { return self.addDateComponent(.second, count: numberOfSeconds) } /// One second before current date var minusOneSecond: Date { return self.addDateComponent(.second, count: -1) } /// Decrease current date by multiple seconds /// /// - Parameter numberOfSeconds: Number of seconds to decrease current date /// - Returns: Updated date func minusSeconds(_ numberOfSeconds: Int) -> Date { return self.addDateComponent(.second, count: -numberOfSeconds) } /// One minute after current date var plusOneMinute: Date { return self.addDateComponent(.minute, count: 1) } /// Increase current date by multiple minutes /// /// - Parameter numberOfMinutes: Number of minutes to increase current date /// - Returns: Updated date func plusMinutes(_ numberOfMinutes: Int) -> Date { return self.addDateComponent(.minute, count: numberOfMinutes) } /// One minute before current date var minusOneMinute: Date { return self.addDateComponent(.minute, count: -1) } /// Decrease current date by multiple minutes /// /// - Parameter numberOfMinutes: Number of minutes to decrease current date /// - Returns: Updated date func minusMinutes(_ numberOfMinutes: Int) -> Date { return self.addDateComponent(.minute, count: -numberOfMinutes) } /// One hour after current date var plusOneHour: Date { return self.addDateComponent(.hour, count: 1) } /// Increase current date by multiple hours /// /// - parameter numberOfHours: Number of hours to increase current date /// /// - returns: Updated date func plusHours(_ numberOfHours: Int) -> Date { return self.addDateComponent(.hour, count: numberOfHours) } /// One hour before current date var minusOneHour: Date { return self.addDateComponent(.hour, count: -1) } /// Decrease current date by multiple hours /// /// - parameter numberOfHours: Number of hours to decrease current date /// /// - returns: Updated date func minusHours(_ numberOfHours: Int) -> Date { return self.addDateComponent(.hour, count: -numberOfHours) } /// One day after current date var plusOneDay: Date { return self.addDateComponent(.day, count: 1) } /// Increase current date by multiple days /// /// - parameter numberOfDays: Number of days to increase current date /// /// - returns: Updated date func plusDays(_ numberOfDays: Int) -> Date { return self.addDateComponent(.day, count: numberOfDays) } /// One day before current date var minusOneDay: Date { return self.addDateComponent(.day, count: -1) } /// Decrease current date by multiple days /// /// - parameter numberOfDays: Number of days to decrease current date /// /// - returns: Updated date func minusDays(_ numberOfDays: Int) -> Date { return self.addDateComponent(.day, count: -numberOfDays) } /// One week after current date var plusOneWeek: Date { return self.addDateComponent(.week, count: 1) } /// Increase current date by multiple weeks /// /// - parameter numberOfWeeks: Number of weeks to increase current date /// /// - returns: Updated date func plusWeeks(_ numberOfWeeks: Int) -> Date { return self.addDateComponent(.week, count: numberOfWeeks) } /// One week before current date var minusOneWeek: Date { return self.addDateComponent(.week, count: -1) } /// Decrease current date by multiple weeks /// /// - parameter numberOfWeeks: Number of weeks to decrease current date /// /// - returns: Updated date func minusWeeks(_ numberOfWeeks: Int) -> Date { return self.addDateComponent(.week, count: -numberOfWeeks) } /// One month after current date var plusOneMonth: Date { return self.addDateComponent(.month, count: 1) } /// Increase current date by multiple months /// /// - parameter numberOfMonths: Number of months to increase current date /// /// - returns: Updated date func plusMonths(_ numberOfMonths: Int) -> Date { return self.addDateComponent(.month, count: numberOfMonths) } /// One month before current date var minusOneMonth: Date { return self.addDateComponent(.month, count: -1) } /// Decrease current date by multiple months /// /// - parameter numberOfMonths: Number of months to decrease current date /// /// - returns: Updated date func minusMonths(_ numberOfMonths: Int) -> Date { return self.addDateComponent(.month, count: -numberOfMonths) } /// One year after current date var plusOneYear: Date { return self.addDateComponent(.year, count: 1) } /// Increase current date by multiple years /// /// - parameter numberOfYears: Number of years to increase current date /// /// - returns: Updated date func plusYears(_ numberOfYears: Int) -> Date { return self.addDateComponent(.year, count: numberOfYears) } /// One year before current date var minusOneYear: Date { return self.addDateComponent(.year, count: -1) } /// Decrease current date by multiple years /// /// - parameter numberOfYears: Number of years to decrease current date /// /// - returns: Updated date func minusYears(_ numberOfYears: Int) -> Date { return self.addDateComponent(.year, count: -numberOfYears) } // MARK: Start/end of the day, week, month, year /// Date at the start of the day var startOfDay: Date { return self.startOfCalendarUnit(.day) } /// Date at the end of the day var endOfDay: Date { return self.endOfCalendarUnit(.day) } /// Date at the start of the week var startOfWeek: Date { return self.startOfCalendarUnit(.weekOfYear) } /// Date at the end of the week var endOfWeek: Date { return self.endOfCalendarUnit(.weekOfYear) } /// Date at the start of the month var startOfMonth: Date { return self.startOfCalendarUnit(.month) } /// Date at the end of the month var endOfMonth: Date { return self.endOfCalendarUnit(.month) } /// Date at the start of the year var startOfYear: Date { return self.startOfCalendarUnit(.year) } /// Date at the end of the year var endOfYear: Date { return self.endOfCalendarUnit(.year) } // MARK: Dates comparison /// Check if current date comes after date /// The same as `isGreaterThanDate(_:)` /// /// - parameter date: Date object to compare /// /// - returns: Bool func isAfterDate(_ date: Date) -> Bool { return self.compare(date) == .orderedDescending } /// Check if current date is greater than another date /// The same as `isAfterDate(_:)` /// /// - parameter date: Date object to compare /// /// - returns: Bool func isGreaterThanDate(_ date: Date) -> Bool { return self.isAfterDate(date) } /// Check if current date comes after date or equal /// The same as `isGreaterOrEqualToDate(_:)` /// /// - parameter date: Date object to compare /// /// - returns: Bool func isOnOrAfterDate(_ date: Date) -> Bool { return self.compare(date) == .orderedDescending || self.compare(date) == .orderedSame } /// Check if current date is greater than another date or equal /// The same as `isOnOrAfterDate(_:)` /// /// - parameter date: Date object to compare /// /// - returns: Bool func isGreaterOrEqualToDate(_ date: Date) -> Bool { return self.isOnOrAfterDate(date) } /// Check if current date comes before date /// The same as `isLessThanDate(_:)` /// /// - parameter date: Date object to compare /// /// - returns: Bool func isBeforeDate(_ date: Date) -> Bool { return self.compare(date) == .orderedAscending } /// Check if current date less than another date /// The same as `isBeforeDate(_:)` /// /// - parameter date: Date to compare /// /// - returns: Bool func isLessThanDate(_ date: Date) -> Bool { return self.isBeforeDate(date) } /// Check if current date comes before date or equal /// The same as `isLessOrEqualToDate(_:)` /// /// - parameter date: Date to compare /// /// - returns: Bool func isOnOrBeforeDate(_ date: Date) -> Bool { return self.compare(date) == .orderedAscending || self.compare(date) == .orderedSame } /// Check if current date less than another date of equal /// The same as `isOnOrBeforeDate(_:)` /// /// - parameter date: Date to compare /// /// - returns: Bool func isLessOrEqualToDate(_ date: Date) -> Bool { return self.isOnOrBeforeDate(date) } /// Check if current date is equal to date /// /// - parameter date: Date object to compare /// /// - returns: Bool func equalToDate(_ date: Date) -> Bool { return self.compare(date) == ComparisonResult.orderedSame } // MARK: Components between dates /// Number of days since date /// /// - parameter date: Date object to compare /// /// - returns: Int func daysSinceDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.day, from: date, to: self, options: []) return components.day! } /// Number of days before date /// /// - parameter date: Date object to compare /// /// - returns: Int func daysBeforeDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.day, from: self, to: date, options: []) return components.day! } /// Number of weeks since date /// /// - parameter date: Date object to compare /// /// - returns: Int func weeksSinceDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.weekOfYear, from: date, to: self, options: []) return components.weekOfYear! } /// Number of weeks before date /// /// - parameter date: Date object to compare /// /// - returns: Int func weeksBeforeDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.weekOfYear, from: self, to: date, options: []) return components.weekOfYear! } /// Number of months since date /// /// - parameter date: Date object to compare /// /// - returns: Int func monthsSinceDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.month, from: date, to: self, options: []) return components.month! } /// Number of months before date /// /// - parameter date: Date object to compare /// /// - returns: Int func monthsBeforeDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.month, from: self, to: date, options: []) return components.month! } /// Number of years since date /// /// - parameter date: Date object to compare /// /// - returns: Int func yearsSinceDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.year, from: date, to: self, options: []) return components.year! } /// Number of years before date /// /// - parameter date: Date object to compare /// /// - returns: Int func yearsBeforeDate(_ date: Date) -> Int { let components = (Calendar.gregorianCalendar as NSCalendar).components(NSCalendar.Unit.year, from: self, to: date, options: []) return components.year! } }
mit
de4f317b050929d58e483bfa9b2674ce
27.285959
137
0.664084
4.308555
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Model/ToybooCreation.swift
1
1598
// // ToybooCreation.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 @objc public class ToybooCreation: NSObject { public let identifier: String public let uzpbUrl: String public let contentUrl: String init(mapper: ToybooCreationMapper, dataMapper: DataIncludeMapper? = nil, metadata: Metadata? = nil) { self.identifier = mapper.identifier! self.uzpbUrl = mapper.uzpbUrl! self.contentUrl = mapper.contentUrl! } }
mit
70c093f95242f28be96fa02358a6918a
39.974359
105
0.737797
4.194226
false
false
false
false
carlo-/ipolito
iPoliTO2/MapViewController.swift
1
20617
// // MapViewController.swift // iPoliTO2 // // Created by Carlo Rapisarda on 30/07/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController { @IBOutlet fileprivate var searchResultsTable: UITableView! @IBOutlet fileprivate var mapView: MKMapView! fileprivate var locationManager = CLLocationManager() fileprivate var searchBarContainer: UIView! fileprivate var searchController = UISearchController(searchResultsController: nil) fileprivate var searchBar: UISearchBar { return searchController.searchBar } fileprivate var searchBarText: String { return searchBar.text ?? "" } fileprivate var timePicker: CRTimePicker? fileprivate var timePickerVisible: Bool = false fileprivate lazy var allRooms: [PTRoom] = [PTRoom].fromBundle() fileprivate var filteredRooms: [PTRoom] = [] fileprivate var roomsToShow: [PTRoom] = [] fileprivate var roomToFocus: PTRoom? fileprivate(set) var isDownloadingFreeRooms: Bool = false fileprivate var freeRoomsLoadedDate: Date? = nil fileprivate var freeRoomsAnnotations: [MKAnnotation] = [] fileprivate var freeRooms: [PTFreeRoom] = [] fileprivate var freeRoomsLoadedDateDescription: String? { guard let date = freeRoomsLoadedDate else { return nil; } let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateFormat = "HH:mm" return ~"ls.mapVC.showingFreeRoomsFor"+" "+formatter.string(from: date) } var status: PTViewControllerStatus = .loggedOut { didSet { statusDidChange() } } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { // Disable use of 'large title' display mode navigationItem.largeTitleDisplayMode = .never } mapView.showsCompass = false setupSearchController() navigationItem.leftBarButtonItem = presentTimePickerButton() locationManager.delegate = self if CLLocationManager.authorizationStatus() != .authorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } showAllRooms() zoomToMainCampus(animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dismissSearchBar() reloadFreeRoomsIfNeeded() focusOnRoom(roomToFocus, animated: true) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) guard isViewLoaded else { return; } UIView.animate(withDuration: 0.35, animations: { self.layoutSearchBar(withControllerViewSize: size) self.layoutTimePicker(withControllerViewSize: size) }) } func statusDidChange() { switch status { case .logginIn: navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.generic.status.loggingIn") case .ready: navigationItem.titleView = PTDualTitleView(withTitle: ~"ls.mapVC.title", subtitle: freeRoomsLoadedDateDescription ?? "") if isViewLoaded { reloadFreeRoomsIfNeeded() } case .loggedOut: navigationItem.titleView = nil freeRoomsLoadedDate = nil default: navigationItem.titleView = PTDualTitleView(withTitle: ~"ls.generic.status.offline", subtitle: freeRoomsLoadedDateDescription ?? "") } } func handleTabBarItemSelection(wasAlreadySelected: Bool) { if wasAlreadySelected { dismissSearchBar() focusOnRoom(nil, animated: true) } } deinit { searchController.view.removeFromSuperview() } } // MARK: - Room Managing methods extension MapViewController { func shouldFocus(onRoom room: PTRoom?) { // Dismiss search bar if needed dismissSearchBar() roomToFocus = room } /// Reloads free rooms if lastest data is nil or not from today fileprivate func reloadFreeRoomsIfNeeded() { if status != .ready { return } if freeRoomsLoadedDate != nil && Calendar.current.isDateInToday(freeRoomsLoadedDate!) { return } downloadFreeRooms() } fileprivate func downloadFreeRooms(forDate date: Date? = nil) { if isDownloadingFreeRooms { return } isDownloadingFreeRooms = true navigationItem.titleView = PTLoadingTitleView(withTitle: ~"ls.mapVC.status.loading") PTSession.shared.requestFreeRooms(forDate: date, completion: { [unowned self] result in OperationQueue.main.addOperation({ switch result { case .success(let freeRooms): self.freeRoomsLoadedDate = date ?? Date() self.freeRooms = freeRooms self.reloadRoomAnnotations() self.navigationItem.titleView = PTDualTitleView(withTitle: ~"ls.mapVC.title", subtitle: self.freeRoomsLoadedDateDescription ?? "") case .failure(_): self.freeRoomsLoadedDate = nil self.freeRooms = [] self.reloadRoomAnnotations() self.navigationItem.titleView = PTDualTitleView(withTitle: ~"ls.mapVC.title", subtitle: ~"ls.mapVC.freeRoomsError") } self.isDownloadingFreeRooms = false }) }) } fileprivate func isRoomFree(_ room: PTRoom) -> Bool { guard freeRooms.count > 0, let roomName = room.name[.Italian]?.lowercased() else { return false } for freeRoom in freeRooms { if freeRoom.lowercased() == roomName { return true } } return false } @discardableResult fileprivate func reloadRoomAnnotations() -> [MKPointAnnotation] { removeAllAnnotations() var annotations: [MKPointAnnotation] = [] for room in roomsToShow { let isRoomFree = self.isRoomFree(room) let annot = MKPointAnnotation(fromRoom: room, free: isRoomFree) if isRoomFree { freeRoomsAnnotations.append(annot) } annotations.append(annot) } mapView.addAnnotations(annotations) if annotations.count == 1 { mapView.selectAnnotation(annotations.first!, animated: true) } return annotations } fileprivate func showAllRooms() { roomsToShow = allRooms reloadRoomAnnotations() } } // MARK: - Time Picker methods extension MapViewController { fileprivate func presentTimePickerButton() -> UIBarButtonItem { let image = #imageLiteral(resourceName: "clock") return UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(presentTimePicker)) } fileprivate func dismissTimePickerButton() -> UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissTimePicker)) } fileprivate func confirmTimePickerButton() -> UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(confirmTimePicker)) } fileprivate func layoutTimePicker(withControllerViewSize newSize: CGSize) { layoutTimePicker(withControllerViewSize: newSize, visible: timePickerVisible) } private func layoutTimePicker(withControllerViewSize newSize: CGSize, visible: Bool) { let orientation = UIDevice.current.orientation let height: CGFloat = 50.0 + 44.0 let width = newSize.width let topBarMaxY: CGFloat if orientation.isLandscape { topBarMaxY = 32.0 } else { topBarMaxY = 64.0 } var newTimePickerFrame = CGRect(x: 0, y: topBarMaxY, width: width, height: height) if !visible { newTimePickerFrame = newTimePickerFrame.offsetBy(dx: width, dy: 0) } timePicker?.frame = newTimePickerFrame } @objc fileprivate func presentTimePicker() { searchBar.isUserInteractionEnabled = false navigationItem.rightBarButtonItem = confirmTimePickerButton() navigationItem.leftBarButtonItem = dismissTimePickerButton() if timePicker == nil { timePicker = CRTimePicker(frame: .zero, date: freeRoomsLoadedDate) timePicker?.backgroundColor = UIColor.clear timePicker?.tintColor = UIColor.iPoliTO.darkGray view.addSubview(timePicker!) timePickerVisible = false layoutTimePicker(withControllerViewSize: view.frame.size, visible: false) } UIView.animate(withDuration: 0.25, animations: { if #available(iOS 11.0, *) { self.navigationItem.searchController = nil } self.layoutTimePicker(withControllerViewSize: self.view.frame.size, visible: true) }, completion: { _ in self.searchController.isActive = false self.timePickerVisible = true self.layoutTimePicker(withControllerViewSize: self.view.frame.size, visible: true) }) } @objc fileprivate func dismissTimePicker() { navigationItem.rightBarButtonItem = nil navigationItem.leftBarButtonItem = presentTimePickerButton() guard let timePicker = timePicker else { return } timePicker.stopScrollView() if #available(iOS 11.0, *) { self.navigationItem.searchController = self.searchController } UIView.animate(withDuration: 0.25, animations: { self.layoutTimePicker(withControllerViewSize: self.view.frame.size, visible: false) }, completion: { _ in self.searchBar.isUserInteractionEnabled = true self.timePickerVisible = false self.layoutTimePicker(withControllerViewSize: self.view.frame.size, visible: false) }) } @objc fileprivate func confirmTimePicker() { guard let timePicker = timePicker else { navigationItem.rightBarButtonItem = nil return } let selectedDate = timePicker.currentSelection() downloadFreeRooms(forDate: selectedDate) dismissTimePicker() } } // MARK: - TableView methods extension MapViewController: UITableViewDelegate, UITableViewDataSource { func setSearchResultsTableVisible(_ visible: Bool, animated: Bool) { if animated { UIView.transition(with: mapView, duration: 0.25, options: .transitionCrossDissolve, animations: { self.searchResultsTable.layer.opacity = (visible ? 1.0 : 0.0) }, completion: nil) } else { searchResultsTable.layer.opacity = (visible ? 1.0 : 0.0)} } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: "searchResultsCell", for: indexPath) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredRooms.count } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let room = filteredRooms[indexPath.row] cell.textLabel?.text = room.localizedName cell.detailTextLabel?.text = room.localizedFloor } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let room = filteredRooms[indexPath.row] dismissSearchBar() focusOnRoom(room) } } // MARK: - Search related methods extension MapViewController: UISearchControllerDelegate, UISearchResultsUpdating { func layoutSearchBar(withControllerViewSize newSize: CGSize) { let orientation = UIDevice.current.orientation let height: CGFloat = 44.0 let width = newSize.width let bottomBarHeight: CGFloat = 49.0 let searchBarMaxY: CGFloat let topBarMaxY: CGFloat if orientation.isLandscape { topBarMaxY = 32.0 searchBarMaxY = 44.0 } else { topBarMaxY = 64.0 searchBarMaxY = 64.0 } if !(searchController.isActive) { if #available(iOS 11.0, *) { // No need to set the frame of the search bar } else { searchBar.frame = CGRect(x: 0, y: 0, width: width, height: height) } } if #available(iOS 11.0, *) { searchResultsTable.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } else { searchBarContainer.frame = CGRect(x: 0, y: topBarMaxY, width: width, height: height) searchResultsTable.contentInset = UIEdgeInsets(top: searchBarMaxY, left: 0, bottom: bottomBarHeight, right: 0) searchResultsTable.scrollIndicatorInsets = UIEdgeInsets(top: searchBarMaxY, left: 0, bottom: bottomBarHeight, right: 0) } } func setupSearchController() { searchController.searchResultsUpdater = self searchController.delegate = self searchController.dimsBackgroundDuringPresentation = false searchBar.placeholder = ~"ls.mapVC.searchBarPlaceholder" searchBarContainer = UIView() if #available(iOS 11.0, *) { navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false } else { // Fallback on earlier versions searchBarContainer.addSubview(searchBar) searchBarContainer.isOpaque = false view.insertSubview(searchBarContainer, belowSubview: searchResultsTable) } definesPresentationContext = true let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor.iPoliTO.darkGray] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], for: .normal) layoutSearchBar(withControllerViewSize: view.frame.size) } func dismissSearchBar(force: Bool = false) { if force || searchController.isActive { searchController.isActive = false } } /* func didPresentSearchController(_ searchController: UISearchController) { } */ func didDismissSearchController(_ searchController: UISearchController) { searchController.searchBar.frame = searchBarContainer.bounds } func willPresentSearchController(_ searchController: UISearchController) { setSearchResultsTableVisible(true, animated: true) } func willDismissSearchController(_ searchController: UISearchController) { setSearchResultsTableVisible(false, animated: true) } func updateSearchResults(for searchController: UISearchController) { let query = searchBarText if query.isEmpty { filteredRooms.removeAll() searchResultsTable.reloadData() if searchController.isBeingDismissed { focusOnRoom(nil) } return; } let queryComps = query.lowercased().components(separatedBy: " ") filteredRooms = allRooms.filter({ room in let roomName = room.localizedName.lowercased() for comp in queryComps { if comp.contains("aula") || comp.contains("room") { continue } if roomName.contains(comp) { return true } } return false }) searchResultsTable.reloadData() } } // MARK: - MapView methods extension MapViewController: MKMapViewDelegate, CLLocationManagerDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKPointAnnotation { let isRoomFree = freeRoomsAnnotations.contains(where: { annot in return annot.hash == annotation.hash }) let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "roomPin") pinView.animatesDrop = false pinView.canShowCallout = true pinView.pinTintColor = isRoomFree ? #colorLiteral(red: 0.4028071761, green: 0.7315050364, blue: 0.2071235478, alpha: 1) : #colorLiteral(red: 0.6823074818, green: 0.08504396677, blue: 0.06545677781, alpha: 1) return pinView } return nil } fileprivate func removeAllAnnotations() { freeRoomsAnnotations.removeAll() mapView.removeAnnotations(mapView.annotations) } fileprivate func focusOnRoom(_ room: PTRoom?, animated: Bool = true) { guard let room = room else { roomToFocus = nil if !searchBarText.isEmpty { searchBar.text = nil } showAllRooms() zoomToMainCampus(animated: animated) return } let coords = CLLocationCoordinate2D(fromRoom: room) guard CLLocationCoordinate2DIsValid(coords) else { focusOnRoom(nil, animated: animated) return } roomToFocus = room searchBar.text = room.localizedName roomsToShow = [room] reloadRoomAnnotations() zoomToCoordinates(coords, withDelta: 0.00125, animated: animated) } fileprivate func zoomToMainCampus(animated: Bool = true) { zoomToCoordinates(CLLocationCoordinate2D.PolitecnicoMainCampus, withDelta: 0.00925, animated: animated) } fileprivate func zoomToCoordinates(_ coordinates: CLLocationCoordinate2D, withDelta delta: Double, animated: Bool = true) { guard CLLocationCoordinate2DIsValid(coordinates) else { return } let span = MKCoordinateSpan(latitudeDelta: delta, longitudeDelta: delta) let region = MKCoordinateRegion(center: coordinates, span: span) mapView.setRegion(region, animated: animated) } } fileprivate extension CLLocationCoordinate2D { static let PolitecnicoMainCampus = CLLocationCoordinate2D(latitude: 45.063371, longitude: 7.659864) init(fromRoom room: PTRoom) { self.latitude = room.latitude self.longitude = room.longitude } } fileprivate extension MKPointAnnotation { convenience init(fromRoom room: PTRoom, free: Bool) { self.init() let roomName = room.localizedName let roomFloor = room.localizedFloor let coords = CLLocationCoordinate2D(fromRoom: room) let roomStatus = free ? ~"ls.mapVC.freeRoom.status.free" : ~"ls.mapVC.freeRoom.status.occupied" self.coordinate = coords self.title = roomName self.subtitle = roomStatus+" - "+roomFloor } }
gpl-3.0
af568bc151ad39784552d89e00e23754
30.522936
219
0.600213
5.480064
false
false
false
false
frootloops/swift
test/Interpreter/protocol_extensions.swift
3
7692
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var ProtocolExtensionTestSuite = TestSuite("ProtocolExtensions") // Extend a protocol with a property. extension Sequence { var myCount: Int { var result = 0 for _ in self { result += 1 } return result } } // Extend a protocol with a function. extension Collection { var myIndices: Range<Index> { return startIndex..<endIndex } func clone() -> Self { return self } } ProtocolExtensionTestSuite.test("Count") { expectEqual(4, ["a", "b", "c", "d"].myCount) expectEqual(4, ["a", "b", "c", "d"].clone().myCount) } extension Sequence { public func myEnumerated() -> EnumeratedSequence<Self> { return self.enumerated() } } ProtocolExtensionTestSuite.test("Enumerated") { var result: [(Int, String)] = [] for (index, element) in ["a", "b", "c"].myEnumerated() { result.append((index, element)) } expectTrue((0, "a") == result[0]) expectTrue((1, "b") == result[1]) expectTrue((2, "c") == result[2]) } extension Sequence { public func myReduce<T>( _ initial: T, combine: (T, Self.Iterator.Element) -> T ) -> T { var result = initial for value in self { result = combine(result, value) } return result } } extension Sequence { public func myZip<S : Sequence>(_ s: S) -> Zip2Sequence<Self, S> { return Zip2Sequence(_sequence1: self, _sequence2: s) } } ProtocolExtensionTestSuite.test("Algorithms") { expectEqual(15, [1, 2, 3, 4, 5].myReduce(0, combine: { $0 + $1 })) var result: [(Int, String)] = [] for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) { result.append((a, b)) } expectTrue((1, "a") == result[0]) expectTrue((2, "b") == result[1]) expectTrue((3, "c") == result[2]) } // Mutating algorithms. extension MutableCollection where Self: RandomAccessCollection, Self.Iterator.Element : Comparable { public mutating func myPartition() -> Index { let first = self.first return self.partition(by: { $0 >= first! }) } } extension RangeReplaceableCollection { public func myJoin<S : Sequence>( _ elements: S ) -> Self where S.Iterator.Element == Self { var result = Self() var iter = elements.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: self) result.append(contentsOf: next) } } return result } } ProtocolExtensionTestSuite.test("MutatingAlgorithms") { expectEqual("a,b,c", ",".myJoin(["a", "b", "c"])) } // Constrained extensions for specific types. extension Collection where Self.Iterator.Element == String { var myCommaSeparatedList: String { if startIndex == endIndex { return "" } var result = "" var first = true for x in self { if first { first = false } else { result += ", " } result += x } return result } } ProtocolExtensionTestSuite.test("ConstrainedExtension") { expectEqual("x, y, z", ["x", "y", "z"].myCommaSeparatedList) } // Existentials var runExistP1 = 0 var existP1_struct = 0 var existP1_class = 0 protocol ExistP1 { func existP1() } extension ExistP1 { func runExistP1() { main.runExistP1 += 1 self.existP1() } } struct ExistP1_Struct : ExistP1 { func existP1() { existP1_struct += 1 } } class ExistP1_Class : ExistP1 { func existP1() { existP1_class += 1 } } ProtocolExtensionTestSuite.test("Existentials") { do { let existP1: ExistP1 = ExistP1_Struct() existP1.runExistP1() expectEqual(1, runExistP1) expectEqual(1, existP1_struct) } do { let existP1 = ExistP1_Class() existP1.runExistP1() expectEqual(2, runExistP1) expectEqual(1, existP1_class) } } protocol P { mutating func setValue(_ b: Bool) func getValue() -> Bool } extension P { var extValue: Bool { get { return getValue() } set(newValue) { setValue(newValue) } } } extension Bool : P { mutating func setValue(_ b: Bool) { self = b } func getValue() -> Bool { return self } } class C : P { var theValue: Bool = false func setValue(_ b: Bool) { theValue = b } func getValue() -> Bool { return theValue } } func toggle(_ value: inout Bool) { value = !value } ProtocolExtensionTestSuite.test("ExistentialToggle") { var p: P = true expectTrue(p.extValue) p.extValue = false expectFalse(p.extValue) toggle(&p.extValue) expectTrue(p.extValue) p = C() p.extValue = true expectTrue(p.extValue) p.extValue = false expectFalse(p.extValue) toggle(&p.extValue) expectTrue(p.extValue) } // Logical lvalues of existential type. struct HasP { var _p: P var p: P { get { return _p } set { _p = newValue } } } ProtocolExtensionTestSuite.test("ExistentialLValue") { var hasP = HasP(_p: false) hasP.p.extValue = true expectTrue(hasP.p.extValue) toggle(&hasP.p.extValue) expectFalse(hasP.p.extValue) } var metatypes: [(Int, Any.Type)] = [] // rdar://problem/20739719 class Super: Init { required init(x: Int) { metatypes.append((x, type(of: self))) } } class Sub: Super {} protocol Init { init(x: Int) } extension Init { init() { self.init(x: 17) } } ProtocolExtensionTestSuite.test("ClassInitializer") { _ = Super() _ = Sub() var sup: Super.Type = Super.self _ = sup.init() sup = Sub.self _ = sup.init() expectTrue(17 == metatypes[0].0) expectTrue(Super.self == metatypes[0].1) expectTrue(17 == metatypes[1].0) expectTrue(Sub.self == metatypes[1].1) expectTrue(17 == metatypes[2].0) expectTrue(Super.self == metatypes[2].1) expectTrue(17 == metatypes[3].0) expectTrue(Sub.self == metatypes[3].1) } // https://bugs.swift.org/browse/SR-617 protocol SelfMetadataTest { associatedtype T = Int func staticTypeOfSelf() -> Any.Type func staticTypeOfSelfTakesT(_: T) -> Any.Type func staticTypeOfSelfCallsWitness() -> Any.Type } extension SelfMetadataTest { func staticTypeOfSelf() -> Any.Type { return Self.self } func staticTypeOfSelfTakesT(_: T) -> Any.Type { return Self.self } func staticTypeOfSelfNotAWitness() -> Any.Type { return Self.self } func staticTypeOfSelfCallsWitness() -> Any.Type { return staticTypeOfSelf() } } class SelfMetadataBase : SelfMetadataTest {} class SelfMetadataDerived : SelfMetadataBase {} func testSelfMetadata<T : SelfMetadataTest>(_ x: T, _ t: T.T) -> [Any.Type] { return [x.staticTypeOfSelf(), x.staticTypeOfSelfTakesT(t), x.staticTypeOfSelfNotAWitness(), x.staticTypeOfSelfCallsWitness()] } ProtocolExtensionTestSuite.test("WitnessSelf") { do { let result = testSelfMetadata(SelfMetadataBase(), 0) expectTrue(SelfMetadataBase.self == result[0]) expectTrue(SelfMetadataBase.self == result[1]) expectTrue(SelfMetadataBase.self == result[2]) expectTrue(SelfMetadataBase.self == result[3]) } do { let result = testSelfMetadata(SelfMetadataDerived() as SelfMetadataBase, 0) expectTrue(SelfMetadataBase.self == result[0]) expectTrue(SelfMetadataBase.self == result[1]) expectTrue(SelfMetadataBase.self == result[2]) expectTrue(SelfMetadataBase.self == result[3]) } // This is the interesting case -- make sure the static type of 'Self' // is correctly passed on from the call site to the extension method do { let result = testSelfMetadata(SelfMetadataDerived(), 0) expectTrue(SelfMetadataDerived.self == result[0]) expectTrue(SelfMetadataBase.self == result[1]) expectTrue(SelfMetadataDerived.self == result[2]) expectTrue(SelfMetadataDerived.self == result[3]) } } runAllTests()
apache-2.0
421157d53a84155b4df5241b655295d5
20.790368
79
0.652106
3.406554
false
true
false
false
megabitsenmzq/PomoNow-iOS
PomoNow/PomoNow/AnimationFromList.swift
1
3539
// // AnimationFromList.swift // PomoNow // // Created by Megabits on 15/10/2. // Copyright © 2015年 Jinyu Meng. All rights reserved. // import UIKit class AnimationFromList: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { //获取动画的源控制器和目标控制器 let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! PomoListViewController let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! PomodoroViewController let container = transitionContext.containerView let snap = fromVC.TimerView.snapshotView(afterScreenUpdates: false) snap?.frame = container.convert(fromVC.TimerView.frame, from: fromVC.view) let snapRound = fromVC.round.snapshotView(afterScreenUpdates: false) snapRound?.frame = container.convert(fromVC.round.frame, from: fromVC.view) fromVC.TimerView.isHidden = true snapRound?.alpha = 0 toVC.view.frame = transitionContext.finalFrame(for: toVC) toVC.view.alpha = 0 //代理管理以下view container.addSubview(snap!) container.addSubview(snapRound!) container.addSubview(toVC.view) UIView.animate(withDuration: 0.1, delay:0,options:UIViewAnimationOptions(), animations: { () -> Void in fromVC.ListContainer.alpha = 0 }) { (finish: Bool) -> Void in fromVC.round.isHidden = true snapRound?.alpha = 1 toVC.timeLabel.text = pomodoroClass.timerLabel if withTask { if task.count > 0 { for i in 0...task.count - 1 { if task[i][3] == "1" { toVC.taskLabel.text = task[i][1] } } } else { withTask = false toVC.setDefaults ("main.withTask",value: withTask as AnyObject) } } else { toVC.taskLabel.text = NSLocalizedString("Start with a task", comment: "Start with a task") } } UIView.animate(withDuration: 0.25, delay:0.1,options:UIViewAnimationOptions(), animations: { () -> Void in toVC.view.layoutIfNeeded() toVC.view.setNeedsDisplay() snapRound?.frame = toVC.round.frame snap?.frame = container.convert(toVC.TimerView.frame, from: toVC.TimerViewContainer) }) { (finish: Bool) -> Void in } UIView.animate(withDuration: 0.1, delay:0.4,options:UIViewAnimationOptions(), animations: { () -> Void in snapRound?.alpha = 0 snap?.alpha = 0 }) { (finish: Bool) -> Void in snap?.removeFromSuperview() snapRound?.removeFromSuperview() } UIView.animate(withDuration: 0.05, delay:0.35,options:UIViewAnimationOptions(), animations: { () -> Void in toVC.view.alpha = 1 }) { (finish: Bool) -> Void in transitionContext.completeTransition(true) } } }
mit
509459ac1355e7752d5cb152e56d8a3d
39.627907
131
0.576989
5.063768
false
false
false
false
threemonkee/VCLabs
VCLabs/Spring Animation/Source Code/CodeViewController.swift
52
2532
// // CodeViewController.swift // DesignerNewsApp // // Created by Meng To on 2015-01-05. // Copyright (c) 2015 Meng To. All rights reserved. // import UIKit import Spring class CodeViewController: UIViewController { @IBOutlet weak var modalView: SpringView! @IBOutlet weak var codeTextView: UITextView! @IBOutlet weak var titleLabel: UILabel! var codeText: String = "" var data: SpringView! override func viewDidLoad() { super.viewDidLoad() modalView.transform = CGAffineTransformMakeTranslation(-300, 0) if data.animation != "" { codeText += "layer.animation = \"\(data.animation)\"\n" } if data.curve != "" { codeText += "layer.curve = \"\(data.curve)\"\n" } if data.force != 1 { codeText += String(format: "layer.force = %.1f\n", Double(data.force)) } if data.duration != 0.7 { codeText += String(format: "layer.duration = %.1f\n", Double(data.duration)) } if data.delay != 0 { codeText += String(format: "layer.delay = %.1f\n", Double(data.delay)) } if data.scaleX != 1 { codeText += String(format: "layer.scaleX = %.1f\n", Double(data.scaleX)) } if data.scaleY != 1 { codeText += String(format: "layer.scaleY = %.1f\n", Double(data.scaleY)) } if data.rotate != 0 { codeText += String(format: "layer.rotate = %.1f\n", Double(data.rotate)) } if data.damping != 0.7 { codeText += String(format: "layer.damping = %.1f\n", Double(data.damping)) } if data.velocity != 0.7 { codeText += String(format: "layer.velocity = %.1f\n", Double(data.velocity)) } codeText += "layer.animate()" codeTextView.text = codeText } @IBAction func closeButtonPressed(sender: AnyObject) { UIApplication.sharedApplication().sendAction("maximizeView:", to: nil, from: self, forEvent: nil) modalView.animation = "slideRight" modalView.animateFrom = false modalView.animateToNext({ self.dismissViewControllerAnimated(false, completion: nil) }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) modalView.animate() UIApplication.sharedApplication().sendAction("minimizeView:", to: nil, from: self, forEvent: nil) } }
gpl-2.0
c403032358686b39fae587e9d41c502f
31.883117
105
0.56872
4.227045
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Playgrounds/Enumerated Types.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
2
6694
//: ![banner](banner-with-plym.png) //: //: # Enumerated Types //: //: (c) Nicholas Outram 2016 //: Version 1.02 //: Change Log: //: 18-11-2016 Released to iTunes U //: 23-11-2016 Improved example on equating enums with assoc. values //: 24-11-2016 Added support for iPad - results from the UI were previously not visible. I've added a pop-over table view to show the results. In the global Sources folder, there is now a TableViewController.swift file. ViewController.swift now presents this as a popover (with forced no adaption to sizeclass so it always presents as a popover!). //: //: Enumerated types are commonly found in other languages. They promote type-safety and readability. //: Swift enumerated types are far more powerful than those found in older languages such as C. For certain use-cases they can be a natural replacment for a class or structure. Like structures and unlike classes, enumerated types are also value-types. //: //: Let's begin with a look at an example. import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: Make sure the Timeline is visible (cmd-alt-return) let vc = ViewController() PlaygroundPage.current.liveView = vc var allResponses = [Int]() //: This closure runs each time a selection is made vc.storeNewValue = { (u : Int) -> Void in allResponses.append(u) } //: This closure runs when the Done button is pressed vc.finished = { //Print all records to the terminal print("Here are all the responses so far") print("---------------------------------") for resp in allResponses { if resp == 1 { print("Disagree") } else if (resp == 2) { print("Slightly Disagree") } else if (resp == 3) { print("Slightly Agree") } else if (resp==4) { print("Agree") } else { print("Error") } } allResponses.removeAll() } //: - Experiment: If you change `else if (resp==4)` to `else if (resp==44)` as if you had made a typing error, how would you know about the error? //: //: Of course, you might suggest using a `switch` statement instead. //: //: - Experiment: Convert the code above to use a `switch` statement instead of `if-else if-else`. Is this an improvement? //: //: A critisism of this code is the use of an integer encoding of the response. Using 1,2,3 and 4 can work of course, and `switch-case` makes the code easier to read, but we still make the following observations: //: - You need to know / remember how the numerical codes relates to the category of the response //: - If you mistype a numerical value, the compiler will not pick up the error //: - If you added another category in the middle (e.g. "Neither Agree or Disagree"), you might then want to redefine all the upper values to retain the order. Such refactoring could result changes throughout the code, and hence increases the chance of introducing bugs. //: //: **Fundamentally**, the number of responses is a finite set of only 4 possible **values**, whereas type `Int` is a much larger set. This *unnecessarily* introduces the possibilty of introducing erroneous values. //: //: Instead of defining constants for each case / category, consider using an enumerated type: enum ResponseType { case disagree case slightlyDisagree case slightlyAgree case agree } //: Here an enumerated type variable has been defined. Equally, we could write the different cases as a comma separated list: /*: enum ResponseType { case disagree, slightlyDisagree, slightlyAgree, agree } */ var response : ResponseType //: Creates an instance of the new type response = ResponseType.agree //: Assigns a new value response = .slightlyAgree //: This is the shorthand notation. //: - Note: For the C programmers among you, do not assume these types are automatically assigned integer *raw values*, they are not. **Each `case` is a unique value in its own right**. Raw-values can be specified however (see [Raw Values](RawValues) later) //: ## Matching enumerated types with conditional statements //: For a simple enumerated type such as this, you can match equivalent values with the `==` operator as you would other types. if response == .agree { print("Great - glad we agree") } else if response == .disagree { print("Ok, I wont bother you with this any more") } else { print("Ok, maybe think about it") } //: Using an enumerated type in this way makes for very readable code. It is also type-safe. //: - Note: [Later](AssociatedValues) you will see more complex cases where `==` cannot be used //: ## Matching with switch-case //: `if` statements require care and can still be prone to mistakes. For example, if you added another enumerated case in your code, you might forget to cover it in all the relevant `if` statements. A `switch-case` is a more robust (and safer) alternative which *requires* that all cases are covered: switch response { case .agree: print("Glad we agree") case .disagree: print("Ok, I wont bother you with this any more") case .slightlyAgree, .slightlyDisagree: print("Ok, maybe think about it") } //: - Experiment: Try commenting out one of the cases - what happens? //: //: - Experiment: Try adding another category to the definition of ResponseType - what happens? //: //: Some key points here: //: * `switch` requires full coverage to compile - Missing a case will result in a compiler error. This is an error that occurs BEFORE you run the code (preferable to a run-time error). //: * No fall-through - If you're aware of `switch-case` in other languagues such as C, you might expect to see `break` statements for each case. In contrast, Swift code does not automatically fall-through into the next case, so there is no need for `break` statements. Given how easy it is to forget to write such `break` statements, so the Swift way is considered safer. However, in Swift you can stil force a fall-through by explicitly writing `fallthrough`. //: * Combining cases - Note how multiple cases (`.slightlyAgree` and `.slightlyDisagree`) are managed in this example using a comma separated list. //: ## Using default //: In the following example, `default` is used to catch all cases not explicitly covered. Some care is needed when using this as the switch will always have full coverage. Therefore if you add a new case and forget to handle it, no compiler error will occur. switch response { case .agree: print("Glad we agree") case .disagree: print("Ok, I wont bother you with this any more") default: print("Ok, maybe think about it") } //: Next we look at how each enumerated case can be assigned a raw value. //: //: ---- //: //: [Next - raw values](@next)
mit
1665af2bfc386d8e90072b2798171958
49.712121
461
0.716612
4.155183
false
false
false
false
mcrollin/safecaster
safecaster/SCRMeasurementScaleView.swift
1
816
// // SCRMeasurementScaleView.swift // safecaster // // Created by Marc Rollin on 5/17/15. // Copyright (c) 2015 safecast. All rights reserved. // import UIKit class SCRMeasurementScaleView: UIView { override func drawRect(rect: CGRect) { let gradient = CAGradientLayer() let lut = SCRMeasurementColorLUT() let steps = 64 let stepSize = lut.n / steps var i = 0 gradient.colors = (1...steps).map { _ in return lut.colorForIndex(lut.n - 1 - stepSize * i++).CGColor } gradient.frame = CGRectMake(0, 0, frame.width, frame.height) layer.insertSublayer(gradient, atIndex: 0) layer.cornerRadius = frame.width / 2 clipsToBounds = true self.alpha = 0.9 } }
cc0-1.0
f8818b43618d62d99a9a4bdc870bab4c
27.137931
111
0.578431
3.961165
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/TestImplementations/ElementIndexPair.swift
15
510
// // ElementIndexPair.swift // Tests // // Created by Krunoslav Zaher on 6/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // struct ElementIndexPair<E: Equatable, I: Equatable> : Equatable { let element: E let index: I init(_ element: E, _ index: I) { self.element = element self.index = index } } func == <E, I>(lhs: ElementIndexPair<E, I>, rhs: ElementIndexPair<E, I>) -> Bool { return lhs.element == rhs.element && lhs.index == rhs.index }
mit
42f18ae104aa7ca412d8d80c397dd409
23.238095
82
0.618861
3.326797
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+WindowTests.swift
11
5689
// // Observable+WindowTests.swift // Tests // // Created by Krunoslav Zaher on 4/29/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableWindowTest : RxTest { } extension ObservableWindowTest { func testWindowWithTimeOrCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(205, 1), next(210, 2), next(240, 3), next(280, 4), next(320, 5), next(350, 6), next(370, 7), next(420, 8), next(470, 9), completed(600) ]) let res = scheduler.start { () -> Observable<String> in let window: Observable<Observable<Int>> = xs.window(timeSpan: 70, count: 3, scheduler: scheduler) let mappedWithIndex = window.mapWithIndex { (o: Observable<Int>, i: Int) -> Observable<String> in return o.map { (e: Int) -> String in return "\(i) \(e)" } } let result = mappedWithIndex.merge() return result } XCTAssertEqual(res.events, [ next(205, "0 1"), next(210, "0 2"), next(240, "0 3"), next(280, "1 4"), next(320, "2 5"), next(350, "2 6"), next(370, "2 7"), next(420, "3 8"), next(470, "4 9"), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) } func testWindowWithTimeOrCount_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(205, 1), next(210, 2), next(240, 3), next(280, 4), next(320, 5), next(350, 6), next(370, 7), next(420, 8), next(470, 9), error(600, testError) ]) let res = scheduler.start { () -> Observable<String> in let window: Observable<Observable<Int>> = xs.window(timeSpan: 70, count: 3, scheduler: scheduler) let mappedWithIndex = window.mapWithIndex { (o: Observable<Int>, i: Int) -> Observable<String> in return o.map { (e: Int) -> String in return "\(i) \(e)" } } let result = mappedWithIndex.merge() return result } XCTAssertEqual(res.events, [ next(205, "0 1"), next(210, "0 2"), next(240, "0 3"), next(280, "1 4"), next(320, "2 5"), next(350, "2 6"), next(370, "2 7"), next(420, "3 8"), next(470, "4 9"), error(600, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) } func testWindowWithTimeOrCount_Disposed() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(105, 0), next(205, 1), next(210, 2), next(240, 3), next(280, 4), next(320, 5), next(350, 6), next(370, 7), next(420, 8), next(470, 9), completed(600) ]) let res = scheduler.start(disposed: 370) { () -> Observable<String> in let window: Observable<Observable<Int>> = xs.window(timeSpan: 70, count: 3, scheduler: scheduler) let mappedWithIndex = window.mapWithIndex { (o: Observable<Int>, i: Int) -> Observable<String> in return o.map { (e: Int) -> String in return "\(i) \(e)" } } let result = mappedWithIndex.merge() return result } XCTAssertEqual(res.events, [ next(205, "0 1"), next(210, "0 2"), next(240, "0 3"), next(280, "1 4"), next(320, "2 5"), next(350, "2 6"), next(370, "2 7") ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 370) ]) } func windowWithTimeOrCount_Default() { let backgroundScheduler = SerialDispatchQueueScheduler(qos: .default) let result = try! Observable.range(start: 1, count: 10, scheduler: backgroundScheduler) .window(timeSpan: 1000, count: 3, scheduler: backgroundScheduler) .mapWithIndex { (o: Observable<Int>, i: Int) -> Observable<String> in return o.map { (e: Int) -> String in return "\(i) \(e)" } } .merge() .skip(4) .toBlocking() .first() XCTAssertEqual(result!, "1 5") } #if TRACE_RESOURCES func testWindowReleasesResourcesOnComplete() { let scheduler = TestScheduler(initialClock: 0) _ = Observable<Int>.just(1).window(timeSpan: 0.0, count: 10, scheduler: scheduler).subscribe() scheduler.start() } func testWindowReleasesResourcesOnError() { let scheduler = TestScheduler(initialClock: 0) _ = Observable<Int>.error(testError).window(timeSpan: 0.0, count: 10, scheduler: scheduler).subscribe() scheduler.start() } #endif }
mit
0dbc32d243a445c5cb52a2644b3023b7
30.425414
115
0.476617
4.412723
false
true
false
false
sunfei/RxSwift
RxSwift/RxSwift/Observables/Implementations/RefCount.swift
11
2630
// // RefCount.swift // Rx // // Created by Krunoslav Zaher on 3/5/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RefCount_<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.Element let parent: RefCount<Element> typealias ParentState = RefCount<Element>.State init(parent: RefCount<Element>, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = self.parent.source.subscribeSafe(self) let state = self.parent.state self.parent.lock.performLocked { if state.count == 0 { self.parent.state.count = 1 self.parent.state.connectableSubscription = self.parent.source.connect() } else { self.parent.state.count = state.count + 1 } } return AnonymousDisposable { subscription.dispose() self.parent.lock.performLocked { let state = self.parent.state if state.count == 1 { state.connectableSubscription!.dispose() self.parent.state.count = 0 self.parent.state.connectableSubscription = nil } else if state.count > 1 { self.parent.state.count = state.count - 1 } else { rxFatalError("Something went wrong with RefCount disposing mechanism") } } } } func on(event: Event<Element>) { switch event { case .Next: trySend(observer, event) case .Error: fallthrough case .Completed: trySend(observer, event) self.dispose() } } } class RefCount<Element>: Producer<Element> { typealias State = ( count: Int, connectableSubscription: Disposable? ) var lock = SpinLock() var state: State = ( count: 0, connectableSubscription: nil ) let source: ConnectableObservableType<Element> init(source: ConnectableObservableType<Element>) { self.source = source } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = RefCount_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
25e714df2dfc192a56ce21e948108e4f
27.912088
145
0.553612
4.77314
false
false
false
false
saoudrizwan/Disk
Sources/Disk+[UIImage].swift
1
8596
// The MIT License (MIT) // // Copyright (c) 2017 Saoud Rizwan <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit public extension Disk { /// Save an array of images to disk /// /// - Parameters: /// - value: array of images to store /// - directory: user directory to store the images in /// - path: folder location to store the images (i.e. "Folder/") /// - Throws: Error if there were any issues creating a folder and writing the given images to it static func save(_ value: [UIImage], to directory: Directory, as path: String) throws { do { let folderUrl = try createURL(for: path, in: directory) try createSubfoldersBeforeCreatingFile(at: folderUrl) try FileManager.default.createDirectory(at: folderUrl, withIntermediateDirectories: false, attributes: nil) for i in 0..<value.count { let image = value[i] var imageData: Data var imageName = "\(i)" var pngData: Data? var jpegData: Data? #if swift(>=4.2) if let data = image.pngData() { pngData = data } else if let data = image.jpegData(compressionQuality: 1) { jpegData = data } #else if let data = UIImagePNGRepresentation(image) { pngData = data } else if let data = UIImageJPEGRepresentation(image, 1) { jpegData = data } #endif if let data = pngData { imageData = data imageName = imageName + ".png" } else if let data = jpegData { imageData = data imageName = imageName + ".jpg" } else { throw createError( .serialization, description: "Could not serialize UIImage \(i) in the array to Data.", failureReason: "UIImage \(i) could not serialize to PNG or JPEG data.", recoverySuggestion: "Make sure there are no corrupt images in the array." ) } let imageUrl = folderUrl.appendingPathComponent(imageName, isDirectory: false) try imageData.write(to: imageUrl, options: .atomic) } } catch { throw error } } /// Append an image to a folder /// /// - Parameters: /// - value: image to store to disk /// - path: folder location to store the image (i.e. "Folder/") /// - directory: user directory to store the image file in /// - Throws: Error if there were any issues writing the image to disk static func append(_ value: UIImage, to path: String, in directory: Directory) throws { do { if let folderUrl = try? getExistingFileURL(for: path, in: directory) { let fileUrls = try FileManager.default.contentsOfDirectory(at: folderUrl, includingPropertiesForKeys: nil, options: []) var largestFileNameInt = -1 for i in 0..<fileUrls.count { let fileUrl = fileUrls[i] if let fileNameInt = fileNameInt(fileUrl) { if fileNameInt > largestFileNameInt { largestFileNameInt = fileNameInt } } } let newFileNameInt = largestFileNameInt + 1 var imageData: Data var imageName = "\(newFileNameInt)" var pngData: Data? var jpegData: Data? #if swift(>=4.2) if let data = value.pngData() { pngData = data } else if let data = value.jpegData(compressionQuality: 1) { jpegData = data } #else if let data = UIImagePNGRepresentation(value) { pngData = data } else if let data = UIImageJPEGRepresentation(value, 1) { jpegData = data } #endif if let data = pngData { imageData = data imageName = imageName + ".png" } else if let data = jpegData { imageData = data imageName = imageName + ".jpg" } else { throw createError( .serialization, description: "Could not serialize UIImage to Data.", failureReason: "UIImage could not serialize to PNG or JPEG data.", recoverySuggestion: "Make sure image is not corrupt." ) } let imageUrl = folderUrl.appendingPathComponent(imageName, isDirectory: false) try imageData.write(to: imageUrl, options: .atomic) } else { let array = [value] try save(array, to: directory, as: path) } } catch { throw error } } /// Append an array of images to a folder /// /// - Parameters: /// - value: images to store to disk /// - path: folder location to store the images (i.e. "Folder/") /// - directory: user directory to store the images in /// - Throws: Error if there were any issues writing the images to disk static func append(_ value: [UIImage], to path: String, in directory: Directory) throws { do { if let _ = try? getExistingFileURL(for: path, in: directory) { for image in value { try append(image, to: path, in: directory) } } else { try save(value, to: directory, as: path) } } catch { throw error } } /// Retrieve an array of images from a folder on disk /// /// - Parameters: /// - path: path of folder holding desired images /// - directory: user directory where images' folder was created /// - type: here for Swifty generics magic, use [UIImage].self /// - Returns: [UIImage] from disk /// - Throws: Error if there were any issues retrieving the specified folder of images static func retrieve(_ path: String, from directory: Directory, as type: [UIImage].Type) throws -> [UIImage] { do { let url = try getExistingFileURL(for: path, in: directory) let fileUrls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []) let sortedFileUrls = fileUrls.sorted(by: { (url1, url2) -> Bool in if let fileNameInt1 = fileNameInt(url1), let fileNameInt2 = fileNameInt(url2) { return fileNameInt1 <= fileNameInt2 } return true }) var images = [UIImage]() for i in 0..<sortedFileUrls.count { let fileUrl = sortedFileUrls[i] let data = try Data(contentsOf: fileUrl) if let image = UIImage(data: data) { images.append(image) } } return images } catch { throw error } } }
mit
5ea0c2b3aa93a5c3dab456626aace4be
42.634518
135
0.541066
5.135006
false
false
false
false
yongju-hong/thrift
lib/swift/Sources/TSet.swift
12
5564
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation public struct TSet<Element : TSerializable & Hashable> : SetAlgebra, Hashable, Collection, ExpressibleByArrayLiteral, TSerializable { /// Typealias for Storage type public typealias Storage = Set<Element> /// Internal Storage used for TSet (Set\<Element\>) internal var storage : Storage /// Mark: Collection public typealias Element = Storage.Element public typealias Indices = Storage.Indices public typealias Index = Storage.Index public typealias IndexDistance = Int public typealias SubSequence = Storage.SubSequence public var indices: Indices { return storage.indices } // Must implement isEmpty even though both SetAlgebra and Collection provide it due to their conflciting default implementations public var isEmpty: Bool { return storage.isEmpty } public func distance(from start: Index, to end: Index) -> IndexDistance { return storage.distance(from: start, to: end) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { return storage.index(i, offsetBy: n) } public func index(_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index) -> Index? { return storage.index(i, offsetBy: n, limitedBy: limit) } #if swift(>=3.2) public subscript (position: Storage.Index) -> Element { return storage[position] } #else public subscript (position: Storage.Index) -> Element? { return storage[position] } #endif /// Mark: SetAlgebra internal init(storage: Set<Element>) { self.storage = storage } public func contains(_ member: Element) -> Bool { return storage.contains(member) } public mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element) { return storage.insert(newMember) } public mutating func remove(_ member: Element) -> Element? { return storage.remove(member) } public func union(_ other: TSet<Element>) -> TSet { return TSet(storage: storage.union(other.storage)) } public mutating func formIntersection(_ other: TSet<Element>) { return storage.formIntersection(other.storage) } public mutating func formSymmetricDifference(_ other: TSet<Element>) { return storage.formSymmetricDifference(other.storage) } public mutating func formUnion(_ other: TSet<Element>) { return storage.formUnion(other.storage) } public func intersection(_ other: TSet<Element>) -> TSet { return TSet(storage: storage.intersection(other.storage)) } public func symmetricDifference(_ other: TSet<Element>) -> TSet { return TSet(storage: storage.symmetricDifference(other.storage)) } public mutating func update(with newMember: Element) -> Element? { return storage.update(with: newMember) } /// Mark: IndexableBase public var startIndex: Index { return storage.startIndex } public var endIndex: Index { return storage.endIndex } public func index(after i: Index) -> Index { return storage.index(after: i) } public func formIndex(after i: inout Storage.Index) { storage.formIndex(after: &i) } public subscript(bounds: Range<Index>) -> SubSequence { return storage[bounds] } /// Mark: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(storage) } /// Mark: TSerializable public static var thriftType : TType { return .set } public init() { storage = Storage() } public init(arrayLiteral elements: Element...) { self.storage = Storage(elements) } public init<Source : Sequence>(_ sequence: Source) where Source.Iterator.Element == Element { storage = Storage(sequence) } public static func read(from proto: TProtocol) throws -> TSet { let (elementType, size) = try proto.readSetBegin() if elementType != Element.thriftType { throw TProtocolError(error: .invalidData, extendedError: .unexpectedType(type: elementType)) } var set = TSet() for _ in 0..<size { let element = try Element.read(from: proto) set.storage.insert(element) } try proto.readSetEnd() return set } public func write(to proto: TProtocol) throws { try proto.writeSetBegin(elementType: Element.thriftType, size: Int32(self.count)) for element in self.storage { try Element.write(element, to: proto) } try proto.writeSetEnd() } } extension TSet: CustomStringConvertible, CustomDebugStringConvertible { public var description : String { return storage.description } public var debugDescription : String { return storage.debugDescription } } public func ==<Element>(lhs: TSet<Element>, rhs: TSet<Element>) -> Bool { return lhs.storage == rhs.storage }
apache-2.0
cb9ccdcda971fd71cd73f28dc68aca97
29.075676
133
0.698239
4.381102
false
false
false
false
XiaoChenYung/GitSwift
GitSwift/Login/LoginViewController.swift
1
5212
// // LoginViewController.swift // GitSwift // // Created by tm on 2017/8/3. // Copyright © 2017年 tm. All rights reserved. // import UIKit import Alamofire import RxAlamofire import RxSwift import GitClient class LoginViewController: BaseViewController { let dis = DisposeBag() @IBOutlet weak var passwordTextField: UnderLineTextField! @IBOutlet weak var usernameTextField: UnderLineTextField! @IBOutlet weak var loginButton: RadiusButton! override func viewDidLoad() { super.viewDidLoad() self.viewModel?.service.client?.login(username: "xiaochenyung", password: "wenweiyv123456").subscribe(onNext: { client in print(client) }).addDisposableTo(dis) // let request = Alamofire.request("https://api.github.com/users").responseJSON { (response) in // // } // let block: ((_ a: Int) -> (Observable<Int>)) = { a in // Observable.create({ subscriber -> Disposable in // subscriber.on(.next(a)) // subscriber.onCompleted() // return Disposables.create() // }) // } // // // // let fruitObservable = Observable.from(["🍎", "🍐", "🍊","🦋"]) // let stringObservable = Observable.from(["❤️","👠","👛","🐤"]) // let animalObservable = Observable.from(["🐶","🐱","🐭","🐹","👢","🦀"]) // let other = Observable.from(["🏈","🎱","⚾️"]) // // let aaa = block(10) // aaa.flatMap { a -> Observable<Int> in // if a > 10000 { // return Observable.just(a) // } else { // return block(a * a) // } // } // .subscribe(onNext: { a in // print(a) // }).addDisposableTo(dis) // aaa.flatMap { a in // let b = a as Int // Observable.just(b) // }.subscribe(onNext: { a in // print(a) // }).addDisposableTo(dis) // self.viewModel?.service.client?.login(username: <#T##String#>, password: <#T##String#>) // let ooo = Observable.combineLatest([fruitObservable, stringObservable, animalObservable, other]) // ooo.flatMap { // Observable.just($0[0]) // }.subscribe(onNext: { (string) in // print(string) // }).addDisposableTo(dis) // let user = "xiaochenyung" // let password = "wenweiyv123456" // let user = "08e8f67b57b54e4bffeef5f343b669e228a0a336" // let password = "x-oauth-basic" // Alamofire.request("https://api.github.com/authorizations/clients/73d8c44f52cc65cd1a19", parameters: ["scopes": ["user, repo"], "client_secret": "3b43822f9e972d27d8a19af8e072a702d6167ba2"], encoding: URLEncoding.default, // headers: ["Accept":"application/vnd.github.mirage-preview+json", "X-GitHub-OTP":password]) // .authenticate(user: user, password: password) // .responseJSON { response in // debugPrint(response) // } // var headers: HTTPHeaders = ["Accept":"application/vnd.github.mirage-preview+json", "X-GitHub-OTP":password] // // if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { // headers[authorizationHeader.key] = authorizationHeader.value // } // // // RxAlamofire.requestJSON( .get, "https://api.github.com/users/XiaoChenYung/received_events", parameters: ["per_page": 100], encoding: URLEncoding.default, headers: headers) // .subscribe(onNext: { response in // print(response.1) // }) // Alamofire.request("https://api.github.com/authorizations/clients/73d8c44f52cc65cd1a19", method: .put, parameters: ["scopes": ["user", "repo"], "client_secret": "3b43822f9e972d27d8a19af8e072a702d6167ba2"], encoding: JSONEncoding.default, headers: headers) // .responseJSON { response in // debugPrint(response) // } // RxAlamofire.request("https://api.github.com/users/XiaoChenYung/received_events", method: .get, parameters: ["per_page": 100], encoding: URLEncoding.default, headers: headers) // .responseJSON { response in // debugPrint(response) // } // Do any additional setup after loading the view. } 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
3d8054bf3667fa71ea5e64eb1a99a48c
35.567376
264
0.558573
4.034429
false
false
false
false
prebid/prebid-mobile-ios
InternalTestApp/PrebidMobileDemoRenderingUITests/UITests/PrebidVideoInterstitialUITest.swift
1
4808
/*   Copyright 2018-2021 Prebid.org, Inc.  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 XCTest class PrebidVideoInterstitialUITest: RepeatedUITestCase { private let waitingTimeout = 15.0 private let videoDuration = TimeInterval(17) let videoInterstitialTitle = "Video Interstitial 320x480 (In-App)" let videoInterstitialEndCardTitle = "Video Interstitial 320x480 with End Card (In-App)" override func setUp() { super.setUp() } func testVideoInterstitial() { repeatTesting(times: 7) { openVideo(title: videoInterstitialTitle) // Wait for the Learn more. let LearnMoreBtn = app.buttons["Learn More"] waitForExists(element: LearnMoreBtn, waitSeconds: 5 ) // Wait for Close let interstitialCloseBtn = app.buttons["PBMCloseButton"] waitForHittable(element: interstitialCloseBtn, waitSeconds: 15) interstitialCloseBtn.tap() verifyPostEvents(expectClick: false) } } func testLearnMore() { repeatTesting(times: 7) { openVideo(title: videoInterstitialTitle) // Wait for the Learn more. let LearnMoreBtn = app.buttons["Learn More"] waitForExists(element: LearnMoreBtn, waitSeconds: 5 ) LearnMoreBtn.tap() // Wait for the click through browser to come up. let clickthroughBrowserCloseBtn = app.buttons["PBMCloseButtonClickThroughBrowser"] waitForHittable(element: clickthroughBrowserCloseBtn, waitSeconds: 5) clickthroughBrowserCloseBtn.tap() let videoCloseBtn = app.buttons["PBMCloseButton"] waitForHittable(element: videoCloseBtn, waitSeconds: 15) videoCloseBtn.tap() verifyPostEvents(expectClick: true) } } func testAutoClose() { repeatTesting(times: 7) { openVideo(title: videoInterstitialTitle) let videoCloseBtn = app.buttons["PBMCloseButton"] waitForHittable(element: videoCloseBtn, waitSeconds: 15) // The close button should disappear // It means the video has closed automatically waitForNotExist(element: videoCloseBtn, waitSeconds: 20) verifyPostEvents(expectClick: false) } } func testTapEndCardThenClose() { repeatTesting(times: 7) { openVideo(title: videoInterstitialEndCardTitle) // Waiting for the end of the video... Thread.sleep(forTimeInterval: videoDuration) // Tap on End card let endCardLink = app.links.firstMatch waitForExists(element: endCardLink, waitSeconds: 2) endCardLink.tap() // Close button should be present let videoCloseBtn = app.buttons["PBMCloseButtonClickThroughBrowser"] waitForHittable(element: videoCloseBtn, waitSeconds: 5) videoCloseBtn.tap() verifyPostEvents(expectClick: true) } } // MARK: - Private methods private func openVideo(title: String) { navigateToExamplesSection() navigateToExample(title) waitAd() let showButton = app.buttons["Show"] waitForEnabled(element: showButton) showButton.tap() } private func waitAd() { let adReceivedButton = app.buttons["interstitialDidReceiveAd called"] let adFailedToLoadButton = app.buttons["interstitialDidFailToReceiveAd called"] waitForEnabled(element: adReceivedButton, failElement: adFailedToLoadButton, waitSeconds: waitingTimeout) } private func verifyPostEvents(expectClick: Bool) { XCTAssertTrue(app.buttons["interstitialWillPresentAd called"].isEnabled) XCTAssertTrue(app.buttons["interstitialDidDismissAd called"].isEnabled) XCTAssertFalse(app.buttons["interstitialWillLeaveApplication called"].isEnabled) XCTAssertEqual(app.buttons["interstitialDidClickAd called"].isEnabled, expectClick) } }
apache-2.0
5ff487af30c867f3cbb9c2edd7712335
35.618321
113
0.636439
5.054795
false
true
false
false
EyreFree/EFQRCode
Source/EFUIntPixel.swift
2
1579
// // EFUIntPixel.swift // EFQRCode // // Created by EyreFree on 2018/11/14. // // Copyright (c) 2017 EyreFree <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreGraphics public struct EFUIntPixel { public var red: UInt8 = 0 public var green: UInt8 = 0 public var blue: UInt8 = 0 public var alpha: UInt8 = 0 init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) { self.red = red self.green = green self.blue = blue self.alpha = alpha } }
mit
e0c9137c9a006e8b67ca619f1b755bd2
37.512195
81
0.713743
4.028061
false
false
false
false
SauvageP/Notes
Notes/Document.swift
1
15483
// // Document.swift // Notes // // Created by Perry Gabriel on 11/18/16. // Copyright © 2016 Perry R. Gabriel. All rights reserved. // import Cocoa import MapKit /// Names of files/directories in the package enum NoteDocumentFileNames : String { case TextFile = "Text.rtf" case AttachmentsDirectory = "Attachments" case QuickLookDirectory = "QuickLook" case QuickLookTextFile = "Preview.rtf" case QuickLookThumbnail = "Thumbnail.png" } enum ErrorCode : Int { /// We couldn't find the document at all case CannotAccessDocument /// We couldn't access any file wrappers inside this document. case CannotLoadFileWrappers /// We couldn't load the Text.rtf file case CannotLoadText /// We couldn't access the Attachment folder. case CannotAccessAttachments /// We couldn't save the Text.rtf file. case CannotSaveText /// We couldn't save an attachment. case CannotSaveAttachment } let ErrorDomain = "NotesErrorDomain" func err(_ code: ErrorCode, _ userInfo : [NSObject:AnyObject]? = nil) -> NSError { // Generate an NSError object, using ErrorDomain and whatever // value we were passed. return NSError(domain: ErrorDomain, code: code.rawValue, userInfo: userInfo) } extension FileWrapper { dynamic var fileExtension : String? { return self.preferredFilename?.components(separatedBy: ".").last } dynamic var thumbnailImage : NSImage { if let fileExtension = self.fileExtension { return NSWorkspace.shared().icon(forFileType: fileExtension) } else { return NSWorkspace.shared().icon(forFileType: "") } } func conformsToType(type: CFString) -> Bool { // Get the extension of this file guard let fileExtension = self.fileExtension else { // If we can't get a file extension // assume that it doesn't conform return false } // Get the file type of the attachment based on its extension guard let filetype = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)?.takeRetainedValue() else { // If we can't figure out the file type // from the extension, it also doesn't conform return false } // Ask the system if this file type conforms to the provided type return UTTypeConformsTo(filetype, type) } } extension Document : AddAttachmentDelegate { func addFile() { let panel = NSOpenPanel() panel.allowsMultipleSelection = false panel.canChooseFiles = true panel.canChooseDirectories = false panel.begin { (result) -> Void in if result == NSModalResponseOK, let resultURL = panel.urls.first { do { // We were given a URL - copy it in! try self.addAttachmentAtURL(url: resultURL as NSURL) // Refresh the attachments list self.attachmentList?.reloadData() } catch let error as NSError { // There was an error adding the attachment, // Show the user!! // Try to get a window in which to present a sheet if let window = self.windowForSheet { // Present the error in a sheet NSApp.presentError(error, modalFor: window, delegate: nil, didPresent: nil, contextInfo: nil) } else { // No window, so present it in a dialog box NSApp.presentError(error) } } } } } } extension Document : NSCollectionViewDataSource { func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { // The number of items is equal to the number of // attachments we have. If for some reason we can't // access 'attachmentFiles', we have zero items. return self.attachedFiles?.count ?? 0 } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { // Get the attachment that this cell should represent let attachment = self.attachedFiles![indexPath.item] // Get the cell itself let item = collectionView .makeItem(withIdentifier: "AttachmentCell", for: indexPath) as! AttachmentCell // Display the image and file extension in the cell item.imageView?.image = attachment.thumbnailImage item.textField?.stringValue = attachment.fileExtension ?? "" // Make this cell use as it delegate item.delegate = self return item } } extension Document : NSCollectionViewDelegate { private func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndex proposedDropIndex: AutoreleasingUnsafeMutablePointer<NSIndexPath?>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionViewDropOperation>) -> NSDragOperation { // Indicate to the user that is they release the mouse button, // it will "copy" whatever they're dragging. return NSDragOperation.copy } func collectionView(_ collectionView: NSCollectionView, acceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionViewDropOperation) -> Bool { // Get tge pasteboard that contains the info the user dropped let pasteboard = draggingInfo.draggingPasteboard() // If the pasteborad contains a URL, and we can get that URL... if pasteboard.types?.contains(NSURLPboardType) == true, let url = NSURL(from: pasteboard) { // Then attempt to add that as an attachment! do { // Add it to the document try self.addAttachmentAtURL(url: url) // Reload the attachment list to display it attachmentList.reloadData() // It succeeded!! return true } catch let error as NSError { // Present the error in a dialog box. self.presentError(error) // It failed, so tell the system to animate the dropped // item back to where it came from return false } } return false } } @objc protocol AttachmentCellDelegate : NSObjectProtocol { func openSelectedAttachment(collectionViewItem : NSCollectionViewItem) } extension Document : AttachmentCellDelegate { func openSelectedAttachment(collectionViewItem: NSCollectionViewItem) { // get the index of this item, or bail out guard let selectedIndex = self.attachmentList.indexPath(for: collectionViewItem)?.item else { return } // Get the attachment in question, or bail out guard let attachment = self.attachedFiles?[selectedIndex] else { return } // First, ensure that the document is saved self.autosave(withImplicitCancellability: false, completionHandler: { (error) -> Void in // If this attachment indicates that it's JSON, and we're // to get JSON data out of it... if attachment.conformsToType(type: kUTTypeJSON), let data = attachment.regularFileContents, let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? NSDictionary { // And if that JSON data includes lat and long entries... if let lat = json?["lat"] as? CLLocationDegrees, let lon = json?["long"] as? CLLocationDegrees { // Build a cooridinate from them let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) // Build a placemark with that coordinate and a map item in the Maps app! let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary: nil)) // And open the map item in the Maps app! mapItem.openInMaps(launchOptions: nil) } } else { var url = self.fileURL url = url?.appendingPathComponent(attachment.preferredFilename!) if let path = url?.path { NSWorkspace.shared().openFile(path, withApplication: nil, andDeactivate: true) } } }) } } class Document: NSDocument { // Main text content var text : NSAttributedString = NSAttributedString() var documentFileWrapper = FileWrapper(directoryWithFileWrappers : [:]) @IBAction func addAttachment(_ sender: NSButton) { if let viewController = AddAttachmentViewController(nibName:"AddAttachmentViewController", bundle: Bundle.main) { viewController.delegate = self self.popover = NSPopover() self.popover?.behavior = .transient self.popover?.contentViewController = viewController self.popover?.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.maxY) } } @IBOutlet weak var attachmentList: NSCollectionView! private var attachmentsDirectoryWrapper : FileWrapper? { guard let fileWrappers = self.documentFileWrapper.fileWrappers else { NSLog("Attempting to access document's contents, but none found!") return nil } var attachmentsDirectoryWrapper = fileWrappers[NoteDocumentFileNames.AttachmentsDirectory.rawValue] if attachmentsDirectoryWrapper == nil { attachmentsDirectoryWrapper = FileWrapper(directoryWithFileWrappers: [:]) attachmentsDirectoryWrapper?.preferredFilename = NoteDocumentFileNames.AttachmentsDirectory.rawValue self.documentFileWrapper.addFileWrapper(attachmentsDirectoryWrapper!) } return attachmentsDirectoryWrapper } dynamic var attachedFiles : [FileWrapper]? { if let attachmentsFileWrappers = self.attachmentsDirectoryWrapper?.fileWrappers { let attachments = Array(attachmentsFileWrappers.values) return attachments } else { return nil } } var popover : NSPopover? override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(_ windowController: NSWindowController) { self.attachmentList.register(forDraggedTypes: [NSURLPboardType]) } func addAttachmentAtURL(url: NSURL) throws { guard attachmentsDirectoryWrapper != nil else { throw err(.CannotAccessAttachments) } self.willChangeValue(forKey: "attachedFiles") let newAttachment = try FileWrapper(url: url as URL, options: FileWrapper.ReadingOptions.immediate) attachmentsDirectoryWrapper?.addFileWrapper(newAttachment) self.updateChangeCount(.changeDone) self.didChangeValue(forKey: "attachedFiles") } func iconImageDataWithSize (size: CGSize) -> NSData? { let image = NSImage(size: size) image.lockFocus() let entireImageRect = CGRect(origin: CGPoint.zero, size: size) // Fill the background with white let backgroundRect = NSBezierPath(rect: entireImageRect) NSColor.white.setFill() backgroundRect.fill() if (self.attachedFiles?.count)! >= 1 { // Render our text, and the first attachment let attachmentImage = self.attachedFiles?[0].thumbnailImage let (firstHalf, secondHalf) = entireImageRect.divided(atDistance: entireImageRect.size.height / 2.0, from: CGRectEdge.minYEdge) // CGRectDivide(entireImageRect, // &firstHalf, // &secondHalf, // entireImageRect.size.height / 2.0, // CGRectEdge.minYEdge) // Unfortunately, CGRectDivide is deprecated in swift 3. Had to use the method above to get desired result. self.text.draw(in: firstHalf) attachmentImage?.draw(in: secondHalf) } else { // Just render our text self.text.draw(in: entireImageRect) } let bitmapRepresentation = NSBitmapImageRep(focusedViewRect: entireImageRect) image.unlockFocus() // Convert it to a PNG return bitmapRepresentation?.representation(using: NSPNGFileType, properties: [:]) as NSData? } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String? { // Returns the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead. return "Document" } override func data(ofType typeName: String) throws -> Data { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } override func read(from data: Data, ofType typeName: String) throws { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded. throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } override func fileWrapper(ofType typeName: String) throws -> FileWrapper { let textRTFData = try self.text.data(from: NSRange(0..<self.text.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType]) // If the current docmuent file wrapper already contains a // text file, remove it - we'll replace it with a new one if let oldTextFileWrapper = self.documentFileWrapper.fileWrappers?[NoteDocumentFileNames.TextFile.rawValue] { self.documentFileWrapper.removeFileWrapper(oldTextFileWrapper) } // Create the Quicklook Folder let thumbnailImageData = self.iconImageDataWithSize(size: CGSize(width: 512, height: 512))! let thumbnailWrapper = FileWrapper(regularFileWithContents: thumbnailImageData as Data) let quicklookPreview = FileWrapper(regularFileWithContents: textRTFData) let quicklookFolderFileWrapper = FileWrapper(directoryWithFileWrappers: [NoteDocumentFileNames.QuickLookTextFile.rawValue:quicklookPreview, NoteDocumentFileNames.QuickLookThumbnail.rawValue:thumbnailWrapper]) quicklookFolderFileWrapper.preferredFilename = NoteDocumentFileNames.QuickLookDirectory.rawValue // Remove the old Quicklook folder if it existed if let oldQuickLookFolder = self.documentFileWrapper.fileWrappers?[NoteDocumentFileNames.QuickLookDirectory.rawValue] { self.documentFileWrapper.removeFileWrapper(oldQuickLookFolder) } // Add the new Quicklook folder self.documentFileWrapper.addFileWrapper(quicklookFolderFileWrapper) // Save the text data into the file self.documentFileWrapper.addRegularFile(withContents: textRTFData, preferredFilename: NoteDocumentFileNames.TextFile.rawValue) // Return the main document's file wrapper - this is what will // be saved on disk return self.documentFileWrapper } override func read(from fileWrapper: FileWrapper, ofType typeName: String) throws { // Ensure that we have additional file wrappers in this file wrapper guard let fileWrappers = fileWrapper.fileWrappers else { throw err(.CannotLoadFileWrappers) } // Ensure that we can access the document text guard let documentTextData = fileWrappers[NoteDocumentFileNames.TextFile.rawValue]?.regularFileContents else { throw err(.CannotLoadText) } // Load the text data as RTF guard let documentText = NSAttributedString(rtf: documentTextData, documentAttributes: nil) else { throw err(.CannotLoadText) } // Keep the text in memory self.documentFileWrapper = fileWrapper self.text = documentText } }
gpl-3.0
a9d075df5b590c1e0caff7b99771a579
32.877462
192
0.72594
4.369743
false
false
false
false
davedelong/DDMathParser
MathParser/Tests/MathParserTests/RewriterTests.swift
1
3687
// // RewriterTests.swift // DDMathParser // // Created by Dave DeLong on 8/27/15. // // import XCTest import MathParser func TestRewrite(_ original: String, expected: String, substitutions: Substitutions = [:], evaluator: Evaluator = Evaluator.default, rewriter: ExpressionRewriter = ExpressionRewriter.default, file: StaticString = #file, line: UInt = #line) { guard let originalE = XCTAssertNoThrows(try Expression(string: original), file: file, line: line) else { return } guard let expectedE = XCTAssertNoThrows(try Expression(string: expected), file: file, line: line) else { return } let rewritten = rewriter.rewriteExpression(originalE, substitutions: substitutions, evaluator: evaluator) XCTAssertEqual(rewritten, expectedE, file: file, line: line) // Also test that the convenience functions produces the same result. let convenienceRewritten = originalE.rewrite(substitutions, rewriter: rewriter, evaluator: evaluator) XCTAssertEqual(convenienceRewritten, rewritten) } class RewriterTests: XCTestCase { func testDefaultRules() { TestRewrite("0 + $foo", expected: "$foo") TestRewrite("$foo + 0", expected: "$foo") TestRewrite("$foo + $foo", expected: "$foo * 2") TestRewrite("$foo - $foo", expected: "0") TestRewrite("1 * $foo", expected: "$foo") TestRewrite("$foo * 1", expected: "$foo") TestRewrite("$foo * $foo", expected: "$foo ** 2") TestRewrite("__num1 * __var1", expected: "__var1 * __num1") TestRewrite("0 * $foo", expected: "0") TestRewrite("$foo * 0", expected: "0") TestRewrite("--$foo", expected: "$foo") TestRewrite("abs(-$foo)", expected: "abs($foo)") TestRewrite("exp($foo) * exp($bar)", expected: "exp($foo + $bar)") TestRewrite("($foo ** $baz) * ($bar ** $baz)", expected: "($foo * $bar) ** $baz") TestRewrite("$foo ** 0", expected: "1") TestRewrite("$foo ** 1", expected: "$foo") TestRewrite("sqrt($foo ** 2)", expected: "abs($foo)") TestRewrite("dtor(rtod($foo))", expected: "$foo") TestRewrite("rtod(dtor($foo))", expected: "$foo") //division TestRewrite("$foo / $foo", expected: "1", substitutions: ["foo": 1]) TestRewrite("$foo / $foo", expected: "$foo / $foo") TestRewrite("($foo * $bar) / $bar", expected: "$foo", substitutions: ["bar": 1]) TestRewrite("($foo * $bar) / $bar", expected: "($foo * $bar) / $bar") TestRewrite("($bar * $foo) / $bar", expected: "$foo", substitutions: ["bar": 1]) TestRewrite("($bar * $foo) / $bar", expected: "($bar * $foo) / $bar") TestRewrite("$bar / ($bar * $foo)", expected: "1/$foo", substitutions: ["bar": 1]) TestRewrite("$bar / ($bar * $foo)", expected: "$bar / ($bar * $foo)") TestRewrite("$bar / ($foo * $bar)", expected: "1/$foo", substitutions: ["bar": 1]) TestRewrite("$bar / ($foo * $bar)", expected: "$bar / ($foo * $bar)") //exponents and roots TestRewrite("nthroot(pow($foo, $bar), $bar)", expected: "abs($foo)", substitutions: ["bar": 2]) TestRewrite("nthroot(pow($foo, $bar), $bar)", expected: "nthroot(pow($foo, $bar), $bar)") TestRewrite("nthroot(pow($foo, $bar), $bar)", expected: "$foo", substitutions: ["bar": 1]) TestRewrite("nthroot(pow($foo, $bar), $bar)", expected: "nthroot(pow($foo, $bar), $bar)") TestRewrite("abs($foo)", expected: "1", substitutions: ["foo": 1]) TestRewrite("abs($foo)", expected: "abs($foo)") } }
mit
16f1f230082a1106ab47d9f74d766782
44.518519
241
0.574722
3.804954
false
true
false
false
notbenoit/tvOS-Twitch
Code/Common/Networking/Responses/Channel.swift
1
1785
// Copyright (c) 2015 Benoit Layer // // 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 struct Channel: Codable { let id: Int let mature: Bool? let status: String? let displayName: String let gameName: String? let channelName: String enum CodingKeys: String, CodingKey { case id = "_id" case mature case status case displayName = "display_name" case gameName = "game" case channelName = "name" } } extension Channel: CustomStringConvertible { internal var description: String { return channelName + (gameName.map { "on " + $0 } ?? "") } } extension Channel: Hashable { var hashValue: Int { return id } } extension Channel: Equatable { } func == (lhs: Channel, rhs: Channel) -> Bool { return lhs.id == rhs.id }
bsd-3-clause
944b2de1687553ab23bb101124ff0dab
30.875
80
0.735014
4.02027
false
false
false
false
angelvasa/AVLighterStickyHeaderView
AVLighterStickyHeaderView/AVLighterStickyHeaderView.swift
1
1884
// // AVLighterStickyHeaderView.swift // AVLighterStickyHeaderView // // Created by Angel Vasa on 13/04/16. // Copyright © 2016 Angel Vasa. All rights reserved. // import UIKit @IBDesignable open class AVLighterStickyHeaderView: UIView { @IBInspectable var minimumHeight: CGFloat = 64 typealias progressValueHandler = (CGFloat) -> () @IBOutlet weak var scrollView: UIScrollView? var gProgressValue: progressValueHandler? override open func willMove(toSuperview newSuperview: UIView?) { self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) self.scrollView?.contentInset = UIEdgeInsetsMake((self.scrollView?.contentInset.top)!, 0, 0, 0) self.scrollView?.scrollIndicatorInsets = (self.scrollView?.contentInset)!; } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { updateView(((change![.newKey] as AnyObject).cgPointValue)!) } var currentOffset: CGPoint? func updateView(_ offset: CGPoint) { currentOffset = offset if (currentOffset!.y > -minimumHeight){ currentOffset = CGPoint(x: currentOffset!.x, y: -minimumHeight) } self.frame.origin.y = -currentOffset!.y-(self.scrollView?.contentInset.top)! let distance: CGFloat = (self.scrollView?.contentInset.top)! - minimumHeight let progressInverse: CGFloat = (currentOffset!.y + (self.scrollView?.contentInset.top)!) / distance let progress: CGFloat = 1 - progressInverse gProgressValue!(progress) } func getProgressValue(_ progressValue: @escaping progressValueHandler) { gProgressValue = progressValue } }
mit
1e3686d8e5989d45cb4d6813dbce55eb
32.035088
156
0.673394
5.048257
false
false
false
false
Bunn/macGist
macGist/PasteboardHelper.swift
1
1712
// // PasteboardHelper.swift // macGist // // Created by Fernando Bunn on 17/06/17. // Copyright © 2017 Fernando Bunn. All rights reserved. // import Foundation import AppKit struct PasteboardHelper { func getPasteboardString() -> String? { let pasteboard = NSPasteboard.general if let copiedItems = pasteboard.readObjects(forClasses: [NSString.self], options: nil) { for item in copiedItems { if let stringItem = item as? String { return stringItem; } } } return nil } /* This only seems to work for Xcode pasted items, since the app that creates the paste can add tags as it see fit there's no standardize way to get an extension from a pasteboard */ func getFileExtension() -> String { let xcodeExtensionType = "DVTSourceTextViewLanguagePboardType" guard let data = NSPasteboard.general.data(forType: NSPasteboard.PasteboardType(rawValue: xcodeExtensionType)), let string = String(data: data, encoding: .utf8), let fileExtension = string.components(separatedBy: ".").last else { return "file" } //Gists doesn't highlight items with some file extensions let types = ["Objective-C-Plus-Plus" : "mm", "Objective-C" : "m"] if let newExtension = types[fileExtension] { return newExtension } return fileExtension } func save(string: String) { let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects([string as NSPasteboardWriting]) } }
mit
a4e3d82ddbfeaf6df3587394aca8faa4
31.283019
119
0.611338
4.902579
false
false
false
false
snit-ram/MultiPageController
MultiPageController/Source/MultiPageController.swift
1
14521
// // MultiPageController.swift // MultiPageController // // Created by Rafael Martins on 10/2/16. // Copyright © 2016 Snit. All rights reserved. // import UIKit let TransformIdentity: CATransform3D = { var identity = CATransform3DIdentity identity.m34 = 1.0 / 200 return identity }() struct LayoutAttributes { var frame: CGRect var alpha: CGFloat var transform3D: CATransform3D var transformRatio: CGFloat var isHidden: Bool } public protocol MultiPageControllerDataSource : class { func numberOfItems(in: MultiPageController) -> Int func multiPageController(_ multiPageController: MultiPageController, viewControllerAt index: Int) -> UIViewController func multiPageController(_ multiPageController: MultiPageController, previewViewAt index: Int) -> UIView } enum State { case expanded case collapsed case transitioning } open class MultiPageController: UIViewController { var viewControllerIndex = 0 open var sideScale: CGFloat = 0.6 open var sideAlpha: CGFloat = 0.8 open var autoSelectionDelay: TimeInterval = 0.6 public weak var dataSource: MultiPageControllerDataSource! var pageViewControllers : [UIViewController?] = [] var previewViews : [UIView] = [] var containerViews : [UIView] = [] var state = State.expanded { didSet { if state == .expanded { timer?.invalidate() } } } func createViewController(at index: Int) -> UIViewController { if let controller = pageViewControllers[index] { return controller } let container = containerViews[index] let viewController = dataSource.multiPageController(self, viewControllerAt: index) pageViewControllers[index] = viewController addChildViewController(viewController) container.addSubview(viewController.view) viewController.view.translatesAutoresizingMaskIntoConstraints = false viewController.view.topAnchor.constraint(equalTo: container.topAnchor).isActive = true viewController.view.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true viewController.view.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true viewController.view.leftAnchor.constraint(equalTo: container.leftAnchor).isActive = true return viewController } private var itemCount = 0 let scrollView : ScrollView = { let scrollView = ScrollView() scrollView.bounces = true scrollView.alwaysBounceHorizontal = true scrollView.scrollsToTop = false scrollView.isDirectionalLockEnabled = true scrollView.showsVerticalScrollIndicator = false return scrollView }() override open func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) scrollView.decelerationRate = UIScrollViewDecelerationRateFast scrollView.delegate = self } private func reset() { itemCount = 0 scrollView.subviews.forEach { $0.removeFromSuperview() } pageViewControllers = [] viewControllerIndex = 0 } var itemSize : CGSize { return itemSize(in: view.bounds) } func itemSize(in containerRect: CGRect) -> CGSize { let side = containerRect.width / 2 return CGSize(width: side, height: side) } var sideItemSize : CGSize { return itemSize.applying(CGAffineTransform(scaleX: sideScale, y: sideScale)) } var spacing : CGFloat { return 0 } var visibleRect : CGRect { return CGRect(origin: scrollView.contentOffset, size: scrollView.bounds.size) } func layoutAttributes(forIndex index: Int) -> LayoutAttributes { let visibleCenter = visibleRect.center let maxDistance = view.bounds.width / 2 let size = itemSize let frame = CGRect( origin: CGPoint(x: itemSize.width / 2 + itemSize.width * CGFloat(index), y: view.bounds.midY - size.height / 2), size: size ) let distance = min(abs(frame.center.x - visibleCenter.x), maxDistance) let ratio = 1 - (distance / maxDistance) let scale = sideScale + (1 - sideScale) * ratio return LayoutAttributes( frame: frame, alpha: sideAlpha + (1 - sideAlpha) * ratio, transform3D: CATransform3DScale(TransformIdentity, scale, scale, 1.0), transformRatio: ratio, isHidden: false ) } func containerLayoutAttributes(forIndex index: Int) -> LayoutAttributes { var attributes = layoutAttributes(forIndex: index) attributes.frame = CGRect(center: attributes.frame.center, size: view.bounds.size) switch state { case .collapsed: attributes.isHidden = true case .expanded, .transitioning: attributes.isHidden = index != viewControllerIndex } let targetScaleX = sideItemSize.width / attributes.frame.width let targetScaleY = sideItemSize.height / attributes.frame.height let scaleX = targetScaleX + (1 - targetScaleX) * attributes.transformRatio let scaleY = targetScaleY + (1 - targetScaleY) * attributes.transformRatio attributes.alpha = 1 * attributes.transformRatio attributes.transform3D = CATransform3DScale(TransformIdentity, scaleX, scaleY, 1) return attributes } @objc fileprivate func tapPreview(_ recognizer: UIGestureRecognizer) { guard let tappedView = recognizer.view, let index = previewViews.index(of: tappedView) else { return } expand(at: index) } open func reloadData() { reset() itemCount = dataSource.numberOfItems(in: self) scrollView.subviews.forEach { $0.removeFromSuperview() } scrollView.contentInset = .zero pageViewControllers = Array(repeating: nil, count: itemCount) scrollView.contentOffset = .zero (0..<itemCount).forEach { index in let previewView = UIView() let recognizer = TapRecognizer() recognizer.addTarget(self, action: #selector(tapPreview(_:))) previewView.isUserInteractionEnabled = true previewView.addGestureRecognizer(recognizer) previewViews.append(previewView) let previewContent = dataSource.multiPageController(self, previewViewAt: index) previewView.addSubview(previewContent) previewContent.translatesAutoresizingMaskIntoConstraints = false previewContent.topAnchor.constraint(equalTo: previewView.topAnchor).isActive = true previewContent.rightAnchor.constraint(equalTo: previewView.rightAnchor).isActive = true previewContent.bottomAnchor.constraint(equalTo: previewView.bottomAnchor).isActive = true previewContent.leftAnchor.constraint(equalTo: previewView.leftAnchor).isActive = true let containerView = UIView() containerView.backgroundColor = .white containerViews.append(containerView) scrollView.addSubview(previewView) } containerViews.forEach { scrollView.addSubview($0) } if itemCount > 0 { let controller = createViewController(at: viewControllerIndex) controller.didMove(toParentViewController: self) } } func apply(attributes: LayoutAttributes, to view: UIView){ view.alpha = attributes.alpha view.layer.transform = attributes.transform3D view.isHidden = attributes.isHidden } func applyTransform(_ index: Int){ apply(attributes: layoutAttributes(forIndex: index), to: previewViews[index]) } func applyContainerTransform(_ index: Int){ if state == .transitioning { return } let attributes = containerLayoutAttributes(forIndex: index) let targetView = containerViews[index] apply(attributes: attributes, to: targetView) if index == viewControllerIndex && attributes.transformRatio < 0.6 && state == .expanded { var finalAttributes = attributes finalAttributes.alpha = 0 let targetScaleX = sideItemSize.width / attributes.frame.width let targetScaleY = sideItemSize.height / attributes.frame.height finalAttributes.transform3D = CATransform3DScale(TransformIdentity, targetScaleX, targetScaleY, 1) finalAttributes.isHidden = false state = .transitioning UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: [], animations: { self.apply(attributes: finalAttributes, to: targetView) }, completion: { completed in self.state = .collapsed }) } } func visibleRange() -> Range<Int> { let midItem = max(Int(floor((scrollView.contentOffset.x + itemSize.width / 2) / itemSize.width)), 0) return max(midItem - 1, 0)..<min(midItem + 2, previewViews.count) } func visibleViews() -> ArraySlice<UIView> { return previewViews[visibleRange()] } func transformVisibleItems(){ let midItem = max(Int(floor((scrollView.contentOffset.x + itemSize.width / 2) / itemSize.width)), 0) let affectedRange = max(midItem - 1, 0)..<min(midItem + 2, itemCount) affectedRange.forEach(applyTransform) previewViews.indices.forEach(applyContainerTransform) } func contentOffset(for index: Int, in containerRect: CGRect) -> CGPoint { return CGPoint(x: CGFloat(index) * itemSize(in: containerRect).width, y: 0) } func contentOffset(for index: Int) -> CGPoint { return contentOffset(for: index, in: view.bounds) } func contentSize(in containerRect: CGRect) -> CGSize { return CGSize(width: (itemSize(in: containerRect).width) * CGFloat(itemCount + 1), height: containerRect.height) } var contentSize : CGSize { return contentSize(in: view.bounds) } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() scrollView.frame = view.bounds scrollView.contentSize = contentSize scrollView.setContentOffset(contentOffset(for: viewControllerIndex), animated: false) previewViews.enumerated().forEach { (index, view) in let attributes = layoutAttributes(forIndex: index) view.layer.transform = CATransform3DIdentity view.frame = attributes.frame view.center = attributes.frame.center } containerViews.enumerated().forEach { (index, view) in let attributes = containerLayoutAttributes(forIndex: index) view.layer.transform = CATransform3DIdentity view.frame = attributes.frame view.center = attributes.frame.center } previewViews.indices.forEach(applyTransform) containerViews.indices.forEach(applyContainerTransform) } var timer: Timer? open func expand(at index: Int){ // makes sure we stop scrolling when expanding scrollView.panGestureRecognizer.isEnabled = false scrollView.panGestureRecognizer.isEnabled = true let currentContentOffset = scrollView.contentOffset let targetContentOffset = CGPoint(x: CGFloat(index) * self.itemSize.width, y: 0) timer?.invalidate() viewControllerIndex = index scrollView.setContentOffset(currentContentOffset, animated: false) let targetView = containerViews[index] var finalAttributes = containerLayoutAttributes(forIndex: index) finalAttributes.isHidden = false finalAttributes.alpha = 1 finalAttributes.transform3D = TransformIdentity var attributes = finalAttributes let scaleX = itemSize.width / finalAttributes.frame.width let scaleY = itemSize.height / finalAttributes.frame.height attributes.transform3D = CATransform3DScale(TransformIdentity, scaleX, scaleY, 1) attributes.isHidden = false attributes.alpha = 0 apply(attributes: attributes, to: targetView) let isNewViewController = pageViewControllers[index] == nil let viewController = createViewController(at: index) state = .transitioning UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: [], animations: { self.scrollView.setContentOffset(targetContentOffset, animated: false) self.apply(attributes: finalAttributes, to: targetView) }, completion: { completed in self.state = .expanded if isNewViewController { viewController.didMove(toParentViewController: self) } }) } } extension MultiPageController : UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { timer?.invalidate() transformVisibleItems() } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var position = targetContentOffset.pointee position.x = round(position.x / itemSize.width) * itemSize.width targetContentOffset.pointee = position } @objc private func handleTimer(_ timer: Timer){ guard let index = timer.userInfo as? Int else { return } if state == .collapsed { expand(at: index) } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let index = Int(round(scrollView.contentOffset.x / itemSize.width)) timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: autoSelectionDelay, target: self, selector: #selector(handleTimer(_:)), userInfo: index, repeats: false) } }
mit
057b09c778282e4d591eaf92ff26e9d9
36.040816
155
0.644421
5.334313
false
false
false
false
TechnologySpeaks/smile-for-life
smile-for-life/UserDefaultsSet.swift
1
1404
// // UserDefaultsSet.swift // smile-for-life // // Created by Lisa Swanson on 9/4/16. // Copyright © 2016 Technology Speaks. All rights reserved. // import Foundation class UserDefaultsSet { var currentUserCalendarDefaults = User() { didSet { print("i am in currentUserDidSet") setCalendarUserDefaults(currentUserCalendarDefaults) } } var setCurrentUser = User() { didSet { setCalendarUserDefaults(setCurrentUser) } } init() { self.currentUserCalendarDefaults = getCalendarUserDefaults() } fileprivate func getCalendarUserDefaults() -> User { let user = User() let defaults = UserDefaults.standard if let userArray = defaults.dictionary(forKey: "currentUser") { let userDict = userArray as NSDictionary let id = userDict["userId"] as? String user.id = Int32(id!) user.name = userDict["userName"] as? String // for (key, value) in userDict { // print("&&&&&&&&&&&&&") // print(key) // print(value) // } } return user } fileprivate func setCalendarUserDefaults(_ userDefault: User) { // print("I am in setDefaults") // print(userDefault) let defaults = UserDefaults.standard let userDict: NSDictionary = ["userName" : userDefault.name!, "userId" : String(userDefault.id!)] defaults.set( userDict, forKey: "currentUser") } }
mit
06742dce93d9266e2598507a46a443ec
23.189655
101
0.641483
4.150888
false
false
false
false
saagarjha/iina
iina/ControlBarView.swift
3
2341
// // ControlBarView.swift // iina // // Created by lhc on 16/7/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa class ControlBarView: NSVisualEffectView { @IBOutlet weak var xConstraint: NSLayoutConstraint! @IBOutlet weak var yConstraint: NSLayoutConstraint! var mousePosRelatedToView: CGPoint? var isDragging: Bool = false private var isAlignFeedbackSent = false override func awakeFromNib() { self.roundCorners(withRadius: 6) self.translatesAutoresizingMaskIntoConstraints = false } override func mouseDown(with event: NSEvent) { mousePosRelatedToView = NSEvent.mouseLocation mousePosRelatedToView!.x -= frame.origin.x mousePosRelatedToView!.y -= frame.origin.y isAlignFeedbackSent = abs(frame.origin.x - (window!.frame.width - frame.width) / 2) <= 5 isDragging = true } override func mouseDragged(with event: NSEvent) { guard let mousePos = mousePosRelatedToView, let windowFrame = window?.frame else { return } let currentLocation = NSEvent.mouseLocation var newOrigin = CGPoint( x: currentLocation.x - mousePos.x, y: currentLocation.y - mousePos.y ) // stick to center if Preference.bool(for: .controlBarStickToCenter) { let xPosWhenCenter = (windowFrame.width - frame.width) / 2 if abs(newOrigin.x - xPosWhenCenter) <= 5 { newOrigin.x = xPosWhenCenter if !isAlignFeedbackSent { NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .default) isAlignFeedbackSent = true } } else { isAlignFeedbackSent = false } } // bound to window frame let xMax = windowFrame.width - frame.width - 10 let yMax = windowFrame.height - frame.height - 25 newOrigin = newOrigin.constrained(to: NSRect(x: 10, y: 0, width: xMax, height: yMax)) // apply position xConstraint.constant = newOrigin.x + frame.width / 2 yConstraint.constant = newOrigin.y } override func mouseUp(with event: NSEvent) { isDragging = false guard let windowFrame = window?.frame else { return } // save final position Preference.set(xConstraint.constant / windowFrame.width, for: .controlBarPositionHorizontal) Preference.set(yConstraint.constant / windowFrame.height, for: .controlBarPositionVertical) } }
gpl-3.0
1d2573aed4ff057047e316041d1bfea0
31.5
97
0.701282
4.201077
false
false
false
false
milseman/swift
benchmark/single-source/Phonebook.swift
21
2429
//===--- Phonebook.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is based on util/benchmarks/Phonebook, with modifications // for performance measuring. import TestsUtils var words = [ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony", "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott", "Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin", "Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter", "Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl", "Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy", "Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce", "Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan", "Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Craig" ] // This is a phone book record. struct Record : Comparable { var first: String var last: String init(_ first_ : String,_ last_ : String) { first = first_ last = last_ } } func ==(lhs: Record, rhs: Record) -> Bool { return lhs.last == rhs.last && lhs.first == rhs.first } func <(lhs: Record, rhs: Record) -> Bool { if lhs.last < rhs.last { return true } if lhs.last > rhs.last { return false } if lhs.first < rhs.first { return true } return false } @inline(never) public func run_Phonebook(_ N: Int) { // The list of names in the phonebook. var Names : [Record] = [] for first in words { for last in words { Names.append(Record(first, last)) } } for _ in 1...N { var t = Names t.sort() } }
apache-2.0
fe26303b4b25454da5a41b30e565c75c
31.386667
81
0.579251
3.225764
false
false
false
false
milseman/swift
test/Reflection/typeref_decoding_imported.swift
12
3791
// RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension -I %S/Inputs // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // ... now, test single-frontend mode with multi-threaded LLVM emission: // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension -I %S/Inputs -whole-module-optimization -num-threads 2 // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // CHECK-32: FIELDS: // CHECK-32: ======= // CHECK-32: TypesToReflect.HasCTypes // CHECK-32: ------------------------ // CHECK-32: mcs: __C.MyCStruct // CHECK-32: (struct __C.MyCStruct) // CHECK-32: mce: __C.MyCEnum // CHECK-32: (struct __C.MyCEnum) // CHECK-32: TypesToReflect.AlsoHasCTypes // CHECK-32: ---------------------------- // CHECK-32: mcu: __C.MyCUnion // CHECK-32: (struct __C.MyCUnion) // CHECK-32: mcsbf: __C.MyCStructWithBitfields // CHECK-32: (struct __C.MyCStructWithBitfields) // CHECK-32: ASSOCIATED TYPES: // CHECK-32: ================= // CHECK-32: BUILTIN TYPES: // CHECK-32: ============== // CHECK-32-LABEL: - __C.MyCStruct: // CHECK-32: Size: 12 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 12 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32-LABEL: - __C.MyCEnum: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32-LABEL: - __C.MyCUnion: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-i386-LABEL: - __C.MyCStructWithBitfields: // CHECK-i386: Size: 4 // CHECK-i386: Alignment: 4 // CHECK-i386: Stride: 4 // CHECK-i386: NumExtraInhabitants: 0 // CHECK-arm-LABEL: - __C.MyCStructWithBitfields: // CHECK-arm: Size: 2 // CHECK-arm: Alignment: 1 // CHECK-arm: Stride: 2 // CHECK-arm: NumExtraInhabitants: 0 // CHECK-32: CAPTURE DESCRIPTORS: // CHECK-32: ==================== // CHECK-64: FIELDS: // CHECK-64: ======= // CHECK-64: TypesToReflect.HasCTypes // CHECK-64: ------------------------ // CHECK-64: mcs: __C.MyCStruct // CHECK-64: (struct __C.MyCStruct) // CHECK-64: mce: __C.MyCEnum // CHECK-64: (struct __C.MyCEnum) // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: TypesToReflect.AlsoHasCTypes // CHECK-64: ---------------------------- // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: mcsbf: __C.MyCStructWithBitfields // CHECK-64: (struct __C.MyCStructWithBitfields) // CHECK-64: ASSOCIATED TYPES: // CHECK-64: ================= // CHECK-64: BUILTIN TYPES: // CHECK-64: ============== // CHECK-64-LABEL: - __C.MyCStruct: // CHECK-64: Size: 24 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 24 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCEnum: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCUnion: // CHECK-64: Size: 8 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 8 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64-LABEL: - __C.MyCStructWithBitfields: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: CAPTURE DESCRIPTORS: // CHECK-64: ====================
apache-2.0
fb8dce524217b1c0529d0cd21c37d6dd
29.087302
268
0.646531
3.135649
false
false
false
false
jingyu982887078/daily-of-programmer
WeiBo/WeiBo/Classes/View/Main/WBMainViewController.swift
1
3492
// // WBMainViewController.swift // WeiBo // // Created by wangjingyu on 2017/5/4. // Copyright © 2017年 wangjingyu. All rights reserved. // import UIKit class WBMainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupChildController() setcomposeButton() } /// 设备方向支持,如果播放视屏,通常是madal展现的 override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } // MARK: -- 监听方法 /// 监听方法 // @objc 允许这个函数在运行时通过oc的消息机制被调用 @objc fileprivate func composeStatus() { print("撰写微博") } /// 撰写按钮 lazy var composeButton: UIButton = UIButton.cz_imageButton( "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button") } ///类似于oc中的分类,不能添加属性,可以添加方法,可以拆分代码块 //便于代码的维护,慢慢的体会 // MARK: - 添加子控制器 extension WBMainViewController { /// 添加撰写按钮 func setcomposeButton() { tabBar.addSubview(self.composeButton) let count = CGFloat(childViewControllers.count) let w = tabBar.bounds.width / count - 1 composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0) composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside) } func setupChildController() { //从本地读取数据 guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),let data = NSData(contentsOfFile: path), let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : AnyObject]] else { return } /// 创建字典的数组,用来®®设置控制器的相关的属性 var arrayM = [UIViewController]() for dict in array! { arrayM.append(controllers(dict: dict)) } viewControllers = arrayM; } /// 添加一个子控制器 ///字典里面有title,imageName,clsName /// - Returns: uiviewController func controllers(dict:[String : AnyObject]) -> UIViewController { // 1.取得字典的内容 guard let title = dict["title"] as? String, let imageName = dict["imageName"] as? String, let clsName = dict["clsName"] as? String, let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type, let visitorInfo = dict["visitorInfo"] as? [String:String] else { return UIViewController() } //2.创建视图控制器 let vc = cls.init() vc.title = title vc.visitorInfo = visitorInfo //3.shezhituxiang vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName) vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal) //4.设置标题的颜色 vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange ], for: .selected) //添加导航栏控制器 let nav = WBNavigationController(rootViewController: vc) return nav } }
mit
998dcef5a4f7877da4ae12964e53bc57
26.919643
125
0.597697
4.429178
false
false
false
false
pkc456/Roastbook
Roastbook/Roastbook/Business Layer/FeedBusinessLayer.swift
1
1365
// // FeedBusinessLayer.swift // Roastbook // // Created by Pradeep Choudhary on 4/8/17. // Copyright © 2017 Pardeep chaudhary. All rights reserved. // import Foundation class FeedBusinessLayer: NSObject { class var sharedInstance: FeedBusinessLayer { struct Static { static let instance: FeedBusinessLayer = FeedBusinessLayer() } return Static.instance } func parseArrayJsonData(data: NSArray) -> [Feed] { let modelObject = Feed.modelsFromDictionaryArray(array: data) return modelObject } //Methods to get dummy data func getFeedInformationDataArray() -> [Feed] { let feedDictionary = getFeedListData() let arrayOfMusicData = Feed.modelsFromDictionaryArray(array: [feedDictionary]) return arrayOfMusicData } private func getFeedListData() -> NSMutableDictionary{ let data : NSMutableDictionary = NSMutableDictionary() data.setValue("I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you I am rockstar. I am rockstar. I am rockstar What are your views. I am waiting. Slide across the down button. Show me! Can you. Testing", forKey: KKEY_FEED) data.setValue("Pardeep", forKey: KKEY_FEED_NAME) return data } }
mit
20e9eb2bde2253694757de5d8b46d22d
33.1
304
0.673754
4.385852
false
false
false
false
rustedivan/tapmap
tapmap/Persistence/LocalProfile.swift
1
1454
// // LocalProfile.swift // tapmap // // Created by Ivan Milles on 2020-07-11. // Copyright © 2020 Wildbrain. All rights reserved. // import Foundation var persistentProfileUrl: URL { try! FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("\(UserState.visitedPlacesKey).plist") } func saveVisitsToDevice(_ hashes: Set<RegionHash>, as key: String) { var url = persistentProfileUrl // Expect tapmap to run offline for long periods, so don't allow iOS to offload the savefile to iCloud // $ I think this is sketchy? var dontOffloadUserstate = URLResourceValues() dontOffloadUserstate.isExcludedFromBackup = true try? url.setResourceValues(dontOffloadUserstate) let encoder = NSKeyedArchiver(requiringSecureCoding: false) encoder.encode(10, forKey: "version") encoder.encode(Date(), forKey: "archive-timestamp") encoder.encode(hashes, forKey: key) let chunk = encoder.encodedData do { try chunk.write(to: url, options: .atomic) } catch (let error) { print("Could not persist to profile at \(url): \(error.localizedDescription)") } } func loadVisitsFromDevice(key: String) -> Set<RegionHash>? { if let profile = NSData(contentsOf: persistentProfileUrl) as Data? { if let persistedState = try? NSKeyedUnarchiver(forReadingFrom: profile) { return persistedState.decodeObject(forKey: key) as? Set<RegionHash> } } return nil }
mit
3f383a9fa98799801dc5b431e83ad63a
31.288889
103
0.748796
3.65995
false
false
false
false
duliodenis/buzzlr
buzzlr/Frameworks/OAuthSwift/OAuthSwift/OAuthSwiftCredential.swift
19
2511
// // OAuthSwiftCredential.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public class OAuthSwiftCredential: NSObject, NSCoding { var consumer_key: String = String() var consumer_secret: String = String() public var oauth_token: String = String() public var oauth_token_secret: String = String() var oauth_verifier: String = String() public var oauth2 = false override init(){ } public init(consumer_key: String, consumer_secret: String){ self.consumer_key = consumer_key self.consumer_secret = consumer_secret } public init(oauth_token: String, oauth_token_secret: String){ self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret } private struct CodingKeys { static let base = NSBundle.mainBundle().bundleIdentifier! + "." static let consumerKey = base + "comsumer_key" static let consumerSecret = base + "consumer_secret" static let oauthToken = base + "oauth_token" static let oauthTokenSecret = base + "oauth_token_secret" static let oauthVerifier = base + "oauth_verifier" } // Cannot declare a required initializer within an extension. // extension OAuthSwiftCredential: NSCoding { public required convenience init(coder decoder: NSCoder) { self.init() self.consumer_key = (decoder.decodeObjectForKey(CodingKeys.consumerKey) as? String) ?? String() self.consumer_secret = (decoder.decodeObjectForKey(CodingKeys.consumerSecret) as? String) ?? String() self.oauth_token = (decoder.decodeObjectForKey(CodingKeys.oauthToken) as? String) ?? String() self.oauth_token_secret = (decoder.decodeObjectForKey(CodingKeys.oauthTokenSecret) as? String) ?? String() self.oauth_verifier = (decoder.decodeObjectForKey(CodingKeys.oauthVerifier) as? String) ?? String() } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(self.consumer_key, forKey: CodingKeys.consumerKey) coder.encodeObject(self.consumer_secret, forKey: CodingKeys.consumerSecret) coder.encodeObject(self.oauth_token, forKey: CodingKeys.oauthToken) coder.encodeObject(self.oauth_token_secret, forKey: CodingKeys.oauthTokenSecret) coder.encodeObject(self.oauth_verifier, forKey: CodingKeys.oauthVerifier) } // } // End NSCoding extension }
mit
296b1fb6cbf1065261627fc525949e99
41.559322
114
0.688172
4.524324
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/Chat/ChatMessage.swift
1
1671
// // ChatMessage.swift // mclient // // Copyright © 2014 - 2019 Christopher Reitz. Licensed under the MIT license. // See LICENSE file in the project root for full license information. // import Foundation //import CoreLocation //import MessageKit private struct ImageMediaItem: MediaItem { var url: URL? var image: UIImage? var placeholderImage: UIImage var size: CGSize init(image: UIImage) { self.image = image self.size = CGSize(width: 240, height: 240) self.placeholderImage = UIImage() } } enum ChatMessageType: String { case inbox = "inbox" case outbox = "outbox" } struct ChatMessage: MessageType { var type: ChatMessageType var messageId: String var sender: Sender var subject: String var sentDate: Date var kind: MessageKind private init(type: ChatMessageType, kind: MessageKind, sender: Sender, subject: String, messageId: String, date: Date) { self.type = type self.kind = kind self.sender = sender self.subject = subject self.messageId = messageId self.sentDate = date } init(type: ChatMessageType, text: String, sender: Sender, subject: String, messageId: String, date: Date) { self.init(type: type, kind: .text(text), sender: sender, subject: subject, messageId: messageId, date: date) } init(type: ChatMessageType, image: UIImage, sender: Sender, subject: String, messageId: String, date: Date) { let mediaItem = ImageMediaItem(image: image) self.init(type: type, kind: .photo(mediaItem), sender: sender, subject: subject, messageId: messageId, date: date) } }
mit
7b468f9e45ba79f7b80e6a58f2a07b8c
26.833333
124
0.668263
4.103194
false
false
false
false
mengxiangyue/Swift-Design-Pattern-In-Chinese
Design_Pattern.playground/Pages/Prototype.xcplaygroundpage/Contents.swift
1
2757
/*: ### **Prototype Pattern** --- [回到列表](Index) 1. 定义:原型模式(Prototype Pattern):使用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式是一种对象创建型模式。。 2. 问题:例如下面例子中需要创建戈登计划乐队的三名成员。(真的不理解外国人下面这个破例子,有点强行解释的意思) 3. 解决方案:定义一个原型,然后通过 clone,创建一个新的实例,修改对应的属性。 4. 使用方法: 1. 定义一个原型类,提供 clone 方法。 2. 创建原型类,调用 clone 方法,获取新的实例,然后根据需要修改对应的属性。 5. 优点: (1) 当创建新的对象实例较为复杂时,使用原型模式可以简化对象的创建过程,通过复制一个已有实例可以提高新实例的创建效率。 (2) 扩展性较好,由于在原型模式中提供了抽象原型类,在客户端可以针对抽象原型类进行编程,而将具体原型类写在配置文件中,增加或减少产品类对原有系统都没有任何影响。 (3) 原型模式提供了简化的创建结构,工厂方法模式常常需要有一个与产品类等级结构相同的工厂等级结构,而原型模式就不需要这样,原型模式中产品的复制是通过封装在原型类中的克隆方法实现的,无须专门的工厂类来创建产品。 (4) 可以使用深克隆的方式保存对象的状态,使用原型模式将对象复制一份并将其状态保存起来,以便在需要的时候使用(如恢复到某一历史状态),可辅助实现撤销操作。 6. 缺点: (1) 需要为每一个类配备一个克隆方法,而且该克隆方法位于一个类的内部,当对已有的类进行改造时,需要修改源代码,违背了“开闭原则”。 (2) 在实现深克隆时需要编写较为复杂的代码,而且当对象之间存在多重的嵌套引用时,为了实现深克隆,每一层对象对应的类都必须支持深克隆,实现起来可能会比较麻烦。 */ import Foundation class ChungasRevengeDisplay { var name: String? let font: String init(font: String) { self.font = font } func clone() -> ChungasRevengeDisplay { return ChungasRevengeDisplay(font:self.font) } } /*: ### Usage */ // Gotan Project 乐队的三位成员,分别是Philippe Cohen Sola、Christophe Mueller以及 Eduardo Makaroff let Prototype = ChungasRevengeDisplay(font:"GotanProject") let Philippe = Prototype.clone() Philippe.name = "Philippe" let Christoph = Prototype.clone() Christoph.name = "Christoph" let Eduardo = Prototype.clone() Eduardo.name = "Eduardo"
mit
4bab7cfd93938c91ffe7a377deeb0bd2
26.711538
106
0.752255
2.03819
false
false
false
false
P0ed/Fx
Sources/Fx/Structs/Closures.swift
1
1020
/// Escaping inout value @propertyWrapper public struct IO<A> { public var get: () -> A public var set: (A) -> Void public var value: A { get { get() } nonmutating set { set(newValue) } } public init(get: @escaping () -> A, set: @escaping (A) -> Void) { self.get = get self.set = set } public var wrappedValue: A { get { value } set { value = newValue } } public init(_ io: IO) { self = io } public init(wrappedValue: A) { self = IO(copy: wrappedValue) } } /// Escaping readonly value @propertyWrapper public struct Readonly<A> { public var get: () -> A public var value: A { get { get() } } public init(get: @escaping () -> A) { self.get = get } public var wrappedValue: A { value } public init(_ readonly: Readonly) { self = readonly } public init(wrappedValue: A) { self = Self { wrappedValue } } } public extension IO { var readonly: Readonly<A> { Readonly(get: get) } init(copy value: A) { var copy = value self = IO(get: { copy }, set: { copy = $0 }) } }
mit
02c499f2a3ae3da49915e84b0123eb46
16.586207
70
0.609804
2.939481
false
false
false
false
mactive/rw-courses-note
advanced-swift-types-and-operations/TypesAndOps.playground/Pages/invalid-state-challenge.xcplaygroundpage/Contents.swift
1
2056
//: [Previous](@previous) import Foundation import struct CoreGraphics.CGFloat import struct CoreGraphics.CGPoint import struct CoreGraphics.CGSize import struct CoreGraphics.CGRect struct CGAngle { var radians: CGFloat } extension CGAngle { @inlinable init(degrees: CGFloat) { radians = degrees / 180.0 * CGFloat.pi } @inlinable var degrees: CGFloat { get { return radians / CGFloat.pi * 180.0 } set { radians = newValue / 180.0 } } } extension CGAngle: CustomStringConvertible { var description: String { return String(format: "%0.2f.C", degrees) } } let angle = CGAngle(radians: .pi) let angle2 = CGAngle(degrees: 90) //: enum 写法 // 这样不同的形状不同的入参 就比各种init方法更好 enum ShapeKind { case circle(center: CGPoint, radius: CGFloat) case square(origin: CGPoint, size: CGFloat) case rotatedSquare(origin: CGPoint, size: CGFloat, angle: CGAngle) case rect(CGRect) case rotatedRect(CGRect, CGAngle) case ellipse(CGRect) case rotatedEllipse(CGRect, CGAngle) } let circleItem = ShapeKind.circle(center: CGPoint.zero, radius: 10) let rotatedSquare = ShapeKind.rotatedSquare(origin: .zero, size: 19.21, angle: CGAngle(degrees: 90)) //: 传统写法 // struct struct Shape { enum `Type` { case circle case square case rotatedSquare case rect case rotatedRect case ellipse case rotetedEllipse } var shareType: Type var rect: CGRect var angle: CGFloat } let center = CGPoint.zero let radius: CGFloat = 10 let circle = Shape(shareType: .circle, rect: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2), angle: 0) circle.angle //: [Next](@next)
mit
eabfa26ec7e7805ccbc0dd8a3c6a492c
22.857143
72
0.584331
4.16632
false
false
false
false
rafaelcpalmeida/UFP-iOS
UFP/UFP/PageViewController.swift
1
3749
// // PageViewController.swift // UFP // // Created by Rafael Almeida on 29/03/17. // Copyright © 2016 Vladimir Romanov. All rights reserved. // https://github.com/VRomanov89/EEEnthusiast---iOS-Dev // import Foundation import UIKit class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { let pageControl = UIPageControl.appearance() public lazy var VCArr: [UIViewController] = { return [self.VCInstance(name: "schedule"), self.VCInstance(name: "queue"), self.VCInstance(name: "finalGrades"), self.VCInstance(name: "partialGrades"), self.VCInstance(name: "atm"), self.VCInstance(name: "assiduity"), self.VCInstance(name: "teachers")] }() private func VCInstance(name: String) -> UIViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name) } override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self if let firstVC = VCArr.first { setViewControllers([firstVC], direction: .forward, animated: true, completion: nil) } self.pageControl.pageIndicatorTintColor = UIColor(red:0.40, green:0.40, blue:0.40, alpha:1.0) self.pageControl.currentPageIndicatorTintColor = UIColor(red:0.34, green:0.62, blue:0.17, alpha:1.0) self.pageControl.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 150) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() for view in self.view.subviews { if view is UIScrollView { view.frame = UIScreen.main.bounds } else if view is UIPageControl { view.backgroundColor = UIColor.clear } } } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = VCArr.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return VCArr.last } guard VCArr.count > previousIndex else { return nil } return VCArr[previousIndex] } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = VCArr.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 guard nextIndex < VCArr.count else { return VCArr.first } guard VCArr.count > nextIndex else { return nil } return VCArr[nextIndex] } public func presentationCount(for pageViewController: UIPageViewController) -> Int { return VCArr.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let firstViewController = viewControllers?.first, let firstViewControllerIndex = VCArr.index(of: firstViewController) else { return 0 } return firstViewControllerIndex } public func getToHome() { if let firstVC = VCArr.first { setViewControllers([firstVC], direction: .forward, animated: true, completion: nil) } } }
mit
5b8ef491824eb44ad891da4d21963b2e
31.877193
156
0.611259
5.198336
false
false
false
false
AllenOoo/SliderMenu-CollectionView
MyDemosInSwift/ViewController.swift
1
2617
// // ViewController.swift // MyDemosInSwift // // Created by zW on 16/8/13. // Copyright © 2016年 allen.wu. All rights reserved. // import UIKit class ViewController: UIViewController, SliderMenuInfoViewDelegate, SliderMenuViewDelegate { var sliderMenu :SliderMenuView! var collection : SliderMenuInfoView! override func viewDidLoad() { super.viewDidLoad() let statusBarBackgroundView = YZView.init(frame: CGRectMake(0, 0, self.view.frame.width, 20)) statusBarBackgroundView.backgroundColor = UIColor.init(red: 255/255.0, green: 66/255.0, blue: 93/255, alpha: 1) self.view.addSubview(statusBarBackgroundView) sliderMenu = SliderMenuView.init(frame: CGRectMake(0, 20, self.view.frame.width, 44)) sliderMenu.titles = ["你","好","Swift","编程","之","美","新生","梦","想"] sliderMenu.delegate = self sliderMenu.index = 3 self.view.addSubview(sliderMenu) collection = SliderMenuInfoView.init(frame: CGRectMake(0, 64, self.view.frame.width, self.view.frame.height-64)) collection.models = [UIImage.init(named: "image1")!, UIImage.init(named: "image2")!, UIImage.init(named: "image3")!, UIImage.init(named: "image4")!, UIImage.init(named: "image5")!, UIImage.init(named: "image6")!, UIImage.init(named: "image7")!, UIImage.init(named: "image8")!, UIImage.init(named: "image9")!] collection.gestureDelegate = self self.view.addSubview(collection) } //MARK: - SliderMenuViewDelegate func didSelectedAtIndex(index: NSInteger, animated: Bool) { // 点击时使下方collectionView滚动 collection.scrollToItemAtIndexPath(NSIndexPath.init(forRow: index, inSection: 0), atScrollPosition: .CenteredHorizontally, animated: animated) } //MARK: - SliderMenuInfoViewDelegate func collectionView(collectionView: SliderMenuInfoView, panning pan: UIPanGestureRecognizer) { // 手指移动时改变滑动菜单对应Item缩放系数 sliderMenu.itemScaledByDistance(Double(pan.translationInView(collectionView).x)) } func collectionView(collectionView: SliderMenuInfoView, didEndPan pan: UIPanGestureRecognizer, to targetIndex: NSInteger) { // 手指离开屏幕后设定滑动菜单对应Item最终状态 sliderMenu.sliderMenuWillScrollToIndex(targetIndex) } }
apache-2.0
dc02ef4b5c9659ddf3e9bbf46ff898f2
37.553846
150
0.638468
4.343154
false
false
false
false
a1049145827/WebViewTest1
WebView/ViewController.swift
1
4697
// // ViewController.swift // WebView // // Created by LiuBruce on 15/11/26. // Copyright © 2015年 LiuBruce. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate { var button = UIButton.init(type: UIButtonType.Custom) var backbutton = UIButton.init(type: UIButtonType.Custom) var forwardbutton = UIButton.init(type: UIButtonType.Custom) var refresh = UIButton.init(type: UIButtonType.Custom) var textField = UITextField.init() var webView = UIWebView.init() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.init(white: 0.95, alpha: 1) textField.frame = CGRectMake(15, 24, self.view.frame.size.width - 100, 32) textField.text = "http://" textField.borderStyle = UITextBorderStyle.RoundedRect self.view.addSubview(textField) button.frame = CGRectMake(textField.frame.origin.x + textField.frame.size.width + 10, textField.frame.origin.y, 60, 32) button.setTitle("打开", forState: UIControlState.Normal) button.backgroundColor = UIColor.redColor() button.addTarget(self, action: Selector("buttonClick:"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) self.webView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 100) webView.backgroundColor = UIColor.whiteColor() webView.delegate = self self.view.addSubview(webView) backbutton.frame = CGRectMake(15, self.view.frame.size.height - 28, 50, 24) backbutton.setBackgroundImage(UIImage(named: "menu_bg_64"), forState: UIControlState.Normal) backbutton.setTitle("后退", forState: UIControlState.Normal) backbutton.addTarget(self, action: Selector("goback:"), forControlEvents: UIControlEvents.TouchUpInside) backbutton.enabled = false self.view.addSubview(backbutton) forwardbutton.frame = CGRectMake(self.view.frame.size.width - 65, self.view.frame.size.height - 28, 50, 24) forwardbutton.setTitle("前进", forState: UIControlState.Normal) forwardbutton.addTarget(self, action: Selector(goforward(forwardbutton)), forControlEvents: UIControlEvents.TouchUpInside) forwardbutton.enabled = false forwardbutton.setBackgroundImage(UIImage(named: "menu_bg_64"), forState: UIControlState.Normal) self.view.addSubview(forwardbutton) refresh.frame = CGRectMake(self.view.frame.size.width/2.0 - 25, self.view.frame.size.height - 28, 50, 24) refresh.setTitle("刷新", forState: UIControlState.Normal) refresh.setBackgroundImage(UIImage(named: "menu_bg_64"), forState: UIControlState.Normal) refresh.addTarget(self, action: "webViewRefresh:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(refresh) } func buttonClick(sender:UIButton) { self.view.endEditing(true) if (textField.text?.isEmpty == false) { // textField.text(isEqual("") let url = NSURL(string :textField.text!) let request = NSURLRequest(URL: url!) self.webView.loadRequest(request) }else { let alertController = UIAlertController(title: "提醒", message: "请输入网址", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil) alertController.addAction(cancelAction) // UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]; // [alertController addAction:okAction]; self.presentViewController(alertController, animated: true, completion: nil) } } func webViewRefresh(sender:UIButton) { self.webView.reload() } func goback(sender:UIButton) { self.webView.goBack() } func goforward(sender:UIButton) { webView.goForward() } func buttonEnable() { self.backbutton.enabled = self.webView.canGoBack self.forwardbutton.enabled = self.webView.canGoForward } func webViewDidFinishLoad(webView: UIWebView) { buttonEnable() print("webViewDidFinishLoad") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f0428c6d512220c16ebb47e3f2f1f603
39.486957
130
0.656572
4.70303
false
false
false
false
plumhead/OSXUtilityPanel
OSXUtilityPanel/OSXUtilityPanel/UtilityWindowController.swift
1
1736
// // UtilityWindowController.swift // OSXUtilityPanel // // Created by Andrew Calderbank on 21/09/2015. // Copyright © 2015 Andrew Calderbank. All rights reserved. // import Cocoa class UtilityWindowController: NSWindowController { lazy var mainStoryboard : NSStoryboard = { let story = NSStoryboard(name: "Main", bundle: nil) return story }() lazy var editController : ViewController = { let edit = self.mainStoryboard.instantiateControllerWithIdentifier("Editor") as! ViewController return edit }() lazy var utilityController : UtilityPanelController = { let inspect = self.mainStoryboard.instantiateControllerWithIdentifier("UtilityPanel") as! UtilityPanelController return inspect }() lazy var splitController : NSSplitViewController = { let split = NSSplitViewController() split.view.wantsLayer = true let editItem = NSSplitViewItem(viewController: self.editController) split.addSplitViewItem(editItem) let insItem = NSSplitViewItem(viewController: self.utilityController) insItem.canCollapse = true split.addSplitViewItem(insItem) return split }() override func windowDidLoad() { super.windowDidLoad() guard let window = window else { fatalError("`window` is expected to be non nil by this time.") } let frameSize = window.contentRectForFrameRect(window.frame).size splitController.view.setFrameSize(frameSize) self.windowFrameAutosaveName = "Window Frame" window.contentViewController = splitController } }
mit
c48ce2d42af517a686353d91ac6257f9
28.913793
120
0.656484
5.404984
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/BeamJunction.swift
1
7187
// // BeamJunction.swift // denm_view // // Created by James Bean on 8/23/15. // Copyright © 2015 James Bean. All rights reserved. // import QuartzCore import DNMModel public class BeamJunction: CustomStringConvertible { public var description: String { get { return getDescription() } } public var x: CGFloat = 0 public var beamsLayer: BeamsLayer? // perhaps not necessary, dealt with abo public var junctionLeft: BeamJunction? { get { return getJunctionLeft() } } public var juntionRight: BeamJunction? { get { return getJunctionRight() } } public var positionInTree: NodePositionTree public var positionInContainer: NodePositionContainer public var currentSubdivisionLevel: Int public var previousSubdivisionLevel: Int? public var nextSubdivisionLevel: Int? public var beamletDirection: Direction = .West // default? public var componentsOnLevel: [Int : BeamJunctionComponent] = [:] init( positionInTree: NodePositionTree, positionInContainer: NodePositionContainer, currentSubdivisionLevel: Int, previousSubdivisionLevel: Int?, nextSubdivisionLevel: Int? ) { self.positionInTree = positionInTree self.positionInContainer = positionInContainer self.currentSubdivisionLevel = currentSubdivisionLevel self.previousSubdivisionLevel = previousSubdivisionLevel self.nextSubdivisionLevel = nextSubdivisionLevel makeDefaultComponentsOnLevel() setDefaultBeamletDirection() } public func setComponent(component: BeamJunctionComponent, forLevel level: Int) { componentsOnLevel[level] = component } public func setComponent(component: BeamJunctionComponent, forLevelRange range: [Int]) { for level in range[0]...range[1] { componentsOnLevel[level] = component } } internal func makeDefaultComponentsOnLevel() { let c: Int = currentSubdivisionLevel - 1 if c < 0 { return } let n: Int? = nextSubdivisionLevel != nil ? nextSubdivisionLevel! - 1 : nil let p: Int? = previousSubdivisionLevel != nil ? previousSubdivisionLevel! - 1 : nil var cOnL: [Int : BeamJunctionComponent] = [:] switch positionInTree { case .SingleInTree: for level in 0...c { cOnL[level] = .Beamlet } case .FirstInTree: switch positionInContainer { case .SingleInContainer: for level in 0...c { cOnL[level] = .Beamlet } break default: for level in 0...c { cOnL[level] = .Start } if c > n! { for level in n! + 1...c { cOnL[level] = .Beamlet } } break } case .MiddleInTree: switch positionInContainer { case .SingleInContainer: for level in 0...c { cOnL[level] = .Beamlet } case .FirstInContainer: for level in 0...c { cOnL[level] = .Start } if c > n! { for level in n! + 1...c { cOnL[level] = .Beamlet } } case .MiddleInContainer: if c == p! && c > n! { for level in n! + 1...c { cOnL[level] = .Stop } } else if c > p! { if c <= n! { for level in p! + 1...c { cOnL[level] = .Start } } else if c > n! { if n! > p! { for level in p! + 1...n! { cOnL[level] = .Start } for level in n! + 1...c { cOnL[level] = .Beamlet } } else if n! == p! { for level in p! + 1...c { cOnL[level] = .Beamlet } } else if n! < p! { for level in n! + 1...p! { cOnL[level] = .Stop } for level in p! + 1...c { cOnL[level] = .Beamlet } } } } else if c < p! && c > n! { for level in n! + 1...c { cOnL[level] = .Stop } } case .LastInContainer: for level in 0...c { cOnL[level] = .Stop } if c > p! { for level in p! + 1...c { cOnL[level] = .Beamlet } } break } case .LastInTree: switch positionInContainer { case .SingleInContainer: for level in 0...c { cOnL[level] = .Beamlet } break default: for level in 0...c { cOnL[level] = .Stop } if c > p! { for level in p! + 1...c { cOnL[level] = .Beamlet } } break } break } componentsOnLevel = cOnL } private func getJunctionLeft() -> BeamJunction? { if beamsLayer == nil { return nil } let index: Int? = beamsLayer!.beamJunctions.indexOfObject(self) if index == nil || index == 0 { return nil } return beamsLayer!.beamJunctions[index! - 1] } private func getJunctionRight() -> BeamJunction? { if beamsLayer == nil { return nil } let index: Int? = beamsLayer!.beamJunctions.indexOfObject(self) if index == nil || index == beamsLayer!.beamJunctions.count - 1 { return nil } return beamsLayer!.beamJunctions[index! + 1] } internal func setDefaultBeamletDirection() { if positionInContainer == .SingleInContainer { beamletDirection = .East } else if positionInContainer == .FirstInContainer { beamletDirection = .East } else if positionInContainer == .LastInContainer { beamletDirection = .West } else { beamletDirection = previousSubdivisionLevel! > nextSubdivisionLevel ? .West : .East } } internal func getDescription() -> String { var description: String = "BeamJunction: " description += "\(positionInTree), \(positionInContainer); " description += "cur: \(currentSubdivisionLevel)" if previousSubdivisionLevel != nil { description += "; prev: \(previousSubdivisionLevel!)" } if nextSubdivisionLevel != nil { description += "; next: \(nextSubdivisionLevel!)" } return description } } public func BeamJunctionMake(durationNode: DurationNode) -> BeamJunction { assert(durationNode.isLeaf, "durationNode must be leaf to create beamJunction") let positionInTree = durationNode.positionInTree! let positionInContainer = durationNode.positionInContainer! let cur = durationNode.duration.subdivisionLevel! let prev: Int? = (durationNode.leafLeft as? DurationNode)?.duration.subdivisionLevel let next: Int? = (durationNode.leafRight as? DurationNode)?.duration.subdivisionLevel let beamJunction = BeamJunction( positionInTree: positionInTree, positionInContainer: positionInContainer, currentSubdivisionLevel: cur, previousSubdivisionLevel: prev, nextSubdivisionLevel: next ) return beamJunction } public enum BeamJunctionComponent { case Start, Stop, Beamlet, Extended }
gpl-2.0
2b39264f802613cb9e79c87bd08ed986
39.370787
95
0.57612
4.202339
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/_RadioGroupPanel.swift
1
1918
// // RadioGroupPanel.swift // denm_view // // Created by James Bean on 10/2/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit /* public class RadioGroupPanel: ButtonSwitchPanel { public var currentButtonSelectedID: String = "" public init( left: CGFloat = 0, top: CGFloat = 0, height: CGFloat = 25, target: AnyObject? = nil, titles: [String] = [] ) { super.init(frame: CGRectMake(left, top, 0, height)) self.target = target addButtonSwitchesWithTitles(titles) currentButtonSelectedID = buttonSwitches.first!.text buttonSwitches.first!.switchOn() // encapsulate for (id, buttonSwitch) in buttonSwitchByID { if id != currentButtonSelectedID { buttonSwitch.switchOff() } } for buttonSwitch in buttonSwitches { buttonSwitch.addTarget(self, action: "stateHasChangedFromSender:", forControlEvents: UIControlEvents.TouchUpInside ) } //layer.borderWidth = 1 //layer.borderColor = UIColor.lightGrayColor().CGColor } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // this is inexcusable, but working...? public override func stateHasChangedFromSender(sender: ButtonSwitch) { for (id, buttonSwitch) in buttonSwitchByID { if id != sender.text { buttonSwitch.switchOff() } else { buttonSwitch.switchOn() currentButtonSelectedID = sender.text } statesByText[sender.text] = sender.isOn } if let environment = target as? _Environment { environment.goToViewWithID(currentButtonSelectedID) } } } */
gpl-2.0
cea6977dc0abf6b796d0261cff18d67d
28.060606
101
0.597809
4.710074
false
false
false
false
auswahlaxiom/Briggs
Source/AdaptiveInterface.swift
1
13638
// // AdaptiveInterface.swift // Briggs // // Copyright (c) 2017 Ada Turner (https://github.com/auswahlaxiom) // // 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 /** An `AdaptiveInterface` contains a collection of `AdaptiveElement`s and forwards `update(for incomingTraitCollection:)` to each of them. `AdaptiveInterface` represents the supplying parent in an inheritence hierarchy of parent-child relationships passing trait information. Recommended override for `UITraitEnvironment`s: ``` override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) update(for: traitCollection) } ``` Extension methods provide conveniences for adding `Behavior`s, `NSLayoutConstraint`s, and `UIView`s with associated `UITraitCollection`s. These are stored in `AdaptiveElement`-conforming containers which append to `self.adaptiveElements`. `AdaptiveInterface` is a class-only protocol to allow for mutating extension methods. */ public protocol AdaptiveInterface: class, AdaptiveElement { /** `adaptiveElements` represent `self`'s children. Each element will be forwarded calls to `update(for incomingTraitCollection:)` that `self` recieves. */ var adaptiveElements: [AdaptiveElement] { get set } } /** The default implementation of `update(for incomingTraitCollection:)` forwards `update(for incomingTraitCollection:)` to each item in `self.adaptiveElements`. */ public extension AdaptiveInterface { /** Default `AdaptiveInterface` implementation forwards `update(for incomingTraitCollection:)` to each of `self`'s children. - note: Child adaptive elements whose `traitCollection` is *not* contained by `incomingTraitCollection` are updated first to avoid conflicting behaviors being active at the same time. */ public func update(for incomingTraitCollection: UITraitCollection) { adaptiveElements.filter { incomingTraitCollection.containsTraits(in: $0.traitCollection) == false }.forEach { $0.update(for: incomingTraitCollection) } adaptiveElements.filter { incomingTraitCollection.containsTraits(in: $0.traitCollection) == true }.forEach { $0.update(for: incomingTraitCollection) } } } /** Convenience methods for adding `AdaptiveBehavior`s, `AdaptiveConstraintContainer`s, and `AdaptiveViewContainer`s. Each has a raw form, which takes a `UITraitCollection`, and two wrappers which take one or more `AdaptiveAttribute`s. */ public extension AdaptiveInterface { // MARK: - Convenience Methods // MARK: Add Behavior /** Add a `Behavior` and counter-`Behavior` for a `UITraitCollection` Convenience for creating an `AdaptiveBehavior` and adding it to `self.adaptiveElements` - parameter traitCollection: `UITraitCollection` for which `behavior` will be executed - parameter behavior: `Behavior` to be executed if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter counterBehavior: Optional `Behavior` (defaults to `nil`) to be executed if `incomingTraitCollection` does not contain `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addBehavior(for traitCollection: UITraitCollection, behavior: @escaping AdaptiveBehavior.Behavior, counterBehavior: AdaptiveBehavior.Behavior? = nil) { let adaptiveBehavior = AdaptiveBehavior(traitCollection: traitCollection, behavior: behavior, counterBehavior: counterBehavior) adaptiveElements.append(adaptiveBehavior) } /** Add a `Behavior` and counter-`Behavior` for a set of `AdaptiveAttribute`s Convenience for creating an `AdaptiveBehavior` and adding it to `self.adaptiveElements` - parameter attributes: Array of `AdaptiveAttribute`s used to create a `UITraitCollection` for which `behavior` will be executed - parameter behavior: `Behavior` to be executed if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter counterBehavior: Optional `Behavior` (defaults to `nil`) to be executed if `incomingTraitCollection` does not contain `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addBehavior(for attributes: [AdaptiveAttribute], behavior: @escaping AdaptiveBehavior.Behavior, counterBehavior: AdaptiveBehavior.Behavior? = nil) { let traitCollection = UITraitCollection.create(with: attributes) addBehavior(for: traitCollection, behavior: behavior, counterBehavior: counterBehavior) } /** Add a `Behavior` and counter-`Behavior` for a single `AdaptiveAttribute` Convenience for creating an `AdaptiveBehavior` and adding it to `self.adaptiveElements` - parameter attribute: Single `AdaptiveAttribute` used to create a `UITraitCollection` for which `behavior` will be executed - parameter behavior: `Behavior` to be executed if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter counterBehavior: Optional `Behavior` (defaults to `nil`) to be executed if `incomingTraitCollection` does not contain `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addBehavior(for attribute: AdaptiveAttribute, behavior: @escaping AdaptiveBehavior.Behavior, counterBehavior: AdaptiveBehavior.Behavior? = nil) { let traitCollection = UITraitCollection.create(with: [attribute]) addBehavior(for: traitCollection, behavior: behavior, counterBehavior: counterBehavior) } // MARK: Add NSLayoutConstraints /** Add an array of `NSLayoutConstraint`s for a `UITraitCollection` Convenience for creating an `AdaptiveConstraintContainer` and adding it to `self.adaptiveElements` - parameter traitCollection: `UITraitCollection` for which `constraints` will be activated - parameter constraints: Array of `NSLayoutConstraint`s to be activated if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addConstraints(for traitCollection: UITraitCollection, constraints: [NSLayoutConstraint]) { let container = AdaptiveConstraintContainer(traitCollection: traitCollection, constraints: constraints) adaptiveElements.append(container) } /** Add an array of `NSLayoutConstraint`s for a set of `AdaptiveAttribute`s Convenience for creating an `AdaptiveConstraintContainer` and adding it to `self.adaptiveElements` - parameter attributes: Array of `AdaptiveAttribute`s used to create a `UITraitCollection` for which `constraints` will be activated - parameter constraints: Variadic array of `NSLayoutConstraint`s to be activated if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addConstraints(for attributes: [AdaptiveAttribute], constraints: NSLayoutConstraint...) { let traitCollection = UITraitCollection.create(with: attributes) addConstraints(for: traitCollection, constraints: constraints) } /** Add an array of `NSLayoutConstraint`s for a single `AdaptiveAttribute` Convenience for creating an `AdaptiveConstraintContainer` and adding it to `self.adaptiveElements` - parameter attribute: Single `AdaptiveAttribute` used to create a `UITraitCollection` for which `constraints` will be activated - parameter constraints: Variadic array of `NSLayoutConstraint`s to be activated if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called */ public func addConstraints(for attribute: AdaptiveAttribute, constraints: NSLayoutConstraint...) { let traitCollection = UITraitCollection.create(with: [attribute]) addConstraints(for: traitCollection, constraints: constraints) } // MARK: Add UIViews /** Add a `UIView` and associated array of `NSLayoutConstraint`s for a `UITraitCollection` Convenience for creating an `AdaptiveViewContainer` and optional `AdaptiveConstraintContainer` and adding them to `self.adaptiveElements` - parameter traitCollection: `UITraitCollection` for which `view` will be added to `parent` and `constraints` will be activated - parameter view: `UIView` to be added to `parent` if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter parent: `UIView` to which `view` will be added - parameter constraints: Optional array of `NSLayoutConstraint`s (defaults to `[]`) used to create an `AdaptiveViewContainer` which will be added alongside the `AdaptiveViewContainer`. Use to specify constraints relating to `view` that will be activated under the same conditions that `view` is added to `parent`. */ public func addView(for traitCollection: UITraitCollection, view: UIView, parent: UIView, constraints: @autoclosure () -> [NSLayoutConstraint] = []) { // Add view to parent, so constraints can be created if they are supplied. Will be removed in updateForTraitCollection if necessary. parent.addSubview(view) let viewContainer = AdaptiveViewContainer(traitCollection: traitCollection, parent: parent, child: view) adaptiveElements.append(viewContainer) // `constraints` is an autoclosure because constraints relating `view` to `parent` or its superviews cannot be instantiated until `view` is in `parent`'s heirarchy let constructedConstraints = constraints() if constructedConstraints.isEmpty == false { let constraintContainer = AdaptiveConstraintContainer(traitCollection: traitCollection, constraints: constructedConstraints) adaptiveElements.append(constraintContainer) } } /** Add a `UIView` and associated array of `NSLayoutConstraint`s for a set of `AdaptiveAttribute`s Convenience for creating an `AdaptiveViewContainer` and optional `AdaptiveConstraintContainer` and adding them to `self.adaptiveElements` - parameter attributes: Array of `AdaptiveAttribute`s used to create a `UITraitCollection` for which `view` will be added to `parent` and `constraints` will be activated - parameter view: `UIView` to be added to `parent` if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter parent: `UIView` to which `view` will be added - parameter constraints: Optional array of `NSLayoutConstraint`s (defaults to `[]`) used to create an `AdaptiveViewContainer` which will be added alongside the `AdaptiveViewContainer`. Use to specify constraints relating to `view` that will be activated under the same conditions that `view` is added to `parent`. */ public func addView(for attributes: [AdaptiveAttribute], view: UIView, parent: UIView, constraints: @autoclosure () -> [NSLayoutConstraint] = []) { let traitCollection = UITraitCollection.create(with: attributes) addView(for: traitCollection, view: view, parent: parent, constraints: constraints) } /** Add a `UIView` and associated array of `NSLayoutConstraint`s for a single `AdaptiveAttribute` Convenience for creating an `AdaptiveViewContainer` and optional `AdaptiveConstraintContainer` and adding them to `self.adaptiveElements` - parameter attribute: Single `AdaptiveAttribute` used to create a `UITraitCollection` for which `view` will be added to `parent` and `constraints` will be activated - parameter view: `UIView` to be added to `parent` if `incomingTraitCollection` contains `traitCollection` when `update(for incomingTraitCollection:)` is called - parameter parent: `UIView` to which `view` will be added - parameter constraints: Optional array of `NSLayoutConstraint`s (defaults to `[]`) used to create an `AdaptiveViewContainer` which will be added alongside the `AdaptiveViewContainer`. Use to specify constraints relating to `view` that will be activated under the same conditions that `view` is added to `parent`. */ public func addView(for attribute: AdaptiveAttribute, view: UIView, parent: UIView, constraints: @autoclosure () -> [NSLayoutConstraint] = []) { let traitCollection = UITraitCollection.create(with: [attribute]) addView(for: traitCollection, view: view, parent: parent, constraints: constraints) } }
mit
319bed30f2e2898ac715620f336beb96
60.432432
318
0.756856
5.047372
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/MapboxNavigation/MapboxNavigation/RoutePageViewController.swift
1
3990
import UIKit import MapboxDirections import MapboxCoreNavigation protocol RoutePageViewControllerDelegate: class { var currentLeg: RouteLeg { get } var currentStep: RouteStep { get } var upComingStep: RouteStep? { get } func stepBefore(_ step: RouteStep) -> RouteStep? func stepAfter(_ step: RouteStep) -> RouteStep? // `didSwipe` is only true when this function is invoked via the user swiping func routePageViewController(_ controller: RoutePageViewController, willTransitionTo maneuverViewController: RouteManeuverViewController, didSwipe: Bool) } class RoutePageViewController: UIPageViewController { weak var maneuverDelegate: RoutePageViewControllerDelegate! var currentManeuverPage: RouteManeuverViewController! var maneuverContainerView: ManeuverContainerView { return view.superview! as! ManeuverContainerView } override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self view.clipsToBounds = false // Disable clipsToBounds on the hidden UIQueuingScrollView to render the shadows properly view.subviews.first?.clipsToBounds = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) updateManeuverViewForStep() } func updateManeuverViewForStep() { let step = maneuverDelegate.upComingStep ?? maneuverDelegate.currentStep let leg = maneuverDelegate.currentLeg let controller = routeManeuverViewController(with: step, leg: leg)! setViewControllers([controller], direction: .forward, animated: false, completion: nil) currentManeuverPage = controller maneuverDelegate.routePageViewController(self, willTransitionTo: controller, didSwipe: false) } func routeManeuverViewController(with step: RouteStep?, leg: RouteLeg?) -> RouteManeuverViewController? { guard step != nil else { return nil } let storyboard = UIStoryboard(name: "Navigation", bundle: .mapboxNavigation) let controller = storyboard.instantiateViewController(withIdentifier: "RouteManeuverViewController") as! RouteManeuverViewController controller.step = step controller.leg = leg return controller } } extension RoutePageViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let controller = viewController as! RouteManeuverViewController let stepAfter = maneuverDelegate.stepAfter(controller.step!) let leg = maneuverDelegate.currentLeg return routeManeuverViewController(with: stepAfter, leg: leg) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let controller = viewController as! RouteManeuverViewController let stepBefore = maneuverDelegate.stepBefore(controller.step!) let leg = maneuverDelegate.currentLeg return routeManeuverViewController(with: stepBefore, leg: leg) } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { let controller = pendingViewControllers.first! as! RouteManeuverViewController maneuverDelegate.routePageViewController(self, willTransitionTo: controller, didSwipe: true) } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard let controller = pageViewController.viewControllers?.last as? RouteManeuverViewController else { return } if completed { currentManeuverPage = controller } } }
lgpl-3.0
294e298ce4bde984839cd16b5be5dce3
45.941176
190
0.7401
5.919881
false
true
false
false
fespinoza/linked-ideas-osx
LinkedIdeas-Shared/Sources/Models/Link.swift
1
5966
// // <.swift // LinkedIdeas // // Created by Felipe Espinoza Castillo on 26/11/15. // Copyright © 2015 Felipe Espinoza Dev. All rights reserved. // #if os(iOS) import UIKit public typealias Color = UIColor #else import AppKit public typealias Color = NSColor #endif public class Link: NSObject, NSCoding, Element { // own attributes var origin: Concept var target: Concept public var originRect: CGRect { return origin.area } public var targetRect: CGRect { return target.area } public var originPoint: CGPoint { return origin.centerPoint } public var targetPoint: CGPoint { return target.centerPoint } public var centerPoint: CGPoint { return CGPoint( x: ((originPoint.x + targetPoint.x) / 2.0), y: ((originPoint.y + targetPoint.y) / 2.0) ) } let textRectPadding: CGFloat = 8.0 var textRect: CGRect { var textSizeWithPadding = attributedStringValue.size() textSizeWithPadding.width += textRectPadding textSizeWithPadding.height += textRectPadding return CGRect(center: centerPoint, size: textSizeWithPadding) } @objc dynamic public var color: Color // MARK: - NSAttributedStringElement @objc dynamic public var attributedStringValue: NSAttributedString public var stringValue: String { return attributedStringValue.string } // MARK: - VisualElement public var isEditable: Bool = false public var isSelected: Bool = false private let padding: CGFloat = 20 static let defaultColor = Color.gray override public var description: String { return "'\(origin.stringValue)' '\(target.stringValue)'" } public override var debugDescription: String { return "[Link][\(origin.identifier)]-[\(target.identifier)]" } // Element public var identifier: String public var area: CGRect { var minX = min(originPoint.x, targetPoint.x) if abs(originPoint.x - targetPoint.x) <= padding { minX -= padding / 2 } var minY = min(originPoint.y, targetPoint.y) if abs(originPoint.y - targetPoint.y) <= padding { minY -= padding / 2 } let maxX = max(originPoint.x, targetPoint.x) let maxY = max(originPoint.y, targetPoint.y) let width = max(maxX - minX, padding) let height = max(maxY - minY, padding) return CGRect(x: minX, y: minY, width: width, height: height) } public func contains(point: CGPoint) -> Bool { guard area.contains(point) else { return false } if textRect.contains(point) { return true } let extendedAreaArrow = Arrow(point1: originPoint, point2: targetPoint, arrowBodyWidth: 20) let minXPoint: CGPoint! = extendedAreaArrow.arrowBodyPoints() .min { (pointA, pointB) -> Bool in pointA.x < pointB.x } let maxXPoint: CGPoint! = extendedAreaArrow.arrowBodyPoints() .max { (pointA, pointB) -> Bool in pointA.x < pointB.x } let linkLine = Line(pointA: originPoint, pointB: targetPoint) let pivotPoint = CGPoint(x: linkLine.evaluateY(0), y: 0) let angledLine = Line(pointA: pivotPoint, pointB: minXPoint) let a = angledLine.intersectionWithYAxis let b = angledLine.intersectionWithXAxis let c: CGFloat = sqrt(pow(a, 2) + pow(b, 2)) let sin_theta = a / c let cos_theta = b / c func transformationFunction(ofPoint pointToTransform: CGPoint) -> CGPoint { return CGPoint( x: pointToTransform.x * cos_theta - sin_theta * pointToTransform.y - minXPoint.x, y: pointToTransform.x * sin_theta + cos_theta * pointToTransform.y - minXPoint.y ) } let transformedRect = CGRect( point1: transformationFunction(ofPoint: minXPoint), point2: transformationFunction(ofPoint: maxXPoint) ) let transformedPoint = transformationFunction(ofPoint: point) return transformedRect.contains(transformedPoint) } public convenience init(origin: Concept, target: Concept) { self.init(origin: origin, target: target, attributedStringValue: NSAttributedString(string: "")) } public init(origin: Concept, target: Concept, attributedStringValue: NSAttributedString) { self.origin = origin self.target = target self.identifier = "\(UUID().uuidString)-link" self.color = Link.defaultColor self.attributedStringValue = attributedStringValue } // MARK: - KVO public static let colorPath = "color" public static let attributedStringValuePath = "attributedStringValue" let identifierKey = "identifierKey" let originKey = "OriginKey" let targetKey = "TargetKey" let colorKey = "colorKey" let attributedStringValueKey = "attributedStringValue" let colorComponentsKey = "colorComponentsKey" public func doesBelongTo(concept: Concept) -> Bool { return origin == concept || target == concept } required public init?(coder aDecoder: NSCoder) { guard let identifier = aDecoder.decodeObject(forKey: identifierKey) as? String, let origin = aDecoder.decodeObject(forKey: originKey) as? Concept, let target = aDecoder.decodeObject(forKey: targetKey) as? Concept else { return nil } self.identifier = identifier self.origin = origin self.target = target if let attributedStringValue = aDecoder.decodeObject(forKey: attributedStringValueKey) as? NSAttributedString { self.attributedStringValue = attributedStringValue } else { self.attributedStringValue = NSAttributedString(string: "") } if let colorComponents = aDecoder.decodeObject(forKey: colorComponentsKey) as? [CGFloat] { self.color = ColorUtils.color(fromComponents: colorComponents) } else { self.color = Link.defaultColor } } public func encode(with aCoder: NSCoder) { aCoder.encode(identifier, forKey: identifierKey) aCoder.encode(origin, forKey: originKey) aCoder.encode(target, forKey: targetKey) aCoder.encode(ColorUtils.extractColorComponents(forColor: color), forKey: colorComponentsKey) aCoder.encode(attributedStringValue, forKey: attributedStringValueKey) } }
mit
4357c400fbd413997a5c4dfce63bf8fa
33.281609
115
0.708634
4.200704
false
false
false
false
Prosumma/Guise
Sources/Guise/Resolver/Array.swift
1
1429
// // Array.swift // Guise // // Created by Gregory Higley on 2022-09-21. // public enum ArrayResolutionConfig { static var throwResolutionErrorWhenNotFound = false } extension Array: ResolutionAdapter { static func resolve<A>( tags: Set<AnyHashable>, args: A, with resolver: Resolver ) throws -> Any { var array: [Element] = [] let criteria = Criteria(Element.self, tags: .contains(tags), args: A.self) for (key, _) in resolver.resolve(criteria: criteria) { try array.append(resolver.resolve(Element.self, tags: key.tags, args: args)) } if ArrayResolutionConfig.throwResolutionErrorWhenNotFound && array.isEmpty { let key = Key([Element].self, tags: tags, args: A.self) throw ResolutionError(key: key, reason: .notFound) } return array } static func resolveAsync<A>( tags: Set<AnyHashable>, args: A, with resolver: Resolver ) async throws -> Any { var array: [Element] = [] let criteria = Criteria(Element.self, tags: .contains(tags), args: A.self) for (key, _) in resolver.resolve(criteria: criteria) { try await array.append(resolver.resolve(Element.self, tags: key.tags, args: args)) } if ArrayResolutionConfig.throwResolutionErrorWhenNotFound && array.isEmpty { let key = Key([Element].self, tags: tags, args: A.self) throw ResolutionError(key: key, reason: .notFound) } return array } }
mit
38114b58451f4e972e69eead746c19dc
30.065217
88
0.668999
3.68299
false
true
false
false
OatmealCode/Oatmeal
Pod/Classes/Extensions/Swift/Range.swift
1
350
//// //// Range.swift //// Cent //// //// Created by Ankur Patel on 6/30/14. //// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. //// // //import Foundation // // //public func ==<T: ForwardIndexType>(left: Range<T>, right: Range<T>) -> Bool { // return left.startIndex == right.startIndex && left.endIndex == right.endIndex //}
mit
6784d81643570e0e16d32685dcc026d6
24
83
0.614286
3.431373
false
false
false
false
ntwf/TheTaleClient
TheTale/Controllers/StartScreen/StartViewController.swift
1
4080
// // StartViewController.swift // the-tale // // Created by Mikhail Vospennikov on 21/05/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import UIKit protocol SegueHandlerDelegate: class { func segueHandler(identifier: String) } protocol AuthPathDelegate: class { var authPath: String? { get set } } final class StartViewController: UIViewController, AuthPathDelegate { // MARK: - AuthPathDelegate var authPath: String? // MARK: - Outlets @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var loginContainer: UIView! @IBOutlet weak var registrationContainer: UIView! @IBOutlet var startingViewsCollection: [UIView]! // MARK: - Load controller override func viewDidLoad() { super.viewDidLoad() startingViewsCollection.forEach { $0.isHidden = true } setupGesture() addNotification() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var shouldAutorotate: Bool { return false } func setupGesture() { let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) segmentedControl.selectedSegmentIndex = 0 checkAuthorisation() } // MARK: - Notification func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(catchNotification(sender:)), name: .TaleAPINonblockingOperationStatusChanged, object: nil) } func catchNotification(sender: Notification) { guard let userInfo = sender.userInfo, let status = userInfo[TaleAPI.UserInfoKey.nonblockingOperationStatus] as? TaleAPI.StatusOperation else { return } switch status { case .ok: checkAuthorisation() case .error: print("error") default: break } } func checkAuthorisation() { TaleAPI.shared.getAuthorisationState { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .success: strongSelf.performSegue(withIdentifier: AppConfiguration.Segue.toJournal, sender: self) case .failure(let error as NSError): debugPrint("checkAuthorisation", error) strongSelf.segmentedControl.isHidden = false strongSelf.loginContainer.isHidden = true strongSelf.registrationContainer.isHidden = false default: break } } } // MARK: - Prepare segue data override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == AppConfiguration.Segue.toWeb { if let navigationViewController = segue.destination as? UINavigationController, let webViewController = navigationViewController.topViewController as? WebViewController, let authPath = authPath { webViewController.authPath = authPath } } else if segue.identifier == AppConfiguration.Segue.toLogin, let loginViewController = segue.destination as? LoginViewController { loginViewController.segueHandlerDelegate = self loginViewController.authPathDelegate = self } } // MARK: - Outlets action @IBAction func showComponents(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { loginContainer.isHidden = true registrationContainer.isHidden = false } else { loginContainer.isHidden = false registrationContainer.isHidden = true } } } // MARK: - SegueHandlerDelegate extension StartViewController: SegueHandlerDelegate { func segueHandler(identifier: String) { performSegue(withIdentifier: identifier, sender: nil) } }
mit
4d78da97628654657dab6b90266e7529
27.725352
116
0.68154
5.163291
false
false
false
false
trill-lang/trill
Sources/Sema/ConstraintGenerator.swift
2
7653
/// /// ConstraintGenerator.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import AST import Foundation final class ConstraintGenerator: ASTTransformer { var goal: DataType = .error var env = ConstraintEnvironment() var system = ConstraintSystem() func reset(with env: ConstraintEnvironment) { self.goal = .error self.env = env self.system = ConstraintSystem() } func bind(_ name: Identifier, to type: DataType) { env[name] = type } // MARK: Monotypes override func visitVarExpr(_ expr: VarExpr) { if expr.isSelf { self.goal = expr.type return } if let stdlib = context.stdlib, expr.isTypeVar { self.goal = stdlib.mirror.type return } if let t = env[expr.name] ?? context.global(named: expr.name)?.type { self.goal = t return } if let decl = expr.decl { self.goal = decl.type return } } override func visitSizeofExpr(_ expr: SizeofExpr) { self.goal = expr.type } override func visitStringInterpolationExpr(_ expr: StringInterpolationExpr) { self.goal = expr.type } override func visitPropertyRefExpr(_ expr: PropertyRefExpr) { // Don't visit the left-hand side if it's a type var, because you're // actually trying to access a static property of the type, not an instance // property/method on the metatype mirror. if let v = expr.lhs as? VarExpr, let typeDecl = expr.typeDecl, v.isTypeVar { goal = typeDecl.type } else { visit(expr.lhs) } system.constrainEqual(goal, expr.typeDecl!.type, node: expr) let tau = env.freshTypeVariable() system.constrainEqual(expr.decl!, tau) self.goal = tau } override func visitVarAssignDecl(_ decl: VarAssignDecl) { let goalType: DataType // let <ident>: <Type> = <expr> if let e = decl.rhs { if let typeRef = decl.typeRef { goalType = typeRef.type } else { goalType = e.type } visit(e) // Bind the given type to the goal type the initializer generated. system.constrainEqual(goal, goalType, node: e) } else { // let <ident>: <Type> // Take the type binding as fact and move on. goalType = decl.type bind(decl.name, to: goalType) } self.goal = goalType } override func visitFuncDecl(_ expr: FuncDecl) { if let body = expr.body { let oldEnv = self.env for p in expr.args { // Bind the type of the parameters. bind(p.name, to: p.type) } // Walk into the function body self.visit(body) self.env = oldEnv } self.goal = expr.type } override func visitFuncCallExpr(_ expr: FuncCallExpr) { visit(expr.lhs) let lhsGoal = self.goal var goals = [DataType]() if let method = expr.decl as? MethodDecl, !method.has(attribute: .static) { goals.append(method.parentType) } for arg in expr.args { visit(arg.val) goals.append(self.goal) } let tau = env.freshTypeVariable() system.constrainEqual(lhsGoal, .function(args: goals, returnType: tau, hasVarArgs: expr.decl!.hasVarArgs), node: expr.lhs) goal = tau } override func visitIsExpr(_ expr: IsExpr) { let tau = env.freshTypeVariable() visit(expr.rhs) system.constrainEqual(goal, tau) system.constrainEqual(expr, .bool) goal = .bool } override func visitCoercionExpr(_ expr: CoercionExpr) { let tau = env.freshTypeVariable() visit(expr.rhs) system.constrainEqual(goal, tau) system.constrainEqual(expr, tau) goal = tau } override func visitInfixOperatorExpr(_ expr: InfixOperatorExpr) { let tau = env.freshTypeVariable() if expr.op.isAssign { goal = .void return } let lhsGoal = expr.decl!.type var goals = [DataType]() visit(expr.lhs) goals.append(goal) visit(expr.rhs) goals.append(goal) system.constrainEqual(lhsGoal, .function(args: goals, returnType: tau, hasVarArgs: false), node: expr) goal = tau } override func visitSubscriptExpr(_ expr: SubscriptExpr) { visit(expr.lhs) var goals: [DataType] = [ self.goal ] expr.args.forEach { a in visit(a.val) goals.append(self.goal) } let tau = env.freshTypeVariable() if let decl = expr.decl { system.constrainEqual(decl, .function(args: goals, returnType: tau, hasVarArgs: false)) } self.goal = tau } override func visitArrayExpr(_ expr: ArrayExpr) { guard case .array(let field, _) = expr.type else { fatalError("invalid array type") } for value in expr.values { visit(value) system.constrainEqual(goal, field, node: value) } goal = expr.type } override func visitTupleExpr(_ expr: TupleExpr) { var goals = [DataType]() for element in expr.values { visit(element) goals.append(self.goal) } system.constrainEqual(expr, .tuple(fields: goals)) self.goal = expr.type } override func visitTernaryExpr(_ expr: TernaryExpr) { let tau = env.freshTypeVariable() visit(expr.condition) system.constrainEqual(expr.condition, .bool) visit(expr.trueCase) system.constrainEqual(expr.trueCase, tau) visit(expr.falseCase) system.constrainEqual(expr.falseCase, tau) system.constrainEqual(expr, tau) self.goal = tau } override func visitPrefixOperatorExpr(_ expr: PrefixOperatorExpr) { visit(expr.rhs) let rhsGoal = self.goal switch expr.op { case .ampersand: goal = .pointer(type: rhsGoal) case .bitwiseNot: goal = rhsGoal case .minus: goal = rhsGoal case .not: goal = .bool system.constrainEqual(rhsGoal, .bool, node: expr.rhs) case .star: guard case .pointer(let element) = expr.rhs.type else { fatalError("invalid dereference?") } goal = element default: fatalError("invalid prefix operator: \(expr.op)") } system.constrainEqual(expr, goal) } override func visitTupleFieldLookupExpr(_ expr: TupleFieldLookupExpr) { visit(expr.lhs) let lhsGoal = self.goal guard case .tuple(let fields) = lhsGoal else { return } system.constrainEqual(expr, fields[expr.field]) self.goal = fields[expr.field] } override func visitParenExpr(_ expr: ParenExpr) { visit(expr.value) self.goal = expr.type } override func visitTypeRefExpr(_ expr: TypeRefExpr) { self.goal = expr.type } override func visitPoundFunctionExpr(_ expr: PoundFunctionExpr) { visitStringExpr(expr) } override func visitClosureExpr(_ expr: ClosureExpr) { // TODO: Implement this } // MARK: Literals override func visitNumExpr(_ expr: NumExpr) { self.goal = expr.type } override func visitCharExpr(_ expr: CharExpr) { self.goal = expr.type } override func visitFloatExpr(_ expr: FloatExpr) { self.goal = expr.type } override func visitBoolExpr(_ expr: BoolExpr) { self.goal = expr.type } override func visitVoidExpr(_ expr: VoidExpr) { self.goal = expr.type } override func visitNilExpr(_ expr: NilExpr) { self.goal = expr.type } override func visitStringExpr(_ expr: StringExpr) { self.goal = expr.type } }
mit
ea62d6444bc79123c745e8839ea871ab
24.681208
79
0.621848
3.884772
false
false
false
false
CatchChat/Yep
Yep/Services/YepDownloader.swift
1
16547
// // YepDownloader.swift // Yep // // Created by NIX on 15/6/29. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import Foundation import ImageIO import YepKit import RealmSwift final class YepDownloader: NSObject { static let sharedDownloader = YepDownloader() lazy var session: NSURLSession = { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil) return session }() private class func updateAttachmentOfMessage(message: Message, withAttachmentFileName attachmentFileName: String, inRealm realm: Realm) { message.localAttachmentName = attachmentFileName if message.mediaType == MessageMediaType.Video.rawValue { if !message.localThumbnailName.isEmpty { message.downloadState = MessageDownloadState.Downloaded.rawValue } } else { message.downloadState = MessageDownloadState.Downloaded.rawValue } } private class func updateThumbnailOfMessage(message: Message, withThumbnailFileName thumbnailFileName: String, inRealm realm: Realm) { message.localThumbnailName = thumbnailFileName if message.mediaType == MessageMediaType.Video.rawValue { if !message.localAttachmentName.isEmpty { message.downloadState = MessageDownloadState.Downloaded.rawValue } } } struct ProgressReporter { struct Task { let downloadTask: NSURLSessionDataTask typealias FinishedAction = NSData -> Void let finishedAction: FinishedAction let progress = NSProgress() let tempData = NSMutableData() let imageSource = CGImageSourceCreateIncremental(nil) let imageTransform: (UIImage -> UIImage)? } let tasks: [Task] var finishedTasksCount = 0 typealias ReportProgress = (progress: Double, image: UIImage?) -> Void let reportProgress: ReportProgress? init(tasks: [Task], reportProgress: ReportProgress?) { self.tasks = tasks self.reportProgress = reportProgress } var totalProgress: Double { let completedUnitCount = tasks.map({ $0.progress.completedUnitCount }).reduce(0, combine: +) let totalUnitCount = tasks.map({ $0.progress.totalUnitCount }).reduce(0, combine: +) return Double(completedUnitCount) / Double(totalUnitCount) } } var progressReporters = [ProgressReporter]() class func downloadAttachmentsOfMessage(message: Message, reportProgress: ProgressReporter.ReportProgress?) { downloadAttachmentsOfMessage(message, reportProgress: reportProgress, imageTransform: nil, imageFinished: nil) } class func downloadAttachmentsOfMessage(message: Message, reportProgress: ProgressReporter.ReportProgress?, imageTransform: (UIImage -> UIImage)?, imageFinished: (UIImage -> Void)?) { let downloadState = message.downloadState if downloadState == MessageDownloadState.Downloaded.rawValue { return } let messageID = message.messageID let mediaType = message.mediaType var attachmentDownloadTask: NSURLSessionDataTask? var attachmentFinishedAction: ProgressReporter.Task.FinishedAction? let attachmentURLString = message.attachmentURLString if !attachmentURLString.isEmpty && message.localAttachmentName.isEmpty, let URL = NSURL(string: attachmentURLString) { attachmentDownloadTask = sharedDownloader.session.dataTaskWithURL(URL) attachmentFinishedAction = { data in SafeDispatch.async { guard let realm = try? Realm() else { return } if let message = messageWithMessageID(messageID, inRealm: realm) { if message.localAttachmentName.isEmpty { let fileName = NSUUID().UUIDString realm.beginWrite() switch mediaType { case MessageMediaType.Image.rawValue: if let _ = NSFileManager.saveMessageImageData(data, withName: fileName) { self.updateAttachmentOfMessage(message, withAttachmentFileName: fileName, inRealm: realm) if let image = UIImage(data: data) { imageFinished?(image) } } case MessageMediaType.Video.rawValue: if let _ = NSFileManager.saveMessageVideoData(data, withName: fileName) { self.updateAttachmentOfMessage(message, withAttachmentFileName: fileName, inRealm: realm) } case MessageMediaType.Audio.rawValue: if let _ = NSFileManager.saveMessageAudioData(data, withName: fileName) { self.updateAttachmentOfMessage(message, withAttachmentFileName: fileName, inRealm: realm) } default: break } let _ = try? realm.commitWrite() } } } } } var thumbnailDownloadTask: NSURLSessionDataTask? var thumbnailFinishedAction: ProgressReporter.Task.FinishedAction? if mediaType == MessageMediaType.Video.rawValue { let thumbnailURLString = message.thumbnailURLString if !thumbnailURLString.isEmpty && message.localThumbnailName.isEmpty, let URL = NSURL(string: thumbnailURLString) { thumbnailDownloadTask = sharedDownloader.session.dataTaskWithURL(URL) thumbnailFinishedAction = { data in SafeDispatch.async { guard let realm = try? Realm() else { return } if let message = messageWithMessageID(messageID, inRealm: realm) { if message.localThumbnailName.isEmpty { let fileName = NSUUID().UUIDString if let _ = NSFileManager.saveMessageImageData(data, withName: fileName) { realm.beginWrite() self.updateThumbnailOfMessage(message, withThumbnailFileName: fileName, inRealm: realm) let _ = try? realm.commitWrite() if let image = UIImage(data: data) { imageFinished?(image) } } } } } } } } var tasks: [ProgressReporter.Task] = [] if let attachmentDownloadTask = attachmentDownloadTask, attachmentFinishedAction = attachmentFinishedAction { tasks.append(ProgressReporter.Task(downloadTask: attachmentDownloadTask, finishedAction: attachmentFinishedAction, imageTransform: imageTransform)) } if let thumbnailDownloadTask = thumbnailDownloadTask, thumbnailFinishedAction = thumbnailFinishedAction { tasks.append(ProgressReporter.Task(downloadTask: thumbnailDownloadTask, finishedAction: thumbnailFinishedAction, imageTransform: imageTransform)) } if tasks.count > 0 { let progressReporter = ProgressReporter(tasks: tasks, reportProgress: reportProgress) sharedDownloader.progressReporters.append(progressReporter) tasks.forEach { $0.downloadTask.resume() } } else { println("Can NOT download attachments of message: \(mediaType), \(messageID)") } } class func downloadDataFromURL(URL: NSURL, reportProgress: ProgressReporter.ReportProgress?, finishedAction: ProgressReporter.Task.FinishedAction) { let downloadTask = sharedDownloader.session.dataTaskWithURL(URL) let task = ProgressReporter.Task(downloadTask: downloadTask, finishedAction: finishedAction, imageTransform: nil) let progressReporter = ProgressReporter(tasks: [task], reportProgress: reportProgress) sharedDownloader.progressReporters.append(progressReporter) downloadTask.resume() } } extension YepDownloader: NSURLSessionDelegate { } extension YepDownloader: NSURLSessionDataDelegate { private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, totalBytes: Int64) { for progressReporter in progressReporters { for i in 0..<progressReporter.tasks.count { if downloadTask == progressReporter.tasks[i].downloadTask { progressReporter.tasks[i].progress.totalUnitCount = totalBytes progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil) return } } } } private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, didReceiveData data: NSData) -> Bool { for progressReporter in progressReporters { for i in 0..<progressReporter.tasks.count { if downloadTask == progressReporter.tasks[i].downloadTask { let didReceiveDataBytes = Int64(data.length) progressReporter.tasks[i].progress.completedUnitCount += didReceiveDataBytes progressReporter.tasks[i].tempData.appendData(data) let progress = progressReporter.tasks[i].progress let final = progress.completedUnitCount == progress.totalUnitCount /* progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil) */ let imageSource = progressReporter.tasks[i].imageSource let data = progressReporter.tasks[i].tempData CGImageSourceUpdateData(imageSource, data, final) var tranformedImage: UIImage? if let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) { /* let image = UIImage(CGImage: cgImage) if let imageTransform = progressReporter.tasks[i].imageTransform { tranformedImage = imageTransform(image) } */ let image = UIImage(CGImage: cgImage.yep_extendedCanvasCGImage) if progressReporter.totalProgress < 1 { let blurPercent = CGFloat(1 - progressReporter.totalProgress) let radius = 5 * blurPercent let iterations = UInt(10 * blurPercent) //println("radius: \(radius), iterations: \(iterations)") if let blurredImage = image.blurredImageWithRadius(radius, iterations: iterations, tintColor: UIColor.clearColor()) { if let imageTransform = progressReporter.tasks[i].imageTransform { tranformedImage = imageTransform(blurredImage) } } } } progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: tranformedImage) return final } } } return false } private func finishDownloadTask(downloadTask: NSURLSessionDataTask) { for i in 0..<progressReporters.count { for j in 0..<progressReporters[i].tasks.count { if downloadTask == progressReporters[i].tasks[j].downloadTask { let finishedAction = progressReporters[i].tasks[j].finishedAction let data = progressReporters[i].tasks[j].tempData finishedAction(data) progressReporters[i].finishedTasksCount += 1 // 若任务都已完成,移除此 progressReporter if progressReporters[i].finishedTasksCount == progressReporters[i].tasks.count { progressReporters.removeAtIndex(i) } return } } } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { //println("YepDownloader begin, expectedContentLength:\(response.expectedContentLength)") reportProgressAssociatedWithDownloadTask(dataTask, totalBytes: response.expectedContentLength) completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { //println("YepDownloader data.length: \(data.length)") let finish = reportProgressAssociatedWithDownloadTask(dataTask, didReceiveData: data) if finish { //println("YepDownloader finish") finishDownloadTask(dataTask) } } } /* extension YepDownloader: NSURLSessionDownloadDelegate { private func handleData(data: NSData, ofDownloadTask downloadTask: NSURLSessionDownloadTask) { for i in 0..<progressReporters.count { for j in 0..<progressReporters[i].tasks.count { if downloadTask == progressReporters[i].tasks[j].downloadTask { let finishedAction = progressReporters[i].tasks[j].finishedAction finishedAction(data) progressReporters[i].finishedTasksCount++ // 若任务都已完成,移除此 progressReporter if progressReporters[i].finishedTasksCount == progressReporters[i].tasks.count { progressReporters.removeAtIndex(i) } return } } } } private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDownloadTask, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { for progressReporter in progressReporters { for i in 0..<progressReporter.tasks.count { if downloadTask == progressReporter.tasks[i].downloadTask { progressReporter.tasks[i].progress.totalUnitCount = totalBytesExpectedToWrite progressReporter.tasks[i].progress.completedUnitCount = totalBytesWritten progressReporter.reportProgress?(progressReporter.totalProgress) return } } } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { guard let response = downloadTask.response as? NSHTTPURLResponse else { return } // 从 s3 下载附件,状态码以 200 为准(有可能 token 不对,返回数据就不是附件文件,或其它特殊情况) if response.statusCode == 200 { if let data = NSData(contentsOfURL: location) { handleData(data, ofDownloadTask: downloadTask) } } else { println("YepDownloader failed to download: \(downloadTask.originalRequest?.URL)") } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { reportProgressAssociatedWithDownloadTask(downloadTask, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } } */
mit
90dcbdf0ebeda967e77aa8d60b152037
37.551643
187
0.593801
6.425274
false
false
false
false
samsymons/Photon
Photon/Geometry/Sphere.swift
1
2291
// Sphere.swift // Copyright (c) 2017 Sam Symons // // 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 simd public final class Sphere: GeometricObject { public let center: Point3D public let radius: Float public var material: Material private var radiusSquared: Float { return radius * radius } public init(center: Point3D, radius: Float, material: Material) { self.center = center self.radius = radius self.material = material } // MARK: - Geometric Object public func intersection(with ray: Ray) -> Intersection { let vector = Vector3D(point: center - ray.origin) let tca = dot(vector, ray.direction) let d2 = dot(vector, vector) - tca * tca if d2 > radiusSquared { return Intersection.none } let thc = sqrt(radiusSquared - d2) var t0 = tca - thc var t1 = tca + thc if t0 > t1 { swap(&t0, &t1) } if t0 < 0 { t0 = t1 if t0 < 0 { return Intersection.none } } let t = t0 let hitPoint = ray.origin + (ray.direction * t) return Intersection(t: t, isHit: true, normal: normalize(Normal(point: hitPoint - center)), material: material, intersectionPoint: hitPoint, localIntersectionPoint: hitPoint) } }
mit
21957716ec7122ea105e7780bbb1dcd2
30.383562
178
0.701004
4.026362
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDK/IntroductionViewController.swift
1
3678
/* Copyright (c) 2015, Apple 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(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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. */ import UIKit public class IntroductionViewController: UIPageViewController, UIPageViewControllerDataSource { // MARK: Properties let pageViewControllers: [UIViewController] = { let introOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introOneViewController") let introTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introTwoViewController") let introThree = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introThreeViewController") return [introOne, introTwo, introThree] }() // MARK: UIViewController public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. dataSource = self setViewControllers([pageViewControllers[0]], direction: .Forward, animated: false, completion: nil) } // MARK: UIPageViewControllerDataSource public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let index = pageViewControllers.indexOf(viewController)! if index - 1 >= 0 { return pageViewControllers[index - 1] } return nil } public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let index = pageViewControllers.indexOf(viewController)! if index + 1 < pageViewControllers.count { return pageViewControllers[index + 1] } return nil } public func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return pageViewControllers.count } public func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } }
bsd-3-clause
a04f252fb5eaa17d356da7d9ae6f659a
42.785714
168
0.746873
5.684699
false
false
false
false
ben-ng/swift
benchmark/single-source/ArrayOfRef.swift
1
2350
//===--- ArrayOfRef.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This benchmark tests creation and destruction of an array of // references. It is meant to be a baseline for comparison against // ArrayOfGenericRef. // // For comparison, we always create four arrays of 10,000 words. protocol Constructible { associatedtype Element init(e:Element) } class ConstructibleArray<T:Constructible> { var array : [T] init(_ e:T.Element) { array = [T]() array.reserveCapacity(10_000) for _ in 0...10_000 { array.append(T(e:e) as T) } } } // Reference to a POD class. class POD : Constructible { typealias Element=Int var x: Int required init(e:Int) { self.x = e } } @inline(never) func genPODRefArray() { _ = ConstructibleArray<POD>(3) // should be a nop } class Dummy {} // Reference to a reference. The nested reference is shared across elements. class CommonRef : Constructible { typealias Element=Dummy var d: Dummy required init(e:Dummy) { self.d = e } } @inline(never) func genCommonRefArray() { let d = Dummy() _ = ConstructibleArray<CommonRef>(d) // should be a nop } enum RefEnum { case None case Some(Dummy) } // Reuse the same enum value for each element. class RefArray<T> { var array : [T] init(_ i:T, count:Int = 10_000) { array = [T](repeating: i, count: count) } } @inline(never) func genRefEnumArray() { let e = RefEnum.Some(Dummy()) _ = RefArray<RefEnum>(e) // should be a nop } // Struct holding a reference. struct S : Constructible { typealias Element=Dummy var d: Dummy init(e:Dummy) { self.d = e } } @inline(never) func genRefStructArray() { let d = Dummy() _ = ConstructibleArray<S>(d) // should be a nop } @inline(never) public func run_ArrayOfRef(_ N: Int) { for _ in 0...N { genPODRefArray() genCommonRefArray() genRefEnumArray() genRefStructArray() } }
apache-2.0
d18f689df8d0e40cf43755e3eed51a2a
20.962617
80
0.634043
3.507463
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Edit data/Update geometries (feature service)/EditGeometryViewController.swift
1
7629
// Copyright 2016 Esri. // // 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 UIKit import ArcGIS class EditGeometryViewController: UIViewController, AGSGeoViewTouchDelegate, AGSCalloutDelegate { @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISOceans) mapView.sketchEditor = sketchEditor // Set touch delegate on map view as self. mapView.touchDelegate = self mapView.callout.delegate = self } } @IBOutlet var toolbar: UIToolbar! @IBOutlet var toolbarBottomConstraint: NSLayoutConstraint! /// The feature table to update features geometries. var featureTable: AGSServiceFeatureTable! /// The service geodatabase that contains damaged property features. var serviceGeodatabase: AGSServiceGeodatabase! /// The feature layer created from the feature table. var featureLayer: AGSFeatureLayer! /// Last identify operation. var lastQuery: AGSCancelable! /// The currently selected feature. var selectedFeature: AGSFeature! /// The sketch editor on the map view. let sketchEditor = AGSSketchEditor() override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["EditGeometryViewController"] // Load the service geodatabase. let damageFeatureService = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer")! loadServiceGeodatabase(from: damageFeatureService) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Default state for toolbar is hidden. setToolbarVisibility(visible: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if sketchEditor.isStarted, let feature = selectedFeature { // Make the feature visible when sketch editor is started. featureLayer.setFeature(feature, visible: true) // Stop sketch editor. sketchEditor.stop() } setToolbarVisibility(visible: false) } /// Load and set a service geodatabase from a feature service URL. /// - Parameter serviceURL: The URL to the feature service. func loadServiceGeodatabase(from serviceURL: URL) { let serviceGeodatabase = AGSServiceGeodatabase(url: serviceURL) serviceGeodatabase.load { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } else { let featureTable = serviceGeodatabase.table(withLayerID: 0)! self.featureTable = featureTable self.serviceGeodatabase = serviceGeodatabase // Add the feature layer to the operational layers on map. let featureLayer = AGSFeatureLayer(featureTable: featureTable) self.featureLayer = featureLayer self.mapView.map?.operationalLayers.add(featureLayer) self.mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: -9030446.96, y: 943791.32, spatialReference: .webMercator()), scale: 2e6)) } } } func setToolbarVisibility(visible: Bool) { toolbarBottomConstraint.constant = visible ? 0 : -toolbar.frame.height - view.safeAreaInsets.bottom UIView.animate(withDuration: 0.3) { [weak self] in self?.view.layoutIfNeeded() } } /// Apply local edits to the geodatabase. func applyEdits() { guard serviceGeodatabase.hasLocalEdits() else { return } serviceGeodatabase.applyEdits { [weak self] (featureTableEditResults: [AGSFeatureTableEditResult]?, error: Error?) in guard let self = self else { return } if let featureTableEditResults = featureTableEditResults, featureTableEditResults.first?.editResults.first?.completedWithErrors == false { self.featureLayer.setFeature(self.selectedFeature, visible: true) } else if let error = error { self.presentAlert(message: "Error while applying edits: \(error.localizedDescription)") } } } func showCallout(for feature: AGSFeature, at tapLocation: AGSPoint?) { let title = feature.attributes["typdamage"] as! String mapView.callout.title = title mapView.callout.show(for: feature, tapLocation: tapLocation, animated: true) } // MARK: - AGSGeoViewTouchDelegate func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { if let query = lastQuery { query.cancel() } // Hide the callout. mapView.callout.dismiss() lastQuery = mapView.identifyLayer(featureLayer, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false) { [weak self] identifyLayerResult in guard let self = self else { return } self.lastQuery = nil if let feature = identifyLayerResult.geoElements.first as? AGSFeature { // Show callout for the feature. self.showCallout(for: feature, at: mapPoint) // Update selected feature. self.selectedFeature = feature } else if let error = identifyLayerResult.error { self.presentAlert(error: error) } } } // MARK: - AGSCalloutDelegate func didTapAccessoryButton(for callout: AGSCallout) { guard let point = selectedFeature.geometry as? AGSPoint else { return } // Hide the callout. mapView.callout.dismiss() // Start the sketch editor with selected feature's geometry to start // tracking user gesture. sketchEditor.start(with: point) // Show the toolbar. setToolbarVisibility(visible: true) // Hide the feature for time being. featureLayer.setFeature(selectedFeature, visible: false) } // MARK: - Actions @IBAction func doneAction() { if let newGeometry = sketchEditor.geometry { selectedFeature.geometry = newGeometry featureTable.update(selectedFeature) { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) // Make the feature visible due to unsuccessful update. self.featureLayer.setFeature(self.selectedFeature, visible: true) } else { // Apply edits. self.applyEdits() } } } // Hide toolbar. setToolbarVisibility(visible: false) // Stop and clear sketch editor. sketchEditor.stop() } }
apache-2.0
8ae1e893ecbf16e6d51f3e5ca5936138
41.149171
158
0.639664
4.865434
false
false
false
false
aslanyanhaik/Quick-Chat
QuickChat/Presenter/Conversations/ConversationCell.swift
1
2718
// MIT License // Copyright (c) 2019 Haik Aslanyan // 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 ConversationCell: UITableViewCell { //MARK: IBOutlets @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! //MARK: Private properties let userID = UserManager().currentUserID() ?? "" //MARK: Public methods func set(_ conversation: ObjectConversation) { timeLabel.text = DateService.shared.format(Date(timeIntervalSince1970: TimeInterval(conversation.timestamp))) messageLabel.text = conversation.lastMessage guard let id = conversation.userIDs.filter({$0 != userID}).first else { return } let isRead = conversation.isRead[userID] ?? true if !isRead { nameLabel.font = nameLabel.font.bold messageLabel.font = messageLabel.font.bold messageLabel.textColor = ThemeService.purpleColor timeLabel.font = timeLabel.font.bold } ProfileManager.shared.userData(id: id) {[weak self] profile in self?.nameLabel.text = profile?.name guard let urlString = profile?.profilePicLink else { self?.profilePic.image = UIImage(named: "profile pic") return } self?.profilePic.setImage(url: URL(string: urlString)) } } //MARK: Lifecycle override func prepareForReuse() { super.prepareForReuse() profilePic.cancelDownload() nameLabel.font = nameLabel.font.regular messageLabel.font = messageLabel.font.regular timeLabel.font = timeLabel.font.regular messageLabel.textColor = .gray messageLabel.text = nil } }
mit
769b06928c4a58f6c28cb9e91b5ed481
38.391304
113
0.728109
4.545151
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/USXStyle.swift
1
7289
// // USXStyle.swift // TranslationEditor // // Created by Mikko Hilpinen on 4.10.2016. // Copyright © 2017 SIL. All rights reserved. // import Foundation // This is a common protocol between all USX style definitions. // The style should be convertable to and from a string protocol USXStyle { var code: String {get} //static func value(of code: String) -> USXStyle? } // Should accept styles which are not recognised enum CharStyle: USXStyle, Equatable { case quotation// = "qt" case keyTerm// = "k" case footNoteOriginReference case crossReferenceOriginReference case notesText case other(code: String) // TODO: Keep updated and create a unit test static let values: [CharStyle] = [.quotation, .keyTerm, .footNoteOriginReference, .crossReferenceOriginReference, .notesText] // IMPLEMENTED METHODS ------------- var code: String { switch self { case .quotation: return "qt" case .keyTerm: return "k" case .footNoteOriginReference: return "fr" case .crossReferenceOriginReference: return "xo" case .notesText: return "ft" case .other(let code): return code } } static func ==(_ left: CharStyle, _ right: CharStyle) -> Bool { return left.code == right.code } // OTHER METHODS ----------------- static func of(_ code: String) -> CharStyle { for value in values { if value.code == code { return value } } return other(code: code) } } enum FootNoteStyle: String, USXStyle { case footNote = "f" case endNote = "fe" case studyNote = "ef" var code: String { return rawValue } } enum CrossReferenceStyle: String, USXStyle { case crossReference = "x" case studyCrossReference = "ex" var code: String { return rawValue } } enum ParaStyle: USXStyle, Equatable { // Paragraph styles case normal case margin case embeddedTextOpening case embeddedTextParagraph case embeddedTextClosing case embeddedTextRefrain case indented(Int) case indentedFlushLeft case closureOfLetter case listItem(Int) case centered case liturgicalNote // Heading and title styles case sectionHeading(Int) case sectionHeadingMajor(Int) case speakerIdentification // Reference ranges / heading references case sectionReferenceRangeMajor case sectionReferenceRange case parallerReferenceRange case descriptiveTitle // Poetry case poeticLine(Int) case poeticLineRight case poeticLineCentered case acrosticHeading case embeddedTextPoeticLine(Int) case blank // Other case other(String) // Style collections private static let nonIndentedHeaderStyles: [ParaStyle] = [.speakerIdentification, .acrosticHeading] private static let nonIndentedParagraphStyles: [ParaStyle] = [.normal, .margin, .embeddedTextOpening, .embeddedTextParagraph, .embeddedTextClosing, .embeddedTextRefrain, .indentedFlushLeft, .closureOfLetter, .centered] private static let nonIndentedStyles: [ParaStyle] = [.descriptiveTitle, .sectionReferenceRange, .sectionReferenceRangeMajor, .liturgicalNote, .poeticLineRight, .poeticLineCentered, .blank] + nonIndentedHeaderStyles + nonIndentedParagraphStyles private static func indentedHeaderStyles(with indentation: Int) -> [ParaStyle] { return [.sectionHeading(indentation), sectionHeadingMajor(indentation)] } private static func indentedParagraphStyles(with indentation: Int) -> [ParaStyle] { return [.indented(indentation), .embeddedTextPoeticLine(indentation)] } private static func indentedStyles(with indentation: Int) -> [ParaStyle] { let otherIndented: [ParaStyle] = [.listItem(indentation), .poeticLine(indentation)] return otherIndented + (indentedHeaderStyles(with: indentation) + indentedParagraphStyles(with: indentation)) } private static func styles(_ indentation: Int) -> [ParaStyle] { return nonIndentedStyles + indentedStyles(with: indentation) } // OPERATORS ----- static func == (left: ParaStyle, right: ParaStyle) -> Bool { return left.code == right.code } // USX STYLE ----- var code: String { switch self { case .normal: return "p" case .margin: return "m" case .embeddedTextOpening: return "pmo" case .embeddedTextParagraph: return "pm" case .embeddedTextClosing: return "pmc" case .embeddedTextRefrain: return "pmr" case .indented(let depth): return "pi\(depth)" case .indentedFlushLeft: return "mi" case .closureOfLetter: return "cls" case .listItem(let depth): return "li\(depth)" case .centered: return "pc" case .liturgicalNote: return "lit" case .sectionHeadingMajor(let depth): return "ms\(depth)" case .sectionHeading(let depth): return "s\(depth)" case .sectionReferenceRangeMajor: return "mr" case .sectionReferenceRange: return "sr" case .parallerReferenceRange: return "r" case .descriptiveTitle: return "d" case .speakerIdentification: return "sp" case .poeticLine(let depth): return "q\(depth)" case .poeticLineRight: return "qr" case .poeticLineCentered: return "qc" case .acrosticHeading: return "qa" case .embeddedTextPoeticLine(let depth): return "qm\(depth)" case .blank: return "b" case .other(let code): return code } } static func value(of code: String) -> ParaStyle { // Parses the possible indentation level from the code // First must find out how many digits there are at the end of the string var lastDigitIndex = -1 let nsCode = code as NSString for index in stride(from: nsCode.length - 1, through: 0, by: -1) { if code.digit(at: index) == nil { break } else { lastDigitIndex = index } } // The process is a bit different if there is an indentation number at the end of the code if lastDigitIndex >= 0 { guard let indentation = code.digit(at: NSMakeRange(lastDigitIndex, nsCode.length - lastDigitIndex)) else { fatalError("failed to parse indentation from code: \(code)") } for indentedStyle in indentedStyles(with: indentation) { if indentedStyle.code == code { return indentedStyle } } } else { for nonIndentedStyle in nonIndentedStyles { if nonIndentedStyle.code == code { return nonIndentedStyle } } // A non-existing number may also be interpreted as 1 for indentedStyle in indentedStyles(with: 1) { if indentedStyle.code == code + "1" { return indentedStyle } } } // If no other style could be parsed, the wild card 'other' is used return other(code) } // OTHER ------- // TODO: Keep these updated func isSectionHeadingStyle() -> Bool { switch self { case .sectionHeading, .sectionHeadingMajor: return true default: return false } } func isHeaderStyle() -> Bool { switch self { case .sectionHeading, .sectionHeadingMajor, .speakerIdentification, .acrosticHeading: return true default: return false } } func isHeaderDescriptionStyle() -> Bool { switch self { case .descriptiveTitle, .sectionReferenceRange, .sectionReferenceRangeMajor: return true default: return false } } func isParagraphStyle() -> Bool { switch self { case .normal, .margin, .embeddedTextOpening, .embeddedTextParagraph, .embeddedTextClosing, .embeddedTextRefrain, .indentedFlushLeft, .closureOfLetter, .centered, .indented, .embeddedTextPoeticLine: return true default: return false } } }
mit
73c2971709fcec9844120a93ac72f462
23.705085
244
0.715148
3.404017
false
false
false
false
Mazy-ma/DemoBySwift
Solive/Solive/Tools/PageScrollView/PageScrollView.swift
1
1987
// // PageScrollView.swift // Solive // // Created by Mazy on 2017/8/29. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class PageScrollView: UIView { fileprivate var topTitlesView: PageTitleView! fileprivate var contentView: PageContentView! fileprivate var titles: [String] fileprivate var childVC: [AnchorViewController] fileprivate var parentVC: UIViewController init(frame: CGRect, titles: [String], childVC: [AnchorViewController], parentVC: UIViewController) { self.titles = titles self.childVC = childVC self.parentVC = parentVC super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private extension PageScrollView { func setupUI() { topTitlesView = PageTitleView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kNaviHeight), titles: titles) topTitlesView.delegate = self addSubview(topTitlesView) let contentRect = CGRect(x: 0, y: topTitlesView.frame.maxY, width: kScreenW, height: bounds.height-topTitlesView.bounds.height) contentView = PageContentView(frame: contentRect, childVC: childVC, parentVC: parentVC) contentView.delegate = self addSubview(contentView) } } extension PageScrollView: PageTitleViewDelegate { func titleView(_ titleView: PageTitleView, selectedIndex index: Int) { contentView.setCurrentIndex(index) } } extension PageScrollView: PageContentViewDelegate { func contentViewEndScroll(_ contentView: PageContentView) { topTitlesView.contentViewDidEndScroll() } func contentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { topTitlesView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
apache-2.0
5021e2ec3b472c08f02552b93ca6efc1
27.342857
135
0.68246
4.923077
false
false
false
false
treejames/firefox-ios
Account/FxAClient10.swift
3
14932
/* 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 Alamofire import Shared import Foundation import FxA public let FxAClientErrorDomain = "org.mozilla.fxa.error" public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) let KeyLength: Int = 32 public struct FxALoginResponse { public let remoteEmail: String public let uid: String public let verified: Bool public let sessionToken: NSData public let keyFetchToken: NSData init(remoteEmail: String, uid: String, verified: Bool, sessionToken: NSData, keyFetchToken: NSData) { self.remoteEmail = remoteEmail self.uid = uid self.verified = verified self.sessionToken = sessionToken self.keyFetchToken = keyFetchToken } } public struct FxAKeysResponse { let kA: NSData let wrapkB: NSData init(kA: NSData, wrapkB: NSData) { self.kA = kA self.wrapkB = wrapkB } } public struct FxASignResponse { public let certificate: String init(certificate: String) { self.certificate = certificate } } // fxa-auth-server produces error details like: // { // "code": 400, // matches the HTTP status code // "errno": 107, // stable application-level error number // "error": "Bad Request", // string description of the error type // "message": "the value of salt is not allowed to be undefined", // "info": "https://docs.dev.lcip.og/errors/1234" // link to more info on the error // } public enum FxAClientError { case Remote(RemoteError) case Local(NSError) } // Be aware that string interpolation doesn't work: rdar://17318018, much good that it will do. extension FxAClientError: Printable, ErrorType { public var description: String { switch self { case let .Remote(error): let errorString = error.error ?? NSLocalizedString("Missing error", comment: "Error for a missing remote error number") let messageString = error.message ?? NSLocalizedString("Missing message", comment: "Error for a missing remote error message") return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>" case let .Local(error): return "<FxAClientError.Local \(error.description)>" } } } public struct RemoteError { let code: Int32 let errno: Int32 let error: String? let message: String? let info: String? var isUpgradeRequired: Bool { return errno == 116 // ENDPOINT_IS_NO_LONGER_SUPPORTED || errno == 117 // INCORRECT_LOGIN_METHOD_FOR_THIS_ACCOUNT || errno == 118 // INCORRECT_KEY_RETRIEVAL_METHOD_FOR_THIS_ACCOUNT || errno == 119 // INCORRECT_API_VERSION_FOR_THIS_ACCOUNT } var isInvalidAuthentication: Bool { return code == 401 } var isUnverified: Bool { return errno == 104 // ATTEMPT_TO_OPERATE_ON_AN_UNVERIFIED_ACCOUNT } } public class FxAClient10 { let URL: NSURL public init(endpoint: NSURL? = nil) { self.URL = endpoint ?? ProductionFirefoxAccountConfiguration().authEndpointURL } public class func KW(kw: String) -> NSData? { return ("identity.mozilla.com/picl/v1/" + kw).utf8EncodedData } /** * The token server accepts an X-Client-State header, which is the * lowercase-hex-encoded first 16 bytes of the SHA-256 hash of the * bytes of kB. */ public class func computeClientState(kB: NSData) -> String? { if kB.length != 32 { return nil } return kB.sha256.subdataWithRange(NSRange(location: 0, length: 16)).hexEncodedString } public class func quickStretchPW(email: NSData, password: NSData) -> NSData { let salt: NSMutableData = NSMutableData(data: KW("quickStretch")!) salt.appendData(":".utf8EncodedData!) salt.appendData(email) return password.derivePBKDF2HMACSHA256KeyWithSalt(salt, iterations: 1000, length: 32) } public class func computeUnwrapKey(stretchedPW: NSData) -> NSData { let salt: NSData = NSData() let contextInfo: NSData = KW("unwrapBkey")! let bytes = stretchedPW.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: UInt(KeyLength)) return bytes } private class func remoteErrorFromJSON(json: JSON, statusCode: Int) -> RemoteError? { if json.isError { return nil } if 200 <= statusCode && statusCode <= 299 { return nil } if let code = json["code"].asInt32 { if let errno = json["errno"].asInt32 { return RemoteError(code: code, errno: errno, error: json["error"].asString, message: json["message"].asString, info: json["info"].asString) } } return nil } private class func loginResponseFromJSON(json: JSON) -> FxALoginResponse? { if json.isError { return nil } if let uid = json["uid"].asString { if let verified = json["verified"].asBool { if let sessionToken = json["sessionToken"].asString { if let keyFetchToken = json["keyFetchToken"].asString { return FxALoginResponse(remoteEmail: "", uid: uid, verified: verified, sessionToken: sessionToken.hexDecodedData, keyFetchToken: keyFetchToken.hexDecodedData) } } } } return nil } private class func keysResponseFromJSON(keyRequestKey: NSData, json: JSON) -> FxAKeysResponse? { if json.isError { return nil } if let bundle = json["bundle"].asString { let data = bundle.hexDecodedData if data.length != 3 * KeyLength { return nil } let ciphertext = data.subdataWithRange(NSMakeRange(0 * KeyLength, 2 * KeyLength)) let MAC = data.subdataWithRange(NSMakeRange(2 * KeyLength, 1 * KeyLength)) let salt: NSData = NSData() let contextInfo: NSData = KW("account/keys")! let bytes = keyRequestKey.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: UInt(3 * KeyLength)) let respHMACKey = bytes.subdataWithRange(NSMakeRange(0 * KeyLength, 1 * KeyLength)) let respXORKey = bytes.subdataWithRange(NSMakeRange(1 * KeyLength, 2 * KeyLength)) if ciphertext.hmacSha256WithKey(respHMACKey) != MAC { NSLog("Bad HMAC in /keys response!") return nil } if let xoredBytes = ciphertext.xoredWith(respXORKey) { let kA = xoredBytes.subdataWithRange(NSMakeRange(0 * KeyLength, 1 * KeyLength)) let wrapkB = xoredBytes.subdataWithRange(NSMakeRange(1 * KeyLength, 1 * KeyLength)) return FxAKeysResponse(kA: kA, wrapkB: wrapkB) } } return nil } private class func signResponseFromJSON(json: JSON) -> FxASignResponse? { if json.isError { return nil } if let cert = json["cert"].asString { return FxASignResponse(certificate: cert) } return nil } lazy private var alamofire: Alamofire.Manager = { let ua = UserAgent.fxaUserAgent let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() return Alamofire.Manager.managerWithUserAgent(ua, configuration: configuration) }() public func login(emailUTF8: NSData, quickStretchedPW: NSData, getKeys: Bool) -> Deferred<Result<FxALoginResponse>> { let deferred = Deferred<Result<FxALoginResponse>>() let authPW = quickStretchedPW.deriveHKDFSHA256KeyWithSalt(NSData(), contextInfo: FxAClient10.KW("authPW")!, length: 32) let parameters = [ "email": NSString(data: emailUTF8, encoding: NSUTF8StringEncoding)!, "authPW": authPW.base16EncodedStringWithOptions(NSDataBase16EncodingOptions.LowerCase), ] var URL: NSURL = self.URL.URLByAppendingPathComponent("/account/login") if getKeys { let components = NSURLComponents(URL: self.URL.URLByAppendingPathComponent("/account/login"), resolvingAgainstBaseURL: false)! components.query = "keys=true" URL = components.URL! } let mutableURLRequest = NSMutableURLRequest(URL: URL) mutableURLRequest.HTTPMethod = Method.POST.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = JSON(parameters).toString(pretty: false).utf8EncodedData let request = alamofire.request(mutableURLRequest) .validate(contentType: ["application/json"]) .responseJSON { (request, response, data, error) in if let error = error { deferred.fill(Result(failure: FxAClientError.Local(error))) return } if let data: AnyObject = data { // Declaring the type quiets a Swift warning about inferring AnyObject. let json = JSON(data) if let remoteError = FxAClient10.remoteErrorFromJSON(json, statusCode: response!.statusCode) { deferred.fill(Result(failure: FxAClientError.Remote(remoteError))) return } if let response = FxAClient10.loginResponseFromJSON(json) { deferred.fill(Result(success: response)) return } } deferred.fill(Result(failure: FxAClientError.Local(FxAClientUnknownError))) } return deferred } public func keys(keyFetchToken: NSData) -> Deferred<Result<FxAKeysResponse>> { let deferred = Deferred<Result<FxAKeysResponse>>() let salt: NSData = NSData() let contextInfo: NSData = FxAClient10.KW("keyFetchToken")! let bytes = keyFetchToken.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: UInt(3 * KeyLength)) let tokenId = bytes.subdataWithRange(NSMakeRange(0 * KeyLength, KeyLength)) let reqHMACKey = bytes.subdataWithRange(NSMakeRange(1 * KeyLength, KeyLength)) let keyRequestKey = bytes.subdataWithRange(NSMakeRange(2 * KeyLength, KeyLength)) let hawkHelper = HawkHelper(id: tokenId.hexEncodedString, key: reqHMACKey) let URL = self.URL.URLByAppendingPathComponent("/account/keys") let mutableURLRequest = NSMutableURLRequest(URL: URL) mutableURLRequest.HTTPMethod = Method.GET.rawValue let hawkValue = hawkHelper.getAuthorizationValueFor(mutableURLRequest) mutableURLRequest.setValue(hawkValue, forHTTPHeaderField: "Authorization") alamofire.request(mutableURLRequest) .validate(contentType: ["application/json"]) .responseJSON { (request, response, data, error) in if let error = error { deferred.fill(Result(failure: FxAClientError.Local(error))) return } if let data: AnyObject = data { // Declaring the type quiets a Swift warning about inferring AnyObject. let json = JSON(data) if let remoteError = FxAClient10.remoteErrorFromJSON(json, statusCode: response!.statusCode) { deferred.fill(Result(failure: FxAClientError.Remote(remoteError))) return } if let response = FxAClient10.keysResponseFromJSON(keyRequestKey, json: json) { deferred.fill(Result(success: response)) return } } deferred.fill(Result(failure: FxAClientError.Local(FxAClientUnknownError))) } return deferred } public func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Result<FxASignResponse>> { let deferred = Deferred<Result<FxASignResponse>>() let parameters = [ "publicKey": publicKey.JSONRepresentation(), "duration": NSNumber(unsignedLongLong: OneDayInMilliseconds), // The maximum the server will allow. ] let salt: NSData = NSData() let contextInfo: NSData = FxAClient10.KW("sessionToken")! let bytes = sessionToken.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: UInt(2 * KeyLength)) let tokenId = bytes.subdataWithRange(NSMakeRange(0 * KeyLength, KeyLength)) let reqHMACKey = bytes.subdataWithRange(NSMakeRange(1 * KeyLength, KeyLength)) let hawkHelper = HawkHelper(id: tokenId.hexEncodedString, key: reqHMACKey) let URL = self.URL.URLByAppendingPathComponent("/certificate/sign") let mutableURLRequest = NSMutableURLRequest(URL: URL) mutableURLRequest.HTTPMethod = Method.POST.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = JSON(parameters).toString(pretty: false).utf8EncodedData let hawkValue = hawkHelper.getAuthorizationValueFor(mutableURLRequest) mutableURLRequest.setValue(hawkValue, forHTTPHeaderField: "Authorization") alamofire.request(mutableURLRequest) .validate(contentType: ["application/json"]) .responseJSON { (request, response, data, error) in if let error = error { deferred.fill(Result(failure: FxAClientError.Local(error))) return } if let data: AnyObject = data { // Declaring the type quiets a Swift warning about inferring AnyObject. let json = JSON(data) if let remoteError = FxAClient10.remoteErrorFromJSON(json, statusCode: response!.statusCode) { deferred.fill(Result(failure: FxAClientError.Remote(remoteError))) return } if let response = FxAClient10.signResponseFromJSON(json) { deferred.fill(Result(success: response)) return } } deferred.fill(Result(failure: FxAClientError.Local(FxAClientUnknownError))) } return deferred } }
mpl-2.0
8882fba229f699d26de020ff2d6cceee
40.248619
138
0.621082
4.964096
false
false
false
false
treejames/firefox-ios
Sync/Synchronizers/HistorySynchronizer.swift
3
8678
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger private let HistoryTTLInSeconds = 5184000 // 60 days. private let HistoryStorageVersion = 1 func makeDeletedHistoryRecord(guid: GUID) -> Record<HistoryPayload> { // Local modified time is ignored in upload serialization. let modified: Timestamp = 0 // Sortindex for history is frecency. Make deleted items more frecent than almost // anything. let sortindex = 5_000_000 let ttl = HistoryTTLInSeconds let json: JSON = JSON([ "id": guid, "deleted": true, ]) let payload = HistoryPayload(json) return Record<HistoryPayload>(id: guid, payload: payload, modified: modified, sortindex: sortindex, ttl: ttl) } func makeHistoryRecord(place: Place, visits: [Visit]) -> Record<HistoryPayload> { let id = place.guid let modified: Timestamp = 0 // Ignored in upload serialization. let sortindex = 1 // TODO: frecency! let ttl = HistoryTTLInSeconds let json: JSON = JSON([ "id": id, "visits": visits.map { $0.toJSON() }, "histUri": place.url, "title": place.title, ]) let payload = HistoryPayload(json) return Record<HistoryPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex, ttl: ttl) } public class HistorySynchronizer: IndependentRecordSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "history") } override var storageVersion: Int { return HistoryStorageVersion } private func mask(maxFailures: Int) -> Result<()> -> Success { var failures = 0 return { result in if result.isSuccess { return Deferred(value: result) } if ++failures > maxFailures { return Deferred(value: result) } log.debug("Masking failure \(failures).") return succeed() } } // TODO: this function should establish a transaction at suitable points. // TODO: a much more efficient way to do this is to: // 1. Start a transaction. // 2. Try to update each place. Note failures. // 3. bulkInsert all failed updates in one go. // 4. Store all remote visits for all places in one go, constructing a single sequence of visits. func applyIncomingToStorage(storage: SyncableHistory, records: [Record<HistoryPayload>], fetched: Timestamp) -> Success { // Skip over at most this many failing records before aborting the sync. let maskSomeFailures = self.mask(3) // TODO: it'd be nice to put this in an extension on SyncableHistory. Waiting for Swift 2.0... func applyRecord(rec: Record<HistoryPayload>) -> Success { let guid = rec.id let payload = rec.payload let modified = rec.modified // We apply deletions immediately. Yes, this will throw away local visits // that haven't yet been synced. That's how Sync works, alas. if payload.deleted { return storage.deleteByGUID(guid, deletedAt: modified).bind(maskSomeFailures) } // It's safe to apply other remote records, too -- even if we re-download, we know // from our local cached server timestamp on each record that we've already seen it. // We have to reconcile on-the-fly: we're about to overwrite the server record, which // is our shared parent. let place = rec.payload.asPlace() if isIgnoredURL(place.url) { log.debug("Ignoring incoming record \(guid) because its URL is one we wish to ignore.") return succeed() } let placeThenVisits = storage.insertOrUpdatePlace(place, modified: modified) >>> { storage.storeRemoteVisits(payload.visits, forGUID: guid) } return placeThenVisits.map({ result in if result.isFailure { let reason = result.failureValue?.description ?? "unknown reason" log.error("Record application failed: \(reason)") } return result }).bind(maskSomeFailures) } return self.applyIncomingToStorage(records, fetched: fetched, apply: applyRecord) } private func uploadModifiedPlaces(places: [(Place, [Visit])], lastTimestamp: Timestamp, fromStorage storage: SyncableHistory, withServer storageClient: Sync15CollectionClient<HistoryPayload>) -> DeferredTimestamp { return self.uploadRecords(places.map(makeHistoryRecord), by: 50, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsSynchronized($0, modified: $1) }) } private func uploadDeletedPlaces(guids: [GUID], lastTimestamp: Timestamp, fromStorage storage: SyncableHistory, withServer storageClient: Sync15CollectionClient<HistoryPayload>) -> DeferredTimestamp { let records = guids.map(makeDeletedHistoryRecord) // Deletions are smaller, so upload 100 at a time. return self.uploadRecords(records, by: 100, lastTimestamp: lastTimestamp, storageClient: storageClient, onUpload: { storage.markAsDeleted($0) >>> always($1) }) } private func uploadOutgoingFromStorage(storage: SyncableHistory, lastTimestamp: Timestamp, withServer storageClient: Sync15CollectionClient<HistoryPayload>) -> Success { let uploadDeleted: Timestamp -> DeferredTimestamp = { timestamp in storage.getDeletedHistoryToUpload() >>== { guids in return self.uploadDeletedPlaces(guids, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient) } } let uploadModified: Timestamp -> DeferredTimestamp = { timestamp in storage.getModifiedHistoryToUpload() >>== { places in return self.uploadModifiedPlaces(places, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient) } } return deferResult(lastTimestamp) >>== uploadDeleted >>== uploadModified >>> effect({ log.debug("Done syncing.") }) >>> succeed } public func synchronizeLocalHistory(history: SyncableHistory, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { if let reason = self.reasonToNotSync(storageClient) { return deferResult(.NotStarted(reason)) } let encoder = RecordEncoder<HistoryPayload>(decode: { HistoryPayload($0) }, encode: { $0 }) if let historyClient = self.collectionClient(encoder, storageClient: storageClient) { let since: Timestamp = self.lastFetched log.debug("Synchronizing \(self.collection). Last fetched: \(since).") // TODO: buffer downloaded records, fetching incrementally, so that we can separate // the network fetch from record application. let applyIncomingToStorage: StorageResponse<[Record<HistoryPayload>]> -> Success = { response in let ts = response.metadata.timestampMilliseconds let lm = response.metadata.lastModifiedMilliseconds! log.debug("Applying incoming history records from response timestamped \(ts), last modified \(lm).") log.debug("Records header hint: \(response.metadata.records)") return self.applyIncomingToStorage(history, records: response.value, fetched: lm) } return historyClient.getSince(since) >>== applyIncomingToStorage // TODO: If we fetch sorted by date, we can bump the lastFetched timestamp // to the last successfully applied record timestamp, no matter where we fail. // There's no need to do the upload before bumping -- the storage of local changes is stable. >>> { self.uploadOutgoingFromStorage(history, lastTimestamp: 0, withServer: historyClient) } >>> { return deferResult(.Completed) } } log.error("Couldn't make history factory.") return deferResult(FatalError(message: "Couldn't make history factory.")) } }
mpl-2.0
d80fb8214cc2b1111270e0993033b892
45.159574
218
0.649113
5.016185
false
false
false
false
rchatham/CoordinatorType
CoordinatorType-macOS/TabCoordinatorType.swift
1
1206
// // TabCoordinatorType.swift // CoordinatorType // // Created by Reid Chatham on 2/26/17. // // import Cocoa public protocol TabCoordinatorType: CoordinatorType { weak var tabController: NSTabViewController? { get set } func rootViewControllers() -> [NSViewController] } extension TabCoordinatorType { public func tabController() -> NSTabViewController { return viewController() as! NSTabViewController } public func viewController() -> NSViewController { let tab = NSTabViewController() start(onTabController: tab) return tab } public func start(onViewController viewController: NSViewController, animated: Bool) { if let tab = viewController as? NSTabViewController { start(onTabController: tab) } else { let tab = NSTabViewController() start(onTabController: tab) viewController.presentViewControllerAsSheet(tab) } } private func start(onTabController tabController: NSTabViewController) { let roots = rootViewControllers() tabController.childViewControllers = roots self.tabController = tabController } }
mit
68cbecd281076ce49239123cd0a8a183
26.409091
90
0.669983
5.457014
false
false
false
false
lorentey/swift
test/Parse/subscripting.swift
6
4556
// RUN: %target-typecheck-verify-swift struct X { } // expected-note {{did you mean}} // Simple examples struct X1 { var stored: Int subscript(i: Int) -> Int { get { return stored } mutating set { stored = newValue } } } struct X2 { var stored: Int subscript(i: Int) -> Int { get { return stored + i } set(v) { stored = v - i } } } struct X3 { var stored: Int subscript(_: Int) -> Int { get { return stored } set(v) { stored = v } } } struct X4 { var stored: Int subscript(i: Int, j: Int) -> Int { get { return stored + i + j } mutating set(v) { stored = v + i - j } } } struct X5 { static var stored: Int = 1 static subscript(i: Int) -> Int { get { return stored + i } set { stored = newValue - i } } } class X6 { static var stored: Int = 1 class subscript(i: Int) -> Int { get { return stored + i } set { stored = newValue - i } } } struct Y1 { var stored: Int subscript(_: i, j: Int) -> Int { // expected-error {{use of undeclared type 'i'}} get { return stored + j } set { stored = j } } } // Mutating getters on constants (https://bugs.swift.org/browse/SR-845) struct Y2 { subscript(_: Int) -> Int { mutating get { return 0 } } } let y2 = Y2() // expected-note{{change 'let' to 'var' to make it mutable}}{{1-4=var}} _ = y2[0] // expected-error{{cannot use mutating getter on immutable value: 'y2' is a 'let' constant}} // Parsing errors struct A0 { subscript // expected-error {{expected '(' for subscript parameters}} i : Int -> Int { get { return stored } set { stored = value } } subscript -> Int { // expected-error {{expected '(' for subscript parameters}} {{12-12=()}} return 1 } } struct A1 { subscript (i : Int) // expected-error{{expected '->' for subscript element type}} Int { get { return stored // expected-error{{use of unresolved identifier}} } set { stored = newValue// expected-error{{use of unresolved identifier}} } } } struct A2 { subscript (i : Int) -> // expected-error{{expected subscripting element type}} { get { return stored } set { stored = newValue // expected-error{{use of unresolved identifier}} } } } struct A3 { subscript(i : Int) // expected-error {{expected '->' for subscript element type}} // expected-error@-1 {{expected subscripting element type}} { get { return i } } } struct A4 { subscript(i : Int) { // expected-error {{expected '->' for subscript element type}} // expected-error@-1 {{expected subscripting element type}} get { return i } } } struct A5 { subscript(i : Int) -> Int // expected-error {{expected '{' in subscript to specify getter and setter implementation}} } struct A6 { subscript(i: Int)(j: Int) -> Int { // expected-error {{expected '->' for subscript element type}} // expected-error@-1 {{function types cannot have argument labels}} // expected-note@-2 {{did you mean}} get { return i + j // expected-error {{use of unresolved identifier}} } } } struct A7 { class subscript(a: Float) -> Int { // expected-error {{class subscripts are only allowed within classes; use 'static' to declare a static subscript}} {{3-8=static}} get { return 42 } } } class A7b { class static subscript(a: Float) -> Int { // expected-error {{'static' cannot appear after another 'static' or 'class' keyword}} {{9-16=}} get { return 42 } } } struct A8 { subscript(i : Int) -> Int // expected-error{{expected '{' in subscript to specify getter and setter implementation}} get { return stored } set { stored = value } } struct A9 { subscript x() -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}} return 0 } } struct A10 { subscript x(i: Int) -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}} return 0 } subscript x<T>(i: T) -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}} return 0 } } struct A11 { subscript x y : Int -> Int { // expected-error {{expected '(' for subscript parameters}} return 0 } } } // expected-error{{extraneous '}' at top level}} {{1-3=}}
apache-2.0
708560f00ea4772b655c2d465acda125
18.808696
166
0.557946
3.659438
false
false
false
false
xiabob/ZhiHuDaily
ZhiHuDaily/ZhiHuDaily/DataSource/GetNewsDetail.swift
1
1749
// // GetNewsDetail.swift // ZhiHuDaily // // Created by xiabob on 17/3/22. // Copyright © 2017年 xiabob. All rights reserved. // import UIKit import SwiftyJSON class GetNewsDetail: XBAPIBaseManager, ManagerProtocol, XBAPILocalCache { var newsID = 0 var model: NewsModel? var path: String { return "/news/\(newsID)" } var shouldCache: Bool {return true} func getDataFromLocal(from key: String) -> Data? { customLoadFromLocal() return nil } func customLoadFromLocal() { guard let realm = RealmManager.shared.defaultRealm else {return} guard let news = realm.object(ofType: News.self, forPrimaryKey: newsID) else {return} model = NewsModel(from: news) } func parseResponseData(_ data: AnyObject) { let detailJson = JSON(data) if detailJson.dictionaryValue.values.count < 6 { errorCode = Error(code: .httpError, errorMessage: "网络异常") model = nil } else { errorCode = Error(code: .success, errorMessage: "") let realm = RealmManager.shared.defaultRealm try? realm?.write({ let newsID = detailJson["id"].intValue let existNews = realm?.object(ofType: News.self, forPrimaryKey: newsID) if let existNews = existNews { //存在则更新 existNews.update(detailNewsDic: detailJson) model = NewsModel(from: existNews) } else { let news = News(detailNewsDic: detailJson) realm?.add(news) model = NewsModel(from: news) } }) } } }
mit
fc46b2c7f526fd8706517d592d99c53d
29.857143
93
0.565972
4.476684
false
false
false
false
cojoj/BuildaUtils
BuildaUtils/JSON.swift
1
3917
// JSON.swift // Buildasaur // // Created by Honza Dvorsky on 12/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Foundation public protocol JSONSerializable { init?(json: NSDictionary) throws func jsonify() -> NSDictionary } public class JSON { private class func parseDictionary(data: NSData) -> ([String: AnyObject]?, NSError?) { let (object, error) = self.parse(data) return (object as? [String: AnyObject], error) } private class func parseArray(data: NSData) -> ([AnyObject]!, NSError!) { let (object, error) = self.parse(data) return (object as? [AnyObject], error) } public class func parse(url: NSURL) -> (AnyObject?, NSError?) { do { let data = try NSData(contentsOfURL: url, options: NSDataReadingOptions(rawValue: 0)) return self.parse(data) } catch { return (nil, error as NSError) } } public class func parse(data: NSData) -> (AnyObject?, NSError?) { do { let obj = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) return (obj as AnyObject, nil) } catch { return (nil, error as NSError) } } } public extension NSDictionary { public func arrayForKey<T>(key: String) -> [T]! { let array = self.arrayForKey(key) var newArray = [T]() for i in array { newArray.append(i as! T) } return newArray } public func optionalForKey<Z>(key: String) -> Z? { if let optional = self[key] as? Z { return optional } return nil } public func nonOptionalForKey<Z>(key: String) -> Z { return self.optionalForKey(key)! } public func optionalArrayForKey(key: String) -> NSArray? { return self.optionalForKey(key) } public func arrayForKey(key: String) -> NSArray { return self.nonOptionalForKey(key) } public func optionalStringForKey(key: String) -> String? { return self.optionalForKey(key) } public func optionalNSURLForKey(key: String) -> NSURL? { if let string = self.optionalStringForKey(key) { return NSURL(string: string) } return nil } public func stringForKey(key: String) -> String { return self.nonOptionalForKey(key) } public func optionalIntForKey(key: String) -> Int? { return self.optionalForKey(key) } public func intForKey(key: String) -> Int { return self.nonOptionalForKey(key) } public func optionalBoolForKey(key: String) -> Bool? { return self.optionalForKey(key) } public func boolForKey(key: String) -> Bool { return self.nonOptionalForKey(key) } public func optionalDictionaryForKey(key: String) -> NSDictionary? { return self.optionalForKey(key) } public func dictionaryForKey(key: String) -> NSDictionary { return self.nonOptionalForKey(key) } public func optionalDateForKey(key: String) -> NSDate? { if let dateString = self.optionalStringForKey(key) { let date = NSDate.dateFromXCSString(dateString) return date } return nil } public func dateForKey(key: String) -> NSDate { return self.optionalDateForKey(key)! } public func optionalDoubleForKey(key: String) -> Double? { return self.optionalForKey(key) } public func doubleForKey(key: String) -> Double { return self.nonOptionalForKey(key) } } public extension NSMutableDictionary { public func optionallyAddValueForKey(value: AnyObject?, key: String) { if let value: AnyObject = value { self[key] = value } } }
mit
cac0bab7b763683df8ca336513e3a1a7
25.113333
97
0.596119
4.451136
false
false
false
false
JadenGeller/Graham
Graham/Graham/Base.swift
1
1245
// // Base.swift // Graham // // Created by Jaden Geller on 10/26/15. // Copyright © 2015 Jaden Geller. All rights reserved. // // Note that implementation details of Digit require Radix be less than sqrt(Backing.max) // so make sure to choose an acceptably large Backing type! public protocol Base { typealias Backing: IntegerType static var radix: Backing { get } static var representations: TypeMap<Backing, Character> { get } } /// Base 10 public struct Decimal: Base { public static let radix: Int8 = 10 public static let representations = TypeMap(digitRepresentations(0..<10)) } /// Base 2 public struct Binary: Base { public static let radix: Int8 = 2 public static let representations = TypeMap(digitRepresentations(0..<2)) } /// Base 16 public struct Hexadecimal: Base { public static let radix: Int8 = 16 public static let representations = TypeMap(digitRepresentations(0..<10) + [10: "A", 11: "B", 12: "C", 13: "D", 14: "E", 15: "F"]) } extension Character { private init(digitBacking: Int8) { self.init(String(digitBacking)) } } func digitRepresentations(range: Range<Int8>) -> Zip2Sequence<Range<Int8>, [Character]> { return zip(range, range.map(Character.init)) }
mit
17829fed07983b9f629c367e0e2510d5
27.930233
134
0.689711
3.658824
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV2/Models/LogMessageSource.swift
1
2954
/** * (C) Copyright IBM Corp. 2021. * * 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 /** An object that identifies the dialog element that generated the error message. */ public enum LogMessageSource: Codable, Equatable { case dialogNode(LogMessageSourceDialogNode) case action(LogMessageSourceAction) case step(LogMessageSourceStep) case handler(LogMessageSourceHandler) private struct GenericLogMessageSource: Codable, Equatable { var type: String private enum CodingKeys: String, CodingKey { case type = "type" } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let genericInstance = try? container.decode(GenericLogMessageSource.self) { switch genericInstance.type { case "dialog_node": if let val = try? container.decode(LogMessageSourceDialogNode.self) { self = .dialogNode(val) return } case "action": if let val = try? container.decode(LogMessageSourceAction.self) { self = .action(val) return } case "step": if let val = try? container.decode(LogMessageSourceStep.self) { self = .step(val) return } case "handler": if let val = try? container.decode(LogMessageSourceHandler.self) { self = .handler(val) return } default: // falling through to throw decoding error break } } throw DecodingError.typeMismatch(LogMessageSource.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Decoding failed for all associated types")) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .dialogNode(let dialog_node): try container.encode(dialog_node) case .action(let action): try container.encode(action) case .step(let step): try container.encode(step) case .handler(let handler): try container.encode(handler) } } }
apache-2.0
9108439ee50d2f8db5c3ae9873ed3aa2
33.348837
157
0.598849
5.02381
false
false
false
false
shitoudev/v2ex
v2ex/PostDetailViewController.swift
1
17483
// // PostDetailViewController.swift // v2ex // // Created by zhenwen on 6/8/15. // Copyright (c) 2015 zhenwen. All rights reserved. // import UIKit import SnapKit import TTTAttributedLabel import v2exKit import SnapKit import Kanna class PostDetailViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var toolbarView: UIView! @IBOutlet weak var toolbarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint! var postId: Int! var postDetail: PostDetailModel! { didSet { self.title = (self.postDetail != nil) ? self.postDetail?.title : "加载中...." } } var dataSouce: [AnyObject] = [AnyObject]() var indexPath: NSIndexPath! var refreshControl: UIRefreshControl! var atTableView: AtUserTableView! //args: NSDictionary func allocWithRouterParams(args: NSDictionary?) -> PostDetailViewController { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("postDetailViewController") as! PostDetailViewController viewController.hidesBottomBarWhenPushed = true return viewController } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) } override func viewDidLoad() { super.viewDidLoad() self.postDetail = nil tableView.registerNib(UINib(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: "commentCellId") tableView.estimatedRowHeight = 90 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = defaultTableFooterView self.refreshControl = UIRefreshControl(frame: self.tableView.bounds) refreshControl.addTarget(self, action: #selector(refresh), forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(self.refreshControl) reloadTableViewData(isPull: false) let topLayer = CALayer() topLayer.frame = CGRect(x: 0, y: 0, width: toolbarView.width, height: 0.5) topLayer.backgroundColor = UIColor.lightGrayColor().CGColor toolbarView.layer.addSublayer(topLayer) let sendButton = toolbarView.viewWithTag(11) as! UIButton sendButton.addTarget(self, action: #selector(sendButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside) getTextView().delegate = self getTextView().placeHolder = "添加评论 输入@自动匹配用户..." getTextView().keyboardType = UIKeyboardType.Twitter } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) addObservers() view.keyboardTriggerOffset = self.toolbarView.height; view.addKeyboardPanningWithActionHandler { (keyboardFrameInView, opening, closing) -> Void in self.view.layoutIfNeeded() self.toolbarBottomConstraint.constant = self.view.height - keyboardFrameInView.origin.y } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) removeObservers() view.removeKeyboardControl() } func refresh() { reloadTableViewData(isPull: true) } func reloadTableViewData(isPull pull: Bool) { // self.postId = 199762 PostDetailModel.getPostDetail(postId, completionHandler: { (detail, error) -> Void in if error == nil { self.dataSouce = [] self.postDetail = detail self.dataSouce.append(self.postDetail) self.tableView.reloadData() // CommentModel.getCommentsFromHtml(self.postId, page: 1, completionHandler: { (obj, error) -> Void in // if error == nil { // self.tableView.beginUpdates() // var indexPaths = [NSIndexPath]() // for (index, val) in enumerate(obj) { // self.dataSouce.append(val) // // let row = self.tableView.numberOfRowsInSection(0)+index // let indexPath = NSIndexPath(forRow: row, inSection: 0) // self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) // } // self.tableView.endUpdates() // } // // if isPull { // self.refreshControl.endRefreshing() // } // }) let salt = "&\(self.postDetail.replies)" CommentModel.getComments(self.postId, salt:salt, completionHandler: { (obj, error) -> Void in if error == nil { self.tableView.beginUpdates() for (index, val) in obj.enumerate() { self.dataSouce.append(val) let row = self.tableView.numberOfRowsInSection(0)+index let indexPath = NSIndexPath(forRow: row, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) } self.tableView.endUpdates() } if pull { self.refreshControl.endRefreshing() } }) }else{ if pull { self.refreshControl.endRefreshing() } } }) } func postLoaded() { tableView.reloadData() } // MARK: button tapped @IBAction func userTapped(sender: AnyObject) { pushToProfileViewController(self.postDetail.member.username) } func commentUserTapped(sender: AnyObject) { let button = sender as! UIButton let comment = dataSouce[button.tag] as! CommentModel pushToProfileViewController(comment.member.username) } func pushToProfileViewController(username: String) { if username != MemberModel.sharedMember.username { let profileViewController = ProfileViewController().allocWithRouterParams(nil) profileViewController.isMine = false profileViewController.username = username navigationController?.pushViewController(profileViewController, animated: true) } } func sendButtonTapped(sender: UIButton) { if !MemberModel.sharedMember.isLogin() { let accountViewController = AccountViewController().allocWithRouterParams(nil) presentViewController(UINavigationController(rootViewController: accountViewController), animated: true, completion: nil) return } if getTextView().text.isEmpty { return } JDStatusBarNotification.showWithStatus("提交中...", styleName: JDStatusBarStyleDark) JDStatusBarNotification.showActivityIndicator(true, indicatorStyle: UIActivityIndicatorViewStyle.White) // get once code let mgr = APIManage.sharedManager let url = APIManage.Router.Post + String(postId) // String(199762) mgr.request(.GET, url, parameters: nil).responseString(encoding: nil) { (response) -> Void in if response.result.isSuccess, let once = APIManage.getOnceStringFromHtmlResponse(response.result.value!) { // submit comment mgr.session.configuration.HTTPAdditionalHeaders?.updateValue(url, forKey: "Referer") mgr.request(.POST, url, parameters: ["content":self.getTextView().text, "once":once]).responseString(encoding: nil, completionHandler: { (response) -> Void in // println("args = \(self.getTextView().text + once), str = \(str)") if response.result.isSuccess { guard let doc = HTML(html: response.result.value!, encoding: NSUTF8StringEncoding) else { JDStatusBarNotification.showWithStatus("数据解析失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning) return } if let divProblem = doc.at_css("div[class='problem']"), liNode = divProblem.at_css("li"), problem = liNode.text { let errorStr = problem JDStatusBarNotification.showWithStatus(errorStr, dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning) } else { // success self.submitSuccessData() } }else{ JDStatusBarNotification.showWithStatus("提交失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning) } // println("cookies___ = \(mgr.session.configuration.HTTPCookieStorage?.cookies)") }) } else { JDStatusBarNotification.showWithStatus("once 获取失败:[", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleWarning) } } } func submitSuccessData() { JDStatusBarNotification.showWithStatus("提交完成:]", dismissAfter: _dismissAfter, styleName: JDStatusBarStyleSuccess) let content = getTextView().text let user = MemberModel.sharedMember let data = ["id":0, "content":content, "created":NSDate().timeIntervalSince1970, "member":["username":user.username, "avatar_large":user.avatar_large]] let comment = CommentModel(fromDictionary: data) // println("comment.data = \(data)") // update row tableView.beginUpdates() dataSouce.append(comment) let row = tableView.numberOfRowsInSection(0) let indexPath = NSIndexPath(forRow: row, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Middle) tableView.endUpdates() tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false) getTextView().text = "" getTextView().setNeedsDisplay() } // MARK: Key-value observing override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let newContentSize = change?[NSKeyValueChangeNewKey]!.CGSizeValue() { var dy = newContentSize.height if let oldContentSize = change?[NSKeyValueChangeOldKey]!.CGSizeValue() { dy -= oldContentSize.height } toolbarHeightConstraint.constant = toolbarHeightConstraint.constant + dy view.setNeedsUpdateConstraints() view.layoutIfNeeded() } } // MARK: Utilities func addObservers() { getTextView().addObserver(self, forKeyPath: "contentSize", options: [.Old, .New], context: nil) } func removeObservers() { getTextView().removeObserver(self, forKeyPath: "contentSize", context: nil) } func getTextView() -> STTextView { return toolbarView.viewWithTag(10) as! STTextView } } // MARK: TTTAttributedLabelDelegate extension PostDetailViewController: TTTAttributedLabelDelegate { func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) { if url != nil { if let urlStr: String = url.absoluteString { if urlStr.hasPrefix("@") { let username = (urlStr as NSString).substringFromIndex(1) let profileViewController = ProfileViewController().allocWithRouterParams(nil) profileViewController.isMine = false profileViewController.username = username navigationController?.pushViewController(profileViewController, animated: true) } else { let webViewController = WebViewController() webViewController.loadURLWithString(url.absoluteString) navigationController?.pushViewController(webViewController, animated: true) } } } } } // MARK: AtUserTableViewDelegate extension PostDetailViewController: AtUserTableViewDelegate { func didSelectedUser(user: MemberModel) { getTextView().text = getTextView().text.stringByReplacingOccurrencesOfString("@" + atTableView.searchText, withString: "@" + user.username + " ", options: NSStringCompareOptions.BackwardsSearch) atTableView?.hidden = true } } // MARK: UITextViewDelegate extension PostDetailViewController: UITextViewDelegate { func textViewDidChange(textView: UITextView) { if !textView.text.isEmpty && dataSouce.count > 0 { if textView.text.characters.last == " " { atTableView?.hidden = true return } let components = textView.text.componentsSeparatedByString(" ") if components.count > 0 { let atText = components.last! let text = atText.stringByReplacingOccurrencesOfString("@", withString: "") if atText.hasPrefix("@") && !text.isEmpty { if atTableView == nil { self.atTableView = AtUserTableView(frame: tableView.bounds, style: .Plain) atTableView.atDelegate = self view.insertSubview(atTableView, belowSubview: toolbarView) atTableView.snp_makeConstraints { (make) -> Void in make.top.equalTo(tableView.snp_top).offset(64) make.left.equalTo(tableView.snp_left) make.right.equalTo(tableView.snp_right) make.bottom.equalTo(tableView.snp_bottom) } let postDetail: PostDetailModel = dataSouce.first as! PostDetailModel var userData = [postDetail.member] for obj in dataSouce { if let comment = obj as? CommentModel where userData.count > 0 { var canAdd = true for user in userData { if user.username == comment.member.username { canAdd = false } } if canAdd { userData.append(comment.member) } } } atTableView.originData = userData } atTableView.searchText = text atTableView.hidden = !atTableView.searchMember() } else { atTableView?.hidden = true } } } else { atTableView?.hidden = true } } } // MARK: UITableViewDataSource & UITableViewDelegate extension PostDetailViewController: UITableViewDelegate, UITableViewDataSource { // UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell: PostContentCell = tableView.dequeueReusableCellWithIdentifier("postContentCellId") as! PostContentCell cell.selectionStyle = UITableViewCellSelectionStyle.None cell.contentLabel.delegate = self cell.updateCell(postDetail) return cell; } else { let cell: CommentCell = tableView.dequeueReusableCellWithIdentifier("commentCellId") as! CommentCell cell.contentLabel.delegate = self let comment = dataSouce[indexPath.row] as! CommentModel cell.updateCell(comment) cell.avatarButton.tag = indexPath.row cell.usernameButton.tag = indexPath.row if !cell.isButtonAddTarget { cell.avatarButton.addTarget(self, action: #selector(commentUserTapped(_:)), forControlEvents: .TouchUpInside) cell.usernameButton.addTarget(self, action: #selector(commentUserTapped(_:)), forControlEvents: .TouchUpInside) cell.isButtonAddTarget = true } return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSouce.count > 0 ? dataSouce.count : 0 } // UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } }
mit
857b53bb3b108e761e6a9c04afab7824
42.09901
202
0.580782
5.761416
false
false
false
false
MR-Zong/ZGResource
Project/FamilyEducationApp-master/家教/SystemSettingVewController.swift
1
3113
// // SystemSettingVewController.swift // 家教 // // Created by goofygao on 15/11/4. // Copyright © 2015年 goofyy. All rights reserved. // import UIKit class SystemSettingVewController: UITableViewController { @IBOutlet weak var settingTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1) let navBar = self.navigationController?.navigationBar navBar?.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1) navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] settingTableView.tableHeaderView = UIView(frame: CGRectMake(0,0,DeviceData.width,0)) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell") let section = indexPath.section switch section { case 0: if indexPath.row == 0 { cell?.textLabel?.text = "消息设置" } else if indexPath.row == 1 { cell?.textLabel?.text = "账号设置" }else { cell?.textLabel?.text = "隐私设置" } cell?.detailTextLabel?.text = nil break default: cell?.detailTextLabel?.font = UIFont.systemFontOfSize(12) if indexPath.row == 0 { cell?.textLabel?.text = "反馈问题" cell?.detailTextLabel?.text = nil } else if indexPath.row == 1 { cell?.textLabel?.text = "版本更新" cell?.detailTextLabel?.text = "Version 1.0.3" }else { cell?.textLabel?.text = "关于我们" cell?.detailTextLabel?.text = "iHat工作室" } break } cell?.textLabel?.backgroundColor = UIColor.clearColor() cell?.detailTextLabel?.backgroundColor = UIColor.clearColor() cell?.backgroundColor = UIColor(white: 0.9, alpha: 1) return cell! } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "通用设置" } else { return "关于软件" } } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } }
gpl-2.0
1eb055af966b2e0bd97577e1f9736d3f
31.645161
118
0.588603
4.865385
false
false
false
false
nearspeak/iOS-SDK
NearspeakKit/NSKApi.swift
1
18537
// // NSKApi.swift // NearspeakKit // // Created by Patrick Steiner on 21.01.15. // Copyright (c) 2015 Mopius OG. All rights reserved. // import UIKit enum HTTPMethod: String { case POST = "POST" case GET = "GET" } /** The NearspeakKit API communication class. */ public class NSKApi: NSObject { /** Set to true if you want to connect to the staging server. */ private var developmentMode: Bool = false /** The staging authentication token NSDefaults key. */ private let kAuthTokenStagingKey = "nsk_auth_token_staging" /** The production authentication token NSDefaults key. */ private let kAuthTokenKey = "nsk_auth_token" /** The api authentication token. */ public var auth_token: String? private var apiParser = NSKApiParser() private var locationManager = NSKLocationManager() /** Init the API object. - parameter devMode: Connect to the staging oder production server. */ public init(devMode: Bool) { super.init() developmentMode = devMode // load auth token from persistent storage self.loadCredentials() } /** Remove the server credentials from the local device. */ public func logout() { auth_token = nil saveCredentials() } /** Save the server credentials to the local device. */ public func saveCredentials() { if (developmentMode) { NSUserDefaults.standardUserDefaults().setObject(auth_token, forKey: kAuthTokenStagingKey) } else { NSUserDefaults.standardUserDefaults().setObject(auth_token, forKey: kAuthTokenKey) } NSUserDefaults.standardUserDefaults().synchronize() } /** Load the server credentials from the local device. */ public func loadCredentials() { if (developmentMode) { auth_token = NSUserDefaults.standardUserDefaults().stringForKey(kAuthTokenStagingKey) } else { auth_token = NSUserDefaults.standardUserDefaults().stringForKey(kAuthTokenKey) } } /** Check if the current user is logged in. */ public func isLoggedIn() -> Bool { if auth_token != nil { // TODO: implemented a better check return true } return false } // MARK: API calls /** Make the api call to the server - parameter apiURL: The URL of the api call. - parameter httpMethod: The HTTP Method to use for the request. - parameter params: The HTTP Header Parameters. - parameter requestCompleted: The request completion block. */ private func apiCall(apiURL: NSURL, httpMethod: HTTPMethod, params: Dictionary<String, String>?, requestCompleted: (succeeded: Bool, data: NSData?) -> ()) { let request = NSMutableURLRequest(URL: apiURL) let session = NSURLSession.sharedSession() //let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) switch httpMethod { case .POST: request.HTTPMethod = httpMethod.rawValue if let para = params { do { request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(para, options: []) } catch let error as NSError { request.HTTPBody = nil Log.error("Api call failed", error) } request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") } default: // GET // GET is the default value //request.HTTPMethod = httpMethod.rawValue request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") } let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if let _ = error { requestCompleted(succeeded: false, data: nil) } else if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { //_ = NSError(domain: "at.nearspeak", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP status code has unexpected value."]) requestCompleted(succeeded: false, data: nil) } else { requestCompleted(succeeded: true, data: data) } } } task.resume() } /** API call to get the authentication token from the API server. - parameter username:: The username of the user. - parameter password:: The password of the user. - parameter requestCompleted: The request completion block. */ public func getAuthToken(username username: String, password : String, requestCompleted: (succeeded: Bool, auth_token: String?) -> ()) { let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "login/getAuthToken", queryItems: nil) if let apiURL = apiComponents.URL { let params = ["email" : username, "password" : password] as Dictionary<String, String> apiCall(apiURL, httpMethod: .POST, params: params, requestCompleted: { (succeeded, data) -> () in if succeeded { self.apiParser.parseGetAuthToken(data!, parsingCompleted: { (succeeded, authToken) -> () in if succeeded { self.auth_token = authToken self.saveCredentials() requestCompleted(succeeded: true, auth_token: authToken) } else { requestCompleted(succeeded: false, auth_token: nil) } }) } else { requestCompleted(succeeded: false, auth_token: nil) } }) } } /** API call to get all Nearspeak tag from the user. - parameter requestCompleted: The request completion block. */ public func getMyTags(requestCompleted: (succeeded: Bool, tags: [NSKTag]) ->()) { if let token = self.auth_token { let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/showMyTags", queryItems: [NSURLQueryItem(name: "auth_token", value: token)]) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .GET, params: nil, requestCompleted: { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseTagsArray(jsonData, parsingCompleted: { (succeeded, tags) -> () in if succeeded { requestCompleted(succeeded: true, tags: tags) } else { requestCompleted(succeeded: false, tags: []) } requestCompleted(succeeded: false, tags: []) }) } else { requestCompleted(succeeded: false, tags: []) } } else { requestCompleted(succeeded: false, tags: []) } }) } else { Log.error("Auth token not found") } } } /** API call to get a Nearspeak tag by its tag identifier. - parameter tagIdentifier: The tag identifier of the tag. - parameter requestCompleted: The request completion block. */ public func getTagById(tagIdentifier tagIdentifier: String, requestCompleted: (succeeded: Bool, tag: NSKTag?) -> ()) { let currentLocale: NSString = NSLocale.preferredLanguages()[0] as NSString let idQueryItem = NSURLQueryItem(name: "id", value: tagIdentifier) let langQueryItem = NSURLQueryItem(name: "lang", value: (currentLocale as String)) let queryItems = [idQueryItem, langQueryItem] let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/show", queryItems: queryItems) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .GET, params: nil, requestCompleted: { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseTagsArray(jsonData, parsingCompleted: { (succeeded, tags) -> () in if succeeded { if tags.count > 0 { requestCompleted(succeeded: true, tag: tags[0]) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } } /** API call to get a Nearspeak tag by its hardware identifier. - parameter hardwareIdentifier: The hardware identifier of the tag. - parameter beaconMajorId: The iBeacon major id. - parameter beaconMinorId: The iBeacon minor id. - parameter requestCompleted: The request completion block. */ public func getTagByHardwareId(hardwareIdentifier hardwareIdentifier: String, beaconMajorId: String, beaconMinorId: String, requestCompleted: (succeeded: Bool, tag: NSKTag?) -> ()) { let currentLocale: String = NSLocale.preferredLanguages().first as String! let idQueryItem = NSURLQueryItem(name: "id", value: NSKApiUtils.formatHardwareId(hardwareIdentifier)) let majorQueryItem = NSURLQueryItem(name: "major", value: beaconMajorId) let minorQueryItem = NSURLQueryItem(name: "minor", value: beaconMinorId) let langQueryItem = NSURLQueryItem(name: "lang", value: currentLocale) let typeQueryItem = NSURLQueryItem(name: "type", value: NSKTagHardwareType.BLE.rawValue) let latitudeQueryItem = NSURLQueryItem(name: "lat", value: "\(locationManager.currentLocation.coordinate.latitude)") let longitudeQueryItem = NSURLQueryItem(name: "lon", value: "\(locationManager.currentLocation.coordinate.longitude)") let queryItems = [idQueryItem, majorQueryItem, minorQueryItem, langQueryItem, typeQueryItem, latitudeQueryItem, longitudeQueryItem] let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/showByHardwareId", queryItems: queryItems) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .GET, params: nil, requestCompleted: { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseTagsArray(jsonData, parsingCompleted: { (succeeded, tags) -> () in if succeeded { if tags.count > 0 { requestCompleted(succeeded: true, tag: tags.first) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } } /** API call to get all supported iBeacon UUIDs. - parameter requestCompleted: The request completion block. */ public func getSupportedBeaconsUUIDs(requestCompleted: (succeeded: Bool, uuids: [String]) ->()) { let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/supportedBeaconUUIDs", queryItems: nil) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .GET, params: nil) { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseUUIDsArray(jsonData, parsingCompleted: { (succeeded, uuids) -> () in if succeeded { requestCompleted(succeeded: true, uuids: uuids) } else { requestCompleted(succeeded: false, uuids: []) } }) } else { requestCompleted(succeeded: false, uuids: []) } } else { requestCompleted(succeeded: false, uuids: []) } } } } /** API call to add a Nearspeak tag. - parameter tag: The Nearspeak tag which should be added. */ public func addTag(tag tag: NSKTag, requestCompleted: (succeeded: Bool, tag: NSKTag?) -> ()) { let currentLocale: String = NSLocale.preferredLanguages().first as String! var queryItems = [NSURLQueryItem]() queryItems.append(NSURLQueryItem(name: "lang", value: currentLocale)) queryItems.append(NSURLQueryItem(name: "purchase_id", value: "4ea93515-5a84-4add-bf81-293b306b968f")) // default // translation if let translation = tag.translation { queryItems.append(NSURLQueryItem(name: "text", value: translation)) } // auth token if let token = self.auth_token { queryItems.append(NSURLQueryItem(name: "auth_token", value: token)) } // name if let name = tag.name { queryItems.append(NSURLQueryItem(name: "name", value: name)) } // hardware infos if let hardwareID = tag.hardwareBeacon?.proximityUUID.UUIDString, major = tag.hardwareBeacon?.major, minor = tag.hardwareBeacon?.minor { queryItems.append(NSURLQueryItem(name: "hardware_id", value: NSKApiUtils.formatHardwareId(hardwareID))) queryItems.append(NSURLQueryItem(name: "major", value: "\(major)")) queryItems.append(NSURLQueryItem(name: "minor", value: "\(minor)")) queryItems.append(NSURLQueryItem(name: "hardware_type", value: NSKTagHardwareType.BLE.rawValue)) } // location let latitude = locationManager.currentLocation.coordinate.latitude let longitude = locationManager.currentLocation.coordinate.longitude if latitude != 0 && longitude != 0 { queryItems.append(NSURLQueryItem(name: "lat", value: "\(locationManager.currentLocation.coordinate.latitude)")) queryItems.append(NSURLQueryItem(name: "lon", value: "\(locationManager.currentLocation.coordinate.longitude)")) } let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/create", queryItems: queryItems) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .POST, params: nil, requestCompleted: { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseTagsArray(jsonData, parsingCompleted: { (succeeded, tags) -> () in if succeeded { if tags.count > 0 { requestCompleted(succeeded: true, tag: tags.first) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } else { requestCompleted(succeeded: false, tag: nil) } } else { requestCompleted(succeeded: false, tag: nil) } }) } } /** API call to remove a Nearspeak tag. - parameter tag: The Nearspeak tag which should be added. */ public func removeTag(tag tag: NSKTag, requestCompleted: (succeeded: Bool) -> ()) { if let tagIdentifier = tag.tagIdentifier, token = auth_token { let idQueryItem = NSURLQueryItem(name: "id", value: tagIdentifier) let tokenQueryItem = NSURLQueryItem(name: "auth_token", value: token) let queryItems = [idQueryItem, tokenQueryItem] let apiComponents = NSKApiUtils.apiURL(developmentMode, path: "tags/delete", queryItems: queryItems) if let apiURL = apiComponents.URL { apiCall(apiURL, httpMethod: .POST, params: nil, requestCompleted: { (succeeded, data) -> () in if succeeded { if let jsonData = data { self.apiParser.parseDeleteReponse(jsonData, parsingCompleted: { (succeeded) -> () in if succeeded { requestCompleted(succeeded: true) } else { requestCompleted(succeeded: false) } }) } else { requestCompleted(succeeded: false) } } else { requestCompleted(succeeded: false) } }) } } } }
lgpl-3.0
da68e85d5d24fa08b9caa75c3aaabd9f
42.310748
186
0.539731
5.37772
false
false
false
false
kstaring/swift
test/SILGen/super.swift
4
3915
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -emit-silgen -parse-as-library -I %t %s | %FileCheck %s import resilient_class public class Parent { public final var finalProperty: String { return "Parent.finalProperty" } public var property: String { return "Parent.property" } public final class var finalClassProperty: String { return "Parent.finalProperty" } public class var classProperty: String { return "Parent.property" } public func methodOnlyInParent() {} public final func finalMethodOnlyInParent() {} public func method() {} public final class func finalClassMethodOnlyInParent() {} public class func classMethod() {} } public class Child : Parent { // CHECK-LABEL: sil @_TFC5super5Childg8propertySS : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : $Child): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC5super6Parentg8propertySS : $@convention(method) (@guaranteed Parent) -> @owned String // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public override var property: String { return super.property } // CHECK-LABEL: sil @_TFC5super5Childg13otherPropertySS : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : $Child): // CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC5super6Parentg13finalPropertySS // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public var otherProperty: String { return super.finalProperty } } public class Grandchild : Child { // CHECK-LABEL: sil @_TFC5super10Grandchild16onlyInGrandchildfT_T_ public func onlyInGrandchild() { // CHECK: function_ref @_TFC5super6Parent18methodOnlyInParentfT_T_ : $@convention(method) (@guaranteed Parent) -> () super.methodOnlyInParent() // CHECK: function_ref @_TFC5super6Parent23finalMethodOnlyInParentfT_T_ super.finalMethodOnlyInParent() } // CHECK-LABEL: sil @_TFC5super10Grandchild6methodfT_T_ public override func method() { // CHECK: function_ref @_TFC5super6Parent6methodfT_T_ : $@convention(method) (@guaranteed Parent) -> () super.method() } } public class GreatGrandchild : Grandchild { // CHECK-LABEL: sil @_TFC5super15GreatGrandchild6methodfT_T_ public override func method() { // CHECK: function_ref @_TFC5super10Grandchild6methodfT_T_ : $@convention(method) (@guaranteed Grandchild) -> () super.method() } } public class ChildToResilientParent : ResilientOutsideParent { public override func method() { super.method() } public override class func classMethod() { super.classMethod() } } public class ChildToFixedParent : OutsideParent { public override func method() { super.method() } public override class func classMethod() { super.classMethod() } } public extension ResilientOutsideChild { public func callSuperMethod() { super.method() } public class func callSuperClassMethod() { super.classMethod() } }
apache-2.0
088e10ad7c6fdccea10b3ea20a32851a
33.955357
165
0.667944
3.786267
false
false
false
false
jbourjeli/SwiftLabelPhoto
Photos++/MosaicCollectionViewLayout.swift
1
6088
// // MosaicCollectionViewLayout.swift // Photos++ // // Created by Joseph Bourjeli on 9/7/16. // Copyright © 2016 WorkSmarterComputing. All rights reserved. // // Algorithm from http://blog.vjeux.com/2012/image/image-layout-algorithm-google-plus.html import UIKit protocol MosaicCollectionViewLayoutDelegate { func collectionView(_ collectionView: UICollectionView, sizeOfCellAtIndexPath indexPath: IndexPath) -> CGSize } class MosaicCollectionViewLayout: UICollectionViewLayout { let minimumRowHeight = CGFloat(100.0) var delegate: MosaicCollectionViewLayoutDelegate! var cellPadding: CGFloat = 1.0 fileprivate var refreshCache: Bool { get { return self.numberOfItemsInCollectionView(collectionView!) != self.cache.count } } fileprivate var contentHeight: CGFloat = 0.0 fileprivate var contentWidth: CGFloat { let inset = self.collectionView!.contentInset return self.collectionView!.bounds.width - (inset.left + inset.right) } fileprivate var cache = [UICollectionViewLayoutAttributes]() override func prepare() { if refreshCache { self.cache.removeAll() self.contentHeight = 0.0 var yOffset: CGFloat = 0 // TODO: Height of collectionViewCell is still not correct. It is cropping the image!!!! var startOfRow = 0 for section in 0 ..< self.collectionView!.numberOfSections { var runningTotalOfRatios = CGFloat(0.0) var rowHeight = CGFloat(0.0) for item in 0 ..< self.collectionView!.numberOfItems(inSection: section) { let indexPath = IndexPath(item: item, section: section) let cellSize = self.delegate.collectionView(self.collectionView!, sizeOfCellAtIndexPath: indexPath) let ratio = cellSize.width / cellSize.height let newHeight = self.contentWidth / (runningTotalOfRatios + ratio) if newHeight >= self.minimumRowHeight { // Add cell to current row runningTotalOfRatios += ratio rowHeight = newHeight } else { // Resize all cells in the previous row self.finalizeRow(startingAt: startOfRow, endingAt: (self.cache.count-1), inSection: section, withRowHeight: rowHeight, atOriginY: yOffset) // Start a new row with the new cell yOffset += rowHeight//cellSize.height + cellPadding self.contentHeight += rowHeight startOfRow = self.cache.count runningTotalOfRatios = ratio rowHeight = self.contentWidth / ratio } print("RowHeight: \(rowHeight), newHeight:\(newHeight), yOffset:\(yOffset)") let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = CGRect.zero//.insetBy(dx: cellPadding, dy: cellPadding) self.cache.append(attributes) } self.finalizeRow(startingAt: startOfRow, endingAt: (self.cache.count-1), inSection: section, withRowHeight: rowHeight, atOriginY: yOffset) self.contentHeight += rowHeight } } } override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) self.cache.removeAll() } override var collectionViewContentSize : CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() for attribute in self.cache { if attribute.frame.intersects(rect) { attributes.append(attribute) } } return attributes } // MARK: - Privates fileprivate func numberOfItemsInCollectionView(_ collectionView: UICollectionView) -> Int { var totalItems = 0 for section in 0 ..< collectionView.numberOfSections { totalItems += collectionView.numberOfItems(inSection: section) } return totalItems } fileprivate func heightForRowFrom(images: [UIImage]) -> Double { let sumOfRatios = images .map({ image in return image.size.width / image.size.height }) .reduce(0.0, { result, curVal in return result + curVal }) return Double(self.contentWidth) / Double(sumOfRatios) } fileprivate func finalizeRow(startingAt startOfRow: Int, endingAt endOfRow: Int, inSection section: Int, withRowHeight rowHeight: CGFloat, atOriginY y: CGFloat) { guard startOfRow <= endOfRow else { return } var xOffset = CGFloat(0.0) for item in startOfRow ... endOfRow { let indexPath = IndexPath(item: item, section: section) let cellSize = self.delegate.collectionView(self.collectionView!, sizeOfCellAtIndexPath: indexPath) let cellWidth = (cellSize.width*rowHeight) / cellSize.height self.cache[item].frame = CGRect(x: xOffset, y: y, width: cellWidth, height: rowHeight) print("ViewCell: .size: (\(cellWidth), \(rowHeight)) aspect: \(cellWidth / rowHeight)") xOffset += cellWidth } } }
mit
875743e15505ef7f5b3eef25aae49744
39.311258
166
0.570724
5.797143
false
false
false
false
Gilbertat/SYKanZhiHu
SYKanZhihu/SYKanZhihu/Class/Manager/Refresh/RefreshHeaderView.swift
1
6577
// // RefreshHeaderView.swift // SYKanZhihu // // Created by shiyue on 16/3/5. // Copyright © 2016年 shiyue. All rights reserved. // import UIKit class RefreshHeaderView: RefreshBaseView { class func header() -> RefreshHeaderView { let header:RefreshHeaderView = RefreshHeaderView(frame: CGRect(x: 0,y: 0, width: UIScreen.main.bounds.width,height: CGFloat(RefreshViewHeight))) return header } //最后更新时间 var lastUpdateTime = Date() { willSet { } didSet{ UserDefaults.standard.set(lastUpdateTime, forKey: RefreshHeaderTimeKey) UserDefaults.standard.synchronize() self.updateTimeLabel() } } //更新时间label var lastUpdateTiemLabel:UILabel! override init(frame: CGRect) { super.init(frame: frame) self.lastUpdateTiemLabel = UILabel() self.lastUpdateTiemLabel.autoresizingMask = .flexibleWidth self.lastUpdateTiemLabel.font = UIFont.boldSystemFont(ofSize: 12) self.lastUpdateTiemLabel.textColor = UIColor.clear self.lastUpdateTiemLabel.backgroundColor = UIColor.clear self.lastUpdateTiemLabel.textAlignment = .center self.addSubview(self.lastUpdateTiemLabel) //判断NSUserDefault有没有记录时间 if UserDefaults.standard.object(forKey: RefreshHeaderTimeKey) == nil { self.lastUpdateTime = Date() } else { self.lastUpdateTime = UserDefaults.standard.object(forKey: RefreshHeaderTimeKey) as! Date } self.updateTimeLabel() } override func layoutSubviews() { super.layoutSubviews() let stateX:CGFloat = 0 let stateY:CGFloat = 0 let stateHeight = self.frame.size.height * 0.5 let stateWidth = self.frame.size.width //状态label self.statusLabel.frame = CGRect(x: stateX, y: stateY, width: stateWidth, height: stateHeight) //时间标签 let lastUpdateX:CGFloat = 0 let lastUpdateY = stateHeight let lastUpdateHeight = stateHeight let lastUpdateWidth = stateWidth self.lastUpdateTiemLabel.frame = CGRect(x: lastUpdateX, y: lastUpdateY, width: lastUpdateWidth, height: lastUpdateHeight) } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) //设置子类尺寸 var rect = self.frame rect.origin.y = -self.frame.size.height self.frame = rect } //更新时间 func updateTimeLabel() { //获取时间 let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" let time = formatter.string(from: self.lastUpdateTime) //更新时间 self.lastUpdateTiemLabel.text = "最后刷新时间:" + time } //监听scrollview变化 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if !self.isUserInteractionEnabled || self.isHidden { return } if self.state == .refreshing { return } if RefreshContentOffSet == keyPath! { self.adjustStateWithContentOffSet() } } //设置状态 override var state:RefreshState { willSet { if state == newValue{ return; } oldState = state setState(newValue) } didSet{ switch state{ case .normal: self.statusLabel.text = RefreshHeaderToRefresh if RefreshState.refreshing == oldState { self.arrowImageView.transform = CGAffineTransform.identity self.lastUpdateTime = Date() UIView.animate(withDuration: RefreshAnimationDuration, animations: { var contentInset:UIEdgeInsets = self.scrollView.contentInset contentInset.top = self.scrollviewOriginalInset.top self.scrollView.contentInset = contentInset }) }else { UIView.animate(withDuration: RefreshAnimationDuration, animations: { self.arrowImageView.transform = CGAffineTransform.identity }) } case .pulling: self.statusLabel.text = RefreshHeaderRelease UIView.animate(withDuration: RefreshAnimationDuration, animations: { self.arrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI )) }) case .refreshing: self.statusLabel.text = RefreshHeaderRefreshing as String; UIView.animate(withDuration: RefreshAnimationDuration, animations: { let top:CGFloat = self.scrollviewOriginalInset.top + self.frame.size.height var inset:UIEdgeInsets = self.scrollView.contentInset inset.top = top self.scrollView.contentInset = inset var offset:CGPoint = self.scrollView.contentOffset offset.y = -top self.scrollView.contentOffset = offset }) case .willRefreshing: break } } } //调整 func adjustStateWithContentOffSet() { let currentOffSetY = self.scrollView.contentOffset.y let happenOffSetY = -self.scrollviewOriginalInset.top if currentOffSetY >= happenOffSetY { return } if self.scrollView.isDragging { let normalToPullingOffSetY = happenOffSetY - self.frame.size.height if self.state == .normal && currentOffSetY < normalToPullingOffSetY { self.state == .pulling } else if self.state == .pulling && currentOffSetY >= normalToPullingOffSetY { self.state == .normal } } else if self.state == .pulling { self.state = .refreshing } } func addState(_ state:RefreshState){ self.state = state } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
505fbc6a7a293ee1653067e66077b932
32.978947
152
0.577757
5.173077
false
false
false
false
dxdp/Stage
Stage/Scanners/RuleScanner.swift
1
6318
// // RuleScanner.swift // Stage // // Copyright © 2016 David Parton // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation public class StageRuleScanner: Scanner { public internal(set) var startingLine: Int = 0 let _string: String public override var string: String { return _string } var _scanLocation: Int = 0 public override var scanLocation: Int { get { return _scanLocation } set { _scanLocation = newValue } } var _caseSensitive: Bool = false public override var caseSensitive: Bool { get { return _caseSensitive } set { _caseSensitive = newValue } } var _charactersToBeSkipped: CharacterSet? public override var charactersToBeSkipped: CharacterSet? { get { return _charactersToBeSkipped } set { _charactersToBeSkipped = newValue } } var _locale: Any? public override var locale: Any? { get { return _locale } set { _locale = newValue } } override init(string: String) { _string = string super.init(string: string) } public func scanBool() throws -> Bool { var next: NSString? = nil guard scanCharacters(from: .nonwhitespaceCharacterSet(), into: &next) && next != nil else { throw StageException.unrecognizedContent(message: "Expecting Bool but received \(string)", line: startingLine, backtrace: []) } return next!.boolValue } static let nsNumberSet = CharacterSet(charactersIn: "0123456789.-") static let nsNumberMatch = try! NSRegularExpression(pattern: "-?(?:\\d*\\.\\d+|\\d+\\.?\\d*)", options: .init(rawValue: 0)) static let nsNumberFormatter = NumberFormatter() public func scanNSNumber() throws -> NSNumber { var numberText: NSString? guard scanCharacters(from: StageRuleScanner.nsNumberSet, into: &numberText) && numberText != nil && StageRuleScanner.nsNumberMatch.numberOfMatches(in: numberText as! String, options: .init(rawValue: 0), range: (numberText as! String).entireRange) == 1 else { throw StageException.unrecognizedContent(message: "Expected number but received \(string)", line: startingLine, backtrace: []) } guard let number = StageRuleScanner.nsNumberFormatter.number(from: numberText! as String) else { throw StageException.unrecognizedContent(message: "Expected number but received \(string)", line: startingLine, backtrace: []) } return number } public func scanInt() throws -> Int { var out: Int32 = 0 guard scanInt32(&out) else { throw StageException.unrecognizedContent(message: "Expected integer but saw \(string)", line: startingLine, backtrace: []) } return Int(out) } public func scanFloat() throws -> Float { return try scanNSNumber().floatValue } public func scanCGFloat() throws -> CGFloat { return CGFloat(try scanFloat()) } public func scanList<T>( itemScan: @autoclosure () throws -> T) throws -> [T] { var output = [T]() while !isAtEnd { output.append(try itemScan()) scanString(",", into: nil) } return output } public func scanBracedList<T>(open: String = "{", close: String = "}", itemScan: @autoclosure () throws -> T) throws -> [T] { if !open.isEmpty && !scanString(open, into: nil) { throw StageException.unrecognizedContent(message: "Expected \(open) to open list but saw \(string)", line: startingLine, backtrace: []) } var output = [T](), gotRightBrace = close.isEmpty while !isAtEnd { if !close.isEmpty && scanString(close, into: nil) { gotRightBrace = true break } output.append(try itemScan()) scanString(",", into: nil) } if !gotRightBrace { throw StageException.unrecognizedContent(message: "Expected \(close) to close list but saw \(string)", line: startingLine, backtrace: []) } return output } public func scanCharacters(from set: CharacterSet) throws -> String { var string: NSString? guard scanCharacters(from: set, into: &string) && string != nil else { throw StageException.unrecognizedContent(message: "Unable to scan to characters in set", line: startingLine, backtrace: []) } return string as! String } public func scanUpTo(string: String) throws -> String { var value: NSString? guard scanUpTo(string, into: &value) && value != nil else { throw StageException.unrecognizedContent(message: "Unable to scan up through \(string)", line: startingLine, backtrace: []) } return value as! String } public func scanLinesTrimmed() -> [String] { return string.components(separatedBy: "\n").map { $0.trimmed() } } }
mit
b610905ffe260ab2924404bb0fdafe7e
40.834437
166
0.614216
4.848043
false
false
false
false
terflogag/BadgeSegmentControl
Sources/BadgeSegmentControl.swift
1
7458
// // SegmentView.swift // BadgeSegmentControl // // Created by terflogag on 03/02/2017. // Copyright (c) 2017 terflogag. All rights reserved. // import UIKit open class BadgeSegmentControl: UIControl { public var segmentAppearance: BadgeSegmentControlAppearance? { didSet { self.applyAppearence() } } public var dividerColour: UIColor = UIColor.lightGray { didSet { self.setNeedsDisplay() } } public var dividerWidth: CGFloat = 1.0 { didSet { self.updateSegmentsLayout() } } public var selectedSegmentIndex: Int { get { if let segment = self.selectedSegment { return segment.index } else { return UISegmentedControlNoSegment } } set(newIndex) { self.deselectSegment() if newIndex >= 0 && newIndex < self.segments.count { let currentSelectedSegment = self.segments[newIndex] self.selectSegment(currentSelectedSegment) } } } public var numberOfSegments: Int { get { return segments.count } } fileprivate var segments: [BadgeSegmentControlView] = [] fileprivate var selectedSegment: BadgeSegmentControlView? // MARK: - Lifecycle required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Init self.layer.masksToBounds = true self.segmentAppearance = BadgeSegmentControlAppearance() } override public init(frame: CGRect) { super.init(frame: frame) // Init self.layer.masksToBounds = true self.segmentAppearance = BadgeSegmentControlAppearance() } public init(frame: CGRect, segmentAppearance: BadgeSegmentControlAppearance) { super.init(frame: frame) // Init self.segmentAppearance = segmentAppearance self.layer.masksToBounds = true } fileprivate func applyAppearence() { let appearence: BadgeSegmentControlAppearance = self.segmentAppearance ?? BadgeSegmentControlAppearance() // Divider self.dividerColour = appearence.dividerColour self.dividerWidth = appearence.dividerWidth // Background self.backgroundColor = appearence.backgroundColor // Border self.layer.borderWidth = appearence.borderWidth self.layer.cornerRadius = appearence.cornerRadius self.layer.borderColor = appearence.borderColor.cgColor } // MARK: - Actions fileprivate func selectSegment(_ segment: BadgeSegmentControlView) { segment.setSelected(true) self.selectedSegment = segment self.sendActions(for: .valueChanged) } fileprivate func deselectSegment() { self.selectedSegment?.setSelected(false) self.selectedSegment = nil } // MARK: - Manage Segment public func addSegmentWithTitle(_ title: String, onSelectionImage: UIImage? = nil, offSelectionImage: UIImage? = nil) { self.insertSegmentWithTitle(title, onSelectionImage: onSelectionImage, offSelectionImage: offSelectionImage, index: self.segments.count) } public func insertSegmentWithTitle(_ title: String?, onSelectionImage: UIImage?, offSelectionImage: UIImage?, index: Int) { let segment = BadgeSegmentControlView(appearance: self.segmentAppearance) segment.title = title segment.onSelectionImage = onSelectionImage segment.offSelectionImage = offSelectionImage segment.index = index segment.didSelectSegment = { [weak self] segment in if self!.selectedSegment != segment { self!.deselectSegment() self!.selectSegment(segment) } } segment.setupUIElements() self.resetSegmentIndicesWithIndex(index, byIndex: 1) self.segments.insert(segment, at: index) self.addSubview(segment) self.layoutSubviews() } public func removeSegmentAtIndex(_ index: Int) { assert(index >= 0 && index < self.segments.count, "Index (\(index)) is out of range") if index == self.selectedSegmentIndex { self.selectedSegmentIndex = UISegmentedControlNoSegment } self.resetSegmentIndicesWithIndex(index, byIndex: -1) let segment = self.segments.remove(at: index) segment.removeFromSuperview() self.updateSegmentsLayout() } fileprivate func resetSegmentIndicesWithIndex(_ index: Int, byIndex: Int) { if index < self.segments.count { for i in index..<self.segments.count { let segment = self.segments[i] segment.index += byIndex } } } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() self.updateSegmentsLayout() } fileprivate func updateSegmentsLayout() { guard self.segments.count > 0 else { return } if self.segments.count > 1 { let segmentWidth = ceil((self.frame.size.width - self.dividerWidth * CGFloat(self.segments.count-1)) / CGFloat(self.segments.count)) var originX: CGFloat = 0.0 for segment in self.segments { segment.frame = CGRect(x: originX, y: 0.0, width: segmentWidth, height: self.frame.size.height) originX += segmentWidth + self.dividerWidth } } else { self.segments[0].frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height) } self.setNeedsDisplay() } // MARK: Drawing override open func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext()! self.drawDividerWithContext(context) } fileprivate func drawDividerWithContext(_ context: CGContext) { context.saveGState() if self.segments.count > 1 { let path = CGMutablePath() var originX: CGFloat = self.segments[0].frame.size.width + self.dividerWidth/2.0 for index in 1..<self.segments.count { path.move(to: CGPoint(x: originX, y: 0.0)) path.addLine(to: CGPoint(x: originX, y: self.frame.size.height)) originX += self.segments[index].frame.width + self.dividerWidth } context.addPath(path) context.setStrokeColor(self.dividerColour.cgColor) context.setLineWidth(self.dividerWidth) context.drawPath(using: CGPathDrawingMode.stroke) } context.restoreGState() } // MARK: - Manage badge public func updateBadge(forValue value: Int, andSection section: Int) { self.segments[section].updateBadgeValue(forValue: value) } func badgeValue(for section: Int) -> Int { return segments[section].badgeValue } }
mit
d3562c873ee382b97daf686d338b0245
29.317073
113
0.586887
5.222689
false
false
false
false
akamatsu/FunikiIllumi
FunikiIllumi WatchKit Extension/InterfaceController.swift
1
4045
// // InterfaceController.swift // FunikiIllumi WatchKit Extension // // Created by aka on 2015/04/22. // Copyright (c) 2015 Masayuki Akamatsu. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { let appGroup = "group.org.akamatsu.FunikiIllumi" var wormhole: MMWormhole! let toumeiID = "Tou Mei" let yuruyakaID = "Yuru Yaka" let bonyariID = "Bon Yari" let chikachikaID = "Chika Chika" let dotabataID = "Dota Bata" let tokidokiID = "Toki Doki" let selectedColor = UIColor(hue: 0.5861, saturation: 1.0, brightness: 1.0, alpha: 1.0) let unselectedColor = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.2, alpha: 1.0) @IBOutlet weak var toumeiButton: WKInterfaceButton! @IBOutlet weak var yuruyakaButton: WKInterfaceButton! @IBOutlet weak var bonyariButton: WKInterfaceButton! @IBOutlet weak var chikachikaButton: WKInterfaceButton! @IBOutlet weak var dotabataButton: WKInterfaceButton! @IBOutlet weak var tokidokiButton: WKInterfaceButton! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. changeButtonColor(toumeiButton) // iOSとの通信 wormhole = MMWormhole(applicationGroupIdentifier:appGroup, optionalDirectory:"FunikiIllumi") // iOSからの受信 self.wormhole.listenForMessageWithIdentifier("fromApp", listener: { (messageObject) -> Void in if let presetID = messageObject.objectForKey("presetID") as? String { self.changeButtonColorByID(presetID) } }) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() WKInterfaceController.openParentApplication(["getPresetID": "getPresetID"], reply: {replyInfo, error in if let presetID = replyInfo["presetID"] as? String { self.changeButtonColorByID(presetID) } }) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func changeButtonColorByID(presetID: String) { switch presetID { case self.toumeiID: self.changeButtonColor(self.toumeiButton) case self.yuruyakaID: self.changeButtonColor(self.yuruyakaButton) case self.bonyariID: self.changeButtonColor(self.bonyariButton) case self.chikachikaID: self.changeButtonColor(self.chikachikaButton) case self.dotabataID: self.changeButtonColor(self.dotabataButton) case self.tokidokiID: self.changeButtonColor(self.tokidokiButton) default: self.changeButtonColor(self.toumeiButton) } } func changeButtonColor(button: WKInterfaceButton) { toumeiButton.setBackgroundColor(unselectedColor) yuruyakaButton.setBackgroundColor(unselectedColor) bonyariButton.setBackgroundColor(unselectedColor) chikachikaButton.setBackgroundColor(unselectedColor) dotabataButton.setBackgroundColor(unselectedColor) tokidokiButton.setBackgroundColor(unselectedColor) button.setBackgroundColor(selectedColor) } @IBAction func toumeiPushed() { changeButtonColor(toumeiButton) WKInterfaceController.openParentApplication(["buttonPushed": toumeiID],reply: nil) } @IBAction func yuruyakaPushed() { changeButtonColor(yuruyakaButton) WKInterfaceController.openParentApplication(["buttonPushed": yuruyakaID],reply: nil) } @IBAction func bonyariPushed() { changeButtonColor(bonyariButton) WKInterfaceController.openParentApplication(["buttonPushed": bonyariID],reply: nil) } @IBAction func chikachikaPushed() { changeButtonColor(chikachikaButton) WKInterfaceController.openParentApplication(["buttonPushed": chikachikaID],reply: nil) } @IBAction func dotabataPushed() { changeButtonColor(dotabataButton) WKInterfaceController.openParentApplication(["buttonPushed": dotabataID],reply: nil) } @IBAction func tokidokiPushed() { changeButtonColor(tokidokiButton) WKInterfaceController.openParentApplication(["buttonPushed": tokidokiID],reply: nil) } }
mit
beafaaff637e8c2c761f33c022c09be2
34.324561
96
0.770052
3.554281
false
false
false
false
bnotified/motified-iOS
motified/Event.swift
1
6788
// // Event.swift // Motified // // Created by Giancarlo Anemone on 3/10/15. // Copyright (c) 2015 Marcus Molchany. All rights reserved. // import Foundation import MapKit class Event: NSObject { var id: Int? var title: String? var desc: String? var startDate: NSDate? var endDate: NSDate? var categories: Array<EventCategory>? var createdBy: String? var isSubscribed: Bool? var subscribedUsers: Int? var address: String? var addressName: String? var location: CLLocation? var isReported: Bool = false var isApproved: Bool = false var page: Int! var index: Int! init(id: Int?, createdBy: String?, title: String?, desc: String?, startDate: NSDate?, endDate: NSDate?, categories: Array<Dictionary<String, AnyObject>>?, isSubscribed: Bool?, subscribedUsers: Int?, address: String?, addressName: String?, isApproved: Bool?, isReported: Bool?) { self.id = id self.createdBy = createdBy self.title = title self.desc = desc self.startDate = startDate self.endDate = endDate self.isSubscribed = isSubscribed self.subscribedUsers = subscribedUsers self.address = address self.addressName = addressName self.isApproved = isApproved! self.isReported = isReported! //self.location = coords self.categories = categories?.map({ (cat) -> EventCategory in return EventCategory(category: cat["category"] as! String, id: cat["id"] as! Int) }) } func getParams() -> Dictionary<String, AnyObject!> { return [ "name": self.title, "description": self.desc, "start": self.getFormattedStartDate(), "end": self.getFormattedEndDate(), "address": self.address, "address_name": self.addressName, "is_reported": self.isReported, "is_approved": self.isApproved ] } func getDisplayAddress() -> String { if (self.addressName != nil && self.addressName?.isEmpty == false) { return self.addressName! } return self.address! } func getImage() -> UIImage { let cat = self.categories!.first return cat!.image } func getCategoryTitle() -> String { return self.categories!.first!.category } func isInCategory(category: EventCategory) -> Bool { for cat in self.categories! { if cat.id == category.id { return true } } return false } func getFormattedDateRange() -> String { if self.startDate == nil || self.endDate == nil { return "" } if (self.startDate?.isOnSameDayAs(self.endDate!) != nil) { return self.getSameDayDateRange() } else { return self.getMultipleDayDateRange() } } func getFormattedDate(date: NSDate) -> String { let formatter = MotifiedDateFormatter(format: MotifiedDateFormat.Server) return formatter.stringFromDate(date) } func getFormattedStartDate() -> String { return self.getFormattedDate(self.startDate!) } func getFormattedEndDate() -> String { return self.getFormattedDate(self.endDate!) } func reportEvent(done: (NSError!) -> ()) { let params = [ "is_reported": true ] let url = NSString(format: "api/events/%d" , self.id!) LoginManager.manager.PATCH(url as String, parameters: params, success: { (NSURLSessionDataTask, AnyObject) -> Void in done(nil) }, failure: { (NSURLSessionDataTask, NSError) -> Void in done(NSError) }) } private func getSameDayDateRange() -> String { let firstFormat = MotifiedDateFormatter(format: MotifiedDateFormat.ClientLong) let secondFormat = MotifiedDateFormatter(format: MotifiedDateFormat.ClientTimeOnly) let start = firstFormat.stringFromDate(self.startDate!.toLocalTime()) let end = secondFormat.stringFromDate(self.endDate!.toLocalTime()) return "\(start)-\(end)" } private func getMultipleDayDateRange() -> String { let format = MotifiedDateFormatter(format: MotifiedDateFormat.ClientLong) let start = format.stringFromDate(self.startDate!.toLocalTime()) let end = format.stringFromDate(self.endDate!.toLocalTime()) return "\(start)-\(end)" } func notifyUserOnDay() { let dateInterval = self.startDate!.toLocalTime().timeIntervalSinceNow - 60*60 self.notifyUserAtInterval(dateInterval, message: "Event Starting In 1 Hour: \(self.title!)") } func notifyUserDayPrior() { let dateInterval = self.startDate!.toLocalTime().timeIntervalSinceNow - 60*60*24 self.notifyUserAtInterval(dateInterval, message: "Event Tomorrow: \(self.title!)") } func notifyUserOnStart() { let dateInterval = self.startDate!.toLocalTime().timeIntervalSinceNow self.notifyUserAtInterval(dateInterval, message: "Event Starting Now: \(self.title!)") } func toggleNotify() { if self.isSubscribed! { self.cancelNotify() } else { self.notify() } } func cancelNotify() { let app = UIApplication.sharedApplication() let notifications = app.scheduledLocalNotifications for nt in notifications! as [UILocalNotification] { let userInfo = nt.userInfo as! Dictionary<String, AnyObject>! if userInfo != nil { if let uid = userInfo["id"]! as? Int { if uid == self.id { NSLog("Cancelling Notification") app.cancelLocalNotification(nt) } } } } } func notify() { if UserPreferenceManager.shouldAlert(PREF_DAY_PRIOR_KEY) { self.notifyUserDayPrior() } if UserPreferenceManager.shouldAlert(PREF_HOUR_PRIOR_KEY) { self.notifyUserOnDay() } if UserPreferenceManager.shouldAlert(PREF_ON_START_KEY) { self.notifyUserOnStart() } } func notifyUserAtInterval(interval: NSTimeInterval, message: String) { if interval < 0 { return () } let notification = UILocalNotification() notification.fireDate = NSDate(timeIntervalSinceNow: interval) notification.alertBody = message notification.userInfo = ["id":self.id!] UIApplication.sharedApplication().scheduleLocalNotification(notification) } }
mit
3e70309817a01f4a34d07f16179f24b9
32.771144
282
0.599146
4.72373
false
false
false
false
rohan-panchal/Scaffold
Scaffold/Classes/Foundation/SCAFFoundation.swift
1
708
// // SCAFFoundation.swift // Pods // // Created by Rohan Panchal on 9/26/16. // // import Foundation public struct Platform { public static var iPhone: Bool { return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone } public static var iPad: Bool { return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad } public static var iOS: Bool { return TARGET_OS_IOS != 0 } public static var TVOS: Bool { return TARGET_OS_TV != 0 } public static var WatchOS: Bool { return TARGET_OS_WATCH != 0 } public static var Simulator: Bool { return TARGET_OS_SIMULATOR != 0 } }
mit
5e11afb1a5fb762cbaac873c7593bc60
17.631579
70
0.583333
4.068966
false
false
false
false
rudedogg/Highlightr
Pod/Classes/Theme.swift
1
12110
// // Theme.swift // Pods // // Created by Illanes, J.P. on 4/24/16. // // import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias RPColor = UIColor public typealias RPFont = UIFont #else import AppKit public typealias RPColor = NSColor public typealias RPFont = NSFont #endif private typealias RPThemeDict = [String:[String:AnyObject]] private typealias RPThemeStringDict = [String:[String:String]] /// Theme parser, can be used to configure the theme parameters. open class Theme { internal let theme : String internal var lightTheme : String! open var codeFont : RPFont! open var boldCodeFont : RPFont! open var italicCodeFont : RPFont! fileprivate var themeDict : RPThemeDict! fileprivate var strippedTheme : RPThemeStringDict! /// Default background color for the current theme. open var themeBackgroundColor : RPColor! init(themeString: String) { theme = themeString setCodeFont(RPFont(name: "Courier", size: 14)!) strippedTheme = stripTheme(themeString) lightTheme = strippedThemeToString(strippedTheme) themeDict = strippedThemeToTheme(strippedTheme) var bkgColorHex = strippedTheme[".hljs"]?["background"] if(bkgColorHex == nil) { bkgColorHex = strippedTheme[".hljs"]?["background-color"] } if let bkgColorHex = bkgColorHex { if(bkgColorHex == "white") { themeBackgroundColor = RPColor(white: 1, alpha: 1) }else if(bkgColorHex == "black") { themeBackgroundColor = RPColor(white: 0, alpha: 1) }else { let range = bkgColorHex.range(of: "#") let str = bkgColorHex.substring(from: (range?.lowerBound)!) themeBackgroundColor = colorWithHexString(str) } }else { themeBackgroundColor = RPColor.white } } /** Changes the theme font. - parameter font: UIFont (iOS or tvOS) or NSFont (OSX) */ open func setCodeFont(_ font: RPFont) { codeFont = font #if os(iOS) || os(tvOS) let boldDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Bold"]) let italicDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Italic"]) let obliqueDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Oblique"]) #else let boldDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Bold"]) let italicDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Italic"]) let obliqueDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Oblique"]) #endif boldCodeFont = RPFont(descriptor: boldDescriptor, size: font.pointSize) italicCodeFont = RPFont(descriptor: italicDescriptor, size: font.pointSize) if(italicCodeFont == nil || italicCodeFont.familyName != font.familyName) { italicCodeFont = RPFont(descriptor: obliqueDescriptor, size: font.pointSize) } else if(italicCodeFont == nil ) { italicCodeFont = font } if(boldCodeFont == nil) { boldCodeFont = font } if(themeDict != nil) { themeDict = strippedThemeToTheme(strippedTheme) } } internal func applyStyleToString(_ string: String, styleList: [String]) -> NSAttributedString { let returnString : NSAttributedString if styleList.count > 0 { var attrs = [String:AnyObject]() attrs[NSFontAttributeName] = codeFont for style in styleList { if let themeStyle = themeDict[style] { for (attrName, attrValue) in themeStyle { attrs.updateValue(attrValue, forKey: attrName) } } } returnString = NSAttributedString(string: string, attributes:attrs ) } else { returnString = NSAttributedString(string: string, attributes:[NSFontAttributeName:codeFont] ) } return returnString } fileprivate func stripTheme(_ themeString : String) -> [String:[String:String]] { let objcString = (themeString as NSString) let cssRegex = try! NSRegularExpression(pattern: "(?:(\\.[a-zA-Z0-9\\-_]*(?:[, ]\\.[a-zA-Z0-9\\-_]*)*)\\{([^\\}]*?)\\})", options:[.caseInsensitive]) let results = cssRegex.matches(in: themeString, options: [.reportCompletion], range: NSMakeRange(0, objcString.length)) var resultDict = [String:[String:String]]() for result in results { if(result.numberOfRanges == 3) { var attributes = [String:String]() let cssPairs = objcString.substring(with: result.rangeAt(2)).components(separatedBy: ";") for pair in cssPairs { let cssPropComp = pair.components(separatedBy: ":") if(cssPropComp.count == 2) { attributes[cssPropComp[0]] = cssPropComp[1] } } if attributes.count > 0 { resultDict[objcString.substring(with: result.rangeAt(1))] = attributes } } } var returnDict = [String:[String:String]]() for (keys,result) in resultDict { let keyArray = keys.replacingOccurrences(of: " ", with: ",").components(separatedBy: ",") for key in keyArray { var props : [String:String]? props = returnDict[key] if props == nil { props = [String:String]() } for (pName, pValue) in result { props!.updateValue(pValue, forKey: pName) } returnDict[key] = props! } } return returnDict } fileprivate func strippedThemeToString(_ theme: RPThemeStringDict) -> String { var resultString = "" for (key, props) in theme { resultString += key+"{" for (cssProp, val) in props { if(key != ".hljs" || (cssProp.lowercased() != "background-color" && cssProp.lowercased() != "background")) { resultString += "\(cssProp):\(val);" } } resultString+="}" } return resultString } fileprivate func strippedThemeToTheme(_ theme: RPThemeStringDict) -> RPThemeDict { var returnTheme = RPThemeDict() for (className, props) in theme { var keyProps = [String:AnyObject]() for (key, prop) in props { switch key { case "color": keyProps[attributeForCSSKey(key)] = colorWithHexString(prop) break case "font-style": keyProps[attributeForCSSKey(key)] = fontForCSSStyle(prop) break case "font-weight": keyProps[attributeForCSSKey(key)] = fontForCSSStyle(prop) break case "background-color": keyProps[attributeForCSSKey(key)] = colorWithHexString(prop) break default: break } } if keyProps.count > 0 { let key = className.replacingOccurrences(of: ".", with: "") returnTheme[key] = keyProps } } return returnTheme } fileprivate func fontForCSSStyle(_ fontStyle:String) -> RPFont { switch fontStyle { case "bold", "bolder", "600", "700", "800", "900": return boldCodeFont case "italic", "oblique": return italicCodeFont default: return codeFont } } fileprivate func attributeForCSSKey(_ key: String) -> String { switch key { case "color": return NSForegroundColorAttributeName case "font-weight": return NSFontAttributeName case "font-style": return NSFontAttributeName case "background-color": return NSBackgroundColorAttributeName default: return NSFontAttributeName } } fileprivate func colorWithHexString (_ hex:String) -> RPColor { var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (cString.hasPrefix("#")) { cString = (cString as NSString).substring(from: 1) } else { switch cString { case "white": return RPColor(white: 1, alpha: 1) case "black": return RPColor(white: 0, alpha: 1) case "red": return RPColor(red: 1, green: 0, blue: 0, alpha: 1) case "green": return RPColor(red: 0, green: 1, blue: 0, alpha: 1) case "blue": return RPColor(red: 0, green: 0, blue: 1, alpha: 1) default: return RPColor.gray } } if (cString.characters.count != 6 && cString.characters.count != 3 ) { return RPColor.gray } var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; var divisor : CGFloat if (cString.characters.count == 6 ) { let rString = (cString as NSString).substring(to: 2) let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2) let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2) Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) divisor = 255.0 }else { let rString = (cString as NSString).substring(to: 1) let gString = ((cString as NSString).substring(from: 1) as NSString).substring(to: 1) let bString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 1) Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) divisor = 15.0 } return RPColor(red: CGFloat(r) / divisor, green: CGFloat(g) / divisor, blue: CGFloat(b) / divisor, alpha: CGFloat(1)) } }
mit
70a33fe3fb26350e2e2ac6a4074d93fd
33.403409
157
0.514781
5.450045
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
4 - Tables and Persistence/6 - Intermediate Table Views/lab/FavoriteBook/FavoriteBook/BookFormViewController.swift
1
1179
import UIKit class BookFormViewController: UIViewController { struct PropertyKeys { static let unwind = "UnwindToBookTable" } var book: Book? @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var authorTextField: UITextField! @IBOutlet weak var genreTextField: UITextField! @IBOutlet weak var lengthTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() updateView() } func updateView() { guard let book = book else {return} titleTextField.text = book.title authorTextField.text = book.author genreTextField.text = book.genre lengthTextField.text = book.length } @IBAction func saveButtonTapped(_ sender: Any) { guard let title = titleTextField.text, let author = authorTextField.text, let genre = genreTextField.text, let length = lengthTextField.text else {return} book = Book(title: title, author: author, genre: genre, length: length) performSegue(withIdentifier: PropertyKeys.unwind, sender: self) } }
mit
4c48992d0601571947a357cba07d24dd
27.071429
79
0.631043
5.081897
false
false
false
false
AugustRush/Stellar
StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/TimingFunction.swift
1
5779
//Copyright (c) 2016 // //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 /// A set of preset bezier curves. public enum TimingFunctionType { /// Equivalent to `kCAMediaTimingFunctionDefault`. case `default` /// Equivalent to `kCAMediaTimingFunctionEaseIn`. case easeIn /// Equivalent to `kCAMediaTimingFunctionEaseOut`. case easeOut /// Equivalent to `kCAMediaTimingFunctionEaseInEaseOut`. case easeInEaseOut /// No easing. case linear /// Inspired by the default curve in Google Material Design. case swiftOut /// case backEaseIn /// case backEaseOut /// case backEaseInOut /// case bounceOut /// case sine /// case circ /// case exponentialIn /// case exponentialOut /// case elasticIn /// case bounceReverse /// case elasticOut /// custom case custom(Double, Double, Double, Double) func easing() -> TimingSolvable { switch self { case .default: return UnitBezier(p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0) case .easeIn: return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 1.0, p2y: 1.0) case .easeOut: return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 0.58, p2y: 1.0) case .easeInEaseOut: return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 0.58, p2y: 1.0) case .linear: return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 1.0, p2y: 1.0) case .swiftOut: return UnitBezier(p1x: 0.4, p1y: 0.0, p2x: 0.2, p2y: 1.0) case .backEaseIn: return EasingContainer(easing: { (t: Double) in return t * t * t - t * sin(t * M_PI) }) case .backEaseOut: return EasingContainer(easing: { (t: Double) in let f = (1 - t); return 1 - (f * f * f - f * sin(f * M_PI)); }) case .backEaseInOut: return EasingContainer(easing: { (t: Double) in if(t < 0.5) { let f = 2 * t; return 0.5 * (f * f * f - f * sin(f * M_PI)); } else { let f = (1.0 - (2.0 * t - 1.0)); let cubic = f * f * f return 0.5 * (1.0 - (cubic - f * sin(f * M_PI))) + 0.5; } }) case .bounceOut: return EasingContainer(easing: { (t: Double) in if(t < 4/11.0){ return (121 * t * t)/16.0; } else if(t < 8/11.0){ return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0; }else if(t < 9/10.0){ return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0; }else{ return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0; } }) case .sine: return EasingContainer(easing: { (t: Double) in return 1 - cos( t * M_PI / 2.0) }) case .circ: return EasingContainer(easing: { (t: Double) in return 1 - sqrt( 1.0 - t * t ) }) case .exponentialIn: return EasingContainer(easing: { (t: Double) in return (t == 0.0) ? t : pow(2, 10 * (t - 1)) }) case .exponentialOut: return EasingContainer(easing: { (t: Double) in return (t == 1.0) ? t : 1 - pow(2, -10 * t) }) case .elasticIn: return EasingContainer(easing: { (t: Double) in return sin(13.0 * M_PI_2 * t) * pow(2, 10 * (t - 1)) }) case .elasticOut: return EasingContainer(easing: { (t: Double) in return sin(-13.0 * M_PI_2 * (t + 1)) * pow(2, -10 * t) + 1.0; }) case .bounceReverse: return EasingContainer(easing: { (t: Double) in var bounce: Double = 4.0 var pow2 = 0.0 repeat { bounce = bounce - 1.0 pow2 = pow(2, bounce) } while (t < (pow2 - 1.0 ) / 11.0) return 1 / pow( 4, 3 - bounce ) - 7.5625 * pow( ( pow2 * 3 - 2 ) / 22 - t, 2 ); }) case .custom(let p1x,let p1y,let p2x,let p2y): return UnitBezier(p1x: p1x, p1y: p1y, p2x: p2x, p2y: p2y) } } } class EasingContainer: TimingSolvable { let easing: (Double) -> Double init(easing: @escaping (Double) -> Double) { self.easing = easing } // func solveOn(_ time: Double, epslion: Double) -> Double { return self.easing(time) } }
mit
292df61e3908def830474bb3b65b351c
36.044872
462
0.518083
3.71879
false
false
false
false