repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kysonyangs/ysbilibili
Pods/SwiftDate/Sources/SwiftDate/Date+Math.swift
5
7269
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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 // MARK: - Shortcuts to convert Date to DateInRegion public extension Date { /// Return the current absolute datetime in local's device region (timezone+calendar+locale) /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the local device's region @available(*, deprecated: 4.1.2, message: "This method is deprecated. use inDefaultRegion instead") public func inLocalRegion() -> DateInRegion { return DateInRegion(absoluteDate: self) } /// Return the current absolute datetime in default's device region (timezone+calendar+locale) /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the current default region public func inDefaultRegion() -> DateInRegion { return DateInRegion(absoluteDate: self) } /// Return the current absolute datetime in UTC/GMT timezone. `Calendar` and `Locale` are set automatically to the device's current settings. /// /// - returns: a new `DateInRegion` instance object which express passed absolute date in UTC timezone public func inGMTRegion() -> DateInRegion { return DateInRegion(absoluteDate: self, in: Region.GMT()) } /// Return the current absolute datetime in the context of passed `Region`. /// /// - parameter region: region you want to use to express `self` date. /// /// - returns: a new `DateInRegion` which represent `self` in the context of passed `Region` public func inRegion(region: Region? = nil) -> DateInRegion { return DateInRegion(absoluteDate: self, in: region) } /// Create a new Date object which is the sum of passed calendar components in `DateComponents` to `self` /// /// - parameter components: components to set /// /// - returns: a new `Date` public func add(components: DateComponents) -> Date { let date: DateInRegion = self.inDateDefaultRegion() + components return date.absoluteDate } /// Create a new Date object which is the sum of passed calendar components in dictionary of `Calendar.Component` values to `self` /// /// - parameter components: components to set /// /// - returns: a new `Date` public func add(components: [Calendar.Component: Int]) -> Date { let date: DateInRegion = self.inDateDefaultRegion() + components return date.absoluteDate } /// Enumerate dates between two intervals by adding specified time components and return an array of dates. /// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically. /// /// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, '.FailedToCalculate' /// /// - Parameters: /// - startDate: starting date /// - endDate: ending date /// - components: components to add /// - Returns: an array of DateInRegion objects public static func dates(between startDate: Date, and endDate: Date, increment components: DateComponents) -> [Date] { var dates: [Date] = [] var currentDate = startDate while (currentDate <= endDate) { dates.append(currentDate) currentDate = currentDate.add(components: components) } return dates } /// Return new date by rounding receiver to the next `value` interval. /// Interval can be `seconds` or `minutes` and you can specify the type of rounding function to use. /// /// - Parameters: /// - value: value to round /// - type: type of rounding public func roundedAt(_ value: IntervalType, type: IntervalRoundingType = .ceil) -> Date { var roundedInterval: TimeInterval = 0 let seconds = value.seconds switch type { case .round: roundedInterval = (self.timeIntervalSinceReferenceDate / seconds).rounded() * seconds case .ceil: roundedInterval = ceil(self.timeIntervalSinceReferenceDate / seconds) * seconds case .floor: roundedInterval = floor(self.timeIntervalSinceReferenceDate / seconds) * seconds } return Date(timeIntervalSinceReferenceDate: roundedInterval) } /// Returns a boolean value that indicates whether the represented absolute date uses daylight saving time when /// expressed in passed timezone. /// /// - Parameter tzName: destination timezone /// - Returns: `true` if date uses DST when represented in given timezone, `false` otherwise public func isDST(in tzName: TimeZoneName) -> Bool { return tzName.timeZone.isDaylightSavingTime(for: self) } /// The current daylight saving time offset of the represented date when expressed in passed timezone. /// /// - Parameter tzName: destination timezone /// - Returns: interval of DST expressed in seconds public func DSTOffset(in tzName: TimeZoneName) -> TimeInterval { return tzName.timeZone.daylightSavingTimeOffset(for: self) } /// The date of the next daylight saving time transition after currently represented date when expressed /// in given timezone. /// /// - Parameter tzName: destination timezone /// - Returns: next transition date public func nextDSTTransitionDate(in tzName: TimeZoneName) -> Date? { guard let next_date = tzName.timeZone.nextDaylightSavingTimeTransition(after: self) else { return nil } return next_date } } // MARK: - Sum of Dates and Date & Components public func - (lhs: Date, rhs: DateComponents) -> Date { return lhs + (-rhs) } public func + (lhs: Date, rhs: DateComponents) -> Date { return lhs.add(components: rhs) } public func + (lhs: Date, rhs: TimeInterval) -> Date { return lhs.addingTimeInterval(rhs) } public func - (lhs: Date, rhs: TimeInterval) -> Date { return lhs.addingTimeInterval(-rhs) } public func + (lhs: Date, rhs: [Calendar.Component : Int]) -> Date { return lhs.add(components: DateInRegion.componentsFrom(values: rhs)) } public func - (lhs: Date, rhs: [Calendar.Component : Int]) -> Date { return lhs.add(components: DateInRegion.componentsFrom(values: rhs, multipler: -1)) } public func - (lhs: Date, rhs: Date) -> TimeInterval { return DateTimeInterval(start: lhs, end: rhs).duration }
mit
7c2a52bdc5d6921276fc4f9bc9a6c5ac
38.505435
142
0.73105
4.088301
false
false
false
false
tensorflow/examples
lite/examples/image_segmentation/ios/ImageSegmentation/TFLite/TFLiteExtension.swift
1
3628
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreGraphics import Foundation import UIKit // MARK: - UIImage /// Extension of iOS classes that is useful for working with TensorFlow Lite computer vision models. extension UIImage { /// Make the same image with orientation being `.up`. /// - Returns: A copy of the image with .up orientation or `nil` if the image could not be /// rotated. func transformOrientationToUp() -> UIImage? { // Check if the image orientation is already .up and don't need any rotation. guard imageOrientation != UIImage.Orientation.up else { // No rotation needed so return a copy of this image. return self.copy() as? UIImage } // Make sure that this image has an CGImage attached. guard let cgImage = self.cgImage else { return nil } // Create a CGContext to draw the rotated image to. guard let colorSpace = cgImage.colorSpace, let context = CGContext( data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } var transform: CGAffineTransform = CGAffineTransform.identity // Calculate the transformation matrix that needed to bring the image orientation to .up switch imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat.pi) break case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat.pi / 2.0) break case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: CGFloat.pi / -2.0) break case .up, .upMirrored: break @unknown default: break } // If the image is mirrored then flip it. switch imageOrientation { case .upMirrored, .downMirrored: transform.translatedBy(x: size.width, y: 0) transform.scaledBy(x: -1, y: 1) break case .leftMirrored, .rightMirrored: transform.translatedBy(x: size.height, y: 0) transform.scaledBy(x: -1, y: 1) case .up, .down, .left, .right: break @unknown default: break } // Apply transformation matrix to the CGContext. context.concatenate(transform) switch imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) default: context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) break } // Create a CGImage from the context. guard let newCGImage = context.makeImage() else { return nil } // Convert it to UIImage. return UIImage.init(cgImage: newCGImage, scale: 1, orientation: .up) } }
apache-2.0
c2c6f3db9e7bc05eab524aa9d34e7f4d
33.884615
100
0.679438
4.258216
false
false
false
false
Harley-xk/HKSplitMenu
Example/Pods/Comet/Comet/Classes/Utils.swift
1
1930
// // Utils.swift // Comet // // Created by Harley.xk on 16/6/27. // // import Foundation import UIKit open class Utils { /// 设备唯一标识号 open class var deviceUUID: String { return UIDevice.current.identifierForVendor!.uuidString } /// 系统版本号 open class var systemVersion: String { return UIDevice.current.systemVersion } /// App 版本号 open class var appVersion: String { let infoDictionary = Bundle.main.infoDictionary! return infoDictionary["CFBundleShortVersionString"] as! String } /// App 版本号(含 build 号) open class var appBuild: String { let infoDictionary = Bundle.main.infoDictionary! return infoDictionary["CFBundleVersion"] as! String } /// 设备型号 /// /// @return iPhone 1,2 etc... open class var deviceModel: 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))) } return identifier } /// 电话呼叫 /// /// - Parameters: /// - phone: 被叫方的电话号码 /// - immediately: 是否跳过确认提示 /// - Return: 不支持电话功能时返回 false @discardableResult open class func call(_ phone: String, immediately: Bool = false) -> Bool { let typeString = immediately ? "tel" : "telprompt" if let callURL = URL(string: typeString + "://" + phone), UIApplication.shared.canOpenURL(callURL) { UIApplication.shared.openURL(callURL) return true } return false } }
mit
7603a8f2409f70736b99fae21ea0b49c
25.028571
97
0.601537
4.509901
false
false
false
false
ldt25290/MyInstaMap
MyInstaMap/MediaSearchAnnotation.swift
1
1975
// // MediaSearchAnnotation.swift // MyInstaMap // // Created by DucTran on 9/1/17. // Copyright © 2017 User. All rights reserved. // import MapKit @objc class MediaSearchAnnotation: NSObject { var mediaId: String? var title: String? var subtitle: String? var coordinate: CLLocationCoordinate2D var photoUrl: String? var avatarUrl: String? var postTime: String? var location: String? init(mediaId: String?, title: String?, subtitle: String?, coordinate: CLLocationCoordinate2D, photoUrl:String?, avatarUrl: String?, postTime: String?, location: String?) { self.mediaId = mediaId self.title = title self.subtitle = subtitle self.coordinate = coordinate self.photoUrl = photoUrl self.avatarUrl = avatarUrl self.postTime = postTime self.location = location } static func getPlaces(media:MediaSearchModel) -> [MediaSearchAnnotation] { guard let array = media.data else { return [] } var places = [MediaSearchAnnotation]() for item in array { let mediaId = item.mediaDataId let title = item.user?.username let subtitle = item.caption?.text let latitude = item.location?.latitude ?? 0, longitude = item.location?.longitude ?? 0 let photoUrl = item.images?.standard_resolution?.url let avatarUrl = item.user?.profile_picture let postTime = item.created_time let location = item.location?.name let place = MediaSearchAnnotation(mediaId:mediaId, title: title, subtitle: subtitle, coordinate: CLLocationCoordinate2DMake(latitude, longitude), photoUrl: photoUrl, avatarUrl: avatarUrl, postTime: postTime, location: location) places.append(place) } return places as [MediaSearchAnnotation] } } extension MediaSearchAnnotation: MKAnnotation { }
mit
d6369a7606944e489e98d5d958b55c51
34.25
239
0.642351
4.61215
false
false
false
false
michaello/Aloha
AlohaGIF/AnimationsComposer.swift
1
4557
// // AnimationsComposer.swift // AlohaGIF // // Created by Michal Pyrka on 18/04/2017. // Copyright © 2017 Michal Pyrka. All rights reserved. // import UIKit import AVFoundation struct AnimationsComposer { private enum Constants { static let startTime = 0.0 static let showAndHideAnimationDuration: Float = 4.0 } var startTime = Constants.startTime func zeroTimeAnimation(animationDestination: AnimationDestination) -> CFTimeInterval { return animationDestination == .preview ? CACurrentMediaTime() : AVCoreAnimationBeginTimeAtZero } func applyRevealAnimation(animationDestination: AnimationDestination, textLayersArrayToApply textLayers: [CATextLayer], speechModelArray: [SpeechModel], customDuration: TimeInterval? = nil, customSpeed: Float? = nil) { let animationModels = self.animationModels(speechModelArray: speechModelArray) let zippedArraysWithStartTime = zipped(textLayers: textLayers, animationModelArray: animationModels) zip(zippedArraysWithStartTime.0, zippedArraysWithStartTime.1).forEach { textLayer, animationModel in let animation = opacityAnimation(duration: customDuration ?? animationModel.duration, toValue: 1.0) if let customSpeed = customSpeed { animation.speed = customSpeed } animation.beginTime = zeroTimeAnimation(animationDestination: animationDestination) + animationModel.beginTime textLayer.add(animation, forKey: "animateOpacity") } } func applyShowAndHideAnimation(animationDestination: AnimationDestination, textLayersArrayToApply textLayers: [CATextLayer], speechModelArray: [SpeechModel], lastTextLayerDelegate: CAAnimationDelegate? = nil) { applyRevealAnimation(animationDestination: animationDestination, textLayersArrayToApply: textLayers, speechModelArray: speechModelArray, customDuration: 0.0, customSpeed: Constants.showAndHideAnimationDuration) let animationModels = self.animationModels(speechModelArray: speechModelArray) zip(textLayers, animationModels).forEach { textLayer, animationModel in let animation = opacityAnimation() animation.speed = Constants.showAndHideAnimationDuration animation.beginTime = zeroTimeAnimation(animationDestination: animationDestination) + CFTimeInterval(animationModel.finishTime) textLayer.add(animation, forKey: "animateOpacityFadeOut") } } private func animationModels(speechModelArray: [SpeechModel]) -> [AnimationModel] { return speechModelArray.map { AnimationModel(beginTime: $0.timestamp - startTime, duration: $0.duration) } } //Function for applying opacity animation for custom start time. private func zipped(textLayers: [CATextLayer], animationModelArray: [AnimationModel]) -> ([CATextLayer], [AnimationModel]) { guard textLayers.count == animationModelArray.count else { Logger.error("Warning: SpeechModels and TextLayers count don't match.") return (textLayers, animationModelArray) } guard startTime != 0.0 else { return (textLayers, animationModelArray) } let animationModelsAfterStartTime = animationModelArray .filter { $0.beginTime > startTime } .sorted { lhs, rhs in lhs.beginTime < rhs.beginTime } let firstAnimationModelAfterStartTime = animationModelsAfterStartTime.first guard let first = firstAnimationModelAfterStartTime, let index = animationModelArray.index(where: { $0.beginTime == first.beginTime }), index > 0 else { return (textLayers, animationModelArray) } var safeTextLayers = [CATextLayer]() var safeAnimationArray = [AnimationModel]() textLayers[0..<index].forEach { $0.opacity = 1.0 } for i in index..<animationModelArray.count { safeTextLayers.append(textLayers[i]) safeAnimationArray.append(animationModelArray[i]) } return (safeTextLayers, safeAnimationArray) } private func opacityAnimation(duration: CFTimeInterval = 0.0, toValue: Float = 0.0) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "opacity") animation.autoreverses = false animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false animation.repeatCount = 1 animation.toValue = toValue animation.duration = duration return animation } }
mit
c6eb71f62bba0c8379c962f3b95e723e
50.191011
222
0.71137
5.165533
false
false
false
false
renyufei8023/WeiBo
weibo/Classes/Home/Controller/BaseTableViewController.swift
1
3421
// // BaseTableViewController.swift // weibo // // Created by 任玉飞 on 16/4/25. // Copyright © 2016年 任玉飞. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { var userLogin = false override func loadView() { userLogin ? super.loadView() : setupVisitorView() } private func setupVisitorView() { } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d3dd7511bbb8690632ba57449e15142b
31.75
157
0.679096
5.574468
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/SCSFPSCheck.swift
1
9061
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // SCSFPSCheck.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. //****************************************************************************** import Foundation import MachO import UIKit import QuartzCore import Darwin struct SCSTestKeys { static let kFIFOTypeTest = "SCSFIFOSpeedTestSciChart" static let kSeriesTypeTest = "SCSNxMSeriesSpeedTestSciChart" static let kScatterTypeTest = "SCSScatterSpeedTestSciChart" static let kAppendTypeTest = "SCSAppendSpeedTestSciChart" static let kSeriesAppendTypetest = "SCSSeriesAppendingTestSciChart" } enum SCSResamplingMode : Int { case none case minMax case mid case max case min case nyquist case cluster2D case minMaxWithUnevenSpacing case auto } struct SCSTestParameters { var resamplingMode : SCSResamplingMode = .none var pointCount = 0 var seriesNumber = 0 var strokeThikness = 1.0 var appendPoints = 0 var duration: Double = 0.0 var timeScale: Double = 0.0 } protocol SCSDrawingProtocolDelegate { func processCompleted(_ testCaseData: [Any]) func processCompleted() func chartExampleStarted() } protocol SCSSpeedTestProtocol { var delegate: SCSDrawingProtocolDelegate? { get set } var chartProviderName: String { get set } func run(_ testParameters: SCSTestParameters) func updateChart() func stop() } class SCSFPSCheck <T: SCSSpeedTestProtocol> : SCSDrawingProtocolDelegate where T: UIView { var version = "" var chartTypeTest = "" var testParameters = SCSTestParameters() var displayLink : CADisplayLink! var secondDisplay : CADisplayLink! var startTime = CFTimeInterval() var frameCount = 0.0 var isCompleted = false weak var chartUIView : T! weak var parentViewController : UIViewController! var fpsdata: Double = 0.0 var cpudata: Double = 0.0 var result = [[Any]]() var testcaseName = "" var chartProviderStartTime: Date! var chartTakenTime = TimeInterval() var calculateStartTime = false var timeIsOut = false var delegate: SCSDrawingProtocolDelegate? init(_ version: String, _ chartUIView: T, _ testKey: String) { self.chartUIView = chartUIView self.version = version self.chartTypeTest = testKey testParameters = parameters(forTypeTest: chartTypeTest) } internal func processCompleted(_ testCaseData: [Any]) { } func parameters(forTypeTest typeTest: String) -> SCSTestParameters { let typeTest = typeTest.replacingOccurrences(of: "SciChartSwiftDemo.", with: "") if (typeTest == SCSTestKeys.kScatterTypeTest) { var testParameters = SCSTestParameters() testParameters.pointCount = 10000 testParameters.duration = 10.0 return testParameters } else if (typeTest == SCSTestKeys.kFIFOTypeTest) { var testParameters = SCSTestParameters() testParameters.pointCount = 1000 testParameters.strokeThikness = 1.0 testParameters.duration = 10.0 return testParameters } else if (typeTest == SCSTestKeys.kSeriesTypeTest) { var testParameters = SCSTestParameters() testParameters.seriesNumber = 100 testParameters.pointCount = 100 testParameters.strokeThikness = 1.0 testParameters.duration = 10.0 return testParameters } else if (typeTest == SCSTestKeys.kAppendTypeTest) { var testParameters = SCSTestParameters() testParameters.pointCount = 10000 testParameters.appendPoints = 1000 testParameters.strokeThikness = 1 testParameters.duration = 10.0 return testParameters } else if (typeTest == SCSTestKeys.kSeriesAppendTypetest) { var testParameters = SCSTestParameters() testParameters.pointCount = 500 testParameters.appendPoints = 500 testParameters.strokeThikness = 0.5 testParameters.duration = 30.0 testParameters.seriesNumber = 3 return testParameters } var testParameters = SCSTestParameters() testParameters.pointCount = 1000 testParameters.duration = 10.0 return testParameters } func processCompleted() { if !timeIsOut { prepareResults() } stopDisplayLink() // if chartUIView { // chartUIView.removeFromSuperview() // self.chartUIView = SpeedTest() // } if let delegate = delegate { delegate.processCompleted(result) } } func chartExampleStarted() { if calculateStartTime { chartTakenTime = fabs(chartProviderStartTime.timeIntervalSinceNow) calculateStartTime = false } } func runTest(_ vc: UIViewController) { result = [[Int]]() parentViewController = vc running() } func running() { timeIsOut = false chartProviderStartTime = Date() chartUIView.delegate = self chartUIView.run(testParameters) startDisplayLink() } func startDisplayLink() { isCompleted = false calculateStartTime = true displayLink = CADisplayLink(target: self, selector: #selector(calcFps)) startTime = CACurrentMediaTime() displayLink.add(to: RunLoop.current, forMode: .defaultRunLoopMode) } func stopDisplayLink() { isCompleted = true displayLink.invalidate() displayLink = nil } @objc func calcFps(_ displayLink: CADisplayLink) { frameCount += 1 cpudata += usageCPU().user let elapsed = displayLink.timestamp - startTime if elapsed >= testParameters.duration { timeIsOut = true prepareResults() chartUIView.stop() } else { chartUIView.updateChart() } } private func prepareResults() { let elapsed = self.displayLink.timestamp - self.startTime fpsdata = frameCount / elapsed cpudata = cpudata/frameCount self.frameCount = 0 self.startTime = self.displayLink.timestamp result.append(["", chartUIView.chartProviderName, fpsdata, cpudata, Date(timeIntervalSinceReferenceDate: chartTakenTime)]) } private let HOST_CPU_LOAD_INFO_COUNT : mach_msg_type_number_t = UInt32(MemoryLayout<host_cpu_load_info_data_t>.size / MemoryLayout<integer_t>.size) private var loadPrevious = host_cpu_load_info() public func usageCPU() -> (system : Double, user : Double, idle : Double, nice : Double) { let load = self.hostCPULoadInfo() let userDiff = Double(load.cpu_ticks.0 - loadPrevious.cpu_ticks.0) let sysDiff = Double(load.cpu_ticks.1 - loadPrevious.cpu_ticks.1) let idleDiff = Double(load.cpu_ticks.2 - loadPrevious.cpu_ticks.2) let niceDiff = Double(load.cpu_ticks.3 - loadPrevious.cpu_ticks.3) let totalTicks = sysDiff + userDiff + niceDiff + idleDiff let sys = sysDiff / totalTicks * 100.0 let user = userDiff / totalTicks * 100.0 let idle = idleDiff / totalTicks * 100.0 let nice = niceDiff / totalTicks * 100.0 loadPrevious = load // TODO: 2 decimal places // TODO: Check that total is 100% return (sys, user, idle, nice) } private func hostCPULoadInfo() -> host_cpu_load_info { var size = HOST_CPU_LOAD_INFO_COUNT var hostInfo = host_cpu_load_info() let result = withUnsafeMutablePointer(to: &hostInfo) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(size)) { host_statistics(mach_host_self(), Int32(HOST_CPU_LOAD_INFO), $0, &size) } } #if DEBUG if result != KERN_SUCCESS { print("ERROR - \(#file):\(#function) - kern_result_t = " + "\(result)") } #endif return hostInfo } }
mit
1bea9ca9576f5daf31dc615d288f4b42
30.782456
151
0.606646
4.673891
false
true
false
false
LiulietLee/Pick-Color
Pick Color/MKLayer.swift
1
11412
// // MKLayer.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit let kMKClearEffectsDuration = 0.3 open class MKLayer: CALayer, CAAnimationDelegate { open var maskEnabled: Bool = true { didSet { self.mask = maskEnabled ? maskLayer : nil } } open var rippleEnabled: Bool = true open var rippleScaleRatio: CGFloat = 1.0 { didSet { self.calculateRippleSize() } } open var rippleDuration: CFTimeInterval = 0.35 open var elevation: CGFloat = 0 { didSet { self.enableElevation() } } open var elevationOffset: CGSize = CGSize.zero { didSet { self.enableElevation() } } open var roundingCorners: UIRectCorner = UIRectCorner.allCorners { didSet { self.enableElevation() } } open var backgroundAnimationEnabled: Bool = true fileprivate weak var superView: UIView? fileprivate weak var superLayer: CALayer? fileprivate var rippleLayer: CAShapeLayer? fileprivate var backgroundLayer: CAShapeLayer? fileprivate var maskLayer: CAShapeLayer? fileprivate var userIsHolding: Bool = false fileprivate var effectIsRunning: Bool = false fileprivate override init(layer: Any) { super.init() } public init(superLayer: CALayer) { super.init() self.superLayer = superLayer setup() } public init(withView view: UIView) { super.init() self.superView = view self.superLayer = view.layer self.setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.superLayer = self.superlayer self.setup() } public func recycle() { superLayer?.removeObserver(self, forKeyPath: "bounds") superLayer?.removeObserver(self, forKeyPath: "cornerRadius") } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let keyPath = keyPath { if keyPath == "bounds" { self.superLayerDidResize() } else if keyPath == "cornerRadius" { if let superLayer = superLayer { setMaskLayerCornerRadius(superLayer.cornerRadius) } } } } open func superLayerDidResize() { if let superLayer = self.superLayer { CATransaction.begin() CATransaction.setDisableActions(true) self.frame = superLayer.bounds self.setMaskLayerCornerRadius(superLayer.cornerRadius) self.calculateRippleSize() CATransaction.commit() } } open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if anim == self.animation(forKey: "opacityAnim") { self.opacity = 0 } else if flag { if userIsHolding { effectIsRunning = false } else { self.clearEffects() } } } open func startEffects(atLocation touchLocation: CGPoint) { userIsHolding = true if let rippleLayer = self.rippleLayer { rippleLayer.timeOffset = 0 rippleLayer.speed = backgroundAnimationEnabled ? 1 : 1.1 if rippleEnabled { startRippleEffect(nearestInnerPoint(touchLocation)) } } } open func stopEffects() { userIsHolding = false if !effectIsRunning { self.clearEffects() } else if let rippleLayer = rippleLayer { rippleLayer.timeOffset = rippleLayer.convertTime(CACurrentMediaTime(), from: nil) rippleLayer.beginTime = CACurrentMediaTime() rippleLayer.speed = 1.2 } } open func stopEffectsImmediately() { userIsHolding = false effectIsRunning = false if rippleEnabled { if let rippleLayer = self.rippleLayer, let backgroundLayer = self.backgroundLayer { rippleLayer.removeAllAnimations() backgroundLayer.removeAllAnimations() rippleLayer.opacity = 0 backgroundLayer.opacity = 0 } } } open func setRippleColor(_ color: UIColor, withRippleAlpha rippleAlpha: CGFloat = 0.3, withBackgroundAlpha backgroundAlpha: CGFloat = 0.3) { if let rippleLayer = self.rippleLayer, let backgroundLayer = self.backgroundLayer { rippleLayer.fillColor = color.withAlphaComponent(rippleAlpha).cgColor backgroundLayer.fillColor = color.withAlphaComponent(backgroundAlpha).cgColor } } // MARK: Touches open func touchesBegan(_ touches: Set<UITouch>, withEvent event: UIEvent?) { if let first = touches.first, let superView = self.superView { let point = first.location(in: superView) startEffects(atLocation: point) } } open func touchesEnded(_ touches: Set<UITouch>, withEvent event: UIEvent?) { self.stopEffects() } open func touchesCancelled(_ touches: Set<UITouch>?, withEvent event: UIEvent?) { self.stopEffects() } open func touchesMoved(_ touches: Set<UITouch>, withEvent event: UIEvent?) { } // MARK: Private fileprivate func setup() { rippleLayer = CAShapeLayer() rippleLayer!.opacity = 0 self.addSublayer(rippleLayer!) backgroundLayer = CAShapeLayer() backgroundLayer!.opacity = 0 backgroundLayer!.frame = superLayer!.bounds self.addSublayer(backgroundLayer!) maskLayer = CAShapeLayer() self.setMaskLayerCornerRadius(superLayer!.cornerRadius) self.mask = maskLayer self.frame = superLayer!.bounds superLayer!.addSublayer(self) superLayer!.addObserver( self, forKeyPath: "bounds", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) superLayer!.addObserver( self, forKeyPath: "cornerRadius", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) self.enableElevation() self.superLayerDidResize() } fileprivate func setMaskLayerCornerRadius(_ radius: CGFloat) { if let maskLayer = self.maskLayer { maskLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: radius).cgPath } } fileprivate func nearestInnerPoint(_ point: CGPoint) -> CGPoint { let centerX = self.bounds.midX let centerY = self.bounds.midY let dx = point.x - centerX let dy = point.y - centerY let dist = sqrt(dx * dx + dy * dy) if let backgroundLayer = self.rippleLayer { // TODO: Fix it if dist <= backgroundLayer.bounds.size.width / 2 { return point } let d = backgroundLayer.bounds.size.width / 2 / dist let x = centerX + d * (point.x - centerX) let y = centerY + d * (point.y - centerY) return CGPoint(x: x, y: y) } return CGPoint.zero } fileprivate func clearEffects() { if let rippleLayer = self.rippleLayer, let backgroundLayer = self.backgroundLayer { rippleLayer.timeOffset = 0 rippleLayer.speed = 1 if rippleEnabled { rippleLayer.removeAllAnimations() backgroundLayer.removeAllAnimations() self.removeAllAnimations() let opacityAnim = CABasicAnimation(keyPath: "opacity") opacityAnim.fromValue = 1 opacityAnim.toValue = 0 opacityAnim.duration = kMKClearEffectsDuration opacityAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) opacityAnim.isRemovedOnCompletion = false opacityAnim.fillMode = kCAFillModeForwards opacityAnim.delegate = self self.add(opacityAnim, forKey: "opacityAnim") } } } fileprivate func startRippleEffect(_ touchLocation: CGPoint) { self.removeAllAnimations() self.opacity = 1 if let rippleLayer = self.rippleLayer, let backgroundLayer = self.backgroundLayer, let superLayer = self.superLayer { rippleLayer.removeAllAnimations() backgroundLayer.removeAllAnimations() let scaleAnim = CABasicAnimation(keyPath: "transform.scale") scaleAnim.fromValue = 0 scaleAnim.toValue = 1 scaleAnim.duration = rippleDuration scaleAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) scaleAnim.delegate = self let moveAnim = CABasicAnimation(keyPath: "position") moveAnim.fromValue = NSValue(cgPoint: touchLocation) moveAnim.toValue = NSValue(cgPoint: CGPoint( x: superLayer.bounds.midX, y: superLayer.bounds.midY)) moveAnim.duration = rippleDuration moveAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) effectIsRunning = true rippleLayer.opacity = 1 if backgroundAnimationEnabled { backgroundLayer.opacity = 1 } else { backgroundLayer.opacity = 0 } rippleLayer.add(moveAnim, forKey: "position") rippleLayer.add(scaleAnim, forKey: "scale") } } fileprivate func calculateRippleSize() { if let superLayer = self.superLayer { let superLayerWidth = superLayer.bounds.width let superLayerHeight = superLayer.bounds.height let center = CGPoint( x: superLayer.bounds.midX, y: superLayer.bounds.midY) let circleDiameter = sqrt( powf(Float(superLayerWidth), 2) + powf(Float(superLayerHeight), 2)) * Float(rippleScaleRatio) let subX = center.x - CGFloat(circleDiameter) / 2 let subY = center.y - CGFloat(circleDiameter) / 2 if let rippleLayer = self.rippleLayer { rippleLayer.frame = CGRect( x: subX, y: subY, width: CGFloat(circleDiameter), height: CGFloat(circleDiameter)) rippleLayer.path = UIBezierPath(ovalIn: rippleLayer.bounds).cgPath if let backgroundLayer = self.backgroundLayer { backgroundLayer.frame = rippleLayer.frame backgroundLayer.path = rippleLayer.path } } } } fileprivate func enableElevation() { if let superLayer = self.superLayer { superLayer.shadowOpacity = 0.5 superLayer.shadowRadius = elevation / 4 superLayer.shadowColor = UIColor.black.cgColor superLayer.shadowOffset = elevationOffset } } }
mit
a0c076d619df698d992bcc7068dd26ce
32.863501
156
0.592096
5.542496
false
false
false
false
Ericdowney/GameOfGuilds
Guilds/Guilds/GuildsViewController.swift
1
2305
// // GuildsViewController.swift // Guilds // // Created by Downey, Eric on 11/21/15. // Copyright © 2015 ICCT. All rights reserved. // import UIKit public class GuildsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var guildsTable: UITableView! var guildLogic: GuildsViewLogic? var guilds: [Guild] = [] override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if self.guildLogic == nil { let wrapper = (UIApplication.sharedApplication().delegate as! AppDelegate).parseWrapper self.guildLogic = GuildsViewLogic(wrapper: wrapper) } } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.guildLogic?.getGuilds { gds in self.guilds = gds self.guildsTable.reloadData() } } // MARK: - Segue public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) guard let guildProfileViewCtrl = segue.destinationViewController as? GuildProfileViewController else { return; } guard let indexPath = self.guildsTable.indexPathForSelectedRow else { return; } self.guildsTable.deselectRowAtIndexPath(indexPath, animated: true) guildProfileViewCtrl.setGuild(self.guilds[indexPath.row]) } // MARK: - Table View public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.guilds.count; } public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "All Guilds"; } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell cell.textLabel?.text = self.guilds[indexPath.row].guildName return cell; } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {} }
mit
ca8169997c68a15962770d76b2761e50
32.405797
116
0.664063
5.200903
false
false
false
false
luinily/hOme
hOme/UI/IRKitConnectorEditorTableDelegate.swift
1
2831
// // IRKitConnectorEditorTableDelegate.swift // hOme // // Created by Coldefy Yoann on 2016/02/20. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class IRKitConnectorEditorTableDelegate: NSObject, UITableViewDataSource, UITableViewDelegate { private let _sectionName = 0 private let _sectionProperties = 1 private let _rowBonjourName = 0 private let _rowIP = 1 private var _irKitConnector: IRKitConnector? func setConnector(connector: IRKitConnector) { _irKitConnector = connector } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "" } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == _sectionName { return 1 } else if section == _sectionProperties { return 2 } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") cell.textLabel?.text = getCellText(indexPath) setCellAccessory(cell, indexPath: indexPath) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case _sectionName: showNameEditView() case _sectionProperties: if indexPath.row == _rowBonjourName { showSelectBonjourNameView() } default: break } } private func getCellText(indexPath: NSIndexPath) -> String { switch indexPath.section { case _sectionName: return "Name" case _sectionProperties: switch indexPath.row { case _rowBonjourName : return "Bonjour Name" case _rowIP : return "IP Address" default: return "" } default: return "" } } private func setCellAccessory(cell: UITableViewCell, indexPath: NSIndexPath) { switch indexPath.section { case _sectionName: let label = UILabel() label.text = _irKitConnector?.name cell.accessoryView = label cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator case _sectionProperties: switch indexPath.row { case _rowBonjourName : let label = UILabel() label.text = _irKitConnector?.bonjourName cell.accessoryView = label cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton case _rowIP : let label = UILabel() label.text = _irKitConnector?.ipAddress cell.accessoryView = label cell.accessoryType = UITableViewCellAccessoryType.None default: cell.accessoryType = UITableViewCellAccessoryType.None } default: return } } private func showNameEditView() { } private func showSelectBonjourNameView() { } }
mit
a95cad8abe1f3cad999105203d75139a
24.25
108
0.735149
4.092619
false
false
false
false
getaaron/zombie
zombie/zombie/ViewController.swift
1
9893
// // ViewController.swift // zombie // // Created by Aaron on 4/27/15. // Copyright (c) 2015 Aaron Brager. All rights reserved. // import UIKit import ResearchKit class ViewController: UIViewController, ORKTaskViewControllerDelegate { var taskViewController : ORKTaskViewController! var PDFData : NSData? @IBOutlet weak var viewPDFButton: UIButton! @IBOutlet weak var surveyButton: UIButton! @IBOutlet weak var walkingTestButton: UIButton! // MARK: - Button Outlets @IBAction func consentTapped(sender: UIButton) { presentTask(consentTask()) } @IBAction func viewPDFTapped(sender: UIButton) { let webVC = self.storyboard!.instantiateViewControllerWithIdentifier("webViewController") as! UIViewController let webView = webVC.view as! UIWebView webView.loadData(PDFData, MIMEType: "application/pdf", textEncodingName: "UTF-8", baseURL: nil) self.navigationController?.pushViewController(webVC, animated: true) } @IBAction func surveyTapped(sender: UIButton) { presentTask(surveyTask()) } @IBAction func walkingTestTapped(sender: UIButton) { presentTask(walkTask()) } func presentTask(task : ORKTask) { taskViewController = ORKTaskViewController(task: task, taskRunUUID: NSUUID()) taskViewController.outputDirectory = path() taskViewController.delegate = self presentViewController(taskViewController, animated: true, completion: nil) } // MARK: - ORKTaskViewControllerDelegate methods func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) { switch taskViewController.task?.identifier { case .Some("ordered task identifier"): generatePDFData() default: break } printDataWithResult(taskViewController.result) taskViewController.dismissViewControllerAnimated(true, completion: nil) } func path() -> NSURL { return NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String, isDirectory: true)! } func printDataWithResult(result : ORKResult) { var error : NSError? = nil if let object = ORKESerializer.JSONObjectForObject(result, error: &error) { println("Results JSON:\n\n\(object)") } else { println("Error:\n\n\(error)") } } } // MARK: - Consent functions extension ViewController { func generatePDFData() { let document = consentDocument.copy() as! ORKConsentDocument // This works if let signatureResult = taskViewController.result.stepResultForStepIdentifier("consent review step identifier")?.firstResult as? ORKConsentSignatureResult { signatureResult.applyToDocument(document) } document.makePDFWithCompletionHandler { (data, error) -> Void in if let data = data where data.length > 0 { // data is not nil self.PDFData = data self.viewPDFButton.hidden = false } } } func consentTask() -> ORKOrderedTask { var steps = consentSteps() return ORKOrderedTask(identifier: "ordered task identifier", steps: steps) } func consentSteps () -> [ORKStep] { var steps = [ORKStep]() // A visual consent step describes the technical consent document simply let visualConsentStep = ORKVisualConsentStep(identifier: "visual consent step identifier", document: consentDocument) steps += [visualConsentStep] // A consent sharing step tells the user how you'll share their stuff let sharingConsentStep = ORKConsentSharingStep(identifier: "consent sharing step identifier", investigatorShortDescription: "Zombie Research Corp™", investigatorLongDescription: "The Zombie Research Corporation™ and related undead research partners", localizedLearnMoreHTMLContent: "Zombie Research Corporation™ will only transmit your personal data to other partners that also study the undead, including the Werewolf Research Corporation™ and Vampire Research Corporation™.") steps += [sharingConsentStep] // A consent review step reviews the consent document and gets a signature let signature = consentDocument.signatures!.first as! ORKConsentSignature let reviewConsentStep = ORKConsentReviewStep(identifier: "consent review step identifier", signature: signature, inDocument: consentDocument) reviewConsentStep.text = "I love, and agree to perform, zombie research." reviewConsentStep.reasonForConsent = "Zombie research is important." steps += [reviewConsentStep] return steps } private var consentDocument: ORKConsentDocument { // Create the document let consentDocument = ORKConsentDocument() consentDocument.title = "Consent to Zombie Research" consentDocument.signaturePageTitle = "Consent Signature" consentDocument.signaturePageContent = "I agree to participate in this zombie-related research study." // Add participant signature let participantSignature = ORKConsentSignature(forPersonWithTitle: "Participant", dateFormatString: nil, identifier: "participant signature identifier") consentDocument.addSignature(participantSignature) // Add investigator signature for the PDF. let investigatorSignature = ORKConsentSignature(forPersonWithTitle: "Zombie Investigator", dateFormatString: nil, identifier: "investigator signature identifier", givenName: "George", familyName: "A. Romero", signatureImage: UIImage(named: "signature")!, dateString: "10/1/1968") consentDocument.addSignature(investigatorSignature) // Create "consent sections" in case the user wants more details before giving consent let consentOverview = ORKConsentSection(type: .Overview) consentOverview.content = "It's important to research zombies so we can get rid of them. Thanks in advance for all of your help researching them." let consentPrivacy = ORKConsentSection(type: .Privacy) consentPrivacy.content = "All information will be strictly confidential, unless a zombie eats your braaaaaaaaains…" let consentTimeCommitment = ORKConsentSection(type: .TimeCommitment) consentTimeCommitment.content = "This shouldn't take too long… as long as the zombies don't move too fast." consentDocument.sections = [consentOverview, consentPrivacy, consentTimeCommitment] return consentDocument } } // MARK: - Survey functions extension ViewController { func surveyTask() -> ORKOrderedTask { var steps = surveySteps() return ORKOrderedTask(identifier: "ordered task identifier", steps: steps) } func surveySteps () -> [ORKStep] { var steps = [ORKStep]() // ORKQuestionStep asks questions and accepts answers based on the ORKAnswerFormat provided // ORKScaleAnswerFormat presents a slider to pick a number from a scale let scaleAnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSInteger.max, step: 1, vertical: false) let scaleQuestionStep = ORKQuestionStep(identifier: "scale question step identifier", title: "Likelihood to Eat Brains", answer: scaleAnswerFormat) scaleQuestionStep.text = "If presented with a giant plate of delicious brains, how likely would you be to eat them?" steps += [scaleQuestionStep] // ORKValuePickerAnswerFormat lets the user pick from a list let choices = [ORKTextChoice(text: "Angry and Vindictive", value: "angry"), ORKTextChoice(text: "Extremely Hungry", value: "hungry"), ORKTextChoice(text: "Even-Tempered", value: "normal")] let valuePickerAnswerFormat = ORKAnswerFormat.valuePickerAnswerFormatWithTextChoices(choices) let valuePickerQuestionStep = ORKQuestionStep(identifier: "value picker question step identifier", title: "Current Feelings", answer: valuePickerAnswerFormat) valuePickerQuestionStep.text = "What's the primary emotion you're feeling right now?" steps += [valuePickerQuestionStep] // ORKBooleanAnswerFormat lets the user pick Yes or No let booleanAnswerFormat = ORKBooleanAnswerFormat() let booleanQuestionStep = ORKQuestionStep(identifier: "boolean question step identifier", title: "Is your body fully intact?", answer: booleanAnswerFormat) steps += [booleanQuestionStep] // ORKCompletionStep lets the user know they've finished a task let completionStep = ORKCompletionStep(identifier: "completion step identifier") completionStep.title = "Hey, Thanks!" completionStep.text = "Thank you for your continued efforts to eradicate zombies." steps += [completionStep] return steps } } // MARK: - AMC's The Walking Test extension ViewController { func walkTask() -> ORKOrderedTask { // Creates a pre-defined Active Task to measure walking return ORKOrderedTask.shortWalkTaskWithIdentifier("short walk task identifier", intendedUseDescription: "Zombies and humans walk differently. Take this test to measure how you walk.", numberOfStepsPerLeg: 20, restDuration: 20, options: nil) } }
mit
63ab5d7e7d3762e6b53abeb3770ded7d
41.770563
248
0.682357
5.191277
false
false
false
false
karimsallam/Reactive
Pods/ReactiveSwift/Sources/Scheduler.swift
2
17286
// // Scheduler.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-06-02. // Copyright (c) 2014 GitHub. All rights reserved. // import Dispatch import Foundation #if os(Linux) import let CDispatch.NSEC_PER_SEC #endif /// Represents a serial queue of work items. public protocol SchedulerProtocol { /// Enqueues an action on the scheduler. /// /// When the work is executed depends on the scheduler in use. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(_ action: @escaping () -> Void) -> Disposable? } /// A particular kind of scheduler that supports enqueuing actions at future /// dates. public protocol DateSchedulerProtocol: SchedulerProtocol { /// The current date, as determined by this scheduler. /// /// This can be implemented to deterministically return a known date (e.g., /// for testing purposes). var currentDate: Date { get } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: Starting time. /// - action: Closure of the action to perform. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? /// Schedules a recurring action at the given interval, beginning at the /// given date. /// /// - parameters: /// - date: Starting time. /// - repeatingEvery: Repetition interval. /// - withLeeway: Some delta for repetition. /// - action: Closure of the action to perform. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? } /// A scheduler that performs all work synchronously. public final class ImmediateScheduler: SchedulerProtocol { public init() {} /// Immediately calls passed in `action`. /// /// - parameters: /// - action: Closure of the action to perform. /// /// - returns: `nil`. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { action() return nil } } /// A scheduler that performs all work on the main queue, as soon as possible. /// /// If the caller is already running on the main queue when an action is /// scheduled, it may be run synchronously. However, ordering between actions /// will always be preserved. public final class UIScheduler: SchedulerProtocol { private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>() private static let dispatchSpecificValue = UInt8.max private static var __once: () = { DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey, value: dispatchSpecificValue) }() #if os(Linux) private var queueLength: Atomic<Int32> = Atomic(0) #else private var queueLength: Int32 = 0 #endif /// Initializes `UIScheduler` public init() { /// This call is to ensure the main queue has been setup appropriately /// for `UIScheduler`. It is only called once during the application /// lifetime, since Swift has a `dispatch_once` like mechanism to /// lazily initialize global variables and static variables. _ = UIScheduler.__once } /// Queues an action to be performed on main queue. If the action is called /// on the main thread and no work is queued, no scheduling takes place and /// the action is called instantly. /// /// - parameters: /// - action: Closure of the action to perform on the main thread. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let disposable = SimpleDisposable() let actionAndDecrement = { if !disposable.isDisposed { action() } #if os(Linux) self.queueLength.modify { $0 -= 1 } #else OSAtomicDecrement32(&self.queueLength) #endif } #if os(Linux) let queued = self.queueLength.modify { value -> Int32 in value += 1 return value } #else let queued = OSAtomicIncrement32(&queueLength) #endif // If we're already running on the main queue, and there isn't work // already enqueued, we can skip scheduling and just execute directly. if queued == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue { actionAndDecrement() } else { DispatchQueue.main.async(execute: actionAndDecrement) } return disposable } } /// A scheduler backed by a serial GCD queue. public final class QueueScheduler: DateSchedulerProtocol { /// A singleton `QueueScheduler` that always targets the main thread's GCD /// queue. /// /// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a /// future date, and will always schedule asynchronously (even if /// already running on the main thread). public static let main = QueueScheduler(internalQueue: DispatchQueue.main) public var currentDate: Date { return Date() } public let queue: DispatchQueue internal init(internalQueue: DispatchQueue) { queue = internalQueue } /// Initializes a scheduler that will target the given queue with its /// work. /// /// - note: Even if the queue is concurrent, all work items enqueued with /// the `QueueScheduler` will be serial with respect to each other. /// /// - warning: Obsoleted in OS X 10.11 @available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead") @available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.") public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") { self.init(internalQueue: DispatchQueue(label: name, target: queue)) } /// Initializes a scheduler that creates a new serial queue with the /// given quality of service class. /// /// - parameters: /// - qos: Dispatch queue's QoS value. /// - name: Name for the queue in the form of reverse domain. /// - targeting: (Optional) The queue on which this scheduler's work is /// targeted @available(OSX 10.10, *) public convenience init( qos: DispatchQoS = .default, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler", targeting targetQueue: DispatchQueue? = nil ) { self.init(internalQueue: DispatchQueue( label: name, qos: qos, target: targetQueue )) } /// Schedules action for dispatch on internal queue /// /// - parameters: /// - action: Closure of the action to schedule. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let d = SimpleDisposable() queue.async { if !d.isDisposed { action() } } return d } private func wallTime(with date: Date) -> DispatchWallTime { let (seconds, frac) = modf(date.timeIntervalSince1970) let nsec: Double = frac * Double(NSEC_PER_SEC) let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec)) return DispatchWallTime(timespec: walltime) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: Starting time. /// - action: Closure of the action to perform. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { let d = SimpleDisposable() queue.asyncAfter(wallDeadline: wallTime(with: date)) { if !d.isDisposed { action() } } return d } /// Schedules a recurring action at the given interval and beginning at the /// given start time. A reasonable default timer interval leeway is /// provided. /// /// - parameters: /// - date: Date to schedule the first action for. /// - repeatingEvery: Repetition interval. /// - action: Closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action) } /// Schedules a recurring action at the given interval with provided leeway, /// beginning at the given start time. /// /// - parameters: /// - date: Date to schedule the first action for. /// - repeatingEvery: Repetition interval. /// - leeway: Some delta for repetition interval. /// - action: Closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { precondition(interval.timeInterval >= 0) precondition(leeway.timeInterval >= 0) let timer = DispatchSource.makeTimerSource( flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue ) timer.scheduleRepeating(wallDeadline: wallTime(with: date), interval: interval, leeway: leeway) timer.setEventHandler(handler: action) timer.resume() return ActionDisposable { timer.cancel() } } } /// A scheduler that implements virtualized time, for use in testing. public final class TestScheduler: DateSchedulerProtocol { private final class ScheduledAction { let date: Date let action: () -> Void init(date: Date, action: @escaping () -> Void) { self.date = date self.action = action } func less(_ rhs: ScheduledAction) -> Bool { return date.compare(rhs.date) == .orderedAscending } } private let lock = NSRecursiveLock() private var _currentDate: Date /// The virtual date that the scheduler is currently at. public var currentDate: Date { let d: Date lock.lock() d = _currentDate lock.unlock() return d } private var scheduledActions: [ScheduledAction] = [] /// Initializes a TestScheduler with the given start date. /// /// - parameters: /// - startDate: The start date of the scheduler. public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) { lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler" _currentDate = startDate } private func schedule(_ action: ScheduledAction) -> Disposable { lock.lock() scheduledActions.append(action) scheduledActions.sort { $0.less($1) } lock.unlock() return ActionDisposable { self.lock.lock() self.scheduledActions = self.scheduledActions.filter { $0 !== action } self.lock.unlock() } } /// Enqueues an action on the scheduler. /// /// - note: The work is executed on `currentDate` as it is understood by the /// scheduler. /// /// - parameters: /// - action: An action that will be performed on scheduler's /// `currentDate`. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: currentDate, action: action)) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: Starting date. /// - action: Closure of the action to perform. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), action: action) } @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: date, action: action)) } /// Schedules a recurring action at the given interval, beginning at the /// given start time /// /// - parameters: /// - date: Date to schedule the first action for. /// - repeatingEvery: Repetition interval. /// - action: Closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) { precondition(interval.timeInterval >= 0) disposable.innerDisposable = schedule(after: date) { [unowned self] in action() self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action) } } /// Schedules a recurring action at the given interval, beginning at the /// given interval (counted from `currentDate`). /// /// - parameters: /// - interval: Interval to add to `currentDate`. /// - repeatingEvery: Repetition interval. /// - leeway: Some delta for repetition interval. /// - action: Closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action) } /// Schedules a recurring action at the given interval with /// provided leeway, beginning at the given start time. /// /// - parameters: /// - date: Date to schedule the first action for. /// - repeatingEvery: Repetition interval. /// - leeway: Some delta for repetition interval. /// - action: Closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { let disposable = SerialDisposable() schedule(after: date, interval: interval, disposable: disposable, action: action) return disposable } /// Advances the virtualized clock by an extremely tiny interval, dequeuing /// and executing any actions along the way. /// /// This is intended to be used as a way to execute actions that have been /// scheduled to run as soon as possible. public func advance() { advance(by: .nanoseconds(1)) } /// Advances the virtualized clock by the given interval, dequeuing and /// executing any actions along the way. /// /// - parameters: /// - interval: Interval by which the current date will be advanced. public func advance(by interval: DispatchTimeInterval) { lock.lock() advance(to: currentDate.addingTimeInterval(interval)) lock.unlock() } /// Advances the virtualized clock to the given future date, dequeuing and /// executing any actions up until that point. /// /// - parameters: /// - newDate: Future date to which the virtual clock will be advanced. public func advance(to newDate: Date) { lock.lock() assert(currentDate.compare(newDate) != .orderedDescending) while scheduledActions.count > 0 { if newDate.compare(scheduledActions[0].date) == .orderedAscending { break } _currentDate = scheduledActions[0].date let scheduledAction = scheduledActions.remove(at: 0) scheduledAction.action() } _currentDate = newDate lock.unlock() } /// Dequeues and executes all scheduled actions, leaving the scheduler's /// date at `NSDate.distantFuture()`. public func run() { advance(to: Date.distantFuture) } /// Rewinds the virtualized clock by the given interval. /// This simulates that user changes device date. /// /// - parameters: /// - interval: Interval by which the current date will be retreated. public func rewind(by interval: DispatchTimeInterval) { lock.lock() let newDate = currentDate.addingTimeInterval(-interval) assert(currentDate.compare(newDate) != .orderedAscending) _currentDate = newDate lock.unlock() } }
apache-2.0
bfbeb6c8c4a42d8cc7171b44a8efac0c
31.863118
179
0.690212
3.920617
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/VanishAccountPopUpAlertView.swift
1
9666
import SwiftUI import WMF struct VanishAccountPopUpAlertView: View { var theme: Theme @Binding var isVisible: Bool @Binding var userInput: String private let titleFont = UIFont.wmf_scaledSystemFont(forTextStyle: .headline, weight: .semibold, size: 18) private let bodyFont = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .regular, size: 15) private let boldFont = UIFont.wmf_scaledSystemFont(forTextStyle: .headline, weight: .bold, size: 18) enum LocalizedStrings { static let title = WMFLocalizedString("vanish-modal-title", value: "Vanishing request", comment: "Title text fot the vanish request modal") static let learnMoreButtonText = CommonStrings.learnMoreButtonText } var body: some View { GeometryReader { geometry in ZStack { Color.black.opacity(isVisible ? 0.3 : 0).edgesIgnoringSafeArea(.all) if isVisible { ScrollView(.vertical, showsIndicators: false) { Spacer() .frame(height: getSpacerHeight(height: geometry.size.height)) VStack(alignment: .center, spacing: 0) { Text(LocalizedStrings.title) .frame(alignment: .center) .fixedSize(horizontal: false, vertical: true) .font(Font(titleFont)) .foregroundColor(Color(theme.colors.primaryText)) .padding(20) Spacer() Image("vanish-account-two-tone") .resizable() .scaledToFill() .frame(width: 85, height: 85, alignment: .center) BulletListView(theme: theme) .background(Color(theme.colors.paperBackground)) .padding([.top, .leading, .trailing], 20) .frame(maxWidth: .infinity, minHeight: 240, alignment: .leading) if #unavailable(iOS 15) { HStack { Button(action: { goToVanishPage() }, label: { Text(LocalizedStrings.learnMoreButtonText) .font(Font(bodyFont)) .foregroundColor(Color(theme.colors.link)) .frame(height: 25, alignment: .center) .background(Color(theme.colors.paperBackground)) }) .padding(.bottom, 20) .frame(height: 25, alignment: .center) Spacer() } .padding(30) .frame(maxHeight: 25) } Divider() Button(action: { withAnimation(.linear(duration: 0.3)) { userInput = "" isVisible = false } }, label: { Text(CommonStrings.okTitle) .frame(maxWidth: .infinity) .frame(height: 43, alignment: .center) .foregroundColor(Color(theme.colors.link)) .font(Font(boldFont)) }).buttonStyle(PlainButtonStyle()) .frame(height: 43) } .frame(width: 300) .frame(minHeight: 470) .background(Color(theme.colors.paperBackground)) .cornerRadius(14) } Spacer() } }.frame(minHeight: geometry.size.height) } } func goToVanishPage() { if let url = URL(string: "https://meta.wikimedia.org/wiki/Right_to_vanish") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } func getSpacerHeight(height: CGFloat) -> CGFloat { if height > 470 { return (height - 470) / 2 } return height / 5 } } struct BulletListView: View { var theme: Theme @SwiftUI.State var orientation = UIDeviceOrientation.unknown enum LocalizedStrings { static let title = WMFLocalizedString("vanish-modal-title", value: "Vanishing request", comment: "Title text fot the vanish request modal") static let firstItem = WMFLocalizedString("vanish-modal-item", value: "If you completed your vanishing request, please allow a couple of days for the request to be processed by an administrator", comment: "Text indicating that the process of vanishing might take days to be completed") static let secondItem = WMFLocalizedString("vanish-modal-item-2", value: "If you are unsure if your request went through please check your Mail app", comment: "Text indicating that the user should check if their email was sent in the Mail app used to send the message") static let thirdItem = WMFLocalizedString("vanish-modal-item-3", value: "If you have further questions about vanishing please visit Meta:Right_to_vanish", comment: "Informative text indicating more information is available at the Meta-wiki page Right to vanish") @available(iOS 15, *) static var thirdItemiOS15: AttributedString? = { let localizedString = WMFLocalizedString("vanish-modal-item-3-ios15", value: "If you have further questions about vanishing please visit %1$@Meta:Right_to_vanish%2$@%3$@", comment: "Informative text indicating more information is available at a Wikipedia page, contains link to page. The parameters do not require translation, as they are used for markdown formatting. Parameters:\n* %1$@ - app-specific non-text formatting, %2$@ - app-specific non-text formatting, %3$@ - app-specific non-text formatting") let substitutedString = String.localizedStringWithFormat( localizedString, "[", "]", "(https://meta.wikimedia.org/wiki/Right_to_vanish)" ) return try? AttributedString(markdown: substitutedString) }() } private let bodyFont = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .regular, size: 15) var body: some View { VStack { HStack { BulletView(theme: theme, height: 52) Text(LocalizedStrings.firstItem) .fixedSize(horizontal: false, vertical: true) .font(Font(bodyFont)) .frame(maxWidth: .infinity, minHeight: 75, alignment: .leading) .foregroundColor(Color(theme.colors.primaryText)) } HStack { BulletView(theme: theme, height: 40) Text(LocalizedStrings.secondItem) .fixedSize(horizontal: false, vertical: true) .font(Font(bodyFont)) .frame(maxWidth: .infinity, minHeight: 70, alignment: .leading) .foregroundColor(Color(theme.colors.primaryText)) } HStack { BulletView(theme: theme, height: 44) if #available(iOS 15, *) { if let text = LocalizedStrings.thirdItemiOS15 { Text(text) .fixedSize(horizontal: false, vertical: true) .font(Font(bodyFont)) .frame(maxWidth: .infinity, minHeight: 70, alignment: .leading) .foregroundColor(Color(theme.colors.primaryText)) .padding(.bottom, 10) } else { Text(LocalizedStrings.thirdItem) .fixedSize(horizontal: false, vertical: true) .font(Font(bodyFont)) .frame(maxWidth: .infinity, minHeight: 70, alignment: .leading) .foregroundColor(Color(theme.colors.primaryText)) .padding(.bottom, 10) } } else { Text(LocalizedStrings.thirdItem) .fixedSize(horizontal: false, vertical: true) .font(Font(bodyFont)) .frame(maxWidth: .infinity, minHeight: 70, alignment: .leading) .foregroundColor(Color(theme.colors.primaryText)) .padding(.bottom, 10) } } } } } struct BulletView: View { var theme: Theme var height: CGFloat var body: some View { VStack { Circle() .frame(width: 3, height: 3, alignment: .top) .foregroundColor(Color(theme.colors.primaryText)) Spacer() }.frame(maxHeight: height, alignment: .leading) } }
mit
6af74ba8d33ec7e15fda3ce2fa200aad
49.082902
519
0.498552
5.561565
false
false
false
false
esttorhe/RxSwift
RxTests/RxSwiftTests/Tests/Observable+AggregateTest.swift
1
9627
// // Observable+AggregateTest.swift // Rx // // Created by Krunoslav Zaher on 4/2/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift class ObservableAggregateTest : RxTest { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } extension ObservableAggregateTest { func test_AggregateWithSeed_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(250) ]) let res = scheduler.start { xs >- aggregate(42, +) } let correctMessages = [ next(250, 42), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeed_Return() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 24), completed(250) ]) let res = scheduler.start { xs >- aggregate(42, +) } let correctMessages = [ next(250, 42 + 24), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeed_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), error(210, testError), ]) let res = scheduler.start { xs >- aggregate(42, +) } let correctMessages: [Recorded<Int>] = [ error(210, testError) ] let correctSubscriptions = [ Subscription(200, 210) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeed_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs >- aggregate(42, +) } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeed_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 3), next(250, 4), completed(260) ]) let res = scheduler.start { xs >- aggregate(42, +) } let correctMessages: [Recorded<Int>] = [ next(260, 42 + 0 + 1 + 2 + 3 + 4), completed(260) ] let correctSubscriptions = [ Subscription(200, 260) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeed_AccumulatorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 3), next(250, 4), completed(260) ]) let res = scheduler.start { xs >- aggregateOrDie(42, { $1 < 3 ? success($0 + $1) : failure(testError)}) } let correctMessages: [Recorded<Int>] = [ error(240, testError) ] let correctSubscriptions = [ Subscription(200, 240) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(250) ]) let res = scheduler.start { xs >- aggregate(42, +, { $0 * 5 }) } let correctMessages = [ next(250, 42 * 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_Return() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 24), completed(250) ]) let res = scheduler.start { xs >- aggregate(42, { $0 + $1 }, { $0 * 5 }) } let correctMessages = [ next(250, (42 + 24) * 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), error(210, testError), ]) let res = scheduler.start { xs >- aggregate(42, { $0 + $1 }, { $0 * 5 }) } let correctMessages: [Recorded<Int>] = [ error(210, testError) ] let correctSubscriptions = [ Subscription(200, 210) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs >- aggregate(42, { $0 + $1 }, { $0 * 5 }) } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 3), next(250, 4), completed(260) ]) let res = scheduler.start { xs >- aggregate(42, { $0 + $1 }, { $0 * 5 }) } let correctMessages: [Recorded<Int>] = [ next(260, (42 + 0 + 1 + 2 + 3 + 4) * 5), completed(260) ] let correctSubscriptions = [ Subscription(200, 260) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_AccumulatorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 3), next(250, 4), completed(260) ]) let res = scheduler.start { xs >- aggregateOrDie(42, { $1 < 3 ? success($0 + $1) : failure(testError) }, { success($0 * 5) }) } let correctMessages: [Recorded<Int>] = [ error(240, testError) ] let correctSubscriptions = [ Subscription(200, 240) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_AggregateWithSeedAndResult_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 3), next(250, 4), completed(260) ]) let res = scheduler.start { xs >- aggregateOrDie(42, { success($0 + $1) }, { (_: Int) -> RxResult<Int> in failure(testError) }) } let correctMessages: [Recorded<Int>] = [ error(260, testError) ] let correctSubscriptions = [ Subscription(200, 260) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } }
mit
800f59f4ab2fd5a6532fd6f934798e1c
27.40118
137
0.515737
5.008845
false
true
false
false
Sorix/CloudCore
Source/Model/Tokens.swift
1
2686
// // Tokens.swift // CloudCore // // Created by Vasily Ulianov on 07.02.17. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CloudKit /** CloudCore's class for storing global `CKToken` objects. Framework uses one to upload or download only changed data (smart-sync). To detect what data is new and old, framework uses CloudKit's `CKToken` objects and it is needed to be loaded every time application launches and saved on exit. Framework stores tokens in 2 places: * singleton `Tokens` object in `CloudCore.tokens` * tokens per record inside *Record Data* attribute, it is managed automatically you don't need to take any actions about that token You need to save `Tokens` object before application terminates otherwise you will loose smart-sync ability. ### Example ```swift func applicationWillTerminate(_ application: UIApplication) { CloudCore.tokens.saveToUserDefaults() } ``` */ open class Tokens: NSObject, NSCoding { var tokensByRecordZoneID = [CKRecordZoneID: CKServerChangeToken]() private struct ArchiverKey { static let tokensByRecordZoneID = "tokensByRecordZoneID" } /// Create fresh object without any Tokens inside. Can be used to fetch full data. public override init() { super.init() } // MARK: User Defaults /// Load saved Tokens from UserDefaults. Key is used from `CloudCoreConfig.userDefaultsKeyTokens` /// /// - Returns: previously saved `Token` object, if tokens weren't saved before newly initialized `Tokens` object will be returned open static func loadFromUserDefaults() -> Tokens { guard let tokensData = UserDefaults.standard.data(forKey: CloudCore.config.userDefaultsKeyTokens), let tokens = NSKeyedUnarchiver.unarchiveObject(with: tokensData) as? Tokens else { return Tokens() } return tokens } /// Save tokens to UserDefaults and synchronize. Key is used from `CloudCoreConfig.userDefaultsKeyTokens` open func saveToUserDefaults() { let tokensData = NSKeyedArchiver.archivedData(withRootObject: self) UserDefaults.standard.set(tokensData, forKey: CloudCore.config.userDefaultsKeyTokens) UserDefaults.standard.synchronize() } // MARK: NSCoding /// Returns an object initialized from data in a given unarchiver. public required init?(coder aDecoder: NSCoder) { if let decodedTokens = aDecoder.decodeObject(forKey: ArchiverKey.tokensByRecordZoneID) as? [CKRecordZoneID: CKServerChangeToken] { self.tokensByRecordZoneID = decodedTokens } else { return nil } } /// Encodes the receiver using a given archiver. open func encode(with aCoder: NSCoder) { aCoder.encode(tokensByRecordZoneID, forKey: ArchiverKey.tokensByRecordZoneID) } }
mit
1ce61d557cbd6764ca4c21b67b4109b3
32.5625
161
0.757542
4.169255
false
false
false
false
22377832/swiftdemo
MapDemo/MapDemo/ViewController.swift
1
4111
// // ViewController.swift // MapDemo // // Created by adults on 2017/3/23. // Copyright © 2017年 adults. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { var locationManager: CLLocationManager? var mapView: MKMapView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mapView = MKMapView() } func setSenterOfMapToLocation(location: CLLocationCoordinate2D){ let span = MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) } func addPinToMapView(){ let location = CLLocationCoordinate2D(latitude:11.56, longitude: 104.92) let annotation = MyAnnotation(coordinate: location, title: "柬埔寨", subtitle: "金边") mapView.addAnnotation(annotation) setSenterOfMapToLocation(location: location) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mapView.mapType = .standard mapView.frame = view.bounds mapView.delegate = self view.addSubview(mapView) } func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } func createLocationManager(startImmediately: Bool){ locationManager = CLLocationManager() if let manager = locationManager{ print("Successfully created the location") manager.delegate = self if startImmediately{ manager.startUpdatingLocation() } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addPinToMapView() if CLLocationManager.locationServicesEnabled(){ switch CLLocationManager.authorizationStatus() { case .authorizedAlways, .authorizedWhenInUse: createLocationManager(startImmediately: true) case .denied: displayAlertWithTitle(title: "Not determined", message: "Location services are not allowed for this app") case .notDetermined: createLocationManager(startImmediately: false) if let manager = self.locationManager{ manager.requestWhenInUseAuthorization() } default: displayAlertWithTitle(title: "Restricted", message: "Location services are not allowed for this app") } } else { print("Location services are not enabled") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("The authorization status of location service is changed to:") switch CLLocationManager.authorizationStatus() { case .authorizedAlways: print("authorized always") case .authorizedWhenInUse: print("authorized when in use") case .denied: print("denied") case .notDetermined: print("not determined") case .restricted: print("restricted") } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Location manager failed with error = \(error)") } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } }
mit
e19facba333b90c23904afe82880d3b4
33.15
121
0.630551
5.723464
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/Result/Result/Result.swift
16
6883
// Copyright (c) 2015 Rob Rix. All rights reserved. /// An enum representing either a failure with an explanatory error, or a success with a result value. public enum Result<T, Error>: Printable, DebugPrintable { case Success(Box<T>) case Failure(Box<Error>) // MARK: Constructors /// Constructs a success wrapping a `value`. public init(value: T) { self = .Success(Box(value)) } /// Constructs a failure wrapping an `error`. public init(error: Error) { self = .Failure(Box(error)) } /// Constructs a result from an Optional, failing with `Error` if `nil` public init(_ value: T?, @autoclosure failWith: () -> Error) { self = value.map { .success($0) } ?? .failure(failWith()) } /// Constructs a success wrapping a `value`. public static func success(value: T) -> Result { return Result(value: value) } /// Constructs a failure wrapping an `error`. public static func failure(error: Error) -> Result { return Result(error: error) } // MARK: Deconstruction /// Returns the value from `Success` Results, `nil` otherwise. public var value: T? { return analysis(ifSuccess: { $0 }, ifFailure: { _ in nil }) } /// Returns the error from `Failure` Results, `nil` otherwise. public var error: Error? { return analysis(ifSuccess: { _ in nil }, ifFailure: { $0 }) } /// Case analysis for Result. /// /// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results. public func analysis<Result>(@noescape #ifSuccess: T -> Result, @noescape ifFailure: Error -> Result) -> Result { switch self { case let .Success(value): return ifSuccess(value.value) case let .Failure(value): return ifFailure(value.value) } } // MARK: Higher-order functions /// Returns a new Result by mapping `Success`es’ values using `transform`, or re-wrapping `Failure`s’ errors. public func map<U>(@noescape transform: T -> U) -> Result<U, Error> { return flatMap { .success(transform($0)) } } /// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors. public func flatMap<U>(@noescape transform: T -> Result<U, Error>) -> Result<U, Error> { return analysis( ifSuccess: transform, ifFailure: Result<U, Error>.failure) } /// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??` public func recover(@autoclosure value: () -> T) -> T { return self.value ?? value() } /// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??` public func recoverWith(@autoclosure result: () -> Result<T,Error>) -> Result<T,Error> { return analysis( ifSuccess: { _ in self }, ifFailure: { _ in result() }) } // MARK: Errors /// The domain for errors constructed by Result. public static var errorDomain: String { return "com.antitypical.Result" } /// The userInfo key for source functions in errors constructed by Result. public static var functionKey: String { return "\(errorDomain).function" } /// The userInfo key for source file paths in errors constructed by Result. public static var fileKey: String { return "\(errorDomain).file" } /// The userInfo key for source file line numbers in errors constructed by Result. public static var lineKey: String { return "\(errorDomain).line" } /// Constructs an error. public static func error(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> NSError { return NSError(domain: "com.antitypical.Result", code: 0, userInfo: [ functionKey: function, fileKey: file, lineKey: line, ]) } // MARK: Printable public var description: String { return analysis( ifSuccess: { ".Success(\($0))" }, ifFailure: { ".Failure(\($0))" }) } // MARK: DebugPrintable public var debugDescription: String { return description } } /// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal. public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { if let left = left.value, right = right.value { return left == right } else if let left = left.error, right = right.error { return left == right } return false } /// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values. public func != <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { return !(left == right) } /// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> T) -> T { return left.recover(right()) } /// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> Result<T, Error>) -> Result<T, Error> { return left.recoverWith(right()) } // MARK: - Cocoa API conveniences /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.: /// /// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) } public func try<T>(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, try: NSErrorPointer -> T?) -> Result<T, NSError> { var error: NSError? return try(&error).map(Result.success) ?? Result.failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line)) } /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.: /// /// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) } public func try(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, try: NSErrorPointer -> Bool) -> Result<(), NSError> { var error: NSError? return try(&error) ? .success(()) : .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line)) } // MARK: - Operators infix operator >>- { // Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc. associativity left // Higher precedence than function application, but lower than function composition. precedence 150 } /// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors. /// /// This is a synonym for `flatMap`. public func >>- <T, U, Error> (result: Result<T, Error>, @noescape transform: T -> Result<U, Error>) -> Result<U, Error> { return result.flatMap(transform) } import Box import Foundation
mit
0adfa8e534e81a25756721dd152da24f
33.174129
162
0.679429
3.575742
false
false
false
false
jspahrsummers/Arbiter
bindings/swift/Arbiter/Types.swift
2
1834
/** * Base class for any Arbiter Swift object which is backed by a corresponding * C object. */ public class CObject : Equatable { /** * Initializes an object of this type from a C pointer, optionally copying its * contents. * * This initializer cannot perform any typechecking, so the pointer must * correspond to an object of this class. * * If `shouldCopy` is false, the CObject is assumed to retain ownership over * the given pointer, and will free it when the CObject is deinitialized by * ARC. */ public init (_ pointer: COpaquePointer, shouldCopy: Bool = true) { if (shouldCopy) { self._pointer = COpaquePointer(ArbiterCreateCopy(UnsafePointer(pointer))); } else { self._pointer = pointer } } /** * Steals ownership of the `pointer` from this object, returning it. * * After invoking this method, `pointer` will be nil. The caller is * responsible for eventually freeing the stolen pointer. */ public func takeOwnership () -> COpaquePointer { precondition(_pointer != nil) let result = _pointer _pointer = nil return result } deinit { if (_pointer != nil) { ArbiterFree(UnsafeMutablePointer(_pointer)) } } /** * The backing C pointer for this object, or nil. */ public var pointer: COpaquePointer { return _pointer } /** * An internally-visible mutable reference to this object's backing pointer. * * This can be used for two-step initialization (where the CObject needs to * complete initializing before the C pointer is known). It is also used in * the implementation of takeOwnership(). */ var _pointer: COpaquePointer } public func == (lhs: CObject, rhs: CObject) -> Bool { return ArbiterEqual(UnsafePointer(lhs.pointer), UnsafePointer(rhs.pointer)) }
mit
3df665a1ef5ae5da06320a695cc55538
25.2
80
0.673937
4.265116
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Maps/Create and save a map/CreateOptionsViewController.swift
1
4700
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS protocol CreateOptionsViewControllerDelegate: AnyObject { func createOptionsViewController(_ createOptionsViewController: CreateOptionsViewController, didSelectBasemap basemap: AGSBasemap, layers: [AGSLayer]) } class CreateOptionsViewController: UITableViewController { private let basemapStyles: KeyValuePairs<String, AGSBasemapStyle> = [ "Streets": .arcGISStreets, "Imagery": .arcGISImageryStandard, "Topographic": .arcGISTopographic, "Oceans": .arcGISOceans ] private let layers: [AGSLayer] = { let layerURLs = [ URL(string: "https://sampleserver5.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer")!, URL(string: "https://sampleserver5.arcgisonline.com/arcgis/rest/services/Census/MapServer")! ] return layerURLs.map { AGSArcGISMapImageLayer(url: $0) } }() private var selectedBasemapIndex: Int = 0 private var selectedLayerIndices: IndexSet = [] weak var delegate: CreateOptionsViewControllerDelegate? // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Choose Basemap" : "Add Operational Layers" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? basemapStyles.count : layers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath) switch indexPath.section { case 0: let basemapStyle = basemapStyles[indexPath.row] cell.textLabel?.text = basemapStyle.key // Accesory view. if selectedBasemapIndex == indexPath.row { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } default: let layer = layers[indexPath.row] cell.textLabel?.text = layer.name // Accessory view. if selectedLayerIndices.contains(indexPath.row) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } } return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 0: // Create a IndexPath for the previously selected index. let previousSelectionIndexPath = IndexPath(row: selectedBasemapIndex, section: 0) selectedBasemapIndex = indexPath.row tableView.reloadRows(at: [indexPath, previousSelectionIndexPath], with: .none) case 1: // Check if already selected. if selectedLayerIndices.contains(indexPath.row) { // Remove the selection. selectedLayerIndices.remove(indexPath.row) } else { selectedLayerIndices.update(with: indexPath.row) } tableView.reloadRows(at: [indexPath], with: .none) default: break } } // MARK: - Actions @IBAction func cancelAction() { // Dissmiss the view if canceled is tapped. dismiss(animated: true) } @IBAction private func doneAction() { // Create a basemap with the selected basemap index. let basemap = AGSBasemap(style: basemapStyles[selectedBasemapIndex].value) // Create an array of the selected operational layers. let selectedLayers = selectedLayerIndices.map { layers[$0].copy() as! AGSLayer } delegate?.createOptionsViewController(self, didSelectBasemap: basemap, layers: selectedLayers) } }
apache-2.0
67065946ea3c821f14e110c12efc299b
37.52459
154
0.645106
4.989384
false
false
false
false
cloudinary/cloudinary_ios
Example/Cloudinary/Controllers/EffectsGalleryViewController.swift
1
8177
// // EffectsGalleryViewController.swift // SampleApp // // Created by Nitzan Jaitman on 31/08/2017. // Copyright © 2017 Cloudinary. All rights reserved. // import Foundation import UIKit import Cloudinary import AVKit class EffectsGalleryViewController: UIViewController, UploadedResourceDetails { // MARK: Properties @IBOutlet weak var imageView: CLDUIImageView! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var videoView: UIView! @IBOutlet weak var currEffectContainer: UIView! fileprivate let sectionInsets = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0) let reuseIdentifier = "EffectCell" var currEffect: EffectMetadata? var effects = [EffectMetadata]() var currUrl: String? var resource: CLDResource! var cloudinary: CLDCloudinary! var observation: NSKeyValueObservation? var isVideo: Bool! var resourceType: CLDUrlResourceType! // video player: var player: AVPlayer! var avpController = AVPlayerViewController() override open func viewDidAppear(_ animated: Bool) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } cloudinary = appDelegate.cloudinary self.player = AVPlayer() self.avpController = AVPlayerViewController() self.avpController.player = self.player avpController.view.frame = videoView.frame self.addChild(avpController) self.currEffectContainer.addSubview(avpController.view) self.isVideo = resource.resourceType == "video" self.resourceType = isVideo ? CLDUrlResourceType.video : CLDUrlResourceType.image DispatchQueue.global().async { if (self.isVideo) { self.effects = CloudinaryHelper.generateVideoEffectList(cloudinary: self.cloudinary, resource: self.resource) } else { self.effects = CloudinaryHelper.generateEffectList(cloudinary: self.cloudinary, resource: self.resource) } DispatchQueue.main.async { self.collectionView.dataSource = self self.collectionView.delegate = self self.updateCurrEffect((self.effects.first)!) } } } @IBAction func codeButtonClicked(_ sender: Any) { if let currUrl = currUrl { openStringUrl(currUrl) } } fileprivate func openStringUrl(_ url: String) { let url = URL(string: url)! if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } else { UIApplication.shared.openURL(url) } } fileprivate func updateCurrEffect(_ effect: EffectMetadata) { currEffect = effect descriptionLabel.text = effect.description self.imageView.image = nil self.player.replaceCurrentItem(with: nil) // Apply scaling/responsive params to a copy of the transformation: let transformation = effect.transformation.copy() as! CLDTransformation if (isVideo) { // manually set size (for images goth are automatic, see the else clause below). Note that DPR // is not supported for videos so we fetch with pixel size: transformation.chain().setWidth(Int(round(UIScreen.main.bounds.width * UIScreen.main.scale))) self.currUrl = cloudinary.createUrl() .setResourceType(self.resourceType) .setTransformation(transformation) .setFormat("mp4") .generate(resource.publicId!) self.videoView.isHidden = false self.avpController.view.isHidden = false self.imageView.isHidden = true activityIndicator.isHidden = true let url = URL(string: self.currUrl!)! self.player.replaceCurrentItem(with: AVPlayerItem(url: url)) } else { transformation.setFetchFormat("png") // note: This url will be used when openning the browser, this is NOT identical to the one shown // inside the app - In the app the size is determined automatically. In the url for browser, the size // will be screen width for full-screen view. self.currUrl = updateCurrUrlForBrowser(cloudinary, transformation) self.videoView.isHidden = true self.avpController.view.isHidden = true self.imageView.isHidden = false activityIndicator.isHidden = false activityIndicator.startAnimating() // use CLDUIImageView with CLDResponsiveParams to automatically handle fetch dimensions and dpr: let params = CLDResponsiveParams.fit().setReloadOnSizeChange(true) self.imageView.cldSetImage(publicId: resource.publicId!, cloudinary: getAppDelegate()!.cloudinary, resourceType: self.resourceType, responsiveParams: params, transformation: transformation) } } fileprivate func updateCurrUrlForBrowser(_ cloudinary: CLDCloudinary, _ transformation: CLDTransformation) -> String { let copy = transformation.copy() as! CLDTransformation copy.chain().setDpr(Float(UIScreen.main.scale)).setWidth(Int(round(UIScreen.main.bounds.width))) return cloudinary.createUrl().setTransformation(copy).setResourceType(self.resourceType).generate(resource.publicId!)! } func setResource(resource: CLDResource) { self.resource = resource; } // MARK: UICollectionViewDelegate public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { updateCurrEffect(effects[indexPath.item]) } } extension EffectsGalleryViewController: UICollectionViewDataSource { // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return effects.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EffectCell let effect = effects[indexPath.row] let params = CLDResponsiveParams.autoFill() let transformation = effect.transformation.copy() as! CLDTransformation cell.imageView.cldSetImage(publicId: resource.publicId!, cloudinary: getAppDelegate()!.cloudinary, resourceType: self.resourceType, responsiveParams: params, transformation: transformation.setFetchFormat("png")) cell.indicator.startAnimating() return cell } } extension EffectsGalleryViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.top } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
mit
66ba9455dabdd414f9b47c223da86310
41.362694
201
0.685298
5.347286
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor/ProfileEditorTab.swift
1
18830
// // ProfileEditorTabView.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa class ProfileEditorTab: NSView { // MARK: - // MARK: Variables let borderRight = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 * 2), height: 250.0)) let borderBottom = NSBox() let buttonClose = NSButton() let textFieldTitle = NSTextField() let textFieldErrorCount = NSTextField() var color = NSColor.clear let colorSelected = NSColor.controlBackgroundColor let colorDeSelected = NSColor.quaternaryLabelColor // NSColor.black.withAlphaComponent(0.08) let colorDeSelectedMouseOver = NSColor.tertiaryLabelColor //NSColor.black.withAlphaComponent(0.14) var trackingArea: NSTrackingArea? @objc var isSelected = false let isSelectedSelector: String var index: Int { if let stackView = self.superview as? NSStackView { return stackView.views.firstIndex(of: self) ?? -1 } return -1 } weak var editor: ProfileEditor? // MARK: - // MARK: Initialization required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(editor: ProfileEditor) { // --------------------------------------------------------------------- // Initialize Key/Value Observing Selector Strings // --------------------------------------------------------------------- self.isSelectedSelector = NSStringFromSelector(#selector(getter: self.isSelected)) // --------------------------------------------------------------------- // Initialize Superclass // --------------------------------------------------------------------- super.init(frame: NSRect.zero) // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() self.editor = editor // --------------------------------------------------------------------- // Setup TabView // --------------------------------------------------------------------- self.setupButtonClose(constraints: &constraints) self.setupTextFieldTitle(constraints: &constraints) self.setupTextFieldErrorCount(constraints: &constraints) // Currently unused self.setupBorderBottom(constraints: &constraints) self.setupBorderRight(constraints: &constraints) // --------------------------------------------------------------------- // Add Notification Observers // --------------------------------------------------------------------- self.addObserver(self, forKeyPath: self.isSelectedSelector, options: .new, context: nil) // --------------------------------------------------------------------- // Activate layout constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) } deinit { self.removeObserver(self, forKeyPath: self.isSelectedSelector, context: nil) } func selectTab() { if let editor = self.editor { editor.select(tab: self.index) } } // MARK: - // MARK: Key/Value Observing Functions override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if keyPath == self.isSelectedSelector { self.borderBottom.isHidden = self.isSelected if self.isSelected { self.color = self.colorSelected } else { self.color = self.colorDeSelected } self.display() } } // MARK: - // MARK: Button Functions @objc func clicked(button: NSButton) { if let editor = self.editor { editor.close(tab: self.index) } } } // MARK: - // MARK: NSView Methods extension ProfileEditorTab { override func draw(_ dirtyRect: NSRect) { self.color.set() self.bounds.fill() } override func updateTrackingAreas() { // --------------------------------------------------------------------- // Remove previous tracking area if it was set // --------------------------------------------------------------------- if let trackingArea = self.trackingArea { self.removeTrackingArea(trackingArea) } // --------------------------------------------------------------------- // Create a new tracking area // --------------------------------------------------------------------- let trackingOptions = NSTrackingArea.Options(rawValue: (NSTrackingArea.Options.mouseEnteredAndExited.rawValue | NSTrackingArea.Options.activeAlways.rawValue)) self.trackingArea = NSTrackingArea(rect: self.bounds, options: trackingOptions, owner: self, userInfo: nil) // --------------------------------------------------------------------- // Add the new tracking area to the button // --------------------------------------------------------------------- self.addTrackingArea(self.trackingArea!) } } // MARK: - // MARK: Mouse Events extension ProfileEditorTab { override func mouseDown(with event: NSEvent) { self.selectTab() } override func mouseEntered(with event: NSEvent) { self.buttonClose.isHidden = false if !self.isSelected { self.color = self.colorDeSelectedMouseOver self.display() } } override func mouseExited(with event: NSEvent) { self.buttonClose.isHidden = true if self.isSelected { self.color = self.colorSelected } else { self.color = self.colorDeSelected } self.display() } } extension ProfileEditorTab { func setupButtonClose(constraints: inout [NSLayoutConstraint]) { self.buttonClose.translatesAutoresizingMaskIntoConstraints = false self.buttonClose.bezelStyle = .roundRect self.buttonClose.setButtonType(.momentaryPushIn) self.buttonClose.isBordered = false self.buttonClose.isTransparent = false self.buttonClose.image = NSImage(named: NSImage.stopProgressTemplateName) self.buttonClose.imageScaling = .scaleProportionallyUpOrDown self.buttonClose.action = #selector(self.clicked(button:)) self.buttonClose.target = self self.buttonClose.isHidden = true // --------------------------------------------------------------------- // Add and to superview // --------------------------------------------------------------------- self.addSubview(self.buttonClose) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // CenterY constraints.append(NSLayoutConstraint(item: self.buttonClose, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) // Leading constraints.append(NSLayoutConstraint(item: self.buttonClose, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 6.0)) // Width constraints.append(NSLayoutConstraint(item: self.buttonClose, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 8.0)) // Width == Height constraints.append(NSLayoutConstraint(item: self.buttonClose, attribute: .width, relatedBy: .equal, toItem: self.buttonClose, attribute: .height, multiplier: 1.0, constant: 0.0)) } internal func setupBorderBottom(constraints: inout [NSLayoutConstraint]) { self.borderBottom.translatesAutoresizingMaskIntoConstraints = false self.borderBottom.boxType = .separator // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(self.borderBottom) // --------------------------------------------------------------------- // Add Constraints // --------------------------------------------------------------------- // Bottom constraints.append(NSLayoutConstraint(item: self.borderBottom, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0.0)) // Leading constraints.append(NSLayoutConstraint(item: self.borderBottom, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0.0)) // Trailing constraints.append(NSLayoutConstraint(item: self.borderBottom, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0.0)) } internal func setupBorderRight(constraints: inout [NSLayoutConstraint]) { self.borderRight.translatesAutoresizingMaskIntoConstraints = false self.borderRight.boxType = .separator self.setContentCompressionResistancePriority(.required, for: .vertical) // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(self.borderRight) // --------------------------------------------------------------------- // Add Constraints // --------------------------------------------------------------------- // Height constraints.append(NSLayoutConstraint(item: self.borderRight, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 22.0)) // Right constraints.append(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.borderRight, attribute: .right, multiplier: 1, constant: 0.5)) // Top constraints.append(NSLayoutConstraint(item: self.borderRight, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0.0)) // Trailing constraints.append(NSLayoutConstraint(item: self.borderRight, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0.0)) } func setupTextFieldTitle(constraints: inout [NSLayoutConstraint]) { self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false self.textFieldTitle.lineBreakMode = .byTruncatingTail self.textFieldTitle.isBordered = false self.textFieldTitle.isBezeled = false self.textFieldTitle.drawsBackground = false self.textFieldTitle.isEditable = false self.textFieldTitle.isSelectable = false self.textFieldTitle.textColor = .labelColor self.textFieldTitle.alignment = .center self.textFieldTitle.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .small), weight: .regular) self.textFieldTitle.stringValue = "Payload" // --------------------------------------------------------------------- // Add and to superview // --------------------------------------------------------------------- self.addSubview(self.textFieldTitle) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // CenterY constraints.append(NSLayoutConstraint(item: self.textFieldTitle, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) // Leading constraints.append(NSLayoutConstraint(item: self.textFieldTitle, attribute: .leading, relatedBy: .equal, toItem: self.buttonClose, attribute: .trailing, multiplier: 1.0, constant: 4.0)) } func setupTextFieldErrorCount(constraints: inout [NSLayoutConstraint]) { self.textFieldErrorCount.translatesAutoresizingMaskIntoConstraints = false self.textFieldErrorCount.translatesAutoresizingMaskIntoConstraints = false self.textFieldErrorCount.lineBreakMode = .byTruncatingTail self.textFieldErrorCount.isBordered = false self.textFieldErrorCount.isBezeled = false self.textFieldErrorCount.drawsBackground = false self.textFieldErrorCount.isEditable = false self.textFieldErrorCount.isSelectable = false self.textFieldErrorCount.textColor = .labelColor self.textFieldErrorCount.alignment = .center self.textFieldErrorCount.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .small), weight: .regular) self.textFieldErrorCount.textColor = .systemRed self.textFieldErrorCount.stringValue = "0" self.textFieldErrorCount.isHidden = true // --------------------------------------------------------------------- // Add and to superview // --------------------------------------------------------------------- self.addSubview(self.textFieldErrorCount) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // CenterY constraints.append(NSLayoutConstraint(item: self.textFieldErrorCount, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) // Leading constraints.append(NSLayoutConstraint(item: self.textFieldErrorCount, attribute: .leading, relatedBy: .equal, toItem: self.textFieldTitle, attribute: .trailing, multiplier: 1.0, constant: 4.0)) // Trailing constraints.append(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.textFieldErrorCount, attribute: .trailing, multiplier: 1.0, constant: 6.0)) } }
mit
063d563feb942f64b8e8df367e4b4d81
43.408019
166
0.412449
7.219709
false
false
false
false
iGenius-Srl/IGColorPicker
IGColorPicker/Classes/View/ColorPickerCell.swift
1
2917
// // Copyright (c) 2017 iGenius Srl // // 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 M13Checkbox class ColorPickerCell: UICollectionViewCell { // MARK: - Properties /// The reuse identifier used to register the UICollectionViewCell to the UICollectionView static let cellIdentifier = String(describing: ColorPickerCell.self) /// The checkbox use to show the tip on the cell var checkbox = M13Checkbox() //MARK: - Initializer init() { super.init(frame: CGRect.zero) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private methods fileprivate func commonInit() { // Setup of checkbox checkbox.isUserInteractionEnabled = false checkbox.backgroundColor = .clear checkbox.hideBox = true checkbox.setCheckState(.unchecked, animated: false) self.addSubview(checkbox) // Setup constraints to checkbox checkbox.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: checkbox, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: checkbox, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: checkbox, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: checkbox, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0)) } }
mit
6f9be737ac6477748e0685333dbfba33
48.440678
463
0.711347
4.877926
false
false
false
false
xiabob/ZhiHuDaily
ZhiHuDaily/ZhiHuDaily/DataSource/GetThemes.swift
1
2392
// // GetThemes.swift // ZhiHuDaily // // Created by xiabob on 17/4/10. // Copyright © 2017年 xiabob. All rights reserved. // import UIKit import SwiftyJSON class GetThemes: XBAPIBaseManager, ManagerProtocol, XBAPILocalCache { var subscribedThemeModel = [ThemeModel]() var unsubscribedThemeModel = [ThemeModel]() var path: String { return "/themes" } var shouldCache: Bool {return true} func getDataFromLocal(from key: String) -> Data? { return nil } func parseResponseData(_ data: AnyObject) { let realm = RealmManager.shared.defaultRealm try? realm?.write { let json = JSON(data) let subscribedJson = json["subscribed"].arrayValue var themes = [Theme]() for themeDic in subscribedJson { let themeID = themeDic["id"].intValue let localTheme = realm?.object(ofType: Theme.self, forPrimaryKey: themeID) if let localTheme = localTheme { localTheme.update(from: themeDic) themes.append(localTheme) } else { let newTheme = Theme(from: themeDic) newTheme.isSubscribed = true realm?.add(newTheme) themes.append(newTheme) } } self.subscribedThemeModel = themes.map({ (value) -> ThemeModel in return ThemeModel(from: value) }) themes.removeAll() let unsubscribedJson = json["others"].arrayValue for themeDic in unsubscribedJson { let themeID = themeDic["id"].intValue let localTheme = realm?.object(ofType: Theme.self, forPrimaryKey: themeID) if let localTheme = localTheme { localTheme.update(from: themeDic) themes.append(localTheme) } else { let newTheme = Theme(from: themeDic) newTheme.isSubscribed = false realm?.add(newTheme) themes.append(newTheme) } } self.unsubscribedThemeModel = themes.map({ (value) -> ThemeModel in return ThemeModel(from: value) }) } } }
mit
d35d3367a5e2771358ac12139f6e83f2
32.647887
90
0.528673
4.94617
false
false
false
false
dreamsxin/swift
validation-test/stdlib/CollectionOld.swift
3
7202
// RUN: %target-run-simple-swift --stdlib-unittest-in-process | tee %t.txt // RUN: FileCheck %s < %t.txt // note: remove the --stdlib-unittest-in-process once all the FileCheck tests // have been converted to StdlibUnittest // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("CollectionTests") /// An *iterator* that adapts a *collection* `C` and any *sequence* of /// its `Index` type to present the collection's elements in a /// permuted order. public struct PermutationGenerator< C: Collection, Indices: Sequence where C.Index == Indices.Iterator.Element > : IteratorProtocol, Sequence { var seq : C var indices : Indices.Iterator /// The type of element returned by `next()`. public typealias Element = C.Iterator.Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Element? { let result = indices.next() return result != nil ? seq[result!] : .none } /// Construct an *iterator* over a permutation of `elements` given /// by `indices`. /// /// - Precondition: `elements[i]` is valid for every `i` in `indices`. public init(elements: C, indices: Indices) { self.seq = elements self.indices = indices.makeIterator() } } var foobar = MinimalCollection(elements: "foobar".characters) // CHECK: foobar for a in foobar { print(a, terminator: "") } print("") // FIXME: separate r from the expression below pending // <rdar://problem/15772601> Type checking failure // CHECK: raboof let i = foobar.indices let r = i.lazy.reversed() for a in PermutationGenerator(elements: foobar, indices: r) { print(a, terminator: "") } print("") func isPalindrome0< S : BidirectionalCollection where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index >(_ seq: S) -> Bool { typealias Index = S.Index let a = seq.indices let i = seq.indices let ir = i.lazy.reversed() var b = ir.makeIterator() for i in a { if seq[i] != seq[b.next()!] { return false } } return true } // CHECK: false print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiImaLasagneHoG".characters))) // CHECK: true print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiimalaSagnaHoG".characters))) func isPalindrome1< S : BidirectionalCollection where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index >(_ seq: S) -> Bool { let a = PermutationGenerator(elements: seq, indices: seq.indices) var b = seq.lazy.reversed().makeIterator() for nextChar in a { if nextChar != b.next()! { return false } } return true } func isPalindrome1_5< S: BidirectionalCollection where S.Iterator.Element == S.Iterator.Element, S.Iterator.Element: Equatable >(_ seq: S) -> Bool { var b = seq.lazy.reversed().makeIterator() for nextChar in seq { if nextChar != b.next()! { return false } } return true } // CHECK: false print(isPalindrome1(MinimalBidirectionalCollection(elements: "MADAMINEDENIMWILLIAM".characters))) // CHECK: true print(isPalindrome1(MinimalBidirectionalCollection(elements: "MadamInEdEnImadaM".characters))) // CHECK: false print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeRemoteelF".characters))) // CHECK: true print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeReMoteelF".characters))) // Finally, one that actually uses indexing to do half as much work. // BidirectionalCollection traversal finally pays off! func isPalindrome2< S: BidirectionalCollection where S.Iterator.Element: Equatable >(_ seq: S) -> Bool { var b = seq.startIndex, e = seq.endIndex while (b != e) { e = seq.index(before: e) if (b == e) { break } if seq[b] != seq[e] { return false } b = seq.index(after: b) } return true } // Test even length // CHECK: false print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarRamireZ".characters))) // CHECK: true print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimaRRamireZ".characters))) // Test odd length // CHECK: false print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarORamireZ".characters))) // CHECK: true print(isPalindrome2(MinimalBidirectionalCollection(elements: "Zerimar-O-ramireZ".characters))) func isPalindrome4< S: BidirectionalCollection where S.Iterator.Element : Equatable, S.Indices.Iterator.Element == S.Index >(_ seq: S) -> Bool { typealias Index = S.Index let a = PermutationGenerator(elements: seq, indices: seq.indices) // FIXME: separate ri from the expression below pending // <rdar://problem/15772601> Type checking failure let i = seq.indices let ri = i.lazy.reversed() var b = PermutationGenerator(elements: seq, indices: ri) for nextChar in a { if nextChar != b.next()! { return false } } return true } // Can't put these literals into string interpolations pending // <rdar://problem/16401145> hella-slow compilation let array = [1, 2, 3, 4] let dict = [0:0, 1:1, 2:2, 3:3, 4:4] func testCount() { // CHECK: testing count print("testing count") // CHECK-NEXT: random access: 4 print("random access: \(array.count)") // CHECK-NEXT: bidirectional: 5 print("bidirectional: \(dict.count)") } testCount() struct SequenceOnly<T : Sequence> : Sequence { var base: T func makeIterator() -> T.Iterator { return base.makeIterator() } } func testUnderestimatedCount() { // CHECK: testing underestimatedCount print("testing underestimatedCount") // CHECK-NEXT: random access: 4 print("random access: \(array.underestimatedCount)") // CHECK-NEXT: bidirectional: 5 print("bidirectional: \(dict.underestimatedCount)") // CHECK-NEXT: Sequence only: 0 let s = SequenceOnly(base: array) print("Sequence only: \(s.underestimatedCount)") } testUnderestimatedCount() CollectionTests.test("isEmptyFirstLast") { expectTrue((10..<10).isEmpty) expectFalse((10...10).isEmpty) expectEqual(10, (10..<100).first) expectEqual(10, (10...100).first) expectEqual(99, (10..<100).last) expectEqual(100, (10...100).last) } /// A `Collection` that vends just the default implementations for /// `CollectionType` methods. struct CollectionOnly<T: Collection> : Collection { var base: T var startIndex: T.Index { return base.startIndex } var endIndex: T.Index { return base.endIndex } func makeIterator() -> T.Iterator { return base.makeIterator() } subscript(position: T.Index) -> T.Iterator.Element { return base[position] } func index(after i: T.Index) -> T.Index { return base.index(after: i) } } // CHECK: all done. print("all done.") CollectionTests.test("first/performance") { // accessing `first` should not perform duplicate work on lazy collections var log: [Int] = [] let col_ = (0..<10).lazy.filter({ log.append($0); return (2..<8).contains($0) }) let col = CollectionOnly(base: col_) expectEqual(2, col.first) expectEqual([0, 1, 2], log) } runAllTests()
apache-2.0
b19e85862261554d8dc5c23c34a31834
25.873134
103
0.69689
3.735477
false
true
false
false
groschovskiy/firebase-for-banking-app
Demo/Banking/BBPaymentCards.swift
1
2024
// // BBPaymentCards.swift // Banking // // Created by Dmitriy Groschovskiy on 30/10/2016. // Copyright © 2016 Barclays Bank, PLC. All rights reserved. // import UIKit import Firebase class BBPaymentCards: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView : UICollectionView! var paymentCards: [BBCardModel] = [] override func viewDidLoad() { super.viewDidLoad() let userRef = FIRAuth.auth()?.currentUser?.uid let cardsRef = FIRDatabase.database().reference(withPath: "Cards") cardsRef.queryOrdered(byChild: "cardNumber").observe(.value, with: { snapshot in var newCard: [BBCardModel] = [] for item in snapshot.children { let cloudItem = BBCardModel(snapshot: item as! FIRDataSnapshot) newCard.append(cloudItem) } self.paymentCards = newCard self.collectionView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - UICollectionViewDataSource with best radio stations func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.paymentCards.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! BBPaymentCardsCell let paymentCardItem = paymentCards[indexPath.row] cell.creditCardImage.image = UIImage(named: "\(paymentCardItem.creditCardArtwork)") return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("You selected cell #\(indexPath.item)!") } @IBAction func closeController(sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } }
apache-2.0
dccdc370711ef4acfd55ee1141184b5b
34.491228
134
0.688581
5.044888
false
false
false
false
pointfreeco/swift-web
Sources/HttpPipeline/SharedMiddlewareTransformers.swift
1
7338
import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Optics import Prelude public func filterMap<A, B, C>( _ f: @escaping (A) -> IO<B?>, or notFoundMiddleware: @escaping Middleware<StatusLineOpen, ResponseEnded, A, C> ) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, B, C>) -> Middleware<StatusLineOpen, ResponseEnded, A, C> { return { middleware in { conn in f(conn.data).flatMap { result in result.map(middleware <<< conn.map <<< const) ?? notFoundMiddleware(conn) } } } } public func filter<A, B>( _ p: @escaping (A) -> Bool, or notFoundMiddleware: @escaping Middleware<StatusLineOpen, ResponseEnded, A, B> ) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, B>) -> Middleware<StatusLineOpen, ResponseEnded, A, B> { return filterMap({ p($0) ? $0 : nil } >>> pure, or: notFoundMiddleware) } /// Wraps basic auth middleware around existing middleware. Provides only the most basic of authentication /// where the username and password are static, e.g. we do not look in a database for the user. /// /// - Parameters: /// - user: The user name to authenticate against. /// - password: The password to authenticate against. /// - realm: The realm. /// - protect: An optional predicate that can further control what values of `A` are protected by basic auth. /// - failure: An optional middleware to run in the case that authentication fails. /// - Returns: Transformed middleware public func basicAuth<A>( user: String, password: String, realm: String? = nil, protect: @escaping (A) -> Bool = const(true), failure: @escaping Middleware<HeadersOpen, ResponseEnded, A, Data> = respond(text: "Please authenticate.") ) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return { middleware in return { conn in guard protect(conn.data) && !validateBasicAuth(user: user, password: password, request: conn.request) else { return middleware(conn) } return conn |> ( writeStatus(.unauthorized) >=> writeHeader(.wwwAuthenticate(.basic(realm: realm))) >=> failure ) } } } public func notFound<A>(_ middleware: @escaping Middleware<HeadersOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return writeStatus(.notFound) >=> middleware } /// Redirects requests whose hosts are not one of an allowed list. This can be useful for redirecting a /// bare domain, e.g. http://pointfree.co, to a `www` domain, e.g. `http://www.pointfree.co`. /// /// - Parameters: /// - isAllowedHost: A predicate used to allow hosts. /// - canonicalHost: The canonical host to redirect to if the host is not allowed. /// - Returns: public func redirectUnrelatedHosts<A>( isAllowedHost: @escaping (String) -> Bool, canonicalHost: String ) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return { middleware in { conn in conn.request.url .filter { !isAllowedHost($0.host ?? "") } .flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false) |> map(\.host .~ canonicalHost) } .flatMap(^\.url) .map { conn |> redirect(to: $0.absoluteString, status: .movedPermanently) } ?? middleware(conn) } } } /// Redirects requests whose hosts are not one of an allowed list. This can be useful for redirecting a /// bare domain, e.g. http://pointfree.co, to a `www` domain, e.g. `http://www.pointfree.co`. /// /// - Parameters: /// - allowedHosts: A list of hosts that are allowed through without redirection. /// - canonicalHost: The canonical host to redirect to if the host is not allowed. /// - Returns: public func redirectUnrelatedHosts<A>( allowedHosts: [String], canonicalHost: String ) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return redirectUnrelatedHosts(isAllowedHost: { allowedHosts.contains($0) }, canonicalHost: canonicalHost) } public func requireHerokuHttps<A>(allowedInsecureHosts: [String]) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return { middleware in return { conn in conn.request.url .filter { url in // `url.scheme` cannot be trusted on Heroku, instead we need to look at the `X-Forwarded-Proto` // header to determine if we are on https or not. conn.request.allHTTPHeaderFields?["X-Forwarded-Proto"] != .some("https") && !allowedInsecureHosts.contains(url.host ?? "") } .flatMap(makeHttps) .map { conn |> redirect(to: $0.absoluteString, status: .movedPermanently) } ?? middleware(conn) } } } public func requireHttps<A>(allowedInsecureHosts: [String]) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, A, Data>) -> Middleware<StatusLineOpen, ResponseEnded, A, Data> { return { middleware in return { conn in conn.request.url .filter { (url: URL) -> Bool in url.scheme != .some("https") && !allowedInsecureHosts.contains(url.host ?? "") } .flatMap(makeHttps) .map { conn |> redirect(to: $0.absoluteString, status: .movedPermanently) } ?? middleware(conn) } } } public func validateBasicAuth(user: String, password: String, request: URLRequest) -> Bool { let auth = request.value(forHTTPHeaderField: "Authorization") ?? "" let parts = Foundation.Data(base64Encoded: String(auth.dropFirst(6))) .map { String(decoding: $0, as: UTF8.self) } .map { $0.split(separator: ":").map(String.init) } return parts?.first == .some(user) && parts?.last == .some(password) } private func makeHttps(url: URL) -> URL? { return URLComponents(url: url, resolvingAgainstBaseURL: false) |> map(\.scheme .~ "https") |> flatMap(^\.url) } /// Transforms middleware into one that logs the request info that comes through and logs the amount of /// time the request took. /// /// - Parameter logger: A function for logging strings. public func requestLogger(logger: @escaping (String) -> Void, uuid: @escaping () -> UUID) -> (@escaping Middleware<StatusLineOpen, ResponseEnded, Prelude.Unit, Data>) -> Middleware<StatusLineOpen, ResponseEnded, Prelude.Unit, Data> { return { middleware in return { conn in let id = uuid().uuidString let startTime = Date().timeIntervalSince1970 logger("\(id) [Request] \(conn.request.httpMethod ?? "GET") \(conn.request.url?.relativePath ?? "")") return middleware(conn).flatMap { b in IO { let endTime = Date().timeIntervalSince1970 // NB: `absoluteString` is necessary because of https://github.com/apple/swift-corelibs-foundation/pull/1312 logger("\(id) [Time] \(Int((endTime - startTime) * 1000))ms") return b } } } } }
mit
1c77858ed78e08bbcf3e089d643d35fd
34.970588
120
0.645135
4.009836
false
false
false
false
JRG-Developer/ObservableType
ObservableType/Library/Observable.swift
1
9311
// // Observable.swift // ObservableType // // Created by Joshua Greene on 8/21/16. // Copyright © 2016 Joshua Greene. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// `Observable` is a simple wrapper around an underlying value that interested observers can register for changes. /// /// To register an observer call `bind(_:, fireImmediately:, closure:)`. You _may_ register more than one closure with the same observer. /// /// The observer is weakly referenced, and the closures are strongly referenced-- whenever the observer becomes `nil`, all of its related closures will be released. /// /// Alternatively, you may immediately release all of an observer's closures by calling `unbind(_:)`, but this is strictly optional (i.e. you don't need to remember to unregister in `deinit`, etc ;). /// /// **Note:** `Observable` uses a private instance of `ObservableClosureDelegate`, which in turn uses by a private `NSMapTable`. Thereby, it has the same limitations and advantages that `ObservableClosureDelegate` does. public class Observable<Type> { // MARK: - Public Properties /// Use this property to get/set the underlying value. /// /// The new value is NOT checked if its the same as the underying value before being set or closures invoked. If this is important to you, set the `value` property instead. /// /// **Warning**: This property is NOT thread safe. /// /// @see `Observable+Equatable` public var unsafeValue: Type { get { return synchronizedValue.unsafeValue } set { let oldValue = synchronizedValue.unsafeValue setUnsafeValue(backingValue: &synchronizedValue.unsafeValue, oldValue: oldValue, newValue: newValue) } } internal func setUnsafeValue(backingValue: inout Type, oldValue: Type, newValue: Type) { fire(value: oldValue, key: Keys.valueWillChange) backingValue = Observable.value(for: newValue, transform: _transform) fire(value: backingValue, key: Keys.valueDidChange) } /// Use this method to set the value without invoking any closures. /// /// **Warning**: This method is **NOT** thread safe. /// /// - parameter value: The value to be set public func setUnsafeValueWithoutFiring(_ value: Type) { synchronizedValue.unsafeValue = Observable.value(for: value, transform: transform) } /// Use this method to invoke all closures immediately. /// /// **Note**: Each closure is dispatched to the queue that was provided whenever it was added via `bind`. It's the consumer's responsibility to ensure that code within the closure is thread safe. public func fire() { fire(value: synchronizedValue.get(), key: Keys.valueDidChange) } public func fire(value: Type, key: String) { let closures = multicastClosure.fire(key: key, removeAfter: false) as [((Type)->(), DispatchQueue?)] closures.forEach { (closure, queue) in guard let queue = queue else { closure(value) return } queue.async { closure(value) } } } /// This closure is called prior to setting the underlying value. /// /// For example, you can use this to "sort" or "filter" elements. public var transform: ((Type)->(Type))? { get { return _transform } set { synchronizedValue.set { value in _transform = newValue setUnsafeValue(backingValue: &value, oldValue: value, newValue: value) } } } internal var _transform: ((Type)->(Type))? = nil internal func unsafeRetransform(_ backingValue: inout Type) { guard let transform = transform else { return } backingValue = transform(backingValue) } // MARK: - Private Properties internal let multicastClosure = ObservableClosureDelegate() internal var synchronizedValue: SynchronizedValue<Type> // MARK: - Object Lifecycle /// Use this initialier to create a new `Observable` instance with an underlying value. /// /// - Parameters: /// - value: The underlying value /// - transform: The transform closure, which is called prior to a new value being set public init(_ value: Type, transform: ((Type)->(Type))? = nil) { let newValue = Observable.value(for: value, transform: transform) self.synchronizedValue = SynchronizedValue(newValue) self._transform = transform } private class func value(for value: Type, transform: ((Type)->(Type))?) -> Type { var newValue = value if let transform = transform { newValue = transform(newValue) } return newValue } // MARK: - Instance Methods /// Use this method to register an observer and releated closure to be called whenever the underlying value did change. /// /// You may register multiple closures for the same observer. Whenvever the observer becomes nil (it's weakly referenced), all of its related closures are released (they're strongly referenced). /// /// **Warning**: Be careful NOT to create a strong reference cycle by capturing an observer within its own closure. Otherwise, the observer, closure, and this `Observable` instance may leak. /// /// - Parameters: /// - observer: The observer to register /// - fireImmediately: Whether or not the closure should be invoked immediately, deraults to true /// - queue: The callback queue or `nil` for none /// - closure: The closure to be invoked whenever the underlying value did change public func bind(_ object: AnyObject, fireImmediately: Bool = true, queue: DispatchQueue? = nil, closure: @escaping (Type)->()) { multicastClosure.addClosure(for: object, key: Keys.valueDidChange, queue: queue, closure: closure) guard fireImmediately == true else { return } let value = synchronizedValue.get() guard let queue = queue else { closure(value) return } queue.async { closure(value) } } /// Use this method to register an observer and releated closure to be called whenever the underlying value will change. /// /// You may register multiple closures for the same observer. Whenvever the observer becomes nil (it's weakly referenced), all of its related closures are released (they're strongly referenced). /// /// **Warning**: Be careful NOT to create a strong reference cycle by capturing an observer within its own closure. Otherwise, the observer, closure, and this `Observable` instance may leak. /// /// - Parameters: /// - observer: The observer to register /// - queue: The callback queue or `nil` for none /// - closure: The closure to be invoked whenever the underlying value will change public func bindWillChange(_ object: AnyObject, queue: DispatchQueue? = nil, closure: @escaping (Type)->()) { multicastClosure.addClosure(for: object, key: Keys.valueWillChange, queue: queue, closure: closure) } /// Use this method to register an observer only ONCE. /// /// This is a convenience method that calls `unbind(_:)` prior to registering the `object`. /// /// - Parameters: /// - observer: The observer to register /// - fireImmediately: Whether or not the closure should be invoked immediately, deraults to true /// - queue: The callback queue or `nil` for none /// - closure: The closure to be invoked whenever the underlying value changes public func bindOnce(_ object: AnyObject, fireImmediately: Bool = true, queue: DispatchQueue? = nil, closure: @escaping (Type)->()) { unbind(object) bind(object, fireImmediately: fireImmediately, queue: queue, closure: closure) } /// Use this method to unregister an observer and all its related closures. /// /// - parameter observer: The obsever to unregister public func unbind(_ object: AnyObject) { multicastClosure.unbind(object) } /// Use this method to unregister ALL observers and their related closures. public func unbindAll() { multicastClosure.unbindAll() } } // MARK: - Keys internal struct Keys { internal static let valueDidChange = "didChange" internal static let valueWillChange = "willChange" }
mit
f472a6b5ef7a458258b6cb555c476a0d
41.706422
219
0.688077
4.568204
false
false
false
false
ZekeSnider/Jared
Jared/CoreModule.swift
1
15564
// // CoreModule.swift // Jared 3.0 - Swiftified // // Created by Zeke Snider on 4/3/16. // Copyright © 2016 Zeke Snider. All rights reserved. // import Foundation import Cocoa import JaredFramework import Contacts enum IntervalType: String { case Minute case Hour case Day case Week case Month } let intervalSeconds: [IntervalType: Double] = [ .Minute: 60.0, .Hour: 3600.0, .Day: 86400.0, .Week: 604800.0, .Month: 2592000.0 ] class CoreModule: RoutingModule { var description: String = NSLocalizedString("CoreDescription") var routes: [Route] = [] let MAXIMUM_CONCURRENT_SENDS = 3 var currentSends: [String: Int] = [:] let scheduleCheckInterval = 30.0 * 60.0 var sender: MessageSender var timer: Timer! var persistentContainer: PersistentContainer = { let container = PersistentContainer(name: "CoreModule") container.loadPersistentStores { description, error in if let error = error { fatalError("Unable to load persistent stores: \(error)") } } return container }() required public init(sender: MessageSender) { self.sender = sender let appsupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Jared").appendingPathComponent("CoreModule") try! FileManager.default.createDirectory(at: appsupport, withIntermediateDirectories: true, attributes: nil) let ping = Route(name:"/ping", comparisons: [.startsWith: ["/ping"]], call: {[weak self] in self?.pingCall($0)}, description: NSLocalizedString("pingDescription")) let thankYou = Route(name:"Thank You", comparisons: [.startsWith: [NSLocalizedString("ThanksJaredCommand")]], call: {[weak self] in self?.thanksJared($0)}, description: NSLocalizedString("ThanksJaredResponse")) let version = Route(name: "/version", comparisons: [.startsWith: ["/version"]], call: {[weak self] in self?.getVersion($0)}, description: "Get the version of Jared running") let whoami = Route(name: "/whoami", comparisons: [.startsWith: ["/whoami"]], call: {[weak self] in self?.getWho($0)}, description: "Get your name") let send = Route(name: "/send", comparisons: [.startsWith: ["/send"]], call: {[weak self] in self?.sendRepeat($0)}, description: NSLocalizedString("sendDescription"),parameterSyntax: NSLocalizedString("sendSyntax")) let name = Route(name: "/name", comparisons: [.startsWith: ["/name"]], call: {[weak self] in self?.changeName($0)}, description: "Change what Jared calls you", parameterSyntax: "/name,[your preferred name]") let schedule = Route(name: "/schedule", comparisons: [.startsWith: ["/schedule"]], call: {[weak self] in self?.schedule($0)}, description: NSLocalizedString("scheduleDescription"), parameterSyntax: "Must be one of these type of inputs: /schedule,add,1,Week,5,full Message\n/schedule,delete,1\n/schedule,list") let barf = Route(name: "/barf", comparisons: [.startsWith: ["/barf"]], call: {[weak self] in self?.barf($0)}, description: NSLocalizedString("barfDescription")) routes = [ping, thankYou, version, send, whoami, name, schedule, barf] //Launch background thread that will check for scheduled messages to send timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true, block: {[weak self] (theTimer) in self?.scheduleThread() }) } deinit { timer.invalidate() } func pingCall(_ incoming: Message) -> Void { sender.send(NSLocalizedString("PongResponse"), to: incoming.RespondTo()) } func barf(_ incoming: Message) -> Void { sender.send(String(data: try! JSONEncoder().encode(incoming), encoding: .utf8) ?? "nil", to: incoming.RespondTo()) } func getWho(_ message: Message) -> Void { if message.sender.givenName != nil { sender.send("Your name is \(message.sender.givenName!).", to: message.RespondTo()) } else { sender.send("I don't know your name.", to: message.RespondTo()) } } func thanksJared(_ message: Message) -> Void { sender.send(NSLocalizedString("WelcomeResponse"), to: message.RespondTo()) } func getVersion(_ message: Message) -> Void { sender.send(NSLocalizedString("versionResponse"), to: message.RespondTo()) } func sendRepeat(_ message: Message) -> Void { guard let parameters = message.getTextParameters() else { return sender.send("Inappropriate input type.", to: message.RespondTo()) } //Validating and parsing arguments guard let repeatNum: Int = Int(parameters[1]) else { return sender.send("Wrong argument. The first argument must be the number of message you wish to send", to: message.RespondTo()) } guard let delay = Int(parameters[2]) else { return sender.send("Wrong argument. The second argument must be the delay of the messages you wish to send", to: message.RespondTo()) } guard var textToSend = parameters[safe: 3] else { return sender.send("Wrong arguments. The third argument must be the message you wish to send.", to: message.RespondTo()) } guard (currentSends[message.sender.handle] ?? 0) < MAXIMUM_CONCURRENT_SENDS else { return sender.send("You can only have \(MAXIMUM_CONCURRENT_SENDS) send operations going at once.", to: message.RespondTo()) } if (currentSends[message.sender.handle] == nil) { currentSends[message.sender.handle] = 0 } //Increment the concurrent send counter for this user currentSends[message.sender.handle] = currentSends[message.sender.handle]! + 1 //If there are commas in the message, take the whole message if parameters.count > 4 { textToSend = parameters[3...(parameters.count - 1)].joined(separator: ",") } //Go through the repeat loop... for _ in 1...repeatNum { sender.send(textToSend, to: message.RespondTo()) Thread.sleep(forTimeInterval: Double(delay)) } //Decrement the concurrent send counter for this user currentSends[message.sender.handle] = (currentSends[message.sender.handle] ?? 0) - 1 } @objc func scheduleThread() { let posts = getPendingPosts() //Loop over all posts for post in posts { guard let handle = post.handle, let text = post.text else { continue } let recipient = AbstractRecipient(handle: handle) sender.send(text, to: recipient) bumpPost(post: post) } } func schedule(_ message: Message) { // /schedule,add,1,Week,5,full Message // /schedule,delete,1 // /schedule,list guard let parameters = message.getTextBody()?.components(separatedBy: ",") else { return sender.send("Inappropriate input type", to:message.RespondTo()) } guard parameters.count > 1 else { return sender.send("More parameters required.", to: message.RespondTo()) } switch parameters[1] { case "add": guard parameters.count > 5 else { return sender.send("Incorrect number of parameters specified.", to: message.RespondTo()) } guard let sendIntervalNumber = Int(parameters[2]) else { return sender.send("Send interval number must be an integer.", to: message.RespondTo()) } guard let sendIntervalType = IntervalType(rawValue: parameters[3]) else { return sender.send("Send interval type must be a valid input (hour, day, week, month).", to: message.RespondTo()) } guard let sendTimes = Int(parameters[4]) else { return sender.send("Send times must be an integer.", to: message.RespondTo()) } let sendMessage = parameters[5] guard let respondToHandle = message.RespondTo()?.handle else { return } let post = NSEntityDescription.insertNewObject(forEntityName: "SchedulePost", into: persistentContainer.viewContext) as! SchedulePost post.sendIntervalNumber = Int64(sendIntervalNumber) post.sendNumberTimes = Int64(sendTimes) post.sendIntervalType = sendIntervalType.rawValue post.currentSendCount = 0 post.text = sendMessage post.handle = respondToHandle post.startDate = Date() post.sendNext = getNextSendTime(number: sendIntervalNumber, type: sendIntervalType) persistentContainer.saveContext() sender.send("Your post has been succesfully scheduled.", to: message.RespondTo()) break case "delete": guard let respondHandle = message.RespondTo()?.handle else { return } guard parameters.count > 2 else { return sender.send("The second parameter must be a valid id.", to: message.RespondTo()) } guard let deleteID = Int(parameters[2]) else { return sender.send("The delete ID must be an integer.", to: message.RespondTo()) } guard deleteID > 0 else { return sender.send("The delete ID must be an positive integer.", to: message.RespondTo()) } let posts = getPosts(for: respondHandle) guard posts.count >= deleteID else { return sender.send("The specified post ID is not valid.", to: message.RespondTo()) } persistentContainer.viewContext.delete(posts[deleteID - 1]) persistentContainer.saveContext() sender.send("The specified scheduled post has been deleted.", to: message.RespondTo()) break case "list": guard let respondHandle = message.RespondTo()?.handle else { return } let posts = getPosts(for: respondHandle) var sendMessage = "\(message.sender.givenName ?? "Hello"), you have \(posts.count) posts scheduled." for (index, post) in posts.enumerated() { sendMessage += "\n\(index + 1): Send a message every \(post.sendIntervalNumber) \(post.sendIntervalType!)(s) \(post.sendNumberTimes) time(s), starting on \(post.startDate!.description(with: Locale.current))." } sender.send(sendMessage, to: message.RespondTo()) break default: sender.send("Invalid schedule command type. Must be add, delete, or list", to: message.RespondTo()) break } } func changeName(_ message: Message) { guard let parsedMessage = message.getTextParameters() else { return sender.send("Inappropriate input type", to:message.RespondTo()) } if (parsedMessage.count == 1) { return sender.send("Wrong arguments.", to: message.RespondTo()) } guard (CNContactStore.authorizationStatus(for: CNEntityType.contacts) == .authorized) else { return sender.send("Sorry, I do not have access to contacts.", to: message.RespondTo()) } let store = CNContactStore() let searchPredicate: NSPredicate if (!(message.sender.handle.contains("@"))) { searchPredicate = CNContact.predicateForContacts(matching: CNPhoneNumber(stringValue: message.sender.handle )) } else { searchPredicate = CNContact.predicateForContacts(matchingEmailAddress: message.sender.handle ) } let peopleFound = try! store.unifiedContacts(matching: searchPredicate, keysToFetch:[CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor]) //We need to create the contact if (peopleFound.count == 0) { // Creating a new contact let newContact = CNMutableContact() newContact.givenName = parsedMessage[1] newContact.note = "Created By jared.app" //If it contains an at, add the handle as email, otherwise add it as phone if (message.sender.handle.contains("@")) { let homeEmail = CNLabeledValue(label: CNLabelHome, value: (message.sender.handle) as NSString) newContact.emailAddresses = [homeEmail] } else { let iPhonePhone = CNLabeledValue(label: "iPhone", value: CNPhoneNumber(stringValue:message.sender.handle)) newContact.phoneNumbers = [iPhonePhone] } let saveRequest = CNSaveRequest() saveRequest.add(newContact, toContainerWithIdentifier:nil) do { try store.execute(saveRequest) } catch { return sender.send("There was an error saving your contact..", to: message.RespondTo()) } sender.send("Ok, I'll call you \(parsedMessage[1]) from now on.", to: message.RespondTo()) } //The contact already exists, modify the value else { let mutableContact = peopleFound[0].mutableCopy() as! CNMutableContact mutableContact.givenName = parsedMessage[1] let saveRequest = CNSaveRequest() saveRequest.update(mutableContact) try! store.execute(saveRequest) sender.send("Ok, I'll call you \(parsedMessage[1]) from now on.", to: message.RespondTo()) } } private func getNextSendTime(number: Int, type: IntervalType) -> Date { return Date().addingTimeInterval(Double(number) * (intervalSeconds[type] ?? 0)) } private func getPosts(for handle: String) -> [SchedulePost] { let postRequest:NSFetchRequest<SchedulePost> = SchedulePost.fetchRequest() let sortDescriptor = NSSortDescriptor(key: "startDate", ascending: false) postRequest.sortDescriptors = [sortDescriptor] postRequest.predicate = NSPredicate(format: "handle == %@", handle) do { return try persistentContainer.viewContext.fetch(postRequest) } catch { return [] } } private func getPendingPosts() -> [SchedulePost] { let postRequest:NSFetchRequest<SchedulePost> = SchedulePost.fetchRequest() postRequest.predicate = NSPredicate(format: "sendNext <= %@", NSDate()) do { return try persistentContainer.viewContext.fetch(postRequest) } catch { return [] } } private func bumpPost(post: SchedulePost) { post.currentSendCount += 1 if (post.currentSendCount == post.sendNumberTimes) { persistentContainer.viewContext.delete(post) } else { post.sendNext = getNextSendTime(number: Int(post.sendIntervalNumber), type: IntervalType(rawValue: post.sendIntervalType!)!) } persistentContainer.saveContext() } }
apache-2.0
93d854a2a03ded170d275231cff2ecb8
41.755495
317
0.607081
4.752061
false
false
false
false
borglab/SwiftFusion
Tests/BeeDatasetTests/BeeDatasetTests.swift
1
2410
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import _Differentiation import BeeDataset import SwiftFusion import TensorFlow import XCTest final class BeeDatasetTests: XCTestCase { /// Tests that we can load the frames from a fake dataset. func testLoadFrames() { let frames = BeeFrames( directory: datasetDirectory.appendingPathComponent("frames").appendingPathComponent("seq1"))! XCTAssertEqual(frames.count, 2) let t1 = frames[0] XCTAssertEqual(t1.shape, [200, 100, 3]) XCTAssertEqual(t1[0, 0], Tensor([255, 0, 0])) let t2 = frames[1] XCTAssertEqual(t2.shape, [200, 100, 3]) XCTAssertEqual(t2[0, 0], Tensor([0, 255, 0])) } /// Tests that we can load the oriented bounding boxes from a fake dataset. func testLoadOrientedBoundingBoxes() { let obbs = beeOrientedBoundingBoxes( file: datasetDirectory.appendingPathComponent("obbs").appendingPathComponent("seq1.txt"))! XCTAssertEqual(obbs.count, 2) XCTAssertEqual(obbs[0], OrientedBoundingBox( center: Pose2(Rot2(1), Vector2(100, 200)), rows: 28, cols: 62)) XCTAssertEqual(obbs[1], OrientedBoundingBox( center: Pose2(Rot2(1.5), Vector2(105, 201)), rows: 28, cols: 62)) } /// Tests that we can load a `BeeVideo`. func testLoadBeeVideo() { let v = BeeVideo(videoName: "bee_video_1")! XCTAssertEqual(v.frames.count, 96) XCTAssertGreaterThanOrEqual(v.tracks.count, 2) XCTAssertEqual(v.tracks[0].count, 96) } /// Directory of a fake dataset for tests. let datasetDirectory = URL.sourceFileDirectory().appendingPathComponent("fakeDataset") } extension URL { /// Creates a URL for the directory containing the caller's source file. static func sourceFileDirectory(file: String = #filePath) -> URL { return URL(fileURLWithPath: file).deletingLastPathComponent() } }
apache-2.0
be81b529bb2a73aa24e3c3b4691229fe
37.253968
99
0.720332
4.0301
false
true
false
false
bradhilton/SwiftTable
Pods/OrderedObjectSet/Sources/OrderedObjectSet.swift
2
2394
// // OrderedObjectSet.swift // OrderedObjectSet // // Created by Bradley Hilton on 2/19/16. // Copyright © 2016 Brad Hilton. All rights reserved. // /// An ordered collection of unique `Element` instances. /// _Warning_: `Element` must be a class type. Unfortunately this can not be enforced as a generic requirement, because /// protocols can't be used as concrete types. public struct OrderedObjectSet<Element> : Hashable, RandomAccessCollection, MutableCollection { public typealias SubSequence = ArraySlice<Element> public typealias Indices = DefaultIndices<OrderedObjectSet<Element>> var array: [ObjectWrapper] var set: Set<ObjectWrapper> /// Always zero, which is the index of the first element when non-empty. public var startIndex: Int { return array.startIndex } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. public var endIndex: Int { return array.endIndex } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } public subscript(position: Int) -> Element { get { return array[position].object as! Element } set { let wrapper = ObjectWrapper(newValue as AnyObject) let oldValue = array[position] set.remove(oldValue) array[position] = wrapper set.insert(wrapper) array = array.enumerated().filter { (index, element) in return index == position || element.hashValue != wrapper.hashValue }.map { $0.element } } } public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { return ArraySlice(array[bounds].map { $0.object as! Element }) } set { replaceSubrange(bounds, with: newValue) } } public func hash(into hasher: inout Hasher) { hasher.combine(set) } } public func ==<T>(lhs: OrderedObjectSet<T>, rhs: OrderedObjectSet<T>) -> Bool { return lhs.set == rhs.set }
mit
b33a8b489bcc1a266cf7b8ae5c0ce1ce
29.291139
119
0.61262
4.464552
false
false
false
false
andrebocchini/SwiftChattyOSX
SwiftChattyOSX/Threads/ChattyViewController.swift
1
30477
// // ChattyViewController.swift // SwiftChattyOSX // // Created by Andre Bocchini on 2/20/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Cocoa import SwiftChatty import WebKit private enum Mode: Int { case Chatty case PinnedThreads case SearchResults } class ChattyViewController: NSViewController, DateFormatting, Alerting { // MARK: Thread list outlets @IBOutlet private weak var threadsTableView: NSTableView! @IBOutlet private weak var progressIndicator: NSProgressIndicator! @IBOutlet private weak var searchField: NSSearchField! @IBOutlet private weak var modeSelectionSegmentedControl: NSSegmentedControl! // MARK: Thread posts outlets @IBOutlet private weak var postsTableView: NSTableView! // MARK: Post view outlets @IBOutlet private weak var postView: NSView! @IBOutlet private weak var authorLabel: NSTextField! @IBOutlet private weak var postWebView: WebView! @IBOutlet private weak var dateLabel: NSTextField! @IBOutlet private weak var pinThreadButton: NSButton! @IBOutlet private weak var lolButton: NSButton! @IBOutlet private weak var infButton: NSButton! @IBOutlet private weak var unfButton: NSButton! @IBOutlet private weak var tagButton: NSButton! @IBOutlet private weak var wtfButton: NSButton! @IBOutlet private weak var expirationIndicator: NSProgressIndicator! // MARK: Variables private var mode = Mode.Chatty private var threadManager = ThreadManager(threads: [Thread]()) private var searchManager = SearchManager() private var filtering = false private var filteredThreads = [Thread]() private var selectedThread: Thread { switch (self.mode) { case .Chatty, .PinnedThreads: return self.threadManager.selectedThread case .SearchResults: return self.searchManager.selectedThread } } private var selectedPost: Post { switch (self.mode) { case .Chatty, .PinnedThreads: return self.threadManager.selectedPost case .SearchResults: return self.searchManager.selectedPost } } private var threadsTableViewDataSource: [Thread] { if self.filtering { return self.filteredThreads } switch (self.mode) { case .Chatty: return self.threadManager.threads case .PinnedThreads: return self.threadManager.pinnedThreads case .SearchResults: return self.searchManager.results } } private var urlRequestForLinkClickedInPost: NSURLRequest? private var newestEventId = 0 private var processingEvents = false private var respondingToNotification = false private var autoUpdateTimer: NSTimer? private lazy var postBodyHtmlTemplate: String? = { if let htmlFilePath = NSBundle.mainBundle().pathForResource("Post", ofType: "html"), let styleSheetFilePath = NSBundle.mainBundle().pathForResource("Stylesheet", ofType: "css") { do { let stylesheet = try String(contentsOfFile: styleSheetFilePath, encoding: NSUTF8StringEncoding) var html = try String(contentsOfFile: htmlFilePath, encoding: NSUTF8StringEncoding) html = html.stringByReplacingOccurrencesOfString("<%= stylesheet %>", withString: stylesheet) return html } catch { return nil } } return nil }() private lazy var notificationCenter: NSUserNotificationCenter = { let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() notificationCenter.delegate = self return notificationCenter }() // MARK: Constants private let searchSegueIdentifier = "search" private let composeNewPostSegueIdentifier = "newPost" private let composeReplySegueIdentifier = "reply" private let showWebLinkSegueIdentifier = "showWebLink" private let blankHtml = "<html><body bgcolor=\"#000000\"></body></html>" private let autoUpdateInterval = 30.0 private let notificationIdentifier = "SwitchChattyOSXNotificationIdentifier" private let userDefaults = NSUserDefaults.standardUserDefaults() // MARK: Initialization override func viewDidLoad() { super.viewDidLoad() configurePostView() configureTableViews() enableProgressIndicator() refreshChatty() } private func configureTableViews() { let threadTableCellNib = NSNib(nibNamed: String(ThreadTableCell.self), bundle: NSBundle.mainBundle()) self.threadsTableView.registerNib(threadTableCellNib!, forIdentifier: ThreadTableCell.identifier) let threadPostTableCellNib = NSNib(nibNamed: String(ThreadPostTableCell.self), bundle: NSBundle.mainBundle()) self.postsTableView.registerNib(threadPostTableCellNib!, forIdentifier: ThreadPostTableCell.identifier) } private func configurePostView() { self.postView.wantsLayer = true self.postView.layer?.backgroundColor = NSColor.standardBackgroundColor.CGColor self.postWebView.mainFrame.loadHTMLString(blankHtml, baseURL: NSBundle.mainBundle().bundleURL) } private func setMode(mode: Mode) { self.mode = mode self.modeSelectionSegmentedControl.selectedSegment = mode.rawValue reloadThreadsTableView(preserveSelection: false) selectFirstThread() } // MARK: Table view convenience operations private func selectFirstThread() { switch (mode) { case .Chatty, .PinnedThreads: self.threadManager.selectFirstThread() case .SearchResults: self.searchManager.selectFirstThread() } selectThread(self.selectedThread) } private func selectThread(thread: Thread) { switch (self.mode) { case .Chatty, .PinnedThreads: self.threadManager.selectThread(thread) case .SearchResults: self.searchManager.selectThread(thread) } for (row, thread) in self.threadsTableViewDataSource.enumerate() { if thread.id == self.selectedThread.id { let rowsToSelect = NSIndexSet(index: row) self.threadsTableView.selectRowIndexes(rowsToSelect, byExtendingSelection: false) self.threadsTableView.scrollRowToVisible(row) } } } private func selectFirstPost() { switch (self.mode) { case .Chatty, .PinnedThreads: self.threadManager.selectFirstPost() case .SearchResults: self.searchManager.selectFirstPost() } selectPost(self.selectedPost) } private func selectPost(post: Post) { switch (self.mode) { case .Chatty, .PinnedThreads: self.threadManager.selectPost(post) case .SearchResults: self.searchManager.selectPost(post) } for (row, post) in self.selectedThread.posts.enumerate() { if post.id == self.selectedPost.id { let rowsToSelect = NSIndexSet(index: row) self.postsTableView.selectRowIndexes(rowsToSelect, byExtendingSelection: false) self.postsTableView.scrollRowToVisible(row) } } displayPost(post) } private func reloadThreadsTableView(preserveSelection preserveSelection: Bool) { if preserveSelection { self.threadsTableView.reloadData() for (row, thread) in self.threadsTableViewDataSource.enumerate() { if thread.id == self.selectedThread.id { let rowsToSelect = NSIndexSet(index: row) self.threadsTableView.selectRowIndexes(rowsToSelect, byExtendingSelection: false) } } } else { self.threadsTableView.reloadData() } } private func reloadPostsTableView(preserveSelection preserveSelection: Bool) { if preserveSelection { self.postsTableView.reloadData() for (row, post) in self.selectedThread.posts.enumerate() { if post.id == self.selectedPost.id { let rowsToSelect = NSIndexSet(index: row) self.postsTableView.selectRowIndexes(rowsToSelect, byExtendingSelection: false) } } } else { self.postsTableView.reloadData() } } // MARK: Auto refresh timer private func enableAutoUpdateTimer() { self.autoUpdateTimer = NSTimer.scheduledTimerWithTimeInterval(autoUpdateInterval, target: self, selector: #selector(ChattyViewController.pollForEvents), userInfo: nil, repeats: true) self.autoUpdateTimer?.fire() } private func disableAutoUpdateTimer() { self.autoUpdateTimer?.invalidate() } // MARK: Chatty private func refreshChatty() { ChattyService.getChatty(success: { (threads: [Thread]) in self.disableProgressIndicator() self.threadManager.threads = threads self.setMode(.Chatty) if self.newestEventId == 0 { self.getNewestEventId() } else { self.enableAutoUpdateTimer() } }, failure: { (error) in self.disableProgressIndicator() self.displayErrorAlert(NSLocalizedString("Error", comment: ""), informativeText: NSLocalizedString("There was a problem downloading threads.", comment: "") + " \(error)") }) } // MARK: Events private func getNewestEventId() { ChattyService.getNewestEventId(success: { (newestEventId) in self.newestEventId = newestEventId self.enableAutoUpdateTimer() }) { (error) in print(error) } } func pollForEvents() { ChattyService.pollForEvent(self.newestEventId, includeParentAuthor: true, success: { (events, lastEventId) in self.newestEventId = lastEventId self.processEvents(events) }, failure: { (error) in switch error { case .TooManyEvents: self.disableAutoUpdateTimer() self.getNewestEventId() default: print(error) } }) } private func processEvents(events: [Event]) { self.processingEvents = true for event in events { if event.type == .NewPost { if let data = event.data as? EventNewPost { processNewPostEvent(data.post, parentAuthor: data.parentAuthor) } } else if event.type == .LolCountsUpdate { if let data = event.data as? EventLolCountUpdates { processLolCountsUpdateEvent(data.updates) } } else if event.type == .CategoryChange { if let data = event.data as? EventCategoryChange { if let category = data.category { processCategoryChangeEvent(category, updatedPostId: data.postId) } } } } processingEvents = false } private func processNewPostEvent(newPost: Post, parentAuthor: String?) { self.threadManager.processNewPostEvent(newPost, parentAuthor: parentAuthor) if self.mode == .Chatty || self.mode == .PinnedThreads { reloadThreadsTableView(preserveSelection: true) reloadPostsTableView(preserveSelection: true) } if shouldPostNewReplyNotification(newPost, parentAuthor: parentAuthor) { postNewReplyNotification(newPost) } } private func processLolCountsUpdateEvent(updates: [LolCountUpdate]) { self.threadManager.processLolCountsUpdateEvent(updates) if self.mode == .Chatty || self.mode == .PinnedThreads { reloadThreadsTableView(preserveSelection: true) reloadPostsTableView(preserveSelection: true) } } private func processCategoryChangeEvent(category: ModerationFlag, updatedPostId: Int) { self.threadManager.processCategoryChangeEvent(category, updatedPostId: updatedPostId) if self.mode == .Chatty || self.mode == .PinnedThreads { reloadThreadsTableView(preserveSelection: true) reloadPostsTableView(preserveSelection: true) } } // MARK: Notifications private func shouldPostNewReplyNotification(post: Post, parentAuthor: String?) -> Bool { let shouldDisplayReplyNotifications = self.userDefaults.integerForKey(Preferences.DisplayReplyNotifications.rawValue) != NSOffState if shouldDisplayReplyNotifications { var account = Account() account.loadFromUserDefaults() if let parentAuthor = parentAuthor where parentAuthor == account.username { return true } } return false } private func postNewReplyNotification(post: Post) { var userInfo = [String: Int]() userInfo["postId"] = post.id userInfo["threadId"] = post.threadId let notification = NSUserNotification() notification.title = NSLocalizedString("New reply", comment: "") notification.subtitle = post.author notification.informativeText = post.htmlAndSpoilerFreeBody notification.identifier = notificationIdentifier notification.userInfo = userInfo self.notificationCenter.scheduleNotification(notification) } // MARK: Pinned threads private func threadPinStatusAsString(thread: Thread) -> String { if thread.isPinned() { return NSLocalizedString("Unpin", comment: "") } else { return NSLocalizedString("Pin", comment: "") } } // MARK: Progress indicator private func enableProgressIndicator() { self.searchField.hidden = true self.progressIndicator.hidden = false self.progressIndicator.startAnimation(self) } private func disableProgressIndicator() { self.searchField.hidden = false self.progressIndicator.hidden = true self.progressIndicator.stopAnimation(self) } // MARK: IBAction @IBAction private func modeSelectionSegmentedControlValueChanged(sender: AnyObject) { self.searchField.stringValue = "" self.filtering = false if let mode = Mode(rawValue: self.modeSelectionSegmentedControl.selectedSegment) { setMode(mode) } else { setMode(.Chatty) } } @IBAction private func refreshToolbarButtonClicked(sender: AnyObject) { enableProgressIndicator() if self.mode == .Chatty { disableAutoUpdateTimer() refreshChatty() } } @IBAction private func searchToolbarButtonClicked(sender: AnyObject) { performSegueWithIdentifier(searchSegueIdentifier, sender: self) } @IBAction private func newPostButtonClicked(sender: AnyObject) { performSegueWithIdentifier(composeNewPostSegueIdentifier, sender: self) } @IBAction private func replyButtonClicked(sender: AnyObject) { performSegueWithIdentifier(composeReplySegueIdentifier, sender: self) } @IBAction private func lolButtonClicked(sender: AnyObject) { if sender as! NSObject == self.lolButton { lolPost(self.selectedPost, tag: .Lol) self.lolButton.configure(.Lol, loled: true) } else if sender as! NSObject == self.infButton { lolPost(self.selectedPost, tag: .Inf) self.infButton.configure(.Inf, loled: true) } else if sender as! NSObject == self.unfButton { lolPost(self.selectedPost, tag: .Unf) self.unfButton.configure(.Unf, loled: true) } else if sender as! NSObject == self.tagButton { lolPost(self.selectedPost, tag: .Tag) self.tagButton.configure(.Tag, loled: true) } else if sender as! NSObject == self.wtfButton { lolPost(self.selectedPost, tag: .Wtf) self.wtfButton.configure(.Wtf, loled: true) } } @IBAction private func pinThreadButtonClicked(sender: AnyObject) { self.selectedThread.isPinned() ? self.threadManager.unpinThread(self.selectedThread) : self.threadManager.pinThread(self.selectedThread) self.pinThreadButton.title = threadPinStatusAsString(self.selectedThread) if (self.mode == .PinnedThreads) { reloadThreadsTableView(preserveSelection: false) } } // MARK: Segues override internal func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { if segue.identifier == self.searchSegueIdentifier { let searchViewController = segue.destinationController as! SearchViewController searchViewController.searchManager = self.searchManager searchViewController.delegate = self } else if segue.identifier == self.composeReplySegueIdentifier { let composeReplyViewController = segue.destinationController as! ComposePostReplyViewController composeReplyViewController.post = self.selectedPost } else if segue.identifier == self.showWebLinkSegueIdentifier { let webBrowserViewController = segue.destinationController as! WebBrowserViewController webBrowserViewController.urlRequest = self.urlRequestForLinkClickedInPost webBrowserViewController.width = self.view.frame.size.width * 0.95 webBrowserViewController.height = self.view.frame.size.height * 0.95 } } // MARK: Posting private func composeNewPost() { performSegueWithIdentifier(composeNewPostSegueIdentifier, sender: self) } private func composeReply() { performSegueWithIdentifier(composeReplySegueIdentifier, sender: self) } // MARK: Search private func search() { performSegueWithIdentifier(searchSegueIdentifier, sender: self) } // MARK: Filtering @IBAction private func searchFieldUpdated(sender: AnyObject) { let filterTerms = self.searchField.stringValue.lowercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if filterTerms.characters.count > 0 { self.filtering = true filter(filterTerms) } else { self.filtering = false } reloadThreadsTableView(preserveSelection: false) } private func filter(terms: String) { var filterSource: [Thread] switch (self.mode) { case .Chatty: filterSource = self.threadManager.threads case .PinnedThreads: filterSource = self.threadManager.pinnedThreads case .SearchResults: filterSource = self.searchManager.results } self.filteredThreads = filterSource.filter({ $0.rootPost().author.lowercaseString.containsString(terms) || $0.rootPost().body.lowercaseString.containsString(terms) }) } // MARK: Display post private func displayPost(post: Post) { self.authorLabel.stringValue = post.author self.dateLabel.stringValue = elapsedTimeUntilNow(fromDate: post.date) if let html = self.postBodyHtmlTemplate?.stringByReplacingOccurrencesOfString("<%= body %>", withString: post.body) { self.postWebView.mainFrame.loadHTMLString(html, baseURL: NSBundle.mainBundle().bundleURL) } self.pinThreadButton.title = threadPinStatusAsString(self.selectedThread) resetLolButtons() configureLolButtonsWithLolTags(post.lols) configureExpirationIndicator(post) } private func configureExpirationIndicator(post: Post) { if post.id == self.selectedThread.rootPost().id { self.expirationIndicator.hidden = false self.expirationIndicator.minValue = 0 self.expirationIndicator.maxValue = 19 self.expirationIndicator.displayedWhenStopped = true self.expirationIndicator.bezeled = true self.expirationIndicator.controlTint = .BlueControlTint self.expirationIndicator.doubleValue = Double(elapsedHoursUntilNow(fromDate: post.date)) + 1 } else { self.expirationIndicator.hidden = true } } // MARK: LOL private func resetLolButtons() { self.lolButton.configure(.Lol, loled: false) self.infButton.configure(.Inf, loled: false) self.unfButton.configure(.Unf, loled: false) self.tagButton.configure(.Tag, loled: false) self.wtfButton.configure(.Wtf, loled: false) } private func configureLolButtonsWithLolTags(lols: [LOL]) { for lol in lols { switch (lol.tag) { case .Lol: self.lolButton.configure(lol) case .Inf: self.infButton.configure(lol) case .Unf: self.unfButton.configure(lol) case .Tag: self.tagButton.configure(lol) case .Wtf: self.wtfButton.configure(lol) default: print("Unsupported tag: \(lol.tag)") } } } private func lolPost(post: Post, tag: LolTag) { var account = Account() account.loadFromUserDefaults() account.loadFromKeyChain() ChattyService.lolPost(account, post: post, tag: tag, success: { print("Successfully tagged post with ID: \(post.id) and TAG: \(tag.rawValue)") }, failure: { (error) in switch (error) { case .LolError(let message): self.displayErrorAlert(NSLocalizedString("Error", comment: ""), informativeText: message) default: self.displayErrorAlert(NSLocalizedString("Error", comment: ""), informativeText: NSLocalizedString("There was a problem trying to tag this post.", comment: "") + " \(error)") } }) } } // MARK: Table view data source extension ChattyViewController: NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { switch (tableView) { case self.threadsTableView: return self.threadsTableViewDataSource.count default: return self.selectedThread.posts.count } } } // MARK: Table view delegate extension ChattyViewController: NSTableViewDelegate { func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { switch (tableView) { case self.threadsTableView: return 140 default: return 29 } } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { switch (tableView) { case self.threadsTableView: if let threadTableCell = tableView.makeViewWithIdentifier(ThreadTableCell.identifier, owner: nil) as? ThreadTableCell { var account = Account() account.loadFromUserDefaults() let thread = self.threadsTableViewDataSource[row] let hasExpirationIndicator = !(self.mode == .SearchResults) let displayRepliesCount = !(self.mode == .SearchResults) var unread = false if self.mode == .Chatty || self.mode == .PinnedThreads { unread = self.threadManager.isThreadUnread(thread) } var newReplies = 0 if self.mode == .Chatty || self.mode == .PinnedThreads { newReplies = self.threadManager.unreadRepliesCount(thread) } if let username = account.username { let isParticipant = thread.isParticipant(username) threadTableCell.configure(thread, isParticipant: isParticipant, hasExpirationIndicator: hasExpirationIndicator, unread: unread, displayRepliesCount: displayRepliesCount, newRepliesCount: newReplies) } else { threadTableCell.configure(thread, isParticipant: false, hasExpirationIndicator: hasExpirationIndicator, unread: unread, displayRepliesCount: displayRepliesCount, newRepliesCount: newReplies) } return threadTableCell } default: if let threadPostTableCell = postsTableView.makeViewWithIdentifier(ThreadPostTableCell.identifier, owner: self) as? ThreadPostTableCell { var account = Account() account.loadFromUserDefaults() let thread = self.selectedThread let post = thread.posts[row] let participant = account.username == post.author let originalPoster = thread.rootPost().author == post.author var unread = false if self.mode == .Chatty || self.mode == .PinnedThreads { unread = self.threadManager.isPostUnread(post) } threadPostTableCell.configure(post, depth: thread.depth(forPost: post), participant: participant, originalPoster: originalPoster, unread: unread) return threadPostTableCell } } return nil } func tableViewSelectionDidChange(notification: NSNotification) { guard !self.processingEvents else { return } switch (notification.object as! NSTableView) { case self.threadsTableView: guard (self.threadsTableView.selectedRow >= 0) && (self.threadsTableView.selectedRow < self.threadsTableViewDataSource.count) else { break } if (mode == .SearchResults) { let searchResult = threadsTableViewDataSource[threadsTableView.selectedRow] selectThread(searchResult) selectPost(searchResult.rootPost()) reloadPostsTableView(preserveSelection: false) } else { let thread = threadsTableViewDataSource[threadsTableView.selectedRow] selectThread(thread) reloadPostsTableView(preserveSelection: false) if !self.respondingToNotification { selectFirstPost() } else { self.respondingToNotification = false } } default: guard (self.postsTableView.selectedRow >= 0) && (self.postsTableView.selectedRow < self.selectedThread.posts.count) else { break } let post = self.selectedThread.posts[self.postsTableView.selectedRow] selectPost(post) } if self.mode == .Chatty || self.mode == .PinnedThreads { self.postsTableView.beginUpdates() let selectedPostRowIndexes = self.postsTableView.selectedRowIndexes self.postsTableView.reloadDataForRowIndexes(selectedPostRowIndexes, columnIndexes: NSIndexSet(index: 0)) self.postsTableView.endUpdates() self.threadsTableView.beginUpdates() let selectedThreadRowIndexes = self.threadsTableView.selectedRowIndexes self.threadsTableView.reloadDataForRowIndexes(selectedThreadRowIndexes, columnIndexes: NSIndexSet(index: 0)) self.threadsTableView.endUpdates() } } func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool { if self.processingEvents { return false } else { return true } } func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { return ThreadTableRowView() } } // MARK: Search view controller delegate extension ChattyViewController: SearchViewControllerDelegate { func searchViewControllerDidFailSearch(viewController: SearchViewController, error: Error) { displayErrorAlert(NSLocalizedString("Error", comment: ""), informativeText: NSLocalizedString("There was a problem executing your search.", comment: "")) } func searchViewControllerDidSearch(viewController: SearchViewController) { setMode(.SearchResults) } } // MARK: WebPolicyDelegate extension ChattyViewController: WebPolicyDelegate { func webView(webView: WebView!, decidePolicyForNewWindowAction actionInformation: [NSObject:AnyObject]!, request: NSURLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) { if actionInformation[WebActionNavigationTypeKey] != nil { urlRequestForLinkClickedInPost = request if userDefaults.integerForKey(Preferences.OpenLinksInExternalBrowser.rawValue) == NSOnState { if let url = self.urlRequestForLinkClickedInPost?.URL { NSWorkspace.sharedWorkspace().openURL(url) } } else { performSegueWithIdentifier(self.showWebLinkSegueIdentifier, sender: self) } } else { listener.ignore() } } } // MARK: Notification delegate extension ChattyViewController: NSUserNotificationCenterDelegate { func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) { center.removeDeliveredNotification(notification) if let postId = notification.userInfo?["postId"] as? Int, let threadId = notification.userInfo?["threadId"] as? Int { for thread in self.threadManager.threads { if thread.id == threadId { for post in thread.posts { if post.id == postId { self.respondingToNotification = true setMode(.Chatty) selectThread(thread) selectPost(post) } } } } } } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } }
mit
6b7abbf85565f7232618dce7f30c3668
34.396051
222
0.638798
5.169805
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFReferencePageBackgroundView.swift
1
630
class WMFReferencePageBackgroundView: UIView { var clearRect:CGRect = CGRectZero { didSet { setNeedsDisplay() } } override func drawRect(rect: CGRect) { super.drawRect(rect) UIColor.clearColor().setFill() UIBezierPath.init(roundedRect: clearRect, cornerRadius: 3).fillWithBlendMode(.Copy, alpha: 1.0) } override func didMoveToSuperview() { userInteractionEnabled = false clearsContextBeforeDrawing = false backgroundColor = UIColor.init(white: 0.0, alpha: 0.5) translatesAutoresizingMaskIntoConstraints = false } }
mit
2523cd0931f0c6905afad125ffd3b2b4
29
103
0.653968
5.163934
false
false
false
false
joerocca/GitHawk
Classes/Issues/Managing/IssueManagingModel.swift
1
867
// // IssueManagingModel.swift // Freetime // // Created by Ryan Nystrom on 12/2/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueManagingModel: ListDiffable { let objectId: String let pullRequest: Bool init(objectId: String, pullRequest: Bool) { self.objectId = objectId self.pullRequest = pullRequest } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { // should only ever be one return "managing_model" as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { if self === object { return true } guard let object = object as? IssueManagingModel else { return false } return pullRequest == object.pullRequest && objectId == object.objectId } }
mit
7b6768d9eed60613a75c2e4225ae64e6
23.055556
78
0.660508
4.681081
false
false
false
false
crossroadlabs/Express
Express/Content.swift
1
3113
//===--- Content.swift ----------------------------------------------------===// // //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express. // //Swift Express is free software: you can redistribute it and/or modify //it under the terms of the GNU Lesser General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public License //along with Swift Express. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// import Foundation import Future import ExecutionContext public protocol ContentFactoryType : DataConsumerType { associatedtype Content init(response:RequestHeadType) func tryConsume(content:ContentType) -> Bool func content() -> Future<Content> } public protocol ContentType { var contentType:String? {get} } public protocol ConstructableContentType : ContentType { associatedtype Factory: ContentFactoryType } public class ContentFactoryBase { public let head:RequestHeadType public required init(response:RequestHeadType) { head = response } } public protocol FlushableContentType : ContentType, FlushableType { } public class FlushableContent : FlushableContentType { let content:FlushableContentType public var contentType:String? { get { return content.contentType } } public required init(content:FlushableContentType) { self.content = content } public func flushTo(out:DataConsumerType) -> Future<Void> { return content.flushTo(out: out) } } public class AbstractContentFactory<T> : ContentFactoryBase, ContentFactoryType { public typealias Content = T var promise:Promise<Content> public required init(response:RequestHeadType) { promise = Promise() super.init(response: response) } public func consume(data:Array<UInt8>) -> Future<Void> { return future(context: immediate) { throw ExpressError.NotImplemented(description: "Not implemented consume in " + Mirror(reflecting: self).description) } } public func dataEnd() throws { throw ExpressError.NotImplemented(description: "Not implemented consume in " + Mirror(reflecting: self).description) } public func tryConsume(content: ContentType) -> Bool { switch content { case let match as Content: //TODO: check this? return value? promise.trySuccess(value: match) return true default: return false } } public func content() -> Future<Content> { return promise.future } }
gpl-3.0
383f1f334fbb208c86e64ae454be8ab7
28.932692
128
0.656923
4.818885
false
false
false
false
contentful/blog-app-ios
Code/AppDelegate.swift
1
3057
// // AppDelegate.swift // Blog // // Created by Boris Bügling on 22/01/15. // Copyright (c) 2015 Contentful GmbH. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { class var AccessToken: String { return "ContentfulAccessToken" } class var SpaceKey: String { return "ContentfulSpaceKey" } class var SpaceChangedNotification: String { return "ContentfulSpaceChangedNotification" } var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { writeKeysToUserDefaults() window?.backgroundColor = UIColor.whiteColor() return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if let components = components { if components.scheme != "contentful-blog" { return false } if components.host != "open" { return false } if components.query == nil { return false } if let path = components.path { if !path.hasPrefix("/space") { return false } let spaceKey = NSURL(fileURLWithPath: path).lastPathComponent var accessToken: String? = nil for parameter in components.query!.componentsSeparatedByString("&") { let parameterComponents = parameter.componentsSeparatedByString("=") if parameterComponents.count != 2 { return false } if parameterComponents[0] == "access_token" { accessToken = parameterComponents[1] } } if let accessToken = accessToken, spaceKey = spaceKey { NSUserDefaults.standardUserDefaults().setValue(accessToken, forKey: AppDelegate.AccessToken) NSUserDefaults.standardUserDefaults().setValue(spaceKey, forKey: AppDelegate.SpaceKey) NSNotificationCenter.defaultCenter().postNotificationName(AppDelegate.SpaceChangedNotification, object: nil, userInfo: [ AppDelegate.SpaceKey: spaceKey, AppDelegate.AccessToken: accessToken ]) return true } } } return false } func writeKeysToUserDefaults() { let defaults = NSUserDefaults.standardUserDefaults() let keys = BlogKeys() if defaults.stringForKey(AppDelegate.SpaceKey) == nil { defaults.setValue(keys.blogSpaceId(), forKey: AppDelegate.SpaceKey) } if defaults.stringForKey(AppDelegate.AccessToken) == nil { defaults.setValue(keys.blogAccessToken(), forKey: AppDelegate.AccessToken) } } }
mit
08b92dad196f2433b1a2efbef643e6e6
33.337079
212
0.607003
5.843212
false
false
false
false
vanyaland/Popular-Movies
iOS/PopularMovies/Network/Network/Webservice.swift
1
1274
// // Webservice.swift // Videos // // Created by Florian on 13/04/16. // Copyright © 2016 Chris Eidhof. All rights reserved. // import UIKit public typealias JSONDictionary = [String: Any] // We create our own session here without a URLCache to avoid playground error messages private var session: URLSession { let config = URLSessionConfiguration.default config.urlCache = nil return URLSession(configuration: config) } public final class Webservice { public var authenticationToken: String? public init() { } /// Loads a resource. The completion handler is always called on the main queue. public func load<A>(_ resource: Resource<A>, completion: @escaping (Result<A>) -> () = logError) { session.dataTask(with: resource.url, completionHandler: { data, response, _ in let result: Result<A> if let httpResponse = response as? HTTPURLResponse , httpResponse.statusCode == 401 { result = Result.error(WebserviceError.notAuthenticated) } else { let parsed = data.flatMap(resource.parse) result = Result(parsed, or: WebserviceError.other) } DispatchQueue.main.async { completion(result) } }) .resume() } }
mit
dab4c78c7277325180352360b837165b
33.405405
102
0.655145
4.546429
false
true
false
false
rechsteiner/LayoutEngine
LayoutEngine/ViewDefaultMetric.swift
1
361
import UIKit public struct ViewDefaultMetric: ViewMetric { public let insets: UIEdgeInsets public let direction: ViewDirection public let hidden: Bool public init(insets: UIEdgeInsets = UIEdgeInsets(), direction: ViewDirection = .left, hidden: Bool = false) { self.insets = insets self.direction = direction self.hidden = hidden } }
mit
926316b4b038d28c0f49c0cbc81dedc5
23.066667
110
0.725762
4.45679
false
false
false
false
sinorychan/iOS-11-by-Examples
iOS-11-by-Examples/Vision/VisionViewController.swift
1
2279
// // VisionViewController.swift // iOS-11-by-Examples // // Created by Artem Novichkov on 20/06/2017. // Copyright © 2017 Artem Novichkov. All rights reserved. // import UIKit class VisionViewController: UITableViewController { lazy var visionExamples = [Example(title: "😀 Face Detection", description: "Detect faces on photo", storyboardName: "Vision", controllerID: "FaceDetection"), Example(title: "🔬 Object Tracking", description: "Track object with camera", storyboardName: "Vision", controllerID: "ObjectTracking"), Example(title: "🤥 Landmarks", description: "Detects face features on photo", storyboardName: "Vision", controllerID: "Landmarks")] override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } } extension VisionViewController { // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return visionExamples.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) let sample = visionExamples[indexPath.row] cell.textLabel?.text = sample.title cell.detailTextLabel?.text = sample.description return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sample = visionExamples[indexPath.row] if let controller = sample.controller { navigationController?.pushViewController(controller, animated: true) } tableView.deselectRow(at: indexPath, animated: true) } }
mit
b62e962ea7f61d6a9cf794b0c7b579bf
36.196721
109
0.564125
6.050667
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Calculator/Calculator/CalculatorButtonItem.swift
1
1588
// // CalculatorButtonItem.swift // Calculator // // Created by 黄伯驹 on 2021/10/29. // import SwiftUI enum CalculatorButtonItem { enum Op: String { case plus = "+" case minus = "-" case divide = "÷" case multiply = "×" case equal = "=" } enum Command: String { case clear = "AC" case flip = "+/-" case percent = "%" } case digit(Int) case dot case op(Op) case command(Command) } extension CalculatorButtonItem { var title: String { switch self { case .digit(let value): return String(value) case .dot: return "." case .op(let op): return op.rawValue case .command(let command): return command.rawValue } } var backgroundColorName: String { switch self { case .digit, .dot: return "digitBackground" case .op: return "operatorBackground" case .command: return "commandBackground" } } } extension CalculatorButtonItem: Hashable {} extension CalculatorButtonItem { var size: CGSize { if case .digit(let value) = self, value == 0 { return CGSize(width: 88 * 2 + 8, height: 88) } return CGSize(width: 88, height: 88) } } extension CalculatorButtonItem: CustomStringConvertible { var description: String { switch self { case .digit(let num): return String(num) case .dot: return "." case .op(let op): return op.rawValue case .command(let command): return command.rawValue } } }
mit
8813a9e928cad118f95f8a2441a62cc5
22.235294
59
0.574684
4.168865
false
false
false
false
HongxiangShe/STV
STV/STV/Classes/Live/View/ChatContentView/ChatContentView.swift
1
1531
// // ChatContentView.swift // STV // // Created by 佘红响 on 2017/7/7. // Copyright © 2017年 she. All rights reserved. // import UIKit private let CELL_ID = "CELL_ID" class ChatContentView: UIView, Nibloadable { @IBOutlet weak var tableView: UITableView! fileprivate lazy var messageArr: [NSAttributedString] = [NSAttributedString]() override func awakeFromNib() { super.awakeFromNib() tableView.backgroundColor = UIColor.clear tableView.separatorStyle = .none tableView.estimatedRowHeight = 40 tableView.rowHeight = UITableViewAutomaticDimension tableView.register(UINib(nibName: "ChatContentCell", bundle: nil), forCellReuseIdentifier: CELL_ID) } func insertMessage(_ message: NSAttributedString) { messageArr.append(message) tableView.reloadData() tableView.scrollToRow(at: IndexPath(row:messageArr.count - 1, section: 0), at: .middle, animated: true) } } extension ChatContentView: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArr.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ChatContentCell = tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath) as! ChatContentCell cell.contentLabel.attributedText = messageArr[indexPath.row] return cell } }
apache-2.0
feec7c60a06e02e4412320a88d3e6f3f
30.708333
126
0.696452
4.801262
false
false
false
false
admkopec/BetaOS
Kernel/Swift Extensions/MemoryBuffer.swift
1
3415
// // MemoryBuffer.swift // Kernel // // Created by Adam Kopeć on 10/17/17. // Copyright © 2017-2018 Adam Kopeć. All rights reserved. // typealias Data = UnsafeBufferPointer<UInt8> typealias MutableData = UnsafeMutableBufferPointer<UInt8> final class MemoryBuffer { let ptr: UnsafeRawPointer let buffer: UnsafeBufferPointer<UInt8> var offset: Int = 0 var bytesRemaining: Int { return (buffer.count - offset) } init(_ basePtr: UnsafeRawPointer, size: Int) { ptr = basePtr let bufferPtr = ptr.bindMemory(to: UInt8.self, capacity: size) buffer = UnsafeBufferPointer(start: bufferPtr, count: size) } init(_ baseAddr: UInt, size: Int) { ptr = UnsafeRawPointer(bitPattern: baseAddr)! let bufferPtr = ptr.bindMemory(to: UInt8.self, capacity: size) buffer = UnsafeBufferPointer(start: bufferPtr, count: size) } func read<T>() /*throws*/ -> T? { guard bytesRemaining > 0 else { return nil // throw ReadError.InvalidOffset } guard bytesRemaining >= MemoryLayout<T>.size else { return nil // throw ReadError.InvalidOffset } let result = ptr.advanced(by: offset).assumingMemoryBound(to: T.self).pointee//ptr.load(fromByteOffset: offset, as: T.self) offset += MemoryLayout<T>.size return result } func readAtIndex<T>(_ index: Int) /*throws*/ -> T? { guard index + MemoryLayout<T>.size <= buffer.count else { return nil // throw ReadError.InvalidOffset } return ptr.load(fromByteOffset: index, as: T.self) } func subBufferAtOffset(_ start: Int, size: Int) -> MemoryBuffer { return MemoryBuffer(ptr.advanced(by: start), size: size) } func subBufferAtOffset(_ start: Int) -> MemoryBuffer { var size = buffer.count - start if size < 0 { size = 0 } return subBufferAtOffset(start, size: size) } // Functions to convert ASCII strings in memory to String. Inefficient // conversions because Foundation isnt available // Only really works for 7bit ASCII as it assumes the code is valid UTF-8 func readASCIIZString(maxSize: Int) /*throws*/ -> String? { guard maxSize > 0 else { return nil // throw ReadError.InvalidOffset } guard bytesRemaining > 0 else { return nil // throw ReadError.InvalidOffset } guard bytesRemaining >= maxSize else { return nil // throw ReadError.InvalidOffset } var result = "" for _ in 0...maxSize-1 { guard let ch: UInt8 = /*try*/ read() else { return nil } if ch == 0 { break } result += String(Character(UnicodeScalar(ch))) } return result } // read from the current offset until the first nul byte is found func scanASCIIZString() /*throws*/ -> String? { var result = "" var ch: UInt8// = try read() guard let ch_: UInt8 = read() else { return nil } ch = ch_ while ch != 0 { result += String(Character(UnicodeScalar(ch))) guard let Ch_: UInt8 = read() else { return nil } ch = Ch_//try read() } return result } }
apache-2.0
f8d7dbe62a22be6c8116572af727d54b
27.915254
131
0.579719
4.385604
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Signer/Signer_Shapes.swift
1
39747
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension Signer { // MARK: Enums public enum Category: String, CustomStringConvertible, Codable { case awsiot = "AWSIoT" public var description: String { return self.rawValue } } public enum EncryptionAlgorithm: String, CustomStringConvertible, Codable { case ecdsa = "ECDSA" case rsa = "RSA" public var description: String { return self.rawValue } } public enum HashAlgorithm: String, CustomStringConvertible, Codable { case sha1 = "SHA1" case sha256 = "SHA256" public var description: String { return self.rawValue } } public enum ImageFormat: String, CustomStringConvertible, Codable { case json = "JSON" case jsondetached = "JSONDetached" case jsonembedded = "JSONEmbedded" public var description: String { return self.rawValue } } public enum SigningProfileStatus: String, CustomStringConvertible, Codable { case active = "Active" case canceled = "Canceled" public var description: String { return self.rawValue } } public enum SigningStatus: String, CustomStringConvertible, Codable { case failed = "Failed" case inprogress = "InProgress" case succeeded = "Succeeded" public var description: String { return self.rawValue } } // MARK: Shapes public struct CancelSigningProfileRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "profileName", location: .uri(locationName: "profileName")) ] /// The name of the signing profile to be canceled. public let profileName: String public init(profileName: String) { self.profileName = profileName } public func validate(name: String) throws { try self.validate(self.profileName, name: "profileName", parent: name, max: 64) try self.validate(self.profileName, name: "profileName", parent: name, min: 2) try self.validate(self.profileName, name: "profileName", parent: name, pattern: "^[a-zA-Z0-9_]{2,}") } private enum CodingKeys: CodingKey {} } public struct DescribeSigningJobRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "jobId", location: .uri(locationName: "jobId")) ] /// The ID of the signing job on input. public let jobId: String public init(jobId: String) { self.jobId = jobId } private enum CodingKeys: CodingKey {} } public struct DescribeSigningJobResponse: AWSDecodableShape { /// Date and time that the signing job was completed. public let completedAt: Date? /// Date and time that the signing job was created. public let createdAt: Date? /// The ID of the signing job on output. public let jobId: String? /// A list of any overrides that were applied to the signing operation. public let overrides: SigningPlatformOverrides? /// The microcontroller platform to which your signed code image will be distributed. public let platformId: String? /// The name of the profile that initiated the signing operation. public let profileName: String? /// The IAM principal that requested the signing job. public let requestedBy: String? /// Name of the S3 bucket where the signed code image is saved by code signing. public let signedObject: SignedObject? /// The Amazon Resource Name (ARN) of your code signing certificate. public let signingMaterial: SigningMaterial? /// Map of user-assigned key-value pairs used during signing. These values contain any information that you specified for use in your signing job. public let signingParameters: [String: String]? /// The object that contains the name of your S3 bucket or your raw code. public let source: Source? /// Status of the signing job. public let status: SigningStatus? /// String value that contains the status reason. public let statusReason: String? public init(completedAt: Date? = nil, createdAt: Date? = nil, jobId: String? = nil, overrides: SigningPlatformOverrides? = nil, platformId: String? = nil, profileName: String? = nil, requestedBy: String? = nil, signedObject: SignedObject? = nil, signingMaterial: SigningMaterial? = nil, signingParameters: [String: String]? = nil, source: Source? = nil, status: SigningStatus? = nil, statusReason: String? = nil) { self.completedAt = completedAt self.createdAt = createdAt self.jobId = jobId self.overrides = overrides self.platformId = platformId self.profileName = profileName self.requestedBy = requestedBy self.signedObject = signedObject self.signingMaterial = signingMaterial self.signingParameters = signingParameters self.source = source self.status = status self.statusReason = statusReason } private enum CodingKeys: String, CodingKey { case completedAt case createdAt case jobId case overrides case platformId case profileName case requestedBy case signedObject case signingMaterial case signingParameters case source case status case statusReason } } public struct Destination: AWSEncodableShape { /// The S3Destination object. public let s3: S3Destination? public init(s3: S3Destination? = nil) { self.s3 = s3 } private enum CodingKeys: String, CodingKey { case s3 } } public struct EncryptionAlgorithmOptions: AWSDecodableShape { /// The set of accepted encryption algorithms that are allowed in a code signing job. public let allowedValues: [EncryptionAlgorithm] /// The default encryption algorithm that is used by a code signing job. public let defaultValue: EncryptionAlgorithm public init(allowedValues: [EncryptionAlgorithm], defaultValue: EncryptionAlgorithm) { self.allowedValues = allowedValues self.defaultValue = defaultValue } private enum CodingKeys: String, CodingKey { case allowedValues case defaultValue } } public struct GetSigningPlatformRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "platformId", location: .uri(locationName: "platformId")) ] /// The ID of the target signing platform. public let platformId: String public init(platformId: String) { self.platformId = platformId } private enum CodingKeys: CodingKey {} } public struct GetSigningPlatformResponse: AWSDecodableShape { /// The category type of the target signing platform. public let category: Category? /// The display name of the target signing platform. public let displayName: String? /// The maximum size (in MB) of the payload that can be signed by the target platform. public let maxSizeInMB: Int? /// A list of partner entities that use the target signing platform. public let partner: String? /// The ID of the target signing platform. public let platformId: String? /// A list of configurations applied to the target platform at signing. public let signingConfiguration: SigningConfiguration? /// The format of the target platform's signing image. public let signingImageFormat: SigningImageFormat? /// The validation template that is used by the target signing platform. public let target: String? public init(category: Category? = nil, displayName: String? = nil, maxSizeInMB: Int? = nil, partner: String? = nil, platformId: String? = nil, signingConfiguration: SigningConfiguration? = nil, signingImageFormat: SigningImageFormat? = nil, target: String? = nil) { self.category = category self.displayName = displayName self.maxSizeInMB = maxSizeInMB self.partner = partner self.platformId = platformId self.signingConfiguration = signingConfiguration self.signingImageFormat = signingImageFormat self.target = target } private enum CodingKeys: String, CodingKey { case category case displayName case maxSizeInMB case partner case platformId case signingConfiguration case signingImageFormat case target } } public struct GetSigningProfileRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "profileName", location: .uri(locationName: "profileName")) ] /// The name of the target signing profile. public let profileName: String public init(profileName: String) { self.profileName = profileName } public func validate(name: String) throws { try self.validate(self.profileName, name: "profileName", parent: name, max: 64) try self.validate(self.profileName, name: "profileName", parent: name, min: 2) try self.validate(self.profileName, name: "profileName", parent: name, pattern: "^[a-zA-Z0-9_]{2,}") } private enum CodingKeys: CodingKey {} } public struct GetSigningProfileResponse: AWSDecodableShape { /// The Amazon Resource Name (ARN) for the signing profile. public let arn: String? /// A list of overrides applied by the target signing profile for signing operations. public let overrides: SigningPlatformOverrides? /// The ID of the platform that is used by the target signing profile. public let platformId: String? /// The name of the target signing profile. public let profileName: String? /// The ARN of the certificate that the target profile uses for signing operations. public let signingMaterial: SigningMaterial? /// A map of key-value pairs for signing operations that is attached to the target signing profile. public let signingParameters: [String: String]? /// The status of the target signing profile. public let status: SigningProfileStatus? /// A list of tags associated with the signing profile. public let tags: [String: String]? public init(arn: String? = nil, overrides: SigningPlatformOverrides? = nil, platformId: String? = nil, profileName: String? = nil, signingMaterial: SigningMaterial? = nil, signingParameters: [String: String]? = nil, status: SigningProfileStatus? = nil, tags: [String: String]? = nil) { self.arn = arn self.overrides = overrides self.platformId = platformId self.profileName = profileName self.signingMaterial = signingMaterial self.signingParameters = signingParameters self.status = status self.tags = tags } private enum CodingKeys: String, CodingKey { case arn case overrides case platformId case profileName case signingMaterial case signingParameters case status case tags } } public struct HashAlgorithmOptions: AWSDecodableShape { /// The set of accepted hash algorithms allowed in a code signing job. public let allowedValues: [HashAlgorithm] /// The default hash algorithm that is used in a code signing job. public let defaultValue: HashAlgorithm public init(allowedValues: [HashAlgorithm], defaultValue: HashAlgorithm) { self.allowedValues = allowedValues self.defaultValue = defaultValue } private enum CodingKeys: String, CodingKey { case allowedValues case defaultValue } } public struct ListSigningJobsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "platformId", location: .querystring(locationName: "platformId")), AWSMemberEncoding(label: "requestedBy", location: .querystring(locationName: "requestedBy")), AWSMemberEncoding(label: "status", location: .querystring(locationName: "status")) ] /// Specifies the maximum number of items to return in the response. Use this parameter when paginating results. If additional items exist beyond the number you specify, the nextToken element is set in the response. Use the nextToken value in a subsequent request to retrieve additional items. public let maxResults: Int? /// String for specifying the next set of paginated results to return. After you receive a response with truncated results, use this parameter in a subsequent request. Set it to the value of nextToken from the response that you just received. public let nextToken: String? /// The ID of microcontroller platform that you specified for the distribution of your code image. public let platformId: String? /// The IAM principal that requested the signing job. public let requestedBy: String? /// A status value with which to filter your results. public let status: SigningStatus? public init(maxResults: Int? = nil, nextToken: String? = nil, platformId: String? = nil, requestedBy: String? = nil, status: SigningStatus? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.platformId = platformId self.requestedBy = requestedBy self.status = status } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListSigningJobsResponse: AWSDecodableShape { /// A list of your signing jobs. public let jobs: [SigningJob]? /// String for specifying the next set of paginated results. public let nextToken: String? public init(jobs: [SigningJob]? = nil, nextToken: String? = nil) { self.jobs = jobs self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case jobs case nextToken } } public struct ListSigningPlatformsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "category", location: .querystring(locationName: "category")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "partner", location: .querystring(locationName: "partner")), AWSMemberEncoding(label: "target", location: .querystring(locationName: "target")) ] /// The category type of a signing platform. public let category: String? /// The maximum number of results to be returned by this operation. public let maxResults: Int? /// Value for specifying the next set of paginated results to return. After you receive a response with truncated results, use this parameter in a subsequent request. Set it to the value of nextToken from the response that you just received. public let nextToken: String? /// Any partner entities connected to a signing platform. public let partner: String? /// The validation template that is used by the target signing platform. public let target: String? public init(category: String? = nil, maxResults: Int? = nil, nextToken: String? = nil, partner: String? = nil, target: String? = nil) { self.category = category self.maxResults = maxResults self.nextToken = nextToken self.partner = partner self.target = target } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListSigningPlatformsResponse: AWSDecodableShape { /// Value for specifying the next set of paginated results to return. public let nextToken: String? /// A list of all platforms that match the request parameters. public let platforms: [SigningPlatform]? public init(nextToken: String? = nil, platforms: [SigningPlatform]? = nil) { self.nextToken = nextToken self.platforms = platforms } private enum CodingKeys: String, CodingKey { case nextToken case platforms } } public struct ListSigningProfilesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "includeCanceled", location: .querystring(locationName: "includeCanceled")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// Designates whether to include profiles with the status of CANCELED. public let includeCanceled: Bool? /// The maximum number of profiles to be returned. public let maxResults: Int? /// Value for specifying the next set of paginated results to return. After you receive a response with truncated results, use this parameter in a subsequent request. Set it to the value of nextToken from the response that you just received. public let nextToken: String? public init(includeCanceled: Bool? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.includeCanceled = includeCanceled self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListSigningProfilesResponse: AWSDecodableShape { /// Value for specifying the next set of paginated results to return. public let nextToken: String? /// A list of profiles that are available in the AWS account. This includes profiles with the status of CANCELED if the includeCanceled parameter is set to true. public let profiles: [SigningProfile]? public init(nextToken: String? = nil, profiles: [SigningProfile]? = nil) { self.nextToken = nextToken self.profiles = profiles } private enum CodingKeys: String, CodingKey { case nextToken case profiles } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// The Amazon Resource Name (ARN) for the signing profile. public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { /// A list of tags associated with the signing profile. public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct PutSigningProfileRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "profileName", location: .uri(locationName: "profileName")) ] /// A subfield of platform. This specifies any different configuration options that you want to apply to the chosen platform (such as a different hash-algorithm or signing-algorithm). public let overrides: SigningPlatformOverrides? /// The ID of the signing platform to be created. public let platformId: String /// The name of the signing profile to be created. public let profileName: String /// The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. public let signingMaterial: SigningMaterial /// Map of key-value pairs for signing. These can include any information that you want to use during signing. public let signingParameters: [String: String]? /// Tags to be associated with the signing profile that is being created. public let tags: [String: String]? public init(overrides: SigningPlatformOverrides? = nil, platformId: String, profileName: String, signingMaterial: SigningMaterial, signingParameters: [String: String]? = nil, tags: [String: String]? = nil) { self.overrides = overrides self.platformId = platformId self.profileName = profileName self.signingMaterial = signingMaterial self.signingParameters = signingParameters self.tags = tags } public func validate(name: String) throws { try self.validate(self.profileName, name: "profileName", parent: name, max: 64) try self.validate(self.profileName, name: "profileName", parent: name, min: 2) try self.validate(self.profileName, name: "profileName", parent: name, pattern: "^[a-zA-Z0-9_]{2,}") try self.tags?.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) } } private enum CodingKeys: String, CodingKey { case overrides case platformId case signingMaterial case signingParameters case tags } } public struct PutSigningProfileResponse: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the signing profile created. public let arn: String? public init(arn: String? = nil) { self.arn = arn } private enum CodingKeys: String, CodingKey { case arn } } public struct S3Destination: AWSEncodableShape { /// Name of the S3 bucket. public let bucketName: String? /// An Amazon S3 prefix that you can use to limit responses to those that begin with the specified prefix. public let prefix: String? public init(bucketName: String? = nil, prefix: String? = nil) { self.bucketName = bucketName self.prefix = prefix } private enum CodingKeys: String, CodingKey { case bucketName case prefix } } public struct S3SignedObject: AWSDecodableShape { /// Name of the S3 bucket. public let bucketName: String? /// Key name that uniquely identifies a signed code image in your bucket. public let key: String? public init(bucketName: String? = nil, key: String? = nil) { self.bucketName = bucketName self.key = key } private enum CodingKeys: String, CodingKey { case bucketName case key } } public struct S3Source: AWSEncodableShape & AWSDecodableShape { /// Name of the S3 bucket. public let bucketName: String /// Key name of the bucket object that contains your unsigned code. public let key: String /// Version of your source image in your version enabled S3 bucket. public let version: String public init(bucketName: String, key: String, version: String) { self.bucketName = bucketName self.key = key self.version = version } private enum CodingKeys: String, CodingKey { case bucketName case key case version } } public struct SignedObject: AWSDecodableShape { /// The S3SignedObject. public let s3: S3SignedObject? public init(s3: S3SignedObject? = nil) { self.s3 = s3 } private enum CodingKeys: String, CodingKey { case s3 } } public struct SigningConfiguration: AWSDecodableShape { /// The encryption algorithm options that are available for a code signing job. public let encryptionAlgorithmOptions: EncryptionAlgorithmOptions /// The hash algorithm options that are available for a code signing job. public let hashAlgorithmOptions: HashAlgorithmOptions public init(encryptionAlgorithmOptions: EncryptionAlgorithmOptions, hashAlgorithmOptions: HashAlgorithmOptions) { self.encryptionAlgorithmOptions = encryptionAlgorithmOptions self.hashAlgorithmOptions = hashAlgorithmOptions } private enum CodingKeys: String, CodingKey { case encryptionAlgorithmOptions case hashAlgorithmOptions } } public struct SigningConfigurationOverrides: AWSEncodableShape & AWSDecodableShape { /// A specified override of the default encryption algorithm that is used in a code signing job. public let encryptionAlgorithm: EncryptionAlgorithm? /// A specified override of the default hash algorithm that is used in a code signing job. public let hashAlgorithm: HashAlgorithm? public init(encryptionAlgorithm: EncryptionAlgorithm? = nil, hashAlgorithm: HashAlgorithm? = nil) { self.encryptionAlgorithm = encryptionAlgorithm self.hashAlgorithm = hashAlgorithm } private enum CodingKeys: String, CodingKey { case encryptionAlgorithm case hashAlgorithm } } public struct SigningImageFormat: AWSDecodableShape { /// The default format of a code signing image. public let defaultFormat: ImageFormat /// The supported formats of a code signing image. public let supportedFormats: [ImageFormat] public init(defaultFormat: ImageFormat, supportedFormats: [ImageFormat]) { self.defaultFormat = defaultFormat self.supportedFormats = supportedFormats } private enum CodingKeys: String, CodingKey { case defaultFormat case supportedFormats } } public struct SigningJob: AWSDecodableShape { /// The date and time that the signing job was created. public let createdAt: Date? /// The ID of the signing job. public let jobId: String? /// A SignedObject structure that contains information about a signing job's signed code image. public let signedObject: SignedObject? /// A SigningMaterial object that contains the Amazon Resource Name (ARN) of the certificate used for the signing job. public let signingMaterial: SigningMaterial? /// A Source that contains information about a signing job's code image source. public let source: Source? /// The status of the signing job. public let status: SigningStatus? public init(createdAt: Date? = nil, jobId: String? = nil, signedObject: SignedObject? = nil, signingMaterial: SigningMaterial? = nil, source: Source? = nil, status: SigningStatus? = nil) { self.createdAt = createdAt self.jobId = jobId self.signedObject = signedObject self.signingMaterial = signingMaterial self.source = source self.status = status } private enum CodingKeys: String, CodingKey { case createdAt case jobId case signedObject case signingMaterial case source case status } } public struct SigningMaterial: AWSEncodableShape & AWSDecodableShape { /// The Amazon Resource Name (ARN) of the certificates that is used to sign your code. public let certificateArn: String public init(certificateArn: String) { self.certificateArn = certificateArn } private enum CodingKeys: String, CodingKey { case certificateArn } } public struct SigningPlatform: AWSDecodableShape { /// The category of a code signing platform. public let category: Category? /// The display name of a code signing platform. public let displayName: String? /// The maximum size (in MB) of code that can be signed by a code signing platform. public let maxSizeInMB: Int? /// Any partner entities linked to a code signing platform. public let partner: String? /// The ID of a code signing; platform. public let platformId: String? /// The configuration of a code signing platform. This includes the designated hash algorithm and encryption algorithm of a signing platform. public let signingConfiguration: SigningConfiguration? public let signingImageFormat: SigningImageFormat? /// The types of targets that can be signed by a code signing platform. public let target: String? public init(category: Category? = nil, displayName: String? = nil, maxSizeInMB: Int? = nil, partner: String? = nil, platformId: String? = nil, signingConfiguration: SigningConfiguration? = nil, signingImageFormat: SigningImageFormat? = nil, target: String? = nil) { self.category = category self.displayName = displayName self.maxSizeInMB = maxSizeInMB self.partner = partner self.platformId = platformId self.signingConfiguration = signingConfiguration self.signingImageFormat = signingImageFormat self.target = target } private enum CodingKeys: String, CodingKey { case category case displayName case maxSizeInMB case partner case platformId case signingConfiguration case signingImageFormat case target } } public struct SigningPlatformOverrides: AWSEncodableShape & AWSDecodableShape { /// A signing configuration that overrides the default encryption or hash algorithm of a signing job. public let signingConfiguration: SigningConfigurationOverrides? /// A signed image is a JSON object. When overriding the default signing platform configuration, a customer can select either of two signing formats, JSONEmbedded or JSONDetached. (A third format value, JSON, is reserved for future use.) With JSONEmbedded, the signing image has the payload embedded in it. With JSONDetached, the payload is not be embedded in the signing image. public let signingImageFormat: ImageFormat? public init(signingConfiguration: SigningConfigurationOverrides? = nil, signingImageFormat: ImageFormat? = nil) { self.signingConfiguration = signingConfiguration self.signingImageFormat = signingImageFormat } private enum CodingKeys: String, CodingKey { case signingConfiguration case signingImageFormat } } public struct SigningProfile: AWSDecodableShape { /// The Amazon Resource Name (ARN) for the signing profile. public let arn: String? /// The ID of a platform that is available for use by a signing profile. public let platformId: String? /// The name of the signing profile. public let profileName: String? /// The ACM certificate that is available for use by a signing profile. public let signingMaterial: SigningMaterial? /// The parameters that are available for use by a code signing user. public let signingParameters: [String: String]? /// The status of a code signing profile. public let status: SigningProfileStatus? /// A list of tags associated with the signing profile. public let tags: [String: String]? public init(arn: String? = nil, platformId: String? = nil, profileName: String? = nil, signingMaterial: SigningMaterial? = nil, signingParameters: [String: String]? = nil, status: SigningProfileStatus? = nil, tags: [String: String]? = nil) { self.arn = arn self.platformId = platformId self.profileName = profileName self.signingMaterial = signingMaterial self.signingParameters = signingParameters self.status = status self.tags = tags } private enum CodingKeys: String, CodingKey { case arn case platformId case profileName case signingMaterial case signingParameters case status case tags } } public struct Source: AWSEncodableShape & AWSDecodableShape { /// The S3Source object. public let s3: S3Source? public init(s3: S3Source? = nil) { self.s3 = s3 } private enum CodingKeys: String, CodingKey { case s3 } } public struct StartSigningJobRequest: AWSEncodableShape { /// String that identifies the signing request. All calls after the first that use this token return the same response as the first call. public let clientRequestToken: String /// The S3 bucket in which to save your signed object. The destination contains the name of your bucket and an optional prefix. public let destination: Destination /// The name of the signing profile. public let profileName: String? /// The S3 bucket that contains the object to sign or a BLOB that contains your raw code. public let source: Source public init(clientRequestToken: String = StartSigningJobRequest.idempotencyToken(), destination: Destination, profileName: String? = nil, source: Source) { self.clientRequestToken = clientRequestToken self.destination = destination self.profileName = profileName self.source = source } public func validate(name: String) throws { try self.validate(self.profileName, name: "profileName", parent: name, max: 64) try self.validate(self.profileName, name: "profileName", parent: name, min: 2) try self.validate(self.profileName, name: "profileName", parent: name, pattern: "^[a-zA-Z0-9_]{2,}") } private enum CodingKeys: String, CodingKey { case clientRequestToken case destination case profileName case source } } public struct StartSigningJobResponse: AWSDecodableShape { /// The ID of your signing job. public let jobId: String? public init(jobId: String? = nil) { self.jobId = jobId } private enum CodingKeys: String, CodingKey { case jobId } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// The Amazon Resource Name (ARN) for the signing profile. public let resourceArn: String /// One or more tags to be associated with the signing profile. public let tags: [String: String] public init(resourceArn: String, tags: [String: String]) { self.resourceArn = resourceArn self.tags = tags } public func validate(name: String) throws { try self.tags.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) } } private enum CodingKeys: String, CodingKey { case tags } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] /// The Amazon Resource Name (ARN) for the signing profile. public let resourceArn: String /// A list of tag keys to be removed from the signing profile. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } public func validate(name: String) throws { try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) try validate($0, name: "tagKeys[]", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$") } try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 200) try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } }
apache-2.0
5e9a8c5be0931742980833c530741c84
41.060317
422
0.636602
5.211354
false
false
false
false
joshpar/Lyrebird
LyrebirdSynth/Lyrebird/LyrebirdEngine.swift
1
3142
// // LyrebirdEngine.swift // Lyrebird // // Created by Joshua Parmenter on 5/1/16. // Copyright © 2016 Op133Studios. All rights reserved. // protocol LyrebirdEngineDelegate { func synthEngineHasStarted(engine: LyrebirdEngine) func synthEngineHasStopped(engine: LyrebirdEngine) } typealias LyrebirdResultOutputBlock = (_ finished: Bool) -> Void class LyrebirdEngine { // initial default engine. This should act as a singleton however! Every init of LyrebirdEngine will overwrite this instance. static var engine: LyrebirdEngine = LyrebirdEngine() var delegate: LyrebirdEngineDelegate? var isRunning : Bool = false var numberOfAudioChannels : LyrebirdInt = 128 var numberOfControlChannels : LyrebirdInt = 2048 var blockSize : LyrebirdInt = 1024 { didSet { if(self.blockSize > 0){ self.iBlockSize = 1.0 / LyrebirdFloat(self.blockSize) } } } var sampleRate : LyrebirdFloat = 44100.0 { didSet { if(self.sampleRate > 0.0){ self.iSampleRate = 1.0 / sampleRate } } } var iBlockSize : LyrebirdFloat = 0.015625 var iSampleRate : LyrebirdFloat = 0.000022676 var audioBlock : [LyrebirdAudioChannel] = [] var controlBlock : [LyrebirdControlChannel] = [] var tree : LyrebirdNodeTree = LyrebirdNodeTree() // need to func start(){ if(!isRunning){ // allocate our memory for idx: Int in 0 ..< numberOfAudioChannels { let channel: LyrebirdAudioChannel = LyrebirdAudioChannel(index: idx, blockSize: blockSize) self.audioBlock.append(channel) } for idx: Int in 0 ..< numberOfControlChannels-1 { let channel: LyrebirdControlChannel = LyrebirdControlChannel(index: idx, iBlockSize: iBlockSize) self.controlBlock.append(channel) } LyrebirdUGenInterface.initInterface() isRunning = true self.delegate?.synthEngineHasStarted(engine: self) } } func stop(){ if(isRunning){ isRunning = false self.delegate?.synthEngineHasStopped(engine: self) } } func clearAll(){ tree = LyrebirdNodeTree() } func processWithInputChannels(inputChannels: [LyrebirdAudioChannel]){ for audioChannel: LyrebirdAudioChannel in self.audioBlock { audioChannel.zeroValues() } // add input channels to the audio block do { try tree.processTree { (nodeTree, finished) in // write to outputs } } catch LyrebirdTreeError.alreadyProcessing { print("Already Processing") } catch _ { print("Throw on some Bootsy Collins, because something funky happened.") } } func runTests(){ } }
artistic-2.0
0c21aae5588bd3ce9f17670ad2aa0c9a
32.414894
129
0.571792
4.506456
false
false
false
false
muhasturk/smart-citizen-ios
Smart Citizen/Controller/Presenter/ReportVC.swift
1
13069
/** * Copyright (c) 2016 Mustafa Hastürk * * 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 Alamofire import SwiftyJSON import AWSS3 class ReportVC: AppVC, UINavigationControllerDelegate, UIImagePickerControllerDelegate { // MARK: - IBOutlet @IBOutlet weak var choosenImage: UIImageView! @IBOutlet weak var descriptionField: UITextView! @IBOutlet weak var categoryButton: UIButton! @IBOutlet weak var titleField: UITextField! @IBOutlet weak var mediaButton: UIButton! var categoryId: Int? var categoryTitle: String? { didSet { self.categoryButton.setTitle(categoryTitle, for: UIControl.State()) } } var categorySelected = false fileprivate var imagePicked = false { willSet { if newValue { self.mediaButton.setTitle("Resmi Değiştir", for: UIControl.State()) } else { self.mediaButton.setTitle("Resim Ekle", for: UIControl.State()) } } } // MARK: Properties fileprivate let requestBaseURL = AppAPI.serviceDomain + AppAPI.reportServiceURL fileprivate let imagePicker = UIImagePickerController() fileprivate let AWSS3BucketName = "smart-citizen" // MARK: - LC override func viewDidLoad() { super.viewDidLoad() self.view.dodo.style.bar.hideOnTap = true self.view.dodo.topAnchor = view.safeAreaLayoutGuide.topAnchor super.locationManager.startUpdatingLocation() self.configureImagePickerController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(_ animated: Bool) { super.addKeyboardObserver() } override func viewDidDisappear(_ animated: Bool) { self.removeKeyboardObserver() super.locationManager.stopUpdatingLocation() } // MARK: - Action @IBAction func sendReportAction(_ sender: AnyObject) { if self.isAllFieldCompleted(){ self.makeDialogForSend() } else { super.createAlertController(title: AppAlertMessages.missingFieldTitle, message: AppAlertMessages.reportMissingFieldMessage, controllerStyle: .alert, actionStyle: .default) } } fileprivate func makeDialogForSend() { let ac = UIAlertController(title: "Raporu Onaylayın", message: "Raporunuz sistemimize yüklenecektir.\nOnaylıyor musunuz?", preferredStyle: .alert) let okAction = UIAlertAction(title: "Yükle", style: .default) { (UIAlertAction) in self.view.dodo.info("Rapor yükleniyor...") self.uploadImageForAWSS3() } let cancelAction = UIAlertAction(title: "İptal Et", style: .cancel, handler: nil) ac.addAction(okAction) ac.addAction(cancelAction) self.present(ac, animated: true, completion: nil) } fileprivate func isAllFieldCompleted() -> Bool { return self.imagePicked && self.titleField.text!.isNotEmpty && self.descriptionField.text.isNotEmpty && self.categorySelected } @IBAction func clearFieldAction(_ sender: AnyObject) { self.clearFields() } @IBAction func selectCategory(_ sender: AnyObject) { self.performSegue(withIdentifier: AppSegues.pushReportCategory, sender: sender) } func clearFields() { self.choosenImage.image = UIImage(named: "Placeholder") self.categorySelected = false self.titleField.text = "" self.descriptionField.text = "" self.categoryButton.setTitle("Kategori", for: UIControl.State()) } // MARK: - Networking func uploadImageForAWSS3() { let ext = "jpg" let t: UIImage = self.choosenImage.image! let pickedImage = t.scaleWithCGSize(CGSize(width: 500, height: 500)) let temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let imageURL: URL = temporaryDirectoryURL.appendingPathComponent("pickedImage.png") let pathString = imageURL.absoluteString // has file:// prefix let onlyPathString = pathString.trimmingCharacters(in: CharacterSet(charactersIn: "file://")) let imageData: Data = pickedImage.jpegData(compressionQuality: 0.7)! try? imageData.write(to: URL(fileURLWithPath: onlyPathString), options: [.atomic]) // change onlypathstring let uploadRequest = AWSS3TransferManagerUploadRequest() uploadRequest?.body = imageURL uploadRequest?.key = ProcessInfo.processInfo.globallyUniqueString + "." + ext uploadRequest?.bucket = self.AWSS3BucketName uploadRequest?.contentType = "image/" + ext uploadRequest?.acl = .publicRead AWSS3TransferManager.init().upload(uploadRequest!).continueWith(block: { (task) -> Any? in if let error = task.error { print("Upload failed ❌ (\(error))") } guard task.result != nil else { self.view.dodo.error("Seçtiğiniz resim AWS servise yüklenemedi.") self.createAlertController(title: "Yükleme Başarısız", message: "Seçtiğiniz resim AWS servise yüklenemedi.", controllerStyle: .alert, actionStyle: .destructive) print("Seçtiğiniz resim AWS servise yüklenemedi.") return "" } let uploadedImageURL = "https://s3-us-west-2.amazonaws.com/\(self.AWSS3BucketName)/\(uploadRequest!.key!)" print(uploadedImageURL) let params = self.configureReportNetworkingParameters(imageUrl: uploadedImageURL) self.reportNetworking(networkingParameters: params as [String : AnyObject]) return "" }) } fileprivate func configureReportNetworkingParameters(imageUrl url: String) -> [String: Any] { var latitude: Double? var longitude: Double? if let location = super.locationManager.location?.coordinate { latitude = location.latitude longitude = location.longitude } let params: [String: Any] = [ "email": AppReadOnlyUser.email as Any, "password": AppReadOnlyUser.password as Any, "latitude": latitude ?? 40.984312, "longitude": longitude ?? 28.753676, "title": self.titleField.text!, "description": self.descriptionField.text!, "categoryId": categoryId!, "imageUrl": url ] return params } // MARK: - Image Picker fileprivate func configureImagePickerController() { self.imagePicker.delegate = self } @IBAction func chooseMediaAction(_ sender: AnyObject) { let actionSheet = UIAlertController(title: "Medya Kaynağı", message: "Medya eklemek için bir kaynak seçiniz.", preferredStyle: .actionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .default) { (UIAlertAction) in self.pickFromCamera() } let photosAction = UIAlertAction(title: "Photos", style: .default) { (UIAlertAction) in self.pickFromPhotos() } let momentsAction = UIAlertAction(title: "Momemts", style: .default) { (UIAlertAction) in self.pickFromMoments() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) actionSheet.addAction(momentsAction) actionSheet.addAction(photosAction) actionSheet.addAction(cameraAction) actionSheet.addAction(cancelAction) self.present(actionSheet, animated: true, completion: nil) } fileprivate func pickFromCamera() { if UIImagePickerController.isSourceTypeAvailable(.camera) { self.imagePicker.sourceType = .camera self.imagePicker.modalPresentationStyle = .fullScreen self.present(self.imagePicker, animated: true, completion: nil) } else { self.createAlertController(title: AppDebugMessages.cameraDeviceNotAvailableTitle, message: AppDebugMessages.cameraDeviceNotAvailableMessage, controllerStyle: .alert, actionStyle: .destructive) print(AppDebugMessages.cameraDeviceNotAvailable) } } fileprivate func pickFromPhotos() { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { self.imagePicker.sourceType = .photoLibrary self.imagePicker.modalPresentationStyle = .fullScreen self.present(self.imagePicker, animated: true, completion: nil) } else { self.createAlertController(title: AppDebugMessages.photosNotAvailableTitle, message: AppDebugMessages.photosNotAvailableMessage, controllerStyle: .alert, actionStyle: .destructive) print(AppDebugMessages.photosNotAvailable) } } fileprivate func pickFromMoments() { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) { self.imagePicker.sourceType = .savedPhotosAlbum self.imagePicker.modalPresentationStyle = .fullScreen self.present(self.imagePicker, animated: true, completion: nil) } else { self.createAlertController(title: AppDebugMessages.momentsNotAvailableTitle, message: AppDebugMessages.momentsNotAvailableMessage, controllerStyle: .alert, actionStyle: .destructive) print(AppDebugMessages.momentsNotAvailable) } } // MARK: - Image Picker Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) if let pickedImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage { self.choosenImage.image = pickedImage self.imagePicked = true } self.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true, completion: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } // MARK: Unwind @IBAction func unwindToReportScene(_ segue: UIStoryboardSegue) { if segue.identifier == "saveReportCategory"{ if let sourceVC = segue.source as? CategoryVC { self.categorySelected = true self.categoryTitle = sourceVC.selectedCategoryTitle self.categoryId = sourceVC.selectedCategoryId } } } } // MARK: - Networking extension ReportVC { fileprivate func reportNetworking(networkingParameters params: [String: AnyObject]) { Alamofire.request(self.requestBaseURL, method: .post, parameters: params, encoding: JSONEncoding.default) .responseJSON { response in self.stopIndicator() switch response.result { case .success(let value): print(AppDebugMessages.serviceConnectionReportIsOk, self.requestBaseURL, separator: "\n") let json = JSON(value) let serviceCode = json["serviceCode"].intValue self.view.dodo.style.bar.hideAfterDelaySeconds = 3 if serviceCode == 0 { self.reportNetworkingSuccessful() } else { let exception = json["exception"] self.reportNetworkingUnsuccessful(exception) } case .failure(let error): self.createAlertController(title: AppAlertMessages.networkingFailuredTitle, message: AppAlertMessages.networkingFailuredMessage, controllerStyle: .alert, actionStyle: .destructive) debugPrint(error) } } } fileprivate func reportNetworkingSuccessful() { self.view.dodo.success("Raporunuz sistemimize kaydedildi.") super.createAlertController(title: "Rapor Gönderildi", message: "Raporunuz sistemimize kaydedildi.", controllerStyle: .alert, actionStyle: .default) self.clearFields() } fileprivate func reportNetworkingUnsuccessful(_ exception: JSON) { self.view.dodo.error("Rapor yüklemesi başarısız oldu.") } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
mit
677de3b7478f167ebf6e0bc046ae7a13
36.785507
198
0.718088
4.543743
false
false
false
false
hucool/XMImagePicker
Pod/Classes/ListViewController.swift
1
3754
// // ViewController.swift // XMImagePicker // // Created by tiger on 2017/2/8. // Copyright © 2017年 xinma. All rights reserved. // import UIKit import Photos class ListViewController: UIViewController { /// all albums fileprivate var albumInfos: [Album] = [] // MARK:- UIView fileprivate lazy var iBackButton: UIBarButtonItem = { self.iBackButton = UIBarButtonItem() self.iBackButton.title = "返回" return self.iBackButton }() fileprivate lazy var iAlbumTableView: UITableView = { self.iAlbumTableView = UITableView() self.iAlbumTableView.delegate = self self.iAlbumTableView.dataSource = self self.iAlbumTableView.register(AlbumCell.self) self.iAlbumTableView.frame = self.view.bounds self.iAlbumTableView.tableFooterView = UIView() return self.iAlbumTableView }() // MARK:- Lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // navigationItem.backBarButtonItem = iBackButton // setup view view.addSubview(iAlbumTableView) loadCameraRoll() loadAllAlbums() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = true } fileprivate func loadCameraRoll() { let info = PhotoMannager.loadCameraRoll() pushGridViewController(albumInfo: info, animated: false) } fileprivate func pushGridViewController(albumInfo: Album, animated: Bool) { DispatchQueue.main.async(execute: { let vc = GridViewController() vc.albumInfo = albumInfo self.navigationController?.pushViewController(vc, animated: animated) // set navigationView self.title = "照片" self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(self.cancleAction)) }) } func cancleAction() { dismiss(animated: true, completion: nil) } fileprivate func loadAllAlbums() { DispatchQueue.global().async { self.albumInfos = PhotoMannager.laodAlbumList() DispatchQueue.main.async(execute: { self.iAlbumTableView.reloadData() }) } } } // MARK:- UITableView extension ListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albumInfos.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let info = albumInfos[indexPath.row] pushGridViewController(albumInfo: info, animated: true) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as AlbumCell cell.albumInfo = albumInfos[indexPath.row] return cell } } // MARK:- AssetSelectDelegate protocol PickerPhotoDelegate: class { func didEndPickingPhotos(_ photos: [Photo], photoIdentifiers identifier: [String]) }
mit
21db38244b42d9e76195ea4a5b3a9369
27.984496
101
0.607382
5.341429
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Repositories/Implementations/ContentRepository.swift
1
2305
// // ContentRepository.swift // Habitica // // Created by Phillip Thelen on 12.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Database import Habitica_Models import Habitica_API_Client import ReactiveSwift class ContentRepository: BaseRepository<ContentLocalRepository> { func retrieveContent(force: Bool = false) -> Signal<ContentProtocol?, Never> { return RetrieveContentCall(language: LanguageHandler.getAppLanguage().code, forceLoading: force).objectSignal.on(value: {[weak self] content in if let content = content { self?.localRepository.save(content) } }) } func retrieveWorldState() -> Signal<WorldStateProtocol?, Never> { return RetrieveWorldStateCall().objectSignal.on(value: {[weak self] worldState in if let worldState = worldState { self?.localRepository.save(worldState) let defaults = UserDefaults.standard defaults.set(worldState.currentEventKey, forKey: "currentEvent") defaults.set(worldState.currentEventStartDate, forKey: "currentEventStartDate") defaults.set(worldState.currentEventEndDate, forKey: "currentEventEndDate") } }) } func getFAQEntries(search searchText: String? = nil) -> SignalProducer<ReactiveResults<[FAQEntryProtocol]>, ReactiveSwiftRealmError> { return localRepository.getFAQEntries(search: searchText) } func getFAQEntry(index: Int) -> SignalProducer<FAQEntryProtocol, ReactiveSwiftRealmError> { return localRepository.getFAQEntry(index: index) } func getSkills(habitClass: String) -> SignalProducer<ReactiveResults<[SkillProtocol]>, ReactiveSwiftRealmError> { return localRepository.getSkills(habitClass: habitClass) } func retrieveHallOfContributors() -> Signal<[MemberProtocol]?, Never> { return RetrieveHallOfContributorsCall().arraySignal } func retrieveHallOfPatrons() -> Signal<[MemberProtocol]?, Never> { return RetrieveHallOfPatronsCall().arraySignal } func clearDatabase() { localRepository.clearDatabase() ImageManager.clearImageCache() } }
gpl-3.0
dbb16f550d94945e606d5593e8dbc0b1
36.16129
151
0.68099
4.8
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureOpenBanking/Sources/FeatureOpenBankingUI/Resources/Media.swift
1
861
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import UIComponentsKit private class BundleFinder {} extension Bundle { public static let openBanking = Bundle.find( "FeatureOpenBanking_FeatureOpenBankingUI.bundle", "Blockchain_FeatureOpenBankingUI.bundle", in: BundleFinder.self ) } extension Media { static let inherited: Media = .empty static let blockchainLogo: Media = .image(named: "blockchain", in: .openBanking) static let bankIcon: Media = .image(named: "bank", in: .openBanking) static let success: Media = .image(named: "success", in: .openBanking) static let error: Media = .image(named: "warning", in: .openBanking) static let clock: Media = .image(named: "clock", in: .openBanking) static let cross: Media = .image(named: "cross", in: .openBanking) }
lgpl-3.0
969c13c27a9d80bdf779053f9cb31c18
36.391304
84
0.702326
3.873874
false
false
false
false
kohtenko/KOSocialOAuth
Pod/Classes/KOSocialOAuthViewContorller.swift
1
8241
// // KOSocialOAuthViewContorller.swift // KOSocialOAuth_Example // // Created by okohtenko on 16/03/15. // Copyright (c) 2015 kohtenko. All rights reserved. // import UIKit protocol KOSocialOAuthViewControllerDelegate: class{ func instagramLoginFinishedWithToken(accessToken: String?) func linkedInLoginFinishedWithToken(accessToken: String?) func vkLoginFinishedWithToken(accessToken: String?) } enum KOSocialOAuthService: Int{ case VK case Instagram case LinkedIn case Facebook case Twitter } class KOSocialOAuthViewContorller: UIViewController, UIWebViewDelegate { weak var delegate: KOSocialOAuthViewControllerDelegate? var service: KOSocialOAuthService = .VK /// Go to http://vk.com/dev and create app. Set appId to this property var vkClientID: String? /// Go to http://vk.com/dev/permissions and decide which permission do need. Set string of coma separated values to this property. (Example: "offline,friends") var vkScope: String? /// Go to https://instagram.com/developer and create app. Set ClientID to this property var instagramClientID: String? /// Go to https://instagram.com/developer and create app. Set ClientID to this property var instagramClientSecret: String? /// Go to https://instagram.com/developer and create app. Set RedirectURL to this property (You can use any URL in app setting) var instagramRedirectURL: String? /// Go to https://developer.linkedin.com/docs/oauth2 and create app. Set Consumer Key / API Key to this property var linkedInClientID: String? /// Go to https://developer.linkedin.com/docs/oauth2 and create app. Set Consumer Secret to this property var linkedInClientSecret: String? /// Go to https://developer.linkedin.com/docs/oauth2 and create app. Set RedirectURL to this property (You can use any URL in app setting OAuth 2.0 Redirect URLs) var linkedInRedirectURL: String? /// Setup a unique string value of your choice that is hard to guess. Used to prevent CSRF. e.g. state=DCEeFWf45A53sdfKef424 var linkedInState: String? @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() var urlString = "" switch service { case .VK: if vkClientID != nil && vkScope != nil { urlString = "https://oauth.vk.com/authorize?client_id=\(vkClientID!)&scope=\(vkScope!)&redirect_uri=blank.html&response_type=token" } case .Instagram: if instagramClientID != nil && instagramRedirectURL != nil { urlString = "https://api.instagram.com/oauth/authorize/?client_id=\(instagramClientID!)&redirect_uri=\(instagramRedirectURL!)&response_type=code" } case .LinkedIn: if linkedInClientID != nil && linkedInState != nil && linkedInRedirectURL != nil{ urlString = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=\(linkedInClientID!)&state=\(linkedInState!)&redirect_uri=\(linkedInRedirectURL!)" } default: break } if let url = NSURL(string: urlString) { webView.loadRequest(NSURLRequest(URL: url)) } } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.URL?.absoluteString{ switch service { case .VK: if let range = url.rangeOfString("#access_token="){ if let endRange = url.rangeOfString("&") { let accessToken = url.substringWithRange(Range(start:range.startIndex, end:endRange.endIndex)) delegate?.vkLoginFinishedWithToken(accessToken) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()) { () -> Void in self.dismissViewControllerAnimated(true, completion: nil) } return false } } case .Instagram: if let code = getCodeFromUrl(url){ let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: NSURL(string: "https://api.instagram.com/oauth/access_token")!) request.HTTPMethod = "POST" let postString = "client_id=\(instagramClientID!)&client_secret=\(instagramClientSecret!)&grant_type=authorization_code&redirect_uri=\(instagramRedirectURL!)&code=\(code)" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let dict = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil) as? NSDictionary { if let access_token = dict["access_token"] as? String{ self.delegate?.instagramLoginFinishedWithToken(access_token) self.dismissViewControllerAnimated(true, completion: nil) }else{ self.cancelPressed() } }else{ self.cancelPressed() } }).resume() return false } case .LinkedIn: if let code = getCodeFromUrl(url){ let urlLinkedIn = "https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=%@&redirect_uri=\(linkedInRedirectURL!)&client_id=\(linkedInClientID!)&client_secret=\(linkedInClientSecret!)" NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlLinkedIn)!, completionHandler: { (data, response, error) -> Void in if let dict = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil) as? NSDictionary{ if let access_token = dict["access_token"] as? String{ self.delegate?.linkedInLoginFinishedWithToken(access_token) self.dismissViewControllerAnimated(true, completion: nil) } else{ self.cancelPressed() } }else{ self.cancelPressed() } }).resume() return false } default: break } } return true } func getCodeFromUrl(url: String) -> String?{ if let range = url.rangeOfString("?code="){ let endRange = url.rangeOfString("&") let startLocation = range.endIndex let endLocation = endRange == nil ? url.endIndex : endRange!.startIndex let rangeOfCode = Range(start: startLocation, end: endLocation) let code = url.substringWithRange(Range(start:startLocation, end:endLocation)) return code } return nil } @IBAction func cancelPressed(){ switch service { case .Instagram: delegate?.instagramLoginFinishedWithToken(nil) case .LinkedIn: delegate?.linkedInLoginFinishedWithToken(nil) case .VK: delegate?.vkLoginFinishedWithToken(nil) default: break } dismissViewControllerAnimated(true, completion: nil) } }
mit
a7a33f3994950c408338032da6f1c940
41.927083
232
0.569712
5.340894
false
false
false
false
Ilhasoft/ISParseBind
ISParseBindSample/ViewController.swift
1
3134
// // ViewController.swift // ParsePersistence // // Created by Daniel Amaral on 13/03/17. // Copyright © 2017 Ilhasoft. All rights reserved. // import UIKit import ISParseBind import MBProgressHUD class ViewController: UIViewController { @IBOutlet var parseBindView:ISParseBindView! @IBOutlet var lbFabricationYear:UILabel! @IBOutlet var slider:ISParseBindSlider! var hud:MBProgressHUD? override func viewDidLoad() { super.viewDidLoad() parseBindView.delegate = self } func validate() { let filtered = self.parseBindView.fields.filter {($0 is UITextField && ($0 as! ISParseBindable).required == true && ($0 as! UITextField).text!.isEmpty)} if !filtered.isEmpty { shake(component: filtered.first as! UIView) }else { save() } } func shake(component:UIView) { let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = 0.6 animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0] component.layer.add(animation, forKey: "shake") } func save() { hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud?.label.text = "Saving..." self.parseBindView.save() } @IBAction func btSaveTapped() { validate() } @IBAction func sliderChanged(slider:UISlider) { self.lbFabricationYear.text = "\(Int(slider.value))" } } extension ViewController : ISParseBindViewDelegate { func didFetch(view: ISParseBindView, error: Error?) { } func willSave(view: ISParseBindView, object: PFObject) -> PFObject? { return object } func didSave(view: ISParseBindView, object: PFObject, isMainEntity: Bool, error: Error?) { if let error = error { print(error.localizedDescription) DispatchQueue.main.async { self.hud?.hide(animated: true) } }else { if isMainEntity == true { DispatchQueue.main.async { self.hud?.label.text = "Main Entity did save \(object.parseClassName)" self.hud?.hide(animated: true, afterDelay: 2) } }else { DispatchQueue.main.async { self.hud!.label.text = "Saving \(object.parseClassName)" } } } } func willSet(component: Any, value: Any) -> Any? { if let component = component as? UISlider, component == slider { return Int(value as! Float) } return value } func didSet(component: Any, value: Any) { } func willFill(component: Any, value: Any) -> Any? { return value } func didFill(component: Any, value: Any) { } }
mit
204b0f7fc873d008095063e47c15197f
27.481818
96
0.557293
4.456615
false
false
false
false
smartystreets/smartystreets-ios-sdk
Sources/SmartyStreets/USAutocomplete/USAutocompleteClient.swift
1
3038
import Foundation public class USAutocompleteClient: NSObject { // It is recommended to instantiate this class using SSClientBuilder var sender:SmartySender var serializer:SmartySerializer public init(sender:Any, serializer:SmartySerializer) { self.sender = sender as! SmartySender self.serializer = serializer } @objc public func sendLookup(lookup: UnsafeMutablePointer<USAutocompleteLookup>, error: UnsafeMutablePointer<NSError?>) -> Bool { // Sends a Lookup object to the US Autocomplete API and stores the result in the Lookup's result field. if let prefix = lookup.pointee.prefix { if prefix.count == 0 { let details = [NSLocalizedDescriptionKey:"sendLookup must be passed a Lookup with the prefix field set."] error.pointee = NSError(domain: SmartyErrors().SSErrorDomain, code: SmartyErrors.SSErrors.FieldNotSetError.rawValue, userInfo: details) return false } let request = buildRequest(lookup:lookup.pointee) let response = self.sender.sendRequest(request: request, error: &error.pointee) if error.pointee != nil { return false } let result:USAutocompleteResult = self.serializer.Deserialize(payload: response?.payload, error: &error.pointee) as! USAutocompleteResult // Naming of parameters to allow JSON deserialization if error.pointee != nil { return false } lookup.pointee.result = result return true } else { return false } } func buildRequest(lookup:USAutocompleteLookup) -> SmartyRequest { let request = SmartyRequest() request.setValue(value: lookup.prefix ?? "", HTTPParameterField: "prefix") request.setValue(value: lookup.getMaxSuggestionsStringIfSet(), HTTPParameterField: "suggestions") request.setValue(value: buildFilterString(list: lookup.cityFilter ?? [String]()), HTTPParameterField: "city_filter") request.setValue(value: buildFilterString(list: lookup.stateFilter ?? [String]()), HTTPParameterField: "state_filter") request.setValue(value: buildFilterString(list: lookup.prefer ?? [String]()), HTTPParameterField: "prefer") request.setValue(value: lookup.getPreferRatioStringIfSet(), HTTPParameterField: "prefer_ratio") if lookup.geolocateType!.name != "none" { request.setValue(value: "true", HTTPParameterField: "geolocate") request.setValue(value: lookup.geolocateType!.name, HTTPParameterField: "geolocate_precision") } else { request.setValue(value: "false", HTTPParameterField: "geolocate") } return request } func buildFilterString(list:[String]) -> String { if list.count == 0 { return String() } return list.joined(separator: ",") } }
apache-2.0
8a3a11c7a88e7cb8b3ceb333f434b08b
44.343284
151
0.641211
4.931818
false
false
false
false
apple/swift
test/TypeRoundTrip/Inputs/testcases/generics.swift
9
2095
import RoundTrip protocol First { associatedtype Assoc : First // Just to confuse things -- a method with the same name as an // associated type func Assoc(_: Int) -> Int } protocol Second { associatedtype Assoc : Second where Assoc.Assoc.Assoc == Self } struct OuterFirst<A : First, B : First> { struct Inner<C : First, D : First> { func method(a: A, b: B, c: C, d: D) { do { let _: (A, A.Assoc, A.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (B, B.Assoc, B.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (C, C.Assoc, C.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (D, D.Assoc, D.Assoc.Assoc) -> () = { _, _, _ in } } } } } struct OuterBoth<A : First & Second, B : First & Second> { struct Inner<C : First & Second, D : First & Second> { func method(a: A, b: B, c: C, d: D) { do { let _: (A, A.Assoc, A.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (B, B.Assoc, B.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (C, C.Assoc, C.Assoc.Assoc) -> () = { _, _, _ in } } do { let _: (D, D.Assoc, D.Assoc.Assoc) -> () = { _, _, _ in } } } } } struct F1: First { typealias Assoc = F2 func Assoc(_ x: Int) -> Int { return x + 1 } } struct F2: First { typealias Assoc = F1 func Assoc(_ x: Int) -> Int { return x * 2 } } struct FS1: First, Second { typealias Assoc = FS2 func Assoc(_ x: Int) -> Int { return x - 1 } } struct FS2: First, Second { typealias Assoc = FS3 func Assoc(_ x: Int) -> Int { return x / 2 } } struct FS3: First, Second { typealias Assoc = FS1 func Assoc(_ x: Int) -> Int { return x * 2 } } public func test() { roundTripType(OuterFirst<F1,F2>.self) roundTripType(OuterBoth<FS1,FS2>.self) roundTripType(OuterFirst<F1,F2>.Inner<F2,F1>.self) roundTripType(OuterBoth<FS1,FS2>.Inner<FS2,FS1>.self) roundTripType(type(of:OuterFirst<F1,F2>.Inner<F2,F1>.method)) roundTripType(type(of:OuterBoth<FS1,FS2>.Inner<FS2,FS1>.method)) }
apache-2.0
b1ea854749ab0b9fd5e4765cb645b67b
22.277778
66
0.524105
2.885675
false
false
false
false
GlobusLTD/components-ios
GlobusSwifty/StructedObject/GLBStructedObject.swift
1
4198
/*--------------------------------------------------*/ import Globus /*--------------------------------------------------*/ extension GLBStructedObject { // MARK: Setters open func set(value: Bool?, forPath path: String) -> Bool { if let unwrapped = value { return self.set(value: unwrapped, forPath: path) } return self.set(object: nil, forPath: path) } open func set(value: Int?, forPath path: String) -> Bool { if let unwrapped = value { return self.set(value: unwrapped, forPath: path) } return self.set(object: nil, forPath: path) } open func set(value: UInt?, forPath path: String) -> Bool { if let unwrapped = value { return self.set(value: unwrapped, forPath: path) } return self.set(object: nil, forPath: path) } open func set(value: Float?, forPath path: String) -> Bool { if let unwrapped = value { return self.set(value: unwrapped, forPath: path) } return self.set(object: nil, forPath: path) } open func set(value: Double?, forPath path: String) -> Bool { if let unwrapped = value { return self.set(value: unwrapped, forPath: path) } return self.set(object: nil, forPath: path) } // MARK: Getters open func boolean(atPath path: String, or: Bool?) -> Bool? { if let number = self.number(atPath: path, or: nil) { return number.boolValue } return or } open func int(atPath path: String, or: Int?) -> Int? { if let number = self.number(atPath: path, or: nil) { return number.intValue } return or } open func uint(atPath path: String, or: UInt?) -> UInt? { if let number = self.number(atPath: path, or: nil) { return number.uintValue } return or } open func float(atPath path: String, or: Float?) -> Float? { if let number = self.number(atPath: path, or: nil) { return number.floatValue } return or } open func double(atPath path: String, or: Double?) -> Double? { if let number = self.number(atPath: path, or: nil) { return number.doubleValue } return or } // MARK: To object open func object(value: Bool?) -> Any? { if let safe = value { return self.object(value: safe) } return nil } open func object(value: Int?) -> Any? { if let safe = value { return self.object(value: safe) } return nil } open func object(value: UInt?) -> Any? { if let safe = value { return self.object(value: safe) } return nil } open func object(value: Float?) -> Any? { if let safe = value { return self.object(value: safe) } return nil } open func object(value: Double?) -> Any? { if let safe = value { return self.object(value: safe) } return nil } // MARK: From object open func boolean(from object: Any?, or: Bool?) -> Bool { if let safe = or { return self.boolean(from: object, or: safe) } return false } open func int(from object: Any?, or: Int?) -> Int { if let safe = or { return self.int(from: object, or: safe) } return 0 } open func uint(from object: Any?, or: UInt?) -> UInt { if let safe = or { return self.uint(from: object, or: safe) } return 0 } open func float(from object: Any?, or: Float?) -> Float { if let safe = or { return self.float(from: object, or: safe) } return 0 } open func double(from object: Any?, or: Double?) -> Double { if let safe = or { return self.double(from: object, or: safe) } return 0 } } /*--------------------------------------------------*/
mit
48ddfc66b996561912eee43596b15c7e
25.402516
67
0.494045
4.274949
false
false
false
false
vector-im/vector-ios
Riot/Modules/KeyBackup/ManualExport/EncryptionKeysExportPresenter.swift
1
5031
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation final class EncryptionKeysExportPresenter: NSObject { // MARK: - Constants private enum Constants { static let keyExportFileName = "riot-keys.txt" } // MARK: - Properties // MARK: Private private let session: MXSession private let activityViewPresenter: ActivityIndicatorPresenterType private let keyExportFileURL: URL private weak var presentingViewController: UIViewController? private weak var sourceView: UIView? private var encryptionKeysExportView: MXKEncryptionKeysExportView? private var documentInteractionController: UIDocumentInteractionController? // MARK: Public // MARK: - Setup init(session: MXSession) { self.session = session self.activityViewPresenter = ActivityIndicatorPresenter() self.keyExportFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(Constants.keyExportFileName) super.init() } deinit { self.deleteKeyExportFile() } // MARK: - Public func present(from viewController: UIViewController, sourceView: UIView?) { self.presentingViewController = viewController self.sourceView = sourceView let keysExportView: MXKEncryptionKeysExportView = MXKEncryptionKeysExportView(matrixSession: self.session) // Make sure the file is empty self.deleteKeyExportFile() keysExportView.show(in: viewController, toExportKeysToFile: self.keyExportFileURL, onLoading: { [weak self] (loading) in guard let self = self else { return } if loading { self.activityViewPresenter.presentActivityIndicator(on: viewController.view, animated: true) } else { self.activityViewPresenter.removeCurrentActivityIndicator(animated: true) } }, onComplete: { [weak self] (success) in guard let self = self else { return } guard success else { self.encryptionKeysExportView = nil return } self.presentInteractionDocumentController() }) self.encryptionKeysExportView = keysExportView } // MARK: - Private private func presentInteractionDocumentController() { let sourceRect: CGRect guard let presentingView = self.presentingViewController?.view else { self.encryptionKeysExportView = nil return } if let sourceView = self.sourceView { sourceRect = sourceView.convert(sourceView.bounds, to: presentingView) } else { sourceRect = presentingView.bounds } let documentInteractionController = UIDocumentInteractionController(url: self.keyExportFileURL) documentInteractionController.delegate = self if documentInteractionController.presentOptionsMenu(from: sourceRect, in: presentingView, animated: true) { self.documentInteractionController = documentInteractionController } else { self.encryptionKeysExportView = nil self.deleteKeyExportFile() } } @objc private func deleteKeyExportFile() { let fileManager = FileManager.default if fileManager.fileExists(atPath: self.keyExportFileURL.path) { try? fileManager.removeItem(atPath: self.keyExportFileURL.path) } } } // MARK: - UIDocumentInteractionControllerDelegate extension EncryptionKeysExportPresenter: UIDocumentInteractionControllerDelegate { // Note: This method is not called in all cases (see http://stackoverflow.com/a/21867096). func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) { self.deleteKeyExportFile() self.documentInteractionController = nil } func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) { self.encryptionKeysExportView = nil self.documentInteractionController = nil } }
apache-2.0
11d58b5d051efc129f97b6df5b16ae71
33.458904
136
0.64838
5.918824
false
false
false
false
ponnierohith/ReaXn
ReaXn/ReaXn/AppDelegate.swift
3
12366
// // AppDelegate.swift // ReaXn // // Created by Kevin Chen on 7/11/15. // Copyright (c) 2015 ReaXn. All rights reserved. // import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TSTapDetectorDelegate, CLLocationManagerDelegate { var window: UIWindow? var tapDetector: TSTapDetector! var locationManager: CLLocationManager! var phone : TCDevice? var connection : TCConnection? let useNotifications : Bool = false func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // initialize tap detector self.tapDetector = TSTapDetector.init() self.tapDetector.listener.collectMotionInformationWithInterval(10) self.tapDetector.delegate = self self.locationManager = CLLocationManager() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.distanceFilter = kCLDistanceFilterNone self.locationManager.requestAlwaysAuthorization() self.locationManager.startUpdatingLocation() UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(expirationCallback) // KNOCK KNOCK ENABLED if NSUserDefaults.standardUserDefaults().objectForKey(Constants.DefaultsKnockKnockEnabledString()) == nil { println("no default value found, setting knockKnock = true") NSUserDefaults.standardUserDefaults().setBool(true, forKey: Constants.DefaultsKnockKnockEnabledString()) } let knockKnockEnabled = NSUserDefaults.standardUserDefaults().boolForKey(Constants.DefaultsKnockKnockEnabledString()) println("knockKnockEnabled = \(knockKnockEnabled)") // LOCATION ENABLED if NSUserDefaults.standardUserDefaults().objectForKey(Constants.DefaultsLocationInfoEnabledString()) == nil { println("no default value found, setting locationInfo = true") NSUserDefaults.standardUserDefaults().setBool(true, forKey: Constants.DefaultsLocationInfoEnabledString()) } let locationEnabled = NSUserDefaults.standardUserDefaults().boolForKey(Constants.DefaultsLocationInfoEnabledString()) println("location enabled = \(locationEnabled)") // NOTIFICATIONS ENABLED if useNotifications { println("==== USING notifications ====") registerForActionableNotifications() } else { println("==== NOT using notification ====") } // setup UINavigationBar color UINavigationBar.appearance().barTintColor = UIColor(red:0.15, green:0.18, blue:0.33, alpha:1.0) UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] return true } func registerForActionableNotifications() { // 1. Create the actions ************************************************** // Open Action let helpAction = UIMutableUserNotificationAction() helpAction.identifier = "HELP_ACTION" helpAction.title = "Help" helpAction.activationMode = UIUserNotificationActivationMode.Background helpAction.authenticationRequired = false helpAction.destructive = false // 2. Create the category *********************************************** // Category let actionCategory = UIMutableUserNotificationCategory() actionCategory.identifier = "HELP_CATEGORY" // A. Set actions for the default context actionCategory.setActions([helpAction], forContext: UIUserNotificationActionContext.Default) // B. Set actions for the minimal context actionCategory.setActions([helpAction], forContext: UIUserNotificationActionContext.Minimal) // 3. Notification Registration ***************************************** let types = UIUserNotificationType.Alert | UIUserNotificationType.Sound let settings = UIUserNotificationSettings(forTypes: types, categories: NSSet(object: actionCategory) as Set<NSObject>) UIApplication.sharedApplication().registerUserNotificationSettings(settings) } 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:. } // We should probably figure out what to do once the expiration times out. // Also, Swift closures confuse me so I defined a function handle. func expirationCallback() { } // Tap detection callback func detectorDidDetectTap(detector: TSTapDetector!) { println("detected knock knock") let knockKnockEnabled = NSUserDefaults.standardUserDefaults().boolForKey(Constants.DefaultsKnockKnockEnabledString()) if knockKnockEnabled { if useNotifications { createActionNotification() } else { sendSMS() createInfoNotification("Your text was sent successfully.") } AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) //TODO: does this even work? } } func createActionNotification() { if useNotifications { // create a corresponding local notification var notification = UILocalNotification() notification.alertBody = "Notification text goes here" // text that will be displayed in the notification notification.alertAction = "Action" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view" notification.soundName = UILocalNotificationDefaultSoundName // play default sound notification.userInfo = ["UUID": NSUUID().UUIDString, ] // assign a unique identifier to the notification so that we can retrieve it later notification.category = "HELP_CATEGORY" UIApplication.sharedApplication().presentLocalNotificationNow(notification) } } func createInfoNotification(text: String) { let notification = UILocalNotification() notification.alertBody = text notification.userInfo = ["UUID": NSUUID().UUIDString, ] notification.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().presentLocalNotificationNow(notification) } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if useNotifications { // Handle notification action ***************************************** if notification.category == "HELP_CATEGORY" { if let action = identifier { switch action{ case "HELP_ACTION": // NSNotificationCenter.defaultCenter().postNotificationName("helpNotification", object: self, userInfo: notification.userInfo) // NSNotificationCenter.defaultCenter().postNotificationName("receivedHelpNotification", object: self, userInfo: notification.userInfo) println("Help action triggered") // dialNumber("6083957313") sendSMS() // AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) default: return } } } completionHandler() } } //MARK: - Twilio func sendSMS() { println("Sending request.") // let phoneNumberKevin = "+6083957313" let phoneNumberBen = "+6178179292" // let phoneNumberSonny = "+6284449233" var kTwilioSID: String = Constants.TwilioSID() var kTwilioSecret: String = Constants.TwilioSecret() let phoneNumberTwilio = Constants.TwilioFromNumber() var kFromNumber: String = phoneNumberTwilio var kToNumber : String if let storedToNumber = NSUserDefaults.standardUserDefaults().objectForKey(Constants.DefaultsKey_TwilioToPhoneNumber()) as? String { kToNumber = storedToNumber } else { kToNumber = phoneNumberBen } var kMessage : String if let storedMessage = NSUserDefaults.standardUserDefaults().objectForKey(Constants.DefaultsKey_TwilioMessage()) as? String { kMessage = "[**Test**] \(storedMessage)" } else { kMessage = "[**ReaXnTest** Dad, I think I’m in danger. Please come get me.]" } if NSUserDefaults.standardUserDefaults().boolForKey(Constants.DefaultsLocationInfoEnabledString()) { let lat = self.locationManager.location.coordinate.latitude let lng = self.locationManager.location.coordinate.longitude kMessage += String(format: "My location is: maps.google.com/?q=%f,%f", lat, lng) } let urlString = "https://\(kTwilioSID):\(kTwilioSecret)@api.twilio.com/2010-04-01/Accounts/\(kTwilioSID)/SMS/Messages.json" if let url = NSURL(string: urlString) { var request: NSMutableURLRequest = NSMutableURLRequest() request.URL = url request.HTTPMethod = "POST" var bodyString: String = "From=\(kFromNumber)&To=\(kToNumber)&Body=\(kMessage)" if let data: NSData = bodyString.dataUsingEncoding(NSUTF8StringEncoding) { request.HTTPBody = data var response: NSURLResponse? var error: NSError? let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) if let httpResponse = response as? NSHTTPURLResponse { println(httpResponse.statusCode) } } } } // func dialNumber(number : String) { // let phoneNumber = "telprompt://\(number)" // println("calling \(phoneNumber)") // UIApplication.sharedApplication().openURL(NSURL(string: phoneNumber)!) // } }
mit
a997e87668d8a28450f680eea97b0f25
42.843972
285
0.635878
5.967181
false
false
false
false
hanwanjie853710069/Easy-living
易持家/Class/Vendor/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
1
9552
// // IQToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 private var kIQToolbarTitleInvocationTarget = "kIQToolbarTitleInvocationTarget" private var kIQToolbarTitleInvocationSelector = "kIQToolbarTitleInvocationSelector" /** @abstract IQToolbar for IQKeyboardManager. */ public class IQToolbar: UIToolbar , UIInputViewAudioFeedback { override public class func initialize() { superclass()?.initialize() self.appearance().barTintColor = nil //Background image self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.Bottom, barMetrics: UIBarMetrics.Default) self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.Top, barMetrics: UIBarMetrics.Default) self.appearance().setBackgroundImage(nil, forToolbarPosition: UIBarPosition.TopAttached, barMetrics: UIBarMetrics.Default) self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.Any) self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.Bottom) self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.Top) self.appearance().setShadowImage(nil, forToolbarPosition: UIBarPosition.TopAttached) //Background color self.appearance().backgroundColor = nil } public var titleFont : UIFont? { didSet { if let newItems = items { for item in newItems { if let newItem = item as? IQTitleBarButtonItem { newItem.font = titleFont break } } } } } public var title : String? { didSet { if let newItems = items { for item in newItems { if let newItem = item as? IQTitleBarButtonItem { newItem.font = titleFont break } } } } } /** Optional target & action to behave toolbar title button as clickable button @param target Target object. @param action Target Selector. */ public func setCustomToolbarTitleTarget(target: AnyObject?, action: Selector?) { toolbarTitleInvocation = (target, action) } /** Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method. */ public var toolbarTitleInvocation : (target: AnyObject?, action: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQToolbarTitleInvocationTarget) var action : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQToolbarTitleInvocationSelector) as? String { action = NSSelectorFromString(selectorString) } return (target: target, action: action) } set(newValue) { objc_setAssociatedObject(self, &kIQToolbarTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.action { objc_setAssociatedObject(self, &kIQToolbarTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQToolbarTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { newItem.titleInvocation = newValue break } } } } } override init(frame: CGRect) { super.init(frame: frame) sizeToFit() autoresizingMask = UIViewAutoresizing.FlexibleWidth tintColor = UIColor .blackColor() self.translucent = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sizeToFit() autoresizingMask = UIViewAutoresizing.FlexibleWidth tintColor = UIColor .blackColor() self.translucent = true } override public func sizeThatFits(size: CGSize) -> CGSize { var sizeThatFit = super.sizeThatFits(size) sizeThatFit.height = 44 return sizeThatFit } override public var tintColor: UIColor! { didSet { if let unwrappedItems = items { for item in unwrappedItems { item.tintColor = tintColor } } } } override public var barStyle: UIBarStyle { didSet { if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { if barStyle == .Default { newItem.selectableTextColor = UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1) } else { newItem.selectableTextColor = UIColor.yellowColor() } break } } } } } override public func layoutSubviews() { super.layoutSubviews() struct InternalClass { static var IQUIToolbarTextButtonClass: AnyClass? = NSClassFromString("UIToolbarTextButton") static var IQUIToolbarButtonClass: AnyClass? = NSClassFromString("UIToolbarButton") } var leftRect = CGRectNull var rightRect = CGRectNull var isTitleBarButtonFound = false let sortedSubviews = self.subviews.sort({ (view1 : UIView, view2 : UIView) -> Bool in let x1 = CGRectGetMinX(view1.frame) let y1 = CGRectGetMinY(view1.frame) let x2 = CGRectGetMinX(view2.frame) let y2 = CGRectGetMinY(view2.frame) if x1 != x2 { return x1 < x2 } else { return y1 < y2 } }) for barButtonItemView in sortedSubviews { if (isTitleBarButtonFound == true) { rightRect = barButtonItemView.frame break } else if (barButtonItemView.dynamicType === UIView.self) { isTitleBarButtonFound = true } else if ((InternalClass.IQUIToolbarTextButtonClass != nil && barButtonItemView.isKindOfClass(InternalClass.IQUIToolbarTextButtonClass!) == true) || (InternalClass.IQUIToolbarButtonClass != nil && barButtonItemView.isKindOfClass(InternalClass.IQUIToolbarButtonClass!) == true)) { leftRect = barButtonItemView.frame } } var x : CGFloat = 16 if (CGRectIsNull(leftRect) == false) { x = CGRectGetMaxX(leftRect) + 16 } let width : CGFloat = CGRectGetWidth(self.frame) - 32 - (CGRectIsNull(leftRect) ? 0 : CGRectGetMaxX(leftRect)) - (CGRectIsNull(rightRect) ? 0 : CGRectGetWidth(self.frame) - CGRectGetMinX(rightRect)) if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { let titleRect = CGRectMake(x, 0, width, self.frame.size.height) newItem.customView?.frame = titleRect break } } } } public var enableInputClicksWhenVisible: Bool { return true } }
apache-2.0
c07e5c2debb26d33587aea22e5ae4fc5
35.880309
288
0.584066
5.64539
false
false
false
false
mownier/pyrobase
PyrobaseTests/RequestMock.swift
1
2992
// // RequestMock.swift // Pyrobase // // Created by Mounir Ybanez on 02/05/2017. // Copyright © 2017 Ner. All rights reserved. // import Pyrobase class RequestMock: RequestProtocol { var content: [AnyHashable: Any] = [ "https://foo.firebaseio.com/name.json?auth=accessToken": "Luche", "https://foo.firebaseio.com/messages/abcde12345qwert.json?auth=accessToken": ["message": "Hello World!"] ] var urlPath: String = "" var expectedErrors: [Error?] = [] var expectedData: [Any] = [] var writeData: [AnyHashable : Any] = [:] var requestMethod: RequestMethod = .get var shouldURLPathBeReplaced: Bool = true var shouldRequestMethodBeReplaced: Bool = true func read(path: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { urlPath = path requestMethod = .get if !expectedErrors.isEmpty, let error = expectedErrors.removeFirst() { completion(.failed(error)) } else { if !expectedData.isEmpty { completion(.succeeded(expectedData.removeFirst())) } else { if let item = content[path] { completion(.succeeded(item)) } else { completion(.succeeded("OK")) } } } } func write(path: String, method: RequestMethod, data: [AnyHashable : Any], completion: @escaping (RequestResult) -> Void) { urlPath = path writeData = data requestMethod = method switch method { case .put: content[path] = data completion(.succeeded(data)) case .post: let newId = "abcde12345qwert" content[newId] = data completion(.succeeded(["name": newId])) case .patch: if !expectedErrors.isEmpty, let error = expectedErrors.removeFirst() { completion(.failed(error)) } else { if !expectedData.isEmpty { completion(.succeeded(expectedData.removeFirst())) } else { var contentInfo = content[path] as! [AnyHashable: Any] for (key, value) in data { contentInfo[key] = value } content[path] = contentInfo completion(.succeeded(data)) } } default: break } } func delete(path: String, completion: @escaping (RequestResult) -> Void) { if shouldURLPathBeReplaced { urlPath = path } if shouldRequestMethodBeReplaced { requestMethod = .delete } content.removeValue(forKey: path) completion(.succeeded("null")) } }
mit
f655032295a229e57c815fa499e01c1f
29.520408
127
0.514209
5.112821
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Home/Detail/View/View/CommentBottomView.swift
1
4027
// // CommentBottomView.swift // Floral // // Created by ALin on 16/5/30. // Copyright © 2016年 ALin. All rights reserved. // 评论列表底部的评论视图 import UIKit class CommentBottomView: UIView { /// placeholder var placeHolderStr : String? { didSet{ if let _ = placeHolderStr { textFiled.placeholder = "回复:"+placeHolderStr! textFiled.becomeFirstResponder() }else{ textFiled.placeholder = "评论" } } } var comment : Comment? /// 代理 weak var delegete :CommentBottomViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } static var g_self : CommentBottomView? private func setup() { CommentBottomView.g_self = self NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentBottomView.keyboardDidChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil) backgroundColor = UIColor.whiteColor() addSubview(textFiled) addSubview(sendBtn) addSubview(underLine) underLine.snp_makeConstraints { (make) in make.left.right.top.equalTo(self) make.height.equalTo(1) } sendBtn.snp_makeConstraints { (make) in make.centerY.equalTo(self) make.right.equalTo(self).offset(-10) make.width.equalTo(40) } textFiled.snp_makeConstraints { (make) in make.height.equalTo(30) make.centerY.equalTo(sendBtn) make.left.equalTo(15) make.right.equalTo(sendBtn.snp_left).offset(-10) } } @objc private func keyboardDidChangeFrame(notify : NSNotification) { let rect : CGRect = notify.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue() if rect.origin.y == ScreenHeight { // 隐藏键盘 placeHolderStr = nil comment = nil } delegete?.commentBottomView!(self, keyboradFrameChange: notify.userInfo!) } private lazy var textFiled : UITextField = { let text = UITextField(frame: CGRectZero, isPlaceHolderSpace: true) text.background = UIImage(named: "s_bg_3rd_292x43") text.placeholder = "评论" text.font = UIFont.systemFontOfSize(12) // 设置placeholder的字体 text.setValue(UIFont.systemFontOfSize(12), forKeyPath: "_placeholderLabel.font") return text }() private lazy var sendBtn = UIButton(title: "发送", imageName: nil, target: g_self!, selector: #selector(CommentBottomView.sendMessage), font: UIFont.systemFontOfSize(13), titleColor: UIColor.blackColor()) /// 分割线 private lazy var underLine = UIImageView(image: UIImage(named:"underLine")) // MARK: - 点击事件 func sendMessage() { let message = textFiled.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) ?? "" if textFiled.text?.characters.count < 1 || message.characters.count < 1 { showErrorMessage("不能发送空消息") return } delegete?.commentBottomView!(self, sendMessage: textFiled.text!, replyComment: comment) // 评论/回复完成后, 置空 textFiled.text = "" } } @objc protocol CommentBottomViewDelegate : NSObjectProtocol { /// 键盘监听的代理 optional func commentBottomView(commentBottomView: CommentBottomView, keyboradFrameChange userInfo:[NSObject : AnyObject]) /// 点击评论/回复 optional func commentBottomView(commentBottomView: CommentBottomView, sendMessage message:String, replyComment comment: Comment?) }
mit
883707e575e3258fa9363e7417b90cc6
31.983051
206
0.628726
4.723301
false
false
false
false
LogTenSafe/MacOSX
LogTenSafe/Source/Services/APIService.swift
1
6614
import Foundation import Alamofire import Defaults /** * This service class is the interface between the application and the API * backend. */ public class APIService { fileprivate var authHeader: String? { if let JWT = Defaults[.JWT] { return "Bearer \(JWT)" } else { return nil } } private var authInterceptor: AuthHeaderInterceptor { return AuthHeaderInterceptor(service: self) } /** * Logs a user in. * * - Parameter login: The credentials to use. * - Parameter handler: Called with the result of the login operation. * - Parameter result: The result of the login operation. Contains the error * if failed. */ func logIn(login: Login, handler: @escaping(_ result: Result<Void, Error>) -> Void = { _ in }) throws { APIRequest("login.json", method: .post, body: login, bodyDecoder: NoBody.self) { [weak self] response in self?.setJWTFromResponse(response) switch response.result { case .success: handler(.success(())) case .failure(let error): handler(.failure(error)) } } } /** Logs a user out. */ func logOut() { APIRequest("logout.json", method: .delete, bodyDecoder: NoBody.self) { _ in Defaults[.JWT] = nil } } /** * Loads the logged-in user's backups. * * - Parameter handler: Called with the result of the operation after the * backups have been loaded. * - Parameter result: The result of the load operation. Contains the loaded * Backups on success, or the error on failure. */ func loadBackups(handler: @escaping (_ result: Result<Array<Backup>, AFError>) -> Void = { _ in }) { APIRequest("backups.json", bodyDecoder: [Backup].self) { [weak self] response in self?.deleteJWTIfAuthorizationFails(response.result) handler(response.result) } } /** * Uploads a backup to the server. * * - Parameter backup: The backup data to upload. * - Parameter progressHandler: A handler that is repeatedly called with a * `Progress` object during the upload. * - Parameter handler: Called when the upload is complete with the result * of the operation. * - Parameter result: The result of the backup operation. Contains the * created Backup on success, or the error on failure. */ public func addBackup(_ backup: DraftBackup, progressHandler: @escaping Request.ProgressHandler = { _ in }, handler: @escaping (_ result: Result<Backup, Error>) -> Void = { _ in }) { AF.upload(multipartFormData: { formData in formData.append(Data(backup.hostname.utf8), withName: "backup[hostname]") formData.append(backup.logbook, withName: "backup[logbook]") }, to: appURL.appendingPathComponent("backups.json"), interceptor: authInterceptor) .uploadProgress(closure: progressHandler) .responseDecodable(of: Backup.self) { [weak self] response in self?.deleteJWTIfAuthorizationFails(response.result) switch response.result { case .success(let backup): handler(.success(backup)) case .failure(let error): handler(.failure(error)) } } } /** * Downloads the logfile for a Backup. * * - Parameter backup: The backup to download the logfile for. * - Parameter destination: Where to download the logfile to. * - Parameter progressHandler: A handler that is repeatedly called with a * `Progress` object during the download. * - Parameter handler: Called when the download is complete with the result * of the operation. * - Parameter result: The result of the download operation. Contains a * local file URL to the downloaded data on success, or the error on * failure. */ func downloadBackup(_ backup: Backup, destination: @escaping DownloadRequest.Destination, progressHandler: @escaping Request.ProgressHandler = { _ in }, handler: @escaping (_ result: Result<URL?, AFError>) -> Void) { guard let URL = backup.downloadURL else { return } AF.download(URL, interceptor: authInterceptor, to: destination) .downloadProgress(closure: progressHandler) .response { [weak self] response in self?.deleteJWTIfAuthorizationFails(response.result) handler(response.result) } } private struct NoBody: Codable {} private func APIRequest<RequestType, ResponseType>(_ path: String, method: HTTPMethod = .get, body: RequestType? = nil, bodyDecoder: ResponseType.Type, handler: @escaping(AFDataResponse<ResponseType>) -> Void = { _ in }) where RequestType: Encodable, ResponseType: Decodable { AF.request(appURL.appendingPathComponent(path), method: method, parameters: body, encoder: JSONParameterEncoder.default, interceptor: authInterceptor).validate().responseDecodable(of: ResponseType.self) { [weak self] response in self?.deleteJWTIfAuthorizationFails(response.result) handler(response) } } private func APIRequest<ResponseType>(_ path: String, method: HTTPMethod = .get, bodyDecoder: ResponseType.Type, handler: @escaping(AFDataResponse<ResponseType>) -> Void = { _ in }) where ResponseType: Decodable { APIRequest(path, method: method, body: Optional<NoBody>.none, bodyDecoder: bodyDecoder, handler: handler) } private func setJWTFromResponse(_ response: DataResponse<APIService.NoBody, AFError>) { if let JWT = response.response?.value(forHTTPHeaderField: "Authorization") { Defaults[.JWT] = String(JWT.dropFirst(7)) // "Bearer " } } private func deleteJWTIfAuthorizationFails<T>(_ result: Result<T, AFError>) { switch result { case .failure(let error): if isAuthorizationError(error) { Defaults[.JWT] = nil } default: break } } } fileprivate struct AuthHeaderInterceptor: RequestInterceptor { let service: APIService func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) { var urlRequest = urlRequest if let authHeader = service.authHeader { urlRequest.addValue(authHeader, forHTTPHeaderField: "Authorization") } completion(.success(urlRequest)) } }
mit
2da7f4955e238b1b1a64371b84b2ec15
41.948052
280
0.637889
4.710826
false
false
false
false
fgengine/quickly
Quickly/Views/Toolbar/QToolbar.swift
1
1499
// // Quickly // open class QToolbarStyleSheet : IQStyleSheet { public var isTranslucent: Bool public var tintColor: UIColor public var contentTintColor: UIColor public init( isTranslucent: Bool, tintColor: UIColor, contentTintColor: UIColor ) { self.isTranslucent = isTranslucent self.tintColor = tintColor self.contentTintColor = contentTintColor } public init(_ styleSheet: QToolbarStyleSheet) { self.isTranslucent = styleSheet.isTranslucent self.tintColor = styleSheet.tintColor self.contentTintColor = styleSheet.contentTintColor } } public class QToolbar : UIToolbar { public init( styleSheet: QToolbarStyleSheet? = nil, items: [UIBarButtonItem] = [] ) { super.init( frame: CGRect( x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50 ) ) if let styleSheet = styleSheet { self.apply(styleSheet) } self.items = items } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func apply(_ styleSheet: QToolbarStyleSheet) { self.isTranslucent = styleSheet.isTranslucent self.barTintColor = styleSheet.tintColor self.tintColor = styleSheet.contentTintColor self.sizeToFit() } }
mit
11ef8ec7e15edca522f78e4829a89202
23.983333
59
0.592395
5.222997
false
false
false
false
TheTekton/Malibu
Sources/Serialization/StringSerializer.swift
1
989
import Foundation public struct StringSerializer: Serializing { var encoding: String.Encoding? public init(encoding: String.Encoding? = nil) { self.encoding = encoding } public func serialize(_ data: Data, response: HTTPURLResponse) throws -> String { if response.statusCode == 204 { return "" } guard data.count > 0 else { throw MalibuError.noDataInResponse } var stringEncoding: UInt if let encoding = encoding { stringEncoding = encoding.rawValue } else if let encodingName = response.textEncodingName { stringEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!) ) } else { stringEncoding = String.Encoding.isoLatin1.rawValue } guard let string = String(data: data, encoding: String.Encoding(rawValue: stringEncoding)) else { throw MalibuError.stringSerializationFailed(stringEncoding) } return string } }
mit
7364384255884eb4a48af927db5213d5
26.472222
101
0.710819
5.045918
false
false
false
false
JakeLin/IBAnimatable
IBAnimatableApp/IBAnimatableApp/Playground/Transitions/TransitionPushedViewController.swift
2
1237
// // Created by Jake Lin on 5/13/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit import IBAnimatable final class TransitionPushedViewController: UIViewController { @IBOutlet fileprivate var gestureLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() if let animatableView = view as? AnimatableView { animatableView.predefinedGradient = makeRandomGradient() } configureGestureLabel() } } private extension TransitionPushedViewController { func configureGestureLabel() { // Shows nothing by default gestureLabel.text = "to pop" guard let navigationController = navigationController as? AnimatableNavigationController else { return } // No gesture for this animator if case .none = navigationController.interactiveGestureType { return } if case .none = navigationController.transitionAnimationType { return } gestureLabel.text = retrieveGestureText(interactiveGestureType: navigationController.interactiveGestureType, transitionAnimationType: navigationController.transitionAnimationType, exit: "pop") } }
mit
bca07d8e2e1ea3fc1a55e355bfa9915d
25.297872
114
0.692557
5.618182
false
false
false
false
fespinoza/linked-ideas-osx
LinkedIdeas-iOS-Core/Sources/DocumentViewController.swift
1
2687
// DocumentViewController.swift // LinkedIdeas-iOS // // Created by Felipe Espinoza on 20/01/2018. // Copyright © 2018 Felipe Espinoza Dev. All rights reserved. // import UIKit import LinkedIdeas_Shared public class DocumentViewController: UIViewController { public var document: Document! // MARK: - private properties private let canvasFrame = CGRect(x: 0, y: 0, width: 3000, height: 2000) private lazy var canvasView: CanvasView = { let canvasView = CanvasView(frame: self.canvasFrame) canvasView.dataSource = self return canvasView }() // MARK: - UIViewController overrides public override func viewDidLoad() { self.view.backgroundColor = .white let scrollView = UIScrollView() scrollView.contentSize = self.canvasFrame.size scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.minimumZoomScale = 0.5 scrollView.maximumZoomScale = 3.0 scrollView.delegate = self // subviews scrollView.addSubview(canvasView) self.view.addSubview(scrollView) // autolayout NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor), scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), scrollView.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor), ]) document.open { [weak self] (success) in print("open \(success)") if let strongSelf = self { strongSelf.canvasView.setNeedsDisplay() let rect = strongSelf.document.documentFocusRect() scrollView.setContentOffset(rect.origin, animated: false) strongSelf.navigationItem.title = strongSelf.document.localizedName } } } public override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = false self.navigationItem.largeTitleDisplayMode = .always self.canvasView.setNeedsDisplay() } } extension DocumentViewController: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return canvasView } } extension DocumentViewController: CanvasViewDataSource { public func drawableElements(forRect rect: CGRect) -> [DrawableElement] { var elements: [DrawableElement] = [] elements += document .concepts .filter({ $0.area.intersects(rect) }) .map { DrawableConcept(concept: $0) as DrawableElement } elements += document .links .filter({ $0.area.intersects(rect) }) .map { DrawableLink(link: $0) as DrawableElement } return elements } }
mit
e574abd8aa9216868e9b54730f85e09a
29.522727
93
0.721891
4.704028
false
false
false
false
lucaslouca/swift-concurrency
app-ios/Fluxcapacitor/FXCViewParallaxTableHeader.swift
1
1569
// // FXCViewParallaxTableHeader.swift // Fluxcapacitor // // Created by Lucas Louca on 09/06/15. // Copyright (c) 2015 Lucas Louca. All rights reserved. // import UIKit class FXCViewParallaxTableHeader: UIView { let parallaxDeltaFactor: CGFloat = 0.5 var defaultHeaderFrame: CGRect! var scrollView: UIScrollView! var subView: UIView! convenience init(size: CGSize, subView:UIView) { self.init(frame: CGRectMake(0, 0, size.width, size.height)) self.scrollView = UIScrollView(frame: self.bounds) self.subView = subView self.subView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleHeight, .FlexibleWidth] self.scrollView.addSubview(self.subView) self.addSubview(self.scrollView) } func layoutForScrollViewContentOffset(contentOffset: CGPoint) { var frame = self.scrollView.frame defaultHeaderFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) if (contentOffset.y > 0) { frame.origin.y = contentOffset.y * parallaxDeltaFactor self.scrollView.frame = frame self.clipsToBounds = true } else { var delta: CGFloat = 0.0 var rect: CGRect = defaultHeaderFrame; delta = fabs(contentOffset.y) rect.origin.y -= delta rect.size.height += delta self.scrollView.frame = rect self.clipsToBounds = false } } }
mit
3a3a5e804fd3a5a09b8444baeb143878
32.382979
159
0.639261
4.521614
false
false
false
false
dvSection8/dvSection8
dvSection8/Classes/Utils/DVUploadFiles.swift
1
3511
// // DVUploadFiles.swift // dvSection8 // // Created by MJ Roldan on 17/01/2018. // import Foundation import MobileCoreServices public class DVUploadFiles: NSObject { public class var shared: DVUploadFiles { struct Static { static let instance: DVUploadFiles = DVUploadFiles() } return Static.instance } private lazy var api: DVAPI = { return DVAPI() }() public func request(_ requests: URLRequest, success: @escaping ResponseSuccessBlock, failed: @escaping ResponseFailedBlock) { self.api.dataRequest(requests, success: { (response) in print(response) success(response) }, failed: { (errorCode) in print(errorCode) failed(errorCode) }) } public func createRequest(with url: URL, params: Paremeters? = nil, headers: HTTPHeaders? = nil, filePathKey: String, paths: [String]) throws -> URLRequest { let boundary = generateBoundaryString() var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0) urlRequest.httpMethod = HTTPMethod.post.rawValue urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") urlRequest.allHTTPHeaderFields = headers urlRequest.httpBody = try createBody(with: params, filePathKey: filePathKey, paths: paths, boundary: boundary) return urlRequest } private func createBody(with parameters: Paremeters?, filePathKey: String, paths: [String], boundary: String) throws -> Data { var body = Data() if parameters != nil { for (key, value) in parameters! { body.append("--\(boundary)\r\n") body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.append("\(value)\r\n") } } for path in paths { guard let url = URL(string: path) else { return body} let filename = url.lastPathComponent do { let data = try Data(contentsOf: url) let mimetype = mimeType(for: path) body.append("--\(boundary)\r\n") body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n") body.append("Content-Type: \(mimetype)\r\n\r\n") body.append(data) body.append("\r\n") } catch { print("Invalid data") } } body.append("--\(boundary)--\r\n") return body } private func generateBoundaryString() -> String { return "Boundary-\(NSUUID().uuidString)" } private func mimeType(for path: String) -> String { let url = NSURL(fileURLWithPath: path) let pathExtension = url.pathExtension if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() { if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { return mimetype as String } } return "application/octet-stream"; } }
mit
5397672f418331c537a09a0295c2a04f
34.11
144
0.564227
5.030086
false
false
false
false
alessiobrozzi/firefox-ios
Telemetry/BookmarkTelemetryPing.swift
2
1786
/* 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 SwiftyJSON public func makeAdHocBookmarkMergePing(_ bundle: Bundle, clientID: String, attempt: Int32, bufferRows: Int?, valid: [String: Bool], clientCount: Int) -> JSON { let anyFailed = valid.reduce(false, { $0 || $1.1 }) var out: [String: Any] = [ "v": 1, "appV": AppInfo.appVersion, "build": bundle.object(forInfoDictionaryKey: "BuildID") as? String ?? "unknown", "id": clientID, "attempt": Int(attempt), "success": !anyFailed, "date": Date().description, "clientCount": clientCount, ] if let bufferRows = bufferRows { out["rows"] = bufferRows } if anyFailed { valid.forEach { key, value in out[key] = value } } return JSON(out) } public func makeAdHocSyncStatusPing(_ bundle: Bundle, clientID: String, statusObject: [String: String]?, engineResults: [String: String]?, resultsFailure: MaybeErrorType?, clientCount: Int) -> JSON { let statusObject: Any = statusObject ?? JSON.null let engineResults: Any = engineResults ?? JSON.null let resultsFailure: Any = resultsFailure?.description ?? JSON.null let out: [String: Any] = [ "v": 1, "appV": AppInfo.appVersion, "build": (bundle.object(forInfoDictionaryKey: "BuildID") as? String ?? "unknown"), "id": clientID, "date": Date().description, "clientCount": clientCount, "statusObject": statusObject, "engineResults": engineResults, "resultsFailure": resultsFailure ] return JSON(out) }
mpl-2.0
6a13a4c03879fe8712812ce8837b92ed
33.346154
199
0.62486
4.013483
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/swifter/XCode/SwifterTestsCommon/PingServer.swift
1
1939
// // PingServer.swift // Swifter // // Created by Brian Gerstle on 8/20/16. // Copyright © 2016 Damian Kołakowski. All rights reserved. // import Foundation // Server extension HttpServer { class func pingServer() -> HttpServer { let server = HttpServer() server.GET["/ping"] = { request in return HttpResponse.ok(.text("pong!")) } return server } } let defaultLocalhost = URL(string:"http://localhost:8080")! // Client extension URLSession { func pingTask( hostURL: URL = defaultLocalhost, completionHandler handler: @escaping (Data?, URLResponse?, Error?) -> Void ) -> URLSessionDataTask { return self.dataTask(with: hostURL.appendingPathComponent("/ping"), completionHandler: handler) } func retryPing( hostURL: URL = defaultLocalhost, timeout: Double = 2.0 ) -> Bool { let semaphore = DispatchSemaphore(value: 0) self.signalIfPongReceived(semaphore, hostURL: hostURL) let timeoutDate = NSDate().addingTimeInterval(timeout) var timedOut = false while semaphore.wait(timeout: DispatchTime.now()) != DispatchTimeoutResult.timedOut { if NSDate().laterDate(timeoutDate as Date) != timeoutDate as Date { timedOut = true break } RunLoop.current.run( mode: RunLoopMode.commonModes, before: NSDate.distantFuture ) } return timedOut } func signalIfPongReceived(_ semaphore: DispatchSemaphore, hostURL: URL) { pingTask(hostURL: hostURL) { data, response, error in if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { semaphore.signal() } else { self.signalIfPongReceived(semaphore, hostURL: hostURL) } }.resume() } }
gpl-3.0
5091380577ca4d1b006fcf401c3a122d
29.746032
103
0.602994
4.8425
false
false
false
false
jfrowies/iEMI
iEMI/EndParkingViewController.swift
1
5705
// // EndParkingViewController.swift // iEMI // // Created by Fer Rowies on 2/16/15. // Copyright (c) 2015 Rowies. All rights reserved. // import UIKit class EndParkingViewController: NetworkActivityViewController { @IBOutlet private weak var closeButton: UIButton! let service: ParkingCloseEMIService = ParkingCloseEMIService() let licensePlate = LicensePlate() var parking: Parking? weak var parkingInformationViewController : ParkingInformationViewController? private let kShowParkingInformationSegue: String = "showParkingInformation" // MARK: - View controller life cycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.refresh(nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == kShowParkingInformationSegue { self.parkingInformationViewController = segue.destinationViewController as? ParkingInformationViewController } } // MARK: - IBActions private let kLoadingParkingText = NSLocalizedString("Loading parking", comment: "loading parking message in close parking") @IBAction func refresh(sender:AnyObject?) { self.closeButton.enabled = false self.loadParking() } @IBAction func closeButtonTouched(sender: UIButton) { guard let currentParking = self.parking else { self.showError(nil,errorMessage: kErrorLoadingClosingText) return } let alertController = UIAlertController(title: nil, message: NSLocalizedString("Are you sure you want to close this parking?", comment: "Close parking action sheet message"), preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button title in action sheet"), style: .Cancel) { (action) in // Do nothing } alertController.addAction(cancelAction) let destroyAction = UIAlertAction(title: NSLocalizedString("Close parking", comment: "Close parking action in action sheet"), style: .Destructive) { [unowned self] (action) in self.closeParking(currentParking) } alertController.addAction(destroyAction) self.presentViewController(alertController, animated: true) {} } // MARK: - private func showError(error: NSError?, errorMessage: String?) { if let currentError = error { print("Error: \(currentError.localizedDescription)") } self.showErrorView(errorMessage, animated:false) } // MARK: - service calls private let kErrorLoadingParkingText = NSLocalizedString("Error loading parking. Try again please.", comment: "error loading parking") private func loadParking() { guard let currentLicensePlate = licensePlate.currentLicensePlate else { self.showError(nil,errorMessage: kErrorLoadingParkingText) return } self.showLoadingView(kLoadingParkingText, animated: false) service.getOpenParking(currentLicensePlate) { [unowned self] (result) -> Void in do { let parking = try result() self.parking = parking self.parkingInformationViewController?.parking = self.parking self.parkingInformationViewController?.reloadParking() self.closeButton.enabled = true self.hideLoadingView(animated: true) } catch ServiceError.ResponseErrorMessage(let errorMessage){ self.showError(nil,errorMessage: errorMessage) } catch let error { self.showError(error as NSError, errorMessage: self.kErrorLoadingParkingText) } } } private let kErrorLoadingClosingText = NSLocalizedString("Error closing parking. Refresh and try again please.", comment: "error closing parking") private let kClosingParkingText = NSLocalizedString("Closing parking", comment: "closing parking message in close parking") private let kSuccessClosingParkingText = NSLocalizedString("Parking successfully closed", comment: "parking successfully closed message in close parking") private func closeParking(parking: Parking) { self.showLoadingView(kClosingParkingText, animated: false) service.closeParking(parking) { [unowned self] (result) -> Void in do { try result() self.showSuccessView(self.kSuccessClosingParkingText, animated: false) } catch let error { if let serviceError = error as? ServiceError { switch serviceError { case .ResponseSuccessfullMessage: self.showSuccessView(self.kSuccessClosingParkingText, animated: false) default: self.showError(error as NSError, errorMessage: self.kErrorLoadingClosingText) } } else { self.showError(error as NSError, errorMessage: self.kErrorLoadingClosingText) } } } } }
apache-2.0
17ecfec27a3e948273957bafc334172a
33.786585
212
0.623488
5.665343
false
false
false
false
jfrowies/iEMI
iEMI/ParkingLocation.swift
1
1179
// // ParkingLocation.swift // iEMI // // Created by Fer Rowies on 8/22/15. // Copyright © 2015 Rowies. All rights reserved. // import UIKit class ParkingLocation: Parking { var fullAddress: String? var streetId: String? var streetName: String? var streetNumberMin: String? var streetNumberMax: String? var streetSide: String? var parkingSpace: String? var parkingSpaceZone: String? var streetNameAndNumber: String? { get { return fullAddress?.stringByReplacingOccurrencesOfString(", Resistencia, Chaco", withString: "") } } override init(json:[String:AnyObject]) { super.init(json: json) fullAddress = json["TarAddress"]?.description streetId = json["TarCallecod"]?.description streetName = json["TarCalleDenom"]?.description streetNumberMin = json["TarCalleDesde"]?.description streetNumberMax = json["TarCalleHasta"]?.description streetSide = json["TarCalleMano"]?.description parkingSpace = json["TarPostaNro"]?.description parkingSpaceZone = json["TarPostaZona"]?.description } }
apache-2.0
298c396e16aa89aad7ba8fb3ae63bc71
26.395349
108
0.646859
4.362963
false
false
false
false
phatblat/realm-cocoa
RealmSwift/Tests/ObjectIdTests.swift
2
3581
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift class ObjectIdTests: TestCase { func testObjectIdInitialization() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) XCTAssertEqual(objectId.stringValue, strValue) XCTAssertEqual(strValue, objectId.stringValue) let now = Date() let objectId2 = ObjectId(timestamp: now, machineId: 10, processId: 20) XCTAssertEqual(Int(now.timeIntervalSince1970), Int(objectId2.timestamp.timeIntervalSince1970)) } func testObjectIdComparision() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) let strValue2 = "000123450000ffbeef91906d" let objectId2 = try! ObjectId(string: strValue2) let strValue3 = "000123450000ffbeef91906c" let objectId3 = try! ObjectId(string: strValue3) XCTAssertTrue(objectId != objectId2) XCTAssertTrue(objectId == objectId3) } func testObjectIdGreaterThan() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) let strValue2 = "000123450000ffbeef91906d" let objectId2 = try! ObjectId(string: strValue2) let strValue3 = "000123450000ffbeef91906c" let objectId3 = try! ObjectId(string: strValue3) XCTAssertTrue(objectId2 > objectId) XCTAssertFalse(objectId > objectId3) } func testObjectIdGreaterThanOrEqualTo() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) let strValue2 = "000123450000ffbeef91906d" let objectId2 = try! ObjectId(string: strValue2) let strValue3 = "000123450000ffbeef91906c" let objectId3 = try! ObjectId(string: strValue3) XCTAssertTrue(objectId2 >= objectId) XCTAssertTrue(objectId >= objectId3) } func testObjectIdLessThan() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) let strValue2 = "000123450000ffbeef91906d" let objectId2 = try! ObjectId(string: strValue2) let strValue3 = "000123450000ffbeef91906c" let objectId3 = try! ObjectId(string: strValue3) XCTAssertTrue(objectId < objectId2) XCTAssertFalse(objectId < objectId3) } func testObjectIdLessThanOrEqualTo() { let strValue = "000123450000ffbeef91906c" let objectId = try! ObjectId(string: strValue) let strValue2 = "000123450000ffbeef91906d" let objectId2 = try! ObjectId(string: strValue2) let strValue3 = "000123450000ffbeef91906c" let objectId3 = try! ObjectId(string: strValue3) XCTAssertTrue(objectId <= objectId2) XCTAssertTrue(objectId <= objectId3) } }
apache-2.0
542e965df45df8b5c5bcf023f6ac6773
33.432692
102
0.66043
4.431931
false
true
false
false
OscarSwanros/swift
test/refactoring/ExtractFunction/static.swift
5
564
class C { func foo1() -> Int { var a = 3 + 1 a = 3 return a } static func foo2() -> Int { var a = 3 + 1 a = 3 return a } } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -extract-function -source-filename %s -pos=3:1 -end-pos=5:13 >> %t.result/L3-5.swift // RUN: diff -u %S/Outputs/static/L3-5.swift.expected %t.result/L3-5.swift // RUN: %refactor -extract-function -source-filename %s -pos=9:1 -end-pos=11:13 >> %t.result/L9-11.swift // RUN: diff -u %S/Outputs/static/L9-11.swift.expected %t.result/L9-11.swift
apache-2.0
13fa8666a7f3abf0521dea5da5bde1ce
28.684211
104
0.60461
2.506667
false
false
false
false
DopamineLabs/DopamineKit-iOS
BoundlessKit/Classes/Integration/HttpClients/Data/Storage/Records/BKDecision.swift
1
1298
// // BKDecision.swift // BoundlessKit // // Created by Akash Desai on 3/8/18. // import Foundation internal class BKDecision : NSObject, BKData { static var neutral: String = "neutralResponse" class func neutral(for actionID: String) -> BKDecision { return BKDecision(neutral, BKRefreshCartridge.neutralCartridgeId, actionID) } let name: String let cartridgeID: String let actionID: String init(_ name: String, _ cartridgeID: String, _ actionID: String) { self.name = name self.cartridgeID = cartridgeID self.actionID = actionID } public required convenience init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let cartridgeID = aDecoder.decodeObject(forKey: "cartridgeID") as? String, let actionID = aDecoder.decodeObject(forKey: "actionID") as? String else { return nil } self.init(name, cartridgeID, actionID) } public func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(cartridgeID, forKey: "cartridgeID") aCoder.encode(actionID, forKey: "actionID") } }
mit
c9e34bc1a6e86176b6bd87db6c2013fe
27.217391
86
0.61094
4.187097
false
false
false
false
ivngar/TDD-TodoList
TDD-TodoList/Controller/ItemListViewController.swift
1
961
// // ItemListViewController.swift // TDD-TodoList // // Created by Ivan Garcia on 22/6/17. // Copyright © 2017 Ivan Garcia. All rights reserved. // import UIKit class ItemListViewController: UIViewController { @IBOutlet var tableView: UITableView! @IBOutlet var dataProvider: (UITableViewDataSource & UITableViewDelegate & ItemManagerSettable)! let itemManager = ItemManager() override func viewDidLoad() { tableView.dataSource = dataProvider tableView.delegate = dataProvider dataProvider.itemManager = itemManager } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } @IBAction func addItem(_ sender: UIBarButtonItem) { if let nextViewController = storyboard?.instantiateViewController(withIdentifier: "InputViewController") as? InputViewController { nextViewController.itemManager = self.itemManager present(nextViewController, animated: true, completion: nil) } } }
mit
a48fc683456a813a0e96022d315ead42
29
134
0.745833
4.948454
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/InteractiveNotifications/MMNotificationAction.swift
1
8038
// // NotificationAction.swift // // Created by okoroleva on 27.07.17. // // import UserNotifications @objcMembers public class MMNotificationAction: NSObject { public static var DismissActionId: String { return UNNotificationDismissActionIdentifier } public static var DefaultActionId: String { return UNNotificationDefaultActionIdentifier } public let identifier: String public let title: String public let options: [MMNotificationActionOptions] public var isTapOnNotificationAlert: Bool { return identifier == MMNotificationAction.DefaultActionId } class func makeAction(dictionary: [String: Any]) -> MMNotificationAction? { if let _ = dictionary[Consts.Interaction.ActionKeys.textInputActionButtonTitle] as? String, let _ = dictionary[Consts.Interaction.ActionKeys.textInputPlaceholder] as? String { return MMTextInputNotificationAction(dictionary: dictionary) } else { return MMNotificationAction(dictionary: dictionary) } } /// Initializes the `MMNotificationAction` /// - parameter identifier: action identifier. "mm_" prefix is reserved for Mobile Messaging ids and cannot be used as a prefix. /// - parameter title: Title of the button which will be displayed. /// - parameter options: Options with which to perform the action. convenience public init?(identifier: String, title: String, options: [MMNotificationActionOptions]?) { guard !identifier.hasPrefix(Consts.Interaction.ActionKeys.mm_prefix) else { return nil } self.init(actionIdentifier: identifier, title: title, options: options) } init(actionIdentifier: String, title: String, options: [MMNotificationActionOptions]?) { self.identifier = actionIdentifier self.title = title self.options = options ?? [] } class func dismissAction(title: String = MMLocalization.localizedString(forKey: "mm_button_cancel", defaultString: "Cancel")) -> MMNotificationAction { return MMNotificationAction(actionIdentifier: DismissActionId, title: title, options: nil) } class func openAction(title: String = MMLocalization.localizedString(forKey: "mm_button_open", defaultString: "Open")) -> MMNotificationAction { return MMNotificationAction(actionIdentifier: DefaultActionId, title: title, options: [MMNotificationActionOptions.foreground]) } class var defaultAction: MMNotificationAction { return MMNotificationAction(actionIdentifier: DefaultActionId, title: "", options: nil) } var unUserNotificationAction: UNNotificationAction { var actionOptions: UNNotificationActionOptions = [] if options.contains(.foreground) { actionOptions.insert(.foreground) } if options.contains(.destructive) { actionOptions.insert(.destructive) } if options.contains(.authenticationRequired) { actionOptions.insert(.authenticationRequired) } return UNNotificationAction(identifier: identifier, title: title, options: actionOptions) } public override var hash: Int { return identifier.hashValue } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? MMNotificationAction else { return false } return identifier == object.identifier } fileprivate init?(dictionary: [String: Any]) { guard let identifier = dictionary[Consts.Interaction.ActionKeys.identifier] as? String, let title = dictionary[Consts.Interaction.ActionKeys.title] as? String else { return nil } var opts = [MMNotificationActionOptions]() if let isForeground = dictionary[Consts.Interaction.ActionKeys.foreground] as? Bool, isForeground { opts.append(.foreground) } if let isAuthRequired = dictionary[Consts.Interaction.ActionKeys.authenticationRequired] as? Bool, isAuthRequired { opts.append(.authenticationRequired) } if let isDestructive = dictionary[Consts.Interaction.ActionKeys.destructive] as? Bool, isDestructive { opts.append(.destructive) } if let isMoRequired = dictionary[Consts.Interaction.ActionKeys.moRequired] as? Bool, isMoRequired { opts.append(.moRequired) } let locTitleKey = dictionary[Consts.Interaction.ActionKeys.titleLocalizationKey] as? String self.identifier = identifier self.title = MMLocalization.localizedString(forKey: locTitleKey, defaultString: title) self.options = opts } } /// Allows text input from the user public final class MMTextInputNotificationAction: MMNotificationAction { public let textInputActionButtonTitle: String public let textInputPlaceholder: String ///Text which was entered in response to action. public var typedText: String? /// Initializes the `TextInputNotificationAction` /// - parameter identifier: action identifier. "mm_" prefix is reserved for Mobile Messaging ids and cannot be used as a prefix. /// - parameter title: Title of the button which will be displayed. /// - parameter options: Options with which to perform the action. /// - parameter textInputActionButtonTitle: Title of the text input action button /// - parameter textInputPlaceholder: Placeholder in the text input field. public init?(identifier: String, title: String, options: [MMNotificationActionOptions]?, textInputActionButtonTitle: String, textInputPlaceholder: String) { guard !identifier.hasPrefix(Consts.Interaction.ActionKeys.mm_prefix) else { return nil } self.textInputActionButtonTitle = textInputActionButtonTitle self.textInputPlaceholder = textInputPlaceholder super.init(actionIdentifier: identifier, title: title, options: options) } fileprivate override init?(dictionary: [String: Any]) { guard let textInputActionButtonTitle = dictionary[Consts.Interaction.ActionKeys.textInputActionButtonTitle] as? String, let textInputPlaceholder = dictionary[Consts.Interaction.ActionKeys.textInputPlaceholder] as? String else { return nil } self.textInputActionButtonTitle = textInputActionButtonTitle self.textInputPlaceholder = textInputPlaceholder super.init(dictionary: dictionary) } override var unUserNotificationAction: UNNotificationAction { var actionOptions: UNNotificationActionOptions = [] if options.contains(.foreground) { actionOptions.insert(.foreground) } if options.contains(.destructive) { actionOptions.insert(.destructive) } if options.contains(.authenticationRequired) { actionOptions.insert(.authenticationRequired) } return UNTextInputNotificationAction(identifier: identifier, title: title, options: actionOptions, textInputButtonTitle: textInputActionButtonTitle, textInputPlaceholder: textInputPlaceholder) } } @objcMembers public final class MMNotificationActionOptions : NSObject { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } public init(options: [MMNotificationActionOptions]) { self.rawValue = options.reduce(0) { (total, option) -> Int in return total | option.rawValue } } public func contains(options: MMLogOutput) -> Bool { return rawValue & options.rawValue != 0 } /// Causes the launch of the application. public static let foreground = MMNotificationActionOptions(rawValue: 0) /// Marks the action button as destructive. public static let destructive = MMNotificationActionOptions(rawValue: 1 << 0) /// Requires the device to be unlocked. /// - remark: If the action options contains `.foreground`, then the action is considered as requiring authentication automatically. public static let authenticationRequired = MMNotificationActionOptions(rawValue: 1 << 1) /// Indicates whether the SDK must generate MO message to report on users interaction. public static let moRequired = MMNotificationActionOptions(rawValue: 1 << 2) /// Indicates whether action is compatible with chat messages. If it is compatible, the action button will be shown in the SDK buil-in chat view. public static let chatCompatible = MMNotificationActionOptions(rawValue: 1 << 3) }
apache-2.0
105fad96b8ad13b17574fc0f72ab331f
38.99005
200
0.752177
4.580057
false
false
false
false
cristiannomartins/Tree-Sets
Tree Sets/PokemonSetsCell.swift
1
5429
// // PokemonSetsCell.swift // Tree Sets // // Created by Cristianno Vieira on 24/01/17. // Copyright © 2017 Cristianno Vieira. All rights reserved. // import UIKit class PokemonSetsCell: UITableViewCell { @IBOutlet weak var hpTotal: UILabel! @IBOutlet weak var atkTotal: UILabel! @IBOutlet weak var defTotal: UILabel! @IBOutlet weak var spaTotal: UILabel! @IBOutlet weak var spdTotal: UILabel! @IBOutlet weak var speTotal: UILabel! @IBOutlet weak var firstAbility: UILabel! @IBOutlet weak var secondAbility: UILabel! @IBOutlet weak var hiddenAbility: UILabel! @IBOutlet weak var nature: UILabel! @IBOutlet weak var holdItem: UILabel! @IBOutlet weak var move1: UILabel! @IBOutlet weak var move2: UILabel! @IBOutlet weak var move3: UILabel! @IBOutlet weak var move4: UILabel! // @IBOutlet weak var hpBar: UIProgressView! // @IBOutlet weak var atkBar: UIProgressView! // @IBOutlet weak var defBar: UIProgressView! // @IBOutlet weak var spaBar: UIProgressView! // @IBOutlet weak var spdBar: UIProgressView! // @IBOutlet weak var speBar: UIProgressView! @IBOutlet weak var hpLabel: UILabel! @IBOutlet weak var atkLabel: UILabel! @IBOutlet weak var defLabel: UILabel! @IBOutlet weak var spaLabel: UILabel! @IBOutlet weak var spdLabel: UILabel! @IBOutlet weak var speLabel: UILabel! //@IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var itemImage: UIButton! @IBOutlet weak var pkmImage: UIImageView! @IBOutlet weak var pkmSetID: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } enum Stats: Int { case hp = 0 case atk case def case spa case spd case spe } func removeItem (statsBuff: [Int]) { switch holdItem.text! { // reset atk case "Choice Band", "Muscle Band", "Thick Club": atkTotal.text = "\(statsBuff[Stats.atk.rawValue])" case "Cell Battery", "Liechi Berry", "Snowball": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 1.5)))" case "Life Orb": atkTotal.text = "\(statsBuff[Stats.atk.rawValue])" spaTotal.text = "\(statsBuff[Stats.spa.rawValue])" case "Weakness Policy": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 2.0)))" spaTotal.text = "\(Int(floor(Double(statsBuff[Stats.spa.rawValue]) * 2.0)))" // reset def case "Ganlon Berry", "Kee Berry": defTotal.text = "\(Int(floor(Double(statsBuff[Stats.def.rawValue]) * 1.5)))" // reset spa case "Choice Specs", "Wise Glasses": spaTotal.text = "\(statsBuff[Stats.spa.rawValue])" case "Absorb Bulb", "Petaya Berry": spaTotal.text = "\(Int(floor(Double(statsBuff[Stats.spa.rawValue]) * 1.5)))" // reset spd case "Apicot Berry", "Luminous Moss", "Maranga Berry": spdTotal.text = "\(Int(floor(Double(statsBuff[Stats.spd.rawValue]) * 1.5)))" case "Assault Vest": spdTotal.text = "\(statsBuff[Stats.spd.rawValue])" // reset spe case "Choice Scarf", "Iron Ball": speTotal.text = "\(statsBuff[Stats.spe.rawValue])" case "Salac Berry": speTotal.text = "\(Int(floor(Double(statsBuff[Stats.spe.rawValue]) * 1.5)))" default: break } } func addItem(statsBuff: [Int]) { switch holdItem.text! { // set atk case "Choice Band": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 1.5)))" case "Cell Battery", "Liechi Berry", "Snowball": atkTotal.text = "\(statsBuff[Stats.atk.rawValue])" case "Life Orb": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 1.3)))" spaTotal.text = "\(Int(floor(Double(statsBuff[Stats.spa.rawValue]) * 1.3)))" case "Muscle Band": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 1.1)))" //FIXME: Thick Club only boosts cubone's or marowak's attack case "Thick Club": atkTotal.text = "\(Int(floor(Double(statsBuff[Stats.atk.rawValue]) * 2.0)))" case "Weakness Policy": atkTotal.text = "\(statsBuff[Stats.atk.rawValue])" spaTotal.text = "\(statsBuff[Stats.spa.rawValue])" //set def case "Ganlon Berry", "Kee Berry": defTotal.text = "\(statsBuff[Stats.def.rawValue])" // set spa case "Choice Specs": spaTotal.text = "\(Int(floor(Double(statsBuff[Stats.spa.rawValue]) * 1.5)))" case "Absorb Bulb", "Petaya Berry": spaTotal.text = "\(statsBuff[Stats.spa.rawValue])" case "Wise Glasses": spaTotal.text = "\(Int(floor(Double(statsBuff[Stats.spa.rawValue]) * 1.1)))" // set spd case "Apicot Berry", "Luminous Moss", "Maranga Berry": spdTotal.text = "\(statsBuff[Stats.spd.rawValue])" case "Assault Vest": spdTotal.text = "\(Int(floor(Double(statsBuff[Stats.spd.rawValue]) * 1.5)))" // set spe case "Choice Scarf": speTotal.text = "\(Int(floor(Double(statsBuff[Stats.spe.rawValue]) * 1.5)))" case "Iron Ball": speTotal.text = "\(Int(floor(Double(statsBuff[Stats.spe.rawValue]) / 2.0)))" case "Salac Berry": speTotal.text = "\(statsBuff[Stats.spe.rawValue])" default: break } } }
mit
e02416fac3abaccb43e92a7bb0dbd653
33.138365
82
0.645173
3.510996
false
false
false
false
Jauzee/showroom
Showroom/ViewControllers/ThingersTapViewController/ThingersTapViewController.swift
2
2481
import UIKit class ThingersTapViewController: UIViewController { @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var hand: UIImageView! @IBOutlet weak var handTouches: UIImageView! @IBOutlet weak var infoTextLabel: UILabel! fileprivate var presenter: PopUpPresenter? } // MARK: Life Cycle extension ThingersTapViewController { override func viewDidLoad() { super.viewDidLoad() backgroundView.layer.cornerRadius = 5 backgroundView.layer.masksToBounds = true handTouches.alpha = 0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) heandAnimation() configureInfoLabel() } override open var shouldAutorotate: Bool { return false } } private var isAlredyShow = false // MARK: Methods extension ThingersTapViewController { class func showPopup(on: UIViewController) { if isAlredyShow == true { return } isAlredyShow = true let storybord = UIStoryboard(storyboard: .Navigation) let vc: ThingersTapViewController = storybord.instantiateViewController() vc.presenter = PopUpPresenter(controller: vc, on: on, showTransition: ShowAlphaModalTransition(duration: 1), hideTransition: HideAlphaModalTransition(duration: 0.8)) } } // MARK: Configure extension ThingersTapViewController { func configureInfoLabel() { guard let text = infoTextLabel.text else { return } let style = NSMutableParagraphStyle() style.lineSpacing = 3 style.alignment = .center let attributedText = text.withAttributes([.paragraphStyle(style)]) infoTextLabel.attributedText = attributedText } } // MARK: Animations private extension ThingersTapViewController { func heandAnimation() { hand.animate(duration: 0.1, delay: 0.6, [.layerScale(from: 1, to: 1.1)], timing: .easyIn) hand.animate(duration: 0, delay: 0.7, [.springScale(from: 1.1, to: 1, bounce: 9, spring: 5)]) handTouches.animate(duration: 0.4, delay: 0.9, [.alphaFrom(0, to: 1, removed: false)], timing: .linear) handTouches.animate(duration: 0.4, delay: 1.3, [.alphaFrom(1, to: 0, removed: false)], timing: .linear) handTouches.animate(duration: 0.4, delay: 1.7, [.alphaFrom(0, to: 1, removed: false)], timing: .linear) } } // MARK: Actions extension ThingersTapViewController { @IBAction func GotItHandler(_ sender: Any) { dismiss(animated: true, completion: nil) } }
gpl-3.0
d72eca3f9a4db9cc001173f46996a220
27.193182
107
0.695284
4.080592
false
false
false
false
WebberLai/WLComics
Pods/SwiftyDropbox/Source/SwiftyDropbox/Shared/Handwritten/DropboxTransportClient.swift
1
25368
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Foundation import Alamofire open class DropboxTransportClient { public let manager: SessionManager public let backgroundManager: SessionManager public let longpollManager: SessionManager open var accessToken: String open var selectUser: String? open var pathRoot: Common.PathRoot? var baseHosts: [String: String] var userAgent: String public convenience init(accessToken: String, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil) { self.init(accessToken: accessToken, baseHosts: nil, userAgent: nil, selectUser: selectUser, pathRoot: pathRoot) } public init(accessToken: String, baseHosts: [String: String]?, userAgent: String?, selectUser: String?, sessionDelegate: SessionDelegate? = nil, backgroundSessionDelegate: SessionDelegate? = nil, longpollSessionDelegate: SessionDelegate? = nil, serverTrustPolicyManager: ServerTrustPolicyManager? = nil, sharedContainerIdentifier: String? = nil, pathRoot: Common.PathRoot? = nil) { let config = URLSessionConfiguration.default let delegate = sessionDelegate ?? SessionDelegate() let serverTrustPolicyManager = serverTrustPolicyManager ?? nil let manager = SessionManager(configuration: config, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager) manager.startRequestsImmediately = false let backgroundManager = { () -> SessionManager in let backgroundConfig = URLSessionConfiguration.background(withIdentifier: "com.dropbox.SwiftyDropbox." + UUID().uuidString) if let sharedContainerIdentifier = sharedContainerIdentifier{ backgroundConfig.sharedContainerIdentifier = sharedContainerIdentifier } if let backgroundSessionDelegate = backgroundSessionDelegate { return SessionManager(configuration: backgroundConfig, delegate: backgroundSessionDelegate, serverTrustPolicyManager: serverTrustPolicyManager) } return SessionManager(configuration: backgroundConfig, serverTrustPolicyManager: serverTrustPolicyManager) }() backgroundManager.startRequestsImmediately = false let longpollConfig = URLSessionConfiguration.default longpollConfig.timeoutIntervalForRequest = 480.0 let longpollSessionDelegate = longpollSessionDelegate ?? SessionDelegate() let longpollManager = SessionManager(configuration: longpollConfig, delegate: longpollSessionDelegate, serverTrustPolicyManager: serverTrustPolicyManager) let defaultBaseHosts = [ "api": "https://api.dropbox.com/2", "content": "https://api-content.dropbox.com/2", "notify": "https://notify.dropboxapi.com/2", ] let defaultUserAgent = "OfficialDropboxSwiftSDKv2/\(Constants.versionSDK)" self.manager = manager self.backgroundManager = backgroundManager self.longpollManager = longpollManager self.accessToken = accessToken self.selectUser = selectUser self.pathRoot = pathRoot; self.baseHosts = baseHosts ?? defaultBaseHosts if let userAgent = userAgent { let customUserAgent = "\(userAgent)/\(defaultUserAgent)" self.userAgent = customUserAgent } else { self.userAgent = defaultUserAgent } } open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType? = nil) -> RpcRequest<RSerial, ESerial> { let host = route.attrs["host"]! ?? "api" var routeName = route.name if route.version > 1 { routeName = String(format: "%@_v%d", route.name, route.version) } let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(routeName)" let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)! var rawJsonRequest: Data? rawJsonRequest = nil if let serverArgs = serverArgs { let jsonRequestObj = route.argSerializer.serialize(serverArgs) rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj) } else { let voidSerializer = route.argSerializer as! VoidSerializer let jsonRequestObj = voidSerializer.serialize(()) rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj) } let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host) let customEncoding = SwiftyArgEncoding(rawJsonRequest: rawJsonRequest!) let managerToUse = { () -> SessionManager in // longpoll requests have a much longer timeout period than other requests if type(of: route) == type(of: Files.listFolderLongpoll) { return self.longpollManager } return self.manager }() let request = managerToUse.request(url, method: .post, parameters: ["jsonRequest": rawJsonRequest!], encoding: customEncoding, headers: headers) request.task?.priority = URLSessionTask.highPriority let rpcRequestObj = RpcRequest(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer) request.resume() return rpcRequestObj } struct SwiftyArgEncoding: ParameterEncoding { fileprivate let rawJsonRequest: Data init(rawJsonRequest: Data) { self.rawJsonRequest = rawJsonRequest } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = urlRequest.urlRequest urlRequest!.httpBody = rawJsonRequest return urlRequest! } } open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType, input: UploadBody) -> UploadRequest<RSerial, ESerial> { let host = route.attrs["host"]! ?? "api" var routeName = route.name if route.version > 1 { routeName = String(format: "%@_v%d", route.name, route.version) } let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(routeName)" let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)! let jsonRequestObj = route.argSerializer.serialize(serverArgs) let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj) let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host) let request: Alamofire.UploadRequest switch input { case let .data(data): request = self.manager.upload(data, to: url, method: .post, headers: headers) case let .file(file): request = self.backgroundManager.upload(file, to: url, method: .post, headers: headers) case let .stream(stream): request = self.manager.upload(stream, to: url, method: .post, headers: headers) } let uploadRequestObj = UploadRequest(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer) request.resume() return uploadRequestObj } open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType, overwrite: Bool, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<RSerial, ESerial> { let host = route.attrs["host"]! ?? "api" var routeName = route.name if route.version > 1 { routeName = String(format: "%@_v%d", route.name, route.version) } let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(routeName)" let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)! let jsonRequestObj = route.argSerializer.serialize(serverArgs) let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj) let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host) weak var _self: DownloadRequestFile<RSerial, ESerial>! let destinationWrapper: DownloadRequest.DownloadFileDestination = { url, resp in var finalUrl = destination(url, resp) if 200 ... 299 ~= resp.statusCode { if FileManager.default.fileExists(atPath: finalUrl.path) { if overwrite { do { try FileManager.default.removeItem(at: finalUrl) } catch let error as NSError { print("Error: \(error)") } } else { print("Error: File already exists at \(finalUrl.path)") } } } else { _self.errorMessage = try! Data(contentsOf: url) // Alamofire will "move" the file to the temporary location where it already resides, // and where it will soon be automatically deleted finalUrl = url } _self.urlPath = finalUrl return (finalUrl, []) } let request = self.backgroundManager.download(url, method: .post, headers: headers, to: destinationWrapper) let downloadRequestObj = DownloadRequestFile(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer) _self = downloadRequestObj request.resume() return downloadRequestObj } public func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType) -> DownloadRequestMemory<RSerial, ESerial> { let host = route.attrs["host"]! ?? "api" let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(route.name)" let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)! let jsonRequestObj = route.argSerializer.serialize(serverArgs) let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj) let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host) let request = self.backgroundManager.request(url, method: .post, headers: headers) let downloadRequestObj = DownloadRequestMemory(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer) request.resume() return downloadRequestObj } fileprivate func getHeaders(_ routeStyle: RouteStyle, jsonRequest: Data?, host: String) -> HTTPHeaders { var headers = ["User-Agent": self.userAgent] let noauth = (host == "notify") if (!noauth) { headers["Authorization"] = "Bearer \(self.accessToken)" if let selectUser = self.selectUser { headers["Dropbox-Api-Select-User"] = selectUser } if let pathRoot = self.pathRoot { let obj = Common.PathRootSerializer().serialize(pathRoot) headers["Dropbox-Api-Path-Root"] = utf8Decode(SerializeUtil.dumpJSON(obj)!) } } if (routeStyle == RouteStyle.Rpc) { headers["Content-Type"] = "application/json" } else if (routeStyle == RouteStyle.Upload) { headers["Content-Type"] = "application/octet-stream" if let jsonRequest = jsonRequest { let value = asciiEscape(utf8Decode(jsonRequest)) headers["Dropbox-Api-Arg"] = value } } else if (routeStyle == RouteStyle.Download) { if let jsonRequest = jsonRequest { let value = asciiEscape(utf8Decode(jsonRequest)) headers["Dropbox-Api-Arg"] = value } } return headers } } open class Box<T> { public let unboxed: T init (_ v: T) { self.unboxed = v } } public enum CallError<EType>: CustomStringConvertible { case internalServerError(Int, String?, String?) case badInputError(String?, String?) case rateLimitError(Auth.RateLimitError, String?, String?, String?) case httpError(Int?, String?, String?) case authError(Auth.AuthError, String?, String?, String?) case accessError(Auth.AccessError, String?, String?, String?) case routeError(Box<EType>, String?, String?, String?) case clientError(Error?) public var description: String { switch self { case let .internalServerError(code, message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "Internal Server Error \(code)" if let m = message { ret += ": \(m)" } return ret case let .badInputError(message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "Bad Input" if let m = message { ret += ": \(m)" } return ret case let .authError(error, _, _, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "API auth error - \(error)" return ret case let .accessError(error, _, _, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "API access error - \(error)" return ret case let .httpError(code, message, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "HTTP Error" if let c = code { ret += "\(c)" } if let m = message { ret += ": \(m)" } return ret case let .routeError(box, _, _, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "API route error - \(box.unboxed)" return ret case let .rateLimitError(error, _, _, requestId): var ret = "" if let r = requestId { ret += "[request-id \(r)] " } ret += "API rate limit error - \(error)" return ret case let .clientError(err): if let e = err { return "\(e)" } return "An unknown system error" } } } func utf8Decode(_ data: Data) -> String { return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String } func asciiEscape(_ s: String) -> String { var out: String = "" for char in s.unicodeScalars { var esc = "\(char)" if !char.isASCII { esc = NSString(format:"\\u%04x", char.value) as String } else { esc = "\(char)" } out += esc } return out } public enum RouteStyle: String { case Rpc = "rpc" case Upload = "upload" case Download = "download" case Other } public enum UploadBody { case data(Data) case file(URL) case stream(InputStream) } /// These objects are constructed by the SDK; users of the SDK do not need to create them manually. /// /// Pass in a closure to the `response` method to handle a response or error. open class Request<RSerial: JSONSerializer, ESerial: JSONSerializer> { let responseSerializer: RSerial let errorSerializer: ESerial init(responseSerializer: RSerial, errorSerializer: ESerial) { self.errorSerializer = errorSerializer self.responseSerializer = responseSerializer } func handleResponseError(_ response: HTTPURLResponse?, data: Data?, error: Error?) -> CallError<ESerial.ValueType> { let requestId = response?.allHeaderFields["X-Dropbox-Request-Id"] as? String if let code = response?.statusCode { switch code { case 500...599: var message = "" if let d = data { message = utf8Decode(d) } return .internalServerError(code, message, requestId) case 400: var message = "" if let d = data { message = utf8Decode(d) } return .badInputError(message, requestId) case 401: let json = SerializeUtil.parseJSON(data!) switch json { case .dictionary(let d): return .authError(Auth.AuthErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId) default: fatalError("Failed to parse error type") } case 403: let json = SerializeUtil.parseJSON(data!) switch json { case .dictionary(let d): return .accessError(Auth.AccessErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"),requestId) default: fatalError("Failed to parse error type") } case 409: let json = SerializeUtil.parseJSON(data!) switch json { case .dictionary(let d): return .routeError(Box(self.errorSerializer.deserialize(d["error"]!)), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId) default: fatalError("Failed to parse error type") } case 429: let json = SerializeUtil.parseJSON(data!) switch json { case .dictionary(let d): return .rateLimitError(Auth.RateLimitErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId) default: fatalError("Failed to parse error type") } case 200: return .clientError(error) default: return .httpError(code, "An error occurred.", requestId) } } else if response == nil { return .clientError(error) } else { var message = "" if let d = data { message = utf8Decode(d) } return .httpError(nil, message, requestId) } } func getStringFromJson(json: [String : JSON], key: String) -> String { if let jsonStr = json[key] { switch jsonStr { case .str(let str): return str; default: break; } } return ""; } } /// An "rpc-style" request open class RpcRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> { public let request: Alamofire.DataRequest public init(request: Alamofire.DataRequest, responseSerializer: RSerial, errorSerializer: ESerial) { self.request = request super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer) } open func cancel() { self.request.cancel() } @discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void) -> Self { self.request.validate().response(queue: queue) { response in if let error = response.error { completionHandler(nil, self.handleResponseError(response.response, data: response.data!, error: error)) } else { completionHandler(self.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil) } } return self } } /// An "upload-style" request open class UploadRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> { public let request: Alamofire.UploadRequest public init(request: Alamofire.UploadRequest, responseSerializer: RSerial, errorSerializer: ESerial) { self.request = request super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer) } @discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self { self.request.uploadProgress { progressData in progressHandler(progressData) } return self } open func cancel() { self.request.cancel() } @discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void) -> Self { self.request.validate().response(queue: queue) { response in if let error = response.error { completionHandler(nil, self.handleResponseError(response.response, data: response.data!, error: error)) } else { completionHandler(self.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil) } } return self } } /// A "download-style" request to a file open class DownloadRequestFile<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> { public let request: Alamofire.DownloadRequest open var urlPath: URL? open var errorMessage: Data public init(request: Alamofire.DownloadRequest, responseSerializer: RSerial, errorSerializer: ESerial) { self.request = request urlPath = nil errorMessage = Data() super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer) } @discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self { self.request.downloadProgress { progressData in progressHandler(progressData) } return self } open func cancel() { self.request.cancel() } @discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping ((RSerial.ValueType, URL)?, CallError<ESerial.ValueType>?) -> Void) -> Self { self.request.validate().response(queue: queue) { response in if let error = response.error { completionHandler(nil, self.handleResponseError(response.response, data: self.errorMessage, error: error)) } else { let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)! let resultData = result.data(using: .utf8, allowLossyConversion: false) let resultObject = self.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!)) completionHandler((resultObject, self.urlPath!), nil) } } return self } } /// A "download-style" request to memory open class DownloadRequestMemory<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> { public let request: Alamofire.DataRequest public init(request: Alamofire.DataRequest, responseSerializer: RSerial, errorSerializer: ESerial) { self.request = request super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer) } @discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self { self.request.downloadProgress { progressData in progressHandler(progressData) } return self } open func cancel() { self.request.cancel() } @discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping ((RSerial.ValueType, Data)?, CallError<ESerial.ValueType>?) -> Void) -> Self { self.request.validate().response(queue: queue) { response in if let error = response.error { completionHandler(nil, self.handleResponseError(response.response, data: response.data, error: error)) } else { let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)! let resultData = result.data(using: .utf8, allowLossyConversion: false) let resultObject = self.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!)) completionHandler((resultObject, response.data!), nil) } } return self } } func caseInsensitiveLookup(_ lookupKey: String, dictionary: [AnyHashable : Any]) -> String? { for key in dictionary.keys { let keyString = key as! String if (keyString.lowercased() == lookupKey.lowercased()) { return dictionary[key] as? String } } return nil }
mit
0eeda9516b048023e6c2f46f06081b88
39.719101
385
0.610691
5.140426
false
false
false
false
jbannister/VirtualTourist
VirtualTourist/VirtualTourist/PhotoViewController.swift
1
3632
// // PhotoViewController.swift // VirtualTourist // // Created by Jan Bannister on 09/11/2015. // Copyright © 2015 JB. All rights reserved. // import UIKit import MapKit import CoreData class PhotoViewController: UICollectionViewController, NSFetchedResultsControllerDelegate { var pin : Location! let reuseIdCollection = "PhotoCellCollection" lazy var sharedContext: NSManagedObjectContext = { return CoreDataStack.Instance().managedObjectContext }() lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "Photo") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] fetchRequest.predicate = NSPredicate(format: "pin == %@", self.pin); let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() override func viewDidLoad() { super.viewDidLoad() self.collectionView!.registerClass(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCellCollection") let fetched = fetchedResultsController fetched.delegate = self try! fetched.performFetch() let photo = fetched.fetchedObjects as? [Photo] if photo?.count != 0 { // fix it print("Photo: \(photo?.count)") } else { CoreDataFlickr() } } func CoreDataFlickr() { Flickr().flickrPin(pin) { (photos, error) in if let p1 = photos { for photo in p1 { photo.pin = self.pin } dispatch_async(dispatch_get_main_queue()) { self.pin.photos.unionInPlace(p1) self.pin.photosArray = Array(self.pin.photos) self.collectionView!.reloadData() } } } } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pin.photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdCollection, forIndexPath: indexPath) as! PhotoCollectionViewCell cell.imageView.image = UIImage(named:"star") let photo = pin.photosArray[indexPath.row] print("Photo: \(photo)") if photo.image == nil { print("Fail") let image = pin.photosArray[indexPath.row].photoRetrieve() print("Image!:\(image)") dispatch_async(dispatch_get_main_queue(), { //cell.imageView.image! = image // Crushed :( }) } else { print("Ok") cell.imageView.image? = pin.photosArray[indexPath.row].image! } return cell } // MARK: Segue -> Pin and Coordinate Region func pinAndCoordinateRegion(pin: Location, coordinateRegion: MKCoordinateRegion) { //self.coordinate = coordinateRegion self.pin = pin } }
mit
905be480020704baade046d2cea23cc4
31.711712
144
0.601763
5.682316
false
false
false
false
ahoppen/swift
test/decl/typealias/on_constrained_protocol.swift
9
3244
// RUN: %target-typecheck-verify-swift // typealias on constrained extension protocol ConstrainedTypealias { associatedtype MyAssocType } extension ConstrainedTypealias where MyAssocType == String { // expected-note {{requirement specified as 'Self.MyAssocType' == 'String' [with Self = Self]}} (from useConstrainedTypealiasInExtension) typealias Content = String } extension ConstrainedTypealias where MyAssocType == Int { func useConstrainedTypealiasInExtension() -> Content {} // expected-error {{'Self.Content' (aka 'String') requires the types 'Int' and 'String' be equivalent}} } func useTypealiasOnConstrainedExtension() -> ConstrainedTypealias.Content {} // define different typealiases on differently constrained extensions protocol DoubleOverloadedTypealias { associatedtype MyAssocType } extension DoubleOverloadedTypealias where MyAssocType == String { // expected-note {{requirement specified as 'Self.MyAssocType' == 'String' [with Self = Self]}} (from useDoubleOverloadedTypealiasInExtension) typealias Content = String // expected-note {{found candidate with type 'String'}} (from useDoubleOverloadedTypealias) } extension DoubleOverloadedTypealias where MyAssocType == Int { typealias Content = Int // expected-note {{found candidate with type 'Int'}} (from useDoubleOverloadedTypealias) func useDoubleOverloadedTypealiasInExtension() -> Content {} // expected-error {{'Self.Content' (aka 'String') requires the types 'Int' and 'String' be equivalent}} } func useDoubleOverloadedTypealias() -> DoubleOverloadedTypealias.Content {} // expected-error {{ambiguous type name 'Content' in 'DoubleOverloadedTypealias'}} // define the same typealias on differently constrained extensions protocol DoubleOverloadedSameTypealias { associatedtype MyAssocType } extension DoubleOverloadedSameTypealias where MyAssocType == String { // expected-note {{requirement specified as 'Self.MyAssocType' == 'String' [with Self = Self]}} (from useDoubleOverloadedSameTypealiasInExtension) typealias Content = Int } extension DoubleOverloadedSameTypealias where MyAssocType == Int { typealias Content = Int func useDoubleOverloadedSameTypealiasInExtension() -> Content {} // expected-error {{'Self.Content' (aka 'Int') requires the types 'Int' and 'String' be equivalent}} } func useDoubleOverloadedSameTypealias() -> DoubleOverloadedSameTypealias.Content {} // Overload associatedtype with typealias (SR-8274) protocol MarkerProtocol {} protocol ProtocolWithAssoctype { associatedtype MyAssocType // expected-note {{found this candidate}} (from useAssocTypeInExtension) expected-note {{found candidate with type 'Self.MyAssocType'}} (from useAssocTypeOutsideExtension) } extension ProtocolWithAssoctype where Self: MarkerProtocol { typealias MyAssocType = Int // expected-note {{found this candidate}} (from useAssocTypeInExtension) expected-note {{found candidate with type 'Int'}} (from useAssocTypeOutsideExtension) func useAssocTypeInExtension() -> MyAssocType {} // expected-error {{'MyAssocType' is ambiguous for type lookup in this context}} } func useAssocTypeOutsideExtension() -> ProtocolWithAssoctype.MyAssocType {} // expected-error {{ambiguous type name 'MyAssocType' in 'ProtocolWithAssoctype'}}
apache-2.0
2be9b6eb6d72ddc74253e3a992d1e350
59.074074
216
0.788841
4.798817
false
false
false
false
totocaster/JSONFeed
Classes/JSONFeedAttachment.swift
1
1566
// // JSONFeedAttachment.swift // JSONFeed // // Created by Toto Tvalavadze on 2017/05/18. // Copyright © 2017 Toto Tvalavadze. All rights reserved. // import Foundation public struct JSONFeedAttachment { /// Specifies the location of the attachment. public let url: URL /// Specifies the type of the attachment, such as `audio/mpeg`. public let mimeType: String /// name for the attachment. /// - important: if there are multiple attachments, and two or more have the exact same title (when title is present), then they are considered as alternate representations of the same thing. In this way a podcaster, for instance, might provide an audio recording in different formats. public let title: String? /// Specifies how large the file is in *bytes*. public let size: UInt64? /// Specifies how long the attachment takes to listen to or watch in *seconds*. public let duration: UInt? // MARK: - Parsing internal init?(json: JsonDictionary) { let keys = JSONFeedSpecV1Keys.Attachment.self guard let url = URL(for: keys.url, inJson: json), let mimeType = json[keys.mimeType] as? String else { return nil } // items without id will be discarded, per spec self.url = url self.mimeType = mimeType self.title = json[keys.title] as? String self.duration = json[keys.durationSeconds] as? UInt self.size = json[keys.sizeBytes] as? UInt64 } }
mit
0b4f0f4f32a9918529f250f9f04ba081
30.938776
289
0.641534
4.347222
false
false
false
false
turekj/ReactiveTODO
ReactiveTODOFramework/Classes/Assemblies/FlowAssembly.swift
1
1814
import Foundation import Swinject import UIKit public class FlowAssembly: AssemblyType { public init() { } public func assemble(container: Container) { container.register(FlowControllerProtocol.self) { r in let configurator = r.resolve(FlowConfigurator.self, name: "main")! let rootController = r.resolve(UINavigationController.self, name: "root")! return FlowController(container: container, configurator: configurator, rootController: rootController) } container.register(UINavigationController.self, name: "root") { _ in let navigationController = UINavigationController(nibName: nil, bundle: nil) navigationController.navigationBar.translucent = false return navigationController } container.register(FlowConfigurator.self, name: "main") { r in let todoListConfigurator = r.resolve(FlowConfigurator.self, name: "todoList")! let createTODOConfigurator = r.resolve(FlowConfigurator.self, name: "createTODO")! let configurators = [todoListConfigurator, createTODOConfigurator] return AggregateFlowConfigurator(configurators: configurators) } container.register(FlowConfigurator.self, name: "todoList") { r in let dao = r.resolve(TODONoteDataAccessObjectProtocol.self)! return TODONoteListFlowConfigurator(todoNoteDAO: dao) } container.register(FlowConfigurator.self, name: "createTODO") { r in let dao = r.resolve(TODONoteDataAccessObjectProtocol.self)! return CreateTODONoteFlowConfigurator(todoNoteDAO: dao) } } }
mit
52e77aedf40d39f67492c57f84b97afc
34.568627
78
0.637817
5.304094
false
true
false
false
ta2yak/loqui
loqui/Extensions/UIColor.swift
1
2208
// // UIColor.swift // loqui // // Created by Kawasaki Tatsuya on 2017/09/04. // Copyright © 2017年 Kawasaki Tatsuya. All rights reserved. // import UIKit import MaterialComponents extension UIColor { static func mainTextColor() -> UIColor { return #colorLiteral(red: 0.2159670293, green: 0.2853322923, blue: 0.3624266684, alpha: 1) } static func subTextColor() -> UIColor { return #colorLiteral(red: 0.6812713742, green: 0.7029740214, blue: 0.7234711051, alpha: 1) } static func accentTextColor() -> UIColor { return UIColor.colorWithHexString("4CB6BE") } static func mainColor() -> UIColor { return UIColor.colorWithHexString("4CB6BE") } static func mainLightColor() -> UIColor { return UIColor.colorWithHexString("64FFDA") } static func mainDarkColor() -> UIColor { return UIColor.colorWithHexString("00BFA5") } static func subColor() -> UIColor { return #colorLiteral(red: 4.173838519e-08, green: 0.3019607365, blue: 0.2509803474, alpha: 1) } static func accentColor() -> UIColor { return #colorLiteral(red: 0.8748016953, green: 0.9442162514, blue: 0.9971715808, alpha: 1) } static func outgoingChatColor() -> UIColor { return MDCPalette.blueGrey.tint50 } static func incomingChatColor() -> UIColor { return UIColor.colorWithHexString("4CB6BE") } //# Handy function to return UIColors from Hex Strings static func colorWithHexString (_ hexStr:String) -> UIColor { let hex = hexStr.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.characters.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: return .clear } return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } }
mit
9cc6c92e7c79943213c2e5de3d2111e4
44.9375
137
0.63356
3.522364
false
false
false
false
AaronMT/firefox-ios
Storage/SyncQueue.swift
9
1991
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SwiftyJSON public struct SyncCommand: Equatable { public let value: String public var commandID: Int? public var clientGUID: GUID? let version: String? public init(value: String) { self.value = value self.version = nil self.commandID = nil self.clientGUID = nil } public init(id: Int, value: String) { self.value = value self.version = nil self.commandID = id self.clientGUID = nil } public init(id: Int?, value: String, clientGUID: GUID?) { self.value = value self.version = nil self.clientGUID = clientGUID self.commandID = id } /** * Sent displayURI commands include the sender client GUID. */ public static func displayURIFromShareItem(_ shareItem: ShareItem, asClient sender: GUID) -> SyncCommand { let jsonObj: [String: Any] = [ "command": "displayURI", "args": [shareItem.url, sender, shareItem.title ?? ""] ] return SyncCommand(value: JSON(jsonObj).stringify()!) } public func withClientGUID(_ clientGUID: String?) -> SyncCommand { return SyncCommand(id: self.commandID, value: self.value, clientGUID: clientGUID) } } public func ==(lhs: SyncCommand, rhs: SyncCommand) -> Bool { return lhs.value == rhs.value } public protocol SyncCommands { func deleteCommands() -> Success func deleteCommands(_ clientGUID: GUID) -> Success func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>> func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> }
mpl-2.0
aa8a9b80ef20709e28624ebcfae35b74
30.109375
110
0.644902
4.375824
false
false
false
false
nicolastinkl/swift
UICatalog:CreatingandCustomizingUIKitControlsinSwift/UICatalog/ButtonViewController.swift
1
3642
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to use UIButton. The buttons are created using storyboards, but each of the system buttons can be created in code by using the UIButton.buttonWithType() initializer. See the UIButton interface for a comprehensive list of the various UIButtonType values. */ import UIKit class ButtonViewController: UITableViewController { // MARK: Properties @IBOutlet var systemTextButton: UIButton @IBOutlet var systemContactAddButton: UIButton @IBOutlet var systemDetailDisclosureButton: UIButton @IBOutlet var imageButton: UIButton @IBOutlet var attributedTextButton: UIButton // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // All of the buttons are created in the storyboard, but configured below. configureSystemTextButton() configureSystemContactAddButton() configureSystemDetailDisclosureButton() configureImageButton() configureAttributedTextSystemButton() } // MARK: Configuration func configureSystemTextButton() { systemTextButton.setTitle(NSLocalizedString("Button", comment: ""), forState: .Normal) systemTextButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) } func configureSystemContactAddButton() { systemContactAddButton.backgroundColor = UIColor.clearColor() systemContactAddButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) } func configureSystemDetailDisclosureButton() { systemDetailDisclosureButton.backgroundColor = UIColor.clearColor() systemDetailDisclosureButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) } func configureImageButton() { // To create this button in code you can use UIButton.buttonWithType() with a parameter value of .Custom. // Remove the title text. imageButton.setTitle("", forState: .Normal) imageButton.tintColor = UIColor.applicationPurpleColor() imageButton.setImage(UIImage(named: "x_icon"), forState: .Normal) // Add an accessibility label to the image. imageButton.accessibilityLabel = NSLocalizedString("X Button", comment: "") imageButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) } func configureAttributedTextSystemButton() { let titleAttributes = [NSForegroundColorAttributeName: UIColor.applicationBlueColor(), NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.toRaw()] let attributedTitle = NSAttributedString(string: NSLocalizedString("Button", comment: ""), attributes: titleAttributes) attributedTextButton.setAttributedTitle(attributedTitle, forState: .Normal) let highlightedTitleAttributes = [NSForegroundColorAttributeName: UIColor.greenColor(), NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleThick.toRaw()] let highlightedAttributedTitle = NSAttributedString(string: NSLocalizedString("Button", comment: ""), attributes: highlightedTitleAttributes) attributedTextButton.setAttributedTitle(highlightedAttributedTitle, forState: .Highlighted) attributedTextButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside) } // MARK: Actions func buttonClicked(sender: UIButton) { NSLog("A button was clicked: \(sender).") } }
mit
a7b4f74b00b82b6b8b0c1b5e81132c45
40.363636
310
0.734066
5.805423
false
true
false
false
Trevi-Swift/Trevi
Sources/ServerResponse.swift
1
4398
// // ServerResponse.swift // Trevi // // Created by LeeYoseob on 2016. 3. 3.. // Copyright © 2016 Trevi Community. All rights reserved. // import Foundation // Make a response of user requests. public class ServerResponse: OutgoingMessage{ public var httpVersion: String = "" public var url: String! public var method: String! public var statusCode: Int!{ didSet{ self.status = StatusCode(rawValue: statusCode)!.statusString() } } private var _hasbody = false private var _body: String?{ didSet { self._hasbody = true var type = "text/plain; charset=utf-8" if (_body?.containsString("!DOCTYPE")) != nil || (_body?.containsString("<html>")) != nil{ type = "text/html; charset=utf-8" } header[Content_Type] = type } } private var _bodyData: NSData! { didSet{ self._hasbody = true } } //for dictionary private var bodys: [ String: String ]?{ didSet{ self._hasbody = true header[Content_Type] = "application/json" } } private var bodyData : NSData? { if let dt = _bodyData{ return dt }else if let bodyString = _body { return bodyString.dataUsingEncoding(NSUTF8StringEncoding)! }else if (bodys != nil) { #if os(Linux) let jsonData = try? NSJSONSerialization.dataWithJSONObject(bodys as! AnyObject, options:NSJSONWritingOptions(rawValue:0)) #else let jsonData = try? NSJSONSerialization.dataWithJSONObject(bodys!, options:NSJSONWritingOptions(rawValue:0)) #endif // if need jsonString, use it return jsonData } return nil } private var status: String! private var firstLine: String! public init(socket: Socket) { super.init(socket: socket) self._body = "" } public func end(){ let hData: NSData = self.prepareHeader() let result: NSMutableData = NSMutableData(data: hData) if self._hasbody { result.appendData(self.bodyData!) } self._end(result) } public func writeHead(statusCode: Int, headers: [String:String] = [:]){ self.statusCode = statusCode mergeHeader(headers) firstLine = "\(httpVersion) \(statusCode) \(status)" + CRLF } public func write(data: String, encoding: String! = nil, type: String! = ""){ _body = data _hasbody = true } public func write(data: NSData, encoding: String! = nil, type: String! = ""){ _bodyData = data if let t = type{ header[Content_Type] = t } _hasbody = true } public func write(data: [String : String], encoding: String! = nil, type: String! = ""){ bodys = data _hasbody = true } /** * Factory method fill header data * * @private * return {NSData} headerdata */ private func prepareHeader () -> NSData { header[Date] = getCurrentDatetime("E,dd LLL yyyy HH:mm:ss 'GMT'") header[Server] = "Trevi-lime" header[Accept_Ranges] = "bytes" if self._hasbody { header[Content_Length] = "\(bodyData!.length)" // replace bodyString length } if firstLine == nil{ statusCode = 200 firstLine = "\(httpVersion) \(statusCode) \(status)" + CRLF } var headerString = firstLine headerString! += dictionaryToString ( header ) return headerString!.dataUsingEncoding ( NSUTF8StringEncoding )! } private func mergeHeader(headers: [String : String]){ for (k,v) in headers { self.header[k] = v } } private func dictionaryToString ( dic: [String : String] ) -> String! { var resultString = "" for (key, value) in dic { if value.lengthOfBytesUsingEncoding ( NSUTF8StringEncoding ) == 0 { resultString += "\(key)\r\n" } else { resultString += "\(key): \(value)\r\n" } } resultString += CRLF return resultString; } }
apache-2.0
1b865ab1012cce8884d75cc27ecc3566
27.006369
133
0.539686
4.584984
false
false
false
false
proxpero/Endgame
Sources/EPD.swift
1
1682
// // EPD.swift // Endgame // // Created by Todd Olsen on 8/4/16. // // import Foundation /// A representation of Extended Position Description data. public struct EPD { /// The position for `self`. public var position: Position /// The opcodes for `self`. public var opcodes: [Opcode] /// Create an EPD. /// /// - parameter position: the initial position of the pieces in the EPD. /// - parameter opcodes: public init(position: Position, opcodes: [Opcode]) { self.position = position self.opcodes = opcodes } /// Creates an `EPD` from a string. public init(parse epd: String) throws { let components = epd.split(by: Character.whitespaces) let fen = (0...3).map { components[$0] }.joined(separator: " ") + " 0 1" let position = try Position(fen: fen) var opcodes: [EPD.Opcode] = [] let codes = (4..<components.endIndex).map { components[$0] }.joined(separator: " ").splitBySemicolon() for entry in codes.map({ $0.splitByWhitespaces() }) { guard let op = entry.first else { throw ParseError.invalidCode(epd) } let rest = entry.dropFirst().map { $0.trimmingCharacters(in: .punctuationCharacters) } guard !rest.isEmpty else { fatalError() } if let opcode = EPD.Opcode(tag: op, value: rest) { opcodes.append(opcode) } } self.init(position: position, opcodes: opcodes) } } extension EPD: Equatable { public static func == (lhs: EPD, rhs: EPD) -> Bool { return lhs.position == rhs.position && lhs.opcodes == rhs.opcodes } }
mit
dc68ee52698067caf2e79e0ff9879fc6
29.035714
110
0.588585
3.814059
false
false
false
false
royhsu/tiny-core
Sources/Core/Observable/Property/Property.swift
1
2110
// // Property.swift // TinyCore // // Created by Roy Hsu on 2019/1/18. // Copyright © 2019 TinyWorld. All rights reserved. // // MARK: - Property public final class Property<Value> { let boardcaster = Broadcaster<Value?>() private let _storage: Atomic<Storage> public init(_ initialValue: Value? = nil) { guard let initialValue = initialValue else { self._storage = Atomic(Storage(value: nil, isInitialValue: true)) return } self._storage = Atomic( Storage(value: initialValue, isInitialValue: false) ) } } extension Property { public var value: Value? { return _storage.value.value } public var createdDate: Date { return _storage.createdDate } public var modifiedDate: Date { return _storage.modifiedDate } public func modify(_ closure: @escaping (inout Value?) -> Void) { _storage.modify { storage in let oldValue = storage.value closure(&storage.value) let newValue = storage.value let change: ObservedChange = storage.isInitialValue ? .initial(value: newValue) : .changed(oldValue: oldValue, newValue: newValue) if storage.isInitialValue { storage.isInitialValue = false } self.boardcaster.notifyAll(with: change) } } /// To modify the underlyine value without notifying observers. public func modifySilently(_ closure: @escaping (inout Value?) -> Void) { _storage.modify { storage in closure(&storage.value) if storage.isInitialValue { storage.isInitialValue = false } } } } // MARK: - Storage extension Property { private struct Storage { var value: Value? var isInitialValue: Bool } } // MARK: - Equatable extension Property: Equatable where Value: Equatable { public static func == (lhs: Property, rhs: Property) -> Bool { return lhs.value == rhs.value } }
mit
7343d5b948fbee526bcd739faebf48ce
19.085714
77
0.587956
4.594771
false
false
false
false
adrfer/swift
stdlib/public/core/StringBridge.swift
2
9537
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. /// Effectively an untyped NSString that doesn't require foundation. public typealias _CocoaStringType = AnyObject public // @testable func _stdlib_binary_CFStringCreateCopy( source: _CocoaStringType ) -> _CocoaStringType { let result = _swift_stdlib_CFStringCreateCopy(nil, source) Builtin.release(result) return result } public // @testable func _stdlib_binary_CFStringGetLength( source: _CocoaStringType ) -> Int { return _swift_stdlib_CFStringGetLength(source) } public // @testable func _stdlib_binary_CFStringGetCharactersPtr( source: _CocoaStringType ) -> UnsafeMutablePointer<UTF16.CodeUnit> { return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII /// characters (does not apply ASCII optimizations). @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency func _cocoaStringToSwiftString_NonASCII( source: _CocoaStringType ) -> String { let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source) let length = _stdlib_binary_CFStringGetLength(cfImmutableValue) let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) return String(_StringCore( baseAddress: COpaquePointer(start), count: length, elementShift: 1, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, Optional<AnyObject>.self))) } /// Loading Foundation initializes these function variables /// with useful values /// Produces a `_StringBuffer` from a given subrange of a source /// `_CocoaStringType`, having the given minimum capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringToContiguous( source: _CocoaStringType, _ range: Range<Int>, minimumCapacity: Int ) -> _StringBuffer { _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil, "Known contiguously-stored strings should already be converted to Swift") let startIndex = range.startIndex let count = range.endIndex - startIndex let buffer = _StringBuffer(capacity: max(count, minimumCapacity), initialSize: count, elementWidth: 2) _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: startIndex, length: count), UnsafeMutablePointer<_swift_shims_UniChar>(buffer.start)) return buffer } /// Reads the entire contents of a _CocoaStringType into contiguous /// storage of sufficient capacity. @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringReadAll( source: _CocoaStringType, _ destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange( location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSlice( target: _StringCore, _ subRange: Range<Int> ) -> _StringCore { _sanityCheck(target.hasCocoaBuffer) let cfSelf: _swift_shims_CFStringRef = unsafeUnwrap(target.cocoaBuffer) _sanityCheck( _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil, "Known contiguously-stored strings should already be converted to Swift") let cfResult: AnyObject = _swift_stdlib_CFStringCreateWithSubstring( nil, cfSelf, _swift_shims_CFRange( location: subRange.startIndex, length: subRange.count)) return String(_cocoaString: cfResult)._core } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency internal func _cocoaStringSubscript( target: _StringCore, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = unsafeUnwrap(target.cocoaBuffer) _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf)._isNull, "Known contiguously-stored strings should already be converted to Swift") return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { return 0x0600 } extension String { @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public // SPI(Foundation) init(_cocoaString: AnyObject) { if let wrapped = _cocoaString as? _NSContiguousString { self._core = wrapped._core return } // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. let cfImmutableValue: _swift_shims_CFStringRef = _stdlib_binary_CFStringCreateCopy(_cocoaString) let length = _swift_stdlib_CFStringGetLength(cfImmutableValue) // Look first for null-terminated ASCII // Note: the code in clownfish appears to guarantee // nul-termination, but I'm waiting for an answer from Chris Kane // about whether we can count on it for all time or not. let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr( cfImmutableValue, kCFStringEncodingASCII) // start will hold the base pointer of contiguous storage, if it // is found. var start = UnsafeMutablePointer<RawByte>(nulTerminatedASCII) let isUTF16 = nulTerminatedASCII._isNull if (isUTF16) { start = UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)) } self._core = _StringCore( baseAddress: COpaquePointer(start), count: length, elementShift: isUTF16 ? 1 : 0, hasCocoaBuffer: true, owner: unsafeBitCast(cfImmutableValue, Optional<AnyObject>.self)) } } // At runtime, this class is derived from `_SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase) public class _SwiftNativeNSString {} @objc public protocol _NSStringCoreType : _NSCopyingType, _NSFastEnumerationType { // The following methods should be overridden when implementing an // NSString subclass. func length() -> Int func characterAtIndex(index: Int) -> UInt16 // We also override the following methods for efficiency. } /// An `NSString` built around a slice of contiguous Swift `String` storage. public final class _NSContiguousString : _SwiftNativeNSString { public init(_ _core: _StringCore) { _sanityCheck( _core.hasContiguousStorage, "_NSContiguousString requires contiguous storage") self._core = _core super.init() } init(coder aDecoder: AnyObject) { _sanityCheckFailure("init(coder:) not implemented for _NSContiguousString") } func length() -> Int { return _core.count } func characterAtIndex(index: Int) -> UInt16 { return _core[index] } func getCharacters( buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) { _precondition(aRange.location + aRange.length <= Int(_core.count)) if _core.elementWidth == 2 { UTF16._copy( _core.startUTF16 + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } else { UTF16._copy( _core.startASCII + aRange.location, destination: UnsafeMutablePointer<UInt16>(buffer), count: aRange.length) } } @objc func _fastCharacterContents() -> UnsafeMutablePointer<UInt16> { return _core.elementWidth == 2 ? UnsafeMutablePointer(_core.startUTF16) : nil } // // Implement sub-slicing without adding layers of wrapping // func substringFromIndex(start: Int) -> _NSContiguousString { return _NSContiguousString(_core[Int(start)..<Int(_core.count)]) } func substringToIndex(end: Int) -> _NSContiguousString { return _NSContiguousString(_core[0..<Int(end)]) } func substringWithRange(aRange: _SwiftNSRange) -> _NSContiguousString { return _NSContiguousString( _core[Int(aRange.location)..<Int(aRange.location + aRange.length)]) } func copy() -> AnyObject { // Since this string is immutable we can just return ourselves. return self } public let _core: _StringCore } extension String { /// Same as `_bridgeToObjectiveC()`, but located inside the core standard /// library. public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject { if let ns = _core.cocoaBuffer where _swift_stdlib_CFStringGetLength(ns) == _core.count { return ns } _sanityCheck(_core.hasContiguousStorage) return _NSContiguousString(_core) } @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency public func _bridgeToObjectiveCImpl() -> AnyObject { return _stdlib_binary_bridgeToObjectiveCImpl() } } #endif
apache-2.0
105c2ecca74dd76ebc97592ba6d35751
31.773196
92
0.712488
4.545758
false
false
false
false
lojals/DoorsConcept
DoorConcept/Controllers/Buildings/BuildingsTableViewController.swift
1
3955
// // BuildingsTableViewController.swift // DoorConcept // // Created by Jorge Raul Ovalle Zuleta on 3/18/16. // Copyright © 2016 jorgeovalle. All rights reserved. // import UIKit import SESlideTableViewCell import DZNEmptyDataSet class BuildingsTableViewController: UITableViewController { let buildingInteractor = BuildingsInteractor() var buildings:[Building] = [Building]() override func viewDidLoad() { self.tableView.emptyDataSetDelegate = self self.tableView.emptyDataSetSource = self } override func viewWillAppear(animated: Bool) { self.loadBuildings() } func loadBuildings(){ buildingInteractor.getBuildings { (data, error) -> Void in if error == nil{ self.buildings = data as! [Building] self.tableView.reloadData() }else{ print(error) } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return buildings.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BuildingCell", forIndexPath: indexPath) as! BuildingsTableViewCell cell.delegate = self cell.tag = indexPath.row cell.configureCellWithBuilding(buildings[indexPath.row]) return cell } } // MARK: - SESlideTableViewCellDelegate extension BuildingsTableViewController:SESlideTableViewCellDelegate{ func slideTableViewCell(cell: SESlideTableViewCell!, didTriggerRightButton buttonIndex: Int) { buildingInteractor.deleteBuilding(buildings[cell.tag]) self.loadBuildings() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let doorView = self.storyboard?.instantiateViewControllerWithIdentifier("DoorsTableViewController") as! DoorsTableViewController doorView.building = buildings[indexPath.row] self.navigationController?.pushViewController(doorView, animated: true) } } // MARK: - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate // Handle the empty state extension BuildingsTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{ func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return UIImage(named: "empty_buildings") } func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = "Oops!!" let infoStr = NSMutableAttributedString(string: str) infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18, weight: 0.7), range: NSMakeRange(0, str.characters.count)) infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count)) return infoStr as NSAttributedString } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = "There’s no buildings yet, add a new one\nclicking in the + button." let infoStr = NSMutableAttributedString(string: str) infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14, weight: 0.1), range: NSMakeRange(0, str.characters.count)) infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count)) return infoStr as NSAttributedString } func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! { return UIColor.whiteColor() } func emptyDataSetShouldFadeIn(scrollView: UIScrollView!) -> Bool { return true } }
mit
ead9886b88b127d6f27d86d9eb194cb5
38.929293
143
0.706984
5.166013
false
false
false
false
steelwheels/Cobalt
Source/CBError.swift
1
2120
/** * @file CBError.swift * @brief Define CBError enum type * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import CoconutData import Foundation public enum CBError: Error { case InternalError(place: String) case UnknownLongOptionName(name: String) case UnknownShortOptionName(name: Character) case TooFewParameter(optionType: CBOptionType, withShortName: Bool) case InvalidParameter(optionType: CBOptionType, withShortName: Bool, argument: String) case NoSubCommand case UnknownSubCommand(name: String) public func toObject() -> NSError { return NSError.parseError(message: self.description) } public var description: String { get { var result = "?" switch self { case .InternalError(let place): result = "Internal error: \(place)" case .UnknownLongOptionName(let name): result = "Unknown long option name: \(name)" case .UnknownShortOptionName(let name): result = "Unknown short option name: \(name)" case .InvalidParameter(let opttype, let withshort, let arg): let optname = optionName(optionType: opttype, withShortName: withshort) result = "Invalid parameter \"\(arg)\" for option \"\(optname)\"" case .TooFewParameter(let opttype, let withshort): let optname = optionName(optionType: opttype, withShortName: withshort) result = "Too few parameter(s) for option \"\(optname)\"" case .NoSubCommand: result = "Sub command is required but it is not given" case .UnknownSubCommand(let cmdname): result = "Unknown sub command: \"\(cmdname)\"" } return result } } private func optionName(optionType opttype: CBOptionType, withShortName withshort: Bool) -> String { var result: String if withshort { if let sname = opttype.shortName { result = "\(sname)" } else { CNLog(logLevel: .error, message: "No short name", atFunction: #function, inFile: #file) result = "?" } } else { if let lname = opttype.longName { result = lname } else { CNLog(logLevel: .error, message: "No long name", atFunction: #function, inFile: #file) result = "?" } } return result } }
gpl-2.0
a8e31d86af263e11b309a04abebc8dbe
29.724638
101
0.696226
3.557047
false
false
false
false
multinerd/Mia
Mia/Extensions/Foundation/Date/Date+TimeAgo.swift
1
3279
import Foundation extension Date { public func timeAgo() -> String { let time = self.timeIntervalSince1970 let now = Date().timeIntervalSince1970 let isPast = now - time > 0 let sec: Double = abs(now - time) let min: Double = round(sec / 60) let hr: Double = round(min / 60) let d: Double = round(hr / 24) if sec < 60 { if sec < 10 { return isPast ? "just now" : "in a few seconds" } else { let string = isPast ? "%.f seconds ago" : "in %.f seconds" return String(format: string, sec) } } if min < 60 { if min == 1 { return isPast ? "1 minute ago" : "in 1 minute" } else { let string = isPast ? "%.f minutes ago" : "in %.f minutes" return String(format: string, min) } } if hr < 24 { if hr == 1 { return isPast ? "last hour" : "next hour" } else { let string = isPast ? "%.f hours ago" : "in %.f hours" return String(format: string, hr) } } if d < 7 { if d == 1 { return isPast ? "yesterday" : "tomorrow" } else { let string = isPast ? "%.f days ago" : "in %.f days" return String(format: string, d) } } if d < 28 { if isPast { if compare(.isLastWeek) { return "last week" } else { let string = "%.f weeks ago" return String(format: string, Double(abs(since(Date(), in: .week)))) } } else { if compare(.isNextWeek) { return "next week" } else { let string = "in %.f weeks" return String(format: string, Double(abs(since(Date(), in: .week)))) } } } if compare(.isThisYear) { if isPast { if compare(.isLastMonth) { return "last month" } else { let string = "%.f months ago" return String(format: string, Double(abs(since(Date(), in: .month)))) } } else { if compare(.isNextMonth) { return "next month" } else { let string = "in %.f months" return String(format: string, Double(abs(since(Date(), in: .month)))) } } } if isPast { if compare(.isLastYear) { return "last year" } else { let string = "%.f years ago" return String(format: string, Double(abs(since(Date(), in: .year)))) } } else { if compare(.isNextYear) { return "next year" } else { let string = "in %.f years" return String(format: string, Double(abs(since(Date(), in: .year)))) } } } }
mit
e8e27dd191c30053bf12e1a9dac16173
31.79
89
0.402562
4.745297
false
false
false
false
towlebooth/watchos-sabbatical-countdown-part2
SabbaticalCountdown2 WatchKit Extension/InterfaceController.swift
1
3680
// // InterfaceController.swift // SabbaticalCountdown2 WatchKit Extension // // Created by Chad Towle on 11/29/15. // Copyright © 2015 Intertech. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { @IBOutlet var yearsLabel: WKInterfaceLabel! @IBOutlet var monthsLabel: WKInterfaceLabel! @IBOutlet var daysLabel: WKInterfaceLabel! var session : WCSession! override init() { super.init() if (WCSession.isSupported()) { session = WCSession.defaultSession() session.delegate = self session.activateSession() } } func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { // get values from app context let displayDate = (applicationContext["dateKey"] as? String) // save to user defaults let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(displayDate, forKey: "dateKey") } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // start/refresh countdown using a one-second timer NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("startCountDown:"), userInfo: nil, repeats: true) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func startCountDown(timer: NSTimer) { // create calendar, date and formatter variables let userCalendar = NSCalendar.currentCalendar() let dateFormatter = NSDateFormatter() dateFormatter.calendar = userCalendar dateFormatter.dateFormat = "yyyy-MM-dd" // create variable to hold 7 years let sevenYears: NSDateComponents = NSDateComponents() sevenYears.setValue(7, forComponent: NSCalendarUnit.Year); // get values from user defaults (tutorial part 2) let defaults = NSUserDefaults.standardUserDefaults() var startDateIntertech = NSDate() if let dateString = defaults.stringForKey("dateKey") { startDateIntertech = dateFormatter.dateFromString(dateString)! } // add 7 years to our start date to calculate the date of our sabbatical var sabbaticalDate = userCalendar.dateByAddingComponents(sevenYears, toDate: startDateIntertech, options: NSCalendarOptions(rawValue: 0)) // since we get a sabbatical every 7 years, add 7 years until sabbaticalDate is in the future while sabbaticalDate!.timeIntervalSinceNow.isSignMinus { sabbaticalDate = userCalendar.dateByAddingComponents(sevenYears, toDate: sabbaticalDate!, options: NSCalendarOptions(rawValue: 0)) } // create year, month and day values for display let flags: NSCalendarUnit = [.Year, .Month, .Day] let dateComponents = userCalendar.components(flags, fromDate: NSDate(), toDate: sabbaticalDate!, options: []) let year = dateComponents.year let month = dateComponents.month let day = dateComponents.day // set labels on interface yearsLabel.setText(String(format: "%d Years", year)) monthsLabel.setText(String(format: "%d Months", month)) daysLabel.setText(String(format: "%d Days", day)) } }
mit
2f543d2f682646730939e5186683b815
37.322917
145
0.672737
5.378655
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CustomerAccessTokenDeletePayload.swift
1
4664
// // CustomerAccessTokenDeletePayload.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Return type for `customerAccessTokenDelete` mutation. open class CustomerAccessTokenDeletePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CustomerAccessTokenDeletePayload /// The destroyed access token. @discardableResult open func deletedAccessToken(alias: String? = nil) -> CustomerAccessTokenDeletePayloadQuery { addField(field: "deletedAccessToken", aliasSuffix: alias) return self } /// ID of the destroyed customer access token. @discardableResult open func deletedCustomerAccessTokenId(alias: String? = nil) -> CustomerAccessTokenDeletePayloadQuery { addField(field: "deletedCustomerAccessTokenId", aliasSuffix: alias) return self } /// The list of errors that occurred from executing the mutation. @discardableResult open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CustomerAccessTokenDeletePayloadQuery { let subquery = UserErrorQuery() subfields(subquery) addField(field: "userErrors", aliasSuffix: alias, subfields: subquery) return self } } /// Return type for `customerAccessTokenDelete` mutation. open class CustomerAccessTokenDeletePayload: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CustomerAccessTokenDeletePayloadQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "deletedAccessToken": if value is NSNull { return nil } guard let value = value as? String else { throw SchemaViolationError(type: CustomerAccessTokenDeletePayload.self, field: fieldName, value: fieldValue) } return value case "deletedCustomerAccessTokenId": if value is NSNull { return nil } guard let value = value as? String else { throw SchemaViolationError(type: CustomerAccessTokenDeletePayload.self, field: fieldName, value: fieldValue) } return value case "userErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CustomerAccessTokenDeletePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try UserError(fields: $0) } default: throw SchemaViolationError(type: CustomerAccessTokenDeletePayload.self, field: fieldName, value: fieldValue) } } /// The destroyed access token. open var deletedAccessToken: String? { return internalGetDeletedAccessToken() } func internalGetDeletedAccessToken(alias: String? = nil) -> String? { return field(field: "deletedAccessToken", aliasSuffix: alias) as! String? } /// ID of the destroyed customer access token. open var deletedCustomerAccessTokenId: String? { return internalGetDeletedCustomerAccessTokenId() } func internalGetDeletedCustomerAccessTokenId(alias: String? = nil) -> String? { return field(field: "deletedCustomerAccessTokenId", aliasSuffix: alias) as! String? } /// The list of errors that occurred from executing the mutation. open var userErrors: [Storefront.UserError] { return internalGetUserErrors() } func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] { return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError] } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { return [] } } }
mit
333ddc46bf1e8cc7f3a558eaaf666f01
37.229508
126
0.746998
4.338605
false
false
false
false
jpush/aurora-imui
iOS/sample/sample/IMUIInputView/Controllers/IMUIRecordVoiceHelper.swift
1
4992
// // IMUIRecordVoiceHelper.swift // IMUIChat // // Created by oshumini on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import AVFoundation let maxRecordTime = 60.0 typealias CompletionCallBack = () -> Void typealias TimerTickCallback = (TimeInterval, CGFloat) -> Void // recordDuration, meter typealias IMUIFinishRecordVoiceCallBack = () -> Data class IMUIRecordVoiceHelper: NSObject { var startRecordCallBack: CompletionCallBack? var timerTickCallBack: TimerTickCallback? var recorder: AVAudioRecorder? var recordPath: String? var timerFireDate: Date? var recordDuration: TimeInterval { get { if timerFireDate != nil { return Date().timeIntervalSince(timerFireDate!) } else { return 0.0 } } } var updater: CADisplayLink! = nil override init() { super.init() } deinit { self.stopRecord() self.recordPath = nil } func resetTimer() { self.timerFireDate = nil updater?.invalidate() updater = nil } func cancelRecording() { if self.recorder == nil { return } if self.recorder?.isRecording != false { self.recorder?.stop() } self.recorder = nil self.resetTimer() } func stopRecord() { self.cancelRecording() self.resetTimer() } func startRecordingWithPath(_ path:String, startRecordCompleted: @escaping CompletionCallBack, timerTickCallback: @escaping TimerTickCallback) { print("Action - startRecordingWithPath:") self.startRecordCallBack = startRecordCompleted self.timerTickCallBack = timerTickCallback self.timerFireDate = Date() self.recordPath = path let audioSession:AVAudioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { print("could not set session category") print(error.localizedDescription) } do { try audioSession.setActive(true) } catch let error as NSError { print("could not set session active") print(error.localizedDescription) } let recordSettings:[String : AnyObject] = [ AVFormatIDKey: NSNumber(value: kAudioFormatAppleIMA4 as UInt32), AVNumberOfChannelsKey: 1 as AnyObject, AVSampleRateKey : 16000.0 as AnyObject ] do { self.recorder = try AVAudioRecorder(url: URL(fileURLWithPath: self.recordPath!), settings: recordSettings) self.recorder!.delegate = self self.recorder!.isMeteringEnabled = true self.recorder!.prepareToRecord() self.recorder?.record(forDuration: 160.0) } catch let error as NSError { recorder = nil print(error.localizedDescription) } if ((self.recorder?.record()) != false) { } else { print("fail record") } self.updater = CADisplayLink(target: self, selector: #selector(self.trackAudio)) updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) updater.frameInterval = 1 if self.startRecordCallBack != nil { DispatchQueue.main.async(execute: self.startRecordCallBack!) } } func trackAudio() { self.timerTickCallBack?(recordDuration, 0.0) } open func finishRecordingCompletion() -> (voiceFilePath: String, duration: TimeInterval){ let duration = recordDuration self.stopRecord() if let _ = recordPath { return (voiceFilePath: recordPath!, duration: duration) } else { return ("",0) } } func cancelledDeleteWithCompletion() { self.stopRecord() if self.recordPath == nil { return } let fileManager:FileManager = FileManager.default if fileManager.fileExists(atPath: self.recordPath!) == true { do { try fileManager.removeItem(atPath: self.recordPath!) } catch let error as NSError { print("can no to remove the voice file \(error.localizedDescription)") } } else { } } open func playVoice(_ recordPath:String) { do { print("\(recordPath)") let player:AVAudioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: recordPath)) player.volume = 1 player.delegate = self player.numberOfLoops = -1 player.prepareToPlay() player.play() } catch let error as NSError { print("get AVAudioPlayer is fail \(error)") } } } // MARK: - AVAudioPlayerDelegate extension IMUIRecordVoiceHelper : AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { print("finished playing \(flag)") } func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { if let e = error { print("\(e.localizedDescription)") } } } // MARK: - AVAudioRecorderDelegate extension IMUIRecordVoiceHelper : AVAudioRecorderDelegate { }
mit
711b5c0e6fbf2f42235b1573f25706d2
23.945
112
0.657046
4.64093
false
false
false
false
hzy87email/actor-platform
actor-apps/app-ios/ActorSwift/Strings.swift
2
3768
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation extension String { var length: Int { return self.characters.count } func trim() -> String { return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()); } subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i] as Character) } func first(count: Int) -> String { let realCount = min(count, length); return substringToIndex(startIndex.advancedBy(realCount)); } func strip(set: NSCharacterSet) -> String { return componentsSeparatedByCharactersInSet(set).joinWithSeparator("") } func replace(src: String, dest:String) -> String { return stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil) } func toLong() -> Int64? { return NSNumberFormatter().numberFromString(self)?.longLongValue } func toJLong() -> jlong { return jlong(toLong()!) } func smallValue() -> String { let trimmed = trim(); if (trimmed.isEmpty){ return "#"; } let letters = NSCharacterSet.letterCharacterSet() let res: String = self[0]; if (res.rangeOfCharacterFromSet(letters) != nil) { return res.uppercaseString; } else { return "#"; } } func hasPrefixInWords(prefix: String) -> Bool { var components = self.componentsSeparatedByString(" ") for i in 0..<components.count { if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) { return true } } return false } func contains(text: String) -> Bool { return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil } func rangesOfString(text: String) -> [Range<String.Index>] { var res = [Range<String.Index>]() var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex) while true { let found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil) if found != nil { res.append(found!) searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex) } else { break } } return res } func repeatString(count: Int) -> String { var res = "" for _ in 0..<count { res += self } return res } var asNS: NSString { return (self as NSString) } } extension NSAttributedString { func append(text: NSAttributedString) -> NSAttributedString { let res = NSMutableAttributedString() res.appendAttributedString(self) res.appendAttributedString(text) return res } func append(text: String, font: UIFont) -> NSAttributedString { return append(NSAttributedString(string: text, attributes: [NSFontAttributeName: font])) } convenience init(string: String, font: UIFont) { self.init(string: string) } } extension NSMutableAttributedString { func appendFont(font: UIFont) { self.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, self.length)) } func appendColor(color: UIColor) { self.addAttribute(NSForegroundColorAttributeName, value: color.CGColor, range: NSMakeRange(0, self.length)) } }
mit
6f543339d27b552bf4505636180f433c
28.209302
136
0.599788
4.893506
false
false
false
false
ayanna92/ayannacolden-programmeerproject
programmeerproject/LoginViewController.swift
1
2546
// // LoginViewController.swift // programmeerproject // // Created by Ayanna Colden on 10/01/2017. // Copyright © 2017 Ayanna Colden. All rights reserved. // import UIKit import Firebase // Source: https://www.youtube.com/watch?v=AsSZulMc7sk class LoginViewController: UIViewController { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var pwField: UITextField! var messagesController: MessagesController? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = true NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillAppear(_ animated: Bool) { let image = UIImage(named: "images-2") let transparentImage = image?.image(alpha: 0.5) self.view.backgroundColor = UIColor(patternImage: transparentImage!) } @IBAction func loginPressed(_ sender: Any) { if emailField.text == "" || pwField.text == "" { emptyError() } FIRAuth.auth()?.signIn(withEmail: emailField.text!, password: pwField.text!, completion: { (user, error) in if error != nil { self.incorrectError() } if user != nil { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SWReveal") self.present(vc, animated: true, completion: nil) } }) } func emptyError() { let errorAlert = UIAlertController(title: "Error", message: "Email and/or password not filled in.", preferredStyle: UIAlertControllerStyle.alert) errorAlert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)) self.present(errorAlert, animated: true, completion: nil) } func incorrectError() { let errorAlert = UIAlertController(title: "Error", message: "Incorrect email and/or password.", preferredStyle: UIAlertControllerStyle.alert) errorAlert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)) self.present(errorAlert, animated: true, completion: nil) } }
apache-2.0
2058457f8d71b700303cac442fbe5e3d
32.933333
153
0.642829
4.820076
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Data Debits/HATDataDebitPermissions.swift
1
2901
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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/ */ // MARK: Struct public struct HATDataDebitPermissions: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `dateCreated` in JSON is `dateCreated` * `purpose` in JSON is `purpose` * `startDate` in JSON is `start` * `period` in JSON is `period` * `endDate` in JSON is `end` * `willCancelAtPeriodsEnd` in JSON is `cancelAtPeriodEnd` * `termsUrl` in JSON is `termsUrl` * `isActive` in JSON is `active` * `isAccepted` in JSON is `accepted` * `conditions` in JSON is `conditions` * `bundle` in JSON is `bundle` */ private enum CodingKeys: String, CodingKey { case dateCreated = "dateCreated" case purpose = "purpose" case startDate = "start" case period = "period" case endDate = "end" case willCancelAtPeriodsEnd = "cancelAtPeriodEnd" case termsUrl = "termsUrl" case isActive = "active" case isAccepted = "accepted" case conditions = "conditions" case bundle = "bundle" } // MARK: - Variables /// The created date of the permission public var dateCreated: String = "" /// The purpose of the permission. A short description of what it offers. Optional public var purpose: String? /// The start date of the permission in an ISO format. Optional public var startDate: String? /// The end date of the permission in an ISO format. Optional public var endDate: String? /// A flag indicating if the permissions will auto cancel when the debit will end public var willCancelAtPeriodsEnd: Bool = false /// The terms and conditions URL for the permissions. Optional public var termsUrl: String? /// The period duration. How long the permissions will be active public var period: Int = 0 /// A flag indicating if the permissions are currently active public var isActive: Bool = false /// A flag indicating if the permissions have been accepted by the user public var isAccepted: Bool = false /// The bundle. It has all sorts of info about which endpoint and fields it can access. Also about mapping and filtering those fields. It can be nil public var bundle: HATDataDefinition = HATDataDefinition() /// Some `Data Debits` can have some conditions attached to them. For example all the search for a `String` or search for a number to be `between` 2 numbers. Optional public var conditions: HATDataDefinition? }
mpl-2.0
4f1daa8a8b6114395c44396a1ef17ea9
38.202703
170
0.667356
4.304154
false
false
false
false
pecuniabanking/pecunia-client
Source/Security.swift
1
9219
/** * Copyright (c) 2015, Pecunia Project. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; version 2 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ import Foundation // Class for parallel running banking requests each with its own authentication need. internal var serialQueue: DispatchQueue = DispatchQueue(label: "de.pecunia.auth-queue", attributes: []); @objc open class AuthRequest : NSObject { fileprivate var service: String = ""; fileprivate var account: String = ""; fileprivate var passwordController: PasswordController?; open var errorOccured = false; open func finishPasswordEntry() -> Void { if errorOccured { Security.deletePasswordForService(service, account: account); } if passwordController != nil { if !errorOccured { let password = passwordController!.result(); if(!Security.setPassword(password!, forService: service, account: account, store: passwordController!.savePassword)) {}; } passwordController!.close(); passwordController = nil; } } open func getPin(_ bankCode: String, userId: String) -> String { service = "Pecunia PIN"; let s = "PIN_\(bankCode)_\(userId)"; if s != account { if passwordController != nil { finishPasswordEntry(); } account = s; } // Serialize password retrieval (especially password dialogs). var result = "<abort>"; serialQueue.sync { let password = Security.passwordForService(self.service, account: self.account); if password != nil { result = password!; return; } if self.passwordController == nil { let user = BankUser.find(withId: userId, bankCode: bankCode); self.passwordController = PasswordController(text: String(format: NSLocalizedString("AP171", comment: ""), user != nil ? user!.name : userId), title: NSLocalizedString( "AP181", comment: "")); } else { self.passwordController!.retry(); } let res = NSApp.runModal(for: self.passwordController!.window!); self.passwordController!.closeWindow(); if res.rawValue == 0 { let pin = self.passwordController!.result(); if(!Security.setPassword(pin!, forService: self.service, account: self.account, store: false)) {}; result = pin!; } else { Security.deletePasswordForService(self.service, account: self.account); self.errorOccured = true; // Don't save the PIN. result = "<abort>"; } } return result; } } @objc open class Security : NSObject { public static var currentSigningOption: SigningOption? = nil; fileprivate static var currentPwService = ""; fileprivate static var currentPwAccount = ""; fileprivate static var passwordCache: [String: String] = [:]; fileprivate static var passwordController: PasswordController?; public static func getPasswordForDataFile() -> String { currentPwService = "Pecunia"; currentPwAccount = "DataFile"; var password = passwordForService(currentPwService, account: currentPwAccount); if password == nil { if passwordController == nil { passwordController = PasswordController(text: NSLocalizedString( "AP163", comment: ""), title: NSLocalizedString("AP162", comment: "")); } else { passwordController!.retry(); } if NSApp.runModal(for: passwordController!.window!).rawValue > 0 { password = nil; } else { password = passwordController!.result(); } passwordController!.closeWindow(); } if password == nil || password!.length == 0 { return "<abort>"; // Hopefully nobody uses this as password. } return password!; } public static func resetPin(bankCode: String, userId: String) { let account = "PIN_\(bankCode)_\(userId)"; Security.deletePasswordForService("Pecunia PIN", account: account); } // TODO: for all keychain functions, they could use a more generic implementation like Locksmith (see Github). @objc public static func setPassword(_ password: String, forService service: String, account: String, store: Bool) -> Bool { let key = service + "/" + account; passwordCache[key] = password; if !store { return true; } let serviceAsUtf8 = (service as NSString).cString(using: String.Encoding.utf8.rawValue); let serviceLength = UInt32(service.lengthOfBytes(using: String.Encoding.utf8)); let accountAsUtf8 = (account as NSString).cString(using: String.Encoding.utf8.rawValue); let accountLength = UInt32(account.lengthOfBytes(using: String.Encoding.utf8)); let passwordAsUtf8 = (password as NSString).cString(using: String.Encoding.utf8.rawValue); let passwordLength = UInt32(password.lengthOfBytes(using: String.Encoding.utf8)); let status = SecKeychainAddGenericPassword(nil, serviceLength, serviceAsUtf8, accountLength, accountAsUtf8, passwordLength + 1, passwordAsUtf8!, nil); // TODO: why passwordlength + 1? if status != noErr { passwordCache.removeValue(forKey: key); } return status == noErr; } @objc public static func passwordForService(_ service: String, account: String) -> String? { let key = service + "/" + account; if let password = passwordCache[key] { return password; } let serviceAsUtf8 = (service as NSString).cString(using: String.Encoding.utf8.rawValue); let serviceLength = UInt32(service.lengthOfBytes(using: String.Encoding.utf8)); let accountAsUtf8 = (account as NSString).cString(using: String.Encoding.utf8.rawValue); let accountLength = UInt32(account.lengthOfBytes(using: String.Encoding.utf8)); var passwordLength: UInt32 = 0; var passwordData: UnsafeMutableRawPointer? = nil; let status = SecKeychainFindGenericPassword(nil, serviceLength, serviceAsUtf8, accountLength, accountAsUtf8, &passwordLength, &passwordData, nil); if (status != noErr) { return nil; } if let passwordData = passwordData { if let password = NSString(utf8String: passwordData.assumingMemoryBound(to: Int8.self)) { passwordCache[key] = password as String; SecKeychainItemFreeContent(nil, passwordData); return password as String; } } return nil; } @objc public static func deletePasswordForService(_ service: String, account: String) -> Void { let key = service + "/" + account; passwordCache.removeValue(forKey: key); let serviceAsUtf8 = (service as NSString).cString(using: String.Encoding.utf8.rawValue); let serviceLength = UInt32(service.lengthOfBytes(using: String.Encoding.utf8)); let accountAsUtf8 = (account as NSString).cString(using: String.Encoding.utf8.rawValue); let accountLength = UInt32(account.lengthOfBytes(using: String.Encoding.utf8)); var itemRef: SecKeychainItem? = nil; let status = SecKeychainFindGenericPassword(nil, serviceLength, serviceAsUtf8, accountLength, accountAsUtf8, nil, nil, &itemRef); if status == noErr { if itemRef != nil { SecKeychainItemDelete(itemRef!); } } } @objc public static func deletePasswordsForService(_ service: String) -> Void { let serviceAsUtf8 = (service as NSString).cString(using: String.Encoding.utf8.rawValue); let serviceLength = UInt32(service.lengthOfBytes(using: String.Encoding.utf8)); var status: OSStatus; var itemRef: SecKeychainItem? = nil; passwordCache.removeAll(keepingCapacity: false); repeat { status = SecKeychainFindGenericPassword(nil, serviceLength, serviceAsUtf8, 0, nil, nil, nil, &itemRef); if status == noErr && itemRef != nil { SecKeychainItemDelete(itemRef!); itemRef = nil; } } while status == noErr && itemRef != nil; } }
gpl-2.0
025d196e17da6eb5c59c8cfd51c30805
38.737069
136
0.622953
4.725269
false
false
false
false
zenangst/Storage
Source/Storage.swift
1
4758
import Foundation public struct Storage { // MARK: - File system static var fileManager: NSFileManager = { let manager = NSFileManager.defaultManager() return manager }() public static let applicationDirectory: String = { let paths:NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let basePath: AnyObject? = (paths.count > 0) ? paths.firstObject : nil return basePath as! String; }() private static func buildPath(path: URLStringConvertible, createPath: Bool = false) -> String { var buildPath = path.string if path.string != Storage.applicationDirectory { buildPath = "\(Storage.applicationDirectory)/\(path.string)" let folderPath = NSString(string: buildPath).stringByDeletingLastPathComponent if folderPath != Storage.applicationDirectory { do { try fileManager.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil) } catch { } } } return buildPath } // MARK: - Loading public static func load(path: URLStringConvertible) -> AnyObject? { let loadPath = Storage.buildPath(path) return fileManager.fileExistsAtPath(loadPath) ? NSKeyedUnarchiver.unarchiveObjectWithFile(loadPath) : nil } public static func load(contentsAtPath path: URLStringConvertible, _ error: NSErrorPointer? = nil) -> String? { let loadPath = Storage.buildPath(path) let contents: NSString? do { contents = try NSString(contentsOfFile: loadPath, encoding: NSUTF8StringEncoding) } catch { contents = nil } return contents as? String } public static func load(dataAtPath path: URLStringConvertible) -> NSData? { let loadPath = Storage.buildPath(path) return fileManager.fileExistsAtPath(loadPath) ? NSData(contentsOfFile: loadPath) : nil } public static func load(JSONAtPath path: URLStringConvertible) -> AnyObject? { var object: AnyObject? if let data = load(dataAtPath: path) { do { object = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch _ { object = nil } } return object } // MARK: - Saving public static func save(object object: AnyObject, _ path: URLStringConvertible = Storage.applicationDirectory, closure: (error: NSError?) -> Void) { let savePath = Storage.buildPath(path, createPath: true) let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(object) var error: NSError? do { try data.writeToFile(savePath, options: NSDataWritingOptions.DataWritingAtomic) } catch let error1 as NSError { error = error1 } closure(error: error) } public static func save(contents contents: String, _ path: URLStringConvertible = Storage.applicationDirectory, closure: (error: NSError?) -> Void) { let savePath = Storage.buildPath(path, createPath: true) var error: NSError? do { try (contents as NSString).writeToFile(savePath, atomically: true, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 } closure(error: error) } public static func save(data data: NSData, _ path: URLStringConvertible = Storage.applicationDirectory, closure: (error: NSError?) -> Void) { let savePath = Storage.buildPath(path, createPath: true) var error: NSError? do { try data.writeToFile(savePath, options: .DataWritingAtomic) } catch let error1 as NSError { error = error1 } closure(error: error) } public static func save(JSON JSON: AnyObject, _ path: URLStringConvertible = Storage.applicationDirectory, closure: (error: NSError?) -> Void) { var error: NSError? do { let data = try NSJSONSerialization.dataWithJSONObject(JSON, options: []) save(data: data, path, closure: closure) } catch let error1 as NSError { error = error1 closure(error: error) } } // MARK: - Helper Methods public static func existsAtPath(path: URLStringConvertible) -> Bool { let loadPath = Storage.buildPath(path) return fileManager.fileExistsAtPath(loadPath) } public static func removeAtPath(path: URLStringConvertible) { let loadPath = Storage.buildPath(path) do { try fileManager.removeItemAtPath(loadPath) } catch { } } } public protocol URLStringConvertible { var url: NSURL { get } var string: String { get } } extension String: URLStringConvertible { public var url: NSURL { let aURL = NSURL(string: self)! return aURL } public var string: String { return self } }
mit
999a87c1c7b7aab46e2438f00f271c47
27.662651
152
0.68306
4.78672
false
false
false
false
joshpc/ElasticPullToRefresh
ElasticPullToRefresh/IndicatorView.swift
1
2984
// // RefreshView.swift // ElasticPullToRefresh // // Created by Joshua Tessier on 2015-12-20. // Copyright © 2015-2018 Joshua Tessier. All rights reserved. // import UIKit public class IndicatorView: UIView { private let circleLayer = CAShapeLayer() private var animating: Bool = false public var indicatorTintColor: UIColor? { didSet { circleLayer.strokeColor = (tintColor ?? UIColor.white).cgColor } } var interactiveProgress: CGFloat = 0.0 { didSet { guard animating == false else { return } circleLayer.strokeStart = 0 circleLayer.strokeEnd = interactiveProgress } } private let strokeAnimations: CAAnimation = { let startAnimation = CABasicAnimation(keyPath: "strokeStart") startAnimation.beginTime = 0.5 startAnimation.fromValue = 0 startAnimation.toValue = 1 startAnimation.duration = 1.5 startAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let endAnimation = CABasicAnimation(keyPath: "strokeEnd") endAnimation.fromValue = 0 endAnimation.toValue = 1 endAnimation.duration = 2 endAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let group = CAAnimationGroup() group.duration = 2.5 group.repeatCount = MAXFLOAT group.animations = [startAnimation, endAnimation] return group }() private let rotationAnimation: CAAnimation = { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = CGFloat.pi * 2 animation.duration = 4 animation.repeatCount = MAXFLOAT return animation }() override init(frame: CGRect) { super.init(frame: frame) setupViews() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } private func setupViews() { translatesAutoresizingMaskIntoConstraints = false circleLayer.lineWidth = 2 circleLayer.fillColor = nil circleLayer.strokeColor = UIColor.white.cgColor circleLayer.strokeStart = 0 circleLayer.strokeEnd = 0 layer.addSublayer(circleLayer) } public override func layoutSubviews() { super.layoutSubviews() let center = CGPoint(x: bounds.midX, y: bounds.midY) let radius = min(bounds.width, bounds.height) / 2 - circleLayer.lineWidth / 2 let startAngle = -CGFloat.pi / 2 let endAngle = startAngle + (2 * CGFloat.pi) let path = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) circleLayer.position = center circleLayer.path = path.cgPath } func set(animating: Bool) { self.interactiveProgress = 0.0 self.animating = animating updateAnimation() } private func updateAnimation() { if animating { circleLayer.add(strokeAnimations, forKey: "strokes") circleLayer.add(rotationAnimation, forKey: "rotation") } else { circleLayer.removeAnimation(forKey: "strokes") circleLayer.removeAnimation(forKey: "rotation") } } }
mit
b2d023f14c41a89af2d108f4322710f2
25.39823
120
0.734831
4.04749
false
false
false
false
lvsti/Ilion
Ilion/FormatDescriptor.swift
1
4585
// // String+FormatTypes.swift // Ilion // // Created by Tamas Lustyik on 2017. 04. 30.. // // Copyright © 2017. Tamas Lustyik // Portions Copyright (c) 2017 SwiftGen // MIT License import Foundation enum FormatDescriptorError: Error { case ambiguousVariableTypes(position: Int, typeA: String, typeB: String) case unspecifiedVariable(position: Int) } struct FormatDescriptor { let placeholders: [Int: String] init(format: String) throws { let range = NSRange(location: 0, length: (format as NSString).length) let matches = FormatDescriptor.formatTypesRegex.matches(in: format, options: [], range: range) var unusedIndex = 0 var placeholderTypes: [Int: String] = [:] try matches.forEach { match in let typeRange = match.range(at: 3) let type = (format as NSString).substring(with: typeRange) let posRange = match.range(at: 2) let pair: (String, Int) if posRange.location == NSNotFound { // No positional specifier unusedIndex += 1 pair = (type, unusedIndex) } else { // Convert the positional specifier to Int let pos = (format as NSString).substring(with: posRange) pair = (type, Int(pos)!) } if let type = placeholderTypes[pair.1] { if type != pair.0 { throw FormatDescriptorError.ambiguousVariableTypes(position: pair.1, typeA: pair.0, typeB: type) } } placeholderTypes[pair.1] = pair.0 } self.placeholders = placeholderTypes } private init(placeholders: [Int: String]) { self.placeholders = placeholders } func validateAsSubstitute(for other: FormatDescriptor) throws { // check whether the argument types match up for (position, type) in placeholders { guard let otherType = other.placeholders[position] else { throw FormatDescriptorError.unspecifiedVariable(position: position) } guard type == otherType else { throw FormatDescriptorError.ambiguousVariableTypes(position: position, typeA: otherType, typeB: type) } } } static func merge(_ descriptors: [FormatDescriptor]) throws -> FormatDescriptor { var mergedPlaceholders: [Int: String] = [:] for descriptor in descriptors { for (position, type) in descriptor.placeholders { if let mergedType = mergedPlaceholders[position], type != mergedType { throw FormatDescriptorError.ambiguousVariableTypes(position: position, typeA: mergedType, typeB: type) } mergedPlaceholders[position] = type } } return FormatDescriptor(placeholders: mergedPlaceholders) } static func variableRanges(in format: String) -> [NSRange] { let range = NSRange(location: 0, length: (format as NSString).length) let matches = FormatDescriptor.formatTypesRegex.matches(in: format, options: [], range: range) return matches.map { $0.range(at: 1) } } // extracted from: https://github.com/SwiftGen/SwiftGenKit/blob/master/Sources/Parsers/StringsFileParser.swift private static let formatTypesRegex: NSRegularExpression = { // %d/%i/%o/%u/%x with their optional length modifiers like in "%lld" let pattern_int = "(?:h|hh|l|ll|q|z|t|j)?[dioux]" // valid flags for float let pattern_float = "[aefg]" // like in "%3$" to make positional specifiers let position = "(?:([1-9]\\d*)\\$)?" // precision like in "%1.2f" let precision = "[-+ 0#]*\\d?(?:\\.(?:\\d|\\*))?" return try! NSRegularExpression( pattern: "(?:^|[^%]|(?<!%)(?:%%)+)(%\(position)\(precision)(@|\(pattern_int)|\(pattern_float)|[csp]))", options: [.caseInsensitive] ) }() }
mit
e7487dd08a1ba4da7ec0f1f5fadf4df6
37.2
115
0.522251
4.982609
false
false
false
false