repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
IngmarStein/swift
refs/heads/master
test/SILGen/objc_extensions.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_extensions_helper class Sub : Base {} extension Sub { override var prop: String! { didSet { // Ignore it. } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC15objc_extensions3Subg4propGSQSS_ // CHECK: = super_method [volatile] %1 : $Sub, #Base.prop!setter.1.foreign // CHECK: = function_ref @_TFC15objc_extensions3SubW4propGSQSS_ // CHECK: } } func foo() { } override func objCBaseMethod() {} } // CHECK-LABEL: sil hidden @_TF15objc_extensions20testOverridePropertyFCS_3SubT_ func testOverrideProperty(_ obj: Sub) { // CHECK: = class_method [volatile] %0 : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> () obj.prop = "abc" } // CHECK: } testOverrideProperty(Sub()) // CHECK-LABEL: sil shared [thunk] @_TFC15objc_extensions3Sub3fooFT_T_ // CHECK: function_ref @_TTDFC15objc_extensions3Sub3foofT_T_ // CHECK: sil shared [transparent] [thunk] @_TTDFC15objc_extensions3Sub3foofT_T_ // CHECK: class_method [volatile] %0 : $Sub, #Sub.foo!1.foreign func testCurry(_ x: Sub) { _ = x.foo } extension Sub { var otherProp: String { get { return "hello" } set { } } } class SubSub : Sub { // CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSub14objCBaseMethodfT_T_ // CHECK: super_method [volatile] %0 : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> () , $@convention(objc_method) (Sub) -> () override func objCBaseMethod() { super.objCBaseMethod() } } extension SubSub { // CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSubs9otherPropSS // CHECK: = super_method [volatile] %1 : $SubSub, #Sub.otherProp!getter.1.foreign // CHECK: = super_method [volatile] %1 : $SubSub, #Sub.otherProp!setter.1.foreign override var otherProp: String { didSet { // Ignore it. } } } // SR-1025 extension Base { fileprivate static var x = 1 } // CHECK-LABEL: sil hidden @_TF15objc_extensions19testStaticVarAccessFT_T_ func testStaticVarAccess() { // CHECK: [[F:%.*]] = function_ref @_TFE15objc_extensionsCSo4BaseauP33_1F05E59585E0BB585FCA206FBFF1A92D1xSi // CHECK: [[PTR:%.*]] = apply [[F]]() // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] _ = Base.x }
78393b4a552c9d38ece3cf68b91fdacd
28.5875
138
0.660752
false
true
false
false
louisdh/microcontroller-kit
refs/heads/master
Sources/MicrocontrollerKit/Nibble.swift
mit
1
// // Nibble.swift // MicrocontrollerKit // // Created by Louis D'hauwe on 14/08/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation /// 4 bits public struct Nibble: Hashable { public let b0: Bit public let b1: Bit public let b2: Bit public let b3: Bit public init(b0: Bit, b1: Bit, b2: Bit, b3: Bit) { self.b0 = b0 self.b1 = b1 self.b2 = b2 self.b3 = b3 } } extension Nibble: CustomStringConvertible { public var description: String { return "\(b3)\(b2)\(b1)\(b0)" } } extension Nibble: Comparable { public static func <(lhs: Nibble, rhs: Nibble) -> Bool { return lhs.decimalValue < rhs.decimalValue } } public extension Nibble { var decimalValue: Int { return 1 * b0.rawValue + 2 * b1.rawValue + 4 * b2.rawValue + 8 * b3.rawValue } } public extension Nibble { static func + (lhs: Nibble, rhs: Nibble) -> (out: Nibble, c: Bit) { let (s0, c0) = halfAdder(a: lhs.b0, b: rhs.b0) let (s1, c1) = fullAdder(a: lhs.b1, b: rhs.b1, cIn: c0) let (s2, c2) = fullAdder(a: lhs.b2, b: rhs.b2, cIn: c1) let (s3, c3) = fullAdder(a: lhs.b3, b: rhs.b3, cIn: c2) let s = Nibble(b0: s0, b1: s1, b2: s2, b3: s3) return (s, c3) } }
06cb7ed573de8d500d8907d3e537a7a3
17.257576
78
0.624896
false
false
false
false
crash-wu/CSRefresher
refs/heads/master
MyViewController.swift
mit
1
// // MyViewController.swift // CSRefresh // // Created by 吴小星 on 16/6/5. // Copyright © 2016年 crash. All rights reserved. // import UIKit class MyViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView : UITableView? var count : Int = 10 override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height), style: .Plain) tableView?.dataSource = self tableView?.delegate = self self.view.addSubview(tableView!) tableView?.autoresizingMask = [.FlexibleHeight,.FlexibleWidth] tableView?.separatorStyle = .None tableView?.dropDownToRefresh({ (_) in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] in self?.tableView?.header?.endRefreshing() } }) tableView?.headerPullToRefreshText = "下拉刷新" tableView?.headerReleaseToRefreshText = "松开马上刷新" tableView?.headerRefreshingText = "正在加载..." tableView?.pullUpToRefresh ({ (_) in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] in self?.count = (self?.count)! + 10 self?.tableView?.reloadData() self?.tableView?.footer?.endRefreshing() } }) tableView?.footerPullToRefreshText = "上拉加载更多" tableView?.footerReleaseToRefreshText = "重开马上加载" tableView?.footerRefreshingText = "正在加载..." } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID = "cellID" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? Cell if cell == nil{ cell = Cell(style: .Default, reuseIdentifier: cellID) } cell?.label.text = "测试单元格:\(indexPath.row)" return cell! } }
f234497f119933ea2f9e16558bc6c807
28.409091
137
0.576121
false
false
false
false
devios1/Gravity
refs/heads/master
Plugins/Default.swift
mit
1
// // Default.swift // Gravity // // Created by Logan Murray on 2016-02-15. // Copyright © 2016 Logan Murray. All rights reserved. // import Foundation // do we really need/want this class? maybe rename? @available(iOS 9.0, *) extension Gravity { @objc public class Default: GravityPlugin { // private static let keywords = ["id", "zIndex", "gravity"] // add more? move? // TODO: these should ideally be blocked at the same location they are used (e.g. zIndex and gravity in Layout, id should be blocked in the kernel. var defaultValues = [GravityNode: [String: AnyObject?]]() // when should we purge this? // deprecated // public override var recognizedAttributes: [String]? { // get { // return nil // all attributes // } // } static var swizzleToken: dispatch_once_t = 0 // we should abstract this to a function in core that just swaps two selectors on a class like swizzle(UIView.self, selector1, selector2) public override class func initialize() { dispatch_once(&swizzleToken) { // method swizzling: let loadView_orig = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.loadView)) let loadView_swiz = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.grav_loadView)) if class_addMethod(UIViewController.self, #selector(UIViewController.loadView), method_getImplementation(loadView_swiz), method_getTypeEncoding(loadView_swiz)) { class_replaceMethod(UIViewController.self, #selector(UIViewController.grav_loadView), method_getImplementation(loadView_orig), method_getTypeEncoding(loadView_orig)); } else { method_exchangeImplementations(loadView_orig, loadView_swiz); } } } public override func instantiateView(node: GravityNode) -> UIView? { var type: AnyClass? = NSClassFromString(node.nodeName) if type == nil { // couldn't find type; try Swift style naming if let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String { type = NSClassFromString("\(appName).\(node.nodeName)") } } if let type = type as? GravityElement.Type where type.instantiateView != nil { return type.instantiateView!(node) } else if let type = type as? UIView.Type { // var view: UIView // tryBlock { let view = type.init() view.translatesAutoresizingMaskIntoConstraints = false // do we need this? i think so // TODO: should we set clipsToBounds for views by default? // } return view // TODO: determine if the instance is an instance of UIView or UIViewController and handle the latter by embedding a view controller } else if let type = type as? UIViewController.Type { let vc = type.init() vc.gravityNode = node node.controller = vc // this might be a problem since node.view is not set at this point (dispatch_async?) // FIXME: there is a design issue here: accessing vc.view calls viewDidLoad on the vc; we should think of a way to avoid doing this until the very end, which may involve wrapping it in an extra view, or swizzling viewDidLoad return UIView() // this will be bound to the node; is a plain UIView enough? //node._view = vc.view // let container = UIView() // container.addSu } return nil } public override func selectAttribute(node: GravityNode, attribute: String, inout value: GravityNode?) -> GravityResult { value = node.attributes[attribute] // good? return .Handled } // this is really a singleton; should we provide a better way for this to be overridden? // we should turn this into processValue() public override func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult { // guard let node = value.parentNode else { // return .NotHandled // } guard let attribute = attribute else { return .NotHandled } // NSLog("KeyPath \(attribute) converted var objectValue: AnyObject? if value != nil { objectValue = value!.objectValue tryBlock { if self.defaultValues[node] == nil { self.defaultValues[node] = [String: AnyObject?]() } if self.defaultValues[node]![attribute] == nil { // only store the default value the first time (so it is deterministic) let defaultValue = node.view.valueForKeyPath(attribute) self.defaultValues[node]![attribute] = defaultValue } } } else { if let nodeIndex = defaultValues[node] { if let defaultValue = nodeIndex[attribute] { NSLog("Default value found for attribute \(attribute): \(defaultValue)") objectValue = defaultValue } } } if let objectValue = objectValue { if tryBlock({ NSLog("Setting property \(attribute) to value: \(objectValue)") node.view.setValue(objectValue, forKeyPath: attribute) }) != nil { NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") return .NotHandled } } else { return .NotHandled } return .Handled } // public override func postprocessValue(node: GravityNode, attribute: String, value: GravityNode) -> GravityResult { // // TODO: if value is a node, check property type on target and potentially convert into a view (view controller?) // // var propertyType: String? = nil // // // this is string.endsWith in swift. :| lovely. // if attribute.lowercaseString.rangeOfString("color", options:NSStringCompareOptions.BackwardsSearch)?.endIndex == attribute.endIndex { // propertyType = "UIColor" // bit of a hack because UIView.backgroundColor doesn't seem to know its property class via inspection :/ // } // // if propertyType == nil { //// NSLog("Looking up property for \(node.view.dynamicType) . \(attribute)") // // is there a better/safer way to do this reliably? // let property = class_getProperty(NSClassFromString("\(node.view.dynamicType)"), attribute) // if property != nil { // if let components = String.fromCString(property_getAttributes(property))?.componentsSeparatedByString("\"") { // if components.count >= 2 { // propertyType = components[1] //// NSLog("propertyType: \(propertyType!)") // } // } // } // } // // var convertedValue: AnyObject? = value.stringValue // // if let propertyType = propertyType { // convertedValue = value.convert(propertyType) //// if let converter = Conversion.converters[propertyType!] { //// var newOutput: AnyObject? = output //// if converter(input: input, output: &newOutput) == .Handled { //// output = newOutput! // this feels ugly //// return .Handled //// } //// } // } // //// NSLog("KeyPath \(attribute) converted // // if tryBlock({ // node.view.setValue(convertedValue, forKeyPath: attribute) // }) != nil { // NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") // } // } // public override func postprocessElement(node: GravityNode) -> GravityResult { // } } } @available(iOS 9.0, *) extension UIViewController { public func grav_loadView() { if self.gravityNode != nil { self.view = self.gravityNode?.view // TODO: make sure this works for all levels of embedded VCs } if !self.isViewLoaded() { grav_loadView() } } }
1c2dfd216697c731ab99d86b8aee0bae
36.19898
228
0.676955
false
false
false
false
nab0y4enko/PrettyFloatingMenuView
refs/heads/master
Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Oleksii Naboichenko on 5/11/17. // Copyright © 2017 Oleksii Naboichenko. All rights reserved. // import UIKit import PrettyFloatingMenuView class ViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var menuView: PrettyFloatingMenuView! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() prepareMenuView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // toggle test menuView.toggle() DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in guard let strongSelf = self else { return } strongSelf.menuView.toggle() } } // MARK: - Private Instance Methods private func prepareMenuView() { let firstItemView = PrettyFloatingMenuItemView() firstItemView.title = NSAttributedString(string: "Test Item 1") firstItemView.iconImage = UIImage(named: "community-icon") firstItemView.action = { (item) in print(item.title!.string) } let secondItemView = PrettyFloatingMenuItemView() secondItemView.title = NSAttributedString(string: "Test Item 2") secondItemView.iconImage = UIImage(named: "trophy-icon") secondItemView.action = { (item) in print(item.title!.string) } let thirdItemView = PrettyFloatingMenuItemView() thirdItemView.title = NSAttributedString(string: "Test Item 3") thirdItemView.iconImage = UIImage(named: "alert-icon") thirdItemView.action = { (item) in print(item.title!.string) } let fourthItemView = PrettyFloatingMenuItemView() fourthItemView.title = NSAttributedString(string: "Test Item 4") fourthItemView.iconImage = UIImage(named: "community-icon") fourthItemView.action = { (item) in print(item.title!.string) } fourthItemView.titleVerticalPosition = .top let fifthItemView = PrettyFloatingMenuItemView() fifthItemView.title = NSAttributedString(string: "Test Item 5") fifthItemView.iconImage = UIImage(named: "trophy-icon") fifthItemView.action = { (item) in print(item.title!.string) } fifthItemView.titleVerticalPosition = .top menuView.itemViews = [firstItemView, secondItemView, thirdItemView, fourthItemView, fifthItemView] // menuView.itemViews = [firstItemView] menuView.setImage(UIImage(named: "menu-icon"), forState: .closed) menuView.setImage(UIImage(named: "close-icon"), forState: .opened) menuView.setImageTintColor(UIColor.red, forState: .opened) menuView.setBackgroundColor(UIColor.yellow, forState: .closed) menuView.setBackgroundColor(UIColor.blue, forState: .opened) menuView.setOverlayColor(UIColor.green.withAlphaComponent(0.5), forState: .opened) menuView.animator = PrettyFloatingMenuRoundSlideAnimator() } }
b075615cc89d1f61513a5dbb583dfc93
34.897727
106
0.646724
false
true
false
false
juangrt/SwiftImageUploader
refs/heads/master
SwiftImageUploader/PhotoShareService.swift
gpl-3.0
1
// // Uploader.swift // SwiftImageUploader // // Created by Juan Carlos Garzon on 6/22/16. // Copyright © 2016 ZongWare. All rights reserved. // import Foundation import UIKit import Alamofire //Make this a singleton class class PhotoShareService { static let sharedInstance = PhotoShareService() enum SegmentType { case PARTY ,MEDIA , USER } func segment(type:SegmentType) -> String { switch type { case SegmentType.PARTY: return "party" case SegmentType.MEDIA: return "media" case SegmentType.USER: return "user" } } func segmentUpload(type:SegmentType) -> String { switch type { case SegmentType.PARTY: return "headerImage" case SegmentType.MEDIA: return "mediaImage" case SegmentType.USER: return "profileImage" } } private func segmentCreate(type:SegmentType) -> [String] { var createParams = [String]() switch type { case SegmentType.PARTY: createParams.append("title") createParams.append("slug") break case SegmentType.MEDIA: break case SegmentType.USER: break } createParams.append("meta") return createParams } func new(seg:SegmentType, image: UIImage, params:[String:String], completion: (result: AnyObject) -> Void) { let apiUrl:String = Config.sharedInstance.host + self.segment(seg) + "/new" let imageData:NSData! = UIImageJPEGRepresentation(image, 1.0) Alamofire.upload(.POST, apiUrl, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: imageData!, name: self.segmentUpload(seg), fileName: "upload.jpg" , mimeType: "image/jpg") for param in params { multipartFormData.appendBodyPart(data: param.1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name : param.0) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } completion(result: "") }) } func get(seg:SegmentType, page:NSNumber , completion: (result: AnyObject) -> Void) { Alamofire.request(.GET , Config.sharedInstance.host + segment(seg)).responseJSON{ response in switch response.result { case .Success(let JSON): let partiesRaw = JSON completion(result: partiesRaw) case .Failure(let error): print("Request failed with error: \(error)") } } } func uploadFile(seg:SegmentType, image: UIImage) { let apiUrl:String = Config.sharedInstance.host + self.segment(seg) + "/new" //Add logic to upload right image representation let imageData:NSData! = UIImageJPEGRepresentation(image, 1.0) Alamofire.upload(.POST, apiUrl, multipartFormData: { multipartFormData in //Appends the image //To Do: Ensure proper mimeType multipartFormData.appendBodyPart(data: imageData!, name: self.segmentUpload(seg), fileName: "upload.jpg" , mimeType: "image/jpg") //To Do: Dynamic keys? multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"name") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } }) } }
a90eb2edb91bf15a0730de46885d7025
32.503497
158
0.499165
false
false
false
false
programmerC/JNews
refs/heads/master
JNews/UILabel+Helpers.swift
gpl-3.0
1
// // UILabel+Helpers.swift // JNews // // Created by ChenKaijie on 16/7/23. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit import Foundation private var labelNumberKey : Void? private var labelTimerKey : Void? extension UILabel { public var labelNumber: NSNumber? { get { return objc_getAssociatedObject(self, &labelNumberKey) as? NSNumber } } private func setLabelNumber(number: NSNumber) { objc_setAssociatedObject(self, &labelNumberKey, number, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public var labelTimer: NSTimer? { get { return objc_getAssociatedObject(self, &labelTimerKey) as? NSTimer } } private func setLabelTimer(timer: NSTimer) { objc_setAssociatedObject(self, &labelTimerKey, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private let BeginNumber = "BeginNumber" private let EndNumber = "EndNumber" private let RangeNumber = "RangeNumber" private let Attributes = "Attributes" private let frequency = 1.0/30.0 extension UILabel { public func setLabelText(text: String, duration: NSTimeInterval, delay: NSTimeInterval, attributed: AnyObject?) { // 使之前的Timer失效 self.labelTimer?.invalidate() // Duration 执行时间 var durationTime: NSTimeInterval = duration < 0.8 ? 0.8 : duration // 初始化 labelNumber self.setLabelNumber(NSNumber.init(int: 0)) let userDict: NSMutableDictionary = NSMutableDictionary() let beginNumber: NSNumber = 0 userDict.setValue(beginNumber, forKey: BeginNumber) let tempNumber = NSInteger(text) guard (tempNumber != nil) else { return } let endNumber = Int64(tempNumber!) guard endNumber < INT64_MAX else { return } userDict.setValue(NSNumber.init(longLong: endNumber), forKey: EndNumber) // 如果每次增长少于数字少于1,减少执行时间 if Double(endNumber)*frequency/durationTime < 1.0 { durationTime = durationTime*0.3 } // 数字滚动每次增长的数目 let rangeNumber = (Double(endNumber)*frequency)/durationTime userDict.setValue(NSNumber(double: rangeNumber), forKey: RangeNumber) if attributed != nil { userDict.setValue(attributed, forKey: Attributes) } // Delay 延时 Delay(delay) { self.setLabelTimer(NSTimer.scheduledTimerWithTimeInterval(frequency, target: self, selector: #selector(UILabel.labelAnimation(_:)), userInfo: userDict, repeats: true)) // 滑动状态和普通状态都执行timer NSRunLoop.currentRunLoop().addTimer(self.labelTimer!, forMode: NSRunLoopCommonModes) } } public func labelAnimation(timer: NSTimer) { if timer.userInfo?.valueForKey(RangeNumber)?.floatValue >= 1.0 { let rangeInteger = timer.userInfo?.valueForKey(RangeNumber)?.longLongValue; let resultInteger = (self.labelNumber?.longLongValue)! + rangeInteger!; self.setLabelNumber(NSNumber(longLong: resultInteger)) } else { let rangeInteger = timer.userInfo?.valueForKey(RangeNumber)?.floatValue; let resultInteger = (self.labelNumber?.floatValue)! + rangeInteger!; self.setLabelNumber(NSNumber(float: resultInteger)) } // 设置 Text let numberText = String.init(format: "%.6d", self.labelNumber!.integerValue) assert(numberText.characters.count == 6, "LabelNumber转换位数出错:\(numberText)") let numberTextString = NSMutableString.init(string: numberText) numberTextString.insertString("h ", atIndex: 2) numberTextString.insertString("m ", atIndex: 6) numberTextString.insertString("s ", atIndex: 10) self.text = numberTextString as String // 设置 Attributes let attributes = timer.userInfo?.valueForKey(Attributes) if attributes != nil { self.drawAttributes(attributes!) } let endNumber : NSNumber = timer.userInfo?.valueForKey(EndNumber) as! NSNumber if self.labelNumber?.longLongValue >= endNumber.longLongValue { // 大于当前时间 let resultNumber: NSNumber = timer.userInfo?.valueForKey(EndNumber) as! NSNumber let resultText = String.init(format: "%.6d", resultNumber.longLongValue) assert(resultText.characters.count == 6, "LabelNumber转换位数出错:\(numberText)") let resultTextString = NSMutableString.init(string: resultText) resultTextString.insertString("h ", atIndex: 2) resultTextString.insertString("m ", atIndex: 6) resultTextString.insertString("s ", atIndex: 10) self.text = resultTextString as String let attributes = timer.userInfo?.valueForKey(Attributes) if attributes != nil { self.drawAttributes(attributes!) } // 停止计时器 self.labelTimer?.invalidate() } } public func drawAttributes(attributes: AnyObject) -> Void { if attributes.isKindOfClass(NSDictionary) { let range = attributes.valueForKey("rangeValue")?.rangeValue let attribute = attributes.valueForKey("attributeValue") self.addAttributes(attribute!, range : range!) } else if attributes.isKindOfClass(NSArray) { for attribute in attributes as! NSArray { let range = attribute.valueForKey("rangeValue")?.rangeValue let attri = attribute.valueForKey("attributeValue") self.addAttributes(attri!, range : range!) } } } private func addAttributes(attributes: AnyObject, range: NSRange) -> Void { let attributedStr = NSMutableAttributedString(attributedString : self.attributedText!) if range.location + range.length < attributedStr.length { attributedStr.addAttributes(attributes as! [String : AnyObject], range: range) } self.attributedText = attributedStr; } }
6dee2e57e485c71960b1fd0c6bcfd9cf
38.012658
179
0.634269
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ModifyAxisBehaviour/SecondaryYAxesChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // SecondaryYAxesChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class SecondaryYAxesChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) xAxis.axisTitle = "Bottom Axis" let rightYAxis = SCINumericAxis() rightYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) rightYAxis.axisId = "rightAxisId" rightYAxis.axisTitle = "Right Axis" rightYAxis.axisAlignment = .right rightYAxis.style.labelStyle.colorCode = 0xFF279B27 let leftYAxis = SCINumericAxis() leftYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) leftYAxis.axisId = "leftAxisId" leftYAxis.axisTitle = "Left Axis" leftYAxis.axisAlignment = .left leftYAxis.style.labelStyle.colorCode = 0xFF4083B7 let ds1 = SCIXyDataSeries(xType: .double, yType: .double) let ds2 = SCIXyDataSeries(xType: .double, yType: .double) let ds1Points = DataManager.getFourierSeries(withAmplitude: 1.0, phaseShift: 0.1, count: 5000) let ds2Points = DataManager.getDampedSinewave(withAmplitude: 3.0, dampingFactor: 0.005, pointCount: 5000, freq: 10) ds1.appendRangeX(ds1Points!.xValues, y: ds1Points!.yValues, count: ds1Points!.size) ds2.appendRangeX(ds2Points!.xValues, y: ds2Points!.yValues, count: ds2Points!.size) let rs1 = SCIFastLineRenderableSeries() rs1.dataSeries = ds1 rs1.strokeStyle = SCISolidPenStyle(colorCode: 0xFF4083B7, withThickness: 2.0) rs1.yAxisId = "leftAxisId" let rs2 = SCIFastLineRenderableSeries() rs2.dataSeries = ds2 rs2.strokeStyle = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 2.0) rs2.yAxisId = "rightAxisId" SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(leftYAxis) self.surface.yAxes.add(rightYAxis) self.surface.renderableSeries.add(rs1) self.surface.renderableSeries.add(rs2) rs1.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) rs2.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } }
4d12867493f061c741e8810145732f3f
45.882353
123
0.642095
false
false
false
false
codeliling/HXDYWH
refs/heads/master
dywh/dywh/controllers/ArticleMapViewController.swift
apache-2.0
1
// // MapViewController.swift // dywh // // Created by lotusprize on 15/5/22. // Copyright (c) 2015年 geekTeam. All rights reserved. // import UIKit import Haneke class ArticleMapViewController: UIViewController,BMKMapViewDelegate { let cache = Shared.imageCache var mapView:BMKMapView! var articleList:[ArticleModel] = [] var mAPView:MapArticlePanelView! var articleModel:ArticleModel? override func viewDidLoad() { super.viewDidLoad() mapView = BMKMapView() mapView.frame = self.view.frame mapView.mapType = UInt(BMKMapTypeStandard) mapView.zoomLevel = 5 mapView.showMapScaleBar = true mapView.mapScaleBarPosition = CGPointMake(10, 10) mapView.showsUserLocation = true mapView.compassPosition = CGPointMake(self.view.frame.width - 50, 10) mapView.setCenterCoordinate(CLLocationCoordinate2DMake(26.2038,109.8151), animated: true) mapView.delegate = self self.view.addSubview(mapView) mAPView = MapArticlePanelView(frame: CGRectMake(10, UIScreen.mainScreen().bounds.size.height - 300, UIScreen.mainScreen().bounds.size.width - 20, 130), title: "", articleDescription: "") mAPView.backgroundColor = UIColor.whiteColor() mAPView.alpha = 0.8 mAPView.hidden = true mAPView.userInteractionEnabled = true var tapView:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "panelClick:") self.mAPView.addGestureRecognizer(tapView) self.view.addSubview(mAPView) } func mapView(mapView: BMKMapView!, didSelectAnnotationView view: BMKAnnotationView!) { var title:String = view.annotation.title!() for aModle in articleList{ if title == aModle.articleName{ articleModel = aModle } } if (articleModel != nil){ mAPView.hidden = false self.loadImageByUrl(mAPView, url: articleModel!.articleImageUrl!) mAPView.title = articleModel!.articleName mAPView.articleDescription = articleModel!.articleDescription mAPView.setNeedsDisplay() } } func addMapPoint(articleModel:ArticleModel){ var annotation:BMKPointAnnotation = BMKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(Double(articleModel.latitude), Double(articleModel.longitude)); annotation.title = articleModel.articleName mapView.addAnnotation(annotation) articleList.append(articleModel) } func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! { if annotation.isKindOfClass(BMKPointAnnotation.classForCoder()) { var newAnnotationView:BMKPinAnnotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: "articleAnnotation"); newAnnotationView.pinColor = UInt(BMKPinAnnotationColorPurple) newAnnotationView.animatesDrop = true;// 设置该标注点动画显示 newAnnotationView.annotation = annotation; newAnnotationView.image = UIImage(named: "locationIcon") newAnnotationView.frame = CGRectMake(newAnnotationView.frame.origin.x, newAnnotationView.frame.origin.y, 30, 30) newAnnotationView.paopaoView = nil return newAnnotationView } return nil } func mapView(mapView: BMKMapView!, annotationViewForBubble view: BMKAnnotationView!) { } func panelClick(gesture:UIGestureRecognizer){ if articleModel != nil{ var detailViewController:ArticleDetailViewController? = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ArticleDetail") as? ArticleDetailViewController detailViewController?.articleModel = articleModel self.navigationController?.pushViewController(detailViewController!, animated: true) } } func loadImageByUrl(view:MapArticlePanelView, url:String){ let URL = NSURL(string: url)! let fetcher = NetworkFetcher<UIImage>(URL: URL) cache.fetch(fetcher: fetcher).onSuccess { image in // Do something with image view.imageLayer.contents = image.CGImage } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) mapView.delegate = self } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) mapView.delegate = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
9345a107cdf2a38db0ef5e1716cfaacd
37.795082
196
0.672723
false
false
false
false
Wolox/wolmo-core-ios
refs/heads/master
WolmoCore/Extensions/UIKit/UIViewController.swift
mit
1
// // UIViewController.swift // WolmoCore // // Created by Guido Marucci Blas on 5/7/16. // Copyright © 2016 Wolox. All rights reserved. // import UIKit public extension UIViewController { /** Loads the childViewController into the specified containerView. It can be done after self's view is initialized, as it uses constraints to determine the childViewController size. Take into account that self will retain the childViewController, so if for any other reason the childViewController is retained in another place, this would lead to a memory leak. In that case, one should call unloadViewController(). - parameter childViewController: The controller to load. - parameter into: The containerView into which the controller will be loaded. - parameter viewPositioning: Back or Front. Default: Front */ func load(childViewController: UIViewController, into containerView: UIView, with insets: UIEdgeInsets = .zero, in viewPositioning: ViewPositioning = .front, layout: LayoutMode = .constraints, respectSafeArea: Bool = false) { childViewController.willMove(toParent: self) addChild(childViewController) childViewController.didMove(toParent: self) childViewController.view.add(into: containerView, with: insets, in: viewPositioning, layout: layout, respectSafeArea: respectSafeArea) } /** Unloads a childViewController and its view from its parentViewController. */ func unloadFromParentViewController() { view.removeFromSuperview() removeFromParent() } /** Unloads all childViewController and their view from self. */ func unloadChildViewControllers() { for childController in self.children { childController.unloadFromParentViewController() } } } // MARK: - Navigation Bar public extension UIViewController { /** Configures the navigation bar to have a particular image as back button. - parameter image: The image of the back button. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarBackButton(_ image: UIImage) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.topItem?.title = "" navigationController.navigationBar.backIndicatorImage = image navigationController.navigationBar.backIndicatorTransitionMaskImage = image } /** Configures the navigation bar color. - parameter color: The new color of the navigation bar. This represents the navigation bar background color. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barTintColor = color } /** Configures the navigation bar tint color. - parameter color: The new tint color of the navigation bar. This represents the color of the left and right button items. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarTintColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.tintColor = color } /** Configures the navigation bar style. - parameter style: The new style of the navigation bar. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarStyle(_ style: UIBarStyle) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barStyle = style } /** Sets a collection of buttons as the navigation bar left buttons. - parameter buttons: the Array of buttons to use. */ func setNavigationLeftButtons(_ buttons: [UIBarButtonItem]) { navigationItem.leftBarButtonItems = buttons } /** Sets a collection of buttons as the navigation bar right buttons. - parameter buttons: the Array of buttons to use. */ func setNavigationRightButtons(_ buttons: [UIBarButtonItem]) { navigationItem.rightBarButtonItems = buttons } /** Adds and configures a label to use as title of the navigation bar. - parameter title: the string of the label. - parameter font: the font to use for the label. - parameter color: the color of the text. */ func setNavigationBarTitle(_ title: String, font: UIFont, color: UIColor) { let label = UILabel(frame: .zero) label.backgroundColor = .clear label.font = font label.textColor = color label.adjustsFontSizeToFitWidth = true label.text = title label.sizeToFit() navigationItem.titleView = label } /** Adds an ImageView with the image passed as the titleView of the navigation bar. - parameter image: The image to set as title. */ func setNavigationBarTitleImage(_ image: UIImage) { navigationItem.titleView = UIImageView(image: image) } }
6f80f8dee8526c7d1cb39e89309d64f0
38.342105
161
0.664047
false
false
false
false
halo/LinkLiar
refs/heads/master
LinkHelper/Classes/BootDaemon.swift
mit
1
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 BootDaemon { enum SubCommand: String { case bootstrap = "bootstrap" case bootout = "bootout" } static func bootstrap() -> Bool { if bootout() { Log.debug("Deactivated daemon so I can now go ahead and safely (re-)activate it...") } else { Log.debug("Just-In-Case-Deactivation failed, but that's fine, let me activate it") } return launchctl(.bootstrap) } static func bootout() -> Bool { return launchctl(.bootout) } // MARK Private Instance Methods private static func launchctl(_ subcommand: SubCommand) -> Bool { Log.debug("Preparing \(subcommand.rawValue) of daemon...") let task = Process() // Set the task parameters task.launchPath = "/usr/bin/sudo" task.arguments = ["/bin/launchctl", subcommand.rawValue, "system", Paths.daemonPlistFile] let outputPipe = Pipe() let errorPipe = Pipe() task.standardOutput = outputPipe task.standardError = errorPipe // Launch the task task.launch() task.waitUntilExit() let status = task.terminationStatus if status == 0 { Log.debug("Task succeeded.") return(true) } else { Log.debug("Task failed \(task.terminationStatus)") let outdata = outputPipe.fileHandleForReading.availableData guard let stdout = String(data: outdata, encoding: .utf8) else { Log.debug("Could not read stdout") return false } let errdata = errorPipe.fileHandleForReading.availableData guard let stderr = String(data: errdata, encoding: .utf8) else { Log.debug("Could not read stderr") return false } Log.debug("Reason: \(stdout) \(stderr)") return(false) } } }
040f660e0cd995fcef2a15242877106b
32.835294
133
0.692629
false
false
false
false
mateuszstompor/MSEngine
refs/heads/master
ExampleProject/MSEngineTestApp/Controllers/ModelsTableViewController.swift
mit
1
// // MenuViewController.swift // MSEngineTestApp // // Created by Mateusz Stompór on 14/10/2017. // Copyright © 2017 Mateusz Stompór. All rights reserved. // import UIKit class ModelsTableViewController: UITableViewController { var lightSources: [MSPositionedLight?]? = MSEngine.getInstance()?.getPointLights() override func viewDidLoad() { super.viewDidLoad() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "PointLightTableViewCell") as? PointLightTableViewCell { if let positionedLight = lightSources?[indexPath.row] { let light = positionedLight.getLight()! let modelPosition = positionedLight.getTransformation() cell.isOn = light.isOn() cell.position = CIVector(x: CGFloat(modelPosition?.position().value(at: 0) ?? 0.0), y: CGFloat(modelPosition?.position().value(at: 1) ?? 0.0), z: CGFloat(modelPosition?.position().value(at: 1) ?? 0.0)) cell.lightPower = light.getPower() cell.lightWasSwitchedBlock = { [weak self] (cell: PointLightTableViewCell, isOn: Bool) in if let indexPath = self?.tableView.indexPath(for: cell) { self?.lightSources?[indexPath.row]?.getLight()?.lights(isOn) } } } return cell } else { return UITableViewCell() } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let pointLightsArray = self.lightSources { return pointLightsArray.count } else { return 0 } } }
f33ba4a3ddc5109bd7092fb94b3c45a0
36.633333
217
0.611603
false
false
false
false
nicksweet/Clink
refs/heads/master
Clink/Classes/Peer.swift
mit
1
// // ClinkPeer.swift // clink // // Created by Nick Sweet on 6/16/17. // import Foundation import CoreBluetooth public protocol ClinkPeerManager { func createPeer(withId peerId: String) func update(value: Any, forKey key: String, ofPeerWithId peerId: String) func getPeer<T: ClinkPeer>(withId peerId: String) -> T? func getKnownPeerIds() -> [Clink.PeerId] func delete(peerWithId peerId: String) } public protocol ClinkPeer { var id: String { get set } init(id: String) subscript(propertyName: Clink.PeerPropertyKey) -> Any? { get set } } extension Clink { public class DefaultPeer: ClinkPeer { public var id: String private var dict = [String: Any]() required public init(id: String) { self.id = id } public init?(dict: [String: Any]) { guard let id = dict["id"] as? String, let dict = dict["dict"] as? [String: Any] else { return nil } self.id = id self.dict = dict } public subscript(propertyName: Clink.PeerPropertyKey) -> Any? { get { return dict[propertyName] } set { dict[propertyName] = newValue } } public func toDict() -> [String: Any] { return [ "id": self.id, "dict": self.dict ] } } }
5fd535d70e248c092e00e5df0e194b41
22.375
76
0.52139
false
false
false
false
ali-zahedi/AZViewer
refs/heads/master
AZViewer/AZConstraint.swift
apache-2.0
1
// // AZConstraint.swift // AZViewer // // Created by Ali Zahedi on 1/14/1396 AP. // Copyright © 1396 AP Ali Zahedi. All rights reserved. // import Foundation public class AZConstraint: NSObject { // MARK: Public public var parent: Any? public var top: NSLayoutConstraint? public var bottom: NSLayoutConstraint? public var left: NSLayoutConstraint? public var right: NSLayoutConstraint? public var centerX: NSLayoutConstraint? public var centerY: NSLayoutConstraint? public var width: NSLayoutConstraint? public var height: NSLayoutConstraint? // MARK: Internal // MARK: Private fileprivate var view: Any! // MARK: Override public init(view: Any) { super.init() self.view = view self.defaultInit() } // MARK: Function fileprivate func defaultInit(){ } } extension AZConstraint{ public func parent(parent: UIView) -> AZConstraint{ self.parent = parent return self } } // constraint extension AZConstraint{ // top public func top(to: Any? = nil, toAttribute: NSLayoutAttribute = .top, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.top = constraint self.top?.isActive = active return self } // bottom public func bottom(to: Any? = nil, toAttribute: NSLayoutAttribute = .bottom, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.bottom = constraint self.bottom?.isActive = active return self } // right public func right(to: Any? = nil, toAttribute: NSLayoutAttribute = .right, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .right, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.right = constraint self.right?.isActive = active return self } // left public func left(to: Any? = nil, toAttribute: NSLayoutAttribute = .left, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .left, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.left = constraint self.left?.isActive = active return self } // centerY public func centerY(to: Any? = nil, toAttribute: NSLayoutAttribute = .centerY, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.centerY = constraint self.centerY?.isActive = active return self } // centerX public func centerX(to: Any? = nil, toAttribute: NSLayoutAttribute = .centerX, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.centerX = constraint self.centerX?.isActive = active return self } // width public func width(to: Any? = nil, toAttribute: NSLayoutAttribute = .width, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to //?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .width, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.width = constraint self.width?.isActive = active return self } // height public func height(to: Any? = nil, toAttribute: NSLayoutAttribute = .height, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to //?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .height, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.height = constraint self.height?.isActive = active return self } }
14bed54b14e02b5766b7b88c55fd31ce
31.856287
184
0.615272
false
false
false
false
piemapping/pie-overlay-menu-ios
refs/heads/master
Source/PieOverlayMenu.swift
mit
1
// // PieOverlayMenu2.swift // PieOverlayMenu // // Created by Anas Ait Ali on 28/12/2016. // Copyright © 2016 Pie mapping. All rights reserved. // import UIKit public protocol PieOverlayMenuProtocol { func setContentViewController(_ viewController: UIViewController, animated: Bool) func showMenu(_ animated: Bool) func closeMenu(_ animated: Bool, _ completion: ((Bool) -> ())?) func getMenuViewController() -> PieOverlayMenuContentViewController? func getContentViewController() -> UIViewController? } open class PieOverlayMenu: UIViewController, PieOverlayMenuProtocol { open fileprivate(set) var contentViewController: UIViewController? open fileprivate(set) var menuViewController: PieOverlayMenuContentViewController? fileprivate var visibleViewController: UIViewController? // MARK: - Init methods - public init() { super.init(nibName: nil, bundle: nil) print("this is not handled yet") } public init(contentViewController: UIViewController, menuViewController: UIViewController) { super.init(nibName: nil, bundle: nil) self.contentViewController = contentViewController self.menuViewController = PieOverlayMenuContentViewController(rootViewController: menuViewController) self.changeVisibleViewController(contentViewController) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func changeVisibleViewController(_ viewController: UIViewController) { visibleViewController?.willMove(toParentViewController: nil) self.addChildViewController(viewController) viewController.view.frame = self.view.bounds self.view.addSubview(viewController.view) visibleViewController?.view.removeFromSuperview() visibleViewController?.removeFromParentViewController() viewController.didMove(toParentViewController: self) visibleViewController = viewController setNeedsStatusBarAppearanceUpdate() } open func setContentViewController(_ viewController: UIViewController, animated: Bool) { //TODO: Implement animated self.contentViewController?.viewWillDisappear(animated) viewController.viewWillAppear(animated) self.changeVisibleViewController(viewController) self.contentViewController?.viewDidDisappear(animated) viewController.viewDidAppear(animated) self.contentViewController = viewController } open func showMenu(_ animated: Bool) { //TODO: Implement animated self.menuViewController?.viewWillAppear(animated) self.changeVisibleViewController(self.menuViewController!) self.menuViewController?.viewDidAppear(animated) } open func closeMenu(_ animated: Bool, _ completion: ((Bool) -> ())? = nil) { //TODO: Implement animated self.menuViewController?.viewWillDisappear(animated) self.changeVisibleViewController(self.contentViewController!) self.menuViewController?.viewDidDisappear(animated) self.menuViewController?.popToRootViewControllerAnimated(true, completion) } open func getMenuViewController() -> PieOverlayMenuContentViewController? { return self.menuViewController } open func getContentViewController() -> UIViewController? { return self.contentViewController } open override var preferredStatusBarStyle: UIStatusBarStyle { return self.visibleViewController?.preferredStatusBarStyle ?? .default } } extension UIViewController { public func pieOverlayMenuContent() -> PieOverlayMenuContentViewController? { return self.pieOverlayMenu()?.getMenuViewController() } public func pieOverlayContentViewController() -> UIViewController? { return self.pieOverlayMenu()?.getContentViewController() } public func pieOverlayMenu() -> PieOverlayMenuProtocol? { var iteration : UIViewController? = self.parent if (iteration == nil) { return topMostController() } repeat { if (iteration is PieOverlayMenuProtocol) { return iteration as? PieOverlayMenuProtocol } else if (iteration?.parent != nil && iteration?.parent != iteration) { iteration = iteration!.parent } else { iteration = nil } } while (iteration != nil) return iteration as? PieOverlayMenuProtocol } internal func topMostController () -> PieOverlayMenuProtocol? { var topController : UIViewController? = UIApplication.shared.keyWindow?.rootViewController if (topController is UITabBarController) { topController = (topController as! UITabBarController).selectedViewController } var lastMenuProtocol : PieOverlayMenuProtocol? while (topController?.presentedViewController != nil) { if(topController?.presentedViewController is PieOverlayMenuProtocol) { lastMenuProtocol = topController?.presentedViewController as? PieOverlayMenuProtocol } topController = topController?.presentedViewController } if (lastMenuProtocol != nil) { return lastMenuProtocol } else { return topController as? PieOverlayMenuProtocol } } }
65407815400e6909be90c2ccbee0acee
38.078014
109
0.693648
false
false
false
false
TZLike/GiftShow
refs/heads/master
GiftShow/GiftShow/Classes/ProductDetail/Model/LeeListDetailModel.swift
apache-2.0
1
// // LeeListDetailModel.swift // GiftShow // // Created by admin on 16/11/3. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit class LeeListDetailModel:LeeBaseModel { //描述 var des:String? //网页地址 var detail_html:String? var favorites_count:NSNumber = 0 var image_urls:[String]? var likes_count:NSNumber = 0 var name:String? var price:CGFloat = 0 var purchase_url:String? var short_description:String? init(dict:[String:NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if "description" == key { self.des = value as! String? } super.setValue(value, forKey: key) } }
acf2b05282692574b81244d9f755bbd2
19.6
63
0.570388
false
false
false
false
hooman/swift
refs/heads/main
test/Sema/placeholder_type.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift let x: _ = 0 // expected-error {{placeholders are not allowed as top-level types}} let x2 = x let dict1: [_: Int] = ["hi": 0] let dict2: [Character: _] = ["h": 0] let arr = [_](repeating: "hi", count: 3) func foo(_ arr: [_] = [0]) {} // expected-error {{type placeholder not allowed here}} let foo = _.foo // expected-error {{placeholders are not allowed as top-level types}} let zero: _ = .zero // expected-error {{placeholders are not allowed as top-level types}} struct S<T> { var x: T } var s1: S<_> = .init(x: 0) var s2 = S<_>(x: 0) let losslessStringConverter = Double.init as (String) -> _? let optInt: _? = 0 let implicitOptInt: _! = 0 let func1: (_) -> Double = { (x: Int) in 0.0 } let func2: (Int) -> _ = { x in 0.0 } let func3: (_) -> _ = { (x: Int) in 0.0 } let func4: (_, String) -> _ = { (x: Int, y: String) in 0.0 } let func5: (_, String) -> _ = { (x: Int, y: Double) in 0.0 } // expected-error {{cannot convert value of type '(Int, Double) -> Double' to specified type '(_, String) -> _'}} let type: _.Type = Int.self let type2: Int.Type.Type = _.Type.self struct MyType1<T, U> { init(t: T, mt2: MyType2<T>) where U == MyType2<T> {} } struct MyType2<T> { init(t: T) {} } let _: MyType2<_> = .init(t: "c" as Character) let _: MyType1<_, MyType2<_>> = .init(t: "s" as Character, mt2: .init(t: "c" as Character)) func dictionary<K, V>(ofType: [K: V].Type) -> [K: V] { [:] } let _: [String: _] = dictionary(ofType: [_: Int].self) let _: [_: _] = dictionary(ofType: [String: Int].self) let _: [String: Int] = dictionary(ofType: _.self) // expected-error {{placeholders are not allowed as top-level types}} let _: @convention(c) _ = { 0 } // expected-error {{@convention attribute only applies to function types}} // expected-error@-1 {{placeholders are not allowed as top-level types}} let _: @convention(c) (_) -> _ = { (x: Double) in 0 } let _: @convention(c) (_) -> Int = { (x: Double) in 0 } struct NonObjc {} let _: @convention(c) (_) -> Int = { (x: NonObjc) in 0 } // expected-error {{'(NonObjc) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} func overload() -> Int? { 0 } func overload() -> String { "" } let _: _? = overload() let _ = overload() as _? struct Bar<T, U> where T: ExpressibleByIntegerLiteral, U: ExpressibleByIntegerLiteral { var t: T var u: U func frobnicate() -> Bar { return Bar(t: 42, u: 42) } } extension Bar { func frobnicate2() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar(t: 42, u: 42) } func frobnicate3() -> Bar { return Bar<_, _>(t: 42, u: 42) } func frobnicate4() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar<_, _>(t: 42, u: 42) } func frobnicate5() -> Bar<_, U> { // expected-error {{type placeholder not allowed here}} return Bar(t: 42, u: 42) } func frobnicate6() -> Bar { return Bar<_, U>(t: 42, u: 42) } func frobnicate7() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar<_, U>(t: 42, u: 42) } func frobnicate8() -> Bar<_, U> { // expected-error {{type placeholder not allowed here}} return Bar<_, _>(t: 42, u: 42) } } // FIXME: We should probably have better diagnostics for these situations--the user probably meant to use implicit member syntax let _: Int = _() // expected-error {{placeholders are not allowed as top-level types}} let _: () -> Int = { _() } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} let _: Int = _.init() // expected-error {{placeholders are not allowed as top-level types}} let _: () -> Int = { _.init() } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} func returnsInt() -> Int { _() } // expected-error {{placeholders are not allowed as top-level types}} func returnsIntClosure() -> () -> Int { { _() } } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} func returnsInt2() -> Int { _.init() } // expected-error {{placeholders are not allowed as top-level types}} func returnsIntClosure2() -> () -> Int { { _.init() } } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} let _: Int.Type = _ // expected-error {{'_' can only appear in a pattern or on the left side of an assignment}} let _: Int.Type = _.self // expected-error {{placeholders are not allowed as top-level types}} struct SomeSuperLongAndComplexType {} func getSomething() -> SomeSuperLongAndComplexType? { .init() } let something: _! = getSomething() extension Array where Element == Int { static var staticMember: Self { [] } static func staticFunc() -> Self { [] } var member: Self { [] } func method() -> Self { [] } } extension Array { static var otherStaticMember: Self { [] } } let _ = [_].staticMember let _ = [_].staticFunc() let _ = [_].otherStaticMember.member let _ = [_].otherStaticMember.method() func f(x: Any, arr: [Int]) { // FIXME: Better diagnostics here. Maybe we should suggest replacing placeholders with 'Any'? if x is _ {} // expected-error {{placeholders are not allowed as top-level types}} if x is [_] {} // expected-error {{type of expression is ambiguous without more context}} if x is () -> _ {} // expected-error {{type of expression is ambiguous without more context}} if let y = x as? _ {} // expected-error {{placeholders are not allowed as top-level types}} if let y = x as? [_] {} // expected-error {{type of expression is ambiguous without more context}} if let y = x as? () -> _ {} // expected-error {{type of expression is ambiguous without more context}} let y1 = x as! _ // expected-error {{placeholders are not allowed as top-level types}} let y2 = x as! [_] // expected-error {{type of expression is ambiguous without more context}} let y3 = x as! () -> _ // expected-error {{type of expression is ambiguous without more context}} switch x { case is _: break // expected-error {{type placeholder not allowed here}} case is [_]: break // expected-error {{type placeholder not allowed here}} case is () -> _: break // expected-error {{type placeholder not allowed here}} case let y as _: break // expected-error {{type placeholder not allowed here}} case let y as [_]: break // expected-error {{type placeholder not allowed here}} case let y as () -> _: break // expected-error {{type placeholder not allowed here}} } if arr is _ {} // expected-error {{placeholders are not allowed as top-level types}} if arr is [_] {} // expected-error {{type of expression is ambiguous without more context}} if arr is () -> _ {} // expected-error {{type of expression is ambiguous without more context}} if let y = arr as? _ {} // expected-error {{placeholders are not allowed as top-level types}} if let y = arr as? [_] {} // expected-error {{type of expression is ambiguous without more context}} if let y = arr as? () -> _ {} // expected-error {{type of expression is ambiguous without more context}} let y1 = arr as! _ // expected-error {{placeholders are not allowed as top-level types}} let y2 = arr as! [_] // expected-error {{type of expression is ambiguous without more context}} let y3 = arr as! () -> _ // expected-error {{type of expression is ambiguous without more context}} switch arr { case is _: break // expected-error {{type placeholder not allowed here}} case is [_]: break // expected-error {{type placeholder not allowed here}} case is () -> _: break // expected-error {{type placeholder not allowed here}} case let y as _: break // expected-error {{type placeholder not allowed here}} case let y as [_]: break // expected-error {{type placeholder not allowed here}} case let y as () -> _: break // expected-error {{type placeholder not allowed here}} } } protocol Publisher { associatedtype Output associatedtype Failure } struct Just<Output>: Publisher { typealias Failure = Never } struct SetFailureType<Output, Failure>: Publisher {} extension Publisher { func setFailureType<T>(to: T.Type) -> SetFailureType<Output, T> { return .init() } } let _: SetFailureType<Int, String> = Just<Int>().setFailureType(to: _.self) // expected-error {{placeholders are not allowed as top-level types}} let _: SetFailureType<Int, [String]> = Just<Int>().setFailureType(to: [_].self) let _: SetFailureType<Int, (String) -> Double> = Just<Int>().setFailureType(to: ((_) -> _).self) let _: SetFailureType<Int, (String, Double)> = Just<Int>().setFailureType(to: (_, _).self) // TODO: Better error message here? Would be nice if we could point to the placeholder... let _: SetFailureType<Int, String> = Just<Int>().setFailureType(to: _.self).setFailureType(to: String.self) // expected-error {{placeholders are not allowed as top-level types}} let _: (_) = 0 as Int // expected-error {{placeholders are not allowed as top-level types}} let _: Int = 0 as (_) // expected-error {{placeholders are not allowed as top-level types}} _ = (1...10) .map { ( $0, ( "\($0)", $0 > 5 ) ) } .map { (intValue, x: (_, boolValue: _)) in x.boolValue ? intValue : 0 }
f733a8d164dc0109d0bf891faca7c0e5
43.357798
196
0.628232
false
false
false
false
alitan2014/swift
refs/heads/master
Heath/Heath/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // Heath // // Created by Mac on 15/7/13. // Copyright (c) 2015年 Mac. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. var navigationBarappearace = UINavigationBar.appearance() navigationBarappearace.translucent = false navigationBarappearace.barTintColor = UIColor.grayColor() //navigation Bar title 字体为白色 UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Heiti SC", size: 17)!] let tabBarController = HeathTabBarcontroller() tabBarController.tabBar.translucent = false tabBarController.tabBar.tintColor=UIColor(red: 251/25.0, green: 78/255.0, blue: 10/255.0, alpha: 1) self.window?.rootViewController=tabBarController return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
ac9e8b0d16675cf493fc02abfb8d3b6a
49.035714
285
0.745539
false
false
false
false
K-cat/CatMediaPickerController
refs/heads/master
Sources/Controllers/CatPhotosPickerController.swift
mit
1
// // CatImagePickerController.swift // CatMediaPicker // // Created by Kcat on 2018/3/10. // Copyright © 2018年 ImKcat. All rights reserved. // // https://github.com/ImKcat/CatMediaPicker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import Photos // MARK: - CatPhotosPickerController Requirements public class CatPhotosPickerControllerConfigure { public var mediaType: PHAssetMediaType = .image { didSet { switch mediaType { case .unknown: mediaType = .image default: break } } } public var maximumSelectCount: Int = 1 { didSet { if maximumSelectCount < 1 { maximumSelectCount = 1 } } } public init() {} } public protocol CatPhotosPickerControllerDelegate: NSObjectProtocol { func didFinishPicking(pickerController: CatPhotosPickerController, media: [CatMedia]) func didCancelPicking(pickerController: CatPhotosPickerController) } // MARK: - CatPhotosPickerController public class CatPhotosPickerController: UINavigationController, UINavigationControllerDelegate, CatPhotosListControllerDelegate { public weak var pickerControllerDelegate: CatPhotosPickerControllerDelegate? // MARK: - Initialize public init(configure: CatPhotosPickerControllerConfigure? = CatPhotosPickerControllerConfigure()) { let listController = CatPhotosListController() listController.pickerControllerConfigure = configure! super.init(rootViewController: listController) listController.listControllerDelegate = self self.delegate = self } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - CatPhotosListControllerDelegate func didTapDoneBarButtonItem(photosListController: CatPhotosListController, pickedAssets: [PHAsset]) { if self.pickerControllerDelegate != nil { guard pickedAssets.count != 0 else { self.pickerControllerDelegate?.didFinishPicking(pickerController: self, media: []) return } let media = pickedAssets.map{ return CatMedia(type: $0.mediaType, source: $0) } self.pickerControllerDelegate?.didFinishPicking(pickerController: self, media: media) } } func didTapCancelBarButtonItem(photosListController: CatPhotosListController) { if self.pickerControllerDelegate != nil { self.pickerControllerDelegate?.didCancelPicking(pickerController: self) } } } // MARK: - CatPhotosListController Requirements protocol CatPhotosListControllerDelegate: NSObjectProtocol { func didTapCancelBarButtonItem(photosListController: CatPhotosListController) func didTapDoneBarButtonItem(photosListController: CatPhotosListController, pickedAssets: [PHAsset]) } // MARK: - CatPhotosListController class CatPhotosListController: UICollectionViewController, UICollectionViewDelegateFlowLayout { weak var listControllerDelegate: CatPhotosListControllerDelegate? var pickerControllerConfigure: CatPhotosPickerControllerConfigure = CatPhotosPickerControllerConfigure() var doneBarButtonItem: UIBarButtonItem? var cancelBarButtonItem: UIBarButtonItem? var photosAssets: [PHAsset] = [] var selectedAssetIndexPaths: [IndexPath] = [] // MARK: - Initialize init() { let photosListCollectionViewLayout = UICollectionViewFlowLayout() photosListCollectionViewLayout.minimumInteritemSpacing = 0 photosListCollectionViewLayout.minimumLineSpacing = 0 photosListCollectionViewLayout.itemSize = CGSize(width: UIScreen.main.bounds.width / 4, height: UIScreen.main.bounds.width / 4) super.init(collectionViewLayout: photosListCollectionViewLayout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Stack override func viewDidLoad() { super.viewDidLoad() self.layoutInit() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.refreshData() } func layoutInit() { self.title = String.localizedString(defaultString: "Photos", key: "CatMediaPicker.PhotosPickerControllerTitle", comment: "") self.view.backgroundColor = UIColor.white self.collectionView?.allowsMultipleSelection = true self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.alwaysBounceVertical = true self.cancelBarButtonItem = UIBarButtonItem(title: String.localizedString(defaultString: "Cancel", key: "CatMediaPicker.Cancel", comment: ""), style: .plain, target: self, action: #selector(cancelAction)) self.navigationItem.leftBarButtonItem = self.cancelBarButtonItem self.doneBarButtonItem = UIBarButtonItem(title: String.localizedString(defaultString: "Done", key: "CatMediaPicker.Done", comment: ""), style: .done, target: self, action: #selector(doneAction)) self.navigationItem.rightBarButtonItem = self.doneBarButtonItem self.collectionView?.register(CatPhotosListCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: CatPhotosListCollectionViewCell.self)) } func refreshData() { self.photosAssets.removeAll() let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let fetchResult = PHAsset.fetchAssets(with: self.pickerControllerConfigure.mediaType, options: fetchOptions) fetchResult.enumerateObjects { (asset, _, _) in self.photosAssets.append(asset) } self.collectionView?.reloadData() } // MARK: - Action @objc func cancelAction() { if self.listControllerDelegate != nil { self.listControllerDelegate?.didTapCancelBarButtonItem(photosListController: self) } } @objc func doneAction() { if self.listControllerDelegate != nil { let selectedIndexPaths = selectedAssetIndexPaths let selectedRows = selectedIndexPaths.map{ return $0.row } let selectedAssets = selectedRows.map{ return self.photosAssets[$0] } self.listControllerDelegate?.didTapDoneBarButtonItem(photosListController: self, pickedAssets: selectedAssets) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let flowLayout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = CGSize(width: size.width / 4, height: size.width / 4) self.collectionView?.collectionViewLayout = flowLayout } // MARK: - UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CatPhotosListCollectionViewCell.self), for: indexPath) as! CatPhotosListCollectionViewCell let photoAsset = photosAssets[indexPath.row] let imageRequestOptions = PHImageRequestOptions() imageRequestOptions.resizeMode = .exact imageRequestOptions.normalizedCropRect = CGRect(x: 0, y: 0, width: 200, height: 200) PHImageManager.default().requestImage(for: photoAsset, targetSize: CGSize(width: 200, height: 200), contentMode: PHImageContentMode.aspectFill, options: imageRequestOptions) { (photoImage, photoImageInfo) in guard photoImage != nil else { return } cell.photoImageView.image = photoImage } cell.isSelected = selectedAssetIndexPaths.contains(indexPath) ? true : false return cell } override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard selectedAssetIndexPaths.count < pickerControllerConfigure.maximumSelectCount else { return false } return true } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedAssetIndexPaths.append(indexPath) } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { for i in 0...(selectedAssetIndexPaths.count - 1) { if selectedAssetIndexPaths[i] == indexPath { selectedAssetIndexPaths.remove(at: i) return } } } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photosAssets.count } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } } class CatPhotosListCollectionViewCell: UICollectionViewCell { var photoImageView: UIImageView var highlightView: UIView var checkmarkView: UIView = { let checkmarkView = UIView() let circleLayer = CAShapeLayer() let circlePath = UIBezierPath() circlePath.move(to: CGPoint(x: 10, y: 0)) circlePath.addCurve(to: CGPoint(x: 0, y: 10), controlPoint1: CGPoint(x: 4.48, y: 0), controlPoint2: CGPoint(x: 0, y: 4.48)) circlePath.addCurve(to: CGPoint(x: 10, y: 20), controlPoint1: CGPoint(x: 0, y: 15.52), controlPoint2: CGPoint(x: 4.48, y: 20)) circlePath.addCurve(to: CGPoint(x: 20, y: 10), controlPoint1: CGPoint(x: 15.52, y: 20), controlPoint2: CGPoint(x: 20, y: 15.52)) circlePath.addCurve(to: CGPoint(x: 10, y: 0), controlPoint1: CGPoint(x: 20, y: 4.48), controlPoint2: CGPoint(x: 15.52, y: 0)) circlePath.close() circlePath.fill() circleLayer.path = circlePath.cgPath circleLayer.fillColor = UIColor(red: 0.0000000000, green: 0.4784313738, blue: 1.0000000000, alpha: 1.0000000000).cgColor let checkmarkLayer = CAShapeLayer() let checkmarkPath = UIBezierPath() checkmarkPath.move(to: CGPoint(x: 8.46, y: 13.54)) checkmarkPath.addCurve(to: CGPoint(x: 8.03, y: 13.75), controlPoint1: CGPoint(x: 8.34, y: 13.66), controlPoint2: CGPoint(x: 8.18, y: 13.75)) checkmarkPath.addCurve(to: CGPoint(x: 7.61, y: 13.54), controlPoint1: CGPoint(x: 7.89, y: 13.75), controlPoint2: CGPoint(x: 7.73, y: 13.65)) checkmarkPath.addLine(to: CGPoint(x: 4.91, y: 10.85)) checkmarkPath.addLine(to: CGPoint(x: 5.77, y: 9.99)) checkmarkPath.addLine(to: CGPoint(x: 8.04, y: 12.26)) checkmarkPath.addLine(to: CGPoint(x: 14.04, y: 6.22)) checkmarkPath.addLine(to: CGPoint(x: 14.88, y: 7.09)) checkmarkPath.addLine(to: CGPoint(x: 8.46, y: 13.54)) checkmarkPath.close() checkmarkPath.usesEvenOddFillRule = true checkmarkPath.fill() checkmarkLayer.path = checkmarkPath.cgPath checkmarkLayer.fillColor = UIColor.white.cgColor checkmarkView.layer.addSublayer(circleLayer) checkmarkView.layer.addSublayer(checkmarkLayer) return checkmarkView }() override var isSelected: Bool { didSet { UIView.animate(withDuration: 0.2, animations: { self.checkmarkView.alpha = self.isSelected ? 1 : 0 self.highlightView.alpha = self.isSelected ? 0.3 : 0 }) } } override init(frame: CGRect) { self.photoImageView = UIImageView() self.highlightView = UIView() super.init(frame: frame) self.layoutInit() } func layoutInit() { self.photoImageView.contentMode = .scaleAspectFill self.photoImageView.translatesAutoresizingMaskIntoConstraints = false self.highlightView.backgroundColor = UIColor.white self.highlightView.alpha = 0 self.highlightView.translatesAutoresizingMaskIntoConstraints = false self.checkmarkView.alpha = 0 self.checkmarkView.contentMode = .scaleAspectFit self.checkmarkView.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.photoImageView) self.contentView.addSubview(self.highlightView) self.contentView.addSubview(self.checkmarkView) var constraintArray: [NSLayoutConstraint] = [] constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[photoImageView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["photoImageView": self.photoImageView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[photoImageView]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["photoImageView": self.photoImageView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[highlightView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["highlightView": self.highlightView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[highlightView]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["highlightView": self.highlightView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[checkmarkView(20)]-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["checkmarkView": self.checkmarkView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[checkmarkView(20)]-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["checkmarkView": self.checkmarkView])) self.addConstraints(constraintArray) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
3d889071ff9f2c5c6e9ddd405fc01974
46.997297
184
0.606791
false
false
false
false
Palleas/Batman
refs/heads/master
Batman/Domain/Builder.swift
mit
1
import Foundation import Result struct Builder { enum BuilderError: Error, AutoEquatable { case missingContent case somethingElse } typealias TitleAndNotes = (title: String, notes: String?) static func task(from content: String) -> Result<TitleAndNotes, BuilderError> { let scanner = Scanner(string: content) var extractedTitle: NSString? scanner.scanUpToCharacters(from: .newlines, into: &extractedTitle) guard let title = extractedTitle else { return .failure(.missingContent) } guard !scanner.isAtEnd else { return .success((title: title as String, notes: nil) as TitleAndNotes) } let index = content.index(content.startIndex, offsetBy: scanner.scanLocation) let notes = content[index...].trimmingCharacters(in: .whitespacesAndNewlines) return .success((title: title as String, notes: notes) as TitleAndNotes) } }
5888c8054e3335f149649095d04b70d5
34.538462
110
0.695887
false
false
false
false
blkbrds/intern09_final_project_tung_bien
refs/heads/master
MyApp/Model/Schema/NotificationContent.swift
mit
1
// // NotificationContent.swift // MyApp // // Created by AST on 9/1/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import ObjectMapper final class NotificationContent: Mappable { var id = 0 var name = "" var content = "" var time = "" var idOrder = 0 init() { } init?(map: Map) { } func mapping(map: Map) { id <- map["id"] idOrder <- map["typeId"] name <- map["title"] content <- map["description"] time <- map["updatedAt"] } }
04695a83e690ddf32c3533185a26859b
16.060606
62
0.543517
false
false
false
false
BridgeNetworking/Bridge
refs/heads/dev
Bridge/Encoding.swift
mit
2
// // Encoding.swift // Rentals // // Created by Justin Huang on 7/28/15. // Copyright (c) 2015 Zumper. All rights reserved. // import Foundation public enum Encoding { case json public func encode(_ mutableRequest: NSMutableURLRequest, parameters: Dict?) throws -> NSMutableURLRequest { guard let parameters = parameters else { return mutableRequest } switch self { case .json: switch HTTPMethod(rawValue: mutableRequest.httpMethod)! { case .GET, .DELETE: // Encode params in the URL of the request let mappedParameters: Array<(key: String, value: String)> = (parameters).map({ (key, value) in if let collection = value as? [Any] { return (key, self.escapeString("\(key)") + "=" + (collection.reduce("", { $0 + ($0.isEmpty ? "" : ",") + self.escapeString("\($1)")}))) } else { return (key, self.escapeString("\(key)") + "=" + self.escapeString("\(value)") ) } }) let flattenedString = mappedParameters.reduce("", { $0 + $1.1 + "&" } ) // Append the leading `?` character for url encoded requests // and drop the trailing `&` from the reduce let queryString = "?" + String(flattenedString.dropLast()) let baseURL = mutableRequest.url mutableRequest.url = URL(string: queryString, relativeTo: baseURL!) case .POST, .PUT: // Encode params in the HTTP body of the request if JSONSerialization.isValidJSONObject(parameters) { do { let data = try JSONSerialization.data(withJSONObject: parameters, options: []) mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableRequest.httpBody = data } catch let error { throw error } } else { // `parameters` is not a valid JSON object throw BridgeErrorType.encoding } } } return mutableRequest } public func serialize(_ data: Data) throws -> ResponseObject { switch self { case .json: let serializedObject: Any? do { serializedObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { throw BridgeErrorType.serializing } if let object = serializedObject as? Array<Any> { return ResponseObject.jsonArray(object) } else if let object = serializedObject as? Dict { return ResponseObject.jsonDict(object) } } throw BridgeErrorType.serializing } func escapeString(_ string: String) -> String { let allowedDelimiters: String = ":#[]@!$&'()*+,;=" var customAllowedSet = CharacterSet.urlQueryAllowed customAllowedSet.remove(charactersIn: allowedDelimiters) let escapedString = string.addingPercentEncoding(withAllowedCharacters: customAllowedSet) return escapedString! } public func serializeToString(_ data: Data) -> String? { switch self { case .json: return String(data: data, encoding: String.Encoding.utf8) } } } public enum ResponseObject { case jsonArray(Array<Any>) case jsonDict(Dict) public func rawValue() -> Any { switch self { case .jsonArray(let arrayValue): return arrayValue as Any case .jsonDict(let dictionaryValue): return dictionaryValue as Any } } public subscript(key: String) -> Any? { switch self { case .jsonDict(let dictionaryValue): return dictionaryValue[key] default: return nil } } }
e9b69421d64963bc79a810a0cf4e8113
33.892562
159
0.527949
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Supporting Files/Supporting Models/BFUserDefaults.swift
mit
1
// // BFUserDefaults.swift // BlocFit // // Created by Colin Conduff on 11/8/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import Foundation struct BFUserDefaults { static let unitSetting = "unitsSetting" static let friendsDefaultTrusted = "friendsDefaultTrusted" static let shareFirstNameWithTrusted = "shareFirstNameWithTrusted" static func stringFor(unitsSetting isImperialUnits: Bool) -> String { if isImperialUnits { return "Imperial (mi)" } else { return "Metric (km)" } } static func getUnitsSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.unitSetting) } static func set(isImperial: Bool) { let defaults = UserDefaults.standard defaults.set(isImperial, forKey: BFUserDefaults.unitSetting) } static func stringFor(friendsWillDefaultToTrusted defaultTrusted: Bool) -> String { if defaultTrusted { return "New friends are trusted by default" } else { return "New friends are untrusted by default" } } static func getNewFriendDefaultTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.friendsDefaultTrusted) } static func set(friendsWillDefaultToTrusted defaultTrusted: Bool) { let defaults = UserDefaults.standard defaults.set(defaultTrusted, forKey: BFUserDefaults.friendsDefaultTrusted) } static func stringFor(willShareFirstNameWithTrustedFriends willShareName: Bool) -> String { if willShareName { return "Share first name with trusted friends" } else { return "Do not share first name with trusted friends" } } static func getShareFirstNameWithTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.shareFirstNameWithTrusted) } static func set(willShareFirstNameWithTrustedFriends willShareName: Bool) { let defaults = UserDefaults.standard defaults.set(willShareName, forKey: BFUserDefaults.shareFirstNameWithTrusted) } }
b2c9b38a3fff8941017b8f24c51978c0
31.728571
95
0.672632
false
false
false
false
zhangao0086/DKImageBrowserVC
refs/heads/develop
DKPhotoGallery/Preview/ImagePreview/DKPhotoImageDownloader.swift
mit
2
// // DKPhotoImageDownloader.swift // DKPhotoGallery // // Created by ZhangAo on 2018/6/6. // Copyright © 2018 ZhangAo. All rights reserved. // import Foundation import Photos import MobileCoreServices #if canImport(SDWebImage) import SDWebImage #endif protocol DKPhotoImageDownloader { static func downloader() -> DKPhotoImageDownloader func downloadImage(with identifier: Any, progressBlock: ((_ progress: Float) -> Void)?, completeBlock: @escaping ((_ image: UIImage?, _ data: Data?, _ error: Error?) -> Void)) } class DKPhotoImageWebDownloader: DKPhotoImageDownloader { private static let shared = DKPhotoImageWebDownloader() static func downloader() -> DKPhotoImageDownloader { return shared } var _downloader: SDWebImageDownloader = { let config = SDWebImageDownloaderConfig() config.executionOrder = .lifoExecutionOrder let downloader = SDWebImageDownloader.init(config: config) return downloader }() func downloadImage(with identifier: Any, progressBlock: ((Float) -> Void)?, completeBlock: @escaping ((UIImage?, Data?, Error?) -> Void)) { if let URL = identifier as? URL { self._downloader.downloadImage(with: URL, options: .highPriority, progress: { (receivedSize, expectedSize, targetURL) in if let progressBlock = progressBlock { progressBlock(Float(receivedSize) / Float(expectedSize)) } }, completed: { (image, data, error, finished) in if (image != nil || data != nil) && finished { completeBlock(image, data, error) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } else { assertionFailure() } } } class DKPhotoImageAssetDownloader: DKPhotoImageDownloader { private static let shared = DKPhotoImageAssetDownloader() static func downloader() -> DKPhotoImageDownloader { return shared } func downloadImage(with identifier: Any, progressBlock: ((Float) -> Void)?, completeBlock: @escaping ((UIImage?, Data?, Error?) -> Void)) { if let asset = identifier as? PHAsset { let options = PHImageRequestOptions() options.resizeMode = .exact options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true if let progressBlock = progressBlock { options.progressHandler = { (progress, error, stop, info) in if progress > 0 { progressBlock(Float(progress)) } } } let isGif = (asset.value(forKey: "uniformTypeIdentifier") as? String) == (kUTTypeGIF as String) if isGif { PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (data, _, _, info) in if let data = data { completeBlock(nil, data, nil) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } else { PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: UIScreen.main.bounds.width * UIScreen.main.scale, height:UIScreen.main.bounds.height * UIScreen.main.scale), contentMode: .default, options: options, resultHandler: { (image, info) in if let image = image { completeBlock(image, nil, nil) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } } else { assertionFailure() } } }
95df9feb48155a360a76491b95c19915
45.071429
188
0.452885
false
false
false
false
HolidayAdvisorIOS/HolidayAdvisor
refs/heads/master
HolidayAdvisor/HolidayAdvisor/PlaceDetailsViewController.swift
mit
1
// // PlaceDetailsViewController.swift // HolidayAdvisor // // Created by Iliyan Gogov on 4/3/17. // Copyright © 2017 Iliyan Gogov. All rights reserved. // import UIKit class PlaceDetailsViewController: UIViewController { @IBOutlet weak var placeImage: UIImageView! @IBOutlet weak var placeNameLabel: UILabel! @IBOutlet weak var placeInfoLabel: UILabel! @IBOutlet weak var placeOwnerLabel: UILabel! var name : String? = "" var imageUrl: String? = "" var info: String? = "" var owner: String? = "" var rating: Int? = 0 override func viewDidLoad() { super.viewDidLoad() self.placeNameLabel.text = self.name self.placeOwnerLabel.text = self.owner self.placeInfoLabel.text = self.info if let url = NSURL(string: self.imageUrl!) { if let data = NSData(contentsOf: url as URL) { self.placeImage?.image = UIImage(data: data as Data) } } } 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. } */ }
b2a03c11efd6406a069dd261207308f7
27.296296
106
0.63678
false
false
false
false
Longhanks/gtk-test
refs/heads/master
Sources/gtk-test/SWGtkOrientation.swift
mit
1
// // Created by Andreas Schulz on 05.06.16. // import Foundation import Gtk struct SWGtkOrientation : OptionSet { let rawValue : GtkOrientation init(rawValue: GtkOrientation) { self.rawValue = rawValue } init() { rawValue = GTK_ORIENTATION_HORIZONTAL } mutating func formUnion(_ other: SWGtkOrientation) {} mutating func formIntersection(_ other: SWGtkOrientation) {} mutating func formSymmetricDifference(_ other: SWGtkOrientation) {} static let Horizontal = SWGtkOrientation(rawValue: GTK_ORIENTATION_HORIZONTAL) static let Vertical = SWGtkOrientation(rawValue: GTK_ORIENTATION_VERTICAL) } extension GtkOrientation: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = Int public init(integerLiteral: IntegerLiteralType) { self.init(UInt32(integerLiteral)) } }
4155c7cc12ea86fc62406d7c8010ab59
25.151515
82
0.726218
false
false
false
false
eppeo/FYSliderView
refs/heads/master
FYBannerView/Classes/View/BannerPageControl.swift
mit
2
// // TimerDelegate.swift // FYBannerView // // Created by 武飞跃 on 2017/4/10. // import Foundation public class BannerPageControl: UIView { public var borderColor: UIColor = UIColor.white.withAlphaComponent(0.6) public var normalColor: UIColor = UIColor.white.withAlphaComponent(0.6) public var selectorColor: UIColor = UIColor.white public var isHidesForSinglePage: Bool = true /** pageControl的样式*/ internal var style: BannerPageControlStyle! internal var numberOfPages: Int = 0 { didSet { updateLayer() invalidateIntrinsicContentSize() if defaultActiveStatus { defaultActiveStatus = false //默认第一个显示 changeActivity(index: 0, isActive: true) } } } internal var currentPage:Int = 0 { willSet{ if newValue == currentPage { return } changeActivity(index: newValue, isActive: true) } didSet{ if currentPage == oldValue { return } changeActivity(index: oldValue, isActive: false) } } private var defaultActiveStatus: Bool = true private var dots:[DotLayer] = [] { didSet{ if dots.count == 1 { if isHidesForSinglePage { dots.first?.isHidden = true } else{ changeActivity(index: 0, isActive: true) } } else{ dots.first?.isHidden = false } } } private func changeActivity(index: Int, isActive: Bool){ guard index >= 0 && index < dots.count else { return } if isActive == true { dots[index].startAnimation() } else{ dots[index].stopAnimation() } } private func createLayer() -> DotLayer { var dot: DotLayer! switch style.type { case .ring: let ringDot = RingDotLayer(size: CGSize(width: style.width, height: style.height), borderWidth: style.borderWidth) ringDot.normalColor = normalColor.cgColor ringDot.selectedColor = selectorColor.cgColor dot = ringDot } defer { dots.append(dot) } dot.anchorPoint = CGPoint.zero dot.stopAnimation() return dot } public override var intrinsicContentSize: CGSize { return style.calcDotSize(num: numberOfPages) } /// 移除多余layer /// /// - Parameter num: 需要移除的layer个数 private func removeLayer(num:Int){ if let unwrapped = layer.sublayers, unwrapped.count >= num { for _ in 0 ..< num { layer.sublayers?.last?.removeFromSuperlayer() } } let range:Range<Int> = numberOfPages ..< dots.count dots.removeSubrange(range) } private func updateLayer(){ let sub = dots.count - numberOfPages if sub > 0 { removeLayer(num: sub) } else if sub < 0 { addLayer() } } private func addLayer(){ for i in 0 ..< numberOfPages { var dot: CALayer! if dots.count > i { dot = dots[i] } else{ dot = createLayer() } let point = style.calcDotPosition(index: i) dot.position = point layer.addSublayer(dot) } } }
888792a31e280499a45e1a182d39f664
23.993333
126
0.496666
false
false
false
false
digitwolf/SwiftFerrySkill
refs/heads/master
Sources/Ferry/Models/SpaceForArrivalTerminals.swift
apache-2.0
1
// // SpaceForArrivalTerminals.swift // FerrySkill // // Created by Shakenova, Galiya on 3/3/17. // // import Foundation import SwiftyJSON public class SpaceForArrivalTerminals { public var terminalID : Int? = 0 public var terminalName : String? = "" public var vesselID : Int? = 0 public var vesselName : String? = "" public var displayReservableSpace : Bool? = false public var reservableSpaceCount : Int? = 0 public var reservableSpaceHexColor : String? = "" public var displayDriveUpSpace : Bool? = false public var driveUpSpaceCount : Int? = 0 public var driveUpSpaceHexColor : String? = "" public var maxSpaceCount : Int? = 0 public var arrivalTerminalIDs: [Int] = [] init() { } public init(_ json: JSON) { terminalID = json["TerminalID"].intValue terminalName = json["TerminalName"].stringValue vesselName = json["VesselName"].stringValue vesselID = json["VesselID"].intValue displayReservableSpace = json["DisplayReservableSpace"].boolValue reservableSpaceCount = json["ReservableSpaceCount"].intValue reservableSpaceHexColor = json["ReservableSpaceHexColor"].stringValue displayDriveUpSpace = json["DisplayDriveUpSpace"].boolValue driveUpSpaceCount = json["DriveUpSpaceCount"].intValue driveUpSpaceHexColor = json["DriveUpSpaceHexColor"].stringValue maxSpaceCount = json["MaxSpaceCount"].intValue for terminal in json["ArrivalTerminalIDs"].arrayValue { arrivalTerminalIDs.append(terminal.intValue) } } public func toJson() -> JSON { var json = JSON([]) json["TerminalID"].intValue = terminalID! json["TerminalName"].stringValue = terminalName! json["VesselName"].stringValue = vesselName! json["VesselID"].intValue = vesselID! json["DisplayReservableSpace"].boolValue = displayReservableSpace! json["ReservableSpaceCount"].intValue = reservableSpaceCount! json["ReservableSpaceHexColor"].stringValue = reservableSpaceHexColor! json["DisplayDriveUpSpace"].boolValue = displayDriveUpSpace! json["DriveUpSpaceCount"].intValue = driveUpSpaceCount! json["DriveUpSpaceHexColor"].stringValue = driveUpSpaceHexColor! json["MaxSpaceCount"].intValue = maxSpaceCount! var terminals: [Int] = [] for terminal in arrivalTerminalIDs { terminals.append(terminal) } json["ArrivalTerminalIDs"] = JSON(terminals) return json } }
5b296b64fa7cb8f0aca585abe295bad7
36.710145
78
0.669101
false
false
false
false
crspybits/SyncServerII
refs/heads/dev
Tests/ServerTests/SpecificDatabaseTests_SharingGroups.swift
mit
1
// // SpecificDatabaseTests_SharingGroups.swift // ServerTests // // Created by Christopher G Prince on 7/4/18. // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class SpecificDatabaseTests_SharingGroups: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAddSharingGroupWithoutName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } } func testAddSharingGroupWithName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID, sharingGroupName: "Foobar") else { XCTFail() return } } func testLookupFromSharingGroupExisting() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let key = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found(let model): guard let obj = model as? Server.SharingGroup else { XCTFail() return } XCTAssert(obj.sharingGroupUUID != nil) case .noObjectFound: XCTFail("No object found") case .error(let error): XCTFail("Error: \(error)") } } func testLookupFromSharingGroupNonExisting() { let key = SharingGroupRepository.LookupKey.sharingGroupUUID(UUID().uuidString) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found: XCTFail() case .noObjectFound: break case .error(let error): XCTFail("Error: \(error)") } } } extension SpecificDatabaseTests_SharingGroups { static var allTests : [(String, (SpecificDatabaseTests_SharingGroups) -> () throws -> Void)] { return [ ("testAddSharingGroupWithoutName", testAddSharingGroupWithoutName), ("testAddSharingGroupWithName", testAddSharingGroupWithName), ("testLookupFromSharingGroupExisting", testLookupFromSharingGroupExisting), ("testLookupFromSharingGroupNonExisting", testLookupFromSharingGroupNonExisting) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_SharingGroups.self) } }
89b702212b3477756d6b306adbe85cd1
31.752688
111
0.648063
false
true
false
false
J-Mendes/Weather
refs/heads/master
Weather/Weather/Core Layer/Data Model/Astronomy.swift
gpl-3.0
1
// // Astronomy.swift // Weather // // Created by Jorge Mendes on 05/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import Foundation struct Astronomy { internal var sunrise: Date! internal var sunset: Date! init() { self.sunrise = Date() self.sunset = Date() } init(dictionary: [String: Any]) { self.init() if let sunriseString: String = dictionary["sunrise"] as? String, let sunrise: Date = sunriseString.dateValueFromHour() { self.sunrise = sunrise } if let sunsetString: String = dictionary["sunset"] as? String, let sunset: Date = sunsetString.dateValueFromHour() { self.sunset = sunset } } }
87f7fa5fbc82b243225da71fdb65ca3e
21.4
72
0.566327
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/CoreData/ManagedObjects/RunPoint+CoreDataClass.swift
mit
1
// // RunPoint+CoreDataClass.swift // BlocFit // // Created by Colin Conduff on 10/1/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import CoreLocation import CoreData public class RunPoint: NSManagedObject { static let entityName = "RunPoint" /* longitude: Double latitude: Double timestamp: NSDate? metersFromLastPoint: Double run: Run? */ class func create( latitude: Double, longitude: Double, run: Run, lastRunPoint: RunPoint?, // must pass in nil if first run point context: NSManagedObjectContext) throws -> RunPoint? { var runPoint: RunPoint? context.performAndWait { runPoint = NSEntityDescription.insertNewObject( forEntityName: RunPoint.entityName, into: context) as? RunPoint runPoint?.run = run runPoint?.timestamp = NSDate() runPoint?.latitude = latitude runPoint?.longitude = longitude if let lastLatitude = lastRunPoint?.latitude, let lastLongitude = lastRunPoint?.longitude { let current2DCoordinates = CLLocationCoordinate2D( latitude: latitude, longitude: longitude) let last2DCoordinates = CLLocationCoordinate2D( latitude: lastLatitude, longitude: lastLongitude) let currentLocation = CLLocation( latitude: current2DCoordinates.latitude, longitude: current2DCoordinates.longitude) let lastLocation = CLLocation( latitude: last2DCoordinates.latitude, longitude: last2DCoordinates.longitude) let distance = currentLocation.distance(from: lastLocation) runPoint?.metersFromLastPoint = distance } else { runPoint?.metersFromLastPoint = 0 } } try context.save() return runPoint } func delete() throws { self.managedObjectContext?.delete(self) try self.managedObjectContext?.save() } }
e6858c669cf78af5097d827bfee0a3dd
29.61039
75
0.54773
false
false
false
false
cezarywojcik/Operations
refs/heads/development
Sources/Core/Shared/ComposedOperation.swift
mit
1
// // ComposedOperation.swift // Operations // // Created by Daniel Thorpe on 28/08/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation open class ComposedOperation<T: Operation>: GroupOperation { open var operation: T public convenience init(_ composed: T) { self.init(operation: composed) } init(operation composed: T) { self.operation = composed super.init(operations: [composed]) name = "Composed <\(T.self)>" addObserver(WillCancelObserver { [unowned self] operation, errors in guard operation === self else { return } if !errors.isEmpty, let op = self.operation as? AdvancedOperation { op.cancelWithError(OperationError.parentOperationCancelledWithErrors(errors)) } else { self.operation.cancel() } }) } }
5ac6cf4eda57b7bd903765226c569f3b
26.666667
93
0.614458
false
false
false
false
miracl/amcl
refs/heads/master
version3/swift/rom_brainpool.swift
apache-2.0
1
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // // rom.swift // // Created by Michael Scott on 12/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // // Note that the original curve has been transformed to an isomorphic curve with A=-3 public struct ROM{ #if D32 // Base Bits= 28 // Brainpool Modulus static public let Modulus:[Chunk] = [0xF6E5377,0x13481D1,0x6202820,0xF623D52,0xD726E3B,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA] static let R2modp:[Chunk] = [0xB9A3787,0x9E04F49,0x8F3CF49,0x2931721,0xF1DBC89,0x54E8C3C,0xF7559CA,0xBB411A3,0x773E15F,0x9] static let MConst:Chunk = 0xEFD89B9 // Brainpool Curve static let CURVE_Cof_I:Int=1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = 0 static let CURVE_B:[Chunk] = [0xEE92B04,0xE58101F,0xF49256A,0xEBC4AF2,0x6B7BF93,0x733D0B7,0x4FE66A7,0x30D84EA,0x62C61C4,0x6] static public let CURVE_Order:[Chunk] = [0x74856A7,0x1E0E829,0x1A6F790,0x7AA3B56,0xD718C39,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA] static public let CURVE_Gx:[Chunk] = [0xE1305F4,0xA191562,0xFBC2B79,0x42C47AA,0x149AFA1,0xB23A656,0x7732213,0xC1CFE7B,0x3E8EB3C,0xA] static public let CURVE_Gy:[Chunk] = [0xB25C9BE,0xABE8F35,0x27001D,0xB6DE39D,0x17E69BC,0xE146444,0xD7F7B22,0x3439C56,0xD996C82,0x2] #endif #if D64 // Base Bits= 56 // Brainpool Modulus static public let Modulus:[Chunk] = [0x13481D1F6E5377,0xF623D526202820,0x909D838D726E3B,0xA1EEA9BC3E660A,0xA9FB57DB] static let R2modp:[Chunk] = [0x9E04F49B9A3787,0x29317218F3CF49,0x54E8C3CF1DBC89,0xBB411A3F7559CA,0x9773E15F] static let MConst:Chunk = 0xA75590CEFD89B9 // Brainpool Curve static let CURVE_Cof_I:Int=1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = 0 static let CURVE_B:[Chunk] = [0xE58101FEE92B04,0xEBC4AF2F49256A,0x733D0B76B7BF93,0x30D84EA4FE66A7,0x662C61C4] static public let CURVE_Order:[Chunk] = [0x1E0E82974856A7,0x7AA3B561A6F790,0x909D838D718C39,0xA1EEA9BC3E660A,0xA9FB57DB] static public let CURVE_Gx:[Chunk] = [0xA191562E1305F4,0x42C47AAFBC2B79,0xB23A656149AFA1,0xC1CFE7B7732213,0xA3E8EB3C] static public let CURVE_Gy:[Chunk] = [0xABE8F35B25C9BE,0xB6DE39D027001D,0xE14644417E69BC,0x3439C56D7F7B22,0x2D996C82] #endif }
fc82e1810c85c336052bbbf5c6e02b63
39.878378
135
0.792066
false
false
false
false
Zewo/TrieRouteMatcher
refs/heads/master
Source/Trie.swift
mit
1
// Trie.swift // // The MIT License (MIT) // // Copyright (c) 2016 Dan Appel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public struct Trie<Element: Comparable, Payload> { let prefix: Element? var payload: Payload? var ending: Bool var children: [Trie<Element, Payload>] init() { self.prefix = nil self.payload = nil self.ending = false self.children = [] } init(prefix: Element, payload: Payload?, ending: Bool, children: [Trie<Element, Payload>]) { self.prefix = prefix self.payload = payload self.ending = ending self.children = children self.children.sort() } } public func ==<Element, Payload where Element: Comparable>(lhs: Trie<Element, Payload>, rhs: Trie<Element, Payload>) -> Bool { return lhs.prefix == rhs.prefix } public func <<Element, Payload where Element: Comparable>(lhs: Trie<Element, Payload>, rhs: Trie<Element, Payload>) -> Bool { return lhs.prefix < rhs.prefix } extension Trie: Comparable { } extension Trie { var description: String { return pretty(depth: 0) } func pretty(depth: Int) -> String { let key: String if let k = self.prefix { key = "\(k)" } else { key = "head" } let payload: String if let p = self.payload { payload = ":\(p)" } else { payload = "" } let children = self.children .map { $0.pretty(depth: depth + 1) } .reduce("", combine: { $0 + $1}) let pretty = "- \(key)\(payload)" + "\n" + "\(children)" let indentation = (0..<depth).reduce("", combine: {$0.0 + " "}) return "\(indentation)\(pretty)" } } extension Trie { mutating func insert<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType, payload: Payload? = nil) { insert(sequence.makeIterator(), payload: payload) } mutating func insert<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator, payload: Payload? = nil) { var iterator = iterator guard let element = iterator.next() else { self.payload = self.payload ?? payload self.ending = true return } for (index, child) in children.enumerated() { var child = child if child.prefix == element { child.insert(iterator, payload: payload) self.children[index] = child self.children.sort() return } } var new = Trie<Element, Payload>(prefix: element, payload: nil, ending: false, children: []) new.insert(iterator, payload: payload) self.children.append(new) self.children.sort() } } extension Trie { func findLast<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Trie<Element, Payload>? { return findLast(sequence.makeIterator()) } func findLast<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Trie<Element, Payload>? { var iterator = iterator guard let target = iterator.next() else { guard ending == true else { return nil } return self } // binary search var lower = 0 var higher = children.count - 1 while (lower <= higher) { let middle = (lower + higher) / 2 let child = children[middle] guard let current = child.prefix else { continue } if (current == target) { return child.findLast(iterator) } if (current < target) { lower = middle + 1 } if (current > target) { higher = middle - 1 } } return nil } } extension Trie { func findPayload<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Payload? { return findPayload(sequence.makeIterator()) } func findPayload<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Payload? { return findLast(iterator)?.payload } } extension Trie { func contains<SequenceType: Sequence where SequenceType.Iterator.Element == Element>(_ sequence: SequenceType) -> Bool { return contains(sequence.makeIterator()) } func contains<Iterator: IteratorProtocol where Iterator.Element == Element>(_ iterator: Iterator) -> Bool { return findLast(iterator) != nil } } extension Trie where Payload: Equatable { func findByPayload(_ payload: Payload) -> [Element]? { if self.payload == payload { // not sure what to do if it doesnt have a prefix if let prefix = self.prefix { return [prefix] } return [] } for child in children { if let prefixes = child.findByPayload(payload) { if let prefix = self.prefix { return [prefix] + prefixes } return prefixes } } return nil } } extension Trie { mutating func sort(_ isOrderedBefore: (Trie<Element, Payload>, Trie<Element, Payload>) -> Bool) { self.children = children.map { child in var child = child child.sort(isOrderedBefore) return child } self.children.sort(isOrderedBefore: isOrderedBefore) } }
767fbe093b6c57224351f14811d3d2c9
30.356164
148
0.58468
false
false
false
false
jzucker2/JZToolKit
refs/heads/master
JZToolKit/Classes/Experimental/ObservingViewController.swift
mit
1
// // ObservingViewController.swift // Pods // // Created by Jordan Zucker on 2/19/17. // // import UIKit class ObservingViewController: ToolKitViewController, Observer { public var kvoContext: Int = 0 open class var observerResponses: [String:Selector]? { return nil } public func updateKVO(with actions: KVOActions, oldValue: NSObject? = nil) { guard let observingKeyPaths = type(of: self).observerResponses else { print("No observer responses exist") return } for (keyPath, _) in observingKeyPaths { if actions.contains(.removeOldValue) { oldValue?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext) } if actions.contains(.remove) { observedObject?.removeObserver(self, forKeyPath: keyPath, context: &kvoContext) } if actions.contains(.add) { observedObject?.addObserver(self, forKeyPath: keyPath, options: [.new, .old, .initial], context: &kvoContext) } } } open var observedObject: NSObject? { didSet { print("hey there: \(#function)") updateKVO(with: .propertyObserverActions, oldValue: oldValue) } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // print("self: \(self.debugDescription) \(#function) context: \(context)") if context == &kvoContext { guard let observingKeyPaths = type(of: self).observerResponses else { print("No observing Key Paths exist") return } guard let actualKeyPath = keyPath, let action = observingKeyPaths[actualKeyPath] else { fatalError("we should have had an action for this keypath since we are observing it") } let mainQueueUpdate = DispatchWorkItem(qos: .userInitiated, flags: [.enforceQoS], block: { [weak self] in // _ = self?.perform(action) _ = self?.perform(action) }) DispatchQueue.main.async(execute: mainQueueUpdate) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // open override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // updateKVO(with: .add) // } // // open override func viewDidDisappear(_ animated: Bool) { // super.viewDidDisappear(animated) // updateKVO(with: .remove) // } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { observedObject = nil } }
0bc476f5039f57257b6f53780c1db1c0
34.445783
156
0.587695
false
false
false
false
J3D1-WARR10R/WikiRaces
refs/heads/master
WKRKit/WKRKit/Other/WKROperation.swift
mit
2
// // WKROperation.swift // WKRKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation /// Subclass the allows async operation blocks final public class WKROperation: BlockOperation { // MARK: - Types public enum State: String { case isReady, isExecuting, isFinished } // MARK: - Properties public var state = State.isReady { willSet { willChangeValue(forKey: newValue.rawValue) willChangeValue(forKey: state.rawValue) } didSet { didChangeValue(forKey: oldValue.rawValue) didChangeValue(forKey: state.rawValue) } } public override var isReady: Bool { return super.isReady && state == .isReady } public override var isExecuting: Bool { return state == .isExecuting } public override var isFinished: Bool { return state == .isFinished } public override var isAsynchronous: Bool { return true } }
c2cf08f0ba2c4f69e98cf1f55b198a10
20.854167
55
0.618684
false
false
false
false
CGDevHusky92/CGDataController
refs/heads/master
CGDataController/CGDataController.swift
mit
1
/** * CGDataController.swift * CGDataController * * Created by Charles Gorectke on 9/27/13. * Copyright (c) 2014 Revision Works, LLC. All rights reserved. * * The MIT License (MIT) * * Copyright (c) 2014 Revision Works, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Last updated on 2/22/15 */ import UIKit import CoreData public let kCGDataControllerFinishedSaveNotification = "kCGDataControllerFinishedSaveNotification" public let kCGDataControllerFinishedBackgroundSaveNotification = "kCGDataControllerFinishedBackgroundSaveNotification" public class CGDataController: NSObject { var defaultStoreName: String? var dataStores = [ String : CGDataStore ]() public static var testBundleClass: AnyClass? public class var sharedDataController: CGDataController { struct StaticData { static let data : CGDataController = CGDataController() } return StaticData.data } public class func initSharedDataWithStoreName(storeName: String, makeDefault defaultStore: Bool = false) -> CGDataStore { if let defStore = CGDataController.sharedDataController.defaultStoreName { if defaultStore { CGDataController.sharedDataController.defaultStoreName = storeName } } else { CGDataController.sharedDataController.defaultStoreName = storeName } let dataStore = CGDataStore(sName: storeName) CGDataController.sharedDataController.dataStores.updateValue(dataStore, forKey: storeName) return dataStore } public class func sharedData() -> CGDataStore { let d = CGDataController.sharedDataController if let s = d.defaultStoreName { return self.sharedDataWithName(s) } assert(false, "You must set a store name by calling +(id)initSharedDataWithStoreName: before making calls to +(id)sharedData") } public class func sharedDataWithName(sName: String) -> CGDataStore { let d = CGDataController.sharedDataController if let s = d.dataStores[sName] { return s } assert(false, "You must set a store name by calling +(id)initSharedDataWithStoreName: before making calls to +(id)sharedDataWithName:") } private class func getModelStoreURL(storeName: String, withBundle bundle: NSBundle) -> NSURL? { var modelURL = bundle.URLForResource(storeName, withExtension: "mom") if let mURL = modelURL {} else { modelURL = bundle.URLForResource(storeName, withExtension: "momd") if let mURL = modelURL { modelURL = mURL.URLByAppendingPathComponent("\(storeName).mom") } } return modelURL } public class func modifiedObjectModelWithStoreName(storeName: String) -> NSManagedObjectModel? { let bundle: NSBundle if let tBundle: AnyClass = testBundleClass { bundle = NSBundle(forClass: tBundle) } else { bundle = NSBundle.mainBundle() } let urlTemp = self.getModelStoreURL(storeName, withBundle: bundle) if let modelURL = urlTemp { let modifiableModelTemp = NSManagedObjectModel(contentsOfURL: modelURL) if let modifiableModel = modifiableModelTemp { var entities = [NSEntityDescription]() let modelEntities = modifiableModel.entities as! [NSEntityDescription] for ent in modelEntities { var currentProps = ent.properties let objId = NSAttributeDescription() objId.name = "objectId" objId.attributeType = .StringAttributeType objId.optional = false objId.defaultValue = NSUUID().UUIDString currentProps.append(objId) let createdAt = NSAttributeDescription() createdAt.name = "createdAt" createdAt.attributeType = .DateAttributeType createdAt.optional = false currentProps.append(createdAt) let updatedAt = NSAttributeDescription() updatedAt.name = "updatedAt" updatedAt.attributeType = .DateAttributeType updatedAt.optional = false currentProps.append(updatedAt) let wasDeleted = NSAttributeDescription() wasDeleted.name = "wasDeleted" wasDeleted.attributeType = .BooleanAttributeType wasDeleted.optional = false wasDeleted.defaultValue = NSNumber(bool: false) currentProps.append(wasDeleted) let note = NSAttributeDescription() note.name = "note" note.attributeType = .StringAttributeType note.optional = true currentProps.append(note) let syncStatus = NSAttributeDescription() syncStatus.name = "syncStatus" syncStatus.attributeType = .Integer16AttributeType syncStatus.optional = false syncStatus.defaultValue = NSNumber(integer: 0) currentProps.append(syncStatus) ent.properties = currentProps entities.append(ent) } modifiableModel.entities = entities return modifiableModel } } else { assert(false, "The model could not be found. Check to make sure you have the correct model name and extension.") } return nil } } //// MARK: - Core Data stack // //lazy var applicationDocumentsDirectory: NSURL = { // // The directory the application uses to store the Core Data store file. This code uses a directory named "com.revisionworks.TestData" in the application's documents Application Support directory. // let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) // return urls[urls.count-1] as! NSURL // }() // //lazy var managedObjectModel: NSManagedObjectModel = { // // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. // let modelURL = NSBundle.mainBundle().URLForResource("TestData", withExtension: "momd")! // return NSManagedObjectModel(contentsOfURL: modelURL)! // }() // //lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // // Create the coordinator and store // var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TestData.sqlite") // var error: NSError? = nil // var failureReason = "There was an error creating or loading the application's saved data." // if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { // coordinator = nil // // Report any error we got. // var dict = [String: AnyObject]() // dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" // dict[NSLocalizedFailureReasonErrorKey] = failureReason // dict[NSUnderlyingErrorKey] = error // error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // // Replace this with code to handle the error appropriately. // // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // NSLog("Unresolved error \(error), \(error!.userInfo)") // abort() // } // // return coordinator // }() // //lazy var managedObjectContext: NSManagedObjectContext? = { // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. // let coordinator = self.persistentStoreCoordinator // if coordinator == nil { // return nil // } // var managedObjectContext = NSManagedObjectContext() // managedObjectContext.persistentStoreCoordinator = coordinator // return managedObjectContext // }() // //// MARK: - Core Data Saving support // //func saveContext () { // if let moc = self.managedObjectContext { // var error: NSError? = nil // if moc.hasChanges && !moc.save(&error) { // // Replace this implementation with code to handle the error appropriately. // // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // NSLog("Unresolved error \(error), \(error!.userInfo)") // abort() // } // } //} public class CGDataStore: NSObject { var _masterManagedObjectContext: NSManagedObjectContext? var masterManagedObjectContext: NSManagedObjectContext? { if let m = _masterManagedObjectContext { return m } _masterManagedObjectContext = self.setupManagedObjectContextWithConcurrencyType(.MainQueueConcurrencyType) return _masterManagedObjectContext } var _backgroundManagedObjectContext: NSManagedObjectContext? public var backgroundManagedObjectContext: NSManagedObjectContext? { if let b = _backgroundManagedObjectContext { return b } _backgroundManagedObjectContext = self.setupManagedObjectContextWithConcurrencyType(.PrivateQueueConcurrencyType) return _backgroundManagedObjectContext } var _managedObjectModel: NSManagedObjectModel? var managedObjectModel: NSManagedObjectModel? { if let m = _managedObjectModel { return m } _managedObjectModel = CGDataController.modifiedObjectModelWithStoreName(storeName) return _managedObjectModel } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? var persistentStoreCoordinator: NSPersistentStoreCoordinator? { if let p = _persistentStoreCoordinator { return p } if let model = managedObjectModel { let fileManager = NSFileManager.defaultManager() let docPath = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeURL = docPath.URLByAppendingPathComponent("\(storeName).sqlite") let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ] var error: NSError? _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) if let p = _persistentStoreCoordinator { let store = p.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) if let s = store { return _persistentStoreCoordinator } else if let err = error { println("Error: \(err.localizedDescription)") } } } return nil } public let storeName: String public init(sName: String) { storeName = sName super.init() NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextDidSaveNotification, object: nil, queue: nil, usingBlock: { note in if let context = self.masterManagedObjectContext { let notifiedContext = note.object as! NSManagedObjectContext if notifiedContext != context { context.performBlock({_ in context.mergeChangesFromContextDidSaveNotification(note) }) } } }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: nil) } public func save() { if let context = backgroundManagedObjectContext { context.performBlockAndWait({_ in var error: NSError? let saved = context.save(&error) if !saved { if let err = error { println("Error: \(err.localizedDescription)") } } NSNotificationCenter.defaultCenter().postNotificationName(kCGDataControllerFinishedSaveNotification, object: nil) }) } } public func saveMasterContext() { if let context = masterManagedObjectContext { context.performBlockAndWait({_ in var error: NSError? let saved = context.save(&error) if !saved { if let err = error { println("Error: \(err.localizedDescription)") } } NSNotificationCenter.defaultCenter().postNotificationName(kCGDataControllerFinishedSaveNotification, object: nil) }) } } public func resetStore() { self.save() self.saveMasterContext() _backgroundManagedObjectContext = nil _masterManagedObjectContext = nil _managedObjectModel = nil _persistentStoreCoordinator = nil } public func deleteStore() { let fileManager = NSFileManager.defaultManager() let docPath = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeURL = docPath.URLByAppendingPathComponent("\(storeName).sqlite") if let storePath = storeURL.path { let exists = fileManager.fileExistsAtPath(storePath) if exists { var error: NSError? fileManager.removeItemAtPath(storePath, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } else { if let context = self.masterManagedObjectContext { for ct in context.registeredObjects { context.deleteObject(ct as! NSManagedObject) } } } } _persistentStoreCoordinator = nil self.persistentStoreCoordinator } } /* Setup Contexts */ private func setupManagedObjectContextWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext? { if let coord = self.persistentStoreCoordinator { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.performBlockAndWait({_ in context.persistentStoreCoordinator = coord }) return context } return nil } /* Generate Status Dictionary */ public func statusDictionaryForClass(className: String) -> NSDictionary? { if let context = backgroundManagedObjectContext { var error: NSError? let request = NSFetchRequest(entityName: className) let count = context.countForFetchRequest(request, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } else { var ret = NSMutableDictionary() let dateObj = self.managedObjectsForClass(className, sortedByKey: "updatedAt", ascending: false, withFetchLimit: 1) if let d = dateObj { if d.count > 1 { println("Error: Fetch for 1 item returned multiple") } else if d.count == 0 { ret.setObject(NSNumber(integer: count), forKey: "count") ret.setObject("", forKey: "lastUpdatedAt") } else { let obj = d[0] as! CGManagedObject ret.setObject(NSNumber(integer: count), forKey: "count") ret.setObject(obj.updatedAt, forKey: "lastUpdatedAt") } } return ret } } return nil } /* Generate New Object With Class */ public func newManagedObjectForClass(className: String) -> CGManagedObject? { if let context = backgroundManagedObjectContext { let objTemp = NSEntityDescription.insertNewObjectForEntityForName(className, inManagedObjectContext: context) as? CGManagedObject if let obj = objTemp { let date = NSDate() obj.createdAt = date obj.updatedAt = date return obj } else { println("Error") } } return nil } /* Single Object Existence */ public func objectExistsOnDiskWithClass(className: String, andObjectId objId: String) -> Bool { let obj = self.managedObjectForClass(className, withId: objId) if let o = obj { return true } else { return false } } /* Single Managed Object Fetch */ public func managedObjectWithManagedID(objID: NSManagedObjectID) -> CGManagedObject? { if let c = backgroundManagedObjectContext { return c.objectRegisteredForID(objID) as? CGManagedObject } return nil } public func managedObjectForClass(className: String, withId objId: String) -> CGManagedObject? { let objArray = self.managedObjectsForClass(className, sortedByKey: "createdAt", ascending: false, withPredicate: NSPredicate(format: "objectId like %@", objId)) if let a = objArray { if a.count == 0 { return nil } else if a.count > 1 { assert(false, "Error: More than one object has objectId <\(objId)>") } return a[0] as? CGManagedObject } return nil } public func nth(num: Int, managedObjectForClass className: String) -> CGManagedObject? { let objArray = self.managedObjectsForClass(className, sortedByKey: "updatedAt", ascending: false) if let a = objArray { if a.count >= num { return a[num - 1] as? CGManagedObject } } return nil } /* Single Dictionary Fetch */ public func managedObjAsDictionaryWithManagedID(objID: NSManagedObjectID) -> NSDictionary? { if let context = backgroundManagedObjectContext { let manObjTemp = context.objectRegisteredForID(objID) as? CGManagedObject if let manObj = manObjTemp { if let name = manObj.entity.name { return self.managedObjAsDictionaryForClass(name, withId: manObj.objectId as String) } else { return self.managedObjAsDictionaryForClass(manObj.entity.managedObjectClassName, withId: manObj.objectId as String) } } } return nil } public func managedObjAsDictionaryForClass(className: String, withId objId: String) -> NSDictionary? { let objArray = self.managedObjsAsDictionariesForClass(className, sortedByKey: "createdAt", ascending: false, withPredicate: NSPredicate(format: "objectId like %@", objId)) if let a = objArray { if a.count == 0 || a.count > 1 { assert(false, "Error: More than one object has objectId <\(objId)>") } return a[0] as? NSDictionary } return nil } /* Fetch Objects */ public func managedObjectsForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil) -> [AnyObject]? { return self.objectsForClass(className, sortedByKey: key, ascending: ascend, withFetchLimit: limit, withBatchSize: num, withPredicate: predicate, asDictionaries: false) } /* Fetch Objects as Dictionaries for quick lookup */ public func managedObjsAsDictionariesForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil) -> [AnyObject]? { return self.objectsForClass(className, sortedByKey: key, ascending: ascend, withFetchLimit: limit, withBatchSize: num, withPredicate: predicate, asDictionaries: true) } private func objectsForClass(className: String, sortedByKey key: String? = nil, ascending ascend: Bool = true, withFetchLimit limit: Int = 0, withBatchSize num: Int = 0, withPredicate predicate: NSPredicate? = nil, asDictionaries dicts: Bool) -> [AnyObject]? { if let context = backgroundManagedObjectContext { let fetchRequest = NSFetchRequest(entityName: className) fetchRequest.predicate = predicate fetchRequest.fetchBatchSize = num if limit > 0 { fetchRequest.fetchLimit = limit } if let k = key { fetchRequest.sortDescriptors = [ NSSortDescriptor(key: k, ascending: ascend) ] } if dicts { fetchRequest.resultType = .DictionaryResultType } var results: [AnyObject]? var error: NSError? context.performBlockAndWait({_ in results = context.executeFetchRequest(fetchRequest, error: &error) if let err = error { println("Error: \(err.localizedDescription)") } }) return results; } return nil } }
383d4d8cff875c9248b965253994fe9d
46.366599
288
0.638416
false
false
false
false
BarTabs/bartabs
refs/heads/master
ios-application/Bar Tabs/TypeViewController.swift
gpl-3.0
1
// // drinksViewController.swift // Bar Tabs // // Created by Dexstrum on 3/2/17. // Copyright © 2017 muhlenberg. All rights reserved. /* This view controller gets all of the sub categories (i.e. Beers, Cocktails, Spirits, Mixed Drinks) and displays it in a table view. */ import UIKit import Alamofire import SwiftyJSON var _category: String? class TypeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var menu : JSON? var category: String { return _category ?? "" } @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = category self.automaticallyAdjustsScrollViewInsets = false tableView.delegate = self tableView.dataSource = self fetchData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] self.navigationController?.navigationBar.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.menu?.count) ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if (self.menu != nil) { let jsonVar : JSON = self.menu! let type = jsonVar[indexPath.row].string cell.textLabel?.text = type } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let jsonVar : JSON = self.menu! _type = jsonVar[indexPath.row].string performSegue(withIdentifier: "typeSegue", sender: nil) } func fetchData() { let service = "menu/getmenu" let parameters: Parameters = [ "barID" : 4, "category" : category ] let dataService = DataService(view: self) dataService.fetchData(service: service, parameters: parameters, completion: {(response: JSON) -> Void in self.menu = response self.tableView.reloadData() }) } }
200525051c034f2ba2def24ebfe4385e
27.957895
117
0.636496
false
false
false
false
nkirby/Humber
refs/heads/master
Humber/_src/View Controller/Pull Request List/PullRequestListViewController.swift
mit
1
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import Async import SafariServices import HMCore import HMGithub // ======================================================= class PullRequestListViewController: UITableViewController, NavigationBarUpdating, TableDividerUpdating { // ======================================================= // MARK: - Init, etc... required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.navigationController?.tabBarItem.imageInsets = UIEdgeInsets(top: 4.0, left: 0.0, bottom: -4.0, right: 0.0) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // ======================================================= // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setupNavigationItemTitle() self.setupNavigationBarStyling() self.setupTableView() self.updateTableDivider() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PullRequestListViewController.didChangeTheme), name: Theme.themeChangedNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ======================================================= // MARK: - Setup private func setupNavigationItemTitle() { self.navigationItem.title = "Pull Requests" } private func setupTableView() { self.tableView.backgroundColor = Theme.color(type: .ViewBackgroundColor) } @objc private func didChangeTheme() { self.updateTableDivider() self.setupTableView() self.setupNavigationBarStyling() } // ======================================================= // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } }
914ad93fb841e42ad51b331aa6a3f103
28.328947
180
0.547331
false
false
false
false
Sherlouk/monzo-vapor
refs/heads/master
Sources/Client.swift
mit
1
import Foundation import Vapor public final class MonzoClient { let publicKey: String let privateKey: String let httpClient: Responder lazy var provider: Provider = { return Provider(client: self) }() // Leaving this code as something that should be investigated! Getting errors with Vapor though. // public convenience init(publicKey: String, privateKey: String, clientFactory: ClientFactoryProtocol) { // let responder: Responder = { // // Attempt to re-use the same client (better performance) // if let port = URI.defaultPorts["https"], // let client = try? clientFactory.makeClient(hostname: "api.monzo.com", port: port, securityLayer: .none) { // return client // } // // // Default Implementation (Will create a new client for every request) // return clientFactory // }() // // self.init(publicKey: publicKey, privateKey: privateKey, httpClient: responder) // } public init(publicKey: String, privateKey: String, httpClient: Responder) { self.publicKey = publicKey self.privateKey = privateKey self.httpClient = httpClient Monzo.setup() } /// Creates a new user with the provided access token required for authenticating all requests public func createUser(userId: String, accessToken: String, refreshToken: String?) -> User { return User(client: self, userId: userId, accessToken: accessToken, refreshToken: refreshToken) } /// Pings the Monzo API and returns true if a valid response was fired back public func ping() -> Bool { let response: String? = try? provider.request(.ping).value(forKey: "ping") return response == "pong" } /// Creates a URI to Monzo's authorisation page, you should redirect users to it in order to authorise usage of their accounts /// /// - Parameters: /// - redirectUrl: The URL that Monzo will redirect the user back to, where you should validate and obtain the access token /// - nonce: An unguessable/random string to prevent against CSRF attacks. Optional, but **recommended**! /// - Returns: The URI to redirect users to public func authorizationURI(redirectUrl: URL, nonce: String?) -> URI { var parameters: [Parameters] = [ .basic("client_id", publicKey), .basic("redirect_uri", redirectUrl.absoluteString), .basic("response_type", "code") ] if let nonce = nonce { parameters.append(.basic("state", nonce)) } let query = parameters.map({ $0.encoded(.urlQuery) }).joined(separator: "&") return URI(scheme: "https", hostname: "auth.getmondo.co.uk", query: query) } /// Validates the user has successfully authorised your client and is capable of making requests /// /// - Parameters: /// - req: The request when the user was redirected back to your server /// - nonce: The nonce used when redirecting the user to Monzo /// - Returns: On success, returns an authenticated user object for further requests public func authenticateUser(_ req: Request, nonce: String?) throws -> User { guard let code = req.query?["code"]?.string, let state = req.query?["state"]?.string else { throw MonzoAuthError.missingParameters } guard state == nonce ?? "" else { throw MonzoAuthError.conflictedNonce } var uri = req.uri uri.query = nil // Remove the query to just get the base URL for comparison let url = try uri.makeFoundationURL() let response = try provider.request(.exchangeToken(self, url, code)) let userId: String = try response.value(forKey: "user_id") let accessToken: String = try response.value(forKey: "access_token") let refreshToken: String? = try? response.value(forKey: "refresh_token") return createUser(userId: userId, accessToken: accessToken, refreshToken: refreshToken) } } final class Monzo { static func setup() { Date.incomingDateFormatters.insert(.rfc3339, at: 0) } }
4089a1f4bc2ad63b4e22f275afae11b7
44.290323
130
0.641026
false
false
false
false
gkaimakas/SwiftyFormsUI
refs/heads/master
SwiftyFormsUI/Classes/TableViews/FormTableView.swift
mit
1
// // FormTableView.swift // Pods // // Created by Γιώργος Καϊμακάς on 14/06/16. // // import Foundation import UIKit open class FormTableView: UITableView { fileprivate enum KeyboardState: Int { case visible = 0 case notVisible = 1 } fileprivate var originalBottonContentInset: CGFloat = 0 fileprivate var keyboardState: KeyboardState = .notVisible public override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) handleKeyboard() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) handleKeyboard() } open func handleKeyboard() { NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default .addObserver(self, selector: #selector(FormTableView.handleKeyboardHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func handleKeyboardShow(_ notification: Notification){ self.layoutIfNeeded() if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size { if keyboardState == .notVisible { originalBottonContentInset = self.contentInset.bottom } self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: 0 + keyboardSize.height, right: self.contentInset.right) } UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .visible }) } @objc func handleKeyboardHide(_ notification: Notification){ self.layoutIfNeeded() self.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: self.originalBottonContentInset, right: self.contentInset.right) UIView.animate(withDuration: 0.5, animations: { () -> Void in self.layoutIfNeeded() self.keyboardState = .notVisible }) } }
5bb79cb9a10d3d2b59da6e8eb2143220
27.735294
165
0.748721
false
false
false
false
firebase/firebase-ios-sdk
refs/heads/master
FirebaseStorage/Sources/StorageListResult.swift
apache-2.0
1
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /** Contains the prefixes and items returned by a `StorageReference.list()` call. */ @objc(FIRStorageListResult) open class StorageListResult: NSObject { /** * The prefixes (folders) returned by a `list()` operation. * * - Returns: A list of prefixes (folders). */ @objc public let prefixes: [StorageReference] /** * The objects (files) returned by a `list()` operation. * * - Returns: A page token if more results are available. */ @objc public let items: [StorageReference] /** * Returns a token that can be used to resume a previous `list()` operation. `nil` * indicates that there are no more results. * * - Returns: A page token if more results are available. */ @objc public let pageToken: String? // MARK: - NSObject overrides @objc override open func copy() -> Any { return StorageListResult(withPrefixes: prefixes, items: items, pageToken: pageToken) } // MARK: - Internal APIs internal convenience init(with dictionary: [String: Any], reference: StorageReference) { var prefixes = [StorageReference]() var items = [StorageReference]() let rootReference = reference.root() if let prefixEntries = dictionary["prefixes"] as? [String] { for prefixEntry in prefixEntries { var pathWithoutTrailingSlash = prefixEntry if prefixEntry.hasSuffix("/") { pathWithoutTrailingSlash = String(prefixEntry.dropLast()) } prefixes.append(rootReference.child(pathWithoutTrailingSlash)) } } if let itemEntries = dictionary["items"] as? [[String: String]] { for itemEntry in itemEntries { if let item = itemEntry["name"] { items.append(rootReference.child(item)) } } } let pageToken = dictionary["nextPageToken"] as? String self.init(withPrefixes: prefixes, items: items, pageToken: pageToken) } internal init(withPrefixes prefixes: [StorageReference], items: [StorageReference], pageToken: String?) { self.prefixes = prefixes self.items = items self.pageToken = pageToken } }
15f318e93a816a2f799959889a099c01
32.130952
90
0.664032
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/master
Tweetometer/AppDelegate.swift
mit
2
// // AppDelegate.swift // TweetsCounter // // Created by Patrick Balestra on 10/19/15. // Copyright © 2015 Patrick Balestra. All rights reserved. // import UIKit import TweetometerKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private lazy var services = AppServices(twitterSession: TwitterSession()) private lazy var appCoordinator = AppCoordinator(window: self.window!, services: services) private lazy var twitterInitializer = TwitterKitInitializer() private var initializers = [DependencyInitializer]() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) initializers = [ twitterInitializer, appCoordinator ] initializers.forEach { $0.start() } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { if let twitterInitializer = initializers.compactMap({ $0 as? TwitterKitInitializer }).first { return twitterInitializer.application(app, open:url, options: options) } return false } }
2e4f07958f4e230c2189f2ff2784cee6
34.594595
145
0.692483
false
false
false
false
krzysztofzablocki/Sourcery
refs/heads/master
SourceryTests/Generating/StencilTemplateSpec.swift
mit
1
import Quick import Nimble import PathKit import SourceryStencil #if SWIFT_PACKAGE import Foundation @testable import SourceryLib #else @testable import Sourcery #endif @testable import SourceryFramework @testable import SourceryRuntime class StencilTemplateSpec: QuickSpec { // swiftlint:disable:next function_body_length override func spec() { describe("StencilTemplate") { func generate(_ template: String) -> String { let arrayAnnotations = Variable(name: "annotated1", typeName: TypeName(name: "MyClass")) arrayAnnotations.annotations = ["Foo": ["Hello", "beautiful", "World"] as NSArray] let singleAnnotation = Variable(name: "annotated2", typeName: TypeName(name: "MyClass")) singleAnnotation.annotations = ["Foo": "HelloWorld" as NSString] return (try? Generator.generate(nil, types: Types(types: [ Class(name: "MyClass", variables: [ Variable(name: "lowerFirstLetter", typeName: TypeName(name: "myClass")), Variable(name: "upperFirstLetter", typeName: TypeName(name: "MyClass")), arrayAnnotations, singleAnnotation ]) ]), functions: [], template: StencilTemplate(templateString: template))) ?? "" } describe("json") { context("given dictionary") { let context = TemplateContext( parserResult: nil, types: Types(types: []), functions: [], arguments: ["json": ["Version": 1] as NSDictionary] ) it("renders unpretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json }}").render(context) expect(result).to(equal("{\"Version\":1}")) } it("renders pretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json:true }}").render(context) expect(result).to(equal("{\n \"Version\" : 1\n}")) } } context("given array") { let context = TemplateContext( parserResult: nil, types: Types(types: []), functions: [], arguments: ["json": ["a", "b"] as NSArray] ) it("renders unpretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json }}").render(context) expect(result).to(equal("[\"a\",\"b\"]")) } it("renders pretty json") { let result = try? StencilTemplate(templateString: "{{ argument.json | json:true }}").render(context) expect(result).to(equal("[\n \"a\",\n \"b\"\n]")) } } } describe("toArray") { context("given array") { it("doesnt modify the value") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | toArray }}{% endfor %}") expect(result).to(equal("[Hello, beautiful, World]")) } } context("given something") { it("transforms it into array") { let result = generate("{% for key,value in type.MyClass.variables.3.annotations %}{{ value | toArray }}{% endfor %}") expect(result).to(equal("[HelloWorld]")) } } } describe("count") { context("given array") { it("counts it") { let result = generate("{{ type.MyClass.allVariables | count }}") expect(result).to(equal("4")) } } } describe("isEmpty") { context("given empty array") { it("returns true") { let result = generate("{{ type.MyClass.allMethods | isEmpty }}") expect(result).to(equal("true")) } } context("given non-empty array") { it("returns false") { let result = generate("{{ type.MyClass.allVariables | isEmpty }}") expect(result).to(equal("false")) } } } describe("sorted") { context("given array") { it("sorts it") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | sorted:\"description\" }}{% endfor %}") expect(result).to(equal("[beautiful, Hello, World]")) } } } describe("sortedDescending") { context("given array") { it("sorts it descending") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | sortedDescending:\"description\" }}{% endfor %}") expect(result).to(equal("[World, Hello, beautiful]")) } } } describe("reversed") { context("given array") { it("reverses it") { let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | reversed }}{% endfor %}") expect(result).to(equal("[World, beautiful, Hello]")) } } } context("given string") { it("generates upperFirstLetter") { expect( generate("{{\"helloWorld\" | upperFirstLetter }}")).to(equal("HelloWorld")) } it("generates lowerFirstLetter") { expect(generate("{{\"HelloWorld\" | lowerFirstLetter }}")).to(equal("helloWorld")) } it("generates uppercase") { expect(generate("{{ \"HelloWorld\" | uppercase }}")).to(equal("HELLOWORLD")) } it("generates lowercase") { expect(generate("{{ \"HelloWorld\" | lowercase }}")).to(equal("helloworld")) } it("generates capitalise") { expect(generate("{{ \"helloWorld\" | capitalise }}")).to(equal("Helloworld")) } it("generates deletingLastComponent") { expect(generate("{{ \"/Path/Class.swift\" | deletingLastComponent }}")).to(equal("/Path")) } it("checks for string in name") { expect(generate("{{ \"FooBar\" | contains:\"oo\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | contains:\"xx\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !contains:\"oo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !contains:\"xx\" }}")).to(equal("true")) } it("checks for string in prefix") { expect(generate("{{ \"FooBar\" | hasPrefix:\"Foo\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | hasPrefix:\"Bar\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasPrefix:\"Foo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasPrefix:\"Bar\" }}")).to(equal("true")) } it("checks for string in suffix") { expect(generate("{{ \"FooBar\" | hasSuffix:\"Bar\" }}")).to(equal("true")) expect(generate("{{ \"FooBar\" | hasSuffix:\"Foo\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasSuffix:\"Bar\" }}")).to(equal("false")) expect(generate("{{ \"FooBar\" | !hasSuffix:\"Foo\" }}")).to(equal("true")) } it("removes instances of a substring") { expect(generate("{{\"helloWorld\" | replace:\"he\",\"bo\" | replace:\"llo\",\"la\" }}")).to(equal("bolaWorld")) expect(generate("{{\"helloWorldhelloWorld\" | replace:\"hello\",\"hola\" }}")).to(equal("holaWorldholaWorld")) expect(generate("{{\"helloWorld\" | replace:\"hello\",\"\" }}")).to(equal("World")) expect(generate("{{\"helloWorld\" | replace:\"foo\",\"bar\" }}")).to(equal("helloWorld")) } } context("given TypeName") { it("generates upperFirstLetter") { expect(generate("{{ type.MyClass.variables.0.typeName }}")).to(equal("myClass")) } it("generates upperFirstLetter") { expect(generate("{{ type.MyClass.variables.0.typeName | upperFirstLetter }}")).to(equal("MyClass")) } it("generates lowerFirstLetter") { expect(generate("{{ type.MyClass.variables.1.typeName | lowerFirstLetter }}")).to(equal("myClass")) } it("generates uppercase") { expect(generate("{{ type.MyClass.variables.0.typeName | uppercase }}")).to(equal("MYCLASS")) } it("generates lowercase") { expect(generate("{{ type.MyClass.variables.1.typeName | lowercase }}")).to(equal("myclass")) } it("generates capitalise") { expect(generate("{{ type.MyClass.variables.1.typeName | capitalise }}")).to(equal("Myclass")) } it("checks for string in name") { expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"my\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"xx\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"my\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"xx\" }}")).to(equal("true")) } it("checks for string in prefix") { expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"my\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"My\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"my\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"My\" }}")).to(equal("true")) } it("checks for string in suffix") { expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"Class\" }}")).to(equal("true")) expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"class\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"Class\" }}")).to(equal("false")) expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"class\" }}")).to(equal("true")) } it("removes instances of a substring") { expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"My\" | replace:\"Class\",\"Struct\" }}")).to(equal("MyStruct")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"s\",\"z\" }}")).to(equal("myClazz")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"\" }}")).to(equal("Class")) expect(generate("{{type.MyClass.variables.0.typeName | replace:\"foo\",\"bar\" }}")).to(equal("myClass")) } } it("rethrows template parsing errors") { expect { try Generator.generate(nil, types: Types(types: []), functions: [], template: StencilTemplate(templateString: "{% tag %}")) } .to(throwError(closure: { (error) in expect("\(error)").to(equal(": Unknown template tag 'tag'")) })) } it("includes partial templates") { var outputDir = Path("/tmp") outputDir = Stubs.cleanTemporarySourceryDir() let templatePath = Stubs.templateDirectory + Path("Include.stencil") let expectedResult = "// Generated using Sourcery Major.Minor.Patch — https://github.com/krzysztofzablocki/Sourcery\n" + "// DO NOT EDIT\n" + "partial template content\n" expect { try Sourcery(cacheDisabled: true).processFiles(.sources(Paths(include: [Stubs.sourceDirectory])), usingTemplates: Paths(include: [templatePath]), output: Output(outputDir)) }.toNot(throwError()) let result = (try? (outputDir + Sourcery().generatedPath(for: templatePath)).read(.utf8)) expect(result).to(equal(expectedResult)) } } } }
d8f257d346b9987a2eedbd9ba157bf50
48.738182
219
0.47931
false
false
false
false
Azero123/JW-Broadcasting
refs/heads/master
JW Broadcasting/SuperMediaHandler.swift
mit
1
// // test.swift // JW Broadcasting // // Created by Austin Zelenka on 12/21/15. // Copyright © 2015 xquared. All rights reserved. // import UIKit import AVKit class SuperMediaPlayer: NSObject, UIGestureRecognizerDelegate { let playerViewController = AVPlayerViewController() let player=AVQueuePlayer() var statusObserver=false var dismissWhenFinished=true var nextDictionary:NSDictionary?=nil var finishedPlaying:()->Void = { () -> Void in } override init() { super.init() playerViewController.player=player player.addPeriodicTimeObserverForInterval(CMTime(value: 1, timescale: 1), queue: nil, usingBlock: { (time:CMTime) in let playerAsset:AVAsset? = self.player.currentItem != nil ? self.player.currentItem!.asset : nil if (playerAsset != nil && playerAsset!.isKindOfClass(AVURLAsset.self)){ if (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") == nil){ NSUserDefaults.standardUserDefaults().setObject(NSDictionary(), forKey: "saved-media-states") } //NSUserDefaults.standardUserDefaults().setObject(NSDictionary(), forKey: "saved-media-states") let updatedDictionary:NSMutableDictionary=(NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).mutableCopy() as! NSMutableDictionary let seconds=Float(CMTimeGetSeconds(self.player.currentTime())) if (seconds>60*5 && Float(CMTimeGetSeconds(playerAsset!.duration))*Float(0.95)>seconds && CMTimeGetSeconds(playerAsset!.duration)>60*10){ updatedDictionary.setObject(NSNumber(float: seconds), forKey: (playerAsset as! AVURLAsset).URL.path!) NSUserDefaults.standardUserDefaults().setObject(updatedDictionary, forKey: "saved-media-states") } else { updatedDictionary.removeObjectForKey((playerAsset as! AVURLAsset).URL.path!) NSUserDefaults.standardUserDefaults().setObject(updatedDictionary, forKey: "saved-media-states") } } }) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceivePress press: UIPress) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func updatePlayerUsingDictionary(dictionary:NSDictionary){ updatePlayerUsingString( unfold(dictionary, instructions: ["files","last","progressiveDownloadURL"]) as! String) updateMetaDataUsingDictionary(dictionary) } func updatePlayerUsingString(url:String){ updatePlayerUsingURL(NSURL(string: url)!) } func updatePlayerUsingURL(url:NSURL){ let newItem=AVPlayerItem(URL: url) NSNotificationCenter.defaultCenter().removeObserver(self) if (self.player.currentItem != nil){ NSNotificationCenter.defaultCenter().removeObserver(self) NSNotificationCenter.defaultCenter().removeObserver(self.player.currentItem!) //print("replace item \(self.player.currentItem?.observationInfo)") if ("\(self.player.currentItem!.observationInfo)".containsString("(")){ print("still here!") self.player.currentItem!.removeObserver(self, forKeyPath: "status") } print("replace item \(self.player.currentItem!.observationInfo)") } player.removeAllItems() player.insertItem(newItem, afterItem: nil) //player.replaceCurrentItemWithPlayerItem(nil) statusObserver=true //NSNotificationCenter.defaultCenter().addObserver(self, selector: "statusChanged", name: "status", object: newItem) newItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.Prior, context: nil) //newItem.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.Prior, context: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: newItem) } func playerItemDidReachEnd(notification:NSNotification){ print("did reach end \(notification.object) \(notification.object?.observationInfo!)") if ((notification.object?.isKindOfClass(AVPlayerItem)) == true){ if (statusObserver){ print("status observer") notification.object?.removeObserver(self, forKeyPath: "status") } while ("\(notification.object!.observationInfo)".containsString("(")){ print("still here!") notification.object?.removeObserver(self, forKeyPath: "status") } statusObserver=false //NSNotificationCenter.removeObserver(self, forKeyPath: AVPlayerItemDidPlayToEndTimeNotification) //notification.object?.removeObserver(self, forKeyPath: AVPlayerItemDidPlayToEndTimeNotification) if (nextDictionary != nil){ print("but we have more!") self.updatePlayerUsingDictionary(self.nextDictionary!) } else if (dismissWhenFinished){ playerViewController.dismissViewControllerAnimated(true, completion: nil) } } finishedPlaying() } func updateMetaDataUsingDictionary(dictionary:NSDictionary){ fetchDataUsingCache(base+"/"+version+"/categories/"+languageCode+"/\(unfold(dictionary, instructions: ["primaryCategory"])!)?detailed=1", downloaded: { dispatch_async(dispatch_get_main_queue()) { self.updateMetaDataItem(AVMetadataiTunesMetadataKeyGenreID, keySpace: AVMetadataKeySpaceiTunes, value: "\(unfold(base+"/"+version+"/categories/"+languageCode+"/\(unfold(dictionary, instructions: ["primaryCategory"])!)?detailed=1|category|name")!)") } }) var itunesMetaData:Dictionary<String,protocol<NSCopying,NSObjectProtocol>>=[:] itunesMetaData[AVMetadataiTunesMetadataKeySongName]=unfold(dictionary, instructions: ["title"]) as? String //itunesMetaData[AVMetadataiTunesMetadataKeyContentRating]="G" itunesMetaData[AVMetadataiTunesMetadataKeyDescription]="\nPublished by Watchtower Bible and Tract Society of New York, Inc.\n© 2016 Watch Tower Bible and Tract Society of Pennsylvania. All rights reserved." //unfold("\(latestVideosPath)|category|media|\(indexPath.row)|description") as? String itunesMetaData[AVMetadataiTunesMetadataKeyCopyright]="Copyright © 2016 Watch Tower Bible and Tract Society of Pennsylvania" itunesMetaData[AVMetadataiTunesMetadataKeyPublisher]="Watchtower Bible and Tract Society of New York, Inc." let imageURL=unfold(dictionary, instructions: ["images",["lsr","sqr","sqs","cvr",""],["sm","md","lg","xs",""]]) as? String if (imageURL != nil){ let image=UIImagePNGRepresentation(imageUsingCache(imageURL!)!) if (image != nil){ itunesMetaData[AVMetadataiTunesMetadataKeyCoverArt]=NSData(data: image!) } } //unfold(dictionary, instructions: ["title","images","lsr","md"]) for key in NSDictionary(dictionary: itunesMetaData).allKeys { updateMetaDataItem(key as! String, keySpace: AVMetadataKeySpaceiTunes, value: itunesMetaData[key as! String]!) } nextDictionary=dictionary } func updateMetaDataItem(key:String, keySpace:String, value:protocol<NSCopying,NSObjectProtocol>){ if (player.currentItem == nil){ print("player not ready!") return } let metadataItem = AVMutableMetadataItem() metadataItem.locale = NSLocale.currentLocale() metadataItem.key = key metadataItem.keySpace = keySpace metadataItem.value = value player.currentItem!.externalMetadata.append(metadataItem) } func play(){ /* If return to within 30 Seconds than prompt for resume Had to be 5 min in or more Had to be less than 95 % through Video has to be longer than 10 minutes */ playIn(UIApplication.sharedApplication().keyWindow!.rootViewController!) } func playIn(presenter:UIViewController){ let playerAsset = self.player.currentItem!.asset if (playerAsset.isKindOfClass(AVURLAsset.self)){ let urlPath=(playerAsset as! AVURLAsset).URL.path! if (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") != nil && (NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).objectForKey(urlPath) != nil){ var seekPoint = CMTimeMake(0, 0) let seconds=(NSUserDefaults.standardUserDefaults().objectForKey("saved-media-states") as! NSDictionary).objectForKey(urlPath) as! NSNumber seekPoint=CMTimeMake(Int64(seconds.floatValue), 1) let fromBeginningText=unfold(base+"/"+version+"/translations/"+languageCode+"|translations|\(languageCode)|btnPlayFromBeginning") as? String let resumeText=unfold(base+"/"+version+"/translations/"+languageCode+"|translations|\(languageCode)|btnResume") as? String let alert=UIAlertController(title: "", message: "", preferredStyle: .Alert) alert.view.tintColor = UIColor.greenColor() alert.addAction(UIAlertAction(title: nil, style: .Cancel , handler: nil)) let action=UIAlertAction(title: resumeText, style: .Default, handler: { (action:UIAlertAction) in self.playerViewController.player?.seekToTime(seekPoint) if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } }) alert.addAction(action) alert.addAction(UIAlertAction(title: fromBeginningText, style: .Default, handler: { (action:UIAlertAction) in if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } })) presenter.presentViewController(alert, animated: true, completion: nil) } if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } } else { if (self.player.currentItem == nil && self.nextDictionary != nil){ self.updatePlayerUsingDictionary(self.nextDictionary!) } presenter.presentViewController(self.playerViewController, animated: true) { self.playerViewController.player!.play() } } } func exitPlayer(){ } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { print("OBSERVER IS PRESENT FRINGE TEAM LOOK OUT!") if (object != nil && object?.isKindOfClass(AVPlayerItem.self)==true && (object as! AVPlayerItem) == player.currentItem && keyPath! == "status"){ object?.removeObserver(self, forKeyPath: "status") statusObserver=false //https://www.jw.org/apps/E_RSSMEDIAMAG?rln=E&rmn=wp&rfm=m4b if (player.status == .ReadyToPlay){ var isAudio = false for track in (player.currentItem!.tracks) { if (track.assetTrack.mediaType == AVMediaTypeAudio){ isAudio=true } if (track.assetTrack.mediaType == AVMediaTypeVideo){ isAudio=false break } } if (isAudio){ if (nextDictionary != nil && playerViewController.contentOverlayView != nil){ fillEmptyVideoSpaceWithDictionary(nextDictionary!) self.nextDictionary=nil } } else { self.nextDictionary=nil } } } } func fillEmptyVideoSpaceWithDictionary(dictionary:NSDictionary){ let imageURL=unfold(dictionary, instructions: ["images",["sqr","sqs","cvr",""],["lg","sm","md","xs",""]]) as? String for subview in (self.playerViewController.contentOverlayView?.subviews)! { subview.removeFromSuperview() } var image:UIImage?=nil let imageView=UIImageView() let backgroundImage=UIImageView() if ((unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "KingdomMelodies"){ image = UIImage(named: "kingdommelodies.png") //imageView.image=image //backgroundImage.image=image } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { if (image == nil){ image=imageUsingCache(imageURL!) } dispatch_async(dispatch_get_main_queue()) { imageView.image=image imageView.frame=CGRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height) backgroundImage.image=image imageView.center=CGPoint(x: (self.playerViewController.contentOverlayView?.frame.size.width)!/2, y: 705-imageView.frame.size.height/2-150) var title=unfold(dictionary, instructions: ["title"]) as? String let extraction=titleExtractor(title!) var visualSongNumber:Int?=nil if ((title?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))>3){ visualSongNumber=Int(title!.substringToIndex(title!.startIndex.advancedBy(3))) } title=extraction["correctedTitle"] let scripturesLabel=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) scripturesLabel.center=CGPoint(x: imageView.center.x, y: 845) scripturesLabel.textAlignment = .Center scripturesLabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) scripturesLabel.text=extraction["parentheses"] self.playerViewController.contentOverlayView?.addSubview(scripturesLabel) let label=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) if (languageCode == "E" && ((unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "Piano" || (unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "Vocal" || (unfold(dictionary, instructions: ["primaryCategory"]) as! String) == "NewSongs")){ label.text="Song \(visualSongNumber!): \(title!)" } else { label.text=(title!) } //imageView.center.y+imageView.frame.size.height/2+90 label.center=CGPoint(x: imageView.center.x, y: 700) label.textAlignment = .Center label.font=UIFont.preferredFontForTextStyle(UIFontTextStyleTitle2) label.clipsToBounds=false //title 3 self.playerViewController.contentOverlayView?.addSubview(label) let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" var albumTitle="" let albumKey=unfold(dictionary, instructions: ["primaryCategory"]) as! String let albums=unfold("\(AudioDataURL)|category|subcategories") as! NSArray for album in albums { if (album["key"] as! String == albumKey){ albumTitle=album["name"] as! String } } //let albumTitle=unfold("\(AudioDataURL)|category|subcategories|\(self.categoryIndex)|name") as! String let Albumlabel=UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) Albumlabel.text=categoryTitleCorrection(albumTitle) Albumlabel.center=CGPoint(x: imageView.center.x, y: 775) Albumlabel.textAlignment = .Center Albumlabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) Albumlabel.clipsToBounds=false Albumlabel.textColor=UIColor.darkGrayColor() //title 3 self.playerViewController.contentOverlayView?.addSubview(Albumlabel) } } self.playerViewController.view.backgroundColor=UIColor.clearColor() self.playerViewController.contentOverlayView?.backgroundColor=UIColor.clearColor() let subviews=NSMutableArray(array: (self.playerViewController.view.subviews)) while subviews.count>0{ let subview=subviews.firstObject as! UIView subviews.addObjectsFromArray(subview.subviews) subview.backgroundColor=UIColor.clearColor() subviews.removeObjectAtIndex(0) } imageView.layer.shadowColor=UIColor.blackColor().CGColor imageView.layer.shadowOpacity=0.5 imageView.layer.shadowRadius=20 backgroundImage.frame=(self.playerViewController.contentOverlayView?.bounds)! self.playerViewController.contentOverlayView?.addSubview(backgroundImage) let backgroundEffect=UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) backgroundEffect.frame=(self.playerViewController.contentOverlayView?.bounds)! self.playerViewController.contentOverlayView?.addSubview(backgroundEffect) self.playerViewController.contentOverlayView?.addSubview(imageView) } }
22cd3789fdf70b69d6a4c3231c4bdc48
46.367299
289
0.601011
false
false
false
false
LiulietLee/BilibiliCD
refs/heads/master
BCD/ViewController/ImageViewController.swift
gpl-3.0
1
// // ImageViewController.swift // BCD // // Created by Liuliet.Lee on 17/6/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit import ViewAnimator import MobileCoreServices import MaterialKit import LLDialog class ImageViewController: UIViewController, Waifu2xDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! { didSet { imageView?.accessibilityIgnoresInvertColors = true } } @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var urlLabel: UILabel! @IBOutlet weak var downloadButton: UIBarButtonItem! @IBOutlet weak var pushButton: UIButton! /// Should be disabled for GIF. @IBOutlet weak var scaleButton: UIBarButtonItem! @IBOutlet weak var separator: UIProgressView! @IBOutlet weak var citationStyleControl: UISegmentedControl! @IBOutlet weak var citationTextView: UITextView! @IBOutlet weak var copyButton: UIButton! @IBOutlet var labels: [UILabel]! private let coverInfoProvider = CoverInfoProvider() private let assetProvider = AssetProvider() var cover: BilibiliCover? var itemFromHistory: History? private let manager = HistoryManager() private var loadingView: LoadingView? private var reference: (info: Info?, style: CitationStyle) = (nil, .apa) { didSet { guard let info = reference.info else { return } citationTextView?.attributedText = info.citation(ofStyle: reference.style) titleLabel?.text = info.title authorLabel?.text = "UP主:\(info.author)" urlLabel.text = "URL:\(info.imageURL)" } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isShowingImage = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver( self, selector: #selector(goBackIfNeeded), name: UIApplication.willResignActiveNotification, object: nil ) } @objc private func goBackIfNeeded() { if itemFromHistory?.isHidden == true { navigationController?.popToRootViewController(animated: false) } } override func viewDidLoad() { super.viewDidLoad() isShowingImage = true if let cover = cover { title = cover.shortDescription if itemFromHistory == nil { coverInfoProvider.getCoverInfoBy(cover: cover) { info in DispatchQueue.main.async { [weak self] in if let info = info { self?.updateUIFrom(info: info) } else { self?.cannotFindVideo() } } } } } else { title = NSLocalizedString( "COVER NOT FOUND", value: "开发者把封面弄丢了", comment: "Indicate cover is not there because developer made a mistkae" ) } if let item = itemFromHistory { reference.info = Info( stringID: item.av!, author: item.up!, title: item.title!, imageURL: item.url! ) if item.origin == nil { updateUIFrom(info: reference.info!) } imageView.image = item.uiImage changeTextColor(to: item.isHidden ? .black : .tianyiBlue) animateView() } else { changeTextColor(to: .bilibiliPink) titleLabel.text = "" authorLabel.text = "" urlLabel.text = "" disableButtons() loadingView = LoadingView(frame: view.bounds) view.addSubview(loadingView!) view.bringSubviewToFront(loadingView!) } } private func animateView() { let type = AnimationType.from(direction: .right, offset: ViewAnimatorConfig.offset) scrollView.doAnimation(type: type) } private func changeTextColor(to color: UIColor) { var labelColor = color if #available(iOS 13.0, *), labelColor == UIColor.black { labelColor = .label } labels?.forEach { $0.textColor = labelColor } citationStyleControl?.tintColor = labelColor separator?.progressTintColor = labelColor copyButton?.tintColor = labelColor navigationController?.navigationBar.barTintColor = color } @IBAction func downloadButtonTapped(_ sender: UIBarButtonItem) { saveImage() } @IBAction func titleButtonTapped() { if let cover = cover { UIApplication.shared.open(cover.url) } } @objc private func saveImage() { let image: Image guard let item = itemFromHistory , let url = item.url , let uiImage = imageView?.image , let data = imageView.image?.data() else { return imageSaved(successfully: false, error: nil) } if url.isGIF { image = .gif(uiImage, data: data) } else { image = .normal(uiImage) } ImageSaver.saveImage(image, completionHandler: imageSaved, alternateHandler: #selector(imageSavingFinished(_:didFinishSavingWithError:contextInfo:))) } @objc func imageSavingFinished(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { imageSaved(successfully: error == nil, error: error) } private func imageSaved(successfully: Bool, error: Error?) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } if !successfully || error != nil { LLDialog() .set(title: "啊叻?!") .set(message: "保存出错了Σ(  ̄□ ̄||)") .setNegativeButton(withTitle: "好吧") .setPositiveButton(withTitle: "再试一次", target: self, action: #selector(self.saveImage)) .show() print(error ?? "Unknown error") } else { LLDialog() .set(title: "保存成功!") .set(message: "封面被成功保存(〜 ̄△ ̄)〜") .setPositiveButton(withTitle: "OK") .show() } } } private func enableButtons() { downloadButton.isEnabled = true scaleButton.isEnabled = !reference.info!.imageURL.isGIF pushButton.isEnabled = true } private func disableButtons() { downloadButton.isEnabled = false scaleButton.isEnabled = false pushButton.isEnabled = false } private func updateUIFrom(info: Info) { reference.info = info assetProvider.getImage(fromUrlPath: info.imageURL) { img in if let image = img { DispatchQueue.main.async { [weak self] in self?.imageView.image = image.uiImage switch image { case .gif: self?.scaleButton.isEnabled = false case .normal: self?.scaleButton.isEnabled = true } self?.enableButtons() self?.loadingView?.dismiss() self?.animateView() self?.addItemToDB(image: image) } } else { DispatchQueue.main.async { [weak self] in self?.cannotFindVideo() } } } } func scaleSucceed(scaledImage: UIImage) { imageView.image = scaledImage manager.replaceOriginCover(of: itemFromHistory!, with: scaledImage) scaleButton.isEnabled = false LLDialog() .set(title: "(。・ω・。)") .set(message: "放大完成~") .setPositiveButton(withTitle: "嗯") .show() } private func addItemToDB(image: Image) { DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + .milliseconds(500)) { [info = reference.info!, id = cover!.shortDescription] in self.itemFromHistory = self.manager.addNewHistory( av: id, image: image, title: info.title, up: info.author, url: info.imageURL ) } } private func cannotFindVideo() { titleLabel.text = "啊叻?" authorLabel.text = "视频不见了?" urlLabel.text = "" loadingView?.dismiss() imageView.image = #imageLiteral(resourceName: "novideo_image") } @IBAction func changeCitationFormat(_ sender: UISegmentedControl) { reference.style = CitationStyle(rawValue: sender.selectedSegmentIndex)! } lazy var generator: UINotificationFeedbackGenerator = .init() @IBAction func copyToPasteBoard() { copyButton.resignFirstResponder() do { guard let citation = citationTextView.attributedText else { throw NSError() } let range = NSRange(location: 0, length: citation.length) let rtf = try citation.data(from: range, documentAttributes: [.documentType : NSAttributedString.DocumentType.rtf]) UIPasteboard.general.items = [ [ kUTTypeRTF as String: String(data: rtf, encoding: .utf8)!, kUTTypeUTF8PlainText as String: citation.string ] ] generator.notificationOccurred(.success) display("已复制到剪贴板") } catch { generator.notificationOccurred(.error) display(error) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem if let vc = segue.destination as? DetailViewController { vc.image = imageView.image vc.isHidden = itemFromHistory?.isHidden } else if let vc = segue.destination as? Waifu2xViewController { vc.originImage = imageView.image vc.delegate = self } } }
6af3a31615c8540f952c532f6591e21c
33.703333
157
0.571319
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Swift/Classes/Model/ImageFilter.swift
mit
1
// // ImageFilter.swift // Example // // Created by Slience on 2022/2/18. // #if canImport(GPUImage) import UIKit import VideoToolbox import HXPHPicker import GPUImage struct FilterTools { static func filters() -> [CameraFilter] { [ BeautifyFilter(), InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] } } class BeautifyFilter: CameraFilter { var filterName: String { return "美白" } var filter: GPUImageBeautifyFilter? func prepare(_ size: CGSize) { filter = GPUImageBeautifyFilter(degree: 0.6) } func render(_ pixelBuffer: CVPixelBuffer) -> CIImage? { var cgImage: CGImage? VTCreateCGImageFromCVPixelBuffer(pixelBuffer, options: nil, imageOut: &cgImage) guard let cgImage = cgImage, let bilateralFilter = filter else { return nil } let picture = GPUImagePicture(cgImage: cgImage) picture?.addTarget(bilateralFilter) bilateralFilter.useNextFrameForImageCapture() picture?.processImage() let result = bilateralFilter.newCGImageFromCurrentlyProcessedOutput().takeRetainedValue() return .init(cgImage: result) } func reset() { filter = nil } } #endif
778e4f011b592caba2cfbadfcf312ac1
24.211538
99
0.631579
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/ChatModule/Chat/ViewController/JCGroupSettingViewController.swift
mit
1
// // JCGroupSettingViewController.swift // JChat // // Created by JIGUANG on 2017/4/27. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import JMessage class JCGroupSettingViewController: UIViewController, CustomNavigation { var group: JMSGGroup! override func viewDidLoad() { super.viewDidLoad() _init() } deinit { NotificationCenter.default.removeObserver(self) } private var tableView: UITableView = UITableView(frame: .zero, style: .grouped) fileprivate var memberCount = 0 fileprivate lazy var users: [JMSGUser] = [] fileprivate var isMyGroup = false fileprivate var isNeedUpdate = false //MARK: - private func private func _init() { self.title = "群组信息" view.backgroundColor = .white users = group.memberArray() memberCount = users.count let user = JMSGUser.myInfo() // && group.ownerAppKey == user.appKey! 这里group.ownerAppKey == "" 目测sdk bug if group.owner == user.username { isMyGroup = true } tableView.separatorStyle = .none tableView.delegate = self tableView.dataSource = self tableView.sectionIndexColor = UIColor(netHex: 0x2dd0cf) tableView.sectionIndexBackgroundColor = .clear tableView.register(JCButtonCell.self, forCellReuseIdentifier: "JCButtonCell") tableView.register(JCMineInfoCell.self, forCellReuseIdentifier: "JCMineInfoCell") tableView.register(GroupAvatorCell.self, forCellReuseIdentifier: "GroupAvatorCell") tableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height) view.addSubview(tableView) customLeftBarButton(delegate: self) JMSGGroup.groupInfo(withGroupId: group.gid) { (result, error) in if error == nil { guard let group = result as? JMSGGroup else { return } self.group = group self.isNeedUpdate = true self._updateGroupInfo() } } NotificationCenter.default.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil) } @objc func _updateGroupInfo() { if !isNeedUpdate { let conv = JMSGConversation.groupConversation(withGroupId: group.gid) group = conv?.target as! JMSGGroup } if group.memberArray().count != memberCount { isNeedUpdate = true memberCount = group.memberArray().count } users = group.memberArray() memberCount = users.count tableView.reloadData() } } extension JCGroupSettingViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 4 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 3 case 2: // return 5 return 4 case 3: return 1 default: return 0 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: if isMyGroup { if memberCount > 13 { return 314 } if memberCount > 8 { return 260 } if memberCount > 3 { return 200 } return 100 } else { if memberCount > 14 { return 314 } if memberCount > 9 { return 260 } if memberCount > 4 { return 200 } return 100 } case 1: return 45 case 2: return 40 default: return 45 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.0001 } return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { var cell = tableView.dequeueReusableCell(withIdentifier: "JCGroupSettingCell") as? JCGroupSettingCell if isNeedUpdate { cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group) isNeedUpdate = false } if cell == nil { cell = JCGroupSettingCell(style: .default, reuseIdentifier: "JCGroupSettingCell", group: self.group) } return cell! } if indexPath.section == 3 { return tableView.dequeueReusableCell(withIdentifier: "JCButtonCell", for: indexPath) } if indexPath.section == 1 && indexPath.row == 0 { return tableView.dequeueReusableCell(withIdentifier: "GroupAvatorCell", for: indexPath) } return tableView.dequeueReusableCell(withIdentifier: "JCMineInfoCell", for: indexPath) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.selectionStyle = .none if indexPath.section == 3 { guard let cell = cell as? JCButtonCell else { return } cell.buttonColor = UIColor(netHex: 0xEB424D) cell.buttonTitle = "退出此群" cell.delegate = self return } cell.accessoryType = .disclosureIndicator if indexPath.section == 0 { guard let cell = cell as? JCGroupSettingCell else { return } cell.bindData(self.group) cell.delegate = self cell.accessoryType = .none return } if let cell = cell as? GroupAvatorCell { cell.title = "群头像" cell.bindData(group) } guard let cell = cell as? JCMineInfoCell else { return } if indexPath.section == 2 { if indexPath.row == 1 { cell.delegate = self cell.indexPate = indexPath cell.accessoryType = .none cell.isSwitchOn = group.isNoDisturb cell.isShowSwitch = true } if indexPath.row == 2 { cell.delegate = self cell.indexPate = indexPath cell.accessoryType = .none cell.isSwitchOn = group.isShieldMessage cell.isShowSwitch = true } } if indexPath.section == 1 { let conv = JMSGConversation.groupConversation(withGroupId: self.group.gid) let group = conv?.target as! JMSGGroup switch indexPath.row { case 1: cell.title = "群聊名称" cell.detail = group.displayName() case 2: cell.title = "群描述" cell.detail = group.desc default: break } } else { switch indexPath.row { case 0: cell.title = "聊天文件" case 1: cell.title = "消息免打扰" case 2: cell.title = "消息屏蔽" // case 2: // cell.title = "清理缓存" case 3: cell.title = "清空聊天记录" default: break } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 1 { switch indexPath.row { case 0: let vc = GroupAvatorViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) case 1: let vc = JCGroupNameViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) case 2: let vc = JCGroupDescViewController() vc.group = group navigationController?.pushViewController(vc, animated: true) default: break } } if indexPath.section == 2 { switch indexPath.row { // case 2: // let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清理缓存") // actionSheet.tag = 1001 // actionSheet.show(in: self.view) case 0: let vc = FileManagerViewController() let conv = JMSGConversation.groupConversation(withGroupId: group.gid) vc.conversation = conv navigationController?.pushViewController(vc, animated: true) case 3: let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "清空聊天记录") actionSheet.tag = 1001 actionSheet.show(in: self.view) default: break } } } } extension JCGroupSettingViewController: UIAlertViewDelegate { func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { switch buttonIndex { case 1: MBProgressHUD_JChat.showMessage(message: "退出中...", toView: self.view) group.exit({ (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error == nil { self.navigationController?.popToRootViewController(animated: true) } else { MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) default: break } } } extension JCGroupSettingViewController: JCMineInfoCellDelegate { func mineInfoCell(clickSwitchButton button: UISwitch, indexPath: IndexPath?) { if indexPath != nil { switch (indexPath?.row)! { case 1: if group.isNoDisturb == button.isOn { return } // 消息免打扰 group.setIsNoDisturb(button.isOn, handler: { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error != nil { button.isOn = !button.isOn MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) case 2: if group.isShieldMessage == button.isOn { return } // 消息屏蔽 group.setIsShield(button.isOn, handler: { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error != nil { button.isOn = !button.isOn MBProgressHUD_JChat.show(text: "\(String.errorAlert(error! as NSError))", view: self.view) } }) default: break } } } } extension JCGroupSettingViewController: JCButtonCellDelegate { func buttonCell(clickButton button: UIButton) { let alertView = UIAlertView(title: "退出此群", message: "确定要退出此群?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定") alertView.show() } } extension JCGroupSettingViewController: JCGroupSettingCellDelegate { func clickMoreButton(clickButton button: UIButton) { let vc = JCGroupMembersViewController() vc.group = self.group self.navigationController?.pushViewController(vc, animated: true) } func clickAddCell(cell: JCGroupSettingCell) { let vc = JCUpdateMemberViewController() vc.group = group self.navigationController?.pushViewController(vc, animated: true) } func clickRemoveCell(cell: JCGroupSettingCell) { let vc = JCRemoveMemberViewController() vc.group = group self.navigationController?.pushViewController(vc, animated: true) } func didSelectCell(cell: JCGroupSettingCell, indexPath: IndexPath) { let index = indexPath.section * 5 + indexPath.row let user = users[index] if user.isEqual(to: JMSGUser.myInfo()) { navigationController?.pushViewController(JCMyInfoViewController(), animated: true) return } let vc = JCUserInfoViewController() vc.user = user navigationController?.pushViewController(vc, animated: true) } } extension JCGroupSettingViewController: UIActionSheetDelegate { func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) { // if actionSheet.tag == 1001 { // // SDK 暂无该功能 // } if actionSheet.tag == 1001 { if buttonIndex == 1 { let conv = JMSGConversation.groupConversation(withGroupId: group.gid) conv?.deleteAllMessages() NotificationCenter.default.post(name: Notification.Name(rawValue: kDeleteAllMessage), object: nil) MBProgressHUD_JChat.show(text: "成功清空", view: self.view) } } } } extension JCGroupSettingViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return true } }
2a88ff5a577b2b593870c8290601cc36
33.570388
159
0.550165
false
false
false
false
shuuchen/Swift-Down-Video
refs/heads/master
source/VideoCollectionViewLayout.swift
mit
1
// // VideoCollectionViewLayout.swift // table_template // // Created by Shuchen Du on 2015/10/12. // Copyright (c) 2015年 Shuchen Du. All rights reserved. // import UIKit protocol PinterestLayoutDelegate { // 1 func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath, withWidth:CGFloat) -> CGFloat // 2 func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat } class VideoCollectionViewLayout: UICollectionViewLayout { // 1 var delegate: PinterestLayoutDelegate! // 2 var numberOfColumns = 2 var cellPadding: CGFloat = 6.0 // 3 private var cache = [UICollectionViewLayoutAttributes]() // 4 private var contentHeight: CGFloat = 0.0 private var contentWidth: CGFloat { let insets = collectionView!.contentInset return CGRectGetWidth(collectionView!.bounds) - (insets.left + insets.right) } }
760af1a5e3c16544079213f183ca682e
26.5
99
0.702392
false
false
false
false
stripe/stripe-ios
refs/heads/master
Tests/Tests/MKPlacemark+PaymentSheetTests.swift
mit
1
// // MKPlacemark+PaymentSheetTests.swift // StripeiOS Tests // // Created by Nick Porter on 6/13/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import Contacts import MapKit import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class MKPlacemark_PaymentSheetTests: XCTestCase { // All address dictionaries are based on an actual placemark of an `MKLocalSearchCompletion` func testAsAddress_UnitedStates() { // Search string used to generate address dictionary: "4 Pennsylvania Pl" let addressDictionary = [ CNPostalAddressStreetKey: "4 Pennsylvania Plaza", CNPostalAddressStateKey: "NY", CNPostalAddressCountryKey: "United States", CNPostalAddressISOCountryCodeKey: "US", CNPostalAddressCityKey: "New York", "SubThoroughfare": "4", CNPostalAddressPostalCodeKey: "10001", "Thoroughfare": "Pennsylvania Plaza", CNPostalAddressSubLocalityKey: "Manhattan", CNPostalAddressSubAdministrativeAreaKey: "New York County", "Name": "4 Pennsylvania Plaza", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "New York", country: "US", line1: "4 Pennsylvania Plaza", line2: nil, postalCode: "10001", state: "NY" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Canada() { // Search string used to generate address dictionary: "40 Bay St To" let addressDictionary = [ CNPostalAddressStreetKey: "40 Bay St", CNPostalAddressStateKey: "ON", CNPostalAddressISOCountryCodeKey: "CA", CNPostalAddressCountryKey: "Canada", CNPostalAddressCityKey: "Toronto", "SubThoroughfare": "40", CNPostalAddressPostalCodeKey: "M5J 2X2", "Thoroughfare": "Bay St", CNPostalAddressSubLocalityKey: "Downtown Toronto", CNPostalAddressSubAdministrativeAreaKey: "SubAdministrativeArea", "Name": "40 Bay St", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Toronto", country: "CA", line1: "40 Bay St", line2: nil, postalCode: "M5J 2X2", state: "ON" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Germany() { // Search string used to generate address dictionary: "Rüsternallee 14" let addressDictionary = [ CNPostalAddressStreetKey: "Rüsternallee 14", CNPostalAddressISOCountryCodeKey: "DE", CNPostalAddressCountryKey: "Germany", CNPostalAddressCityKey: "Berlin", CNPostalAddressPostalCodeKey: "14050", "SubThoroughfare": "14", "Thoroughfare": "Rüsternallee", CNPostalAddressSubLocalityKey: "Charlottenburg-Wilmersdorf", CNPostalAddressSubAdministrativeAreaKey: "Berlin", "Name": "Rüsternallee 14", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Berlin", country: "DE", line1: "Rüsternallee 14", line2: nil, postalCode: "14050", state: nil ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Brazil() { // Search string used to generate address dictionary: "Avenida Paulista 500" let addressDictionary = [ CNPostalAddressStreetKey: "Avenida Paulista, 500", CNPostalAddressStateKey: "SP", CNPostalAddressISOCountryCodeKey: "BR", CNPostalAddressCountryKey: "Brazil", CNPostalAddressCityKey: "Paulínia", "SubThoroughfare": "500", CNPostalAddressPostalCodeKey: "13145-089", "Thoroughfare": "Avenida Paulista", CNPostalAddressSubLocalityKey: "Jardim Planalto", "Name": "Avenida Paulista, 500", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Paulínia", country: "BR", line1: "Avenida Paulista, 500", line2: nil, postalCode: "13145-089", state: "SP" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Japan() { // Search string used to generate address dictionary: "Nagatacho 2" let addressDictionary = [ CNPostalAddressStreetKey: "Nagatacho 2-Chōme", CNPostalAddressStateKey: "Tokyo", CNPostalAddressISOCountryCodeKey: "JP", CNPostalAddressCountryKey: "Japan", CNPostalAddressCityKey: "Chiyoda", "Thoroughfare": "Nagatacho 2-Chōme", CNPostalAddressSubLocalityKey: "Nagatacho", "Name": "Nagatacho 2-Chōme", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Chiyoda", country: "JP", line1: "Nagatacho 2-Chōme", line2: nil, postalCode: nil, state: "Tokyo" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } func testAsAddress_Australia() { // Search string used to generate address dictionary: "488 George St Syd" let addressDictionary = [ CNPostalAddressStreetKey: "488 George St", CNPostalAddressStateKey: "NSW", CNPostalAddressISOCountryCodeKey: "AU", CNPostalAddressCountryKey: "Australia", CNPostalAddressCityKey: "Sydney", CNPostalAddressPostalCodeKey: "2000", "SubThoroughfare": "488", "Thoroughfare": "George St", CNPostalAddressSubAdministrativeAreaKey: "Sydney", "Name": "488 George St", ] as [String: Any] let placemark = MKPlacemark( coordinate: CLLocationCoordinate2D(), addressDictionary: addressDictionary ) let expectedAddress = PaymentSheet.Address( city: "Sydney", country: "AU", line1: "488 George St", line2: nil, postalCode: "2000", state: "NSW" ) XCTAssertEqual(placemark.asAddress, expectedAddress) } }
43e85c763be14b13c587a1c0bc7d2dec
35.784689
96
0.573881
false
true
false
false
omaarr90/healthcare
refs/heads/master
Sources/App/Models/Disease.swift
mit
1
import Vapor import Fluent import Foundation final class Disease: Model { var id: Node? var name: String // var doctors: Children<Doctor> // var symptoms: Children<Symptom> // var exists: Bool = false init(name: String) { self.id = nil //UUID().uuidString.makeNode() self.name = name // self.doctors = self.children(Doctor.self).all() // self.symptoms = symptoms } init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") // doctors = try node.extract("doctors") // symptoms = try node.extract("symptoms") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": name, // "doctors": self.c, // "symptoms": Node(node:symptoms) ]) } } extension Disease { static func mainDisease(symptos: [Int]) throws -> Disease { var mostFrequent = symptos[0] var counts = [Int: Int]() symptos.forEach { counts[$0] = (counts[$0] ?? 0) + 1 } if let (value, _) = counts.max(by: {$0.1 < $1.1}) { mostFrequent = value } return try Disease.find(mostFrequent)! } } extension Disease: Preparation { static func prepare(_ database: Database) throws { try database.create("diseases") { diseases in diseases.id() diseases.string("name") } } static func revert(_ database: Database) throws { try database.delete("diseases") } }
93d2385cac728a43eeb889e97909d9d2
23.880597
62
0.534493
false
false
false
false
jmalesh/CareShare
refs/heads/master
CareShare/CareShare/TableViewCell.swift
mit
1
// // TableViewCell.swift // CareShare // // Created by Jess Malesh on 7/6/16. // Copyright © 2016 Jess Malesh. All rights reserved. // import UIKit import QuartzCore //protocol TableViewCellDelegate //{ // func medListItemDeleted(medListItem: MedListItem) //} class TableViewCell: UITableViewCell { let gradientLayer = CAGradientLayer() var originalCenter = CGPoint() var deleteOnDragRelease = false var delegate: TableViewCellDelegate? var medListItem: MedListItem? required init(coder aDecoder : NSCoder) { fatalError("NSCoding not supported") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) gradientLayer.frame = bounds let color1 = UIColor(white: 1.0, alpha: 0.2).CGColor as CGColorRef let color2 = UIColor(white: 1.0, alpha: 0.1).CGColor as CGColorRef let color3 = UIColor.clearColor().CGColor as CGColorRef let color4 = UIColor(white: 0.0, alpha: 0.1).CGColor as CGColorRef gradientLayer.colors = [color1, color2, color3, color4] gradientLayer.locations = [0.0, 0.01, 0.95, 1.0] layer.insertSublayer(gradientLayer, atIndex: 0) let recognizer = UIPanGestureRecognizer(target: self, action: "handlePan:") recognizer.delegate = self addGestureRecognizer(recognizer) } override func layoutSubviews() { super.layoutSubviews() gradientLayer.frame = bounds } func handlePan(recognizer: UIPanGestureRecognizer) { if recognizer.state == .Began { originalCenter = center } if recognizer.state == .Changed { let translation = recognizer.translationInView(self) center = CGPointMake(originalCenter.x + translation.x, originalCenter.y) deleteOnDragRelease = frame.origin.x < -frame.size.width / 2.0 } if recognizer.state == .Ended { let originalFrame = CGRect(x: 0, y: frame.origin.y, width: bounds.size.width, height: bounds.size.height) if !deleteOnDragRelease { UIView.animateWithDuration(0.2, animations: { self.frame = originalFrame}) } } if deleteOnDragRelease { if delegate != nil && medListItem != nil{ delegate!.medListItemDeleted(medListItem!) } } } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = panGestureRecognizer.translationInView(superview!) if fabs(translation.x) > fabs(translation.y) { return true } return false } return false } }
2e9032c8060749814c30e6bd83bbdb91
31.377778
117
0.63315
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dMaterialManager.swift
gpl-3.0
1
// // dMaterialManager.swift // DrakkenEngine // // Created by Allison Lindner on 23/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // internal class dMaterialTexture { internal var texture: dTexture internal var index: Int internal init(texture: dTexture, index: Int) { self.texture = texture self.index = index } } internal class dMaterialData { internal var shader: dShader internal var buffers: [dBufferable] = [] internal var textures: [dMaterialTexture] = [] internal init(shader: dShader) { self.shader = shader } } internal class dMaterialManager { private var _materials: [String : dMaterialData] = [:] internal func create(name: String, shader: String, buffers: [dBufferable], textures: [dMaterialTexture]) { let instancedShader = dCore.instance.shManager.get(shader: shader) let materialData = dMaterialData(shader: instancedShader) materialData.buffers = buffers materialData.textures = textures self._materials[name] = materialData } internal func get(material name: String) -> dMaterialData? { return self._materials[name] } }
e511be7e931360ee672acc35dc7051ab
22.64
68
0.684433
false
false
false
false
codefellows/sea-d34-iOS
refs/heads/master
Sample Code/Week 3/GithubToGo/GithubToGo/UserSearchViewController.swift
mit
1
// // UserSearchViewController.swift // GithubToGo // // Created by Bradley Johnson on 4/15/15. // Copyright (c) 2015 BPJ. All rights reserved. // import UIKit class UserSearchViewController: UIViewController,UICollectionViewDataSource, UISearchBarDelegate, UINavigationControllerDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! let imageFetchService = ImageFetchService() var users = [User]() override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.searchBar.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.delegate = self } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.delegate = nil } //MARK: UISeachBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() GithubService.sharedInstance.fetchUsersForSearch(searchBar.text, completionHandler: { (users, error) -> (Void) in self.users = users! self.collectionView.reloadData() }) } func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return text.validForURL() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.users.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as! UserCell cell.imageView.image = nil let user = self.users[indexPath.row] if user.avatarImage != nil { cell.imageView.image = user.avatarImage } else { self.imageFetchService.fetchImageForURL(user.avatarURL, imageViewSize: cell.imageView.frame.size, completionHandler: { (downloadedImage) -> (Void) in cell.imageView.alpha = 0 cell.imageView.transform = CGAffineTransformMakeScale(1.0, 1.0) user.avatarImage = downloadedImage cell.imageView.image = downloadedImage UIView.animateWithDuration(0.4, animations: { () -> Void in cell.imageView.alpha = 1 cell.imageView.transform = CGAffineTransformMakeScale(-2.0, -2.0) }) }) } return cell } func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if toVC is UserDetailViewController { return ToUserDetailAnimationController() } return nil } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowUser" { let destination = segue.destinationViewController as! UserDetailViewController let indexPath = self.collectionView.indexPathsForSelectedItems().first as! NSIndexPath let user = self.users[indexPath.row] destination.selectedUser = user } } }
b0978b3676bc0c3b9cb4c5b099146e5b
33.602041
279
0.729578
false
false
false
false
Daltron/BigBoard
refs/heads/master
Example/BigBoard/ExampleViewController.swift
mit
1
// // ViewController.swift // BigBoard // // Created by Dalton on 04/14/2016. // Copyright (c) 2016 Dalton. All rights reserved. // import UIKit class ExampleViewController: UIViewController, ExampleViewDelegate { var model:ExampleModel! var exampleView:ExampleView! init(){ super.init(nibName: nil, bundle: nil) edgesForExtendedLayout = UIRectEdge() model = ExampleModel() exampleView = ExampleView(delegate: self) view = exampleView title = "BigBoard" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addStockButtonPressed)) navigationItem.rightBarButtonItem?.tintColor = UIColor.white } func addStockButtonPressed() { let addStockController = ExampleAddStockViewController { (stock:BigBoardSearchResultStock) in print("Loading stock with symbol: \(stock.symbol!)") self.model.mapStockWithSymbol(symbol: stock.symbol!, success: { print("Stock successfully mapped.") print("--------------------------") self.exampleView.stocksTableView.reloadData() }, failure: { (error) in print(error) print("--------------------------") }) } navigationController?.pushViewController(addStockController, animated: true) } // MARK: ExampleViewDelegate Implementation func numberOfStocks() -> Int { return model.numberOfStocks() } func stockAtIndex(_ index: Int) -> BigBoardStock { return model.stockAtIndex(index) } func stockSelectedAtIndex(_ index:Int) { let exampleStockDetailsModel = ExampleStockDetailsModel(stock: model.stockAtIndex(index)) let exampleStockDetailsViewController = ExampleStockDetailsViewController(model: exampleStockDetailsModel) navigationController!.pushViewController(exampleStockDetailsViewController, animated: true) } func refreshControllPulled() { model.refreshStocks(success: { self.exampleView.refreshControl.endRefreshing() self.exampleView.stocksTableView.reloadData() }) { (error) in print(error) } } }
91318f41837ba6672db237ffee4e00a6
32.302632
142
0.634927
false
false
false
false
tomasharkema/HoelangTotTrein.iOS
refs/heads/develop
HoelangTotTrein/PickerViewController.swift
apache-2.0
1
// // PickerViewController.swift // HoelangTotTrein // // Created by Tomas Harkema on 15-02-15. // Copyright (c) 2015 Tomas Harkema. All rights reserved. // import UIKit import CoreLocation import Observable typealias SelectStationHandler = (Station) -> Void let PickerAnimationDuration = 0.5 class PickerViewController : UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pickerTitle: UILabel! @IBOutlet weak var searchView: UITextField! @IBOutlet weak var leftMarginSearchField: NSLayoutConstraint! @IBOutlet weak var headerView: UIView! @IBOutlet weak var pulldownIcon: UIImageView! var screenshotImageView:UIImageView! var backdropImageView:UIImageView! var backdrop: UIImage? var willDismiss:Bool = false var isDismissing:Bool = false var mode:StationType! { didSet { pickerTitle?.text = (mode == StationType.From) ? "Van" : "Naar" } } var currentStation:Station! { didSet { reload() } } var selectStationHandler:SelectStationHandler! var mostUsed = [Station]() var stations = [Station]() func reload() { { self.mostUsed = MostUsed.getListByVisited().slice(10) self.stations = TreinTicker.sharedInstance.stations.filter { [weak self] station in return (self?.mostUsed.contains(station) != nil) } } ~> { if let tv = self.tableView { tv.reloadData() self.selectRow() } } } /// MARK: View Lifecycle var locationUpdatedSubscription: EventSubscription<CLLocation>? = Optional.None; override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.clearColor() tableView.backgroundView = nil tableView.delegate = self tableView.dataSource = self backdropImageView = UIImageView(frame: view.bounds) view.insertSubview(backdropImageView, belowSubview: headerView) screenshotImageView = UIImageView(frame: view.bounds) view.insertSubview(screenshotImageView, belowSubview: backdropImageView) // set inital state backdropImageView.image = backdrop pickerTitle.text = (mode == StationType.From) ? "Van" : "Naar" searchView.delegate = self searchView.addTarget(self, action: Selector("textFieldDidChange:"), forControlEvents: UIControlEvents.EditingChanged) searchView.attributedPlaceholder = NSAttributedString(string: "Zoeken...", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor().colorWithAlphaComponent(0.3)]) headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9); backdropImageView.alpha = 0 self.stations = TreinTicker.sharedInstance.stations reload() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) locationUpdatedSubscription = TreinTicker.sharedInstance.locationUpdated += { [weak self] _ in self?.reload() return; } animateMenu(true, animated: true, completion: nil) } override func viewWillDisappear(animated: Bool) { locationUpdatedSubscription?.invalidate() } /// MARK: Show State Animations var showState:Bool = false func animateMenu(state:Bool, animated:Bool, completion:((Bool) -> Void)?) { let show = state if state { self.headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9); backdropImageView.alpha = 0 screenshotImageView.image = backdrop let blurImg = backdrop?.applyBlurWithRadius(20, tintColor: UIColor.clearColor(), saturationDeltaFactor: 1.0, maskImage: nil) backdropImageView.image = blurImg } let fase1:()->() = { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, 0.0), 0.9, 0.9) self.backdropImageView.alpha = 0.25 } let fase2:()->() = { if show { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, 0.0), 1.0, 1.0) self.backdropImageView.alpha = 1 } else { self.tableView.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(0.0, self.view.bounds.height), 0.9, 0.9) self.backdropImageView.alpha = 0 } } let header:()->() = { self.headerView.transform = show ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) } if animated { UIView.animateKeyframesWithDuration(PickerAnimationDuration, delay: 0, options: UIViewKeyframeAnimationOptions.CalculationModeCubic | UIViewKeyframeAnimationOptions.AllowUserInteraction, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: fase1) UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: fase2) }, completion: completion) UIView.animateWithDuration(PickerAnimationDuration, animations: header) { if $0 { if !show { self.headerView.transform = CGAffineTransformMakeTranslation(0, -self.headerView.bounds.height) self.backdropImageView.hidden = true } self.isDismissing = false } } } else { header() fase1() fase2() if let c = completion { c(true) } } } /// MARK: Table View Delegation func selectRow() { var indexPath:NSIndexPath? if let station = currentStation { if let index = findIndex(mostUsed, station) { indexPath = NSIndexPath(forRow: index, inSection: 0) } else if let index = findIndex(stations, station) { indexPath = NSIndexPath(forRow: index, inSection: 2) } if let ix = indexPath { if tableView.cellForRowAtIndexPath(ix) != nil { tableView.selectRowAtIndexPath(ix, animated: false, scrollPosition: UITableViewScrollPosition.Middle) } } } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var station:Station if indexPath.section == 0 { station = mostUsed[indexPath.row] } else if indexPath.section == 1 { station = TreinTicker.sharedInstance.closeStations[indexPath.row] } else if indexPath.section == 2 { station = stations[indexPath.row] } else { station = stationsFound()[indexPath.row] } var cell:PickerCellView = self.tableView.dequeueReusableCellWithIdentifier("cell") as! PickerCellView cell.station = station return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 4 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return !isInEditingState() ? mostUsed.count : 0 } else if section == 1 { return !isInEditingState() ? TreinTicker.sharedInstance.closeStations.count : 0 } else if section == 2 { return !isInEditingState() ? stations.count : 0 } else { return isInEditingState() ? stationsFound().count : 0 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cb = selectStationHandler { if indexPath.section == 0 { currentStation = mostUsed[indexPath.row] } else if indexPath.section == 1 { currentStation = TreinTicker.sharedInstance.closeStations[indexPath.row] } else if indexPath.section == 2 { currentStation = stations[indexPath.row] } else { currentStation = stationsFound()[indexPath.row] } searchView.resignFirstResponder() searchView.text = "" } dismissPicker() } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return isInEditingState() ? "" : (mostUsed.count == 0 ? "" : "Meest gebruikt") } else if section == 1 { return isInEditingState() ? "" : (TreinTicker.sharedInstance.closeStations.count == 0 ? "" : "Dichstbij") } else if section == 2 { return isInEditingState() ? "" : (stations.count == 0 ? "" : "A-Z") } return "" } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let headerView = view as! UITableViewHeaderFooterView headerView.textLabel.font = UIFont(name: "VarelaRound-Regular", size: 16.0) headerView.textLabel.textColor = UIColor.blackColor() headerView.contentView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8) headerView.backgroundView = nil } func textFieldDidBeginEditing(textField: UITextField) { UIView.animateWithDuration(0.2) { self.leftMarginSearchField.constant = -self.pickerTitle.bounds.width self.pickerTitle.alpha = 0 self.view.layoutIfNeeded() } } func textFieldDidEndEditing(textField: UITextField) { UIView.animateWithDuration(0.2) { self.leftMarginSearchField.constant = 16 self.pickerTitle.alpha = 1 self.view.layoutIfNeeded() } } func textFieldDidChange(textField:UITextField) { tableView.reloadData() } func stationsFound() -> [Station] { return stations.filter { ($0.name.lang.lowercaseString as NSString).containsString(self.searchView.text.lowercaseString) } } func isInEditingState() -> Bool { return searchView.text != "" } /// MARK: ScrollView Delegation func scrollViewDidScroll(scrollView: UIScrollView) { tableView.alpha = 1 pulldownIcon.alpha = 0 pulldownIcon.transform = CGAffineTransformIdentity if scrollView.contentOffset.y < 0 && !isDismissing { headerView.transform = CGAffineTransformMakeTranslation(0, scrollView.contentOffset.y/2) if scrollView.contentOffset.y < -50 { willDismiss = true scrollView.transform = CGAffineTransformMakeTranslation(0, 10) let progress = min(((-scrollView.contentOffset.y - 50) / 50)/4, 0.5) let scale = 1 - (0.25 * progress) tableView.transform = CGAffineTransformMakeScale(scale, scale) tableView.alpha = 1 - progress pulldownIcon.alpha = min(progress * 10, 1) let scalePulldown = min(progress * 10, 1) pulldownIcon.transform = CGAffineTransformMakeScale(scalePulldown, scalePulldown) } else { willDismiss = false scrollView.transform = CGAffineTransformIdentity } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if willDismiss { self.isDismissing = true dismissPicker() } } /// MARK: Button Delegation @IBAction func closeButton(sender: AnyObject) { if searchView.isFirstResponder() { searchView.text = "" searchView.endEditing(true) tableView.reloadData() } else { dismissPicker() } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func dismissPicker() { searchView.text = "" searchView.endEditing(true) searchView.resignFirstResponder() if let cb = selectStationHandler { cb(currentStation) willDismiss = false } animateMenu(false, animated: true) { _ in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { self.performSegueWithIdentifier("unwindPicker", sender: self) } //self.dismissViewControllerAnimated(true, completion: nil) return; } } }
063493380c33f9b6942c9312c655e474
31.89779
175
0.680914
false
false
false
false
mattermost/ios
refs/heads/master
Mattermost/MattermostApi.swift
apache-2.0
1
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. import Foundation import UIKit protocol MattermostApiProtocol { func didRecieveResponse(_ result: JSON) func didRecieveError(_ message: String) } open class MattermostApi: NSObject { static let API_ROUTE_V4 = "/api/v4" static let API_ROUTE_V3 = "/api/v3" static let API_ROUTE = API_ROUTE_V4 var baseUrl = "" var data: NSMutableData = NSMutableData() var statusCode = 200 var delegate: MattermostApiProtocol? override init() { super.init() self.initBaseUrl() } func initBaseUrl() { let defaults = UserDefaults.standard let url = defaults.string(forKey: CURRENT_URL) if (url != nil && (url!).count > 0) { baseUrl = url! } } func getPing() { return getPing(versionRoute: MattermostApi.API_ROUTE) } func getPing(versionRoute: String) { var endpoint: String = baseUrl + versionRoute if (versionRoute == MattermostApi.API_ROUTE_V3) { endpoint += "/general/ping" } else { endpoint += "/system/ping" } print(endpoint) guard let url = URL(string: endpoint) else { print("Error cannot create URL") DispatchQueue.main.async { self.delegate?.didRecieveError("Invalid URL. Please check to make sure the URL is correct.") } return } let urlRequest = URLRequest(url: url) let session = URLSession.shared let task = session.dataTask(with: urlRequest) { (data, response, error) in var code = 0 if (response as? HTTPURLResponse) != nil { code = (response as! HTTPURLResponse).statusCode } guard error == nil else { print(error!) print("Error: statusCode=\(code) data=\(error!.localizedDescription)") DispatchQueue.main.async { self.delegate?.didRecieveError("\(error!.localizedDescription) [\(code)]") } return } guard let responseData = data else { print("Error: did not receive data") DispatchQueue.main.async { self.delegate?.didRecieveError("Did not receive data from the server.") } return } let json = JSON(data: responseData as Data) if (code == 200) { print("Found API version " + versionRoute) Utils.setProp(API_ROUTE_PROP, value: versionRoute) DispatchQueue.main.async { self.delegate?.didRecieveResponse(json) } } else if (code == 404) { print("Couldn't find V4 API falling back to V3") if (versionRoute != MattermostApi.API_ROUTE_V3) { return self.getPing(versionRoute: MattermostApi.API_ROUTE_V3) } else { DispatchQueue.main.async { self.delegate?.didRecieveError("Couldn't find the correct Mattermost server version.") } } } else { let datastring = NSString(data: responseData as Data, encoding: String.Encoding.utf8.rawValue) print("Error: statusCode=\(code) data=\(datastring!)") if let message = json["message"].string { DispatchQueue.main.async { self.delegate?.didRecieveError(message) } } else { DispatchQueue.main.async { self.delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured (-1)")) } } } } task.resume() } func attachDeviceId() { var endpoint: String = baseUrl + Utils.getProp(API_ROUTE_PROP) if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) { endpoint += "/users/attach_device" } else { endpoint += "/users/sessions/device" } print(endpoint) guard let url = URL(string: endpoint) else { print("Error cannot create URL") return } var urlRequest = URLRequest(url: url) if (Utils.getProp(API_ROUTE_PROP) == MattermostApi.API_ROUTE_V3) { urlRequest.httpMethod = "POST" } else { urlRequest.httpMethod = "PUT" } urlRequest.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With") urlRequest.httpBody = try! JSON(["device_id": "apple:" + Utils.getProp(DEVICE_TOKEN)]).rawData() let session = URLSession.shared let task = session.dataTask(with: urlRequest) { (data, response, error) in var code = 0 if (response as? HTTPURLResponse) != nil { code = (response as! HTTPURLResponse).statusCode } guard error == nil else { print(error!) print("Error: statusCode=\(code) data=\(error!.localizedDescription)") return } } task.resume() } func connection(_ connection: NSURLConnection!, didFailWithError error: NSError!) { statusCode = error.code print("Error: statusCode=\(statusCode) data=\(error.localizedDescription)") delegate?.didRecieveError("\(error.localizedDescription) [\(statusCode)]") } func connection(_ didReceiveResponse: NSURLConnection!, didReceiveResponse response: URLResponse!) { statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1 self.data = NSMutableData() let mmsid = Utils.getCookie(MATTERM_TOKEN) Utils.setProp(MATTERM_TOKEN, value: mmsid) print(mmsid) if (mmsid == "") { Utils.setProp(CURRENT_USER, value: "") Utils.setProp(MATTERM_TOKEN, value: "") } } func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace?) -> Bool { return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust } func connection(_ connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge?) { if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let credentials = URLCredential(trust: challenge!.protectionSpace.serverTrust!) challenge!.sender!.use(credentials, for: challenge!) } challenge?.sender!.continueWithoutCredential(for: challenge!) } func connection(_ connection: NSURLConnection!, didReceiveData data: Data!) { self.data.append(data) } func connectionDidFinishLoading(_ connection: NSURLConnection!) { let json = JSON(data: data as Data) if (statusCode == 200) { delegate?.didRecieveResponse(json) } else { let datastring = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) print("Error: statusCode=\(statusCode) data=\(datastring!)") if let message = json["message"].string { delegate?.didRecieveError(message) } else { delegate?.didRecieveError(NSLocalizedString("UNKOWN_ERR", comment: "An unknown error has occured. (-1)")) } } } }
033bc7e9f72274a3fae4223f34a4537b
34.061135
134
0.547266
false
false
false
false
NUKisZ/MyTools
refs/heads/master
MyTools/MyTools/Tools/Const.swift
mit
1
// // Const.swift // MengWuShe // // Created by zhangk on 16/10/17. // Copyright © 2016年 zhangk. All rights reserved. // import UIKit public let kUserDefaults = UserDefaults.standard public let kScreenWidth = UIScreen.main.bounds.size.width //屏幕宽度 public let kScreenHeight = UIScreen.main.bounds.size.height //屏幕高度 public let kDeviceName = UIDevice.current.name //获取设备名称 例如:**的手机 public let kSysName = UIDevice.current.systemName //获取系统名称 例如:iPhone OS public let kSysVersion = UIDevice.current.systemVersion //获取系统版本 例如:9.2 public let kDeviceUUID = (UIDevice.current.identifierForVendor?.uuidString)! //获取设备唯一标识符 例如:FBF2306E-A0D8-4F4B-BDED-9333B627D3E6 public let kDeviceModel = UIDevice.current.model //获取设备的型号 例如:iPhone public let kInfoDic = Bundle.main.infoDictionary! as [String:Any] public let kAppVersion = (Bundle.main.infoDictionary?["CFBundleShortVersionString"])! // 获取App的版本 public let kAppBuildVersion = (Bundle.main.infoDictionary?["CFBundleVersion"])! // 获取App的build版本 public let kAppName = (Bundle.main.infoDictionary?["CFBundleDisplayName"])! // 获取App的名称 //var context = JSContext() //context = web?.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext? public let javaScriptContext = "documentView.webView.mainFrame.javaScriptContext" //微信相关 //获得access_token public let MWSGetAccessToken = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code" //测试access_token是否有效 public let MWSTestAccessToken = "https://api.weixin.qq.com/sns/auth?access_token=%@&openid=%@" //获得用户信息 public let MWSGetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@"
e6ed9267e9f4a32f0621ef6037322ec1
40.555556
139
0.694652
false
false
false
false
ramunasjurgilas/operation-queue-ios
refs/heads/master
operation-queue-ios/ViewControllers/PendingTasks/PendingTaskOperation.swift
mit
1
// // PendingTaskOperation.swift // operation-queue-ios // // Created by Ramunas Jurgilas on 2017-04-11. // Copyright © 2017 Ramūnas Jurgilas. All rights reserved. // import UIKit class PendingTaskOperation: Operation { var count = 0 let task: Task var executionStart = Date() var currentIteration = 0 var timer: Timer? init(pendingTask: Task) { task = pendingTask super.init() } override func start() { executionStart = Date() task.status = TaskStatus.executing.rawValue try? task.managedObjectContext?.save() isExecuting = true isFinished = false main() } override func main() { print("start on: -> " + Date().debugDescription) for i in currentIteration...30 { DispatchQueue.main.async { [weak self] in self?.task.duration = Int32((self?.executionStart.timeIntervalSinceNow)!) * -1 } currentIteration = i print("Iteration: \(currentIteration)") if isExecuting == false { // count = i print("Is executing: \(i.description) " + isExecuting.description) // isFinished = true return } sleep(1) } DispatchQueue.main.async { [weak self] in self?.task.status = TaskStatus.completed.rawValue self?.task.duration = Int32((self?.executionStart.timeIntervalSinceNow)!) * -1 try? self?.task.managedObjectContext?.save() } print("end " + Date().debugDescription) isFinished = true } func postpone() { timer?.invalidate() task.status = TaskStatus.postponed.rawValue print("Post pone: \(currentIteration)") isExecuting = false isFinished = false timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(resume), userInfo: nil, repeats: false) } func resume() { if task.status != TaskStatus.postponed.rawValue { print("Task is not postponed. Can not resume.") } timer?.invalidate() print("resume operaiton") DispatchQueue.main.async { [weak self] in self?.task.status = TaskStatus.executing.rawValue try? self?.task.managedObjectContext?.save() } DispatchQueue.global(qos: .default).async { [weak self] in self?.isExecuting = true self?.isFinished = false self?.main() } } fileprivate var _executing: Bool = false override var isExecuting: Bool { get { return _executing } set { if _executing != newValue { willChangeValue(forKey: "isExecuting") _executing = newValue didChangeValue(forKey: "isExecuting") } } } fileprivate var _finished: Bool = false; override var isFinished: Bool { get { return _finished } set { if _finished != newValue { willChangeValue(forKey: "isFinished") _finished = newValue didChangeValue(forKey: "isFinished") } } } }
18f15eb53e9c1e1af1640a7d3e93a421
29.172727
128
0.549563
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/Session/Modules/API Request/Sync/Sync+Stickers.swift
mit
1
// // MethodRequest+Stickers.swift // Pelican // // Created by Takanu Kyriako on 17/12/2017. // import Foundation /** This extension handles any kinds of operations involving stickers (including setting group sticker packs). */ extension MethodRequestSync { /** Returns a StickerSet type for the name of the sticker set given, if successful. */ public func getStickerSet(_ name: String) -> StickerSet? { let request = TelegramRequest.getStickerSet(name: name) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) } /** Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). */ public func uploadStickerFile(_ sticker: Sticker, userID: String) -> FileDownload? { guard let request = TelegramRequest.uploadStickerFile(userID: userID, sticker: sticker) else { PLog.error("Can't create uploadStickerFile request.") return nil } let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) } /** Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. */ @discardableResult public func createNewStickerSet(userID: String, name: String, title: String, sticker: Sticker, emojis: String, containsMasks: Bool? = nil, maskPosition: MaskPosition? = nil) -> Bool { let request = TelegramRequest.createNewStickerSet(userID: userID, name: name, title: title, sticker: sticker, emojis: emojis, containsMasks: containsMasks, maskPosition: maskPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Adds a sticker to a sticker set created by the bot. */ @discardableResult public func addStickerToSet(userID: String, name: String, pngSticker: Sticker, emojis: String, maskPosition: MaskPosition? = nil) -> Bool { let request = TelegramRequest.addStickerToSet(userID: userID, name: name, pngSticker: pngSticker, emojis: emojis, maskPosition: maskPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Use this method to move a sticker in a set created by the bot to a specific position. */ @discardableResult public func setStickerPositionInSet(stickerID: String, newPosition: Int) -> Bool { let request = TelegramRequest.setStickerPositionInSet(stickerID: stickerID, position: newPosition) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } /** Use this method to delete a sticker from a set created by the bot. */ @discardableResult public func deleteStickerFromSet(stickerID: String) -> Bool { let request = TelegramRequest.deleteStickerFromSet(stickerID: stickerID) let response = tag.sendSyncRequest(request) return MethodRequest.decodeResponse(response) ?? false } }
fde43aa89129e37eb2d551c552ac97e8
32.161616
143
0.681084
false
false
false
false
bascar2020/ios-truelinc
refs/heads/master
Pods/QRCodeReader.swift/Sources/QRCodeReaderView.swift
gpl-3.0
1
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit final class QRCodeReaderView: UIView, QRCodeReaderDisplayable { lazy var overlayView: UIView = { let ov = ReaderOverlayView() ov.backgroundColor = .clear ov.clipsToBounds = true ov.translatesAutoresizingMaskIntoConstraints = false return ov }() let cameraView: UIView = { let cv = UIView() cv.clipsToBounds = true cv.translatesAutoresizingMaskIntoConstraints = false return cv }() lazy var cancelButton: UIButton? = { let cb = UIButton() cb.translatesAutoresizingMaskIntoConstraints = false cb.setTitleColor(.gray, for: .highlighted) return cb }() lazy var switchCameraButton: UIButton? = { let scb = SwitchCameraButton() scb.translatesAutoresizingMaskIntoConstraints = false return scb }() lazy var toggleTorchButton: UIButton? = { let ttb = ToggleTorchButton() ttb.translatesAutoresizingMaskIntoConstraints = false return ttb }() func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool) { translatesAutoresizingMaskIntoConstraints = false addComponents() cancelButton?.isHidden = !showCancelButton switchCameraButton?.isHidden = !showSwitchCameraButton toggleTorchButton?.isHidden = !showTorchButton guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton else { return } let views = ["cv": cameraView, "ov": overlayView, "cb": cb, "scb": scb, "ttb": ttb] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views)) if showCancelButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views)) } else { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views)) } if showSwitchCameraButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views)) } if showTorchButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views)) } for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) { addConstraint(NSLayoutConstraint(item: overlayView, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0)) } } // MARK: - Convenience Methods private func addComponents() { addSubview(cameraView) addSubview(overlayView) if let scb = switchCameraButton { addSubview(scb) } if let ttb = toggleTorchButton { addSubview(ttb) } if let cb = cancelButton { addSubview(cb) } } }
ca3d24977b869e5157cda5b853542c11
33.469231
169
0.699397
false
false
false
false
PatrickChow/Swift-Awsome
refs/heads/master
News/Modules/Message/ViewController/MessagesListingViewController.swift
mit
1
// // Created by Patrick Chow on 2017/7/19. // Copyright (c) 2017 JIEMIAN. All rights reserved. import UIKit import Foundation import AsyncDisplayKit class MessagesListingViewController: ViewController { open lazy var tableNode: ASTableNode = { let instance = ASTableNode(style: .plain) instance.backgroundColor = UIColor.clear instance.delegate = self instance.dataSource = self instance.frame = self.view.bounds instance.view.separatorStyle = .singleLine instance.view.tableFooterView = UIView() instance.view.separatorInset = .zero instance.view.layoutMargins = .zero instance.view.nv.separatorColor(UIColor(hexNumber: 0xe8e8e8), night: UIColor(hexNumber: 0x4d4d4d)) if #available(iOS 9.0, *) { instance.view.cellLayoutMarginsFollowReadableWidth = false } return instance }() override func viewDidLoad() { super.viewDidLoad() title = "消息" view.addSubnode(tableNode) listingProvider.request(.messages("1")) .filterSuccessfulStatusCodes() .mapJSON() .subscribe { (event) in switch event { case let .next(response): print(response) case let .error(e): print(e) case .completed: print("完成") } } .disposed(by: disposeBag) } } extension MessagesListingViewController: ASTableDelegate, ASTableDataSource { func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return 10 } func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock { return { [weak self] () -> ASCellNode in let cellNode = MessagesListingNode("测试数据") return cellNode } } }
ef0feccbd58e28f18aa19dc5474fb845
27.911765
106
0.598169
false
false
false
false
avito-tech/Paparazzo
refs/heads/master
Paparazzo/Marshroute/PhotoLibrary/Assembly/PhotoLibraryMarshrouteAssemblyImpl.swift
mit
1
import UIKit import Marshroute public final class PhotoLibraryMarshrouteAssemblyImpl: BasePaparazzoAssembly, PhotoLibraryMarshrouteAssembly { public func module( selectedItems: [PhotoLibraryItem], maxSelectedItemsCount: Int?, routerSeed: RouterSeed, configure: (PhotoLibraryModule) -> () ) -> UIViewController { let photoLibraryItemsService = PhotoLibraryItemsServiceImpl() let interactor = PhotoLibraryInteractorImpl( selectedItems: selectedItems, maxSelectedItemsCount: maxSelectedItemsCount, photoLibraryItemsService: photoLibraryItemsService ) let router = PhotoLibraryMarshrouteRouter(routerSeed: routerSeed) let presenter = PhotoLibraryPresenter( interactor: interactor, router: router ) let viewController = PhotoLibraryViewController() viewController.addDisposable(presenter) viewController.setTheme(theme) presenter.view = viewController configure(presenter) return viewController } }
b29797af4ee18b423c99ab178f25c8e2
29.842105
110
0.651024
false
true
false
false
mpurland/Morpheus
refs/heads/master
Morpheus/CollectionDataSource.swift
bsd-3-clause
1
import UIKit import ReactiveCocoa public protocol CollectionDataSource: CollectionViewDataSource { var collectionView: UICollectionView { get } } public class CollectionModelDataSource<Model> { public typealias ReuseTransformer = Model -> ReuseIdentifier public typealias CellConfigurerTransformer = Model -> CollectionCellConfigurer<Model> public let collectionView: UICollectionView public let collectionModel: CollectionModel<Model> public let reuseTransformer: ReuseTransformer public let cellConfigurerTransformer: CellConfigurerTransformer init(collectionView otherCollectionView: UICollectionView, collectionModel otherCollectionModel: CollectionModel<Model>, reuseTransformer otherReuseTransformer: ReuseTransformer, cellConfigurerTransformer otherCellConfigurerTransformer: CellConfigurerTransformer) { collectionView = otherCollectionView collectionModel = otherCollectionModel reuseTransformer = otherReuseTransformer cellConfigurerTransformer = otherCellConfigurerTransformer } }
b0950288f760292bd776a9329faf68fd
45.608696
269
0.815299
false
true
false
false
movielala/VideoThumbnailViewKit
refs/heads/master
VideoThumbnailViewKit/VideoThumbnailView/VideoThumbnailView.swift
mit
2
// // VideoThumbnailView.swift // VideoThumbnailView // // Created by Toygar Dundaralp on 9/29/15. // Copyright (c) 2015 Toygar Dundaralp. All rights reserved. // import UIKit import AVFoundation public class VideoThumbnailView: UIView { private var videoScroll = UIScrollView() private var thumImageView = UIImageView() private var arrThumbViews = NSMutableArray() private var scrollContentWidth = 0.0 private var videoURL = NSURL() private var videoDuration = 0.0 private var activityIndicator = UIActivityIndicatorView() init(frame: CGRect, videoURL url: NSURL, thumbImageWidth thumbWidth: Double) { super.init(frame: frame) self.videoURL = url self.videoDuration = self.getVideoTime(url) activityIndicator = UIActivityIndicatorView( frame: CGRect( x: self.center.x - 15, y: self.frame.size.height / 2 - 15, width: 30.0, height: 30.0)) activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = .White activityIndicator.startAnimating() addSubview(self.activityIndicator) videoScroll = UIScrollView( frame: CGRect( x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)) videoScroll.showsHorizontalScrollIndicator = false videoScroll.showsVerticalScrollIndicator = false videoScroll.bouncesZoom = false videoScroll.bounces = false self.addSubview(videoScroll) self.thumbImageProcessing( videoUrl: videoURL, thumbWidth: thumbWidth) { (thumbImages, error) -> Void in // println(thumbImages) } self.layer.masksToBounds = true } private func thumbImageProcessing( videoUrl url: NSURL, thumbWidth: Double, completion: ((thumbImages: NSMutableArray?, error: NSError?) -> Void)?) { let priority = DISPATCH_QUEUE_PRIORITY_HIGH dispatch_async(dispatch_get_global_queue(priority, 0)) { for index in 0...Int(self.videoDuration) { let thumbXCoords = Double(index) * thumbWidth self.thumImageView = UIImageView( frame: CGRect( x: thumbXCoords, y: 0.0, width: thumbWidth, height: Double(self.frame.size.height))) self.thumImageView.contentMode = .ScaleAspectFit self.thumImageView.backgroundColor = UIColor.clearColor() self.thumImageView.layer.borderColor = UIColor.grayColor().CGColor self.thumImageView.layer.borderWidth = 0.25 self.thumImageView.tag = index self.thumImageView.image = self.generateVideoThumbs( self.videoURL, second: Double(index), thumbWidth: thumbWidth) self.scrollContentWidth = self.scrollContentWidth + thumbWidth self.videoScroll.addSubview(self.thumImageView) self.videoScroll.sendSubviewToBack(self.thumImageView) if let imageView = self.thumImageView as UIImageView? { self.arrThumbViews.addObject(imageView) } } self.videoScroll.contentSize = CGSize( width: Double(self.scrollContentWidth), height: Double(self.frame.size.height)) self.activityIndicator.stopAnimating() completion?(thumbImages: self.arrThumbViews, error: nil) self.videoScroll.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true) } } private func getVideoTime(url: NSURL) -> Float64 { let videoTime = AVURLAsset(URL: url, options: nil) return CMTimeGetSeconds(videoTime.duration) } private func generateVideoThumbs(url: NSURL, second: Float64, thumbWidth: Double) -> UIImage { let asset = AVURLAsset(URL: url, options: nil) let generator = AVAssetImageGenerator(asset: asset) generator.maximumSize = CGSize(width: thumbWidth, height: Double(self.frame.size.height)) generator.appliesPreferredTrackTransform = false let thumbTime = CMTimeMakeWithSeconds(second, 1) do { let ref = try generator.copyCGImageAtTime(thumbTime, actualTime: nil) return UIImage(CGImage: ref) }catch { print(error) } return UIImage() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
a424134c4a68e73cf101f3ba6353d94a
34.108333
96
0.690007
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/minimum-moves-to-equal-array-elements-ii.swift
mit
2
/** * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ * * */ class Solution { func minMoves2(_ nums: [Int]) -> Int { let n = nums.count if n == 0 { return 0 } let list = nums.sorted() let med = list[n/2] var total = 0 for n in list { total += abs(n - med) } return total } } /** * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-i/ * * */ // Date: Wed May 19 08:51:03 PDT 2021 class Solution { func minMoves2(_ nums: [Int]) -> Int { let nums = nums.sorted() let n = nums.count let med = nums[n / 2] let costL = nums.reduce(0) { $0 + abs($1 - med) } return costL } }
b8dbc03de73999a44e5fff857587b6ac
21.176471
74
0.513263
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripeFinancialConnections/StripeFinancialConnectionsTests/FinancialConnectionsSheetTests.swift
mit
1
// // FinancialConnectionsSheetTests.swift // StripeFinancialConnectionsTests // // Created by Vardges Avetisyan on 11/9/21. // import XCTest @testable import StripeFinancialConnections @_spi(STP) import StripeCore @_spi(STP) import StripeCoreTestUtils class EmptyFinancialConnectionsAPIClient: FinancialConnectionsAPIClient { func fetchFinancialConnectionsAccounts(clientSecret: String, startingAfterAccountId: String?) -> Promise<StripeAPI.FinancialConnectionsSession.AccountList> { return Promise<StripeAPI.FinancialConnectionsSession.AccountList>() } func fetchFinancialConnectionsSession(clientSecret: String) -> Promise<StripeAPI.FinancialConnectionsSession> { return Promise<StripeAPI.FinancialConnectionsSession>() } func generateSessionManifest(clientSecret: String, returnURL: String?) -> Promise<FinancialConnectionsSessionManifest> { return Promise<FinancialConnectionsSessionManifest>() } } class EmptySessionFetcher: FinancialConnectionsSessionFetcher { func fetchSession() -> Future<StripeAPI.FinancialConnectionsSession> { return Promise<StripeAPI.FinancialConnectionsSession>() } } class FinancialConnectionsSheetTests: XCTestCase { private let mockViewController = UIViewController() private let mockClientSecret = "las_123345" private let mockAnalyticsClient = MockAnalyticsClient() override func setUpWithError() throws { mockAnalyticsClient.reset() } func testAnalytics() { let sheet = FinancialConnectionsSheet(financialConnectionsSessionClientSecret: mockClientSecret, returnURL: nil, analyticsClient: mockAnalyticsClient) sheet.present(from: mockViewController) { _ in } // Verify presented analytic is logged XCTAssertEqual(mockAnalyticsClient.loggedAnalytics.count, 1) guard let presentedAnalytic = mockAnalyticsClient.loggedAnalytics.first as? FinancialConnectionsSheetPresentedAnalytic else { return XCTFail("Expected `FinancialConnectionsSheetPresentedAnalytic`") } XCTAssertEqual(presentedAnalytic.clientSecret, mockClientSecret) // Mock that financialConnections is completed let host = HostController(api: EmptyFinancialConnectionsAPIClient(), clientSecret: "test", returnURL: nil) sheet.hostController(host, viewController: UIViewController(), didFinish: .canceled) // Verify closed analytic is logged XCTAssertEqual(mockAnalyticsClient.loggedAnalytics.count, 2) guard let closedAnalytic = mockAnalyticsClient.loggedAnalytics.last as? FinancialConnectionsSheetClosedAnalytic else { return XCTFail("Expected `FinancialConnectionsSheetClosedAnalytic`") } XCTAssertEqual(closedAnalytic.clientSecret, mockClientSecret) XCTAssertEqual(closedAnalytic.result, "cancelled") } func testAnalyticsProductUsage() { let _ = FinancialConnectionsSheet(financialConnectionsSessionClientSecret: mockClientSecret, returnURL: nil, analyticsClient: mockAnalyticsClient) XCTAssertEqual(mockAnalyticsClient.productUsage, ["FinancialConnectionsSheet"]) } }
2aad526b0c01d171a8cfa1ee93d1b390
44.114286
161
0.770108
false
true
false
false
Ramesh-P/virtual-tourist
refs/heads/master
Virtual Tourist/FlickrAPIConstants.swift
mit
1
// // FlickrAPIConstants.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 3/2/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation // MARK: FlickrAPIConstants struct Flickr { // MARK: URLs struct Constants { static let apiScheme = "https" static let apiHost = "api.flickr.com" static let apiPath = "/services/rest" } // MARK: Bounding Box struct BoundingBox { static let halfWidth = 1.0 static let halfHeight = 1.0 static let latitudeRange = (-90.0, 90.0) static let longitudeRange = (-180.0, 180.0) } // MARK: Flickr Parameter Keys struct ParameterKeys { static let method = "method" static let apiKey = "api_key" static let sort = "sort" static let boundingBox = "bbox" static let search = "safe_search" static let contentType = "content_type" static let media = "media" static let extras = "extras" static let photosPerPage = "per_page" static let format = "format" static let noJSONCallback = "nojsoncallback" } // MARK: Flickr Parameter Values struct ParameterValues { static let photosSearch = "flickr.photos.search" static let apiKey = "6ebf6fc89a59ca7d25b46f895d25ab0e" static let datePostedAsc = "date-posted-asc" static let datePostedDesc = "date-posted-desc" static let dateTakenAsc = "date-taken-asc" static let dateTakenDesc = "date-taken-desc" static let interestingnessDesc = "interestingness-desc" static let interestingnessAsc = "interestingness-asc" static let relevance = "relevance" static let useSafeSearch = "1" static let photosOnly = "1" static let photos = "photos" static let mediumURL = "url_m" static let photosLimit = "21" static let jsonFormat = "json" static let disableJSONCallback = "1" } // MARK: Flickr Response Keys struct ResponseKeys { static let status = "stat" static let photos = "photos" static let photo = "photo" static let title = "title" static let mediumURL = "url_m" } // MARK: Flickr Response Values struct ResponseValues { static let ok = "ok" } }
a258f378d18c14034e47fe5169caa43d
29.5
63
0.613703
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Sources/EventDetailComponent/Calendar/EventKit/EventKitEventStore.swift
mit
1
import EventKit import EventKitUI import UIKit public class EventKitEventStore: NSObject, EventStore { private let window: UIWindow private let eventStore: EKEventStore private var eventStoreChangedSubscription: NSObjectProtocol? public init(window: UIWindow) { self.window = window self.eventStore = EKEventStore() super.init() eventStoreChangedSubscription = NotificationCenter.default.addObserver( forName: .EKEventStoreChanged, object: eventStore, queue: .main, using: { [weak self] _ in if let strongSelf = self { strongSelf.delegate?.eventStoreChanged(strongSelf) } }) } public var delegate: EventStoreDelegate? public func editEvent(definition event: EventStoreEventDefinition, sender: Any?) { attemptCalendarStoreEdit { [weak self, eventStore] in let calendarEvent = EKEvent(eventStore: eventStore) calendarEvent.title = event.title calendarEvent.location = event.room calendarEvent.startDate = event.startDate calendarEvent.endDate = event.endDate calendarEvent.url = event.deeplinkURL calendarEvent.notes = event.shortDescription calendarEvent.addAlarm(EKAlarm(relativeOffset: -1800)) let editingViewController = EKEventEditViewController() editingViewController.editViewDelegate = self editingViewController.eventStore = eventStore editingViewController.event = calendarEvent switch sender { case let sender as UIBarButtonItem: editingViewController.popoverPresentationController?.barButtonItem = sender case let sender as UIView: editingViewController.popoverPresentationController?.sourceView = sender editingViewController.popoverPresentationController?.sourceRect = sender.bounds default: break } self?.window.rootViewController?.present(editingViewController, animated: true) } } public func removeEvent(identifiedBy eventDefinition: EventStoreEventDefinition) { attemptCalendarStoreEdit { [weak self] in if let event = self?.storeEvent(for: eventDefinition) { do { try self?.eventStore.remove(event, span: .thisEvent) } catch { print("Failed to remove event \(eventDefinition) from calendar. Error=\(error)") } } } } public func contains(eventDefinition: EventStoreEventDefinition) -> Bool { return storeEvent(for: eventDefinition) != nil } private func storeEvent(for eventDefinition: EventStoreEventDefinition) -> EKEvent? { let predicate = eventStore.predicateForEvents( withStart: eventDefinition.startDate, end: eventDefinition.endDate, calendars: nil ) let events = eventStore.events(matching: predicate) return events.first(where: { $0.url == eventDefinition.deeplinkURL }) } private func attemptCalendarStoreEdit(edit: @escaping () -> Void) { if EKEventStore.authorizationStatus(for: .event) == .authorized { edit() } else { requestCalendarEditingAuthorisation(success: edit) } } private func requestCalendarEditingAuthorisation(success: @escaping () -> Void) { eventStore.requestAccess(to: .event) { [weak self] granted, _ in DispatchQueue.main.async { if granted { success() } else { self?.presentNotAuthorizedAlert() } } } } private func presentNotAuthorizedAlert() { let alert = UIAlertController( title: "Not Authorised", message: "Grant Calendar access to Eurofurence in Settings to add events to Calendar.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { _ in if let settingsURL = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(settingsURL) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) window.rootViewController?.present(alert, animated: true) } } extension EventKitEventStore: EKEventEditViewDelegate { public func eventEditViewController( _ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction ) { controller.presentingViewController?.dismiss(animated: true) } }
4e287bf2dbbafccdbfb05884ecf19cbc
35.416058
100
0.607136
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureSettings/Sources/FeatureSettingsUI/PaymentMethods/RemovePaymentMethod/RemovePaymentMethodViewController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import RxSwift import ToolKit final class RemovePaymentMethodViewController: UIViewController { // MARK: - Private IBOutlets @IBOutlet private var titleLabel: UILabel! @IBOutlet private var descriptionLabel: UILabel! @IBOutlet private var badgeImageView: BadgeImageView! @IBOutlet private var buttonView: ButtonView! // MARK: - Injected private let presenter: RemovePaymentMethodScreenPresenter private let disposeBag = DisposeBag() // MARK: - Setup init(presenter: RemovePaymentMethodScreenPresenter) { self.presenter = presenter super.init(nibName: RemovePaymentMethodViewController.objectName, bundle: .module) } required init?(coder: NSCoder) { unimplemented() } override func viewDidLoad() { super.viewDidLoad() buttonView.viewModel = presenter.removeButtonViewModel badgeImageView.viewModel = presenter.badgeImageViewModel titleLabel.content = presenter.titleLabelContent descriptionLabel.content = presenter.descriptionLabelContent presenter.dismissal .emit(weak: self) { (self) in self.dismiss(animated: true, completion: nil) } .disposed(by: disposeBag) presenter.viewDidLoad() } }
e6777d130d866166bbca81e12be9bbe6
28.73913
90
0.703216
false
false
false
false
abakhtin/ABProgressButton
refs/heads/master
ABProgressButton/ABProgressButton.swift
mit
1
// // ABProgreeButton.swift // DreamHome // // Created by Alex Bakhtin on 8/5/15. // Copyright © 2015 bakhtin. All rights reserved. // import UIKit /// ABProgressButton provides functionality for creating custom animation of UIButton during processing some task. /// Should be created in IB as custom class UIButton to prevent title of the button appearing. /// Provides mechanism for color inverting on highlitening and using tintColor for textColor(default behavior for system button) @IBDesignable @objc open class ABProgressButton: UIButton { @IBInspectable open var animationShift: CGSize = CGSize(width: 0.0, height: 0.0) /// **UI configuration. IBInspectable.** Allows change corner radius on default button state. Has default value of 5.0 @IBInspectable open var cornerRadius: CGFloat = 5.0 /// **UI configuration. IBInspectable.** Allows change border width on default button state. Has default value of 3.0 @IBInspectable open var borderWidth: CGFloat = 3.0 /// **UI configuration. IBInspectable.** Allows change border color on default button state. Has default value of control tintColor @IBInspectable open lazy var borderColor: UIColor = { return self.tintColor }() /// **UI configuration. IBInspectable.** Allows change circle radius on processing button state. Has default value of 20.0 @IBInspectable open var circleRadius: CGFloat = 20.0 /// **UI configuration. IBInspectable.** Allows change circle border width on processing button state. Has default value of 3.0 @IBInspectable open var circleBorderWidth: CGFloat = 3.0 /// **UI configuration. IBInspectable.** Allows change circle border color on processing button state. Has default value of control tintColor @IBInspectable open lazy var circleBorderColor: UIColor = { return self.tintColor }() /// **UI configuration. IBInspectable.** Allows change circle background color on processing button state. Has default value of UIColor.whiteColor() @IBInspectable open var circleBackgroundColor: UIColor = UIColor.white /// **UI configuration. IBInspectable.** Allows change circle cut angle on processing button state. /// Should have value between 0 and 360 degrees. Has default value of 45 degrees @IBInspectable open var circleCutAngle: CGFloat = 45.0 /// **UI configuration. IBInspectable.** /// If true, colors of content and background will be inverted on button highlightening. Image should be used as template for correct image color inverting. /// If false you should use default mechanism for text and images highlitening. /// Has default value of true @IBInspectable open var invertColorsOnHighlight: Bool = true /// **UI configuration. IBInspectable.** /// If true, tintColor whould be used for text, else value from UIButton.textColorForState() would be used. /// Has default value of true @IBInspectable open var useTintColorForText: Bool = true /** **Buttons states enum** - .Default: Default state of button with border line. - .Progressing: State of button without content, button has the form of circle with cut angle with rotation animation. */ public enum State { case `default`, progressing } /** **State changing** Should be used to change state of button from one state to another. All transitions between states would be animated. To update progress indicator use `progress` value */ open var progressState: State = .default { didSet { if(progressState == .default) { self.updateToDefaultStateAnimated(true)} if(progressState == .progressing) { self.updateToProgressingState()} self.updateProgressLayer() } } /** **State changing** Should be used to change progress indicator. Should have value from 0.0 to 1.0. `progressState` should be .Progressing to allow change progress(except nil value). */ open var progress: CGFloat? { didSet { if progress != nil { assert(self.progressState == .progressing, "Progress state should be .Progressing while changing progress value") } progress = progress == nil ? nil : min(progress!, CGFloat(1.0)) self.updateProgressLayer() } } // MARK : Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.privateInit() self.registerForNotifications() } override init(frame: CGRect) { super.init(frame: frame) self.privateInit() self.registerForNotifications() } override open func prepareForInterfaceBuilder() { self.privateInit() } deinit { self.unregisterFromNotifications() } fileprivate func privateInit() { if (self.useTintColorForText) { self.setTitleColor(self.tintColor, for: UIControlState()) } if (self.invertColorsOnHighlight) { self.setTitleColor(self.shapeBackgroundColor, for: UIControlState.highlighted) } self.layer.insertSublayer(self.shapeLayer, at: 0) self.layer.insertSublayer(self.crossLayer, at: 1) self.layer.insertSublayer(self.progressLayer, at: 2) self.updateToDefaultStateAnimated(false) } override open func layoutSubviews() { super.layoutSubviews() self.shapeLayer.frame = self.layer.bounds self.updateShapeLayer() self.crossLayer.frame = self.layer.bounds self.progressLayer.frame = self.layer.bounds self.bringSubview(toFront: self.imageView!) } override open var isHighlighted: Bool { didSet { if (self.invertColorsOnHighlight) { self.imageView?.tintColor = isHighlighted ? self.shapeBackgroundColor : self.circleBorderColor } self.crossLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor self.progressLayer.strokeColor = isHighlighted ? self.circleBackgroundColor.cgColor : self.circleBorderColor.cgColor if (isHighlighted) { self.shapeLayer.fillColor = (progressState == State.default) ? self.borderColor.cgColor : self.circleBorderColor.cgColor } else { self.shapeLayer.fillColor = (progressState == State.default) ? self.shapeBackgroundColor.cgColor : self.circleBackgroundColor.cgColor } } } // MARK : Methods used to update states fileprivate var shapeLayer = CAShapeLayer() fileprivate lazy var crossLayer: CAShapeLayer = { let crossLayer = CAShapeLayer() crossLayer.path = self.crossPath().cgPath crossLayer.strokeColor = self.circleBorderColor.cgColor return crossLayer }() fileprivate lazy var progressLayer: CAShapeLayer = { let progressLayer = CAShapeLayer() progressLayer.strokeColor = self.circleBorderColor.cgColor progressLayer.fillColor = UIColor.clear.cgColor return progressLayer }() fileprivate lazy var shapeBackgroundColor: UIColor = { return self.backgroundColor ?? self.circleBackgroundColor }() fileprivate func updateToDefaultStateAnimated(_ animated:Bool) { self.shapeLayer.strokeColor = self.borderColor.cgColor; self.shapeLayer.fillColor = self.shapeBackgroundColor.cgColor self.crossLayer.isHidden = true self.animateDefaultStateAnimated(animated) } fileprivate func updateToProgressingState() { self.titleLabel?.alpha = 0.0 self.shapeLayer.strokeColor = self.circleBorderColor.cgColor self.shapeLayer.fillColor = self.circleBackgroundColor.cgColor self.crossLayer.isHidden = false self.animateProgressingState(self.shapeLayer) } fileprivate func updateShapeLayer() { if self.progressState == .default { self.shapeLayer.path = self.defaultStatePath().cgPath } self.crossLayer.path = self.crossPath().cgPath } fileprivate func updateProgressLayer() { self.progressLayer.isHidden = (self.progressState != .progressing || self.progress == nil) if (self.progressLayer.isHidden == false) { let progressCircleRadius = self.circleRadius - self.circleBorderWidth let progressArcAngle = CGFloat(M_PI) * 2 * self.progress! - CGFloat(M_PI_2) let circlePath = UIBezierPath() let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) circlePath.addArc(withCenter: center, radius:progressCircleRadius, startAngle:CGFloat(-M_PI_2), endAngle:progressArcAngle, clockwise:true) circlePath.lineWidth = self.circleBorderWidth let updateProgressAnimation = CABasicAnimation(); updateProgressAnimation.keyPath = "path" updateProgressAnimation.fromValue = self.progressLayer.path updateProgressAnimation.toValue = circlePath.cgPath updateProgressAnimation.duration = progressUpdateAnimationTime self.progressLayer.path = circlePath.cgPath self.progressLayer.add(updateProgressAnimation, forKey: "update progress animation") } } // MARK : Methods used to animate states and transions between them fileprivate let firstStepAnimationTime = 0.3 fileprivate let secondStepAnimationTime = 0.15 fileprivate let textAppearingAnimationTime = 0.2 fileprivate let progressUpdateAnimationTime = 0.1 fileprivate func animateDefaultStateAnimated(_ animated: Bool) { if !animated { self.shapeLayer.path = self.defaultStatePath().cgPath self.titleLabel?.alpha = 1.0 self.showContentImage() } else { self.shapeLayer.removeAnimation(forKey: "rotation animation") let firstStepAnimation = CABasicAnimation(); firstStepAnimation.keyPath = "path" firstStepAnimation.fromValue = self.shapeLayer.path firstStepAnimation.toValue = self.animateToCircleReplacePath().cgPath firstStepAnimation.duration = secondStepAnimationTime self.shapeLayer.path = self.animateToCircleFakeRoundPath().cgPath self.shapeLayer.add(firstStepAnimation, forKey: "first step animation") let secondStepAnimation = CABasicAnimation(); secondStepAnimation.keyPath = "path" secondStepAnimation.fromValue = self.shapeLayer.path! secondStepAnimation.toValue = self.defaultStatePath().cgPath secondStepAnimation.beginTime = CACurrentMediaTime() + secondStepAnimationTime secondStepAnimation.duration = firstStepAnimationTime self.shapeLayer.path = self.defaultStatePath().cgPath self.shapeLayer.add(secondStepAnimation, forKey: "second step animation") let delay = secondStepAnimationTime + firstStepAnimationTime UIView.animate(withDuration: textAppearingAnimationTime, delay: delay, options: UIViewAnimationOptions(), animations: { () -> Void in self.titleLabel?.alpha = 1.0 }, completion: { (complete) -> Void in self.showContentImage() }) } } fileprivate func animateProgressingState(_ layer: CAShapeLayer) { let firstStepAnimation = CABasicAnimation(); firstStepAnimation.keyPath = "path" firstStepAnimation.fromValue = layer.path firstStepAnimation.toValue = self.animateToCircleFakeRoundPath().cgPath firstStepAnimation.duration = firstStepAnimationTime layer.path = self.animateToCircleReplacePath().cgPath layer.add(firstStepAnimation, forKey: "first step animation") let secondStepAnimation = CABasicAnimation(); secondStepAnimation.keyPath = "path" secondStepAnimation.fromValue = layer.path secondStepAnimation.toValue = self.progressingStatePath().cgPath secondStepAnimation.beginTime = CACurrentMediaTime() + firstStepAnimationTime secondStepAnimation.duration = secondStepAnimationTime layer.path = self.progressingStatePath().cgPath layer.add(secondStepAnimation, forKey: "second step animation") let animation = CABasicAnimation(); animation.keyPath = "transform.rotation"; animation.fromValue = 0 * M_PI animation.toValue = 2 * M_PI animation.repeatCount = Float.infinity animation.duration = 1.5 animation.beginTime = CACurrentMediaTime() + firstStepAnimationTime + secondStepAnimationTime layer.add(animation, forKey: "rotation animation") layer.anchorPoint = CGPoint(x: 0.5 + self.animationShift.width / self.bounds.size.width, y: 0.5 + self.animationShift.height / self.bounds.size.height) UIView.animate(withDuration: textAppearingAnimationTime, animations: { () -> Void in self.titleLabel?.alpha = 0.0 self.hideContentImage() }) } // MARK : Pathes creation for different states fileprivate func defaultStatePath() -> UIBezierPath { let bordersPath = UIBezierPath(roundedRect:self.bounds, cornerRadius:self.cornerRadius) bordersPath.lineWidth = self.borderWidth return bordersPath } fileprivate func progressingStatePath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let circlePath = UIBezierPath() let startAngle = self.circleCutAngle/180 * CGFloat(M_PI) let endAngle = 2 * CGFloat(M_PI) circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:startAngle, endAngle:endAngle, clockwise:true) circlePath.lineWidth = self.circleBorderWidth return circlePath } fileprivate func animateToCircleFakeRoundPath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let rect = CGRect(x: center.x - self.circleRadius, y: center.y - self.circleRadius, width: self.circleRadius * 2, height: self.circleRadius * 2) let bordersPath = UIBezierPath(roundedRect: rect, cornerRadius: self.circleRadius) bordersPath.lineWidth = self.borderWidth return bordersPath } fileprivate func animateToCircleReplacePath() -> UIBezierPath { let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let circlePath = UIBezierPath() circlePath.addArc(withCenter: center, radius:self.circleRadius, startAngle:CGFloat(0.0), endAngle:CGFloat(M_PI * 2), clockwise:true) circlePath.lineWidth = self.circleBorderWidth return circlePath } fileprivate func crossPath() -> UIBezierPath { let crossPath = UIBezierPath() let center = CGPoint(x: self.bounds.midX + self.animationShift.width, y: self.bounds.midY + self.animationShift.height) let point1 = CGPoint(x: center.x - self.circleRadius/2, y: center.y + self.circleRadius / 2) let point2 = CGPoint(x: center.x + self.circleRadius/2, y: center.y + self.circleRadius / 2) let point3 = CGPoint(x: center.x + self.circleRadius/2, y: center.y - self.circleRadius / 2) let point4 = CGPoint(x: center.x - self.circleRadius/2, y: center.y - self.circleRadius / 2) crossPath.move(to: point1) crossPath.addLine(to: point3) crossPath.move(to: point2) crossPath.addLine(to: point4) crossPath.lineWidth = self.circleBorderWidth return crossPath } // MARK : processing animation stopping while in background // Should be done to prevent animation broken on entering foreground fileprivate func registerForNotifications() { NotificationCenter.default.addObserver(self, selector:#selector(self.applicationDidEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector:#selector(self.applicationWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) } fileprivate func unregisterFromNotifications() { NotificationCenter.default.removeObserver(self) } func applicationDidEnterBackground(_ notification: Notification) { self.pauseLayer(self.layer) } func applicationWillEnterForeground(_ notification: Notification) { self.resumeLayer(self.layer) } fileprivate func pauseLayer(_ layer: CALayer) { let pausedTime = layer.convertTime(CACurrentMediaTime(), from:nil) layer.speed = 0.0 layer.timeOffset = pausedTime } fileprivate func resumeLayer(_ layer: CALayer) { let pausedTime = layer.timeOffset layer.speed = 1.0 layer.timeOffset = 0.0 layer.beginTime = 0.0 let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime layer.beginTime = timeSincePause } // MARK : Content images hiding // The only available way to make images hide is to set the object to nil // If you now any way else please help me here fileprivate var imageForNormalState: UIImage? fileprivate var imageForHighlitedState: UIImage? fileprivate var imageForDisabledState: UIImage? fileprivate func hideContentImage() { self.imageForNormalState = self.image(for: UIControlState()) self.setImage(UIImage(), for: UIControlState()) self.imageForHighlitedState = self.image(for: UIControlState.highlighted) self.setImage(UIImage(), for: UIControlState.highlighted) self.imageForDisabledState = self.image(for: UIControlState.disabled) self.setImage(UIImage(), for: UIControlState.disabled) } fileprivate func showContentImage() { if self.imageForNormalState != nil { self.setImage(self.imageForNormalState, for: UIControlState()); self.imageForNormalState = nil } if self.imageForHighlitedState != nil { self.setImage(self.imageForHighlitedState, for: UIControlState.highlighted) self.imageForHighlitedState = nil } if self.imageForDisabledState != nil { self.setImage(self.imageForDisabledState, for: UIControlState.disabled) self.imageForDisabledState = nil } } }
9b0944858a7ada9a174260f1ff16998d
47.119898
171
0.684409
false
false
false
false
cplaverty/KeitaiWaniKani
refs/heads/master
WaniKaniKit/Extensions/FMDatabaseAdditionsVariadic.swift
mit
1
// // FMDatabaseAdditionsVariadic.swift // FMDB // import Foundation import FMDB extension FMDatabase { /// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods /// /// :param: sql The SQL statement to be used. /// :param: values The NSArray of the arguments to be bound to the ? placeholders in the SQL. /// :param: completionHandler The closure to be used to call the appropriate FMDatabase method to return the desired value. /// /// :returns: This returns the T value if value is found. Returns nil if column is NULL or upon error. private func valueForQuery<T>(_ sql: String, values: [Any]?, completionHandler: (FMResultSet) -> T?) throws -> T? { var result: T? let rs = try executeQuery(sql, values: values) defer { rs.close() } if rs.next() && !rs.columnIndexIsNull(0) { result = completionHandler(rs) } return result } /// This is a rendition of stringForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns string value if value is found. Returns nil if column is NULL or upon error. func stringForQuery(_ sql: String, values: [Any]? = nil) throws -> String? { return try valueForQuery(sql, values: values) { $0.string(forColumnIndex: 0) } } /// This is a rendition of intForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns integer value if value is found. Returns nil if column is NULL or upon error. func intForQuery(_ sql: String, values: [Any]? = nil) throws -> Int32? { return try valueForQuery(sql, values: values) { $0.int(forColumnIndex: 0) } } /// This is a rendition of longForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns long value if value is found. Returns nil if column is NULL or upon error. func longForQuery(_ sql: String, values: [Any]? = nil) throws -> Int? { return try valueForQuery(sql, values: values) { $0.long(forColumnIndex: 0) } } /// This is a rendition of boolForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error. func boolForQuery(_ sql: String, values: [Any]? = nil) throws -> Bool? { return try valueForQuery(sql, values: values) { $0.bool(forColumnIndex: 0) } } /// This is a rendition of doubleForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Double value if value is found. Returns nil if column is NULL or upon error. func doubleForQuery(_ sql: String, values: [Any]? = nil) throws -> Double? { return try valueForQuery(sql, values: values) { $0.double(forColumnIndex: 0) } } /// This is a rendition of dateForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error. func dateForQuery(_ sql: String, values: [Any]? = nil) throws -> Date? { return try valueForQuery(sql, values: values) { $0.date(forColumnIndex: 0) } } /// This is a rendition of dataForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error. func dataForQuery(_ sql: String, values: [Any]? = nil) throws -> Data? { return try valueForQuery(sql, values: values) { $0.data(forColumnIndex: 0) } } }
c08a846dabd20d79e6baefc1f72925a5
42.318966
127
0.642985
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/SoftwareVideoLayerFrameManager.swift
gpl-2.0
1
// // SoftwareVideoLayerFrameManager.swift // Telegram // // Created by Mikhail Filimonov on 26/05/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import Foundation import TGUIKit import Postbox import TelegramCore import SwiftSignalKit import CoreMedia private let applyQueue = Queue() private let workers = ThreadPool(threadCount: 3, threadPriority: 0.2) private var nextWorker = 0 final class SoftwareVideoLayerFrameManager { private var dataDisposable = MetaDisposable() private let source = Atomic<SoftwareVideoSource?>(value: nil) private var baseTimestamp: Double? private var frames: [MediaTrackFrame] = [] private var minPts: CMTime? private var maxPts: CMTime? private let account: Account private let resource: MediaResource private let secondaryResource: MediaResource? private let queue: ThreadPoolQueue private let layerHolder: SampleBufferLayer private var rotationAngle: CGFloat = 0.0 private var aspect: CGFloat = 1.0 private var layerRotationAngleAndAspect: (CGFloat, CGFloat)? private let hintVP9: Bool var onRender:(()->Void)? init(account: Account, fileReference: FileMediaReference, layerHolder: SampleBufferLayer) { var resource = fileReference.media.resource var secondaryResource: MediaResource? self.hintVP9 = fileReference.media.isWebm for attribute in fileReference.media.attributes { if case .Video = attribute { if let thumbnail = fileReference.media.videoThumbnails.first { resource = thumbnail.resource secondaryResource = fileReference.media.resource } } } nextWorker += 1 self.account = account self.resource = resource self.secondaryResource = secondaryResource self.queue = ThreadPoolQueue(threadPool: workers) self.layerHolder = layerHolder } deinit { self.dataDisposable.dispose() } func start() { let secondarySignal: Signal<String?, NoError> if let secondaryResource = self.secondaryResource { secondarySignal = self.account.postbox.mediaBox.resourceData(secondaryResource, option: .complete(waitUntilFetchStatus: false)) |> map { data -> String? in if data.complete { return data.path } else { return nil } } } else { secondarySignal = .single(nil) } let firstReady: Signal<String, NoError> = combineLatest( self.account.postbox.mediaBox.resourceData(self.resource, option: .complete(waitUntilFetchStatus: false)), secondarySignal ) |> mapToSignal { first, second -> Signal<String, NoError> in if let second = second { return .single(second) } else if first.complete { return .single(first.path) } else { return .complete() } } self.dataDisposable.set((firstReady |> deliverOn(applyQueue)).start(next: { [weak self] path in if let strongSelf = self { let _ = strongSelf.source.swap(SoftwareVideoSource(path: path, hintVP9: strongSelf.hintVP9, unpremultiplyAlpha: true)) } })) } func tick(timestamp: Double) { applyQueue.async { if self.baseTimestamp == nil && !self.frames.isEmpty { self.baseTimestamp = timestamp } if let baseTimestamp = self.baseTimestamp { var index = 0 var latestFrameIndex: Int? while index < self.frames.count { if baseTimestamp + self.frames[index].position.seconds + self.frames[index].duration.seconds <= timestamp { latestFrameIndex = index //print("latestFrameIndex = \(index)") } index += 1 } if let latestFrameIndex = latestFrameIndex { let frame = self.frames[latestFrameIndex] for i in (0 ... latestFrameIndex).reversed() { self.frames.remove(at: i) } if self.layerHolder.layer.status == .failed { self.layerHolder.layer.flush() } self.layerHolder.layer.enqueue(frame.sampleBuffer) DispatchQueue.main.async { self.onRender?() } } } self.poll() } } private var polling = false private func poll() { if self.frames.count < 2 && !self.polling, self.source.with ({ $0 != nil }) { self.polling = true let minPts = self.minPts let maxPts = self.maxPts self.queue.addTask(ThreadPoolTask { [weak self] state in if state.cancelled.with({ $0 }) { return } if let strongSelf = self { var frameAndLoop: (MediaTrackFrame?, CGFloat, CGFloat, Bool)? var hadLoop = false for _ in 0 ..< 1 { frameAndLoop = (strongSelf.source.with { $0 })?.readFrame(maxPts: maxPts) if let frameAndLoop = frameAndLoop { if frameAndLoop.0 != nil || minPts != nil { break } else { if frameAndLoop.3 { hadLoop = true } //print("skip nil frame loop: \(frameAndLoop.3)") } } else { break } } if let loop = frameAndLoop?.3, loop { hadLoop = true } applyQueue.async { if let strongSelf = self { strongSelf.polling = false if let (_, rotationAngle, aspect, _) = frameAndLoop { strongSelf.rotationAngle = rotationAngle strongSelf.aspect = aspect } var noFrame = false if let frame = frameAndLoop?.0 { if strongSelf.minPts == nil || CMTimeCompare(strongSelf.minPts!, frame.position) < 0 { var position = CMTimeAdd(frame.position, frame.duration) for _ in 0 ..< 1 { position = CMTimeAdd(position, frame.duration) } strongSelf.minPts = position } strongSelf.frames.append(frame) strongSelf.frames.sort(by: { lhs, rhs in if CMTimeCompare(lhs.position, rhs.position) < 0 { return true } else { return false } }) //print("add frame at \(CMTimeGetSeconds(frame.position))") //let positions = strongSelf.frames.map { CMTimeGetSeconds($0.position) } //print("frames: \(positions)") } else { noFrame = true //print("not adding frames") } if hadLoop { strongSelf.maxPts = strongSelf.minPts strongSelf.minPts = nil //print("loop at \(strongSelf.minPts)") } if strongSelf.source.with ({ $0 == nil }) || noFrame { delay(0.2, onQueue: applyQueue.queue, closure: { [weak strongSelf] in strongSelf?.poll() }) } else { strongSelf.poll() } } } } }) } } }
9dd12aeb6959b8fd7424a69f999fe055
38.849558
139
0.458694
false
false
false
false
rsaenzi/MyMoviesListApp
refs/heads/master
MyMoviesListApp/MyMoviesListApp/AuthInteractor.swift
mit
1
// // AuthInteractor.swift // MyMoviesListApp // // Created by Rigoberto Sáenz Imbacuán on 5/29/17. // Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved. // import Foundation import Moya import SwiftKeychainWrapper typealias GetDeviceCodeCallback = (_ authInfo: GetDeviceCodeResponse?, _ code: APIResponseCode) -> Void typealias GetTokenCallback = (_ success: Bool, _ code: APIResponseCode) -> Void class AuthInteractor { fileprivate var deviceCodeInfo: GetDeviceCodeResponse? func hasSavedCredentials() -> Bool { guard let _: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiAccessToken.rawValue), let _: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiRefreshToken.rawValue) else { return false } return true } func getDeviceCode(using clientId: String, callback: @escaping GetDeviceCodeCallback) { deviceCodeInfo = nil let provider = MoyaProvider<APIService>(endpointClosure: APIService.endpointClosure) provider.request(.getDeviceCode(clientId: clientId)) { [weak self] result in guard let `self` = self else { callback(nil, .referenceError) return } switch result { case let .success(moyaResponse): self.handleSuccessDeviceCode(moyaResponse, callback) case .failure(_): callback(nil, .connectionError) return } } } fileprivate func handleSuccessDeviceCode(_ response: Response, _ callback: GetDeviceCodeCallback) { guard response.statusCode == 200 else { callback(nil, .httpCodeError) return } var json: String = "" do { json = try response.mapString() } catch { callback(nil, .parsingError) return } guard json.characters.count > 0 else { callback(nil, .emptyJsonError) return } guard let result = GetDeviceCodeResponse(JSONString: json) else { callback(nil, .mappingError) return } deviceCodeInfo = result callback(result, .success) } func getToken(callback: @escaping GetTokenCallback) { guard let info = deviceCodeInfo else { callback(false, .missingParameterError) return } let provider = MoyaProvider<APIService>(endpointClosure: APIService.endpointClosure) provider.request(.getToken(code: info.deviceCode, clientId: APICredentials.traktClientId, clientSecret: APICredentials.traktClientSecret)) { [weak self] result in guard let `self` = self else { callback(false, .referenceError) return } switch result { case let .success(moyaResponse): self.handleSuccessToken(moyaResponse, callback) case .failure(_): callback(false, .connectionError) return } } } fileprivate func handleSuccessToken(_ response: Response, _ callback: GetTokenCallback) { var json: String = "" do { json = try response.mapString() } catch { callback(false, .parsingError) return } guard response.statusCode == 200 else { callback(false, .httpCodeError) return } guard json.characters.count > 0 else { callback(false, .emptyJsonError) return } guard let result = GetTokenResponse(JSONString: json) else { callback(false, .mappingError) return } let saveAccessToken: Bool = KeychainWrapper.standard.set(result.accessToken, forKey: KeychainKey.apiAccessToken.rawValue) let saveRefreshToken: Bool = KeychainWrapper.standard.set(result.refreshToken, forKey: KeychainKey.apiRefreshToken.rawValue) guard saveAccessToken, saveRefreshToken else { callback(false, .dataSaveError) return } callback(true, .success) } }
29e4076e5e0c9577f1ab604194eb0818
30.226027
132
0.559553
false
false
false
false
zjzsliyang/Potions
refs/heads/master
Lift/Lift/ViewController.swift
mit
1
// // ViewController.swift // Lift // // Created by Yang Li on 24/04/2017. // Copyright © 2017 Yang Li. All rights reserved. // import UIKit import PSOLib import Buckets class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIPopoverPresentationControllerDelegate { let floorCount = 20 let liftCount = 5 let distanceX: CGFloat = 170 let distanceY: CGFloat = 60 let liftVelocity: Double = 0.3 let liftDelay: Double = 0.5 var upDownButton = [[UIButton]]() var liftDisplay = [UILabel]() var lift = [UIView]() var liftCurrentPosition: [CGFloat] = Array(repeating: 1290.0, count: 5) var liftCurrentButton: [[Bool]] = Array(repeating: Array(repeating: false, count: 20), count: 5) var liftCurrentDirection: [Int] = Array(repeating: 0, count: 5) // 0 represents static, 1 represents Up Direction, -1 represents Down Direction var liftBeingSet: [Bool] = Array(repeating: false, count: 5) var liftDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRandomDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRequestQueue = Queue<Int>() var liftInAnimation: [Int] = Array(repeating: 0, count: 5) // var sAWT: [Double] = Array(repeating: 0, count: 5) // var sART: [Double] = Array(repeating: 0, count: 5) // var sRPC: [Double] = Array(repeating: 0, count: 5) @IBAction func modeChosen(_ sender: UISwitch) { weak var weakSelf = self var fucktimer = Timer() if sender.isOn { fucktimer = Timer(timeInterval: 1, repeats: true) { (fucktimer) in let randomFloor = Int(arc4random() % UInt32((weakSelf?.floorCount)!)) let randomDirection = Int(arc4random() % 2) if (!(weakSelf?.upDownButton[randomFloor][randomDirection].isSelected)!) && (weakSelf?.upDownButton[randomFloor][randomDirection].isEnabled)! { weakSelf?.buttonTapped(sender: self.upDownButton[randomFloor][randomDirection]) } } RunLoop.current.add(fucktimer, forMode: .defaultRunLoopMode) fucktimer.fire() } else { if (fucktimer.isValid) { fucktimer.invalidate() } } } override func viewDidLoad() { super.viewDidLoad() initFloorSign() initUpDownButton() initLiftDisplay() initLift() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let deviceModelName = UIDevice.current.modelName if deviceModelName != "iPad Pro 12.9" { let alertController = UIAlertController(title: "CAUTION", message: "This app can only run on the\n 12.9-inch iPad Pro", preferredStyle: .alert) let alertActionOk = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertActionOk) present(alertController, animated: true, completion: nil) } let timer = Timer(timeInterval: 0.1, repeats: true) { (timer) in for i in 0..<self.liftCount { self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: i), liftIndex: i) self.updateCurrentDirection(liftIndex: i) } } RunLoop.current.add(timer, forMode: .commonModes) timer.fire() } func initLift() { var liftX: CGFloat = 250 for liftIndex in 0..<liftCount { let liftUnit = UIView(frame: CGRect(x: liftX, y: 1290, width: 33.6, height: 45.7)) let liftUnitButton = UIButton(frame: CGRect(x: 0, y: 0, width: liftUnit.frame.width, height: liftUnit.frame.height)) liftUnit.addSubview(liftUnitButton) liftUnitButton.setImage(UIImage(named: "lift"), for: .normal) liftUnitButton.tag = liftIndex liftUnitButton.addTarget(self, action: #selector(popoverChosenView(sender:)), for: .touchUpInside) self.view.addSubview(liftUnit) lift.append(liftUnit) liftX = liftX + distanceX } } func popoverChosenView(sender: UIButton) { let layout = UICollectionViewFlowLayout() let chosenView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 300, height: 240), collectionViewLayout: layout) chosenView.delegate = self chosenView.dataSource = self chosenView.tag = sender.tag liftBeingSet[sender.tag] = true chosenView.register(LiftButtonViewCell.self, forCellWithReuseIdentifier: "cell") chosenView.backgroundColor = UIColor.lightGray let popoverViewController = UIViewController() popoverViewController.modalPresentationStyle = .popover popoverViewController.popoverPresentationController?.sourceView = sender popoverViewController.popoverPresentationController?.sourceRect = sender.bounds popoverViewController.preferredContentSize = chosenView.bounds.size popoverViewController.popoverPresentationController?.delegate = self popoverViewController.view.addSubview(chosenView) self.present(popoverViewController, animated: true, completion: nil) } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { for i in 0..<liftCount { if liftBeingSet[i] { print("current lift: " + String(i)) inLiftScan(liftIndex: i) liftBeingSet[i] = false } } } func inLiftScan(liftIndex: Int) { for i in 0..<floorCount { if liftCurrentButton[liftIndex][i] { liftDestinationDeque[liftIndex].enqueueFirst(i) liftCurrentButton[liftIndex][i] = false } } _ = liftDestinationDeque[liftIndex].sorted() liftAnimation(liftIndex: liftIndex) } func randomGenerateDestination(destinationTag: Int) -> Int { if destinationTag < 0 { return Int(arc4random() % UInt32(abs(destinationTag + 1))) + 1 } else { return floorCount - Int(arc4random() % UInt32(floorCount - destinationTag)) } } func updateCurrentDirection(liftIndex: Int) { if lift[liftIndex].layer.presentation()?.position == nil { liftCurrentDirection[liftIndex] = 0 return } let currentPresentationY = lift[liftIndex].layer.presentation()?.frame.minY if currentPresentationY! < liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 1 } if currentPresentationY! > liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = -1 } if currentPresentationY! == liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 0 } liftCurrentPosition[liftIndex] = currentPresentationY! return } func naiveDispatch() { if liftRequestQueue.isEmpty { return } let currentRequest = liftRequestQueue.dequeue() print("current Request: " + String(currentRequest)) if currentRequest < 0 { var closestLiftDistance = 20 var closestLift = -1 for i in 0..<liftCount { if liftCurrentDirection[i] <= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) { closestLift = i closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(-currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } else { var closestLiftDistance = 20 var closestLift = -1 for j in 0..<liftCount { if liftCurrentDirection[j] >= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) { closestLift = j closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } } /* func SPODispatch() { let spaceMin: [Int] = Array(repeating: 0, count: liftRequestQueue.count) let spaceMax: [Int] = Array(repeating: 5, count: liftRequestQueue.count) let searchSpace = PSOSearchSpace(boundsMin: spaceMin, max: spaceMax) let optimizer = PSOStandardOptimizer2011(for: searchSpace, optimum: 0, fitness: { (positions: UnsafeMutablePointer<Double>?, dimensions: Int32) -> Double in // AWT: Average Waiting Time var liftTempDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var fMax: [Int] = Array(repeating: 0, count: self.liftCount) var fMin: [Int] = Array(repeating: 0, count: self.liftCount) for i in 0..<self.liftRequestQueue.count { switch Int((positions?[i])!) { case 0: liftTempDestinationDeque[0].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[0].first!) case 1: liftTempDestinationDeque[1].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[1].first!) case 2: liftTempDestinationDeque[2].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[2].first!) case 3: liftTempDestinationDeque[3].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[3].first!) default: liftTempDestinationDeque[4].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[4].first!) } } // ART: Average Riding Time // EC: Energy Consumption // Total var sFitnessFunc: Double = 0 return sFitnessFunc }, before: nil, iteration: nil) { (optimizer: PSOStandardOptimizer2011?) in // to do } optimizer?.operation.start() } */ func liftAnimation(liftIndex: Int) { if liftDestinationDeque[liftIndex].isEmpty { return } liftInAnimation[liftIndex] = liftInAnimation[liftIndex] + 1 var destinationFloor: Int = 0 if liftCurrentDirection[liftIndex] == 0 { let currentFloor = getLiftCurrentFloor(liftIndex: liftIndex) if abs(currentFloor - (liftDestinationDeque[liftIndex].first! + 1)) < abs(currentFloor - (liftDestinationDeque[liftIndex].last! + 1)) { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } } else { if liftCurrentDirection[liftIndex] > 0 { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } } print("destination floor: " + String(destinationFloor)) let destinationDistance = CGFloat(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex)) * (distanceY) let destinationTime = liftVelocity * abs(Double(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex))) UIView.animate(withDuration: destinationTime, delay: liftDelay, options: .curveEaseInOut, animations: { self.lift[liftIndex].center.y = self.lift[liftIndex].center.y - destinationDistance }, completion: { (finished) in self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: liftIndex), liftIndex: liftIndex) self.updateUpDownButton(destinationTag: (self.liftCurrentDirection[liftIndex] * destinationFloor), liftIndex: liftIndex) if !self.liftDestinationDeque[liftIndex].isEmpty { self.liftAnimation(liftIndex: liftIndex) } self.liftInAnimation[liftIndex] = self.liftInAnimation[liftIndex] - 1 }) } func updateUpDownButton(destinationTag: Int, liftIndex: Int) { print("destinationTag: " + String(destinationTag)) if destinationTag == 0 { if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][0].isSelected = false upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][1].isSelected = false } return } if destinationTag > 0 { if upDownButton[destinationTag - 1][0].isSelected { upDownButton[destinationTag - 1][0].isSelected = false } } else { if upDownButton[-destinationTag - 1][1].isSelected { upDownButton[-destinationTag - 1][1].isSelected = false } } if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[abs(destinationTag) - 1][0].isSelected = false upDownButton[abs(destinationTag) - 1][1].isSelected = false } } func getLiftCurrentFloor(liftIndex: Int) -> Int { if lift[liftIndex].layer.presentation()?.position != nil { return (Int(floor((1290 - (lift[liftIndex].layer.presentation()!.frame.minY)) / distanceY)) + 1) } else { print("returning model layer position") return (Int(floor((1290 - (lift[liftIndex].layer.model().frame.minY)) / distanceY)) + 1) } } func updateLiftDisplay(currentFloor: Int, liftIndex: Int) { liftDisplay[liftIndex].text = String(currentFloor) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! LiftButtonViewCell cell.liftButton?.setTitle(convertNumber(number: indexPath.row + 1), for: .normal) cell.liftButton?.setTitleColor(UIColor.blue, for: .selected) cell.liftButton?.tag = collectionView.tag cell.liftButton?.addTarget(self, action: #selector(liftButtonTapped(sender:)), for: .touchUpInside) return cell } func liftButtonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected let currentLift = sender.tag let currentFloorButton = convertLetter(letter: sender.currentTitle!) liftCurrentButton[currentLift][currentFloorButton - 1] = !liftCurrentButton[currentLift][currentFloorButton - 1] } func convertLetter(letter: String) -> Int { let asciiLetter = Character(letter).asciiValue if asciiLetter < 65 { return asciiLetter - 48 } else { return asciiLetter - 55 } } func convertNumber(number: Int) -> String { if number < 10 { return String(number) } else { return String(describing: UnicodeScalar(number - 10 + 65)!) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return floorCount } func initFloorSign() { var floorY: CGFloat = 1300 for floorNum in 0..<floorCount { let floorNumView = UIImageView(image: UIImage(named: String(floorNum + 1))) floorNumView.frame = CGRect(x: 36, y: floorY, width: 30, height: 30) floorNumView.contentMode = .scaleAspectFill self.view.addSubview(floorNumView) floorY = floorY - distanceY } } func initLiftDisplay() { var liftDisplayX: CGFloat = 220 for _ in 0..<liftCount { let liftDisplayUnit = UILabel(frame: CGRect(x: liftDisplayX, y: 100, width: 50, height: 50)) liftDisplayUnit.text = String(1) liftDisplayUnit.font = UIFont(name: "Digital-7", size: 50) liftDisplayUnit.textAlignment = .right self.view.addSubview(liftDisplayUnit) liftDisplay.append(liftDisplayUnit) liftDisplayX = liftDisplayX + distanceX } } func initUpDownButton() { var upDownButtonY: CGFloat = 1305 for i in 0..<floorCount { var upDownButtonUnit = [UIButton]() let upDownButtonUp = UIButton(frame: CGRect(x: 90, y: upDownButtonY, width: 25, height: 25)) upDownButtonUp.setImage(UIImage(named: "up"), for: .normal) upDownButtonUp.setImage(UIImage(named: "up-active"), for: .selected) upDownButtonUp.tag = i + 1 upDownButtonUp.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) let upDownButtonDown = UIButton(frame: CGRect(x: 130, y: upDownButtonY, width: 25, height: 25)) upDownButtonDown.setImage(UIImage(named: "down"), for: .normal) upDownButtonDown.setImage(UIImage(named: "down-active"), for: .selected) upDownButtonDown.tag = -(i + 1) upDownButtonDown.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) upDownButtonUnit.append(upDownButtonUp) upDownButtonUnit.append(upDownButtonDown) self.view.addSubview(upDownButtonUp) self.view.addSubview(upDownButtonDown) upDownButton.append(upDownButtonUnit) upDownButtonY = upDownButtonY - distanceY } upDownButton[0][1].isEnabled = false upDownButton[19][0].isEnabled = false } func buttonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { liftRequestQueue.enqueue(sender.tag) naiveDispatch() for i in 0..<liftCount { if liftInAnimation[i] == 0 { liftAnimation(liftIndex: i) } } } } } class LiftButtonViewCell: UICollectionViewCell { var liftButton: UIButton? override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { liftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) liftButton?.titleLabel?.font = UIFont(name: "Elevator Buttons", size: 50) self.addSubview(liftButton!) } } extension Character { var asciiValue: Int { get { let unicodeString = String(self).unicodeScalars return Int(unicodeString[unicodeString.startIndex].value) } } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPad6,7", "iPad6,8": return "iPad Pro 12.9" case "i386", "x86_64": return "Simulator" default: return identifier } } }
0a257b6644a40bb54a669687174c5cfb
38.505219
171
0.685568
false
false
false
false
tjarratt/Xcode-Better-Refactor-Tools
refs/heads/master
Fake4SwiftKit/Use Cases/Parse Swift Protocol/Dependencies/XMASFakeProtocolPersister.swift
mit
3
import Foundation @objc open class XMASFakeProtocolPersister : NSObject { fileprivate(set) open var fileManager : XMASFileManager fileprivate(set) open var protocolFaker : XMASSwiftProtocolFaking @objc public init(protocolFaker: XMASSwiftProtocolFaking, fileManager: XMASFileManager) { self.fileManager = fileManager self.protocolFaker = protocolFaker } let generatedFakesDir = "fakes" @objc open func persistFakeForProtocol( _ protocolDecl : ProtocolDeclaration, nearSourceFile: String) throws -> FakeProtocolPersistResults { let dirContainingSource = (nearSourceFile as NSString).deletingLastPathComponent let fakesDir = (dirContainingSource as NSString).appendingPathComponent(generatedFakesDir) let fakeFileName = ["Fake", protocolDecl.name, ".swift"].joined(separator: "") let pathToFake = (fakesDir as NSString).appendingPathComponent(fakeFileName) if !fileManager.fileExists(atPath: fakesDir as String, isDirectory: nil) { try self.fileManager.createDirectory( atPath: fakesDir, withIntermediateDirectories: true, attributes: nil) } do { let fileContents = try self.protocolFaker.fakeForProtocol(protocolDecl) let fileData : Data = fileContents.data(using: String.Encoding.utf8)! _ = fileManager.createFile(atPath: pathToFake, contents: fileData, attributes: nil) } catch let error as NSError { throw error } return FakeProtocolPersistResults.init( path: pathToFake, containingDir: generatedFakesDir ) } } @objc open class FakeProtocolPersistResults : NSObject { fileprivate(set) open var pathToFake : String fileprivate(set) open var directoryName : String public init(path: String, containingDir: String) { pathToFake = path directoryName = containingDir super.init() } }
5e5e9bca03d5cb7f48d0fdf25cd7d516
33.793103
98
0.677899
false
false
false
false
jjochen/photostickers
refs/heads/master
MessagesExtension/Services/StickerFlowLayout.swift
mit
1
// // StickerFlowLayout.swift // PhotoStickers // // Created by Jochen Pfeiffer on 09.04.17. // Copyright © 2017 Jochen Pfeiffer. All rights reserved. // import UIKit struct StickerFlowLayout { private static func minimumItemWidth(in _: CGRect) -> CGFloat { return 90 } static func sectionInsets(in _: CGRect) -> UIEdgeInsets { let inset = CGFloat(12) return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) } static func minimumInterItemSpacing(in _: CGRect) -> CGFloat { return 10 } static func minimumLineSpacing(in bounds: CGRect) -> CGFloat { return minimumInterItemSpacing(in: bounds) } static func itemSize(in bounds: CGRect) -> CGSize { let sectionInsets = self.sectionInsets(in: bounds) let minimumInterItemSpacing = self.minimumInterItemSpacing(in: bounds) let minimumItemWidth = self.minimumItemWidth(in: bounds) let numberOfItems = floor((bounds.width - sectionInsets.left - sectionInsets.right + minimumInterItemSpacing) / (minimumItemWidth + minimumInterItemSpacing)) let maxItemWidth = (bounds.size.width - sectionInsets.left - sectionInsets.right - (numberOfItems - 1) * minimumInterItemSpacing) / numberOfItems let sideLength = floor(maxItemWidth) return CGSize(width: sideLength, height: sideLength) } }
309ac7d73c5edba130623dbc125ede99
32.878049
165
0.692585
false
false
false
false
chrisamanse/iOS-NSDate-Utilities
refs/heads/master
NSDate_Extensions/NSDate+Comparable.swift
mit
1
// // NSDate+Comparable.swift // NSDate_Extensions // // Created by Chris Amanse on 5/12/15. // Copyright (c) 2015 Joe Christopher Paul Amanse. All rights reserved. // // This code is licensed under the MIT License // // 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 func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.isEqualToDate(rhs) } extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } public func >(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedDescending } public func <=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs < rhs || lhs.compare(rhs) == .OrderedSame } public func >=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs > rhs || lhs.compare(rhs) == .OrderedSame }
27fcaa255b5afe4784e922909a2b9204
37.102041
81
0.723473
false
false
false
false
ReactiveKit/ReactiveAlamofire
refs/heads/master
Sources/Request.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import ReactiveKit extension DataRequest { public func toSignal() -> Signal<(URLRequest?, HTTPURLResponse?, Data?), NSError> { return Signal { observer in let request = self .response { response in if let error = response.error { observer.failed(error as NSError) } else { observer.next(response.request, response.response, response.data) observer.completed() } } request.resume() return BlockDisposable { request.cancel() } } } public func toSignal<S: DataResponseSerializerProtocol>(_ responseSerializer: S) -> Signal<S.SerializedObject, NSError> { return Signal { observer in let request = self.response(responseSerializer: responseSerializer) { response in switch response.result { case .success(let value): observer.next(value) observer.completed() case .failure(let error): observer.failed(error as NSError) } } request.resume() return BlockDisposable { request.cancel() } } } public func toDataSignal() -> Signal<Data, NSError> { return toSignal(DataRequest.dataResponseSerializer()) } public func toStringSignal(encoding: String.Encoding? = nil) -> Signal<String, NSError> { return toSignal(DataRequest.stringResponseSerializer(encoding: encoding)) } public func toJSONSignal(options: JSONSerialization.ReadingOptions = .allowFragments) -> Signal<Any, NSError> { return toSignal(DataRequest.jsonResponseSerializer(options: options)) } public func toPropertyListSignal(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Signal<Any, NSError> { return toSignal(DataRequest.propertyListResponseSerializer(options: options)) } } /// Streaming API extension DataRequest { public func toStreamingSignal() -> Signal<Data, NSError> { return Signal { observer in let request = self .stream { data in observer.next(data) }.response { response in if let error = response.error { observer.failed(error as NSError) } else { observer.completed() } } request.resume() return BlockDisposable { request.cancel() } } } // public func toStringStreamingSignal(delimiter: String, encoding: String.Encoding = .utf8) -> Signal<String, NSError> { // return toSignal() // .tryMap { data -> ReactiveKit.Result<String, NSError> in // if let string = String(data: data, encoding: encoding) { // return .success(string) // } else { // return .failure(NSError(domain: "toStringStreamingSignal: Could not decode string!", code: 0, userInfo: nil)) // } // } // .flatMapLatest { string in // Signal<String, NSError>.sequence(string.characters.map { String($0) }) // } // .split { character in // character == delimiter // } // .map { // $0.joined(separator: "") // } // } // // public func toJSONStreamingSignal(delimiter: String = "\n", encoding: String.Encoding = .utf8, options: JSONSerialization.ReadingOptions = .allowFragments) -> Signal<Any, NSError> { // return toStringStreamingSignal(delimiter: delimiter, encoding: encoding) // .map { message in // message.trimmingCharacters(in: .whitespacesAndNewlines) // } // .filter { message in // !message.isEmpty // } // .tryMap { message -> ReactiveKit.Result<Any, NSError> in // do { // guard let data = message.data(using: encoding) else { // return .failure(NSError(domain: "toJSONStreamingSignal: Could not encode string!", code: 0, userInfo: nil)) // } // let json = try JSONSerialization.jsonObject(with: data, options: options) // return .success(json) // } catch { // return .failure(error as NSError) // } // } // } } extension SignalProtocol { public func split(_ isDelimiter: @escaping (Element) -> Bool) -> Signal<[Element], Error> { return Signal { observer in var buffer: [Element] = [] return self.observe { event in switch event { case .next(let element): if isDelimiter(element) { observer.next(buffer) buffer.removeAll() } else { buffer.append(element) } case .completed: observer.completed() case .failed(let error): observer.failed(error) } } } } }
72ae83680cd7c9f5c9a53d5f345ea9db
31.657303
185
0.640977
false
false
false
false
Bunn/firefox-ios
refs/heads/master
Client/Frontend/Extensions/DevicePickerViewController.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import SnapKit protocol DevicePickerViewControllerDelegate { func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) } private struct DevicePickerViewControllerUX { static let TableHeaderRowHeight = CGFloat(50) static let TableHeaderTextFont = UIFont.systemFont(ofSize: 16) static let TableHeaderTextColor = UIColor.Photon.Grey50 static let TableHeaderTextPaddingLeft = CGFloat(20) static let DeviceRowTintColor = UIColor.Photon.Green60 static let DeviceRowHeight = CGFloat(50) static let DeviceRowTextFont = UIFont.systemFont(ofSize: 16) static let DeviceRowTextPaddingLeft = CGFloat(72) static let DeviceRowTextPaddingRight = CGFloat(50) } /// The DevicePickerViewController displays a list of clients associated with the provided Account. /// The user can select a number of devices and hit the Send button. /// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. /// That is up to it's delegate, who can listen for cancellation and success events. enum LoadingState { case LoadingFromCache case LoadingFromServer case Loaded } class DevicePickerViewController: UITableViewController { enum DeviceOrClient: Equatable { case client(RemoteClient) case device(RemoteDevice) var identifier: String? { switch self { case .client(let c): return c.fxaDeviceId case .device(let d): return d.id } } public static func == (lhs: DeviceOrClient, rhs: DeviceOrClient) -> Bool { switch (lhs, rhs) { case (.device(let a), .device(let b)): return a.id == b.id && a.lastAccessTime == b.lastAccessTime case (.client(let a), .client(let b)): return a == b // is equatable case (.device(_), .client(_)): return false case (.client(_), .device(_)): return false } } } var devicesAndClients = [DeviceOrClient]() var profile: Profile? var profileNeedsShutdown = true var pickerDelegate: DevicePickerViewControllerDelegate? var loadState = LoadingState.LoadingFromCache var selectedIdentifiers = Set<String>() // Stores DeviceOrClient.identifier // ShareItem has been added as we are now using this class outside of the ShareTo extension to provide Share To functionality // And in this case we need to be able to store the item we are sharing as we may not have access to the // url later. Currently used only when sharing an item from the Tab Tray from a Preview Action. var shareItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() title = Strings.SendToTitle refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem( title: Strings.SendToCancelButton, style: .plain, target: self, action: #selector(cancel) ) tableView.register(DevicePickerTableViewHeaderCell.self, forCellReuseIdentifier: DevicePickerTableViewHeaderCell.CellIdentifier) tableView.register(DevicePickerTableViewCell.self, forCellReuseIdentifier: DevicePickerTableViewCell.CellIdentifier) tableView.register(DevicePickerNoClientsTableViewCell.self, forCellReuseIdentifier: DevicePickerNoClientsTableViewCell.CellIdentifier) tableView.tableFooterView = UIView(frame: .zero) tableView.allowsSelection = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadCachedClients() } override func numberOfSections(in tableView: UITableView) -> Int { if devicesAndClients.isEmpty { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if devicesAndClients.isEmpty { return 1 } else { if section == 0 { return 1 } else { return devicesAndClients.count } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if !devicesAndClients.isEmpty { if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: DevicePickerTableViewHeaderCell.CellIdentifier, for: indexPath) as! DevicePickerTableViewHeaderCell } else { let clientCell = tableView.dequeueReusableCell(withIdentifier: DevicePickerTableViewCell.CellIdentifier, for: indexPath) as! DevicePickerTableViewCell let item = devicesAndClients[indexPath.row] switch item { case .client(let client): clientCell.nameLabel.text = client.name clientCell.clientType = client.type == "mobile" ? .Mobile : .Desktop case .device(let device): clientCell.nameLabel.text = device.name clientCell.clientType = device.type == "mobile" ? .Mobile : .Desktop } if let id = item.identifier { clientCell.checked = selectedIdentifiers.contains(id) } cell = clientCell } } else { if self.loadState == .Loaded { cell = tableView.dequeueReusableCell(withIdentifier: DevicePickerNoClientsTableViewCell.CellIdentifier, for: indexPath) as! DevicePickerNoClientsTableViewCell } else { cell = UITableViewCell(style: .default, reuseIdentifier: "ClientCell") } } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if devicesAndClients.isEmpty || indexPath.section != 1 { return } tableView.deselectRow(at: indexPath, animated: true) guard let id = devicesAndClients[indexPath.row].identifier else { return } if selectedIdentifiers.contains(id) { selectedIdentifiers.remove(id) } else { selectedIdentifiers.insert(id) } UIView.performWithoutAnimation { // if the selected cell is off-screen when the tableview is first shown, the tableview will re-scroll without disabling animation tableView.reloadRows(at: [indexPath], with: .none) } navigationItem.rightBarButtonItem?.isEnabled = !selectedIdentifiers.isEmpty } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if !devicesAndClients.isEmpty { if indexPath.section == 0 { return DevicePickerViewControllerUX.TableHeaderRowHeight } else { return DevicePickerViewControllerUX.DeviceRowHeight } } else { return tableView.frame.height } } fileprivate func ensureOpenProfile() -> Profile { // If we were not given a profile, open the default profile. This happens in case we are called from an app // extension. That also means that we need to shut down the profile, otherwise the app extension will be // terminated when it goes into the background. if let profile = self.profile { // Re-open the profile if it was shutdown. This happens when we run from an app extension, where we must // make sure that the profile is only open for brief moments of time. if profile.isShutdown { profile._reopen() } return profile } let profile = BrowserProfile(localName: "profile") self.profile = profile self.profileNeedsShutdown = true return profile } // Load cached clients from the profile, triggering a sync to fetch newer data. fileprivate func loadCachedClients() { guard let profile = self.ensureOpenProfile() as? BrowserProfile else { return } self.loadState = .LoadingFromCache // Load and display the cached clients. // Don't shut down the profile here: we immediately call `reloadClients`. profile.remoteClientsAndTabs.getRemoteDevices() >>== { devices in profile.remoteClientsAndTabs.getClients().uponQueue(.main) { result in withExtendedLifetime(profile) { guard let clients = result.successValue else { return } self.update(devices: devices, clients: clients, endRefreshing: false) self.reloadClients() } } } } fileprivate func reloadClients() { guard let profile = self.ensureOpenProfile() as? BrowserProfile, let account = profile.getAccount() else { return } self.loadState = .LoadingFromServer account.updateFxADevices(remoteDevices: profile.remoteClientsAndTabs) >>== { profile.remoteClientsAndTabs.getRemoteDevices() >>== { devices in profile.getClients().uponQueue(.main) { result in guard let clients = result.successValue else { return } withExtendedLifetime(profile) { self.loadState = .Loaded // If we are running from an app extension then make sure we shut down the profile as soon as we are // done with it. if self.profileNeedsShutdown { profile._shutdown() } self.loadState = .Loaded self.update(devices: devices, clients: clients, endRefreshing: true) } } } } } fileprivate func update(devices: [RemoteDevice], clients: [RemoteClient], endRefreshing: Bool) { assert(Thread.isMainThread) guard let profile = self.ensureOpenProfile() as? BrowserProfile, let account = profile.getAccount() else { return } let fxaDeviceIds = devices.compactMap { $0.id } let newRemoteDevices = devices.filter { account.commandsClient.sendTab.isDeviceCompatible($0) } func findClient(forDevice device: RemoteDevice) -> RemoteClient? { return clients.find({ $0.fxaDeviceId == device.id }) } let oldRemoteClients = devices.filter { !account.commandsClient.sendTab.isDeviceCompatible($0) } .compactMap { findClient(forDevice: $0) } let fullList = newRemoteDevices.sorted { $0.id ?? "" > $1.id ?? "" }.map { DeviceOrClient.device($0) } + oldRemoteClients.sorted { $0.guid ?? "" > $1.guid ?? "" }.map { DeviceOrClient.client($0) } // Sort the lists, and compare guids and modified, to see if the list has changed and tableview needs reloading. let isSame = fullList.elementsEqual(devicesAndClients) { new, old in new == old // equatable } guard !isSame else { if endRefreshing { refreshControl?.endRefreshing() } return } devicesAndClients = fullList if devicesAndClients.isEmpty { navigationItem.rightBarButtonItem = nil } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.SendToSendButtonTitle, style: .done, target: self, action: #selector(self.send)) navigationItem.rightBarButtonItem?.isEnabled = false } tableView.reloadData() if endRefreshing { refreshControl?.endRefreshing() } } @objc func refresh() { if let refreshControl = self.refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPoint(x: 0, y: height) } reloadClients() } @objc func cancel() { pickerDelegate?.devicePickerViewControllerDidCancel(self) } @objc func send() { guard let profile = self.ensureOpenProfile() as? BrowserProfile else { return } var pickedItems = [DeviceOrClient]() for id in selectedIdentifiers { if let item = devicesAndClients.find({ $0.identifier == id }) { pickedItems.append(item) } } profile.remoteClientsAndTabs.getRemoteDevices().uponQueue(.main) { result in guard let devices = result.successValue else { return } let pickedDevices: [RemoteDevice] = pickedItems.compactMap { item in switch item { case .client(let client): return devices.find { client.fxaDeviceId == $0.id } case .device(let device): return device } } self.pickerDelegate?.devicePickerViewController(self, didPickDevices: pickedDevices) } // Replace the Send button with a loading indicator since it takes a while to sync // up our changes to the server. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(width: 25, height: 25)) loadingIndicator.color = UIColor.Photon.Grey60 loadingIndicator.startAnimating() let customBarButton = UIBarButtonItem(customView: loadingIndicator) self.navigationItem.rightBarButtonItem = customBarButton } } class DevicePickerTableViewHeaderCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewSectionHeader" let nameLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.font = DevicePickerViewControllerUX.TableHeaderTextFont nameLabel.text = Strings.SendToDevicesListTitle nameLabel.textColor = DevicePickerViewControllerUX.TableHeaderTextColor nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(DevicePickerViewControllerUX.TableHeaderTextPaddingLeft) make.centerY.equalTo(self) make.right.equalTo(self) } preservesSuperviewLayoutMargins = false layoutMargins = .zero separatorInset = .zero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ClientType: String { case Mobile = "deviceTypeMobile" case Desktop = "deviceTypeDesktop" } class DevicePickerTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewCell" var nameLabel: UILabel var checked: Bool = false { didSet { self.accessoryType = checked ? .checkmark : .none } } var clientType = ClientType.Mobile { didSet { self.imageView?.image = UIImage(named: clientType.rawValue) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { nameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) nameLabel.font = DevicePickerViewControllerUX.DeviceRowTextFont nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = .byWordWrapping self.tintColor = DevicePickerViewControllerUX.DeviceRowTintColor self.preservesSuperviewLayoutMargins = false self.selectionStyle = .none } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(DevicePickerViewControllerUX.DeviceRowTextPaddingLeft) make.centerY.equalTo(self.snp.centerY) make.right.equalTo(self.snp.right).offset(-DevicePickerViewControllerUX.DeviceRowTextPaddingRight) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class DevicePickerNoClientsTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerNoClientsTableViewCell" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupHelpView(contentView, introText: Strings.SendToNoDevicesFound, showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise. // Move the separator off screen separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
8046cdbe4814c22c9ff6b46a1be70adb
38.986486
187
0.644418
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift
mit
1
// // PreCompLayer.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// A layer that holds another animation composition. final class PreCompLayerModel: LayerModel { /// The reference ID of the precomp. let referenceID: String /// A value that remaps time over time. let timeRemapping: KeyframeGroup<Vector1D>? /// Precomp Width let width: Double /// Precomp Height let height: Double private enum CodingKeys : String, CodingKey { case referenceID = "refId" case timeRemapping = "tm" case width = "w" case height = "h" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PreCompLayerModel.CodingKeys.self) self.referenceID = try container.decode(String.self, forKey: .referenceID) self.timeRemapping = try container.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .timeRemapping) self.width = try container.decode(Double.self, forKey: .width) self.height = try container.decode(Double.self, forKey: .height) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(referenceID, forKey: .referenceID) try container.encode(timeRemapping, forKey: .timeRemapping) try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) } }
2da518848b4de56cb6243429a65f7d05
28.98
108
0.710474
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/01098-no-stacktrace.swift
apache-2.0
65
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck private class B<C> { init(c: C) { s { func g<U>(h: (A, U) -> U) -> (A, U) -> U { } func f() { } } struct d<f : e, g: e where g.h == f.h> { } protocol e { } enum A : String { case b = "" } let c: A? = nil if c == .b {
a4009ae65f99c56e6c18f980e1895bac
23.6
79
0.645528
false
false
false
false
salvonos/CityPicker
refs/heads/master
Pod/Classes/CityPickerClass.swift
mit
1
// // CityPickerClass.swift // Noemi Official // // Created by LIVECT LAB on 13/03/2016. // Copyright © 2016 LIVECT LAB. All rights reserved. // import UIKit class cityPickerClass { class func getNations() -> (nations:[String], allValues:NSDictionary){ var nations = [String]() var allValues = NSDictionary() let podBundle = NSBundle(forClass: self) if let path = podBundle.pathForResource("countriesToCities", ofType: "json") { do { let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe) do { let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let nationsArray = jsonResult.allKeys as! [String] let sortedNations = nationsArray.sort { $0 < $1 } nations = sortedNations allValues = jsonResult } catch {} } catch {} } return (nations, allValues) } }
4b3bc2f9c59ce3b1203d82104dfa1ca3
25.816327
169
0.520548
false
false
false
false
Malecks/PALette
refs/heads/master
Palette/InterfaceIdiom.swift
mit
1
// // InterfaceIdiom.swift // PALette // // Created by Alexander Mathers on 2016-03-26. // Copyright © 2016 Malecks. All rights reserved. // import Foundation import UIKit enum UIUserInterfaceIdiom : Int { case unspecified case phone case pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 }
f6fae90592b355f3cf50ac0c945f6dc5
39.612903
124
0.698173
false
false
false
false
Qmerce/ios-sdk
refs/heads/master
Apester/ViewControllers/Strip/APEMultipleStripsViewController.swift
mit
1
// // APEMultipleStripsViewController.swift // ApisterKitDemo // // Created by Hasan Sa on 24/02/2019. // Copyright © 2019 Apester. All rights reserved. // import UIKit import ApesterKit class APEMultipleStripsViewController: UIViewController { @IBOutlet private weak var collectionView: UICollectionView! { didSet { collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false } } private var channelTokens: [String] = StripConfigurationsFactory.tokens override func viewDidLoad() { super.viewDidLoad() // update stripView delegates channelTokens.forEach { APEViewService.shared.stripView(for: $0)?.delegate = self } } } extension APEMultipleStripsViewController: UICollectionViewDataSource { static let emptyCellsCount = 2 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.channelTokens.count * Self.emptyCellsCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReuseCellIdentifier", for: indexPath) as! APEStripCollectionViewCell if indexPath.row % Self.emptyCellsCount == 0 { let token = self.channelTokens[indexPath.row / Self.emptyCellsCount] let stripView = APEViewService.shared.stripView(for: token) cell.show(stripView: stripView, containerViewController: self) } return cell } } extension APEMultipleStripsViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.row % Self.emptyCellsCount == 0 { let token = self.channelTokens[indexPath.row / Self.emptyCellsCount] let stripView = APEViewService.shared.stripView(for: token) return CGSize(width: collectionView.bounds.width, height: stripView?.height ?? 0) } return CGSize(width: collectionView.bounds.width, height: 220) } } extension APEMultipleStripsViewController: APEStripViewDelegate { func stripView(_ stripView: APEStripView, didCompleteAdsForChannelToken token: String) { } func stripView(_ stripView: APEStripView, didUpdateHeight height: CGFloat) { self.collectionView.reloadData() } func stripView(_ stripView: APEStripView, didFinishLoadingChannelToken token: String) {} func stripView(_ stripView: APEStripView, didFailLoadingChannelToken token: String) { DispatchQueue.main.async { APEViewService.shared.unloadStripViews(with: [token]) self.collectionView.reloadData() } } }
1917f4003432d4c963f7e4cc52fa5042
36.21519
160
0.713946
false
false
false
false
abitofalchemy/auralML
refs/heads/master
Sandbox/STBlueMS_iOS/W2STApp/MainApp/Demo/BlueVoice/W2STBlueVoiceViewController.swift
bsd-3-clause
1
/** My notes: ** https://stackoverflow.com/questions/34361991/saving-recorded-audio-swift ** https://stackoverflow.com/questions/28233219/recording-1-second-audio-ios * * Removing the ASR code * Work to ** */ import Foundation import MediaPlayer import BlueSTSDK import AVFoundation //import UIKit /** * Audio callback called when an audio buffer can be reused * userData: pointer to our SyncQueue with the buffer to reproduce * queue: audio queue where the buffer will be played * buffer: audio buffer that must be filled */ fileprivate func audioCallback(usedData:UnsafeMutableRawPointer?, queue:AudioQueueRef, buffer:AudioQueueBufferRef){ // SampleQueue *ptr = (SampleQueue*) userData let sampleQueuePtr = usedData?.assumingMemoryBound(to: BlueVoiceSyncQueue.self) //NSData* data = sampleQueuePtr->pop(); let data = sampleQueuePtr?.pointee.pop(); //uint8* temp = (uint8*) buffer->mAudioData let temp = buffer.pointee.mAudioData.assumingMemoryBound(to: UInt8.self); //memcpy(temp,data) data?.copyBytes(to: temp, count: Int(buffer.pointee.mAudioDataByteSize)); // Enqueuing an audio queue buffer after writing to disk? AudioQueueEnqueueBuffer(queue, buffer, 0, nil); } public class W2STBlueVoiceViewController: BlueMSDemoTabViewController, BlueVoiceSelectDelegate, BlueSTSDKFeatureDelegate, AVAudioRecorderDelegate, UITableViewDataSource{ /* sa> see below for base decarasion */ private static let ASR_LANG_PREF="W2STBlueVoiceViewController.AsrLangValue" private static let DEFAULT_ASR_LANG=BlueVoiceLangauge.ENGLISH private static let CODEC="ADPCM" private static let SAMPLING_FREQ_kHz = 8; private static let NUM_CHANNELS = UInt32(1); /* * number of byffer that the sysmte will allocate, each buffer will contain * a sample recived trought the ble connection */ private static let NUM_BUFFERS=18; private static let SAMPLE_TYPE_SIZE = UInt32(2)//UInt32(MemoryLayout<UInt16>.size); //each buffer contains 40 audio sample private static let BUFFER_SIZE = (40*SAMPLE_TYPE_SIZE); /** object used to check if the user has an internet connection */ private var mInternetReachability: Reachability?; //////////////////// GUI reference //////////////////////////////////////// @IBOutlet weak var mCodecLabel: UILabel! @IBOutlet weak var mAddAsrKeyButton: UIButton! @IBOutlet weak var mSampligFreqLabel: UILabel! @IBOutlet weak var mAsrStatusLabel: UILabel! @IBOutlet weak var mSelectLanguageButton: UIButton! @IBOutlet weak var mRecordButton: UIButton! @IBOutlet weak var mPlayButton: UIButton! @IBOutlet weak var mAsrResultsTableView: UITableView! @IBOutlet weak var mAsrRequestStatusLabel: UILabel! private var engine:BlueVoiceASREngine?; private var mFeatureAudio:BlueSTSDKFeatureAudioADPCM?; private var mFeatureAudioSync:BlueSTSDKFeatureAudioADPCMSync?; private var mAsrResults:[String] = []; var recordingSession: AVAudioSession! var whistleRecorder: AVAudioRecorder! var whistlePlayer: AVAudioPlayer! var playButton: UIButton! /////////////////// AUDIO ////////////////////////////////////////////////// //https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription private var mAudioFormat = AudioStreamBasicDescription( mSampleRate: Float64(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000), mFormatID: kAudioFormatLinearPCM, mFormatFlags: kLinearPCMFormatFlagIsSignedInteger, mBytesPerPacket: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE * W2STBlueVoiceViewController.NUM_CHANNELS, mFramesPerPacket: 1, mBytesPerFrame: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE*W2STBlueVoiceViewController.NUM_CHANNELS, mChannelsPerFrame: W2STBlueVoiceViewController.NUM_CHANNELS, mBitsPerChannel: UInt32(8) * W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE, mReserved: 0); //audio queue where play the sample private var queue:AudioQueueRef?; //queue of audio buffer to play private var buffers:[AudioQueueBufferRef?] = Array(repeating:nil, count: NUM_BUFFERS) //syncronized queue used to store the audio sample from the node // when an audio buffer is free it will be filled with sample from this object private var mSyncAudioQueue:BlueVoiceSyncQueue?; //variable where store the audio before send to an speech to text service private var mRecordData:Data?; /////////CONTROLLER STATUS//////////// private var mIsMute:Bool=false; private var mIsRecording:Bool=false; override public func viewDidLoad(){ super.viewDidLoad() view.backgroundColor = UIColor.gray //set the constant string mCodecLabel.text = mCodecLabel.text!+W2STBlueVoiceViewController.CODEC mSampligFreqLabel.text = mSampligFreqLabel.text!+String(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz)+" kHz" newLanguageSelected(getDefaultLanguage()); mAsrResultsTableView.dataSource=self; /* ** here I add ** */ recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try recordingSession.setActive(true) recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { self.loadRecordingUI() } else { self.loadFailUI() } } } } catch { self.loadFailUI() } // UI mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) } func loadRecordingUI() { // mRecordButton = UIButton() mRecordButton.translatesAutoresizingMaskIntoConstraints = false mRecordButton.setTitle("Tap to Record", for: .normal) mRecordButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1) mRecordButton.addTarget(self, action: #selector(onRecordButtonPressed(_:)), for: .touchUpInside) // stackView.addArrangedSubview(recordButton) playButton = UIButton() playButton.translatesAutoresizingMaskIntoConstraints = false playButton.setTitle("Tap to Play", for: .normal) playButton.isHidden = true playButton.alpha = 0 playButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1) playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside) // stackView.addArrangedSubview(playButton) } func loadFailUI() { let failLabel = UILabel() failLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) failLabel.text = "Recording failed: please ensure the app has access to your microphone." failLabel.numberOfLines = 0 // self.view.addArrangedSubview(failLabel) self.view.addSubview(failLabel) } class func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } class func getWhistleURL() -> URL { NSLog("test: getting the file url"); return getDocumentsDirectory().appendingPathComponent("whistle.m4a") } /* * enable the ble audio stremaing and initialize the audio queue */ override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); mFeatureAudio = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCM.self) as! BlueSTSDKFeatureAudioADPCM?; mFeatureAudioSync = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCMSync.self) as! BlueSTSDKFeatureAudioADPCMSync?; //if both feature are present enable the audio if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{ audio.add(self); audioSync.add(self); self.node.enableNotification(audio); self.node.enableNotification(audioSync); initAudioQueue(); initRecability(); NSLog(">> audio features ARE present!!") }else{ NSLog(">> both features are not present!!") } } /** * stop the ble audio streaming and the audio queue */ override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated); if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{ deInitAudioQueue(); audio.remove(self); audioSync.remove(self); self.node.disableNotification(audio); self.node.disableNotification(audioSync); } } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated); engine?.destroyListener(); } private func initAudioQueue(){ //create the queue where store the sample mSyncAudioQueue = BlueVoiceSyncQueue(size: W2STBlueVoiceViewController.NUM_BUFFERS); //create the audio queue AudioQueueNewOutput(&mAudioFormat,audioCallback, &mSyncAudioQueue,nil, nil, 0, &queue); //create the system audio buffer that will be filled with the data inside the mSyncAudioQueue for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{ AudioQueueAllocateBuffer(queue!, W2STBlueVoiceViewController.BUFFER_SIZE, &buffers[i]); if let buffer = buffers[i]{ buffer.pointee.mAudioDataByteSize = W2STBlueVoiceViewController.BUFFER_SIZE; memset(buffer.pointee.mAudioData,0,Int(W2STBlueVoiceViewController.BUFFER_SIZE)); AudioQueueEnqueueBuffer(queue!, buffer, 0, nil); } }//for //start playing the audio AudioQueueStart(queue!, nil); mIsMute=false; } /// free the audio initialized audio queues private func deInitAudioQueue(){ AudioQueueStop(queue!, true); for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{ if let buffer = buffers[i]{ AudioQueueFreeBuffer(queue!,buffer); } } } /// function called when the net state change /// /// - Parameter notifier: object where read the net state private func onReachabilityChange(_ notifier:Reachability?){ let netStatus = notifier?.currentReachabilityStatus(); if let status = netStatus{ if(status == NotReachable){ mAsrStatusLabel.text="Disabled"; }else{ NSLog("attemping to load ASR Engine"); loadAsrEngine(getDefaultLanguage()); } } } /// register this class as a observer of the net state private func initRecability(){ NotificationCenter.default.addObserver(forName:Notification.Name.reachabilityChanged, object:nil, queue:nil) { notification in if(!(notification.object is Reachability)){ return; } let notificaitonObj = notification.object as! Reachability?; self.onReachabilityChange(notificaitonObj); } mInternetReachability = Reachability.forInternetConnection(); mInternetReachability?.startNotifier(); onReachabilityChange(mInternetReachability); } private func deInitRecability(){ mInternetReachability?.stopNotifier(); } /// get the selected language for the asr engine /// /// - Returns: <#return value description#> public func getDefaultLanguage()->BlueVoiceLangauge{ // let lang = loadAsrLanguage(); return W2STBlueVoiceViewController.DEFAULT_ASR_LANG; } /// called when the user select a new language for the asr /// it store this information an reload the engine /// /// - Parameter language: language selected public func newLanguageSelected(_ language:BlueVoiceLangauge){ // loadAsrEngine(language); // storeAsrLanguage(language); mSelectLanguageButton.setTitle(language.rawValue, for:UIControlState.normal) } /// load the language from the user preference /// /// - Returns: language stored in the preference or the default one // private func loadAsrLanguage()->BlueVoiceLangauge?{ // let userPref = UserDefaults.standard; // let langString = userPref.string(forKey: W2STBlueVoiceViewController.ASR_LANG_PREF); // if let str = langString{ // return BlueVoiceLangauge(rawValue: str); // } // return nil; // } /// store in the preference the selected language /// /// - Parameter language: language to store private func storeAsrLanguage(_ language:BlueVoiceLangauge){ let userPref = UserDefaults.standard; userPref.setValue(language.rawValue, forKey:W2STBlueVoiceViewController.ASR_LANG_PREF); } /// register this class as a delegate of the BlueVoiceSelectLanguageViewController /// /// - Parameters: /// - segue: segue to prepare /// - sender: object that start the segue override public func prepare(for segue: UIStoryboardSegue, sender: Any?) { let dest = segue.destination as? BlueVoiceSelectLanguageViewController; if let dialog = dest{ dialog.delegate=self; } } /// call when the user press the mute button, it mute/unmute the audio /// /// - Parameter sender: button where the user click @IBAction func onMuteButtonClick(_ sender: UIButton) { var img:UIImage?; if(!mIsMute){ img = UIImage(named:"volume_off"); AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); }else{ img = UIImage(named:"volume_on"); AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); } mIsMute = !mIsMute; sender.setImage(img, for:.normal); } /// check that the audio engine has a valid service key /// /// - Returns: true if the service has a valid service key or it does not need a key, /// false otherwise private func checkAsrKey() -> Bool{ if let engine = engine{ if(engine.needAuthKey && !engine.hasLoadedAuthKey()){ showErrorMsg("Please add the engine key", title: "Engine Fail", closeController: false); return false;// orig bool is False }else{ return true; } } return false; } /// Start the voice to text, if the engine can manage the continuos recognition private func onContinuousRecognizerStart(){ // NSLog("Entered on cont recognizer start"); // guard checkAsrKey() else{ // return; // } // mRecordButton.setTitle("Stop recongition", for: .normal); // if(!mIsMute){ // AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); // } // engine?.startListener(); // mIsRecording=true; } /// Stop a continuos recognition private func onContinuousRecognizerStop(){ // mIsRecording=false; // if(!mIsMute){ // AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); // } // if let engine = engine{ // engine.stopListener(); // setRecordButtonTitle(engine); // } } /// Start a non continuos voice to text service private func onRecognizerStart(){ /* Unused: guard checkAsrKey() else{ return; }*/ if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); } let audioURL = W2STBlueVoiceViewController.getWhistleURL() print(audioURL.absoluteString) mRecordData = Data(); engine?.startListener(); mIsRecording=true; let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { // 5 whistleRecorder = try AVAudioRecorder(url: audioURL, settings: settings) whistleRecorder.delegate = self whistleRecorder.record() } catch { finishRecording(success: false) } } /// Stop a non continuos voice to text service, and send the recorded data /// to the service private func onRecognizerStop(){ print ("RECOGNIZER STOP..."); mIsRecording=false; mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) // print (mIsRecording); if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0); } if let engine = engine{ if(mRecordData != nil){ print ("Data is not nil"); // _ = engine.sendASRRequest(audio: mRecordData!, callback: self); mRecordData=nil; } engine.stopListener(); setRecordButtonTitle(engine); print ("setRecordButtonTitle") } } /// set the starting value for the record button /// who is calling on this? /// - Parameter asrEngine: voice to text engine that will be used private func setRecordButtonTitle(_ asrEngine: BlueVoiceASREngine!){ let recorTitle = asrEngine.hasContinuousRecognizer ? "Start recongition" : "Keep press to record" print ("mIsRecording:",mIsRecording) mRecordButton.setTitle(recorTitle, for: .normal); } /// call when the user release the record button, it stop a non contiuos /// voice to text /// /// - Parameter sender: button released @IBAction func onRecordButtonRelease(_ sender: UIButton) { if (engine?.hasContinuousRecognizer == false){ print ("onRecordButton Released") // onRecognizerStop(); } } /// call when the user press the record buttom, it start the voice to text /// service /// /// - Parameter sender: button pressed @IBAction func onRecordButtonPressed(_ sender: UIButton) { print("Button Pressed"); // engine?.hasContinousRecognizer does not work, so it will be taken out for now // if let hasContinuousRecognizer = engine?.hasContinuousRecognizer{ // if (hasContinuousRecognizer){ // if(mIsRecording){ // NSLog("Is recording"); // onContinuousRecognizerStop(); // }else{ // onContinuousRecognizerStart(); // // }//if isRecording // }else{ if (mIsRecording) { onRecognizerStop() mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1) mRecordButton.setTitle("Keep Pressed to Record!!!!!!!", for: .normal); }else{ onRecognizerStart(); // in this func we set the mIsRecording mRecordButton.setTitle("Stop Recording", for: .normal); mRecordButton.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1) engine?.startListener(); mIsRecording=true; } // }//if hasContinuos // }else{ print ("not engine has cont recognizer"); }//if let if(!mIsMute){ AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0); } }//onRecordButtonPressed public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { NSLog("audioRecorderDidFinishRecording"); if !flag { finishRecording(success: false) } } /// call when the user press the add key button, it show the popup to insert /// the key /// /// - Parameter sender: button pressed @IBAction func onAddAsrKeyButtonClick(_ sender: UIButton) { let insertKeyDialog = engine?.getAuthKeyDialog(); if let viewContoller = insertKeyDialog { viewContoller.modalPresentationStyle = .popover; self.present(viewContoller, animated: false, completion: nil); let presentationController = viewContoller.popoverPresentationController; presentationController?.sourceView = sender; presentationController?.sourceRect = sender.bounds }//if let } /// create a new voice to text service that works with the selected language /// /// - Parameter language: voice language private func loadAsrEngine(_ language:BlueVoiceLangauge){ if(engine != nil){ engine!.destroyListener(); } let samplingRateHz = UInt((W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000)) engine = BlueVoiceASREngineUtil.getEngine(samplingRateHz:samplingRateHz,language: language); if let asrEngine = engine{ mAsrStatusLabel.text = asrEngine.name; mAddAsrKeyButton.isHidden = !asrEngine.needAuthKey; let asrTitle = asrEngine.hasLoadedAuthKey() ? "Change Service Key" : "Add Service Key"; mAddAsrKeyButton.setTitle(asrTitle, for:UIControlState.normal) setRecordButtonTitle(asrEngine); } } func finishRecording(success: Bool) { view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1) whistleRecorder.stop() whistleRecorder = nil if success { mRecordButton.setTitle("(again)Tap to Re-record", for: .normal) // if playButton.isHidden { // UIView.animate(withDuration: 0.35) { [unowned self] in // self.playButton.isHidden = false // self.playButton.alpha = 1 // } // } // navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTapped)) } else { mRecordButton.setTitle("(start)Tap to Record", for: .normal) let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } func playTapped() { let audioURL = W2STBlueVoiceViewController.getWhistleURL() do { whistlePlayer = try AVAudioPlayer(contentsOf: audioURL) whistlePlayer.play() } catch { let ac = UIAlertController(title: "Playback failed", message: "Problem playing your whistle; please try re-recording.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } /////////////////////// BlueSTSDKFeatureDelegate /////////////////////////// /// call when the BlueSTSDKFeatureAudioADPCM has new data, it will enque the data /// to be play by the sistem and send it to the asr service if it is recording the audio /// /// - Parameters: /// - feature: feature that generate the new data /// - sample: new data private func didAudioUpdate(_ feature: BlueSTSDKFeatureAudioADPCM, sample: BlueSTSDKFeatureSample){ let sampleData = BlueSTSDKFeatureAudioADPCM.getLinearPCMAudio(sample); if let data = sampleData{ mSyncAudioQueue?.push(data: data) if(mIsRecording){ // if(engine!.hasContinuousRecognizer){ // _ = engine!.sendASRRequest(audio: data, callback: self); // }else{ if(mRecordData != nil){ objc_sync_enter(mRecordData); mRecordData?.append(data); objc_sync_exit(mRecordData); // }// mRecordData!=null } } // else { print ("not recording");} //if is Recording }//if data!=null } /// call when the BlueSTSDKFeatureAudioADPCMSync has new data, it is used to /// correclty decode the data from the the BlueSTSDKFeatureAudioADPCM feature /// /// - Parameters: /// - feature: feature that generate new data /// - sample: new data private func didAudioSyncUpdate(_ feature: BlueSTSDKFeatureAudioADPCMSync, sample: BlueSTSDKFeatureSample){ // NSLog("test"); mFeatureAudio?.audioManager.setSyncParam(sample); } /// call when a feature gets update /// /// - Parameters: /// - feature: feature that get update /// - sample: new feature data public func didUpdate(_ feature: BlueSTSDKFeature, sample: BlueSTSDKFeatureSample) { if(feature .isKind(of: BlueSTSDKFeatureAudioADPCM.self)){ self.didAudioUpdate(feature as! BlueSTSDKFeatureAudioADPCM, sample: sample); } if(feature .isKind(of: BlueSTSDKFeatureAudioADPCMSync.self)){ self.didAudioSyncUpdate(feature as! BlueSTSDKFeatureAudioADPCMSync, sample: sample); } } //////////////////////////BlueVoiceAsrRequestCallback/////////////////////////// /// callback call when the asr engin has a positive results, the reult table /// will be updated wit the new results /// /// - Parameter text: world say from the user func onAsrRequestSuccess(withText text:String ){ print("ASR Success:"+text); mAsrResults.append(text); DispatchQueue.main.async { self.mAsrResultsTableView.reloadData(); self.mAsrRequestStatusLabel.isHidden=true; } } /// callback when some error happen during the voice to text translation /// /// - Parameter error: error during the voice to text translation func onAsrRequestFail(error:BlueVoiceAsrRequestError){ print("ASR Fail:"+error.rawValue.description); DispatchQueue.main.async { self.mAsrRequestStatusLabel.text = error.description; self.mAsrRequestStatusLabel.isHidden=false; if(self.mIsRecording){ //if an error happen during the recording, stop it if(self.engine!.hasContinuousRecognizer){ self.onContinuousRecognizerStop(); }else{ self.onRecognizerStop(); } } } } /////////////////////// TABLE VIEW DATA DELEGATE ///////////////////////// public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return mAsrResults.count; } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ var cell = tableView.dequeueReusableCell(withIdentifier: "AsrResult"); if (cell == nil){ cell = UITableViewCell(style: .default, reuseIdentifier: "AsrResult"); cell?.selectionStyle = .none; } cell?.textLabel?.text=mAsrResults[indexPath.row]; return cell!; } }
7a91797bd31aab92e45f4cf77acec021
36.782205
160
0.610053
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
refs/heads/master
DNSwiftProject/DNSwiftProject/Classes/Expend/DNTool/LocalNotificationHelper.swift
apache-2.0
1
// // LocalNotificationHelper.swift // DNSwiftProject // // Created by mainone on 16/12/23. // Copyright © 2016年 wjn. All rights reserved. // https://github.com/AhmettKeskin/LocalNotificationHelper import UIKit import AVKit class LocalNotificationHelper: NSObject { let LOCAL_NOTIFICATION_CATEGORY : String = "LocalNotificationCategory" // MARK: - Shared Instance class func sharedInstance() -> LocalNotificationHelper { struct Singleton { static var sharedInstance = LocalNotificationHelper() } return Singleton.sharedInstance } // MARK: - Schedule Notification func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, userInfo: [NSObject: AnyObject]?) { let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, soundName: String, userInfo: [NSObject: AnyObject]?){ let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, soundName: String, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: ["key" as NSObject: key as AnyObject], soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } // MARK: - Present Notification func presentNotificationWithKey(key: String, title: String, message: String, soundName: String, userInfo: [NSObject: AnyObject]?) { let notification = notificationWithTitle(key: key, title: title, message: message, date: nil, userInfo: ["key" as NSObject: key as AnyObject], soundName: nil, hasAction: true) UIApplication.shared.presentLocalNotificationNow(notification) } // MARK: - Create Notification func notificationWithTitle(key : String, title: String, message: String, date: NSDate?, userInfo: [NSObject: AnyObject]?, soundName: String?, hasAction: Bool) -> UILocalNotification { var dct : Dictionary<String,AnyObject> = userInfo as! Dictionary<String,AnyObject> dct["key"] = String(stringLiteral: key) as AnyObject? let notification = UILocalNotification() notification.alertAction = title notification.alertBody = message notification.userInfo = dct notification.soundName = soundName ?? UILocalNotificationDefaultSoundName notification.fireDate = date as Date? notification.hasAction = hasAction return notification } func getNotificationWithKey(key : String) -> UILocalNotification { var notif : UILocalNotification? for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ notif = notification break } return notif! } func cancelNotification(key : String){ for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ UIApplication.shared.cancelLocalNotification(notification) break } } func getAllNotifications() -> [UILocalNotification]? { return UIApplication.shared.scheduledLocalNotifications } func cancelAllNotifications() { UIApplication.shared.cancelAllLocalNotifications() } func registerUserNotificationWithActionButtons(actions : [UIUserNotificationAction]){ let category = UIMutableUserNotificationCategory() category.identifier = LOCAL_NOTIFICATION_CATEGORY category.setActions(actions, for: UIUserNotificationActionContext.default) let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: NSSet(object: category) as? Set<UIUserNotificationCategory>) UIApplication.shared.registerUserNotificationSettings(settings) } func registerUserNotification(){ let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) } func createUserNotificationActionButton(identifier : String, title : String) -> UIUserNotificationAction{ let actionButton = UIMutableUserNotificationAction() actionButton.identifier = identifier actionButton.title = title actionButton.activationMode = UIUserNotificationActivationMode.background actionButton.isAuthenticationRequired = true actionButton.isDestructive = false return actionButton } }
d90fee0e9ce443b75a023591c9bd7d76
44.438462
190
0.701541
false
false
false
false
gnachman/iTerm2
refs/heads/master
SearchableComboListView/SearchableComboListViewController.swift
gpl-2.0
2
// // SearchableComboListViewController.swift // SearchableComboListView // // Created by George Nachman on 1/24/20. // import AppKit @objc(iTermSearchableComboListViewControllerDelegate) protocol SearchableComboListViewControllerDelegate: NSObjectProtocol { func searchableComboListViewController(_ listViewController: SearchableComboListViewController, didSelectItem item: SearchableComboViewItem?) } class SearchableComboListViewController: NSViewController { @IBOutlet public weak var tableView: SearchableComboTableView! @IBOutlet public weak var searchField: NSSearchField! @IBOutlet public weak var visualEffectView: NSVisualEffectView! private var closeOnSelect = true @objc(delegate) @IBOutlet public weak var delegate: SearchableComboListViewControllerDelegate? let groups: [SearchableComboViewGroup] public var selectedItem: SearchableComboViewItem? { didSet { let _ = view tableViewController!.selectedTag = selectedItem?.tag ?? -1 } } public var insets: NSEdgeInsets { let frame = view.convert(searchField.bounds, from: searchField) return NSEdgeInsets(top: NSMaxY(view.bounds) - NSMaxY(frame), left: NSMinX(frame), bottom: 0, right: NSMaxX(view.bounds) - NSMaxX(frame)) } public var tableViewController: SearchableComboTableViewController? init(groups: [SearchableComboViewGroup]) { self.groups = groups super.init(nibName: "SearchableComboView", bundle: Bundle(for: SearchableComboListViewController.self)) } override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { preconditionFailure() } required init?(coder: NSCoder) { preconditionFailure() } public override func awakeFromNib() { tableViewController = SearchableComboTableViewController(tableView: tableView, groups: groups) tableViewController?.delegate = self visualEffectView.blendingMode = .behindWindow; visualEffectView.material = .menu; visualEffectView.state = .active; } func item(withTag tag: Int) -> SearchableComboViewItem? { for group in groups { for item in group.items { if item.tag == tag { return item } } } return nil } } extension SearchableComboListViewController: NSTextFieldDelegate { @objc(controlTextDidChange:) public func controlTextDidChange(_ obj: Notification) { tableViewController?.filter = searchField.stringValue } public override func viewWillAppear() { view.window?.makeFirstResponder(searchField) } } extension SearchableComboListViewController: SearchableComboTableViewControllerDelegate { func searchableComboTableViewController(_ tableViewController: SearchableComboTableViewController, didSelectItem item: SearchableComboViewItem?) { selectedItem = item delegate?.searchableComboListViewController(self, didSelectItem: item) if closeOnSelect { view.window?.orderOut(nil) } } func searchableComboTableViewControllerGroups(_ tableViewController: SearchableComboTableViewController) -> [SearchableComboViewGroup] { return groups } } extension SearchableComboListViewController: SearchableComboListSearchFieldDelegate { func searchFieldPerformKeyEquivalent(with event: NSEvent) -> Bool { guard let window = searchField.window else { return false } guard let firstResponder = window.firstResponder else { return false } guard let textView = firstResponder as? NSTextView else { return false } guard window.fieldEditor(false, for: nil) != nil else { return false } guard searchField == textView.delegate as? NSSearchField else { return false } let mask: NSEvent.ModifierFlags = [.shift, .control, .option, .command] guard event.modifierFlags.intersection(mask) == [] else { return super.performKeyEquivalent(with: event) } if event.keyCode == 125 /* down arrow */ || event.keyCode == 126 /* up arrow */ { // TODO: Prevent reentrancy? closeOnSelect = false tableView.window?.makeFirstResponder(tableView) tableView.keyDown(with: event) closeOnSelect = true return true } return super.performKeyEquivalent(with: event) } }
e8a70e1607d3718958e45ad41ed9d25e
35.19084
140
0.659776
false
false
false
false
bradhowes/vhtc
refs/heads/master
VariableHeightTableCells/UINib+Extensions.swift
mit
1
// // UINib+Extensions.swift // VariableHeightTableCells // // Created by Brad Howes on 8/1/17. // Copyright © 2017 Brad Howes. All rights reserved. // import UIKit /** Internal class that allows us to find the bundle that contains it. */ private class OurBundle: NSObject { static let name = "BundleName" /// Obtain the Bundle that contains ourselves and our resources public static var bundle: Bundle = { // This is convoluted to support instantiation within Xcode due to IB processing and CocoaPods processing which // will have different results. // let bundle = Bundle(for: OurBundle.self) if let path = bundle.path(forResource: OurBundle.name, ofType: "bundle") { if let inner = Bundle(path: path) { // This is the result for proper CocoaPods support // return inner } } // This is the result for non-CocoaPods (e.g. Xcode) support // return bundle }() } extension UINib { /** Instantiate a new NIB using a CellIdent enumeration to determine which one. Only works if the CellIdent's `rawString` value is the same as the name of a NIB file in the main bundle. - parameter ident: the NIB to load */ convenience init(ident: CellIdent) { let nibName: String = ident.rawValue self.init(nibName: nibName, bundle: OurBundle.bundle) } /** Generic class method that will instantiate a NIB based on the given kind value, where T is the view class name for instance in the NIB. - parameter kind: the key to work with - returns: instance of T */ class func instantiate<T>(ident: CellIdent) -> T { return UINib(ident: ident).instantiate(withOwner: nil, options: nil)[0] as! T } }
55d921ac14e38b890a64ac53ae3083f3
28.31746
119
0.63346
false
false
false
false
findmybusnj/findmybusnj-swift
refs/heads/master
findmybusnj-widget/Presenters/WidgetBannerPresenter.swift
gpl-3.0
1
// // WidgetBannerPresenter.swift // findmybusnj // // Created by David Aghassi on 2/21/17. // Copyright © 2017 David Aghassi. All rights reserved. // import UIKit // Dependencies import SwiftyJSON import findmybusnj_common /** Class for managing the next bus banner at the top of the widget */ class WidgetBannerPresenter: ETAPresenter { var sanitizer = JSONSanitizer() /** Assigns the banner the proper string based on the current arrival information */ func assignTextForArrivalBanner(label: UILabel, json: JSON) { label.text = "The next bus will be" let arrivalCase = determineArrivalCase(json: json) switch arrivalCase { case "Arrived": label.text = "The next bus has \(arrivalCase.lowercased())" return case"Arriving": label.text = "The next bus is \(arrivalCase.lowercased())" return case "Delay": label.text = "\(label.text ?? "") delayed" return default: let arrivalTime = sanitizer.getSanitizedArrivaleTimeAsInt(json) label.text = "\(label.text ?? "") \(arrivalTime.description) min." return } } // no-ops since they aren't used by this presenter func formatCellForPresentation(_ cell: UITableViewCell, json: JSON) {} func assignArrivalTimeForJson(_ cell: UITableViewCell, json: JSON) {} func assignBusAndRouteTextForJson(_ cell: UITableViewCell, json: JSON) {} }
0a31f9b938d892aca0c639851566a12a
27.428571
80
0.691314
false
false
false
false
google/JacquardSDKiOS
refs/heads/main
JacquardSDK/Classes/IMUDataCollection/IMUModuleProtocol.swift
apache-2.0
1
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Combine import Foundation /// Information about the current state of IMU session download. public enum IMUSessionDownloadState { /// Downloading of session is in progress, contains progress percentage. case downloading(Int) /// Session has been downloaded, contains downloaded file path. case downloaded(URL) } /// Metadata for a recorded IMU session. /// /// All data collected as part of a data collection session can be organized with the following hierarchy: /// Campaign /// - Group /// - Session /// - Subject (User) /// A campaign sets the overall goal for a data collection exercise. /// Campaigns may contain one or more groups which in turn can contain one or more session which may contain one or more subjects. /// For example, Campaign 1234 consists of motion data gathered while the subject is walking. /// Data collection for Group 5 under campaign 1234 is recorded at 2pm on July 15 2021 and has 10 subjects/users. /// Group 5 may carry out multiple Sessions. Therefore, each data collection session needs to be labelled with the /// campaign identifier, group identifier, session identifier and subject identifier. public struct IMUSessionInfo: Codable { /// Unique indentfier for the IMU recording. public let sessionID: String /// Identifies the Campaign of a recording session. public let campaignID: String /// Identifies the group or setting of a recording session. public let groupID: String /// Product used for recording the IMU Data. public let productID: String /// Indentfier for the Subject/User performing the motion. public let subjectID: String // This can be used to validate the size of the downloaded raw file. let fsize: UInt32 // CRC16 (CCITT) of the data file. let crc16: UInt32 init(trial: Google_Jacquard_Protocol_DataCollectionTrialList) { self.sessionID = trial.trialID self.campaignID = trial.campaignID self.groupID = trial.sessionID self.productID = trial.productID guard let trialData = trial.trialData.first, let sensorData = trialData.sensorData.first else { preconditionFailure("Cannot have a session without trial or sensor data") } self.subjectID = trialData.subjectID self.fsize = sensorData.fsize self.crc16 = sensorData.crc16 } init(metadata: Google_Jacquard_Protocol_DataCollectionMetadata) { self.sessionID = metadata.trialID self.campaignID = metadata.campaignID self.groupID = metadata.sessionID self.productID = metadata.productID self.subjectID = metadata.subjectID self.fsize = 0 self.crc16 = 0 } } /// Provides an interface to perform various operations related to IMU. public protocol IMUModule { /// Configures the tag for IMU data access. /// /// Before accessing IMU data, the tag must have IMU module loaded and activated. /// This method will perform all required steps asynchronously and publish when /// completed. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule activation was /// successful or will publish a `ModuleError` in case of an error. func initialize() -> AnyPublisher<Void, ModuleError> /// Activates the module. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule activation was /// successful or a `ModuleError` in case of failure. func activateModule() -> AnyPublisher<Void, ModuleError> /// Deactivates the module. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMUModule deactivation was /// successful or a `ModuleError` in case of failure. func deactivateModule() -> AnyPublisher<Void, ModuleError> /// Starts recording IMU data. /// /// Parameters cannot be empty, /// - Parameters: /// - sessionID: Unique id provided by the client app. Should be non empty & less than 30 characters. /// - campaignID: Identifies the Campaign of a recording session. Should be non empty & less than 30 characters. /// - groupID: Identifies the Group or setting of a recording session. Should be non empty & less than 30 characters. /// - productID: Identifies the Product used for recording the IMU Data. Should be non empty & less than 30 characters. /// - subjectID: Indentfier for the Subject/User performing the motion. Should be non empty & less than 30 characters. /// - Returns: Any publisher with a `DataCollectionStatus` Result. Verify status to confirm IMU recording was started /// or return an error if recording could not be started. func startRecording( sessionID: String, campaignID: String, groupID: String, productID: String, subjectID: String ) -> AnyPublisher<DataCollectionStatus, Error> /// Stops the current IMU recording session. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMU recording was stopped /// or will publish an error if recording could not be stopped. func stopRecording() -> AnyPublisher<Void, Error> /// Requests Tag to send IMU sessions. /// /// - Returns: Any publisher that publishes `IMUSessionInfo` objects available on the tag, /// or will publish an error if List sessions request was not acknowledged by the Tag. func listSessions() -> AnyPublisher<IMUSessionInfo, Error> /// Deletes a particular session from the device. /// /// - Parameter session: IMU session to delete. /// - Returns: Any publisher with a `Void` Result, indicating that session was erased /// or will publish an error if the session could not be erased from the tag. func eraseSession(session: IMUSessionInfo) -> AnyPublisher<Void, Error> /// Deletes all sessions from the device. /// /// - Returns: Any publisher with a `Void` Result, indicating that all sessions were erased /// or will publish an error if the sessions could not be erased from the tag. func eraseAllSessions() -> AnyPublisher<Void, Error> /// Retrieves data for an IMUSesion. /// /// - Parameter session: IMU session for which data download will be done. /// - Returns: Any publisher with `IMUSesionDownloadState` as Result, /// `IMUSesionDownloadState.downloading` indicates the progress of download. /// `IMUSesionDownloadState.downloaded` contains the URL path of the downloaded file . /// will publish an error if the session data could not be fetched. func downloadIMUSessionData( session: IMUSessionInfo ) -> AnyPublisher<IMUSessionDownloadState, Error> /// Will stop the current IMU session downloading. /// /// - Returns: Any publisher with a `Void` Result, indicating that IMU session download was stopped. /// or will publish an error if downloading could not be stopped. func stopDownloading() -> AnyPublisher<Void, Error> /// Retrieves data for an IMUSession. /// /// - Parameter path: File path of the downloaded IMU session file. /// - Returns: Any publisher with a `bool` and `IMUSessionData` as Result. /// Bool indicates if file was fully parsed, publisher will publish an error if the session data could not be parsed. func parseIMUSession( path: URL ) -> AnyPublisher<(fullyParsed: Bool, session: IMUSessionData), Error> /// Retrieves data for an IMUSession. /// /// - Parameter session: IMU session to be parsed. /// - Returns: Any publisher with a `bool` and `IMUSessionData` as Result. /// Bool indicates if file was fully parsed, publisher will publish an error if the session data could not be parsed. func parseIMUSession( session: IMUSessionInfo ) -> AnyPublisher<(fullyParsed: Bool, session: IMUSessionData), Error> }
8fe990db0e91f7077a5f03e4430f6d45
42.62234
130
0.726131
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/Model/DotLottie/Zip/FileManager+ZIP.swift
apache-2.0
2
// // FileManager+ZIP.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension FileManager { /// The default permissions for newly added entries. static let defaultFilePermissions = UInt16(0o644) class func attributes(from entry: ZipEntry) -> [FileAttributeKey: Any] { let centralDirectoryStructure = entry.centralDirectoryStructure let fileTime = centralDirectoryStructure.lastModFileTime let fileDate = centralDirectoryStructure.lastModFileDate let defaultPermissions = defaultFilePermissions var attributes = [.posixPermissions: defaultPermissions] as [FileAttributeKey: Any] // Certain keys are not yet supported in swift-corelibs #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) attributes[.modificationDate] = Date(dateTime: (fileDate, fileTime)) #endif let externalFileAttributes = centralDirectoryStructure.externalFileAttributes let permissions = permissions(for: externalFileAttributes) attributes[.posixPermissions] = NSNumber(value: permissions) return attributes } class func permissions(for externalFileAttributes: UInt32) -> UInt16 { let permissions = mode_t(externalFileAttributes >> 16) & ~S_IFMT let defaultPermissions = defaultFilePermissions return permissions == 0 ? defaultPermissions : UInt16(permissions) } /// Unzips the contents at the specified source URL to the destination URL. /// /// - Parameters: /// - sourceURL: The file URL pointing to an existing ZIP file. /// - destinationURL: The file URL that identifies the destination directory of the unzip operation. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. func unzipItem(at sourceURL: URL, to destinationURL: URL) throws { guard (try? sourceURL.checkResourceIsReachable()) == true else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path]) } guard let archive = ZipArchive(url: sourceURL) else { throw ZipArchive.ArchiveError.unreadableArchive } for entry in archive { let path = entry.path let entryURL = destinationURL.appendingPathComponent(path) guard entryURL.isContained(in: destinationURL) else { throw CocoaError( .fileReadInvalidFileName, userInfo: [NSFilePathErrorKey: entryURL.path]) } let crc32: UInt32 = try archive.extract(entry, to: entryURL) func verifyChecksumIfNecessary() throws { if crc32 != entry.checksum { throw ZipArchive.ArchiveError.invalidCRC32 } } try verifyChecksumIfNecessary() } } // MARK: - Helpers func createParentDirectoryStructure(for url: URL) throws { let parentDirectoryURL = url.deletingLastPathComponent() try createDirectory(at: parentDirectoryURL, withIntermediateDirectories: true, attributes: nil) } } extension Date { fileprivate init(dateTime: (UInt16, UInt16)) { var msdosDateTime = Int(dateTime.0) msdosDateTime <<= 16 msdosDateTime |= Int(dateTime.1) var unixTime = tm() unixTime.tm_sec = Int32((msdosDateTime & 31) * 2) unixTime.tm_min = Int32((msdosDateTime >> 5) & 63) unixTime.tm_hour = Int32((Int(dateTime.1) >> 11) & 31) unixTime.tm_mday = Int32((msdosDateTime >> 16) & 31) unixTime.tm_mon = Int32((msdosDateTime >> 21) & 15) unixTime.tm_mon -= 1 // UNIX time struct month entries are zero based. unixTime.tm_year = Int32(1980 + (msdosDateTime >> 25)) unixTime.tm_year -= 1900 // UNIX time structs count in "years since 1900". let time = timegm(&unixTime) self = Date(timeIntervalSince1970: TimeInterval(time)) } } #if swift(>=4.2) #else #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) #else // The swift-corelibs-foundation version of NSError.swift was missing a convenience method to create // error objects from error codes. (https://github.com/apple/swift-corelibs-foundation/pull/1420) // We have to provide an implementation for non-Darwin platforms using Swift versions < 4.2. extension CocoaError { fileprivate static func error(_ code: CocoaError.Code, userInfo: [AnyHashable: Any]? = nil, url: URL? = nil) -> Error { var info: [String: Any] = userInfo as? [String: Any] ?? [:] if let url = url { info[NSURLErrorKey] = url } return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info) } } #endif #endif extension URL { fileprivate func isContained(in parentDirectoryURL: URL) -> Bool { // Ensure this URL is contained in the passed in URL let parentDirectoryURL = URL(fileURLWithPath: parentDirectoryURL.path, isDirectory: true).standardized return standardized.absoluteString.hasPrefix(parentDirectoryURL.absoluteString) } }
5ae7fde363ace73c841455c7230f09d7
37.515385
121
0.7144
false
false
false
false
Senspark/ee-x
refs/heads/master
src/ios/ee/firebase_core/FirebaseInitializer.swift
mit
1
// // FirebaseCoreBridge.swift // Pods // // Created by eps on 6/26/20. // private let kTag = "\(FirebaseInitializer.self)" class FirebaseInitializer { private static let _sharedInstance = FirebaseInitializer() private let _logger = PluginManager.instance.logger private var _initialized = false public class var instance: FirebaseInitializer { return _sharedInstance } private init() { _logger.info("\(kTag): constructor") } public func initialize() -> Bool { if _initialized { return true } _initialized = true FirebaseApp.configure() return true } }
34ac672185811ae971b307a657a13213
19.8125
62
0.621622
false
false
false
false
dbahat/conventions-ios
refs/heads/sff
Conventions/Conventions/feedback/ConventionFeedbackViewController.swift
apache-2.0
1
// // ConventionFeedbackViewController.swift // Conventions // // Created by David Bahat on 7/22/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation import Firebase class ConventionFeedbackViewController: BaseViewController, FeedbackViewProtocol { @IBOutlet private weak var contentView: UIView! @IBOutlet private weak var filledEventsFeedbackLabel: UILabel! @IBOutlet private weak var seperatorView: UIView! @IBOutlet private weak var sendAllFeedbackDescriptionLabel: UILabel! @IBOutlet private weak var sendFeedbackContainer: UIView! @IBOutlet private weak var sendFeedbackContainerHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var feedbackView: FeedbackView! @IBOutlet private weak var feedbackViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var submittedEventsTabledView: UITableView! @IBOutlet private weak var submittedEventsTableViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var eventsToSubmitTableView: UITableView! @IBOutlet private weak var eventsToSubmitHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var submitAllFeedbacksButtonIndicator: UIActivityIndicatorView! @IBOutlet private weak var submitAllFeedbacksButton: UIButton! @IBOutlet private weak var fillEventFeedbackTitleLabel: UILabel! @IBOutlet private weak var fillEventFeedbackMessageLabel: UILabel! @IBOutlet private weak var filledFeedbacksTitleLabel: UILabel! @IBOutlet private weak var conventionFeedbackTitleLabel: UILabel! @IBOutlet private weak var generalFeedbackTitleLabel: UILabel! @IBOutlet private weak var toastView: UIView! private let submittedEventsDataSource = EventsTableDataSource() private let eventsToSubmitDataSource = EventsTableDataSource() private var userInputs: UserInput.Feedback { get { return Convention.instance.feedback.conventionInputs } } override func viewDidLoad() { super.viewDidLoad() feedbackView.delegate = self feedbackView.setHeaderHidden(true) feedbackView.textColor = Colors.textColor feedbackView.buttonColor = Colors.buttonColor feedbackView.linkColor = Colors.feedbackLinksColorConvention feedbackView.setFeedback( questions: Convention.instance.feedbackQuestions, answers: userInputs.answers, isSent: userInputs.isSent) // In this view the feedbackView should always be expended. // Note - should be done after setting the questions/answers, since they affect the view height. feedbackView.state = .expended // Need to set the view height constrant only after we set the // feedback and it's collapsed state, since its size changes based on the questions and state feedbackViewHeightConstraint.constant = feedbackView.getHeight() initializeEventsTableViews() navigationItem.title = "פידבק לכנס" submitAllFeedbacksButton.setTitleColor(Colors.buttonColor, for: UIControl.State()) fillEventFeedbackTitleLabel.textColor = Colors.textColor fillEventFeedbackMessageLabel.textColor = Colors.textColor filledFeedbacksTitleLabel.textColor = Colors.textColor conventionFeedbackTitleLabel.textColor = Colors.textColor generalFeedbackTitleLabel.textColor = Colors.textColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(ConventionFeedbackViewController.keyboardFrameWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Saving to the filesystem only when leaving the screen, since we don't want to save // on each small change inside free-text questions Convention.instance.feedback.save() NotificationCenter.default.removeObserver(self) } func feedbackProvided(_ feedback: FeedbackAnswer) { // If the answer already exists, override it if let existingAnswerIndex = userInputs.answers.firstIndex(where: {$0.questionText == feedback.questionText}) { userInputs.answers.remove(at: existingAnswerIndex) } userInputs.answers.append(feedback) Convention.instance.feedback.save() feedbackView.setSendButtonEnabled(userInputs.answers.count > 0) } func feedbackCleared(_ feedback: FeedbackQuestion) { guard let existingAnswerIndex = userInputs.answers.firstIndex(where: {$0.questionText == feedback.question}) else { // no existing answer means nothing to clear return } userInputs.answers.remove(at: existingAnswerIndex); feedbackView.setSendButtonEnabled(userInputs.answers.count > 0) } func sendFeedbackWasClicked() { // Force close the keyboard view.endEditing(true) Convention.instance.conventionFeedbackForm.submit(conventionName: Convention.displayName, answers: userInputs.answers, callback: { success in Convention.instance.feedback.conventionInputs.isSent = success self.feedbackView.setFeedbackAsSent(success) Analytics.logEvent("ConventionFeedback", parameters: [ "name": "SendAttempt" as NSObject, "full_text": success ? "success" : "failure" as NSObject ]) if !success { TTGSnackbar(message: "לא ניתן לשלוח את הפידבק. נסה שנית מאוחר יותר", duration: TTGSnackbarDuration.middle, superView: self.toastView).show() return } // Cancel the convention feedback reminder notifications (so the user won't see it again) NotificationsSchedualer.removeConventionFeedback() NotificationsSchedualer.removeConventionFeedbackLastChance() // filter un-answered questions and animate the possible layout height change self.feedbackView.removeAnsweredQuestions(self.userInputs.answers) self.feedbackViewHeightConstraint.constant = self.feedbackView.getHeight() UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) }) } func feedbackViewHeightDidChange(_ newHeight: CGFloat) { feedbackViewHeightConstraint.constant = newHeight } // Resize the screen to be at the height minus the keyboard, so that the keyboard won't hide the user's feedback @objc func keyboardFrameWillChange(_ notification: Notification) { let keyboardBeginFrame = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardFrameBeginUserInfoKey)! as AnyObject).cgRectValue let keyboardEndFrame = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardFrameEndUserInfoKey)! as AnyObject).cgRectValue let animationCurve = UIView.AnimationCurve(rawValue: ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardAnimationCurveUserInfoKey)! as AnyObject).intValue) let animationDuration: TimeInterval = ((notification.userInfo! as NSDictionary).object(forKey: UIResponder.keyboardAnimationDurationUserInfoKey)! as AnyObject).doubleValue UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(animationCurve!) var newFrame = self.view.frame let keyboardFrameEnd = self.view.convert(keyboardEndFrame!, to: nil) let keyboardFrameBegin = self.view.convert(keyboardBeginFrame!, to: nil) newFrame.origin.y -= (keyboardFrameBegin.origin.y - keyboardFrameEnd.origin.y) self.view.frame = newFrame; UIView.commitAnimations() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let eventViewController = segue.destination as? EventViewController; if let event = sender as? ConventionEvent { eventViewController?.event = event } } @IBAction fileprivate func submitAllEventsFeedbackWasTapped(_ sender: UIButton) { submitAllFeedbacksButton.isHidden = true submitAllFeedbacksButtonIndicator.isHidden = false var submittedEventsCount = 0; for event in eventsToSubmitDataSource.events { event.submitFeedback({success in if !success { TTGSnackbar(message: "לא ניתן לשלוח את הפידבק. נסה שנית מאוחר יותר", duration: TTGSnackbarDuration.middle, superView: self.toastView) .show(); return } submittedEventsCount += 1; if submittedEventsCount == self.eventsToSubmitDataSource.events.count { self.submitAllFeedbacksButton.isHidden = false self.submitAllFeedbacksButtonIndicator.isHidden = true // reset the tableViews to reflect the new changes in submitted events self.initializeEventsTableViews() self.submittedEventsTabledView.reloadData() self.eventsToSubmitTableView.reloadData() } }) } } fileprivate func initializeEventsTableViews() { submittedEventsDataSource.events = Convention.instance.events.getAll().filter({$0.didSubmitFeedback()}) submittedEventsTableViewHeightConstraint.constant = CGFloat(102 * submittedEventsDataSource.events.count) submittedEventsTabledView.dataSource = submittedEventsDataSource submittedEventsTabledView.delegate = submittedEventsDataSource submittedEventsDataSource.referencingViewController = self eventsToSubmitDataSource.events = Convention.instance.events.getAll().filter({ ($0.feedbackAnswers.count > 0 || $0.attending) && $0.canFillFeedback() && !$0.didSubmitFeedback() && !Convention.instance.isFeedbackSendingTimeOver()}) eventsToSubmitHeightConstraint.constant = CGFloat(102 * eventsToSubmitDataSource.events.count) eventsToSubmitTableView.dataSource = eventsToSubmitDataSource eventsToSubmitTableView.delegate = eventsToSubmitDataSource eventsToSubmitDataSource.referencingViewController = self if eventsToSubmitDataSource.events.count == 0 && submittedEventsDataSource.events.count == 0 { sendFeedbackContainerHeightConstraint.constant = 81 sendFeedbackContainer.isHidden = false submitAllFeedbacksButton.isHidden = true seperatorView.isHidden = true filledEventsFeedbackLabel.isHidden = true sendAllFeedbackDescriptionLabel.text = "בחר אירועים שהיית בהם דרך התוכניה ומלא עליהם פידבק" } else if eventsToSubmitDataSource.events.count == 0 { sendFeedbackContainerHeightConstraint.constant = 0 sendFeedbackContainer.isHidden = true } else { sendFeedbackContainerHeightConstraint.constant = eventsToSubmitHeightConstraint.constant + 116 sendFeedbackContainer.isHidden = false } } class EventsTableDataSource : NSObject, UITableViewDataSource, UITableViewDelegate { var events = Array<ConventionEvent>() weak var referencingViewController: UIViewController? func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let event = events[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: EventTableViewCell.self)) as! EventTableViewCell cell.setEvent(event) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let event = events[indexPath.row] referencingViewController?.performSegue(withIdentifier: "ConventionFeedbackToEventSegue", sender: event) } } }
2f8c8cf2a00d99d1c4aee8dfcbc504f7
46.773585
203
0.687204
false
false
false
false
nua-schroers/AccessibilityExamples
refs/heads/master
AccessibilityExamples/ViewWithSwitch.swift
mit
1
// // ViewWithSwitch.swift // AccessibilityExamples // // Created by Dr. Wolfram Schroers on 3/1/15. // Copyright (c) 2015 Wolfram Schroers. All rights reserved. // import UIKit /// This is a view which contains a description label and a switch. /// The entire view shall be accessible and behave like a switch that can be /// turned. /// /// Note that we do NOT want to access the individual sub-elements /// (i.e., the label and the switch) individually when VoiceOver is active. We only want to deal with /// the entire cell. class ViewWithSwitch: CustomView { /// MARK: Properties var textLabel = UILabel() var theSwitch = UISwitch() /// MARK: Configuration methods override func setup() { super.setup() // View setup (nothing to do with Accessibility). let powerSettingText = NSLocalizedString("Power setting", comment: "") self.textLabel.text = powerSettingText self.textLabel.frame = CGRect(x: 5, y: 5, width: 200, height: 50) self.theSwitch.frame = CGRect(x: 205, y: 5, width: 50, height: 50) self.addSubview(self.textLabel) self.addSubview(self.theSwitch) // Accessibility setup. self.isAccessibilityElement = true // The entire view shall be accessible. self.textLabel.isAccessibilityElement = false // But the label and the switch shall not be. self.theSwitch.isAccessibilityElement = false self.accessibilityLabel = powerSettingText // This is the standard label text of this view. self.accessibilityHint = "Double tap to activate or deactivate" // This is the hint. // This view shall behave as a button with VoiceOver. self.accessibilityTraits = UIAccessibilityTraits(rawValue: super.accessibilityTraits.rawValue | UIAccessibilityTraits.button.rawValue) self.updateAccessibility() } override func updateAccessibility() { super.updateAccessibility() // The value is the current setting and we use a custom text here. self.accessibilityValue = self.theSwitch.isOn ? "active" : "inactive" } /// MARK: UIAccessibilityAction /// This method is automagically called when the user double-taps /// while the view is highlighted. /// /// Note that this method is NOT used at all if VoiceOver is /// turned off! override func accessibilityActivate() -> Bool { // Toggle the switch. let newValue = !self.theSwitch.isOn self.theSwitch.setOn(newValue, animated: true) // Update the accessibility value. self.updateAccessibility() // Inform the user of the new situation. UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: "") // Return whether the action was successful (in this case is it always is). return true } }
87adfb10e91d77718e98ee5f6d4a35d5
35.1125
142
0.677051
false
false
false
false
s1Moinuddin/TextFieldWrapper
refs/heads/master
Example/Pods/TextFieldWrapper/TextFieldWrapper/Classes/Protocols/Zoomable.swift
mit
2
// // Zoomable.swift // TextFieldWrapper // // Created by Shuvo on 7/29/17. // Copyright © 2017 Shuvo. All rights reserved. // import UIKit protocol Zoomable {} extension Zoomable where Self:UIView { private func addPerspectiveTransformToParentSubviews() { let scale: CGFloat = 0.8 var transform3D = CATransform3DIdentity transform3D.m34 = -1/500 transform3D = CATransform3DScale(transform3D, scale, scale, 1) //let asdf = self.window?.rootViewController if let topController = window?.visibleViewController() { if let parentView = topController.view { parentView.subviews.forEach({ (mySubview) in if (mySubview != self && !(mySubview is UIVisualEffectView) && !(mySubview is UITableView)) { mySubview.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 0.5)) mySubview.layer.transform = transform3D } }) } } } private func removePerspectiveTransformFromParentSubviews() { if let topController = window?.visibleViewController() { if let parentView = topController.view { parentView.subviews.forEach({ (mySubview) in if mySubview != self { mySubview.layer.transform = CATransform3DIdentity } }) } } } func zoomIn(duration:TimeInterval, scale: CGFloat) { UIView.animate(withDuration: duration) { [weak self] in self?.backgroundColor = UIColor.white self?.layer.borderColor = UIColor.gray.cgColor self?.layer.borderWidth = 2.0 self?.layer.cornerRadius = 4.0 self?.layer.isOpaque = true self?.transform = CGAffineTransform(scaleX: scale, y: scale) self?.addPerspectiveTransformToParentSubviews() } } func zoomOut(duration:TimeInterval) { UIView.animate(withDuration: duration) { [weak self] in self?.layer.borderColor = UIColor.clear.cgColor self?.layer.borderWidth = 0 self?.layer.cornerRadius = 0 self?.layer.isOpaque = false self?.transform = .identity self?.removePerspectiveTransformFromParentSubviews() } } }
e3138dd8de9255908de3b70f20f8ddac
33.4
113
0.578904
false
false
false
false
rnine/AMCoreAudio
refs/heads/develop
Source/Internal/AudioHardware.swift
mit
1
// // AudioHardware.swift // SimplyCoreAudio // // Created by Ruben on 7/9/15. // Copyright © 2015 9Labs. All rights reserved. // import CoreAudio.AudioHardwareBase import Foundation import os.log /// This class allows subscribing to hardware-related audio notifications. /// /// For a comprehensive list of supported notifications, see `AudioHardwareEvent`. final class AudioHardware { // MARK: - Fileprivate Properties fileprivate var allKnownDevices = [AudioDevice]() fileprivate var isRegisteredForNotifications = false // MARK: - Internal Functions /// Enables device monitoring so events like the ones below are generated: /// /// - added or removed device /// - new default input device /// - new default output device /// - new default system output device /// /// - SeeAlso: `disableDeviceMonitoring()` func enableDeviceMonitoring() { registerForNotifications() for device in AudioDevice.allDevices() { add(device: device) } } /// Disables device monitoring. /// /// - SeeAlso: `enableDeviceMonitoring()` func disableDeviceMonitoring() { for device in allKnownDevices { remove(device: device) } unregisterForNotifications() } } // MARK: - Fileprivate Functions fileprivate extension AudioHardware { func add(device: AudioDevice) { allKnownDevices.append(device) } func remove(device: AudioDevice) { allKnownDevices.removeAll { $0 == device } } // MARK: - Notification Book-keeping func registerForNotifications() { if isRegisteredForNotifications { unregisterForNotifications() } var address = AudioObjectPropertyAddress( mSelector: kAudioObjectPropertySelectorWildcard, mScope: kAudioObjectPropertyScopeWildcard, mElement: kAudioObjectPropertyElementWildcard ) let systemObjectID = AudioObjectID(kAudioObjectSystemObject) let selfPtr = Unmanaged.passUnretained(self).toOpaque() if noErr != AudioObjectAddPropertyListener(systemObjectID, &address, propertyListener, selfPtr) { os_log("Unable to add property listener for systemObjectID: %@.", systemObjectID) } else { isRegisteredForNotifications = true } } func unregisterForNotifications() { guard isRegisteredForNotifications else { return } var address = AudioObjectPropertyAddress( mSelector: kAudioObjectPropertySelectorWildcard, mScope: kAudioObjectPropertyScopeWildcard, mElement: kAudioObjectPropertyElementWildcard ) let systemObjectID = AudioObjectID(kAudioObjectSystemObject) let selfPtr = Unmanaged.passUnretained(self).toOpaque() if noErr != AudioObjectRemovePropertyListener(systemObjectID, &address, propertyListener, selfPtr) { os_log("Unable to remove property listener for systemObjectID: %@.", systemObjectID) } else { isRegisteredForNotifications = false } } } // MARK: - C Convention Functions private func propertyListener(objectID: UInt32, numInAddresses: UInt32, inAddresses : UnsafePointer<AudioObjectPropertyAddress>, clientData: Optional<UnsafeMutableRawPointer>) -> Int32 { let _self = Unmanaged<AudioHardware>.fromOpaque(clientData!).takeUnretainedValue() let address = inAddresses.pointee let notificationCenter = NotificationCenter.default switch address.mSelector { case kAudioObjectPropertyOwnedObjects: // Get the latest device list let latestDeviceList = AudioDevice.allDevices() let addedDevices = latestDeviceList.filter { (audioDevice) -> Bool in !(_self.allKnownDevices.contains { $0 == audioDevice }) } let removedDevices = _self.allKnownDevices.filter { (audioDevice) -> Bool in !(latestDeviceList.contains { $0 == audioDevice }) } // Add new devices for device in addedDevices { _self.add(device: device) } // Remove old devices for device in removedDevices { _self.remove(device: device) } let userInfo: [AnyHashable: Any] = [ "added": addedDevices, "removed": removedDevices ] notificationCenter.post(name: Notifications.deviceListChanged.name, object: _self, userInfo: userInfo) case kAudioHardwarePropertyDefaultInputDevice: notificationCenter.post(name: Notifications.defaultInputDeviceChanged.name, object: _self) case kAudioHardwarePropertyDefaultOutputDevice: notificationCenter.post(name: Notifications.defaultOutputDeviceChanged.name, object: _self) case kAudioHardwarePropertyDefaultSystemOutputDevice: notificationCenter.post(name: Notifications.defaultSystemOutputDeviceChanged.name, object: _self) default: break } return noErr }
b6358ce653d5ef9dacb46840dc06bca3
31.528662
110
0.665949
false
false
false
false
erikmartens/NearbyWeather
refs/heads/develop
NearbyWeather/Scenes/Weather Station Meteorology Details Scene/Table Cells/Weather Station Meteorology Details Header/WeatherStationMeteorologyDetailsHeaderCellModel.swift
mit
1
// // WeatherStationCurrentInformationHeaderCellModel.swift // NearbyWeather // // Created by Erik Maximilian Martens on 13.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit struct WeatherStationMeteorologyDetailsHeaderCellModel { let weatherConditionSymbolImage: UIImage? let weatherConditionTitle: String? let weatherConditionSubtitle: String? let temperature: String? let daytimeStatus: String? let backgroundColor: UIColor init( weatherConditionSymbolImage: UIImage? = nil, weatherConditionTitle: String? = nil, weatherConditionSubtitle: String? = nil, temperature: String? = nil, daytimeStatus: String? = nil, backgroundColor: UIColor = Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundDay ) { self.weatherConditionSymbolImage = weatherConditionSymbolImage self.weatherConditionTitle = weatherConditionTitle self.weatherConditionSubtitle = weatherConditionSubtitle self.temperature = temperature self.daytimeStatus = daytimeStatus self.backgroundColor = backgroundColor } init( weatherInformationDTO: WeatherInformationDTO, temperatureUnitOption: TemperatureUnitOption, dimensionalUnitsOption: DimensionalUnitOption, isBookmark: Bool ) { let isDayTime = MeteorologyInformationConversionWorker.isDayTime(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) let isDayTimeString = MeteorologyInformationConversionWorker.isDayTimeString(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) let dayCycleStrings = MeteorologyInformationConversionWorker.dayCycleTimeStrings(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) self.init( weatherConditionSymbolImage: MeteorologyInformationConversionWorker.weatherConditionSymbol( fromWeatherCode: weatherInformationDTO.weatherCondition.first?.identifier, isDayTime: isDayTime ), weatherConditionTitle: weatherInformationDTO.weatherCondition.first?.conditionName?.capitalized, weatherConditionSubtitle: weatherInformationDTO.weatherCondition.first?.conditionDescription?.capitalized, temperature: MeteorologyInformationConversionWorker.temperatureDescriptor( forTemperatureUnit: temperatureUnitOption, fromRawTemperature: weatherInformationDTO.atmosphericInformation.temperatureKelvin ), daytimeStatus: String .begin(with: isDayTimeString) .append(contentsOf: dayCycleStrings?.currentTimeString, delimiter: .space) .ifEmpty(justReturn: nil), backgroundColor: (isDayTime ?? true) ? Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundDay : Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundNight ) } }
275b9b11d8569811b4a0a4361d7bd40d
44.28125
192
0.796411
false
false
false
false
HLoveMe/HExtension-swift
refs/heads/master
HExtension/HExtension/newsModel.swift
apache-2.0
1
// // newsModel.swift // HExtension // // Created by space on 16/1/8. // Copyright © 2016年 Space. All rights reserved. // class newsModel: KeyValueModel { var ID:Int = 0 var title:String? var mediatype:Int = 0 var type:String? var time:String? var indexdetail:String? var smallpic:String? var replycount:Int = 0 var pagecount:Int = 0 var jumppage:Int = 0 var lasttime:String? var updatetime:String? var coverimages:[String]? var newstype:Int = 0 var urls:[String]? var imgUrls:[String]? { get{ if self.urls != nil { }else{ let range = indexdetail!.range(of: "http://") let str = indexdetail!.substring(from: (range?.lowerBound)!) self.urls = str.components(separatedBy: ",") } return urls } } override func propertyNameInDictionary() -> [String : String]? { return ["ID":"id"] } }
fdc0651977311cab4575e87d414186a0
22.697674
76
0.541708
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/RectNode.swift
mit
1
// // RectNode.swift // lottie-swift // // Created by Brandon Withrow on 1/21/19. // import Foundation import CoreGraphics final class RectNodeProperties: NodePropertyMap, KeypathSearchable { var keypathName: String init(rectangle: Rectangle) { self.keypathName = rectangle.name self.direction = rectangle.direction self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.position.keyframes)) self.size = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.size.keyframes)) self.cornerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: rectangle.cornerRadius.keyframes)) self.keypathProperties = [ "Position" : position, "Size" : size, "Roundness" : cornerRadius ] self.properties = Array(keypathProperties.values) } let keypathProperties: [String : AnyNodeProperty] let properties: [AnyNodeProperty] let direction: PathDirection let position: NodeProperty<Vector3D> let size: NodeProperty<Vector3D> let cornerRadius: NodeProperty<Vector1D> } final class RectangleNode: AnimatorNode, PathNode { let properties: RectNodeProperties let pathOutput: PathOutputNode init(parentNode: AnimatorNode?, rectangle: Rectangle) { self.properties = RectNodeProperties(rectangle: rectangle) self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) self.parentNode = parentNode } // MARK: Animator Node var propertyMap: NodePropertyMap & KeypathSearchable { return properties } let parentNode: AnimatorNode? var hasLocalUpdates: Bool = false var hasUpstreamUpdates: Bool = false var lastUpdateFrame: CGFloat? = nil var isEnabled: Bool = true { didSet{ self.pathOutput.isEnabled = self.isEnabled } } func rebuildOutputs(frame: CGFloat) { let size = properties.size.value.sizeValue * 0.5 let radius = min(min(properties.cornerRadius.value.cgFloatValue, size.width) , size.height) let position = properties.position.value.pointValue var bezierPath = BezierPath() let points: [CurveVertex] if radius <= 0 { /// No Corners points = [ /// Lead In CurveVertex(point: CGPoint(x: size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 1 CurveVertex(point: CGPoint(x: size.width, y: size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 2 CurveVertex(point: CGPoint(x: -size.width, y: size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 3 CurveVertex(point: CGPoint(x: -size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), /// Corner 4 CurveVertex(point: CGPoint(x: size.width, y: -size.height), inTangentRelative: .zero, outTangentRelative: .zero) .translated(position), ] } else { let controlPoint = radius * EllipseNode.ControlPointConstant points = [ /// Lead In CurveVertex( CGPoint(x: radius, y: 0), CGPoint(x: radius, y: 0), CGPoint(x: radius, y: 0)) .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), /// Corner 1 CurveVertex( CGPoint(x: radius, y: 0), // In tangent CGPoint(x: radius, y: 0), // Point CGPoint(x: radius, y: controlPoint)) .translated(CGPoint(x: -radius, y: -radius)) .translated(CGPoint(x: size.width, y: size.height)) .translated(position), CurveVertex( CGPoint(x: controlPoint, y: radius), // In tangent CGPoint(x: 0, y: radius), // Point CGPoint(x: 0, y: radius)) // Out Tangent .translated(CGPoint(x: -radius, y: -radius)) .translated(CGPoint(x: size.width, y: size.height)) .translated(position), /// Corner 2 CurveVertex( CGPoint(x: 0, y: radius), // In tangent CGPoint(x: 0, y: radius), // Point CGPoint(x: -controlPoint, y: radius))// Out tangent .translated(CGPoint(x: radius, y: -radius)) .translated(CGPoint(x: -size.width, y: size.height)) .translated(position), CurveVertex( CGPoint(x: -radius, y: controlPoint), // In tangent CGPoint(x: -radius, y: 0), // Point CGPoint(x: -radius, y: 0)) // Out tangent .translated(CGPoint(x: radius, y: -radius)) .translated(CGPoint(x: -size.width, y: size.height)) .translated(position), /// Corner 3 CurveVertex( CGPoint(x: -radius, y: 0), // In tangent CGPoint(x: -radius, y: 0), // Point CGPoint(x: -radius, y: -controlPoint)) // Out tangent .translated(CGPoint(x: radius, y: radius)) .translated(CGPoint(x: -size.width, y: -size.height)) .translated(position), CurveVertex( CGPoint(x: -controlPoint, y: -radius), // In tangent CGPoint(x: 0, y: -radius), // Point CGPoint(x: 0, y: -radius)) // Out tangent .translated(CGPoint(x: radius, y: radius)) .translated(CGPoint(x: -size.width, y: -size.height)) .translated(position), /// Corner 4 CurveVertex( CGPoint(x: 0, y: -radius), // In tangent CGPoint(x: 0, y: -radius), // Point CGPoint(x: controlPoint, y: -radius)) // Out tangent .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), CurveVertex( CGPoint(x: radius, y: -controlPoint), // In tangent CGPoint(x: radius, y: 0), // Point CGPoint(x: radius, y: 0)) // Out tangent .translated(CGPoint(x: -radius, y: radius)) .translated(CGPoint(x: size.width, y: -size.height)) .translated(position), ] } let reversed = properties.direction == .counterClockwise let pathPoints = reversed ? points.reversed() : points for point in pathPoints { bezierPath.addVertex(reversed ? point.reversed() : point) } bezierPath.close() pathOutput.setPath(bezierPath, updateFrame: frame) } }
dd212ec578b8b1b05aefab2f02af467c
34.611702
113
0.601643
false
false
false
false