repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tuanan94/FRadio-ios
refs/heads/xcode8
SwiftRadio/Libraries/Spring/TransitionZoom.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class TransitionZoom: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { @objc var isPresenting = true @objc var duration = 0.4 public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! if isPresenting { container.addSubview(fromView) container.addSubview(toView) toView.alpha = 0 toView.transform = CGAffineTransform(scaleX: 2, y: 2) SpringAnimation.springEaseInOut(duration: duration) { fromView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) fromView.alpha = 0 toView.transform = CGAffineTransform.identity toView.alpha = 1 } } else { container.addSubview(toView) container.addSubview(fromView) SpringAnimation.springEaseInOut(duration: duration) { fromView.transform = CGAffineTransform(scaleX: 2, y: 2) fromView.alpha = 0 toView.transform = CGAffineTransform(scaleX: 1, y: 1) toView.alpha = 1 } } delay(delay: duration, closure: { transitionContext.completeTransition(true) }) } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } @objc public func animationController(forPresentedController presented: UIViewController, presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
688b1354076363d90a93de0c2c858c8d
41.43038
210
0.684964
false
false
false
false
crossroadlabs/Express
refs/heads/master
Express/AnyContent+MultipartFormData.swift
gpl-3.0
2
//===--- AnyContent+MultipartFormData.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 public extension AnyContent { func asMultipartFormData() throws -> Any? { throw ExpressError.NotImplemented(description: "multipart form data parsing is not implemented yet") } }
f339e2a9aa246cb2053bb58eaa27b099
39.642857
108
0.671064
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Constraints/requirement_failures_in_contextual_type.swift
apache-2.0
6
// RUN: %target-typecheck-verify-swift struct A<T> {} extension A where T == Int32 { // expected-note 2 {{where 'T' = 'Int'}} struct B : ExpressibleByIntegerLiteral { // expected-note {{where 'T' = 'Int'}} typealias E = Int typealias IntegerLiteralType = Int init(integerLiteral: IntegerLiteralType) {} } typealias C = Int } let _: A<Int>.B = 0 // expected-error@-1 {{referencing struct 'B' on 'A' requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.C = 0 // expected-error@-1 {{referencing type alias 'C' on 'A' requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.B.E = 0 // expected-error@-1 {{referencing type alias 'E' on 'A.B' requires the types 'Int' and 'Int32' be equivalent}}
9cf5c6f53dbeadfed37122b87f2cd174
34.142857
111
0.655827
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
refs/heads/best-ui
Team UI/Browser/Browser/ConnectionCtrls.swift
mit
1
// // ConnectionCtrl.swift // Browser // // Created by Burak Erol on 10.12.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import Foundation class JSONConnectionCtrl:ConnectionCtrl { override func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, data: NSData) -> ()) { let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let data = try! NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions()]) self.post(data, request: request, postCompleted: postCompleted) } } class ConnectionCtrl { // func post(params : AnyObject, url : String, // postCompleted : (succeeded: Bool, data: NSData) -> ()) // { // let request = NSMutableURLRequest(URL: NSURL(string: url)!) // request.HTTPMethod = "POST" // request.addValue("application/json", forHTTPHeaderField: "Content-Type") // request.addValue("application/json", forHTTPHeaderField: "Accept") // request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions()]) // // let session = NSURLSession.sharedSession() // let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in // postCompleted(succeeded: error == nil, data: data!) // }) // // // task.resume() // // } func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, data: NSData) -> ()){ postCompleted(succeeded: false,data: "Es wird die abstrakte Klasse ConnectionCtrl".dataUsingEncoding(NSUTF8StringEncoding)!) } private func post(data : NSData, request : NSMutableURLRequest, postCompleted : (succeeded: Bool, data: NSData) -> ()) { request.HTTPMethod = "POST" request.HTTPBody = data let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in postCompleted(succeeded: error == nil, data: data!) }) task.resume() } }
7dfa849272fefb9872df9eac4d1f8960
36.619048
136
0.635289
false
false
false
false
adrianodiasx93/TBEmptyDataSet
refs/heads/master
TBEmptyDataSet/EmptyDataView.swift
mit
1
// // EmptyDataView.swift // TBEmptyDataSet // // Created by Xin Hong on 15/11/19. // Copyright © 2015年 Teambition. All rights reserved. // import UIKit internal class EmptyDataView: UIView { fileprivate struct ViewStrings { static let contentView = "contentView" static let imageView = "imageView" static let titleLabel = "titleLabel" static let descriptionLabel = "descriptionLabel" static let customView = "customView" } // MARK: - Properties internal lazy var contentView: UIView = { let contentView = UIView() contentView.translatesAutoresizingMaskIntoConstraints = false contentView.backgroundColor = UIColor.clear contentView.alpha = 0 return contentView }() internal lazy var imageView: UIImageView = { [unowned self] in let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = UIColor.clear imageView.contentMode = .scaleAspectFill self.contentView.addSubview(imageView) return imageView }() internal lazy var titleLabel: UILabel = { [unowned self] in let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.backgroundColor = UIColor.clear titleLabel.font = UIFont.systemFont(ofSize: 27) titleLabel.textColor = UIColor(white: 0.6, alpha: 1) titleLabel.textAlignment = .center titleLabel.lineBreakMode = .byWordWrapping titleLabel.numberOfLines = 0 self.contentView.addSubview(titleLabel) return titleLabel }() internal lazy var descriptionLabel: UILabel = { [unowned self] in let descriptionLabel = UILabel() descriptionLabel.translatesAutoresizingMaskIntoConstraints = false descriptionLabel.backgroundColor = UIColor.clear descriptionLabel.font = UIFont.systemFont(ofSize: 17) descriptionLabel.textColor = UIColor(white: 0.6, alpha: 1) descriptionLabel.textAlignment = .center descriptionLabel.lineBreakMode = .byWordWrapping descriptionLabel.numberOfLines = 0 self.contentView.addSubview(descriptionLabel) return descriptionLabel }() internal var customView: UIView? { willSet { if let customView = customView { customView.removeFromSuperview() } } didSet { if let customView = customView { contentView.addSubview(customView) } } } internal var tapGesture: UITapGestureRecognizer? internal var verticalOffset = DefaultValues.verticalOffset internal var verticalSpaces = DefaultValues.verticalSpaces internal var titleMargin = DefaultValues.titleMargin internal var descriptionMargin = DefaultValues.descriptionMargin internal var shouldForceShowImageView = false internal var forcedImageViewSize: CGFloat = DefaultValues.forcedImageViewSize // MARK: - Helper fileprivate func shouldShowImageView() -> Bool { return imageView.image != nil } fileprivate func shouldShowTitleLabel() -> Bool { if let title = titleLabel.attributedText { return title.length > 0 } return false } fileprivate func shouldShowDescriptionLabel() -> Bool { if let description = descriptionLabel.attributedText { return description.length > 0 } return false } fileprivate func removeAllConstraints() { contentView.removeConstraints(contentView.constraints) removeConstraints(constraints) } // MARK: - View life cycle override init(frame: CGRect) { super.init(frame: frame) addSubview(self.contentView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func didMoveToSuperview() { frame = super.bounds UIView.animate(withDuration: 0.25, animations: { () -> Void in self.contentView.alpha = 1 }) } // MARK: - Actions // swiftlint:disable function_body_length internal func setConstraints() { let centerX = NSLayoutConstraint(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) let centerY = NSLayoutConstraint(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: verticalOffset) addConstraint(centerX) addConstraint(centerY) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[\(ViewStrings.contentView)]|", options: [], metrics: nil, views: [ViewStrings.contentView: contentView])) if let customView = customView { let translatesFrameIntoConstraints = customView.translatesAutoresizingMaskIntoConstraints customView.translatesAutoresizingMaskIntoConstraints = false if translatesFrameIntoConstraints { contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: .none, attribute: .notAnAttribute, multiplier: 1, constant: customView.frame.width)) contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .equal, toItem: .none, attribute: .notAnAttribute, multiplier: 1, constant: customView.frame.height)) contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[\(ViewStrings.customView)]|", options: [], metrics: nil, views: [ViewStrings.customView: customView])) } else { contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .leading, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: customView, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[\(ViewStrings.customView)]|", options: [], metrics: nil, views: [ViewStrings.customView: customView])) } } else { var viewStrings = [String]() var views = [String: UIView]() if shouldShowImageView() || shouldForceShowImageView { if imageView.superview == nil { contentView.addSubview(imageView) } let viewString = ViewStrings.imageView viewStrings.append(viewString) views[viewString] = imageView contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)) if shouldForceShowImageView { contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: forcedImageViewSize)) contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 0)) } } else { imageView.removeFromSuperview() } if shouldShowTitleLabel() { if titleLabel.superview == nil { contentView.addSubview(titleLabel) } let viewString = ViewStrings.titleLabel viewStrings.append(viewString) views[viewString] = titleLabel contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .leading, multiplier: 1, constant: titleMargin)) contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: titleLabel, attribute: .trailing, multiplier: 1, constant: titleMargin)) } else { titleLabel.removeFromSuperview() } if shouldShowDescriptionLabel() { if descriptionLabel.superview == nil { contentView.addSubview(descriptionLabel) } let viewString = ViewStrings.descriptionLabel viewStrings.append(viewString) views[viewString] = descriptionLabel contentView.addConstraint(NSLayoutConstraint(item: descriptionLabel, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: descriptionLabel, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .leading, multiplier: 1, constant: descriptionMargin)) contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: descriptionLabel, attribute: .trailing, multiplier: 1, constant: descriptionMargin)) } else { descriptionLabel.removeFromSuperview() } var verticalFormat = String() for (index, viewString) in viewStrings.enumerated() { verticalFormat += "[\(viewString)]" if index != viewStrings.count - 1 { let verticalSpace = index < verticalSpaces.count ? verticalSpaces[index] : DefaultValues.verticalSpace verticalFormat += "-(\(verticalSpace))-" } } if !verticalFormat.isEmpty { contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|\(verticalFormat)|", options: [], metrics: nil, views: views)) } } } internal func prepareForDisplay() { imageView.image = nil titleLabel.attributedText = nil descriptionLabel.attributedText = nil customView = nil removeAllConstraints() } internal func reset() { imageView.image = nil titleLabel.attributedText = nil descriptionLabel.attributedText = nil customView = nil tapGesture = nil removeAllConstraints() } }
7bdeccd537cc50598924e01f5b763219
46.682403
226
0.663096
false
false
false
false
JGiola/swift-package-manager
refs/heads/main
Sources/TSCUtility/StringMangling.swift
apache-2.0
3
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Extensions to `String` to provide various forms of identifier mangling. Many /// of them are programming-related. extension String { /// Returns a form of the string that is a valid bundle identifier public func spm_mangledToBundleIdentifier() -> String { let mangledUnichars: [UInt16] = self.utf16.map({ switch $0 { case // A-Z 0x0041...0x005A, // a-z 0x0061...0x007A, // 0-9 0x0030...0x0039, // - 0x2D, // . 0x2E: return $0 default: return 0x2D } }) return String(utf16CodeUnits: mangledUnichars, count: mangledUnichars.count) } /// Returns a form of the string that is valid C99 Extended Identifier (by /// replacing any invalid characters in an unspecified but consistent way). /// The output string is guaranteed to be non-empty as long as the input /// string is non-empty. public func spm_mangledToC99ExtendedIdentifier() -> String { // Map invalid C99-invalid Unicode scalars to a replacement character. let replacementUnichar: UnicodeScalar = "_" var mangledUnichars: [UnicodeScalar] = self.unicodeScalars.map({ switch $0.value { case // A-Z 0x0041...0x005A, // a-z 0x0061...0x007A, // 0-9 0x0030...0x0039, // _ 0x005F, // Latin (1) 0x00AA...0x00AA, // Special characters (1) 0x00B5...0x00B5, 0x00B7...0x00B7, // Latin (2) 0x00BA...0x00BA, 0x00C0...0x00D6, 0x00D8...0x00F6, 0x00F8...0x01F5, 0x01FA...0x0217, 0x0250...0x02A8, // Special characters (2) 0x02B0...0x02B8, 0x02BB...0x02BB, 0x02BD...0x02C1, 0x02D0...0x02D1, 0x02E0...0x02E4, 0x037A...0x037A, // Greek (1) 0x0386...0x0386, 0x0388...0x038A, 0x038C...0x038C, 0x038E...0x03A1, 0x03A3...0x03CE, 0x03D0...0x03D6, 0x03DA...0x03DA, 0x03DC...0x03DC, 0x03DE...0x03DE, 0x03E0...0x03E0, 0x03E2...0x03F3, // Cyrillic 0x0401...0x040C, 0x040E...0x044F, 0x0451...0x045C, 0x045E...0x0481, 0x0490...0x04C4, 0x04C7...0x04C8, 0x04CB...0x04CC, 0x04D0...0x04EB, 0x04EE...0x04F5, 0x04F8...0x04F9, // Armenian (1) 0x0531...0x0556, // Special characters (3) 0x0559...0x0559, // Armenian (2) 0x0561...0x0587, // Hebrew 0x05B0...0x05B9, 0x05BB...0x05BD, 0x05BF...0x05BF, 0x05C1...0x05C2, 0x05D0...0x05EA, 0x05F0...0x05F2, // Arabic (1) 0x0621...0x063A, 0x0640...0x0652, // Digits (1) 0x0660...0x0669, // Arabic (2) 0x0670...0x06B7, 0x06BA...0x06BE, 0x06C0...0x06CE, 0x06D0...0x06DC, 0x06E5...0x06E8, 0x06EA...0x06ED, // Digits (2) 0x06F0...0x06F9, // Devanagari and Special character 0x093D. 0x0901...0x0903, 0x0905...0x0939, 0x093D...0x094D, 0x0950...0x0952, 0x0958...0x0963, // Digits (3) 0x0966...0x096F, // Bengali (1) 0x0981...0x0983, 0x0985...0x098C, 0x098F...0x0990, 0x0993...0x09A8, 0x09AA...0x09B0, 0x09B2...0x09B2, 0x09B6...0x09B9, 0x09BE...0x09C4, 0x09C7...0x09C8, 0x09CB...0x09CD, 0x09DC...0x09DD, 0x09DF...0x09E3, // Digits (4) 0x09E6...0x09EF, // Bengali (2) 0x09F0...0x09F1, // Gurmukhi (1) 0x0A02...0x0A02, 0x0A05...0x0A0A, 0x0A0F...0x0A10, 0x0A13...0x0A28, 0x0A2A...0x0A30, 0x0A32...0x0A33, 0x0A35...0x0A36, 0x0A38...0x0A39, 0x0A3E...0x0A42, 0x0A47...0x0A48, 0x0A4B...0x0A4D, 0x0A59...0x0A5C, 0x0A5E...0x0A5E, // Digits (5) 0x0A66...0x0A6F, // Gurmukhi (2) 0x0A74...0x0A74, // Gujarti 0x0A81...0x0A83, 0x0A85...0x0A8B, 0x0A8D...0x0A8D, 0x0A8F...0x0A91, 0x0A93...0x0AA8, 0x0AAA...0x0AB0, 0x0AB2...0x0AB3, 0x0AB5...0x0AB9, 0x0ABD...0x0AC5, 0x0AC7...0x0AC9, 0x0ACB...0x0ACD, 0x0AD0...0x0AD0, 0x0AE0...0x0AE0, // Digits (6) 0x0AE6...0x0AEF, // Oriya and Special character 0x0B3D 0x0B01...0x0B03, 0x0B05...0x0B0C, 0x0B0F...0x0B10, 0x0B13...0x0B28, 0x0B2A...0x0B30, 0x0B32...0x0B33, 0x0B36...0x0B39, 0x0B3D...0x0B43, 0x0B47...0x0B48, 0x0B4B...0x0B4D, 0x0B5C...0x0B5D, 0x0B5F...0x0B61, // Digits (7) 0x0B66...0x0B6F, // Tamil 0x0B82...0x0B83, 0x0B85...0x0B8A, 0x0B8E...0x0B90, 0x0B92...0x0B95, 0x0B99...0x0B9A, 0x0B9C...0x0B9C, 0x0B9E...0x0B9F, 0x0BA3...0x0BA4, 0x0BA8...0x0BAA, 0x0BAE...0x0BB5, 0x0BB7...0x0BB9, 0x0BBE...0x0BC2, 0x0BC6...0x0BC8, 0x0BCA...0x0BCD, // Digits (8) 0x0BE7...0x0BEF, // Telugu 0x0C01...0x0C03, 0x0C05...0x0C0C, 0x0C0E...0x0C10, 0x0C12...0x0C28, 0x0C2A...0x0C33, 0x0C35...0x0C39, 0x0C3E...0x0C44, 0x0C46...0x0C48, 0x0C4A...0x0C4D, 0x0C60...0x0C61, // Digits (9) 0x0C66...0x0C6F, // Kannada 0x0C82...0x0C83, 0x0C85...0x0C8C, 0x0C8E...0x0C90, 0x0C92...0x0CA8, 0x0CAA...0x0CB3, 0x0CB5...0x0CB9, 0x0CBE...0x0CC4, 0x0CC6...0x0CC8, 0x0CCA...0x0CCD, 0x0CDE...0x0CDE, 0x0CE0...0x0CE1, // Digits (10) 0x0CE6...0x0CEF, // Malayam 0x0D02...0x0D03, 0x0D05...0x0D0C, 0x0D0E...0x0D10, 0x0D12...0x0D28, 0x0D2A...0x0D39, 0x0D3E...0x0D43, 0x0D46...0x0D48, 0x0D4A...0x0D4D, 0x0D60...0x0D61, // Digits (11) 0x0D66...0x0D6F, // Thai...including Digits 0x0E50...0x0E59 } 0x0E01...0x0E3A, 0x0E40...0x0E5B, // Lao (1) 0x0E81...0x0E82, 0x0E84...0x0E84, 0x0E87...0x0E88, 0x0E8A...0x0E8A, 0x0E8D...0x0E8D, 0x0E94...0x0E97, 0x0E99...0x0E9F, 0x0EA1...0x0EA3, 0x0EA5...0x0EA5, 0x0EA7...0x0EA7, 0x0EAA...0x0EAB, 0x0EAD...0x0EAE, 0x0EB0...0x0EB9, 0x0EBB...0x0EBD, 0x0EC0...0x0EC4, 0x0EC6...0x0EC6, 0x0EC8...0x0ECD, // Digits (12) 0x0ED0...0x0ED9, // Lao (2) 0x0EDC...0x0EDD, // Tibetan (1) 0x0F00...0x0F00, 0x0F18...0x0F19, // Digits (13) 0x0F20...0x0F33, // Tibetan (2) 0x0F35...0x0F35, 0x0F37...0x0F37, 0x0F39...0x0F39, 0x0F3E...0x0F47, 0x0F49...0x0F69, 0x0F71...0x0F84, 0x0F86...0x0F8B, 0x0F90...0x0F95, 0x0F97...0x0F97, 0x0F99...0x0FAD, 0x0FB1...0x0FB7, 0x0FB9...0x0FB9, // Georgian 0x10A0...0x10C5, 0x10D0...0x10F6, // Latin (3) 0x1E00...0x1E9B, 0x1EA0...0x1EF9, // Greek (2) 0x1F00...0x1F15, 0x1F18...0x1F1D, 0x1F20...0x1F45, 0x1F48...0x1F4D, 0x1F50...0x1F57, 0x1F59...0x1F59, 0x1F5B...0x1F5B, 0x1F5D...0x1F5D, 0x1F5F...0x1F7D, 0x1F80...0x1FB4, 0x1FB6...0x1FBC, // Special characters (4) 0x1FBE...0x1FBE, // Greek (3) 0x1FC2...0x1FC4, 0x1FC6...0x1FCC, 0x1FD0...0x1FD3, 0x1FD6...0x1FDB, 0x1FE0...0x1FEC, 0x1FF2...0x1FF4, 0x1FF6...0x1FFC, // Special characters (5) 0x203F...0x2040, // Latin (4) 0x207F...0x207F, // Special characters (6) 0x2102...0x2102, 0x2107...0x2107, 0x210A...0x2113, 0x2115...0x2115, 0x2118...0x211D, 0x2124...0x2124, 0x2126...0x2126, 0x2128...0x2128, 0x212A...0x2131, 0x2133...0x2138, 0x2160...0x2182, 0x3005...0x3007, 0x3021...0x3029, // Hiragana 0x3041...0x3093, 0x309B...0x309C, // Katakana 0x30A1...0x30F6, 0x30FB...0x30FC, // Bopmofo [sic] 0x3105...0x312C, // CJK Unified Ideographs 0x4E00...0x9FA5, // Hangul, 0xAC00...0xD7A3: return $0 default: return replacementUnichar } }) // Apply further restrictions to the prefix. loop: for (idx, c) in mangledUnichars.enumerated() { switch c.value { case // 0-9 0x0030...0x0039, // Annex D. 0x0660...0x0669, 0x06F0...0x06F9, 0x0966...0x096F, 0x09E6...0x09EF, 0x0A66...0x0A6F, 0x0AE6...0x0AEF, 0x0B66...0x0B6F, 0x0BE7...0x0BEF, 0x0C66...0x0C6F, 0x0CE6...0x0CEF, 0x0D66...0x0D6F, 0x0E50...0x0E59, 0x0ED0...0x0ED9, 0x0F20...0x0F33: mangledUnichars[idx] = replacementUnichar break loop default: break loop } } // Combine the characters as a string again and return it. // FIXME: We should only construct a new string if anything changed. // FIXME: There doesn't seem to be a way to create a string from an // array of Unicode scalars; but there must be a better way. return mangledUnichars.reduce("") { $0 + String($1) } } /// Mangles the contents to a valid C99 Extended Identifier. This method /// is the mutating version of `mangledToC99ExtendedIdentifier()`. public mutating func spm_mangleToC99ExtendedIdentifier() { self = spm_mangledToC99ExtendedIdentifier() } }
e8ca4d9d106ed3ec78473d61cfb54206
42.175781
84
0.486203
false
false
false
false
amosavian/swift-corelibs-foundation
refs/heads/master
Foundation/NSCFString.swift
apache-2.0
5
// 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 CoreFoundation internal class _NSCFString : NSMutableString { required init(characters: UnsafePointer<unichar>, length: Int) { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(extendedGraphemeClusterLiteral value: StaticString) { fatalError() } required init(stringLiteral value: StaticString) { fatalError() } required init(capacity: Int) { fatalError() } required init(string aString: String) { fatalError() } deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } override var length: Int { return CFStringGetLength(unsafeBitCast(self, to: CFString.self)) } override func character(at index: Int) -> unichar { return CFStringGetCharacterAtIndex(unsafeBitCast(self, to: CFString.self), index) } override func replaceCharacters(in range: NSRange, with aString: String) { CFStringReplace(unsafeBitCast(self, to: CFMutableString.self), CFRangeMake(range.location, range.length), aString._cfObject) } override var classForCoder: AnyClass { return NSMutableString.self } } internal final class _NSCFConstantString : _NSCFString { internal var _ptr : UnsafePointer<UInt8> { // FIXME: Split expression as a work-around for slow type // checking (tracked by SR-5322). let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size let offset = offTemp1 + offTemp2 let ptr = Unmanaged.passUnretained(self).toOpaque() return ptr.load(fromByteOffset: offset, as: UnsafePointer<UInt8>.self) } private var _lenOffset : Int { // FIXME: Split expression as a work-around for slow type // checking (tracked by SR-5322). let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size return offTemp1 + offTemp2 + MemoryLayout<UnsafePointer<UInt8>>.size } private var _lenPtr : UnsafeMutableRawPointer { return Unmanaged.passUnretained(self).toOpaque() } #if arch(s390x) internal var _length : UInt64 { return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt64.self) } #else internal var _length : UInt32 { return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt32.self) } #endif required init(characters: UnsafePointer<unichar>, length: Int) { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(extendedGraphemeClusterLiteral value: StaticString) { fatalError() } required init(stringLiteral value: StaticString) { fatalError() } required init(capacity: Int) { fatalError() } required init(string aString: String) { fatalError("Constant strings cannot be constructed in code") } deinit { fatalError("Constant strings cannot be deallocated") } override var length: Int { return Int(_length) } override func character(at index: Int) -> unichar { return unichar(_ptr[index]) } override func replaceCharacters(in range: NSRange, with aString: String) { fatalError() } override var classForCoder: AnyClass { return NSString.self } } internal func _CFSwiftStringGetLength(_ string: AnyObject) -> CFIndex { return (string as! NSString).length } internal func _CFSwiftStringGetCharacterAtIndex(_ str: AnyObject, index: CFIndex) -> UniChar { return (str as! NSString).character(at: index) } internal func _CFSwiftStringGetCharacters(_ str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UniChar>) { (str as! NSString).getCharacters(buffer, range: NSMakeRange(range.location, range.length)) } internal func _CFSwiftStringGetBytes(_ str: AnyObject, encoding: CFStringEncoding, range: CFRange, buffer: UnsafeMutablePointer<UInt8>?, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>?) -> CFIndex { let convertedLength: CFIndex switch encoding { // TODO: Don't treat many encodings like they are UTF8 case CFStringEncoding(kCFStringEncodingUTF8), CFStringEncoding(kCFStringEncodingISOLatin1), CFStringEncoding(kCFStringEncodingMacRoman), CFStringEncoding(kCFStringEncodingASCII), CFStringEncoding(kCFStringEncodingNonLossyASCII): let encodingView = (str as! NSString).substring(with: NSRange(range)).utf8 if let buffer = buffer { for (idx, character) in encodingView.enumerated() { buffer.advanced(by: idx).initialize(to: character) } } usedBufLen?.pointee = encodingView.count convertedLength = encodingView.count case CFStringEncoding(kCFStringEncodingUTF16): let encodingView = (str as! NSString)._swiftObject.utf16 let start = encodingView.startIndex if let buffer = buffer { for idx in 0..<range.length { // Since character is 2 bytes but the buffer is in term of 1 byte values, we have to split it up let character = encodingView[start.advanced(by: idx + range.location)] let byte0 = UInt8(character & 0x00ff) let byte1 = UInt8((character >> 8) & 0x00ff) buffer.advanced(by: idx * 2).initialize(to: byte0) buffer.advanced(by: (idx * 2) + 1).initialize(to: byte1) } } // Every character was 2 bytes usedBufLen?.pointee = range.length * 2 convertedLength = range.length default: fatalError("Attempted to get bytes of a Swift string using an unsupported encoding") } return convertedLength } internal func _CFSwiftStringCreateWithSubstring(_ str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).substring(with: NSMakeRange(range.location, range.length))._nsObject) } internal func _CFSwiftStringCreateCopy(_ str: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).copy() as! NSObject) } internal func _CFSwiftStringCreateMutableCopy(_ str: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((str as! NSString).mutableCopy() as! NSObject) } internal func _CFSwiftStringFastCStringContents(_ str: AnyObject, _ nullTerminated: Bool) -> UnsafePointer<Int8>? { return (str as! NSString)._fastCStringContents(nullTerminated) } internal func _CFSwiftStringFastContents(_ str: AnyObject) -> UnsafePointer<UniChar>? { return (str as! NSString)._fastContents } internal func _CFSwiftStringGetCString(_ str: AnyObject, buffer: UnsafeMutablePointer<Int8>, maxLength: Int, encoding: CFStringEncoding) -> Bool { return (str as! NSString).getCString(buffer, maxLength: maxLength, encoding: CFStringConvertEncodingToNSStringEncoding(encoding)) } internal func _CFSwiftStringIsUnicode(_ str: AnyObject) -> Bool { return (str as! NSString)._encodingCantBeStoredInEightBitCFString } internal func _CFSwiftStringInsert(_ str: AnyObject, index: CFIndex, inserted: AnyObject) { (str as! NSMutableString).insert((inserted as! NSString)._swiftObject, at: index) } internal func _CFSwiftStringDelete(_ str: AnyObject, range: CFRange) { (str as! NSMutableString).deleteCharacters(in: NSMakeRange(range.location, range.length)) } internal func _CFSwiftStringReplace(_ str: AnyObject, range: CFRange, replacement: AnyObject) { (str as! NSMutableString).replaceCharacters(in: NSMakeRange(range.location, range.length), with: (replacement as! NSString)._swiftObject) } internal func _CFSwiftStringReplaceAll(_ str: AnyObject, replacement: AnyObject) { (str as! NSMutableString).setString((replacement as! NSString)._swiftObject) } internal func _CFSwiftStringAppend(_ str: AnyObject, appended: AnyObject) { (str as! NSMutableString).append((appended as! NSString)._swiftObject) } internal func _CFSwiftStringAppendCharacters(_ str: AnyObject, chars: UnsafePointer<UniChar>, length: CFIndex) { (str as! NSMutableString).appendCharacters(chars, length: length) } internal func _CFSwiftStringAppendCString(_ str: AnyObject, chars: UnsafePointer<Int8>, length: CFIndex) { (str as! NSMutableString)._cfAppendCString(chars, length: length) }
9fea0d339e54fad4b9a7ae110b7f40e7
35.713115
232
0.691337
false
false
false
false
e-sites/Natrium
refs/heads/main
Sources/Helpers/PlistHelper.swift
mit
1
// // PlistHelper.swift // CommandLineKit // // Created by Bas van Kuijck on 11/02/2019. // import Foundation enum PlistHelper { static func getValue(`for` key: String, in plistFile: String) -> String? { guard let dic = NSDictionary(contentsOfFile: plistFile) else { return nil } return dic.object(forKey: key) as? String } private static func getValueType(_ value: String) -> String { if value == "true" || value == "false" { return "bool" } else if Int(value) != nil { return "integer" } else { return "string" } } static func write(value: String, `for` key: String, in plistFile: String) { let exists = Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Print :\(key)\"", "\"\(plistFile)\"", "2>/dev/null" ]) ?? "" if exists.isEmpty { let type = getValueType(value) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key) \(type) \(value)\"", "\"\(plistFile)\"" ]) } else { Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Set :\(key) \(value)\"", "\"\(plistFile)\"" ]) } } static func write(array: [String], `for` key: String, in plistFile: String) { remove(key: key, in: plistFile) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key) array\"", "\"\(plistFile)\"" ]) for value in array { let type = getValueType(value) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key): \(type) \(value)\"", "\"\(plistFile)\"" ]) } } static func remove(key: String, in plistFile: String) { Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Delete :\(key)\"", "\"\(plistFile)\"" ]) } }
ae2e8574c9ba536d73516717e6ade119
29.378378
96
0.496441
false
false
false
false
TouchInstinct/LeadKit
refs/heads/master
TIEcommerce/Sources/Filters/FiltersViewModel/BaseFilterViewModel.swift
apache-2.0
1
// // Copyright (c) 2022 Touch Instinct // // 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 TISwiftUtils import UIKit open class BaseFilterViewModel<CellViewModelType: FilterCellViewModelProtocol & Hashable, PropertyValue: FilterPropertyValueRepresenter & Hashable>: FilterViewModelProtocol { // MARK: - FilterViewModelProtocol public typealias Change = (indexPath: IndexPath, viewModel: CellViewModelType) public var values: [PropertyValue] = [] { didSet { filtersCollection?.update() } } public var selectedValues: [PropertyValue] = [] { didSet { filtersCollection?.update() } } public weak var filtersCollection: Updatable? public weak var pickerDelegate: FiltersPickerDelegate? public private(set) var cellsViewModels: [CellViewModelType] public init(filterPropertyValues: [PropertyValue], cellsViewModels: [CellViewModelType] = []) { self.values = filterPropertyValues self.cellsViewModels = cellsViewModels } open func filterDidSelected(atIndexPath indexPath: IndexPath) -> [Change] { let (selected, deselected) = toggleProperty(atIndexPath: indexPath) let changedValues = values .enumerated() .filter { selected.contains($0.element) || deselected.contains($0.element) } changedValues.forEach { index, element in let isSelected = selectedValues.contains(element) setSelectedCell(atIndex: index, isSelected: isSelected) setSelectedProperty(atIndex: index, isSelected: isSelected) } let changedItems = changedValues .map { Change(indexPath: IndexPath(item: $0.offset, section: .zero), viewModel: cellsViewModels[$0.offset]) } pickerDelegate?.filters(didSelected: selected) return changedItems } open func setSelectedCell(atIndex index: Int, isSelected: Bool) { cellsViewModels[index].isSelected = isSelected } open func setSelectedProperty(atIndex index: Int, isSelected: Bool) { values[index].isSelected = isSelected } }
d1f8e7314767f259bedaaae5cb515b37
36.837209
115
0.691149
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift
mit
1
// // FormDescriptor.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormDescriptor { // MARK: Properties public let title: String public var sections: [FormSectionDescriptor] = [] // MARK: Init public init(title: String) { self.title = title } // MARK: Public public func addSection(section: FormSectionDescriptor) { sections.append(section) } public func removeSectionAtIndex(index: Int) throws { guard index >= 0 && index < sections.count - 1 else { throw FormErrorType.SectionOutOfIndex } sections.removeAtIndex(index) } public func formValues() -> [String : AnyObject] { var formValues: [String : AnyObject] = [:] for section in sections { for row in section.rows { if row.rowType != .Button { if row.value != nil { formValues[row.tag] = row.value! } else { formValues[row.tag] = NSNull() } } } } return formValues } public func validateForm() -> FormRowDescriptor? { for section in sections { for row in section.rows { if let required = row.configuration[FormRowDescriptor.Configuration.Required] as? Bool { if required && row.value == nil { return row } } } } return nil } }
febc8dfce6e63669de9512747f15c367
24.848485
104
0.509379
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
Pods/Material/Sources/iOS/Icon.swift
apache-2.0
4
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public struct Icon { /// An internal reference to the icons bundle. private static var internalBundle: Bundle? /** A public reference to the icons bundle, that aims to detect the correct bundle to use. */ public static var bundle: Bundle { if nil == Icon.internalBundle { Icon.internalBundle = Bundle(for: View.self) let url = Icon.internalBundle!.resourceURL! let b = Bundle(url: url.appendingPathComponent("com.cosmicmind.material.icons.bundle")) if let v = b { Icon.internalBundle = v } } return Icon.internalBundle! } /// Get the icon by the file name. public static func icon(_ name: String) -> UIImage? { return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } /// Google icons. public static let add = Icon.icon("ic_add_white") public static let addCircle = Icon.icon("ic_add_circle_white") public static let addCircleOutline = Icon.icon("ic_add_circle_outline_white") public static let arrowBack = Icon.icon("ic_arrow_back_white") public static let arrowDownward = Icon.icon("ic_arrow_downward_white") public static let audio = Icon.icon("ic_audiotrack_white") public static let bell = Icon.icon("cm_bell_white") public static let cameraFront = Icon.icon("ic_camera_front_white") public static let cameraRear = Icon.icon("ic_camera_rear_white") public static let check = Icon.icon("ic_check_white") public static let clear = Icon.icon("ic_close_white") public static let close = Icon.icon("ic_close_white") public static let edit = Icon.icon("ic_edit_white") public static let email = Icon.icon("ic_email_white") public static let favorite = Icon.icon("ic_favorite_white") public static let favoriteBorder = Icon.icon("ic_favorite_border_white") public static let flashAuto = Icon.icon("ic_flash_auto_white") public static let flashOff = Icon.icon("ic_flash_off_white") public static let flashOn = Icon.icon("ic_flash_on_white") public static let history = Icon.icon("ic_history_white") public static let home = Icon.icon("ic_home_white") public static let image = Icon.icon("ic_image_white") public static let menu = Icon.icon("ic_menu_white") public static let moreHorizontal = Icon.icon("ic_more_horiz_white") public static let moreVertical = Icon.icon("ic_more_vert_white") public static let movie = Icon.icon("ic_movie_white") public static let pen = Icon.icon("ic_edit_white") public static let place = Icon.icon("ic_place_white") public static let phone = Icon.icon("ic_phone_white") public static let photoCamera = Icon.icon("ic_photo_camera_white") public static let photoLibrary = Icon.icon("ic_photo_library_white") public static let search = Icon.icon("ic_search_white") public static let settings = Icon.icon("ic_settings_white") public static let share = Icon.icon("ic_share_white") public static let star = Icon.icon("ic_star_white") public static let starBorder = Icon.icon("ic_star_border_white") public static let starHalf = Icon.icon("ic_star_half_white") public static let videocam = Icon.icon("ic_videocam_white") public static let visibility = Icon.icon("ic_visibility_white") public static let work = Icon.icon("ic_work_white") /// CosmicMind icons. public struct cm { public static let add = Icon.icon("cm_add_white") public static let arrowBack = Icon.icon("cm_arrow_back_white") public static let arrowDownward = Icon.icon("cm_arrow_downward_white") public static let audio = Icon.icon("cm_audio_white") public static let audioLibrary = Icon.icon("cm_audio_library_white") public static let bell = Icon.icon("cm_bell_white") public static let check = Icon.icon("cm_check_white") public static let clear = Icon.icon("cm_close_white") public static let close = Icon.icon("cm_close_white") public static let edit = Icon.icon("cm_pen_white") public static let image = Icon.icon("cm_image_white") public static let menu = Icon.icon("cm_menu_white") public static let microphone = Icon.icon("cm_microphone_white") public static let moreHorizontal = Icon.icon("cm_more_horiz_white") public static let moreVertical = Icon.icon("cm_more_vert_white") public static let movie = Icon.icon("cm_movie_white") public static let pause = Icon.icon("cm_pause_white") public static let pen = Icon.icon("cm_pen_white") public static let photoCamera = Icon.icon("cm_photo_camera_white") public static let photoLibrary = Icon.icon("cm_photo_library_white") public static let play = Icon.icon("cm_play_white") public static let search = Icon.icon("cm_search_white") public static let settings = Icon.icon("cm_settings_white") public static let share = Icon.icon("cm_share_white") public static let shuffle = Icon.icon("cm_shuffle_white") public static let skipBackward = Icon.icon("cm_skip_backward_white") public static let skipForward = Icon.icon("cm_skip_forward_white") public static let star = Icon.icon("cm_star_white") public static let videocam = Icon.icon("cm_videocam_white") public static let volumeHigh = Icon.icon("cm_volume_high_white") public static let volumeMedium = Icon.icon("cm_volume_medium_white") public static let volumeOff = Icon.icon("cm_volume_off_white") } }
26b1acc94e5caed81d514eaaaa8d0d7f
51.17037
104
0.717592
false
false
false
false
Adorkable-forkable/CleanroomLogger
refs/heads/master
Code/Implementation/DefaultLogFormatter.swift
mit
1
// // DefaultLogFormatter.swift // Cleanroom Project // // Created by Evan Maloney on 3/18/15. // Copyright (c) 2015 Gilt Groupe. All rights reserved. // import Foundation /** The `DefaultLogFormatter` is a basic implementation of the `LogFormatter` protocol. This implementation is used by default if no other log formatters are specified. */ public struct DefaultLogFormatter: LogFormatter { /** If `true`, the receiver will include the timestamp of the log entry when formatting the log message. */ public let includeTimestamp: Bool /** If `true`, the receiver will include an identifier for the calling thread when formatting the log message. This makes it possible to distinguish between distinct paths of execution when analyzing logs generated by multi-threaded applications. */ public let includeThreadID: Bool private static let timestampFormatter: NSDateFormatter = { let fmt = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS zzz" return fmt }() /** Initializes the DefaultLogFormatter using the given settings. :param: includeTimestamp If `true`, the log entry timestamp will be included in the formatted message. :param: includeThreadID If `true`, an identifier for the calling thread will be included in the formatted message. */ public init(includeTimestamp: Bool = false, includeThreadID: Bool = false) { self.includeTimestamp = includeTimestamp self.includeThreadID = includeThreadID } /** Returns a formatted representation of the given `LogEntry`. :param: entry The `LogEntry` being formatted. :returns: The formatted representation of `entry`. This particular implementation will never return `nil`. */ public func formatLogEntry(entry: LogEntry) -> String? { let severity = DefaultLogFormatter.stringRepresentationOfSeverity(entry.severity) let caller = DefaultLogFormatter.stringRepresentationForCallingFile(entry.callingFilePath, line: entry.callingFileLine) let message = DefaultLogFormatter.stringRepresentationForPayload(entry) var timestamp: String? if includeTimestamp { timestamp = DefaultLogFormatter.stringRepresentationOfTimestamp(entry.timestamp) } var threadID: String? if includeThreadID { threadID = DefaultLogFormatter.stringRepresentationOfThreadID(entry.callingThreadID) } return DefaultLogFormatter.formatLogMessageWithSeverity(severity, caller: caller, message: message, timestamp: timestamp, threadID: threadID) } /** Returns the formatted log message given the string representation of the severity, caller and message associated with a given `LogEntry`. This implementation is used by the `DefaultLogFormatter` for creating the log messages that will be recorded. :param: severity The string representation of the log entry's severity. :param: caller The string representation of the caller's source file and line. :param: message The log message. :param: timestamp An optional timestamp string to include in the message. :param: threadID An optional thread ID to include in the message. :returns: The formatted log message. */ public static func formatLogMessageWithSeverity(severity: String, caller: String, message: String, timestamp: String?, threadID: String?) -> String { var fmt = "" if let timestamp = timestamp { fmt += "\(timestamp) | " } if let threadID = threadID { fmt += "\(threadID) | " } fmt += "\(severity) | \(caller) — \(message)" return fmt } /** Returns a string representation of a given `LogSeverity` value. This implementation is used by the `DefaultLogFormatter` for creating string representations for representing the `severity` value of `LogEntry` instances. :param: severity The `LogSeverity` for which a string representation is desired. :returns: A string representation of the `severity` value. */ public static func stringRepresentationOfSeverity(severity: LogSeverity) -> String { var severityTag = severity.printableValueName.uppercaseString while severityTag.utf16.count < 7 { severityTag = " " + severityTag } return severityTag } /** Returns a string representation for a calling file and line. This implementation is used by the `DefaultLogFormatter` for creating string representations of a `LogEntry`'s `callingFilePath` and `callingFileLine` properties. :param: filePath The full file path of the calling file. :param: line The line number within the calling file. :returns: The string representation of `filePath` and `line`. */ public static func stringRepresentationForCallingFile(filePath: String, line: Int) -> String { let file = filePath.pathComponents.last ?? "(unknown)" return "\(file):\(line)" } /** Returns a string representation of an arbitrary optional value. This implementation is used by the `DefaultLogFormatter` for creating string representations of `LogEntry` payloads. :param: entry The `LogEntry` whose payload is desired in string form. :returns: The string representation of `entry`'s payload. */ public static func stringRepresentationForPayload(entry: LogEntry) -> String { switch entry.payload { case .Trace: return entry.callingFunction case .Message(let msg): return msg case .Value(let value): return stringRepresentationForValue(value) } } /** Returns a string representation of an arbitrary optional value. This implementation is used by the `DefaultLogFormatter` for creating string representations of `LogEntry` instances containing `.Value` payloads. :param: value The value for which a string representation is desired. :returns: If value is `nil`, the string "`(nil)`" is returned; otherwise, the return value of `stringRepresentationForValue(Any)` is returned. */ public static func stringRepresentationForValue(value: Any?) -> String { if let value = value { return stringRepresentationForValue(value) } else { return "(nil)" } } /** Returns a string representation of an arbitrary value. This implementation is used by the `DefaultLogFormatter` for creating string representations of `LogEntry` instances containing `.Value` payloads. :param: value The value for which a string representation is desired. :returns: A string representation of `value`. */ public static func stringRepresentationForValue(value: Any) -> String { let type = reflect(value).summary let desc: String if let debugValue = value as? CustomDebugStringConvertible { desc = debugValue.debugDescription } else if let printValue = value as? CustomStringConvertible { desc = printValue.description } else if let objcValue = value as? NSObject { desc = objcValue.description } else { desc = "(no description)" } return "<\(type): \(desc)>" } /** Returns a string representation of an `NSDate` timestamp. This implementation is used by the `DefaultLogFormatter` for creating string representations of a `LogEntry`'s `timestamp` property. :param: timestamp The timestamp. :returns: The string representation of `timestamp`. */ public static func stringRepresentationOfTimestamp(timestamp: NSDate) -> String { return timestampFormatter.stringFromDate(timestamp) } /** Returns a string representation of a thread identifier. This implementation is used by the `DefaultLogFormatter` for creating string representations of a `LogEntry`'s `callingThreadID` property. :param: threadID The thread identifier. :returns: The string representation of `threadID`. */ public static func stringRepresentationOfThreadID(threadID: UInt64) -> String { return NSString(format: "%08X", threadID) as String } }
62a497ea51c8e0cb72800170d81b82e1
32.526923
149
0.65986
false
false
false
false
sffernando/SwiftLearning
refs/heads/master
FoodTracker/FoodTracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // FoodTracker // // Created by koudai on 2016/11/29. // Copyright © 2016年 fernando. All rights reserved. // import UIKit class MealTableViewController: UITableViewController { //MARK: peropeties var meals = [Meal]() 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.leftBarButtonItem = editButtonItem if let savedMeals = loadMeals() { meals += savedMeals } else { loadSampleMeals() } } func loadSampleMeals() { let meal1 = Meal.init(name: "Caprese salad", photo: UIImage.init(named: "meal1"), rating: 5)! let meal2 = Meal.init(name: "Chicken and Potatoes", photo: UIImage.init(named: "meal2"), rating: 4)! let meal3 = Meal.init(name: "Pasta with Meatballs", photo: UIImage.init(named: "meal3"), rating: 3)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return meals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MealTableViewCell // Configure the cell... let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.image cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source meals.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) saveMeals() } 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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destination as! MealViewController if let selectCell = sender as? MealTableViewCell { let indexPath = tableView.indexPath(for: selectCell) let selectMeal = meals[(indexPath?.row)!] mealDetailViewController.meal = selectMeal } } else if segue.identifier == "AddItem" { print("Adding new meal.") } } @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal { if let selectIndexPath = tableView.indexPathForSelectedRow { meals[selectIndexPath.row] = meal tableView.reloadRows(at: [selectIndexPath], with: .none) } else { let newIndexPath = NSIndexPath.init(row: meals.count, section: 0) meals.append(meal) tableView.insertRows(at: [newIndexPath as IndexPath], with: .bottom) } saveMeals() } } //MARK: NSCoding func saveMeals() { let ifSuccessfulSaved = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path) if !ifSuccessfulSaved { print("Failed to save meals") } } func loadMeals() -> [Meal]? { return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal] } }
749d00fd0066536ec212603deb0885eb
34.493421
136
0.63911
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Foundation+Extras/TimeInterval+Formatter.swift
apache-2.0
1
// // TimeInterval+Formatter.swift // SwiftDate // // Created by Daniele Margutti on 14/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public extension TimeInterval { public struct ComponentsFormatterOptions { /// Fractional units may be used when a value cannot be exactly represented using the available units. /// For example, if minutes are not allowed, the value “1h 30m” could be formatted as “1.5h”. /// The default value of this property is false. public var allowsFractionalUnits: Bool = false /// Specify the units that can be used in the output. /// By default `[.year, .month, .weekOfMonth, .day, .hour, .minute, .second]` are used. public var allowedUnits: NSCalendar.Unit = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second] /// A Boolean value indicating whether to collapse the largest unit into smaller units when a certain threshold is met. /// By default is `false`. public var collapsesLargestUnit: Bool = false /// The maximum number of time units to include in the output string. /// The default value of this property is 0, which does not cause the elimination of any units. public var maximumUnitCount: Int = 0 /// The formatting style for units whose value is 0. /// By default is `.default` public var zeroFormattingBehavior: DateComponentsFormatter.ZeroFormattingBehavior = .default /// The preferred style for units. /// By default is `.abbreviated`. public var unitsStyle: DateComponentsFormatter.UnitsStyle = .abbreviated /// Locale of the formatter public var locale: LocaleConvertible? { set { self.calendar.locale = newValue?.toLocale() } get { return self.calendar.locale } } /// Calendar public var calendar: Calendar = Calendar.autoupdatingCurrent public func apply(toFormatter formatter: DateComponentsFormatter) { formatter.allowsFractionalUnits = self.allowsFractionalUnits formatter.allowedUnits = self.allowedUnits formatter.collapsesLargestUnit = self.collapsesLargestUnit formatter.maximumUnitCount = self.maximumUnitCount formatter.unitsStyle = self.unitsStyle formatter.calendar = self.calendar } public init() {} } /// Return the local thread shared formatter for date components private static func sharedFormatter() -> DateComponentsFormatter { let name = "SwiftDate_\(NSStringFromClass(DateComponentsFormatter.self))" return threadSharedObject(key: name, create: { let formatter = DateComponentsFormatter() formatter.includesApproximationPhrase = false formatter.includesTimeRemainingPhrase = false return formatter }) } @available(*, deprecated: 5.0.13, obsoleted: 5.1, message: "Use toIntervalString function instead") public func toString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String { return self.toIntervalString(options: callback) } /// Format a time interval in a string with desidered components with passed style. /// /// - Parameters: /// - units: units to include in string. /// - style: style of the units, by default is `.abbreviated` /// - Returns: string representation public func toIntervalString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String { let formatter = TimeInterval.sharedFormatter() var options = ComponentsFormatterOptions() callback?(&options) options.apply(toFormatter: formatter) return (formatter.string(from: self) ?? "") } /// Format a time interval in a string with desidered components with passed style. /// /// - Parameter options: options for formatting. /// - Returns: string representation public func toString(options: ComponentsFormatterOptions) -> String { let formatter = TimeInterval.sharedFormatter() options.apply(toFormatter: formatter) return (formatter.string(from: self) ?? "") } /// Return a string representation of the time interval in form of clock countdown (ie. 57:00:00) /// /// - Parameter zero: behaviour with zero. /// - Returns: string representation public func toClock(zero: DateComponentsFormatter.ZeroFormattingBehavior = .pad) -> String { return self.toIntervalString(options: { $0.unitsStyle = .positional $0.zeroFormattingBehavior = zero }) } /// Extract requeste time units components from given interval. /// Reference date's calendar is used to make the extraction. /// /// NOTE: /// Extraction is calendar/date based; if you specify a `refDate` calculation is made /// between the `refDate` and `refDate + interval`. /// If `refDate` is `nil` evaluation is made from `now()` and `now() + interval` in the context /// of the `SwiftDate.defaultRegion` set. /// /// - Parameters: /// - units: units to extract /// - from: starting reference date, `nil` means `now()` in the context of the default region set. /// - Returns: dictionary with extracted components public func toUnits(_ units: Set<Calendar.Component>, to refDate: DateInRegion? = nil) -> [Calendar.Component: Int] { let dateTo = (refDate ?? DateInRegion()) let dateFrom = dateTo.addingTimeInterval(-self) let components = dateFrom.calendar.dateComponents(units, from: dateFrom.date, to: dateTo.date) return components.toDict() } /// Express a time interval (expressed in seconds) in another time unit you choose. /// Reference date's calendar is used to make the extraction. /// /// - parameter component: time unit in which you want to express the calendar component /// - parameter from: starting reference date, `nil` means `now()` in the context of the default region set. /// /// - returns: the value of interval expressed in selected `Calendar.Component` public func toUnit(_ component: Calendar.Component, to refDate: DateInRegion? = nil) -> Int? { return self.toUnits([component], to: refDate)[component] } }
fa76ca21214f6219992ac32796cd4dc4
39.888112
121
0.728237
false
false
false
false
maxoll90/FSwift
refs/heads/master
FSwift/Network/ServiceUtil.swift
mit
3
// // ServiceUtil.swift // FSwift // // Created by Kelton Person on 11/15/14. // Copyright (c) 2014 Kelton. All rights reserved. // import Foundation let emptyBody:NSData = "".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! public class RequestResponse { public let statusCode: Int public let body: NSData public let headers: Dictionary<String, AnyObject> private var bodyText: String? init(statusCode: Int, body: NSData, headers: Dictionary<String, AnyObject>) { self.statusCode = statusCode self.body = body self.headers = headers } public var bodyAsText: String { if let bodyT = self.bodyText { return bodyT } else { self.bodyText = NSString(data: body, encoding: NSUTF8StringEncoding)! as String return self.bodyText! } } } public enum RequestMethod : String { case POST = "POST" case GET = "GET" case DELETE = "DELETE" case PUT = "PUT" case OPTIONS = "OPTIONS" case CONNECT = "CONNECT" case TRACE = "TRACE" case HEAD = "HEAD" } public extension String { func withParams(params: Dictionary<String, AnyObject>) -> String { let endpoint = self.hasPrefix("?") ? self : self + "?" return endpoint + (NSString(data: ServiceUtil.asParams(params), encoding: NSUTF8StringEncoding)! as String) } } public class ServiceUtil { public class func asJson(obj: AnyObject) -> NSData? { var error: NSError? return NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions.PrettyPrinted, error: &error) } public class func asParamsStr(params: Dictionary<String, AnyObject>) -> String { var pairs:[String] = [] for (key, value) in params { if let v = value as? Dictionary<String, AnyObject> { for (subKey, subValue) in v { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, subValue.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append("\(key)[\(subKey)]=\(escapedFormat)") } } else if let v = value as? [AnyObject] { for subValue in v { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, subValue.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append("\(key)[]=\(escapedFormat)") } } else { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, value.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append( "\(key)=\(escapedFormat)") } } let str = "&".join(pairs) return str } public class func asParams(params: Dictionary<String, AnyObject>) -> NSData { return asParamsStr(params).dataUsingEncoding(NSUTF8StringEncoding)! } public class func delete(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.DELETE, body: body, headers: headers) } public class func get(url:String, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.GET, body: emptyBody, headers: headers) } public class func post(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.POST, body: body, headers: headers) } public class func put(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.PUT, body: body, headers: headers) } public class func options(url:String, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.OPTIONS, body: emptyBody, headers: headers) } public class func request(url:String, requestMethod: RequestMethod, body: NSData, headers: Dictionary<String, AnyObject>) -> Future<RequestResponse> { let request = NSMutableURLRequest(URL: NSURL(string: url)!) let session = NSURLSession.sharedSession() request.HTTPMethod = requestMethod.rawValue request.HTTPBody = body for (headerKey, headerValue) in headers { if let multiHeader = headerValue as? [String] { for str in multiHeader { request.addValue(str, forHTTPHeaderField: headerKey) } } else { request.addValue(headerValue as? String, forHTTPHeaderField: headerKey) } } let promise = Promise<RequestResponse>() var error: NSError let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in if error != nil { promise.completeWith(error) } else { let httpResponse = response as! NSHTTPURLResponse var responseHeaders:Dictionary<String, AnyObject> = [:] for (headerKey, headerValue) in httpResponse.allHeaderFields { responseHeaders[headerKey as! String] = headerValue } promise.completeWith(RequestResponse(statusCode: httpResponse.statusCode, body: data, headers: responseHeaders)) } }) task.resume() return promise.future } }
f781e77ddef0d3579775cee7f9523b66
36.63522
174
0.609291
false
false
false
false
erremauro/Password-Update
refs/heads/master
Password Update/Utils.swift
mit
1
// // Utils.swift // Password Update // // Created by Roberto Mauro on 4/23/17. // Copyright © 2017 roberto mauro. All rights reserved. // import Cocoa import Foundation class Utils { static func getAppName() -> String { let kBundleName = kCFBundleNameKey as String let appTitle = Bundle.main.infoDictionary![kBundleName] as! String return appTitle.capitalized } static func getBundleId() -> String { return Bundle.main.bundleIdentifier! } static func dialogWith(title: String, text: String, isOK: Bool = true) { let popUp = NSAlert() popUp.messageText = title popUp.informativeText = text popUp.alertStyle = isOK ? NSAlertStyle.informational : NSAlertStyle.warning popUp.addButton(withTitle: "OK") popUp.runModal() } static func shakeWindow(_ window: NSWindow) { let numberOfShakes:Int = 4 let durationOfShake:Float = 0.6 let vigourOfShake:Float = 0.01 let frame:CGRect = (window.frame) let shakeAnimation = CAKeyframeAnimation() let shakePath = CGMutablePath() shakePath.move(to: CGPoint(x: NSMinX(frame), y: NSMinY(frame))) for _ in 1...numberOfShakes { shakePath.addLine(to: CGPoint( x:NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame) )) shakePath.addLine(to: CGPoint( x:NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame) )) } shakePath.closeSubpath() shakeAnimation.path = shakePath shakeAnimation.duration = CFTimeInterval(durationOfShake) window.animations = ["frameOrigin":shakeAnimation] window.animator().setFrameOrigin((window.frame.origin)) } }
6f1a14ccc106f3a8c394e2105dc1be7f
30.064516
76
0.599688
false
false
false
false
alexito4/SwiftSandbox
refs/heads/master
LinkedList.playground/Pages/CopyOnWrite.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation var str = "Hello, playground" public class Node<T> { var value: T { get { return _value! } set { _value = newValue } } var _value: T? var next: Node! var previous: Node! init() { next = self previous = self } } extension LinkedList { mutating func copy() -> LinkedList<T> { var copy = LinkedList<T>() for node in self { copy.append(value: node) } return copy } } public struct LinkedList<T> { fileprivate var sentinel = Node<T>() private var mutableSentinel: Node<T> { mutating get { if !isKnownUniquelyReferenced(&sentinel) { sentinel = self.copy().sentinel } return sentinel } } public mutating func append(value: T) { let newNode = Node<T>() newNode.value = value let sentinel = mutableSentinel newNode.next = sentinel newNode.previous = sentinel.previous sentinel.previous.next = newNode sentinel.previous = newNode } public func value(at index: Int) -> T? { return node(at: index)?.value } private func node(at index: Int) -> Node<T>? { if index >= 0 { var node = sentinel.next! var i = index while let _ = node._value { if i == 0 { return node } i -= 1 node = node.next } } return nil } public mutating func remove(at index: Int) -> T? { let _ = mutableSentinel let found = node(at: index) guard let node = found else { return nil } return remove(node) } public func remove(_ node: Node<T>) -> T { node.previous.next = node.next node.next.previous = node.previous return node.value } public mutating func removeAll() { let sentinel = mutableSentinel sentinel.next = sentinel sentinel.previous = sentinel } } extension LinkedList: CustomStringConvertible { public var description: String { var text = "[" var node = sentinel.next! while let value = node._value { text += "\(value)" node = node.next if node._value != nil { text += ", " } } return text + "]" } } public struct LinkedListIterator<T>: IteratorProtocol { var node: Node<T> mutating public func next() -> T? { let next = node.next! guard let value = next._value else { return nil } defer { node = next } return value } } extension LinkedList: Sequence { public func makeIterator() -> LinkedListIterator<T> { return LinkedListIterator(node: sentinel) } } var list = LinkedList<Int>() list.append(value: 0) list.append(value: 1) list.append(value: 2) list.append(value: 3) list.append(value: 4) print("Original \(list)") var copy = list copy.remove(at: 2) print("Copy \(copy)") print("List \(list)") list.value(at: 2) //: [Next](@next)
71429fb584fe34a40463b92a3255c6d2
20.272727
57
0.522894
false
false
false
false
vernon99/Gamp
refs/heads/master
Gamp/AppViewController.swift
gpl-3.0
1
// // AppViewController.swift // Gamp // // Created by Mikhail Larionov on 7/19/14. // Copyright (c) 2014 Mikhail Larionov. All rights reserved. // import UIKit class AppViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollForCards: UIScrollView! var cards:Array<GACardView> = [] override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.view.backgroundColor = UIColor.whiteColor() // Label var label = UILabel(frame: CGRectMake(0, 0, 200, 20)) label.center = CGPointMake(self.view.frame.width/2, 40) label.textAlignment = NSTextAlignment.Center label.textColor = PNGreenColor label.font = UIFont(name: "Avenir-Medium", size:23.0) label.text = "General metrics" self.view.addSubview(label) // Card for var buildNumber = 0; buildNumber < builds.count; buildNumber++ { var card:GACardView? = GACardView.instanceFromNib() if let currentCard = card { // Build number currentCard.buildString = builds[buildNumber].build // Date and time let dateStringFormatter = NSDateFormatter() dateStringFormatter.dateFormat = "MM.dd.yyyy" var startDate = dateStringFormatter.dateFromString(builds[buildNumber].date) var endDate = (buildNumber == 0 ? NSDate(timeIntervalSinceNow: -86400*1) : dateStringFormatter.dateFromString(builds[buildNumber-1].date)) var endDateMinusMonth = endDate.dateByAddingTimeInterval(-86400*30) if endDateMinusMonth.compare(startDate) == NSComparisonResult.OrderedDescending { startDate = endDateMinusMonth } currentCard.startDate = startDate currentCard.endDate = endDate var dateEnd = NSDate(timeIntervalSinceNow: -86400*1) var dateStart = NSDate(timeIntervalSinceNow: -86400*31) // Sizing and updating card layout currentCard.frame.origin = CGPoint(x: Int(currentCard.frame.width)*buildNumber, y: 50) currentCard.frame.size.height = self.view.frame.size.height - currentCard.frame.origin.y; currentCard.prepare() // Adding to the scroll and to the array cards.append(currentCard) self.scrollForCards.addSubview(currentCard) // Changing scroll size if buildNumber == 0 { currentCard.load() self.scrollForCards.frame.size.width = currentCard.frame.width self.scrollForCards.contentSize = CGSize(width: currentCard.frame.width * CGFloat(builds.count), height: self.scrollForCards.frame.height) } } } } func scrollViewDidScroll(scrollView: UIScrollView!) { var indexOfPage = scrollForCards.contentOffset.x / scrollForCards.frame.width; var currentPage = Int(indexOfPage); if !cards[currentPage].loadingStarted { cards[currentPage].load() } } init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } }
0042d5329f391f54370e5c8d671a363d
38.233333
158
0.590767
false
true
false
false
bendjones/GithubNotifications
refs/heads/master
Foo/Promise.swift
mit
1
// // Promise.swift // FruitilsKit // // Created by Ben Jones on 7/4/14. // Copyright (c) 2014 Avocado Software Inc. All rights reserved. // import Foundation final public class Promise<T> { public typealias Resolved = T -> () public typealias Rejected = NSError -> () public typealias Fulfilled = () -> () private var value: T? private var error: NSError? private var fulfilledCallbacks: [Fulfilled] private var resolvedCallbacks: [Resolved] private var rejectedCallbacks: [Rejected] private var resolved: Bool = false private var rejected: Bool = false private var canceled: Bool = false public required init() { fulfilledCallbacks = [Fulfilled]() resolvedCallbacks = [Resolved]() rejectedCallbacks = [Rejected]() } private var isFulfilled: Bool { get { return resolved || rejected } } /// Add a closure to be called when the promise is marked fulfilled, that is, either resolved or rejected /// /// :param: callback the closure to run when finished /// :returns: the promise which the callback was set for public func whenFulfilled(callback: Fulfilled) -> Self { if isFulfilled { callback() } else { fulfilledCallbacks.append(callback) } return self } /// Add a closure to be called when the promise is marked resolved /// /// :param: callback the closure to run when resolved, the closure is passed in the value passed to resolve /// :returns: the promise which the callback was set for public func whenResolved(callback: Resolved) -> Self { if resolved { callback(value!) } else { resolvedCallbacks.append(callback) } return self } /// Add a closure to be called the promise is marked rejected /// /// :param: callback the closure to run when rejected, the closure is passed in the error passed to reject /// :returns: the promise which the callback was set for public func whenRejected(callback: Rejected) -> Self { if rejected { callback(error!) } else { rejectedCallbacks.append(callback) } return self } /// Mark the promise resolved, the success case /// /// :param: value the returned result the promise was issued for, like a network request response public func resolve(value: T) -> Void { self.value = value resolved = true if canceled { return } for callback: Resolved in resolvedCallbacks { callback(value) } fulfill() } /// Mark the promise rejected, the failure case /// /// :param: error the error from the requested promise public func reject(err: NSError) -> Void { error = err rejected = true if canceled { return } for callback: Rejected in rejectedCallbacks { callback(err) } fulfill() } /// The promise has been fulfilled call all the fulfilled callbacks private func fulfill() -> Void { for callback: Fulfilled in fulfilledCallbacks { callback() } } /// Cancel the promise public func cancel() -> Void { canceled = true } }
d49c095959b9fd3c182b28e4e1fbcc4b
25.341085
111
0.599176
false
false
false
false
avinassh/Calculator-Swift
refs/heads/master
Calculator/CalculatorBrain.swift
mit
1
// // CalculatorBrain.swift // Calculator // // Created by avi on 09/02/15. // Copyright (c) 2015 avi. All rights reserved. // import Foundation class CalculatorBrain { private enum Op: Printable { case Operand(Double) case UnaryOperation(String, Double -> Double) case BinaryOperation(String, (Double, Double) -> Double) var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _): return symbol } } } } // Alternatives: // var opStack: Array<Op> = Array<Op>() // var opStack = Array<Op>() private var opStack = [Op]() // Alternatives: // var knownOps = Dictionary<String, Op>() private var knownOps = [String: Op]() // init does not require func keyword init() { func learnOp(op: Op) { knownOps[op.description] = op } learnOp(Op.BinaryOperation("+", +)) learnOp(Op.BinaryOperation("−") { $1 - $0 }) learnOp(Op.BinaryOperation("×", *)) learnOp(Op.BinaryOperation("÷") { $1 / $0 }) learnOp(Op.UnaryOperation("√", sqrt)) learnOp(Op.UnaryOperation("cos", cos)) learnOp(Op.UnaryOperation("sin", sin)) } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { // type of operation is Optional Op (CalculatorBrain.Op?) opStack.append(operation) } return evaluate() } func evaluate() -> Double? { let (result, remainder) = evaluate(opStack) println("\(opStack) = \(result) with \(remainder) left over") return result } private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case Op.Operand(let operand): return (operand, remainingOps) case Op.UnaryOperation(_, let operation): let operandEvaluation = evaluate(remainingOps) // following might work: //return (operation(operandEvaluation.result!), operandEvaluation.remainingOps) // however if result is nil, exception will be thrown and // crash our app if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } // now, in case result is nil, the if block will fail and // // control will come out and return (nil, ops) case Op.BinaryOperation(_, let operation): let op1Evalution = evaluate(remainingOps) if let operand1 = op1Evalution.result { let op2Evalution = evaluate(op1Evalution.remainingOps) if let operand2 = op2Evalution.result { return (operation(operand1, operand2), op2Evalution.remainingOps) } } } } return (nil, ops) } }
f735907463c83454abd26d26c92fc655
33.49505
95
0.5412
false
false
false
false
everald/JetPack
refs/heads/master
Sources/UI/ShapeView.swift
mit
1
import UIKit @objc(JetPack_ShapeView) open class ShapeView: View { private var normalFillColor: UIColor? private var normalStrokeColor: UIColor? public override init() { super.init() if let layerFillColor = shapeLayer.fillColor { fillColor = UIColor(cgColor: layerFillColor) } if let layerStrokeColor = shapeLayer.strokeColor { strokeColor = UIColor(cgColor: layerStrokeColor) } } public required init?(coder: NSCoder) { super.init(coder: coder) if let layerFillColor = shapeLayer.fillColor { fillColor = UIColor(cgColor: layerFillColor) } if let layerStrokeColor = shapeLayer.strokeColor { strokeColor = UIColor(cgColor: layerStrokeColor) } } open override func action(for layer: CALayer, forKey event: String) -> CAAction? { switch event { case "fillColor", "path", "strokeColor": if let animation = super.action(for: layer, forKey: "opacity") as? CABasicAnimation { animation.fromValue = shapeLayer.path animation.keyPath = event return animation } fallthrough default: return super.action(for: layer, forKey: event) } } open var fillColor: UIColor? { get { return normalFillColor } set { guard newValue != normalFillColor else { return } normalFillColor = newValue shapeLayer.fillColor = newValue?.tinted(with: tintColor).cgColor } } public var fillColorDimsWithTint = false { didSet { guard fillColorDimsWithTint != oldValue else { return } updateActualFillColor() } } @available(*, unavailable, message: "Don't override this.") // cannot mark as final open override class var layerClass: AnyClass { return CAShapeLayer.self } open var path: UIBezierPath? { get { guard let layerPath = shapeLayer.path else { return nil } return UIBezierPath(cgPath: layerPath) } set { let shapeLayer = self.shapeLayer guard let path = newValue else { shapeLayer.path = nil return } shapeLayer.fillRule = path.usesEvenOddFillRule ? .evenOdd : .nonZero switch path.lineCapStyle { case .butt: shapeLayer.lineCap = .butt case .round: shapeLayer.lineCap = .round case .square: shapeLayer.lineCap = .square } var dashPatternCount = 0 path.getLineDash(nil, count: &dashPatternCount, phase: nil) var dashPattern = [CGFloat](repeating: 0, count: dashPatternCount) var dashPhase = CGFloat(0) path.getLineDash(&dashPattern, count: nil, phase: &dashPhase) shapeLayer.lineDashPattern = dashPattern.map { $0 as NSNumber } shapeLayer.lineDashPhase = dashPhase switch path.lineJoinStyle { case .bevel: shapeLayer.lineJoin = .bevel case .miter: shapeLayer.lineJoin = .miter case .round: shapeLayer.lineJoin = .round } shapeLayer.lineWidth = path.lineWidth shapeLayer.miterLimit = path.miterLimit shapeLayer.path = path.cgPath } } public private(set) final lazy var shapeLayer: CAShapeLayer = self.layer as! CAShapeLayer open var strokeEnd: CGFloat { get { return shapeLayer.strokeEnd } set { shapeLayer.strokeEnd = newValue } } open var strokeColor: UIColor? { get { return normalStrokeColor } set { guard newValue != normalStrokeColor else { return } normalStrokeColor = newValue shapeLayer.strokeColor = newValue?.tinted(with: tintColor).cgColor } } public var strokeColorDimsWithTint = false { didSet { guard strokeColorDimsWithTint != oldValue else { return } updateActualStrokeColor() } } open var strokeStart: CGFloat { get { return shapeLayer.strokeStart } set { shapeLayer.strokeStart = newValue } } open override func tintColorDidChange() { super.tintColorDidChange() if let originalFillColor = normalFillColor, originalFillColor.tintAlpha != nil { shapeLayer.fillColor = originalFillColor.tinted(with: tintColor).cgColor } if let originalStrokeColor = normalStrokeColor, originalStrokeColor.tintAlpha != nil { shapeLayer.strokeColor = originalStrokeColor.tinted(with: tintColor).cgColor } } private func updateActualFillColor() { let actualFillColor = normalFillColor?.tinted(for: self, dimsWithTint: fillColorDimsWithTint).cgColor guard actualFillColor != shapeLayer.fillColor else { return } shapeLayer.fillColor = actualFillColor } private func updateActualStrokeColor() { let actualStrokeColor = normalStrokeColor?.tinted(for: self, dimsWithTint: strokeColorDimsWithTint).cgColor guard actualStrokeColor != shapeLayer.strokeColor else { return } shapeLayer.strokeColor = actualStrokeColor } }
9c6b7476f3c6a9ab6780ee6068488def
20.819048
109
0.716718
false
false
false
false
lukevanin/onthemap
refs/heads/master
OnTheMap/LoginViewController.swift
mit
1
// // LoginViewController.swift // OnTheMap // // Created by Luke Van In on 2017/01/12. // Copyright © 2017 Luke Van In. All rights reserved. // // View controller for login and signup. Presented modally by the tab bar controller. // import UIKit import SafariServices import FBSDKLoginKit // // Delegate for the login controller. Delegates login actions to an external object. // class LoginViewController: UIViewController { enum State { case pending case busy } private let contentSegue = "content" private var state: State = .pending { didSet { updateState() } } // MARK: Outlets @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var udacityLoginButton: UIButton! @IBOutlet weak var facebookLoginButton: UIButton! @IBOutlet weak var signupButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: Actions // // // @IBAction func unwindToLogin(_ segue: UIStoryboardSegue) { } // // Sign up button tapped. Show web view to allow user to create an account. // @IBAction func onSignUpAction(_ sender: Any) { resignResponders() let url = URL(string: "https://www.udacity.com/account/auth#!/signup") let viewController = SFSafariViewController(url: url!) present(viewController, animated: true, completion: nil) } // // Udacity login button tapped. Try to authenticate the user with the entered username and password. // @IBAction func onUdacityLoginAction(_ sender: Any) { // Resign focus from any input fields to dismiss the keyboard. resignResponders() // Get username text input. Show an error if the username field is blank. guard let username = usernameTextField.text, !username.isEmpty else { let message = "Please enter a username." showAlert(forErrorMessage: message) { [weak self] in self?.usernameTextField.becomeFirstResponder() } return } // Get password text input. Show an error if the password field is blank. guard let password = passwordTextField.text, !password.isEmpty else { let message = "Please enter a password." showAlert(forErrorMessage: message) { [weak self] in self?.passwordTextField.becomeFirstResponder() } return } // Attempt authentication with username and password. state = .busy let userService = UdacityUserService() let interactor = LoginUseCase( request: .credentials(username: username, password: password), service: userService, completion: handleLoginResult ) interactor.execute() } // // Facebook login button tapped. Authenticate the user with Facebook, then authorize the token with Udacity API. // @IBAction func onFacebookLoginAction(_ sender: Any) { // Resign focus from any input fields to dismiss the keyboard. resignResponders() state = .busy facebookLogin(completion: handleLoginResult) } // // // private func facebookLogin(completion: @escaping (Result<Bool>) -> Void) { let login = FBSDKLoginManager() let permissions = ["public_profile"] login.logIn(withReadPermissions: permissions, from: self) { (result, error) in // Show an error alert if an error occurred... if let error = error { completion(.failure(error)) return } // ... otherwise login with the facebook token. guard let result = result else { // Facebook login did not return an error or a result. Show error and go back to pending. let error = ServiceError.response completion(.failure(error)) return } guard !result.isCancelled else { // Operation cancelled by user. Just go back to the pending state. completion(.success(false)) return } guard let token = result.token.tokenString else { // No token returned in result. let error = ServiceError.authentication completion(.failure(error)) return } // Login to udacity with facebook token. let interactor = LoginUseCase( request: .facebook(token: token), service: UdacityUserService(), completion: completion ) interactor.execute() } } // // // private func handleLoginResult(_ result: Result<Bool>) { DispatchQueue.main.async { self.state = .pending switch result { case .success(let isAuthenticated): // Logged in successfully with facebook. if isAuthenticated { self.showContent() } case .failure(let error): // Facebook login failed. Show error self.showAlert(forError: error) } } } // // Resign focus from the input texfield and dismiss the keyboard. // private func resignResponders() { usernameTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } // // Show the primary app content after successful login. // private func showContent() { performSegue(withIdentifier: self.contentSegue, sender: nil) } // MARK: View life cycle override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateState() } // MARK: State // // Update the UI to display the current state. Disables input fields and shows activity indicator while login is // in progress. // private func updateState() { switch state { case .pending: configureUI(inputEnabled: true, activityVisible: false) case .busy: configureUI(inputEnabled: false, activityVisible: true) } } // // Configure the UI with the state. Disables/enables text and button interaction, and shows/hides activity // indicator. // private func configureUI(inputEnabled: Bool, activityVisible: Bool) { usernameTextField.isEnabled = inputEnabled passwordTextField.isEnabled = inputEnabled udacityLoginButton.isEnabled = inputEnabled facebookLoginButton.isEnabled = inputEnabled signupButton.isEnabled = inputEnabled if activityVisible { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } } // // Text field delegate for login controller. // extension LoginViewController: UITextFieldDelegate { // // Dismiss keyboard when done button is tapped. // func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
471756fcd616321af069c3e04d6f7926
29.220472
118
0.585461
false
false
false
false
apple/swift-argument-parser
refs/heads/main
Tests/ArgumentParserUnitTests/InputOriginTests.swift
apache-2.0
1
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import XCTest @testable import ArgumentParser final class InputOriginTests: XCTestCase {} extension InputOriginTests { func testIsDefaultValue() { func Assert(elements: [InputOrigin.Element], expectedIsDefaultValue: Bool) { let inputOrigin = InputOrigin(elements: elements) if expectedIsDefaultValue { XCTAssertTrue(inputOrigin.isDefaultValue) } else { XCTAssertFalse(inputOrigin.isDefaultValue) } } Assert(elements: [], expectedIsDefaultValue: false) Assert(elements: [.defaultValue], expectedIsDefaultValue: true) Assert(elements: [.argumentIndex(SplitArguments.Index(inputIndex: 1))], expectedIsDefaultValue: false) Assert(elements: [.defaultValue, .argumentIndex(SplitArguments.Index(inputIndex: 1))], expectedIsDefaultValue: false) } }
045afe82029c7a9803948c5c6a0ba01e
37.212121
121
0.650278
false
true
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/Specification/Operator.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. /// AND operator /// /// Combine two specifications into a single specification. /// /// This is a shorthand for the `Specification.and()` function. /// /// Both the `left` specifiction and the `right` specifiction must be satisfied. /// /// ## Example /// /// `let spec = onlyDigits & between2And4Letters & modulus13Checksum` /// /// /// - parameter left: The specification to be checked first. /// - parameter right: The specification to be checked last. /// /// - returns: A combined specification public func & (left: Specification, right: Specification) -> Specification { return left.and(right) } /// OR operator /// /// Combine two specifications into a single specification. /// /// This is a shorthand for the `Specification.or()` function. /// /// Either the `left` specifiction or the `right` specifiction must be satisfied. /// /// ## Example /// /// `let spec = connectionTypeWifi | connectionType4G | hasOfflineData` /// /// /// - parameter left: The specification to be checked first. /// - parameter right: The specification to be checked last. /// /// - returns: A combined specification public func | (left: Specification, right: Specification) -> Specification { return left.or(right) } /// Negate operator /// /// This is a shorthand for the `Specification.not()` function. /// /// This specifiction is satisfied, when the given specification is not satisfied. /// /// This specifiction is not satisfied, when the given specification is satisfied. /// /// ## Example /// /// `let spec = ! filesystemIsFull` /// /// /// - parameter specification: The specification to be inverted. /// /// - returns: A specification public prefix func ! (specification: Specification) -> Specification { return specification.not() } /// Equivalence operator /// /// This is a shorthand for the `Specification.isSatisfiedBy()` function /// /// ## Example: /// /// `let spec = CharacterSetSpecification.decimalDigits` /// `spec == "123"` /// /// /// - parameter left: The specification that is to perform the checking /// - parameter right: The candidate object that is to be checked. /// /// - returns: `true` if the candidate object satisfies the specification, `false` otherwise. public func == (left: Specification, right: Any?) -> Bool { return left.isSatisfiedBy(right) } /// Not equivalent operator /// /// This is a shorthand for the `Specification.isSatisfiedBy()` function /// /// ## Example: /// /// `let spec = CharacterSetSpecification.decimalDigits` /// `spec != "123"` /// /// /// - parameter left: The specification that is to perform the checking /// - parameter right: The candidate object that is to be checked. /// /// - returns: `true` if the candidate object doesn't satisfy the specification, `false` otherwise. public func != (left: Specification, right: Any?) -> Bool { return !left.isSatisfiedBy(right) }
f1bee6cdfe27a47113117eefd80ab341
28.393939
99
0.693814
false
false
false
false
authorfeng/argparse.swift
refs/heads/master
argparse.swift
unlicense
1
// // argparse.swift // // Created by authorfeng on 27/08/2017. // Copyright © 2017 Author Feng. All rights reserved. // import Foundation // MARK:- Const let SUPPRESS = "==SUPPRESS==" let OPTIONAL = "?" let ZERO_OR_MORE = "*" let ONE_OR_MORE = "+" let PARSER = "A..." let REMAINDER = "..." let _UNRECOGNIZED_ARGS_ATTR = "_unrecognized_args" // MARK:- Utility functions and classes func hasatter(_ obj: Any, _ name: String) -> Bool { let mirror = Mirror(reflecting: obj) for case let (label?, _) in mirror.children { if label == name { return true } } return false } func getEnvironmentVar(_ name: String) -> String? { guard let rawValue = getenv(name) else { return nil } return String(utf8String: rawValue) } func setEnvironmentVar(name: String, value: String, overwrite: Bool) { setenv(name, value, overwrite ? 1 : 0) } struct RegexHelper { let regex: NSRegularExpression? init(_ pattern: String) { regex = try! NSRegularExpression(pattern: "^-\\d+$|^-\\d*\\.\\d+$", options: NSRegularExpression.Options.caseInsensitive) } func match(_ input: String) -> Bool { if let matchs = regex?.matches(in: input, range: NSMakeRange(0, input.utf8.count)) { return matchs.count > 0 } else { return false } } } extension String { static let None = "" static let identifierMatcher = RegexHelper("[a-z0-9A-Z\\_]*") subscript (i: Int) -> Character { return self[self.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return self[start..<end] } subscript (r: ClosedRange<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return self[start...end] } func substring(from index: Int) -> String { return self.substring(from: self.index(self.startIndex, offsetBy: index)) } func substring(to index: Int) -> String { return self.substring(to: self.index(self.startIndex, offsetBy: index)) } func lstrip(inStr: String=" ") -> String { let trimedStr = self.trimmingCharacters(in: CharacterSet(charactersIn: inStr)) if trimedStr.isEmpty { return trimedStr } let range = self.localizedStandardRange(of: trimedStr) return self.substring(from:range!.lowerBound) } func join(_ objs: Array<Any>) -> String { var js = "" if objs.isEmpty { return js } for obj in objs { js += "\(obj)\(self)" } return js.substring(to: js.index(js.startIndex, offsetBy: js.utf8.count - self.utf8.count)) } func split(_ separator: String, _ maxSplits: Int) -> Array<String> { if maxSplits == 0 { return [self] } let arr = self.components(separatedBy: separator) if maxSplits < 0 || maxSplits + 1 >= arr.count { return arr } var retArr = Array(arr[arr.startIndex ..< maxSplits]) retArr.append("=".join(Array(arr[maxSplits ..< arr.endIndex]))) return retArr } func isidentifier() -> Bool { return String.identifierMatcher.match(self) } } extension Dictionary { func hasKey(_ key: Key) -> Bool { return self.keys.contains(key) } func hasattr(_ key: Key) -> Bool { return self.hasKey(key) } mutating func setattr(_ key: Key, _ value: Value) -> Void { self.updateValue(value, forKey: key) } mutating func setdefault(forKey key: Key, _ `default`: Value?=nil) -> Value? { if self.hasKey(key) { return self[key]! } else { if let deft = `default` { self.updateValue(deft, forKey: key) return deft } else { return nil } } } func get(forKey: Key, `default`: Value) -> Value { if self.hasKey(forKey) { return self[forKey]! } else { return `default` } } mutating func pop(forKey: Key, _ `default`: Value) -> Value { self.setdefault(forKey: forKey, `default`) return self.removeValue(forKey: forKey)! } mutating func update(_ dic: Dictionary<Key, Value>) { for k in dic.keys { self.updateValue(dic[k]!, forKey: k) } } } protocol _AttributeHolder { typealias Attribute = (String, Any?) var __dict__: Dictionary<String, Any?> { get } func __repr__() -> String func _get_kwargs() -> [Attribute] func _get_args() -> [Any] } extension _AttributeHolder { public func __repr__() -> String { let type_name = type(of: self) var arg_strings: [String] = [] var star_args: [String: Any] = [:] for arg in self._get_args() { arg_strings.append("\(arg)") } for (name, value) in self._get_kwargs() { if name.isidentifier() { arg_strings.append("\(name)=\(String(describing: value))") } else { star_args[name] = value } } if !star_args.isEmpty { arg_strings.append("**\(star_args)") } return "\(type_name)(\(", ".join(arg_strings))))" } public func _get_kwargs() -> [Attribute] { var kwargs: [Attribute] = [] for key in self.__dict__.keys.sorted() { kwargs.append((key, self.__dict__[key])) } return kwargs } public func _get_args() -> [Any] { return [] } } // MARK:- Formatting Help class _Formatter { func _indent() { } } class HelpFormatter: _Formatter { var _current_indent = 0 var _indent_increment = 0 var _max_help_position = 0 var _action_max_length = 0 var _level = 0 var _width = 80 var _prog = String.None var _root_section: _Section = _Section() let _whitespace_matcher: RegexHelper let _long_break_matcher: RegexHelper override init() { self._whitespace_matcher = RegexHelper(String.None) self._long_break_matcher = self._whitespace_matcher } required init(_ prog: String, _ indent_increment: Int, _ max_help_position: Int, _ width: Int) { // default setting for width let indent_increment = (indent_increment < 0) ? 2 : indent_increment let max_help_position = (max_help_position < 0) ? 24 : max_help_position let width = (width < 0) ? 80 : width self._prog = prog self._indent_increment = indent_increment self._max_help_position = max_help_position self._max_help_position = min(max_help_position, max(width - 20, indent_increment)) self._width = width self._current_indent = 0 self._level = 0 self._action_max_length = 0 self._whitespace_matcher = RegexHelper("\\s+") self._long_break_matcher = RegexHelper("\\n\\n\\n+") super.init() self._root_section = _Section(self, nil) } // MARK: Section and indentation methods override func _indent() { self._current_indent += self._indent_increment self._level += 1 } func _dedent() { self._current_indent -= self._indent_increment assert(self._current_indent >= 0, "Indent decreased below 0.") self._level -= 1 } class _Section { let formatter: _Formatter let parent: String // todo let heading: String var items: Array<Any> = [] init() { self.formatter = _Formatter() self.parent = String.None self.heading = String.None } init(_ formatter: HelpFormatter, _ parent: String?, _ heading: String=String.None) { self.formatter = formatter if (parent != nil) { self.parent = parent! } else { self.parent = String.None } self.heading = heading self.items = [] } func format_help() -> String { if !self.parent.isEmpty { self.formatter._indent() } return String.None } } func _add_item() { } // MARK: Message building methods func start_section() { } func end_section() { } func add_text(_ text: String) { } func add_usage(_ usage: String) { } func add_argument(_ action: Action) { } func add_arguments(_ actions: Array<Action>) { for action in actions { self.add_argument(action) } } // MARK: Help-formatting methods func format_help() -> String { return "" } func _join_parts(_ part_strings: Array<String>) -> String { return "" } func _format_usage(_ useage: String) -> String { return "" } func _format_actions_usage() -> String { return "" } func _format_text(_ text: String) -> String { return "" } func _format_action(_ action: Action) -> String { return "" } func _format_action_invocation(_ action: Action) -> String { return "" } func _metavar_formatter(_ action: Action, _ default_metavar: String) -> (Int) -> String { let result: String if action.metavar != nil { result = action.metavar! } else if !action.choices.isEmpty { let choice_strs = action.choices.map {String(describing: $0)} result = String("{\(", ".join(choice_strs))}") } else { result = default_metavar } func format(_ tuple_size: Int) -> String { // todo: return result } return format } func _format_args(_ action: Action, _ default_metavar: String) -> String { let get_metavar = self._metavar_formatter(action, default_metavar) var result = "" let metaver = get_metavar(1) if action.nargs == nil { result = metaver } else if let nargs = action.nargs as? String { if nargs == OPTIONAL { result = String("[\(metaver)]") } else if nargs == ZERO_OR_MORE { result = String("[\(metaver) [\(metaver) ...]]") } else if nargs == REMAINDER { result = "..." } else if nargs == PARSER { result = String("\(get_metavar(1)) ...)") } } else if let nargs = action.nargs as? Int { result = " ".join(Array(repeating: metaver, count: nargs)) } return result } func _expand_help(_ action: Action) -> String { return "" } func _iter_indented_subactions(_ action: Action) { } func _split_lines(_ text: String, _ width: Int) -> String { return "" } func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String { return "" } func _get_help_string(_ action: Action) -> String { return action.help } func _get_default_metavar_for_optional(_ action: Action) -> String { return action.dest!.uppercased() } func _get_default_metavar_for_positional(_ action: Action) -> String { return action.dest! } } class RawDescriptionHelpFormatter: HelpFormatter { override func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String { return "" } } class RawTextHelpFormatter: RawDescriptionHelpFormatter { func _fill_text(_ text: String, _ width: Int) -> String { return "" } } class ArgumentDefaultsHelpFormatter: HelpFormatter { override func _get_help_string(_ action: Action) -> String { return "" } } class MetavarTypeHelpFormatter: HelpFormatter { override func _get_default_metavar_for_optional(_ action: Action) -> String { return "" } override func _get_default_metavar_for_positional(_ action: Action) -> String { return "" } } // MARK:- Options and Arguments func _get_action_name(_ argument: Action) -> String { if !argument.option_strings.isEmpty { return "/".join(argument.option_strings) } else if let metavar = argument.metavar { if metavar != SUPPRESS { return metavar } } else if let dest = argument.dest { if dest != SUPPRESS { return dest } } return String.None } enum AE: Error { case ArgumentError(argument: Any, message: String) case ArgumentTypeError } // MARK:- Action classes let _ACTIONS_DICTIONARY = [ "_StoreAction.Type": _StoreAction.self, "_StoreConstAction.Type": _StoreConstAction.self, "_StoreTrueAction.Type": _StoreTrueAction.self, "_StoreFalseAction.Type": _StoreFalseAction.self, "_AppendAction.Type": _AppendAction.self, "_AppendConstAction.Type": _AppendConstAction.self, "_CountAction.Type": _CountAction.self, "_HelpAction.Type": _HelpAction.self, "_VersionAction.Type": _VersionAction.self, "_SubParsersAction.Type": _SubParsersAction.self, ] func isAction(_ actionName: String) -> Bool { return _ACTIONS_DICTIONARY.hasKey(actionName) } func getAction(_ actionName: String, _ kwargs: Dictionary<String, Any>) -> Action { switch actionName { case "_StoreAction.Type": return _StoreAction(kwargs) case "_StoreConstAction.Type": return _StoreConstAction(kwargs) // case "_StoreTrueAction.Type": // action = _StoreTrueAction(kwargs) // case "_StoreFalseAction.Type": // action = _StoreFalseAction(kwargs) // case "_AppendAction.Type": // action = _AppendAction(kwargs) // case "_AppendConstAction.Type": // action = _AppendConstAction(kwargs) // case "_CountAction.Type": // action = _CountAction(kwargs) case "_HelpAction.Type": return _HelpAction(kwargs) // case "_VersionAction.Type": // action = _VersionAction(kwargs) // case "_SubParsersAction.Type": // action = _SubParsersAction(kwargs) default: return Action() } } class Action: _AttributeHolder, Hashable, Equatable { var __dict__: Dictionary<String, Any?> var container: _ActionsContainer=_ActionsContainer() var required: Bool=false var option_strings: [String] { get { if let option_strings = self.__dict__["option_strings"] as? [String] { return option_strings } else { return [] } } set { self.__dict__.updateValue(newValue, forKey: "option_strings") } } var dest: String? { get { return self.__dict__["dest"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "dest") } } var nargs: Any? { get { return self.__dict__["nargs"] as Any } set { self.__dict__.updateValue(newValue, forKey: "nargs") } } var `const`: Any? { get { return self.__dict__["const"] as Any } set { self.__dict__.updateValue(newValue, forKey: "const") } } var `default`: Any? { get { return self.__dict__["default"] as Any } set { self.__dict__.updateValue(newValue, forKey: "default") } } var type: Any.Type? { get { return self.__dict__["type"] as! Any.Type? } set { self.__dict__.updateValue(newValue, forKey: "type") } } var choices: [Any] { get { if let option_strings = self.__dict__["choices"] as? [Any] { return option_strings } else { return [] } } set { self.__dict__.updateValue(newValue, forKey: "choices") } } var help: String { get { if let help = self.__dict__["help"] as? String { return help } else { return "" } } set { self.__dict__.updateValue(newValue, forKey: "help") } } var metavar: String? { get { return self.__dict__["metavar"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "metavar") } } init() { self.__dict__ = [:] } init(option_strings: Array<String>, dest: String, nargs: String?=nil, `const`: Any?=nil, `default`: Any?=nil, type: Any.Type?=nil, choices: Array<Any>=[], required: Bool=false, help: String=String.None, metavar: String=String.None ) { self.__dict__ = [:] self.option_strings = option_strings self.dest = dest self.nargs = nargs self.`const` = `const` self.`default` = `default` self.type = type self.choices = choices self.required = required self.help = help self.metavar = metavar } func _get_kwargs() -> [Attribute] { let names = [ "option_strings", "dest", "nargs", "const", "default", "type", "choices", "help", "metavar", ] return names.map { ($0, self.__dict__[$0]) } } func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { fatalError("\(type(of: self)).__call__() not defined") } var hashValue: Int { return self.dest!.hashValue } static func == (lhs: Action, rhs: Action) -> Bool { return lhs.hashValue == rhs.hashValue } } class _StoreAction: Action { init(_ kwargs: Dictionary<String, Any>) { if let nargsStr = kwargs["nargs"] as! String? { if let nargNum = Int(nargsStr) { if nargNum == 0 { fatalError("nargs for store actions must be > 0; if you have nothing to store, actions such as store true or store const may be more appropriate") } } } if let constStr = kwargs["const"] as! String? { if !constStr.isEmpty && (kwargs["nargs"] as! String) != OPTIONAL { fatalError("nargs must be \"\(OPTIONAL)\" to supply const") } } super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs["dest"] as! String, nargs: kwargs["nargs"] as! String?, const: kwargs.hasKey("const") ? kwargs["const"] as! String : String.None, default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None, type: kwargs["type"] as? Any.Type, required: kwargs.hasKey("required") ? kwargs["required"] as! Bool : false, help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None, metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { // setattr(namespace, self.dest, values) } } class _StoreConstAction: Action { init(_ kwargs: Dictionary<String, Any>) { super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs["dest"] as! String, nargs: "0", const: kwargs["const"] as! String, default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None, help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None, metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { } } class _StoreTrueAction: Action { } class _StoreFalseAction: Action { } class _AppendAction: Action { } class _AppendConstAction: Action { } class _CountAction: Action { } class _HelpAction: Action { init(_ kwargs: Dictionary<String, Any>) { super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs.hasKey("dest") ? kwargs["dest"] as! String : SUPPRESS, nargs: "0", default: kwargs.hasKey("default") ? kwargs["default"] as! String : SUPPRESS, help: kwargs["help"] as! String) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { } } class _VersionAction: Action { } class _SubParsersAction: Action { } // MARK:- Type classes class FileType { init() { } } // MARK:- Optional and Positional Parsing class Namespace: _AttributeHolder { var __dict__: Dictionary<String, Any?> init(_ kwargs: Dictionary<String, Any?>=[:]) { self.__dict__ = [:] for item in kwargs { self.__dict__.updateValue(item.value, forKey: item.key) } } } class _ActionsContainer { var _get_formatter_enable: Bool { get { return false } } var description: String? = nil var prefix_chars: String = "-" var `default`: String? = nil var conflict_handler: String = String.None var _defaults: Dictionary<String, Any> = [:] var _registries: Dictionary<String, Dictionary<String, String>> = [:] var _actions: Array<Action> = [] var _option_string_actions: Dictionary<String, Action> = [:] var _action_groups: Array<_ArgumentGroup> = [] var _mutually_exclusive_groups: Array<_ArgumentGroup> = [] var _negative_number_matcher: RegexHelper = RegexHelper(String.None) var _has_negative_number_optionals: Array<Any> = [] static let _CONFLICT_HANDLER = [ "_handle_conflict_error" : _handle_conflict_error, "_handle_conflict_resolve" : _handle_conflict_resolve, ] init() { } init(description: String?, prefix_chars: String, `default`: String?, conflict_handler: String) { self.description = description self.`default` = `default` self.prefix_chars = prefix_chars self.conflict_handler = conflict_handler // set up registries self._registries = [:] // register actions self.register(registry_name: "action", value: String.None, object: "_StoreAction.Type") self.register(registry_name: "action", value: "store", object: "_StoreAction.Type") self.register(registry_name: "action", value: "store_const", object: "_StoreConstAction.Type") self.register(registry_name: "action", value: "store_true", object: "_StoreTrueAction.Type") self.register(registry_name: "action", value: "store_false", object: "_StoreFalseAction.Type") self.register(registry_name: "action", value: "append", object: "_AppendAction.Type") self.register(registry_name: "action", value: "append_const", object: "_AppendConstAction.Type") self.register(registry_name: "action", value: "count", object: "_CountAction.Type") self.register(registry_name: "action", value: "help", object: "_HelpAction.Type") self.register(registry_name: "action", value: "version", object: "_VersionAction.Type") self.register(registry_name: "action", value: "parsers", object: "_SubParsersAction.Type") // raise an exception if the conflict handler is invalid self._get_handler() // action storage self._actions = [] self._option_string_actions = [:] // groups self._action_groups = [] self._mutually_exclusive_groups = [] // defaults storage self._defaults = [:] // determines whether an "option" looks like a negative number self._negative_number_matcher = RegexHelper("^-\\d+$|^-\\d*\\.\\d+$") // whether or not there are any optionals that look like negative // numbers -- uses a list so it can be shared and edited self._has_negative_number_optionals = [] } // MARK: Registration methods func register(registry_name: String, value: String, object: String) -> Void { self._registries.setdefault(forKey: registry_name, [:]) self._registries[registry_name]?.updateValue(object, forKey: value) } func _registry_get(registry_name: String, value: String, `default`: String=String.None) -> String { return self._registries[registry_name]!.get(forKey: value, default: `default`) } // MARK: Namespace default accessor methods func set_defaultsset_defaults(_ kwargs: Dictionary<String, Any>){ } func get_default() -> Any { return "" } // MARK: Adding argument actions func add_argument(_ args: String..., kwargs: Dictionary<String, Any>=[:]) -> Action { // if no positional args are supplied or only one is supplied and // it doesn't look like an option string, parse a positional argument let chars = self.prefix_chars var kwargs = kwargs if args.isEmpty || args.count == 1 && !chars.contains(args[0][0]){ if !args.isEmpty && kwargs.hasKey("dest") { fatalError("dest supplied twice for positional argument") } kwargs = self._get_positional_kwargs(dest: args.first!, kwargs: kwargs) } else { kwargs = self._get_optional_kwargs(args: args, kwargs: kwargs) } // otherwise, we're adding an optional argument if !kwargs.hasKey("default") { let dest = kwargs["dest"] as! String if self._defaults.keys.contains(dest) { kwargs["default"] = self._defaults[dest] } else if let deft = self.`default` { kwargs["default"] = deft } } // create the action object, and add it to the parser let actionName = self._pop_action_class(kwargs: kwargs) if !isAction(actionName) { fatalError("unknown action \"\(actionName)\"") } let action = getAction(actionName, kwargs) // raise an error if the metavar does not match the type let type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))") // todo // if not callable(type_func) { // fatalError("\(actionName) is not callable") // } // raise an error if the metavar does not match the type if self._get_formatter_enable { self._get_formatter()._format_args(action, String.None) // todo // catch TypeError // fatalError("length of metavar tuple does not match nargs") } return self._add_action(action) } func add_argument_group(args: String..., kwargs: Dictionary<String, Any>=[:]) -> _ArgumentGroup { let title = (args.count > 0) ? args.first : String.None let description = (args.count > 1) ? args[1] : String.None let group = _ArgumentGroup(container: self, title: title!, description: description, kwargs: kwargs) self._action_groups.append(group) return group } func add_mutually_exclusive_group() -> Void { } func _add_action(_ action: Action) -> Action { // resolve any conflicts self._check_conflict(action) // add to actions list self._actions.append(action) action.container = self // index the action by any option strings it has for option_string in action.option_strings { self._option_string_actions[option_string] = action } // set the flag if any option strings look like negative numbers for option_string in action.option_strings { if self._negative_number_matcher.match(option_string) { if !self._has_negative_number_optionals.isEmpty { self._has_negative_number_optionals.append(true) } } } // return the created action return action } func _get_handler() -> String { let handler_func_name = "_handle_conflict_\(self.conflict_handler)" if _ActionsContainer._CONFLICT_HANDLER.hasKey(handler_func_name) { return handler_func_name } else { fatalError("invalid conflict_resolution value: \(handler_func_name)") } } func _check_conflict(_ action: Action) { // find all options that conflict with this option var confl_optionals: Array<(String, Action)> = [] for option_string in action.option_strings { if self._option_string_actions.hasKey(option_string) { let confl_optional = self._option_string_actions[option_string] confl_optionals.append((option_string, confl_optional!)) } } // resolve any conflicts if !confl_optionals.isEmpty { let conflict_handler_func_name = self._get_handler() self._do_conflict_handle(conflict_handler_func_name, action, confl_optionals) } } func _handle_conflict_error(_ action: Action, _ conflicting_actions: Array<(String, Action)>) { var message = "" // todo ", ".join(conflicting_actions) // todo: ArgumentError fatalError(message) } func _handle_conflict_resolve(_ action: Action, _ confl_optionals: Array<(String, Action)>) { } func _do_conflict_handle(_ conflict_handler_func_name: String, _ action: Action, _ confl_optionals: Array<(String, Action)>) { switch conflict_handler_func_name { case "_handle_conflict_error": self._handle_conflict_error(action, confl_optionals) break case "_handle_conflict_resolve": self._handle_conflict_resolve(action, confl_optionals) break default: break } } func _add_container_actions(_ container: _ActionsContainer) -> Void { } func _get_positional_kwargs(dest: String, kwargs: Dictionary<String, Any>) -> Dictionary<String, Any> { var kwargs = kwargs if kwargs.hasKey("required") { fatalError("'required' is an invalid argument for positionals") } if ![OPTIONAL, ZERO_OR_MORE].contains(kwargs["nargs"] as! String) { kwargs["required"] = true } if kwargs["nargs"] as! String == ZERO_OR_MORE && !kwargs.keys.contains("default") { kwargs["required"] = true } kwargs["dest"] = dest kwargs["option_strings"] = [] return kwargs } func _get_optional_kwargs(args: Array<String>, kwargs: Dictionary<String, Any>) -> Dictionary<String, Any> { // determine short and long option strings var kwargs = kwargs var option_strings: Array<String> = [] var long_option_strings: Array<String> = [] for option_string in args { // error on strings that don't start with an appropriate prefix if !self.prefix_chars.contains(option_string[0]) { fatalError("invalid option string \(option_string): must start with a character \(self.prefix_chars)") } // strings starting with two prefix characters are long options option_strings.append(option_string) if option_string.lengthOfBytes(using: String.Encoding.utf8) > 1 && self.prefix_chars.contains(option_string[1]) { long_option_strings.append(option_string) } } // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' var dest:String = String.None if kwargs.hasKey("dest") { dest = kwargs["dest"] as! String } if dest.isEmpty { var dest_option_string:String if !long_option_strings.isEmpty { dest_option_string = long_option_strings.first! } else { dest_option_string = option_strings.first! } dest = dest_option_string.lstrip(inStr: self.prefix_chars) if dest.isEmpty { fatalError("dest: is required for options like \(option_strings)") } dest = dest.replacingOccurrences(of: "-", with: "_") } // return the updated keyword arguments kwargs["dest"] = dest kwargs["option_strings"] = option_strings return kwargs } func _pop_action_class(kwargs: Dictionary<String, Any>, _ `default`: String=String.None) -> String { var kwargs = kwargs let action = kwargs.pop(forKey: "action", `default`) as! String return self._registry_get(registry_name: "action", value: action, default: action) } func _get_formatter() -> HelpFormatter { fatalError("_get_formatter() not implemented in \(Mirror(reflecting: self).subjectType))") } } class _ArgumentGroup: _ActionsContainer { var title: String = String.None var _group_actions: Array<Action.Type> = [] override init() { super.init() } init(container: _ActionsContainer, title: String=String.None, description: String=String.None, kwargs: Dictionary<String, Any>) { var kwargs = kwargs // add any missing keyword arguments by checking the container kwargs.setdefault(forKey: "conflict_handler", container.conflict_handler) kwargs.setdefault(forKey: "prefix_chars", container.prefix_chars) kwargs.setdefault(forKey: "default", container.`default`) super.init(description: description, prefix_chars: kwargs["prefix_chars"] as! String, default: kwargs["default"] as? String, conflict_handler: kwargs["conflict_handler"] as! String) // group attributes self.title = title self._group_actions = [] // share most attributes with the container self._registries = container._registries self._actions = container._actions self._option_string_actions = container._option_string_actions self._defaults = container._defaults self._has_negative_number_optionals = container._has_negative_number_optionals self._mutually_exclusive_groups = container._mutually_exclusive_groups } } class _MutuallyExclusiveGroup: _ArgumentGroup { } class ArgumentParser: _ActionsContainer, _AttributeHolder { var __dict__: Dictionary<String, Any?> override var _get_formatter_enable: Bool { get { return true } } var allow_abbrev: Bool=true var epilog: String? var fromfile_prefix_chars: String?=nil var _positionals: _ArgumentGroup=_ArgumentGroup() var _optionals: _ArgumentGroup=_ArgumentGroup() var _subparsers: _ArgumentGroup? var prog: String? { get { return self.__dict__["prog"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "prog") } } var formatter_class: HelpFormatter.Type { get { if let formatter_class = self.__dict__["formatter_class"] as? HelpFormatter.Type { return formatter_class } else { return HelpFormatter.self } } set { self.__dict__.updateValue(newValue, forKey: "formatter_class") } } var add_help: Bool { get { if let add_help = self.__dict__["add_help"] as? Bool { return add_help } else { return true } } set { self.__dict__.updateValue(newValue, forKey: "add_help") } } var usage: String? { get { return self.__dict__["usage"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "usage") } } override var description: String? { get { return self.__dict__["description"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "description") } } override var conflict_handler: String { get { if let conflict_handler = self.__dict__["conflict_handler"] as? String { return conflict_handler } else { return "error" } } set { self.__dict__.updateValue(newValue, forKey: "conflict_handler") } } init(prog: String? = nil, usage: String? = nil, description: String? = nil, epilog: String? = nil, parents: Array<_ActionsContainer>=[], formatter_class: HelpFormatter.Type = HelpFormatter.self, prefix_chars: String = "-", fromfile_prefix_chars: String? = nil, `default`: String? = nil, conflict_handler: String = "error", add_help: Bool=true, allow_abbrev: Bool=true) { self.__dict__ = [:] super.init(description: description, prefix_chars: prefix_chars, default: `default`, conflict_handler: conflict_handler) // default setting for prog if let _ = prog { self.prog = prog } else { // todo: path.basename self.prog = CommandLine.arguments[0] } self.usage = usage self.epilog = epilog self.formatter_class = formatter_class self.fromfile_prefix_chars = fromfile_prefix_chars self.add_help = add_help self.allow_abbrev = allow_abbrev self._positionals = self.add_argument_group(args: "positional arguments") self._optionals = self.add_argument_group(args: "optional arguments") self._subparsers = nil // register types class identity: Action { } self.register(registry_name: "type", value: String.None, object: "identity.self") // add help argument if necessary // (using explicit default to override global default) let default_prefix = prefix_chars.contains("-") ? "-" : prefix_chars[0] if self.add_help { self.add_argument(default_prefix+"h", default_prefix+default_prefix+"help", kwargs: ["action": "help", "default": SUPPRESS, "help": "show this help message and exit"]) } // add parent arguments and defaults for parent in parents { self._add_container_actions(parent) // todo // let defaults = parent._defaults // self._defaults.update(defaults) } } // MARK: Pretty __repr__ methods func _get_kwargs() -> [Attribute] { let names = [ "prog", "usage", "description", "formatter_class", "conflict_handler", "add_help", ] return names.map { ($0, self.__dict__[$0]) } } // MARK: Optional/Positional adding methods func add_subparsers(_ kwargs: Dictionary<String, Any>) -> Action { return Action() } // MARK: Command line argument parsing methods func parse_args(_ args: Array<String>=[], _ namespace: Dictionary<String, Any>=[:]) -> Dictionary<String, Any> { let (args, argv) = self.parse_known_args(args: args, namespace: namespace) if !argv.isEmpty { fatalError("unrecognized arguments: \(argv.joined(separator: " "))") } return args } func parse_known_args( args: Array<String>=[], namespace: Dictionary<String, Any>=[:]) -> (Dictionary<String, Any>, Array<String>) { var namespace = namespace var args = args if args.isEmpty { // args default to the system args args = Array(CommandLine.arguments.suffix(from: 1)) } else { // make sure that args are mutable } // default Namespace built from parser defaults // if namespace is None: // namespace = Namespace() // add any action defaults that aren't present for action in self._actions { if action.dest != SUPPRESS { // if !hasattr(obj: namespace, name: action.dest) { if !namespace.hasattr(action.dest!) { var defaultEqualSUPPRESS = false if let `default` = action.`default` as? String { defaultEqualSUPPRESS = (`default` == SUPPRESS) } if !defaultEqualSUPPRESS { namespace.updateValue(action.`default`, forKey: action.dest!) } } } } // add any parser defaults that aren't present for dest in self._defaults.keys { // if !hasattr(obj: namespace, name: dest) { if !namespace.hasattr(dest) { namespace.updateValue(self._defaults[dest], forKey: dest) } } //# parse the arguments and exit if there are any errors (namespace, args) = self._parse_known_args(arg_strings: args, namespace: namespace) // if hasattr(obj: namespace, name: _UNRECOGNIZED_ARGS_ATTR) { if namespace.hasattr(_UNRECOGNIZED_ARGS_ATTR) { args += namespace[_UNRECOGNIZED_ARGS_ATTR] as! Array<String> namespace.removeValue(forKey: _UNRECOGNIZED_ARGS_ATTR) } return (namespace, args) } func _parse_known_args(arg_strings: Array<String>, namespace: Dictionary<String, Any>) -> (Dictionary<String, Any>, Array<String>) { var arg_strings = arg_strings // replace arg strings that are file references if (self.fromfile_prefix_chars != String.None) { arg_strings = self._read_args_from_files(arg_strings: arg_strings) } // map all mutually exclusive arguments to the other arguments // they can't occur with var action_conflicts: Dictionary<Action, Any> = [:] for mutex_group in self._mutually_exclusive_groups { let group_actions = mutex_group._group_actions var c = 0 for mutex_action in mutex_group._group_actions { c += 1 // todo } } // find all option indices, and determine the arg_string_pattern // which has an 'O' if there is an option at an index, // an 'A' if there is an argument, or a '-' if there is a '--' var option_string_indices: Dictionary<Int, Any> = [:] var arg_string_pattern_parts: Array<String> = [] var i = 0 for arg_string in arg_strings { // all args after -- are non-options if arg_string == "--" { arg_string_pattern_parts.append("-") for arg_string in arg_strings { arg_string_pattern_parts.append("A") } } // otherwise, add the arg to the arg strings // and note the index if it was an option else { let option_tuple = self._parse_optional(arg_string) var pattern: String if option_tuple.isEmpty { pattern = "A" } else { option_string_indices[i] = option_tuple pattern = "O" } arg_string_pattern_parts.append(pattern) } } // join the pieces together to form the pattern let arg_strings_pattern = "".join(arg_string_pattern_parts) // converts arg strings to the appropriate and then takes the action var seen_actions = Set<Action>() var seen_non_default_actions = Set<Action>() func take_action(_ action: Action, _ argument_strings: Array<String>, option_string: String?=nil) { seen_actions.insert(action) let argument_values = self._get_values(action, argument_strings) // error if this argument is not allowed with other previously seen arguments, // assuming that actions that use the default value don't really count as "present" if argument_values as! _OptionalNilComparisonType != action.`default` { seen_non_default_actions.insert(action) if let actions = action_conflicts[action] { if let actionArray = actions as? Array<Action> { for conflict_action in actionArray { if seen_non_default_actions.contains(conflict_action) { // raise ArgumentError fatalError("not allowed with argument \(_get_action_name(conflict_action))") } } } } } // take the action if we didn't receive a SUPPRESS value (e.g. from a default) var takeAction = true if let avStr = argument_values as? String { if avStr == SUPPRESS { takeAction = false } } if takeAction { action.__call__(self, namespace, argument_values, option_string) } } return ([:], []) } func _read_args_from_files(arg_strings: Array<String>) -> Array<String> { return arg_strings } func convert_arg_line_to_args(_ arg_line: String) -> Array<String> { return [arg_line] } func _match_argument(_ action: Action, _ arg_strings_pattern: String) -> Int { return 0 } func _match_arguments_partial(_ action: Action, _ arg_strings_pattern: String) -> Array<String> { var result: Array<String> = [] return result } func _parse_optional(_ arg_string: String) -> Array<Any> { // if it's an empty string, it was meant to be a positional if arg_string.isEmpty { return [] } // if it doesn't start with a prefix, it was meant to be positional if !self.prefix_chars.contains(arg_string[0]) { return [] } // if the option string is present in the parser, return the action if self._option_string_actions.hasKey(arg_string) { let action = self._option_string_actions[arg_string] return [action, arg_string, String.None] } // if it's just a single character, it was meant to be positional if arg_string.utf8.count == 1 { return [] } // if the option string before the "=" is present, return the action if arg_string.contains("=") { let splitedStr = arg_string.split("=", 1) let option_string = splitedStr.first! let explicit_arg = splitedStr.last! if self._option_string_actions.hasKey(option_string) { let action = self._option_string_actions[option_string] return [action, option_string, explicit_arg] } } if self.allow_abbrev { // search through all possible prefixes of the option string // and all actions in the parser for possible interpretations let option_tuples = self._get_option_tuples(arg_string) // if multiple actions match, the option string was ambiguous if option_tuples.count > 1 { let options = ", ".join(option_tuples.map {"\($0[1] as! String)"}) self.error("ambiguous option: \(arg_string) could match \(options)") } // if exactly one action matched, this segmentation is good, // so return the parsed action else if option_tuples.count == 1 { return option_tuples.first! } } // if it was not found as an option, but it looks like a negative // number, it was meant to be positional // unless there are negative-number-like options if self._negative_number_matcher.match(arg_string) { if self._has_negative_number_optionals.isEmpty { return [] } } // if it contains a space, it was meant to be a positional if arg_string.contains(" ") { return [] } // it was meant to be an optional but there is no such option // in this parser (though it might be a valid option in a subparser) return [String.None, arg_string, String.None] } func _get_option_tuples(_ option_string: String) -> Array<Array<Any>> { var result: Array<Array<Any>> = [] // option strings starting with two prefix characters are only split at the '=' let chars = self.prefix_chars var option_prefix: String var explicit_arg: String if chars.contains(option_string[0]) && chars.contains(option_string[1]) { if option_string.contains("=") { let arr = option_string.split("=", 1) option_prefix = arr.first! explicit_arg = arr.last! } else { option_prefix = option_string explicit_arg = String.None } for option_string in self._option_string_actions.keys { if option_string.hasPrefix(option_prefix) { let action: Action = self._option_string_actions[option_string]! let tup: Array<Any> = [action, option_string, explicit_arg] result.append(tup) } } } // single character options can be concatenated with their arguments // but multiple character options always have to have their argument separate else if chars.contains(option_string[0]) && !chars.contains(option_string[1]) { option_prefix = option_string explicit_arg = String.None let short_option_prefix = option_string.substring(to: 2) let short_explicit_arg = option_string.substring(from: 2) for option_string in self._option_string_actions.keys { if option_string == short_option_prefix { let action = self._option_string_actions[option_string] let tup: Array<Any> = [action, option_string, short_explicit_arg] result.append(tup) } else if option_string.hasPrefix(option_prefix) { let action = self._option_string_actions[option_string] let tup: Array<Any> = [action, option_string, short_explicit_arg] result.append(tup) } } } // shouldn't ever get here else { self.error("unexpected option string: \(option_string)") } // return the collected option tuples return result } func _get_nargs_pattern(_ action: Action) -> String { return String.None } // MAKR: Value conversion methods func _get_values(_ action: Action, _ arg_strings: Array<String>) -> Any { // for everything but PARSER, REMAINDER args, strip out first '--' var arg_strings = arg_strings var needRemove = true if let nargs = action.nargs as? String { if [PARSER, REMAINDER].contains(nargs) { needRemove = false } } if needRemove { // arg_strings.remove("--") var index = arg_strings.count - 1 while index >= 0 { if "--" == arg_strings[index] { arg_strings.remove(at: index) } index -= 1 } } // optional argument produces a default when not present var value: Any? var otherType = true // all other types of nargs produce a list if let nargs = action.nargs as? String { otherType = false if arg_strings.isEmpty && nargs == OPTIONAL { if action.option_strings.isEmpty { value = action.`const` } else { value = action.`default` } if let valueStr = value as? String { value = self._get_value(action, valueStr) self._check_value(action, value) } } // when nargs='*' on a positional, if there were no command-line // args, use the default if it is anything other than None else if arg_strings.isEmpty && nargs == ZERO_OR_MORE && action.option_strings.isEmpty { if (action.`default` != nil) { value = action.`default` } else { value = arg_strings } self._check_value(action, value) } // single argument or optional argument produces a single value else if arg_strings.count == 1 && nargs == OPTIONAL { let arg_string = arg_strings.first value = self._get_value(action, arg_string!) self._check_value(action, value) } // REMAINDER arguments convert all values, checking none else if nargs == REMAINDER { value = arg_strings.map {self._get_value(action, $0)} } // PARSER arguments convert all values, but check only the first else if nargs == PARSER { value = arg_strings.map {self._get_value(action, $0)} self._check_value(action, (value as! Array<Any>).first) } else { otherType = true } } // single argument or optional argument produces a single value if arg_strings.count == 1 && action.nargs == nil { let arg_string = arg_strings.first value = self._get_value(action, arg_string!) self._check_value(action, value) otherType = false } // all other types of nargs produce a list if otherType { value = arg_strings.map {self._get_value(action, $0)} for v in value as! Array<Any> { self._check_value(action, v) } } // return the converted value return value } func _get_value(_ action: Action, _ arg_string: String) -> Any { var type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))") // todo // check if type_func callable // convert the value to the appropriate type // todo // ArgumentTypeErrors indicate errors // TypeErrors or ValueErrors also indicate errors // return the converted value return arg_string } func _check_value(_ action: Action, _ value: Any) { // converted value must be one of the choices (if specified) // if !action.choices.isEmpty && !action.choices.contains(where: value as! (Any) throws -> Bool) { if false { fatalError("invalid choice: \(value) (choose from \(action.choices))") } } // MARK: Help-formatting methods func format_usage() -> String { return "" } func format_help() -> String { return "" } override func _get_formatter() -> HelpFormatter { return self.formatter_class.init(self.prog!, -1, -1, -1) } // MARK: Help-printing methods func print_usage() { } func print_help() { } func _print_message() { } // MARK: Exiting methods func exit(_ status: Int=0, _ message: String=String.None) { if !message.isEmpty { } } func error(_ message: String) { } }
49f63731d52c228a7980c092f749248d
31.542857
189
0.553468
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
refs/heads/master
精通Swift设计模式/Chapter 11/SportsStore/SportsStore/ViewController.swift
mit
1
import UIKit class ProductTableCell : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var stockStepper: UIStepper! @IBOutlet weak var stockField: UITextField! var product:Product?; } var handler = { (p:Product) in println("Change: \(p.name) \(p.stockLevel) items in stock"); }; class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var totalStockLabel: UILabel! @IBOutlet weak var tableView: UITableView! var productStore = ProductDataStore(); override func viewDidLoad() { super.viewDidLoad() displayStockTotal(); productStore.callback = {(p:Product) in for cell in self.tableView.visibleCells() { if let pcell = cell as? ProductTableCell { if pcell.product?.name == p.name { pcell.stockStepper.value = Double(p.stockLevel); pcell.stockField.text = String(p.stockLevel); } } } self.displayStockTotal(); } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return productStore.products.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let product = productStore.products[indexPath.row]; let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell") as ProductTableCell; cell.product = productStore.products[indexPath.row]; cell.nameLabel.text = product.name; cell.descriptionLabel.text = product.productDescription; cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); return cell; } @IBAction func stockLevelDidChange(sender: AnyObject) { if var currentCell = sender as? UIView { while (true) { currentCell = currentCell.superview!; if let cell = currentCell as? ProductTableCell { if let product = cell.product? { if let stepper = sender as? UIStepper { product.stockLevel = Int(stepper.value); } else if let textfield = sender as? UITextField { if let newValue = textfield.text.toInt()? { product.stockLevel = newValue; } } cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); productLogger.logItem(product); } break; } } displayStockTotal(); } } func displayStockTotal() { let finalTotals:(Int, Double) = productStore.products.reduce((0, 0.0), {(totals, product) -> (Int, Double) in return ( totals.0 + product.stockLevel, totals.1 + product.stockValue ); }); var factory = StockTotalFactory.getFactory(StockTotalFactory.Currency.GBP); var totalAmount = factory.converter?.convertTotal(finalTotals.1); var formatted = factory.formatter?.formatTotal(totalAmount!); totalStockLabel.text = "\(finalTotals.0) Products in Stock. " + "Total Value: \(formatted!)"; } }
4b63120dc149b163be066ac412d57665
36.343137
83
0.559464
false
false
false
false
qutheory/vapor
refs/heads/main
Sources/XCTVapor/XCTHTTPResponse.swift
mit
2
public struct XCTHTTPResponse { public var status: HTTPStatus public var headers: HTTPHeaders public var body: ByteBuffer } extension XCTHTTPResponse { private struct _ContentContainer: ContentContainer { var body: ByteBuffer var headers: HTTPHeaders var contentType: HTTPMediaType? { return self.headers.contentType } mutating func encode<E>(_ encodable: E, using encoder: ContentEncoder) throws where E : Encodable { fatalError("Encoding to test response is not supported") } func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable { try decoder.decode(D.self, from: self.body, headers: self.headers) } func decode<C>(_ content: C.Type, using decoder: ContentDecoder) throws -> C where C : Content { var decoded = try decoder.decode(C.self, from: self.body, headers: self.headers) try decoded.afterDecode() return decoded } } public var content: ContentContainer { _ContentContainer(body: self.body, headers: self.headers) } } extension Response.Body { var isEmpty: Bool { return self.count == 0 } } public func XCTAssertContent<D>( _ type: D.Type, _ res: XCTHTTPResponse, file: StaticString = #file, line: UInt = #line, _ closure: (D) throws -> () ) rethrows where D: Decodable { guard let contentType = res.headers.contentType else { XCTFail("response does not contain content type", file: (file), line: line) return } let content: D do { let decoder = try ContentConfiguration.global.requireDecoder(for: contentType) content = try decoder.decode(D.self, from: res.body, headers: res.headers) } catch { XCTFail("could not decode body: \(error)", file: (file), line: line) return } try closure(content) } public func XCTAssertContains(_ haystack: String?, _ needle: String?, file: StaticString = #file, line: UInt = #line) { let file = (file) switch (haystack, needle) { case (.some(let haystack), .some(let needle)): XCTAssert(haystack.contains(needle), "\(haystack) does not contain \(needle)", file: file, line: line) case (.some(let haystack), .none): XCTFail("\(haystack) does not contain nil", file: file, line: line) case (.none, .some(let needle)): XCTFail("nil does not contain \(needle)", file: file, line: line) case (.none, .none): XCTFail("nil does not contain nil", file: file, line: line) } } public func XCTAssertEqualJSON<T>(_ data: String?, _ test: T, file: StaticString = #file, line: UInt = #line) where T: Codable & Equatable { guard let data = data else { XCTFail("nil does not equal \(test)", file: (file), line: line) return } do { let decoded = try JSONDecoder().decode(T.self, from: Data(data.utf8)) XCTAssertEqual(decoded, test, file: (file), line: line) } catch { XCTFail("could not decode \(T.self): \(error)", file: (file), line: line) } }
ab199c01ef05e67c9d2942578ae81c36
31.265306
119
0.623023
false
false
false
false
wrengels/Amplify4
refs/heads/master
Amplify4/Amplify4/Amplify4/Document.swift
gpl-2.0
1
// // Document.swift // Amplify4 // // Created by Bill Engels on 1/15/15. // Copyright (c) 2015 Bill Engels. All rights reserved. // import Cocoa class Document: NSDocument { var text = "" override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) // Add any code here that needs to be executed once the windowController has loaded the document's window. } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String? { // Returns the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead. return "Document" } override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } }
d89533d14536cb3855b050efbefa53ea
40.277778
198
0.708389
false
false
false
false
ContinuousLearning/PokemonKit
refs/heads/master
Carthage/Checkouts/PromiseKit/Categories/UIKit/UIAlertView+Promise.swift
mit
1
import Foundation #if !COCOAPODS import PromiseKit #endif import UIKit.UIAlertView /** To import the `UIActionSheet` category: use_frameworks! pod "PromiseKit/UIKit" Or `UIKit` is one of the categories imported by the umbrella pod: use_frameworks! pod "PromiseKit" And then in your sources: #if !COCOAPODS import PromiseKit #endif */ extension UIAlertView { public func promise() -> Promise<Int> { let proxy = PMKAlertViewDelegate() delegate = proxy proxy.retainCycle = proxy show() if numberOfButtons == 1 && cancelButtonIndex == 0 { NSLog("PromiseKit: An alert view is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.") } return proxy.promise } } private class PMKAlertViewDelegate: NSObject, UIAlertViewDelegate { let (promise, fulfill, reject) = Promise<Int>.defer_() var retainCycle: NSObject? @objc func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex != alertView.cancelButtonIndex { fulfill(buttonIndex) } else { reject(NSError.cancelledError()) } } }
c6c69ddaaaf462ae5eddc434c307f6f9
26.54
279
0.673929
false
false
false
false
DannyvanSwieten/SwiftSignals
refs/heads/master
GameEngine/Grid.swift
gpl-3.0
1
// // Grid.swift // SwiftEngine // // Created by Danny van Swieten on 2/15/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import Foundation class Grid<T: Arithmetic> { var data: UnsafeMutablePointer<T>? var size = 0 init(aSize: Int) { size = aSize data = UnsafeMutablePointer<T>.alloc(size * size) } deinit { data?.destroy() } subscript(row: Int) -> UnsafeMutablePointer<T> { return data!.advancedBy(row * size) } } func heightMap(size: Int, initialValue: Float) -> Grid<Float>{ let grid = Grid<Float>(aSize: size) grid[0][0] = fmodf(Float(rand()), 1.0) grid[0][size] = fmodf(Float(rand()), 1.0) grid[size][size] = fmodf(Float(rand()), 1.0) grid[size][0] = fmodf(Float(rand()), 1.0) return grid }
67802e357dcad7089782f41f876933d1
20.692308
62
0.577515
false
false
false
false
daniel-barros/Comedores-UGR
refs/heads/master
Comedores UGR/MenuTableViewController.swift
mit
1
// // MenuTableViewController.swift // Comedores UGR // // Created by Daniel Barros López on 3/9/16. /* MIT License Copyright (c) 2016 Daniel Barros 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 EventKitUI import SafariServices class MenuTableViewController: UITableViewController { let fetcher = WeekMenuFetcher() var weekMenu = [DayMenu]() var error: FetcherError? var lastTimeTableViewReloaded: Date? /// `false` when there's a saved menu or the vc has already fetched since viewDidLoad(). var isFetchingForFirstTime = true fileprivate let lastUpdateRowHeight: CGFloat = 46.45 // MARK: - override func viewDidLoad() { super.viewDidLoad() weekMenu = fetcher.savedMenu ?? [] NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 150 if weekMenu.isEmpty == false { tableView.contentOffset.y = lastUpdateRowHeight // Hides "last update" row isFetchingForFirstTime = false } refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: #selector(fetchData), for: .valueChanged) updateSeparatorsInset(for: tableView.frame.size) if fetcher.needsToUpdateMenu { if isFetchingForFirstTime { refreshControl!.layoutIfNeeded() refreshControl!.beginRefreshing() tableView.contentOffset.y = -tableView.contentInset.top } fetchData() } } deinit { NotificationCenter.default.removeObserver(self) } func appDidBecomeActive(_ notification: Notification) { // Menu was updated externally and changes need to be reflected in UI if let savedMenu = fetcher.savedMenu, savedMenu != weekMenu { self.error = nil weekMenu = savedMenu tableView.reloadData() } else { // This makes sure that only the date for today's menu is highlighted if let lastReload = lastTimeTableViewReloaded, Calendar.current.isDateInToday(lastReload) == false { tableView.reloadData() } // Menu needs to be updated if fetcher.needsToUpdateMenu { fetchData() } } } func fetchData() { if fetcher.isFetching == false { fetcher.fetchMenu(completionHandler: { menu in self.error = nil let menuChanged = self.weekMenu != menu self.weekMenu = menu self.lastTimeTableViewReloaded = Date() self.isFetchingForFirstTime = false mainQueue { if menuChanged { self.tableView.reloadData() } else { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row } UIView.animate(withDuration: 0.5) { if self.refreshControl!.isRefreshing { self.refreshControl!.endRefreshing() } } } }, errorHandler: { error in self.error = error self.lastTimeTableViewReloaded = Date() self.isFetchingForFirstTime = false mainQueue { if self.weekMenu.isEmpty { self.tableView.reloadData() } else { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row showing error message temporarily delay(1) { self.error = nil // Next time first cell is loaded it will show last update date instead of error message } } UIView.animate(withDuration: 0.5) { if self.refreshControl!.isRefreshing { self.refreshControl!.endRefreshing() } } } }) } } @IBAction func prepareForUnwind(_ segue: UIStoryboardSegue) { } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) updateSeparatorsInset(for: size) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if weekMenu.isEmpty { return isFetchingForFirstTime ? 0 : 1 } return weekMenu.count + 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if weekMenu.isEmpty == false { // First row shows error message if any (eventually dismissed, see fetchData()), or last update date if indexPath.row == 0 { if let error = error { let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell cell.configure(with: error) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LastUpdateCell", for: indexPath) as! LastUpdateTableViewCell cell.configure(with: fetcher.lastUpdate) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuTableViewCell cell.configure(with: weekMenu[indexPath.row - 1]) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell cell.configure(with: error) return cell } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row == 0 { return false } if self.weekMenu[indexPath.row - 1].isClosedMenu { return false } return true } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if weekMenu.isEmpty || indexPath.row == 0 { return nil } let menu = self.weekMenu[indexPath.row - 1] let calendarAction = addToCalendarRowAction(for: menu) if let allergensRowAction = allergensInfoRowAction(for: menu) { return [calendarAction, allergensRowAction] } else { return [calendarAction] } } // MARK: - UIScrollViewDelegate // Avoids "last update" row scrolling down to first dish row override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if lastUpdateRowIsVisible { self.tableView.scrollToRow(at: IndexPath(row: 1, section: 0), at: .top, animated: true) } } } // MARK: Helpers private extension MenuTableViewController { func addToCalendarRowAction(for menu: DayMenu) -> UITableViewRowAction { let rowAction = UITableViewRowAction(style: .normal, title: NSLocalizedString("Add to\nCalendar"), handler: { action, indexPath in switch EventManager.authorizationStatus { case .authorized: self.presentEventEditViewController(for: menu) case .denied: self.presentAlertController(title: NSLocalizedString("Access Denied"), message: NSLocalizedString("Please go to the app's settings and allow us to access your calendars."), showsGoToSettings: true) case .notDetermined: self.requestEventAccessPermission(for: menu) case .restricted: self.presentAlertController(title: NSLocalizedString("Access Restricted"), message: NSLocalizedString("Access to calendars is restricted, possibly due to parental controls being in place."), showsGoToSettings: false) } }) rowAction.backgroundColor = .customAlternateRedColor return rowAction } func allergensInfoRowAction(for menu: DayMenu) -> UITableViewRowAction? { if let _ = menu.allergens { // TODO: Implement return nil } else { return nil } } func presentEventEditViewController(for menu: DayMenu) { let eventVC = EKEventEditViewController() let eventStore = EKEventStore() eventVC.eventStore = eventStore eventVC.editViewDelegate = self eventVC.event = EventManager.createEvent(in: eventStore, for: menu) self.present(eventVC, animated: true, completion: nil) } func presentAlertController(title: String, message: String, showsGoToSettings: Bool) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel"), style: .cancel, handler: { action in self.dismiss(animated: true, completion: nil) self.tableView.isEditing = false }) alertController.addAction(cancelAction) if showsGoToSettings { let settingsAction = UIAlertAction(title: NSLocalizedString("Go to Settings"), style: .default, handler: { action in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) }) alertController.addAction(settingsAction) alertController.preferredAction = settingsAction } self.present(alertController, animated: true, completion: nil) } func requestEventAccessPermission(for menu: DayMenu) { EventManager.requestAccessPermission { granted in mainQueue { if granted { self.presentEventEditViewController(for: menu) } else { self.tableView.isEditing = false } } } } var lastUpdateRowIsVisible: Bool { let offset = navigationController!.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height return weekMenu.isEmpty == false && tableView.contentOffset.y < lastUpdateRowHeight - offset } /// Updates the table view's separators left inset according to the given size. func updateSeparatorsInset(for size: CGSize) { tableView.separatorInset.left = size.width * 0.2 - 60 } } // MARK: - EKEventEditViewDelegate extension MenuTableViewController: EKEventEditViewDelegate { func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { if let event = controller.event, action == .saved { EventManager.saveDefaultInfo(from: event) } dismiss(animated: true, completion: nil) self.tableView.isEditing = false } }
e7b8758d1c0579d55b4dc3602093f06e
37.289552
246
0.613783
false
false
false
false
shnhrrsn/SHNUrlRouter
refs/heads/master
Tests/UrlRouterTests.swift
mit
2
// // UrlRouterTests.swift // SHNUrlRouter // // Copyright (c) 2015-2018 Shaun Harrison // // 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 XCTest @testable import SHNUrlRouter class UrlRouterTests: XCTestCase { func testReadMeExample() { var router = UrlRouter() var selectedIndex = -1 var id = -1 var section: String? router.add("id", pattern: "[0-9]+") router.add("section", pattern: "profile|activity") router.register("feed") { (parameters) in selectedIndex = 0 } router.register("user/{id}/{section?}") { (parameters) in guard let stringId = parameters["id"], let intId = Int(stringId) else { return } selectedIndex = 1 id = intId section = parameters["section"] ?? "default" } XCTAssertTrue(router.dispatch(for: "http://example.com/feed")) XCTAssertEqual(selectedIndex, 0) XCTAssertFalse(router.dispatch(for: "http://example.com/user")) XCTAssertTrue(router.dispatch(for: "http://example.com/user/5")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "default") XCTAssertTrue(router.dispatch(for: "http://example.com/user/5/profile")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "profile") } func testBasicDispatchingOfRoutes() { var router = UrlRouter() var dispatched = false router.register("foo/bar") { _ in dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/bar")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithParameter() { var router = UrlRouter() var dispatched = false router.register("foo/{bar}") { parameters in XCTAssertEqual(parameters["bar"], "swift") dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithOptionalParameter() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{bar}/{baz?}") { parameters in dispatched = "\(parameters["bar"] ?? "").\(parameters["baz"] ?? "1")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/4")) XCTAssertEqual(dispatched, "swift.4") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertEqual(dispatched, "swift.1") } func testBasicDispatchingOfRoutesWithOptionalParameters() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{name}/boom/{age?}/{location?}") { parameters in dispatched = "\(parameters["name"] ?? "").\(parameters["age"] ?? "56").\(parameters["location"] ?? "ca")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/steve/boom")) XCTAssertEqual(dispatched, "steve.56.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4")) XCTAssertEqual(dispatched, "swift.4.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4/org")) XCTAssertEqual(dispatched, "swift.4.org") } }
10485942348e81ce7093c2bd9f68f924
30.309524
108
0.713815
false
true
false
false
justaninja/clients_list
refs/heads/master
ClientsList/ClientsList/Location.swift
mit
1
// // Location.swift // ClientsList // // Created by Konstantin Khokhlov on 29.06.17. // Copyright © 2017 Konstantin Khokhlov. All rights reserved. // import Foundation import CoreLocation /// A location model struct. struct Location: Equatable { // MARK: - Keys private let nameKey = "name" private let latitudeKey = "latitudeKey" private let longitudeKey = "longitudeKey" // MARK: - Properties let name: String let coordinate: CLLocationCoordinate2D? var plistDictionary: [String: Any] { var dict = [String: Any]() dict[nameKey] = name if let coordinate = coordinate { dict[latitudeKey] = coordinate.latitude dict[longitudeKey] = coordinate.longitude } return dict } // MARK: - Inits init(name: String, coordinate: CLLocationCoordinate2D? = nil) { self.name = name self.coordinate = coordinate } init?(dictionary: [String: Any]) { guard let name = dictionary[nameKey] as? String else { return nil } let coordinate: CLLocationCoordinate2D? if let latitude = dictionary[latitudeKey] as? Double, let longitude = dictionary[longitudeKey] as? Double { coordinate = CLLocationCoordinate2DMake(latitude, longitude) } else { coordinate = nil } self.name = name self.coordinate = coordinate } } func == (lhs: Location, rhs: Location) -> Bool { if lhs.coordinate?.latitude != rhs.coordinate?.latitude { return false } if lhs.coordinate?.longitude != rhs.coordinate?.longitude { return false } if lhs.name != rhs.name { return false } return true }
39b0e18245a5565f884cd237c49bc3a1
23.671429
115
0.621309
false
false
false
false
skyline75489/Honeymoon
refs/heads/master
Honeymoon/Server.swift
mit
1
// // Server.swift // Honeymoon // // Created by skyline on 15/9/29. // Copyright © 2015年 skyline. All rights reserved. // import Foundation import GCDWebServer public class Server { let webServer = GCDWebServer() var handlerMap = [Rule:Handler]() var url:String { get { return self.webServer.serverURL.absoluteString } } init() { webServer.addDefaultHandlerForMethod("GET", requestClass: GCDWebServerRequest.self, processBlock: {request in let errorResp = GCDWebServerDataResponse(HTML: "<html><body><h3>Not Found</h3></body></html>") errorResp.statusCode = 404 return errorResp }) webServer.addDefaultHandlerForMethod("POST", requestClass: GCDWebServerRequest.self, processBlock: {request in let errorResp = GCDWebServerDataResponse(HTML: "<html><body><h3>Not Found</h3></body></html>") errorResp.statusCode = 404 return errorResp }) } public func addRoute(route:String, method: String, requestClass: AnyClass=GCDWebServerRequest.self, handlerClosure: HandlerClosure) { let r = Rule(rule: route, method: method) if r.variables.count > 0 { let h = Handler(path: route, method: method, handlerClosure: handlerClosure, pathRegex: r._regex?.pattern, parameters: r.variables) self.addHandlerWithParameter(h, requestClass: requestClass) } else { let h = Handler(path: route, method: method, handlerClosure: handlerClosure) self.addHandler(h, requestClass: requestClass) } } public func addStaticHandler(basePath:String, dir:String) { self.webServer.addGETHandlerForBasePath(basePath, directoryPath: dir, indexFilename: nil, cacheAge: 3600, allowRangeRequests: false) } private func addHandler(handler:Handler, requestClass:AnyClass=GCDWebServerRequest.self) { webServer.addHandlerForMethod(handler.method, path: handler.path, requestClass: requestClass, processBlock: { request in let req = self.prepareRequest(request) let resp = handler.handlerClosure!(req) var returnResp = Response(body: "") if let resp = resp as? Response { returnResp = resp } if let resp = resp as? String { returnResp = Response(body: resp) } return self.prepareResponse(returnResp) }) } private func addHandlerWithParameter(handler: Handler, requestClass:AnyClass=GCDWebServerRequest.self) { webServer.addHandlerForMethod(handler.method, pathRegex: handler.pathRegex, requestClass: requestClass, processBlock: { request in let r = Regex(pattern: handler.pathRegex!) var params = [String:String]() if let m = r.match(request.path) { for var i = 0 ; i < handler.routeParameters?.count; i++ { let key = handler.routeParameters?[i] params[key!] = m.group(i+1) } } let req = self.prepareRequest(request, routeParams:params) let resp = handler.handlerClosure!(req) var returnResp = Response(body: "") if let resp = resp as? Response { returnResp = resp } if let resp = resp as? String { returnResp = Response(body: resp) } return self.prepareResponse(returnResp) }) } private func prepareRequest(request:GCDWebServerRequest, routeParams:[String:String]?=nil) -> Request { let req = Request() req.method = request.method req.path = request.path req.params = routeParams if let r = request as? GCDWebServerURLEncodedFormRequest { req.form = [String:String]() for (k, v) in r.arguments { let newKey = String(k) let newValue = v as! String req.form?[newKey] = newValue } } return req } private func prepareResponse(response: Response) -> GCDWebServerResponse { if let redirect = response.redirect { return GCDWebServerResponse(redirect: NSURL(string: redirect), permanent: false) } let resp = GCDWebServerDataResponse.init(HTML: response.body) resp.statusCode = response.statusCode! resp.contentType = response.contentType resp.contentLength = response.contentLength! return resp } public func start(port:UInt?=nil) { if let port = port { webServer.runWithPort(port, bonjourName: "GCD Web Server") } else { webServer.runWithPort(8000, bonjourName: "GCD Web Server") } } }
d08a2905cb9715de9c568c45f2900e8a
37.186047
143
0.599594
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/CountryOrText.swift
mit
1
import Foundation import CodablePlus public enum CountryOrText: Codable { case country(value: Country) case text(value: String) public init(from decoder: Decoder) throws { var dictionary: [String : Any]? do { let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self) dictionary = try jsonContainer.decode(Dictionary<String, Any>.self) } catch { } guard let jsonDictionary = dictionary else { let container = try decoder.singleValueContainer() let value = try container.decode(String.self) self = .text(value: value) return } guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else { throw SchemaError.typeDecodingError } let container = try decoder.singleValueContainer() switch type { case Country.schemaName: let value = try container.decode(Country.self) self = .country(value: value) default: throw SchemaError.typeDecodingError } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .country(let value): try container.encode(value) case .text(let value): try container.encode(value) } } public var country: Country? { switch self { case .country(let value): return value default: return nil } } public var text: String? { switch self { case .text(let value): return value default: return nil } } }
2c919a048306b94eddbcb27d8efeb2dc
26.134328
83
0.552255
false
false
false
false
tiehuaz/iOS-Application-for-AURIN
refs/heads/master
AurinProject/SidebarMenu/MapViewController.swift
apache-2.0
1
// // MapViewController.swift // AurinProject // // Created by tiehuaz on 8/29/15. // Copyright (c) 2015 AppCoda. All rights reserved. // import UIKit import MapKit /* Second Visualizaiton interface based on retured data, drawing polygon for each data based on geospatial information * also put red pin in each polygon to show details for this polygon. */ class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var menuButton:UIBarButtonItem! @IBOutlet weak var mapView: MKMapView! let user = Singleton.sharedInstance var measureNum :CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } print(user.mapData.count) } override func viewWillAppear(animated: Bool) { addPolygonToMap() openMapForPlace() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if (overlay is MKPolygon) { var overlayPathView = MKPolygonRenderer(overlay: overlay) overlayPathView.fillColor = UIColor.redColor().colorWithAlphaComponent(measureNum) overlayPathView.strokeColor = UIColor.blackColor().colorWithAlphaComponent(0.7) overlayPathView.lineWidth = 5 return overlayPathView } else if (overlay is MKPolyline) { var overlayPathView = MKPolylineRenderer(overlay: overlay) overlayPathView.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) overlayPathView.lineWidth = 1 return overlayPathView } return nil } func addPolygonToMap() { for (suburbName,polygon) in user.mapData{ var stringArr = suburbName.componentsSeparatedByString(":") var points = polygon var range = Double(stringArr[3])! if user.flag == 0{ if range<10{ measureNum = 0.2 }else if(range>=10&&range<15){ measureNum = 0.4 }else if(range>=15&&range<20){ measureNum = 0.6 }else{ measureNum = 0.8 } }else if user.flag == 1{ if range<80000{ measureNum = 0.2 }else if(range>=80000&&range<120000){ measureNum = 0.4 }else if(range>=120000&&range<160000){ measureNum = 0.6 }else{ measureNum = 0.8 } }else if user.flag == 2{ if range<30{ measureNum = 0.2 }else if(range>=30&&range<35){ measureNum = 0.4 }else if(range>=35&&range<40){ measureNum = 0.6 }else{ measureNum = 0.8 } } var polygon = MKPolygon(coordinates: &points, count: points.count) self.mapView.addOverlay(polygon) var lati : Double = Double(stringArr[1])! var lonti : Double = Double(stringArr[2])! var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(lati,lonti) var objectAnnotation = MKPointAnnotation() objectAnnotation.coordinate = pinLocation objectAnnotation.title = stringArr[0] as! String if user.flag == 0{ objectAnnotation.subtitle = "housing stress: \(range)" }else if user.flag == 1{ objectAnnotation.subtitle = "population: \(range)" }else if user.flag == 2{ objectAnnotation.subtitle = "numeric: \(range), Severity: \(stringArr[4])" } self.mapView.addAnnotation(objectAnnotation) } } func openMapForPlace() { let span = MKCoordinateSpanMake(1, 1) let location = CLLocationCoordinate2D( latitude: (-37.796286-37.804424-37.852993)/3, longitude: (144.927181+145.027181+144.927181)/3 ) let region = MKCoordinateRegion(center: location, span: span) // let regionDistance: CLLocationDistance = 1000000 mapView.setRegion(region, animated: true) } @IBAction func returnButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
538032ef2716cd10ff420d0d61bb9a03
33.123288
118
0.557607
false
false
false
false
CodePath2017Group4/travel-app
refs/heads/master
BeeFun/Pods/SwiftyBeaver/Sources/ConsoleDestination.swift
apache-2.0
11
// // ConsoleDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation public class ConsoleDestination: BaseDestination { /// use NSLog instead of print, default is false public var useNSLog = false /// uses colors compatible to Terminal instead of Xcode, default is false public var useTerminalColors: Bool = false { didSet { if useTerminalColors { // use Terminal colors reset = "\u{001b}[0m" escape = "\u{001b}[38;5;" levelColor.verbose = "251m" // silver levelColor.debug = "35m" // green levelColor.info = "38m" // blue levelColor.warning = "178m" // yellow levelColor.error = "197m" // red } else { // use colored Emojis for better visual distinction // of log level for Xcode 8 levelColor.verbose = "💜 " // silver levelColor.debug = "💚 " // green levelColor.info = "💙 " // blue levelColor.warning = "💛 " // yellow levelColor.error = "❤️ " // red } } } override public var defaultHashValue: Int { return 1 } public override init() { super.init() levelColor.verbose = "💜 " // silver levelColor.debug = "💚 " // green levelColor.info = "💙 " // blue levelColor.warning = "💛 " // yellow levelColor.error = "❤️ " // red } // print to Xcode Console. uses full base class functionality override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { let formattedString = super.send(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) if let str = formattedString { if useNSLog { #if os(Linux) print(str) #else NSLog("%@", str) #endif } else { print(str) } } return formattedString } }
f12e3d65dd7e04098f583d8c4fe23f27
33.263889
135
0.507094
false
false
false
false
iOSDevLog/ijkplayer
refs/heads/master
ijkplayer-Swift/ijkplayer-Swift/Demo/IJKDemoInputURLViewController.swift
lgpl-2.1
1
// // IJKDemoInputURLViewController.swift // ijkplayer-Swift // // Created by iOS Dev Log on 2017/8/24. // Copyright © 2017年 iOSDevLog. All rights reserved. // import UIKit class IJKDemoInputURLViewController: UIViewController, UITextViewDelegate { let rtmp = "rtmp://live.hkstv.hk.lxdns.com/live/hks" let m3u8 = "https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8" let rtsp = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov" @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() title = "Input URL" textView.delegate = self navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Play", style: .done, target: self, action: #selector(self.onClickPlayButton)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textView.text = rtsp } @objc func onClickPlayButton() { let url = URL(string: textView.text) let scheme: String? = url?.scheme?.lowercased() if (scheme == "http") || (scheme == "https") || (scheme == "rtmp") || (scheme == "rtsp") { IJKPlayerViewController.present(from: self, withTitle: "URL: \(String(describing: url))", url: url!, completion: {() -> Void in self.navigationController?.popViewController(animated: false) }) } } func textViewDidEndEditing(_ textView: UITextView) { onClickPlayButton() } }
40a15dd7048e25a1731c839c4eb4459a
33.477273
145
0.632169
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSPopUpButtonSpec.swift
gpl-3.0
5
import Quick import Nimble import ReactiveCocoa import ReactiveSwift import Result import AppKit final class NSPopUpButtonSpec: QuickSpec { override func spec() { describe("NSPopUpButton") { var button: NSPopUpButton! var window: NSWindow! weak var _button: NSButton? let testTitles = (0..<100).map { $0.description } beforeEach { window = NSWindow() button = NSPopUpButton(frame: .zero) _button = button for (i, title) in testTitles.enumerated() { let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") item.tag = 1000 + i button.menu?.addItem(item) } window.contentView?.addSubview(button) } afterEach { autoreleasepool { button.removeFromSuperview() button = nil } expect(_button).to(beNil()) } it("should emit selected index changes") { var values = [Int]() button.reactive.selectedIndexes.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1, 99] } it("should emit selected title changes") { var values = [String]() button.reactive.selectedTitles.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == ["1", "99"] } it("should accept changes from its bindings to its index values") { let (signal, observer) = Signal<Int?, NoError>.pipe() button.reactive.selectedIndex <~ SignalProducer(signal) observer.send(value: 1) expect(button.indexOfSelectedItem) == 1 observer.send(value: 99) expect(button.indexOfSelectedItem) == 99 observer.send(value: nil) expect(button.indexOfSelectedItem) == -1 expect(button.selectedItem?.title).to(beNil()) } it("should accept changes from its bindings to its title values") { let (signal, observer) = Signal<String?, NoError>.pipe() button.reactive.selectedTitle <~ SignalProducer(signal) observer.send(value: "1") expect(button.selectedItem?.title) == "1" observer.send(value: "99") expect(button.selectedItem?.title) == "99" observer.send(value: nil) expect(button.selectedItem?.title).to(beNil()) expect(button.indexOfSelectedItem) == -1 } it("should emit selected item changes") { var values = [NSMenuItem]() button.reactive.selectedItems.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) let titles = values.map { $0.title } expect(titles) == ["1", "99"] } it("should emit selected tag changes") { var values = [Int]() button.reactive.selectedTags.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1001, 1099] } it("should accept changes from its bindings to its tag values") { let (signal, observer) = Signal<Int, NoError>.pipe() button.reactive.selectedTag <~ SignalProducer(signal) observer.send(value: 1001) expect(button.selectedItem?.tag) == 1001 expect(button.indexOfSelectedItem) == 1 observer.send(value: 1099) expect(button.selectedItem?.tag) == 1099 expect(button.indexOfSelectedItem) == 99 observer.send(value: 1042) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 // Sending an invalid tag number doesn't change the selection observer.send(value: testTitles.count + 1) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 } } } }
e752d1ea6631925664228c4b309cb112
27.181818
72
0.665054
false
false
false
false
ColinEberhardt/ReactiveTwitterSearch
refs/heads/master
ReactiveTwitterSearch/TweetCellView.swift
mit
1
// // TweetCell.swift // ReactiveTwitterSearch // // Created by Colin Eberhardt on 11/05/2015. // Copyright (c) 2015 Colin Eberhardt. All rights reserved. // import UIKit import ReactiveCocoa import Result class TweetCellView: UITableViewCell, ReactiveView { @IBOutlet weak var usernameText: UILabel! @IBOutlet weak var statusText: UILabel! @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var ageText: UILabel! lazy var scheduler: QueueScheduler = { let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) return QueueScheduler(queue: queue) }() func bindViewModel(viewModel: AnyObject) { if let tweetViewModel = viewModel as? TweetViewModel { //FIXME: how to lift this to signal producer for takeUntil? // _ = toVoidSignal(self.rac_prepareForReuseSignal.asSignal()) statusText.rac_text <~ tweetViewModel.status usernameText.rac_text <~ tweetViewModel.username.producer.map { "@\($0)" } // because the ageInSeconds property is mutable, we need to ensure that we 'complete' // the signal that the rac_text property is bound to. Hence the use of takeUntil. ageText.rac_text <~ tweetViewModel.ageInSeconds.producer .map { "\($0) secs" } // .takeUntil(triggerSignal) avatarImageView.image = nil avatarImageSignalProducer(tweetViewModel.profileImageUrl.value) .startOn(scheduler) // .takeUntil(triggerSignal) .observeOn(QueueScheduler.mainQueueScheduler) .startWithNext { self.avatarImageView.image = $0 } } } private func avatarImageSignalProducer(imageUrl: String) -> SignalProducer<UIImage?, NoError> { guard let url = NSURL(string: imageUrl), data = NSData(contentsOfURL: url) else { print("App Transport Security rejected URL: \(imageUrl)") return SignalProducer(value: nil) } return SignalProducer(value: UIImage(data: data)) } }
f180d3c7b0d9cbc1478f3c66bf17899a
31.95082
97
0.681592
false
false
false
false
migchaves/EGTracker
refs/heads/master
Pod/Classes/TrackerDataBase/EGTrackerDBManager.swift
mit
1
// // EGTrackerDBManager.swift // TinyGoi // // Created by Miguel Chaves on 26/02/16. // Copyright © 2016 E-Goi. All rights reserved. // import UIKit import CoreData class EGTrackerDBManager: NSObject { // MARK: - Class Properties var managedObjectContext: NSManagedObjectContext var managedObjectModel: NSManagedObjectModel var persistentStoreCoordinator: NSPersistentStoreCoordinator // MARK: - Init class override init() { self.managedObjectModel = NSManagedObjectModel.init(contentsOfURL: EGTrackerDBManager.getModelUrl())! self.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: self.managedObjectModel) do { try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: EGTrackerDBManager.storeURL(), options: nil) } catch let error as NSError { print(error) abort() } self.managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType) self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator self.managedObjectContext.mergePolicy = NSOverwriteMergePolicy } // MARK: - Shared Instance class var sharedInstance: EGTrackerDBManager { struct Singleton { static let instance = EGTrackerDBManager() } return Singleton.instance } // MARK: - Create and Save objects func managedObjectOfType(objectType: String) -> NSManagedObject { let newObject = NSEntityDescription.insertNewObjectForEntityForName(objectType, inManagedObjectContext: self.managedObjectContext) return newObject } func saveContext() { if (!self.managedObjectContext.hasChanges) { return } else { do { try self.managedObjectContext.save() } catch let exception as NSException { print("Error while saving \(exception.userInfo) : \(exception.reason)") } catch { print("Error while saving data!") } } } // MARK: - Retrieve data func allEntriesOfType(objectType: String) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true do { let result = try self.managedObjectContext.executeFetchRequest(request) return result } catch { print("Error executing request in the Data Base") } return [] } func getEntryOfType(objectType: String, propertyName: String, propertyValue: AnyObject) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true let predicate = NSPredicate(format: "\(propertyName) == \(propertyValue)") request.predicate = predicate do { let result = try self.managedObjectContext.executeFetchRequest(request) var returnArray: [AnyObject] = [AnyObject]() for element in result { returnArray.append(element) } return returnArray } catch { print("Error executing request in the Data Base") } return [] } func deleteAllEntriesOfType(objectType: String) { let elements = allEntriesOfType(objectType) if (elements.count > 0) { for element in elements { self.managedObjectContext.deleteObject(element as! NSManagedObject) } saveContext() } } func deleteObject(object: NSManagedObject) { self.managedObjectContext.deleteObject(object) saveContext() } // MARK: - Private functions static private func getModelUrl() -> NSURL { return NSBundle.mainBundle().URLForResource("TrackerDataBase", withExtension: "momd")! } static private func storeURL () -> NSURL? { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last let storeUrl = applicationDocumentsDirectory?.URLByAppendingPathComponent("TrackerDataBase.sqlite") return storeUrl } }
a7cd776a51c14bbf1bfb5f7b6fe107e0
31.433333
144
0.622738
false
false
false
false
daher-alfawares/iBeacon
refs/heads/master
Beacon/Beacon/ViewController.swift
apache-2.0
1
// // ViewController.swift // Beacon // // Created by Daher Alfawares on 1/19/15. // Copyright (c) 2015 Daher Alfawares. All rights reserved. // import UIKit class ViewController: UITableViewController { let beacons = BeaconDataSource() override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self; self.tableView.dataSource = self; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.beacons.count() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // View let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell // Model let beaconInfo = self.beacons.beaconInfoAtIndex(indexPath.row) // Control cell.textLabel?.text = beaconInfo.name cell.detailTextLabel?.text = beaconInfo.uuid return cell; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // View let beaconViewController = segue.destinationViewController as BeaconViewController // Model let tableView = self.tableView; let index = tableView.indexPathForCell(sender as UITableViewCell) let row = index?.row let beacon = self.beacons.beaconInfoAtIndex (row!) as BeaconInfo beaconViewController.beaconName = beacon.name beaconViewController.beaconUUID = beacon.uuid beaconViewController.beaconImageName = beacon.image beaconViewController.beaconMajor = beacon.major beaconViewController.beaconMinor = beacon.minor } }
faadb1b1d0cb47914902c7e294e5729d
29.783333
118
0.64104
false
false
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/TableOfContentsAboutThisArticleItem.swift
mit
1
import Foundation open class TableOfContentsAboutThisArticleItem : NSObject, TableOfContentsFooterItem { let url:URL init(url: URL) { self.url = url super.init() } open var titleText:String { return WMFLocalizedString("article-about-title", language: self.url.wmf_language, value: "About this article", comment: "The text that is displayed before the 'about' section at the bottom of an article") } open let itemType: TableOfContentsItemType = TableOfContentsItemType.primary open let footerViewIndex: WMFArticleFooterViewIndex = WMFArticleFooterViewIndex.aboutThisArticle open override func isEqual(_ object: Any?) -> Bool { if let item = object as? TableOfContentsAboutThisArticleItem { return self === item || (titleText == item.titleText && itemType == item.itemType && indentationLevel == item.indentationLevel) } else { return false } } }
4c5f9619e8eaffc5a2f646e55a4f04c6
35.5
212
0.649706
false
false
false
false
Binglin/MappingAce
refs/heads/master
Mapping/ViewController.swift
mit
2
// // ViewController.swift // Mapping // // Created by 郑林琴 on 16/10/10. // Copyright © 2016年 Ice Butterfly. All rights reserved. // import UIKit import MappingAce class ViewController: UIViewController { struct PhoneNumber: Mapping { var tel: String var type: String } override func viewDidLoad() { super.viewDidLoad() self.testStructMapping() self.testStructMappingWithDefaultValue() } func testStructMapping(){ struct UserArrayPhoneEntity: Mapping{ var age: Int? var name: String? var phone: PhoneNumber var phones: [PhoneNumber] } let phone: [String : Any] = [ "tel": "186xxxxxxxx", "type": "work" ] let phones = Array(repeating: phone, count: 10) let dic: [String : Any] = [ "age" : 14.0, "name": "Binglin", "phone": phone, "phones": phones ] let user = UserArrayPhoneEntity(fromDic: dic) let serialized = user.toDictionary() print(serialized) } func testStructMappingWithDefaultValue(){ struct UserArrayPhoneEntity: InitMapping{ var age: Int? var name: String = "default" var phone: PhoneNumber? var phones: [PhoneNumber] = [] } struct PhoneNumber: Mapping { var tel: String var type: String } let phone: [String : Any] = [ "tel": "186xxxxxxxx", "type": "work" ] let phones = Array(repeating: phone, count: 10) let dic: [String : Any] = [ "age" : 14.0, "phone": phone, "phones": phones ] let user = UserArrayPhoneEntity(fromDic: dic) let serialized = user.toDictionary() print(serialized) } }
ac420361c3f254786e07bc8f036a99af
20.572917
57
0.487687
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Processor/HTMLProcessor.swift
gpl-2.0
2
import Foundation /// Struct to represent a HTML element /// public struct HTMLElement { public enum TagType { case selfClosing case closed case single } public let tag: String public let attributes: [ShortcodeAttribute] public let type: TagType public let content: String? } /// A class that processes a string and replace the designated shortcode for the replacement provided strings /// open class HTMLProcessor: Processor { /// Whenever an HTML is found by the processor, this closure will be executed so that elements can be customized. /// public typealias Replacer = (HTMLElement) -> String? // MARK: - Basic Info let element: String // MARK: - Regex private enum CaptureGroups: Int { case all = 0 case name case arguments case selfClosingElement case content case closingTag static let allValues: [CaptureGroups] = [.all, .name, .arguments, .selfClosingElement, .content, .closingTag] } /// Regular expression to detect attributes /// Capture groups: /// /// 1. The element name /// 2. The element argument list /// 3. The self closing `/` /// 4. The content of a element when it wraps some content. /// 5. The closing tag. /// private lazy var htmlRegexProcessor: RegexProcessor = { [unowned self] in let pattern = "\\<(\(element))(?![\\w-])([^\\>\\/]*(?:\\/(?!\\>)[^\\>\\/]*)*?)(?:(\\/)\\>|\\>(?:([^\\<]*(?:\\<(?!\\/\\1\\>)[^\\<]*)*)(\\<\\/\\1\\>))?)" let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) return RegexProcessor(regex: regex) { (match: NSTextCheckingResult, text: String) -> String? in return self.process(match: match, text: text) } }() // MARK: - Parsing & processing properties private let attributesParser = ShortcodeAttributeParser() private let replacer: Replacer // MARK: - Initializers public init(for element: String, replacer: @escaping Replacer) { self.element = element self.replacer = replacer } // MARK: - Processing public func process(_ text: String) -> String { return htmlRegexProcessor.process(text) } } // MARK: - Regex Match Processing Logic private extension HTMLProcessor { /// Processes an HTML Element regex match. /// func process(match: NSTextCheckingResult, text: String) -> String? { guard match.numberOfRanges == CaptureGroups.allValues.count else { return nil } let attributes = self.attributes(from: match, in: text) let elementType = self.elementType(from: match, in: text) let content: String? = match.captureGroup(in: CaptureGroups.content.rawValue, text: text) let htmlElement = HTMLElement(tag: element, attributes: attributes, type: elementType, content: content) return replacer(htmlElement) } // MARK: - Regex Match Processing Logic /// Obtains the attributes from an HTML element match. /// private func attributes(from match: NSTextCheckingResult, in text: String) -> [ShortcodeAttribute] { guard let attributesText = match.captureGroup(in: CaptureGroups.arguments.rawValue, text: text) else { return [] } return attributesParser.parse(attributesText) } /// Obtains the element type for an HTML element match. /// private func elementType(from match: NSTextCheckingResult, in text: String) -> HTMLElement.TagType { if match.captureGroup(in: CaptureGroups.selfClosingElement.rawValue, text: text) != nil { return .selfClosing } else if match.captureGroup(in: CaptureGroups.closingTag.rawValue, text: text) != nil { return .closed } return .single } }
2be83d46dc0db518328f8018115a8afd
31.08871
159
0.615481
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/Seismography/Demangler.swift
mit
1
/// Demangler.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation private let MAXIMUM_SUBST_REPEAT_COUNT = 2048 public final class Demangler { public final class Node { public enum Kind: Hashable { case global case identifier(String) case module(String) case data case function case tuple case emptyTuple case firstElementMarker case tupleElement case type case bottomType case typeType case functionType case argumentTuple case substitutedType } let kind: Kind var children: [Node] = [] public init(_ kind: Kind) { self.kind = kind } func addChild(_ node: Node) { self.children.append(node) } func reverseChildren() { self.children.reverse() } fileprivate func contains(_ kind: Kind) -> Bool { guard self.kind != kind else { return true } return self.children.contains { $0.contains(kind) } } public func print(to stream: TextOutputStream) { return Printer(root: self, stream: stream).printRoot() } final class Printer { let root: Node var stream: TextOutputStream init(root: Node, stream: TextOutputStream) { self.root = root self.stream = stream } } } private let buffer: Data private var position = 0 private var nodeStack = [Node]() private var substitutions = [Node]() private var substitutionBuffer = [String]() private var nextWordIdx = 0 public init(_ text: Data) { self.substitutionBuffer = [String](repeating: "", count: MAXIMUM_WORDS_CAPACITY) self.nodeStack.reserveCapacity(16) self.substitutions.reserveCapacity(16) self.buffer = text } public static func demangleSymbol(_ mangledName: String) -> Node? { let dem = Demangler(mangledName.data(using: .utf8)!) let prefixLength = dem.getManglingPrefixLength(mangledName) guard prefixLength > 0 else { return nil } dem.position += prefixLength if !dem.demangleTopLevel() { return nil } let topLevel = dem.createNode(.global) for nd in dem.nodeStack { switch nd.kind { case .type: topLevel.addChild(nd.children.first!) default: topLevel.addChild(nd) } } guard !topLevel.children.isEmpty else { return nil } return topLevel } } // MARK: Core Demangling Routines fileprivate extension Demangler { func demangleTopLevel() -> Bool { while self.position < self.buffer.count { guard let node = self.demangleEntity() else { return false } pushNode(node) } return true } func demangleEntity() -> Node? { switch nextChar() { case ManglingScalars.UPPERCASE_A: return self.demangleSubstitutions() case ManglingScalars.UPPERCASE_B: return createNode(.type, [createNode(.bottomType)]) case ManglingScalars.UPPERCASE_D: return self.demangleDataType() case ManglingScalars.UPPERCASE_F: return self.demangleFunction() case ManglingScalars.LOWERCASE_F: return self.demangleFunctionType() case ManglingScalars.UPPERCASE_G: return self.demangleBoundGenericType() case ManglingScalars.UPPERCASE_T: return self.createNode(.type, [createNode(.typeType)]) case ManglingScalars.LOWERCASE_T: return self.popTuple() case ManglingScalars.LOWERCASE_Y: return self.createNode(.emptyTuple) case ManglingScalars.UNDERSCORE: return self.createNode(.firstElementMarker) default: pushBack() return demangleIdentifier() } } func demangleNumber() -> Int? { guard peekChar().isDigit else { return nil } var number = 0 while true { let c = peekChar() guard c.isDigit else { return number } let newNum = (10 * number) + Int(c - ManglingScalars.ZERO) if newNum < number { return nil } number = newNum nextChar() } } func demangleIdentifier() -> Node? { var hasWordSubsts = false var isPunycoded = false let c = peekChar() guard c.isDigit else { return nil } if c == ManglingScalars.ZERO { nextChar() if peekChar() == ManglingScalars.ZERO { nextChar() isPunycoded = true } else { hasWordSubsts = true } } var result = "" repeat { while hasWordSubsts && peekChar().isLetter { let c = nextChar() let proposedIdx: Int if c.isLowerLetter { proposedIdx = Int(c - ManglingScalars.LOWERCASE_A) } else { assert(c.isUpperLetter) proposedIdx = Int(c - ManglingScalars.UPPERCASE_A) hasWordSubsts = false } guard proposedIdx < self.nextWordIdx else { return nil } assert(proposedIdx < MAXIMUM_WORDS_CAPACITY) let cachedWord = self.substitutionBuffer[Int(proposedIdx)] result.append(cachedWord) } if nextIf(ManglingScalars.ZERO) { break } guard let numChars = demangleNumber() else { return nil } if isPunycoded { nextIf(ManglingScalars.DOLLARSIGN) } guard self.position + numChars <= buffer.count else { return nil } let sliceData = buffer.subdata(in: position..<position + numChars) let slice = String(data: sliceData, encoding: .utf8)! guard !isPunycoded else { let punycoder = Punycode() guard let punyString = punycoder.decode(utf8String: slice.utf8) else { return nil } result.append(punyString) self.position += numChars continue } result.append(slice) var wordStartPos: Int? for idx in 0...sliceData.count { let c = idx < sliceData.count ? sliceData[idx] : 0 guard let startPos = wordStartPos else { if c.isStartOfWord { wordStartPos = idx } continue } if ManglingScalars.isEndOfWord(c, sliceData[idx - 1]) { if idx - startPos >= 2 && self.nextWordIdx < MAXIMUM_WORDS_CAPACITY { let wordData = sliceData.subdata(in: startPos..<idx) let wordString = String(data: wordData, encoding: .utf8)! self.substitutionBuffer[self.nextWordIdx] = wordString self.nextWordIdx += 1 } wordStartPos = nil } } self.position += numChars } while hasWordSubsts guard !result.isEmpty else { return nil } let identNode = createNode(.identifier(result)) addSubstitution(identNode) return identNode } } // MARK: Demangling Substitutions fileprivate extension Demangler { func demangleSubstitutions() -> Node? { var repeatCount = -1 while true { switch nextChar() { case 0: // End of text. return nil case let c where c.isLowerLetter: let lowerLetter = Int(c - ManglingScalars.LOWERCASE_A) guard let subst = pushSubstitutions(repeatCount, lowerLetter) else { return nil } pushNode(subst) repeatCount = -1 // Additional substitutions follow. continue case let c where c.isUpperLetter: let upperLetter = Int(c - ManglingScalars.UPPERCASE_A) // No more additional substitutions. return pushSubstitutions(repeatCount, upperLetter) case let c where c == ManglingScalars.DOLLARSIGN: // The previously demangled number is the large (> 26) index of a // substitution. let idx = repeatCount + 26 + 1 guard idx < self.substitutions.count else { return nil } return self.substitutions[idx] default: pushBack() // Not a letter? Then it's the repeat count (no underscore) // or a large substitution index (underscore). guard let nextRepeatCount = demangleNumber() else { return nil } repeatCount = nextRepeatCount } } } func pushSubstitutions(_ repeatCount: Int, _ idx: Int) -> Node? { guard idx < self.substitutions.count else { return nil } guard repeatCount <= MAXIMUM_SUBST_REPEAT_COUNT else { return nil } let substitutedNode = self.substitutions[idx] guard 0 < repeatCount else { return substitutedNode } for _ in 0..<repeatCount { pushNode(substitutedNode) } return substitutedNode } } // MARK: Demangling Declarations fileprivate extension Demangler { func popTuple() -> Node? { let root = createNode(.tuple) var firstElem = false repeat { firstElem = popNode(.firstElementMarker) != nil let tupleElmt = createNode(.tupleElement) guard let type = popNode(.type) else { return nil } tupleElmt.addChild(type) root.addChild(tupleElmt) } while (!firstElem) root.reverseChildren() return createNode(.type, [root]) } func popModule() -> Node? { if let ident = popNode(), case let .identifier(text) = ident.kind { return createNode(.module(text)) } return popNode({ $0.kind.isModule }) } func popContext() -> Node? { if let module = popModule() { return module } guard let type = popNode(.type) else { return popNode({ $0.kind.isContext }) } guard type.children.count == 1 else { return nil } guard let child = type.children.first else { return nil } guard child.kind.isContext else { return nil } return child } func demangleDataType() -> Node? { guard let name = popNode({ $0.kind.isIdentifier }) else { return nil } guard let context = popContext() else { return nil } let type = createNode(.type, [createNode(.data, [context, name])]) addSubstitution(type) return type } func demangleFunction() -> Node? { guard let type = popNode(.type) else { return nil } guard let fnType = type.children.first, fnType.kind == .functionType else { return nil } guard let name = popNode({ $0.kind.isIdentifier }) else { return nil } guard let context = popContext() else { return nil } return createNode(.function, [context, name, type]) } func demangleFunctionType() -> Node? { let funcType = createNode(.functionType) if let params = demangleFunctionPart(.argumentTuple) { funcType.addChild(params) } guard let returnType = popNode(.type) else { return nil } funcType.addChild(returnType) return createNode(.type, [funcType]) } func demangleFunctionPart(_ kind: Node.Kind) -> Node? { let type: Node if popNode(.emptyTuple) != nil { type = createNode(.type, [createNode(.tuple)]) } else { type = popNode(.type)! } return createNode(kind, [type]) } func demangleBoundGenericType() -> Node? { guard let nominal = popNode(.type)?.children[0] else { return nil } var typeList = [Node]() if popNode(.emptyTuple) == nil { let type = popNode(.type)! if type.children[0].kind == .tuple { typeList.append(contentsOf: type.children[0].children) } else { typeList.append(type.children[0]) } } let args = createNode(.argumentTuple, typeList) switch nominal.kind { case .data: let boundNode = createNode(.substitutedType, [nominal, args]) let nty = createNode(.type, [boundNode]) self.addSubstitution(nty) return nty default: fatalError() } } } // MARK: Parsing fileprivate extension Demangler { func peekChar() -> UInt8 { guard self.position < self.buffer.count else { return 0 } return self.buffer[position] } @discardableResult func nextChar() -> UInt8 { guard self.position < self.buffer.count else { return 0 } defer { self.position += 1 } return buffer[position] } @discardableResult func nextIf(_ c: UInt8) -> Bool { guard peekChar() == c else { return false } self.position += 1 return true } func pushBack() { assert(position > 0) position -= 1 } func consumeAll() -> String { let str = buffer.dropFirst(position) self.position = buffer.count return String(bytes: str, encoding: .utf8)! } } // MARK: Manipulating The Node Stack fileprivate extension Demangler { func createNode(_ k: Node.Kind, _ children: [Node] = []) -> Node { let node = Node(k) for child in children { node.addChild(child) } return node } func pushNode(_ Nd: Node) { nodeStack.append(Nd) } func popNode() -> Node? { return self.nodeStack.popLast() } func popNode(_ kind: Node.Kind) -> Node? { guard let lastNode = nodeStack.last else { return nil } guard lastNode.kind == kind else { return nil } return popNode() } func popNode(_ pred: (Node) -> Bool) -> Node? { guard let lastNode = nodeStack.last else { return nil } guard pred(lastNode) else { return nil } return popNode() } private func addSubstitution(_ Nd: Node) { self.substitutions.append(Nd) } private func getManglingPrefixLength(_ mangledName: String) -> Int { guard !mangledName.isEmpty else { return 0 } guard mangledName.starts(with: MANGLING_PREFIX) else { return 0 } return MANGLING_PREFIX.count } } // MARK: Demangler Node Attributes fileprivate extension Demangler.Node.Kind { var isContext: Bool { switch self { case .data: return true case .function: return true case .module(_): return true case .substitutedType: return true case .global: return false case .identifier(_): return false case .tuple: return false case .emptyTuple: return false case .firstElementMarker: return false case .tupleElement: return false case .type: return false case .bottomType: return false case .typeType: return false case .functionType: return false case .argumentTuple: return false } } var isModule: Bool { switch self { case .module(_): return true default: return false } } var isIdentifier: Bool { switch self { case .identifier(_): return true default: return false } } } // MARK: Printing extension Demangler.Node.Printer { func printRoot() { print(self.root) } func print(_ node: Demangler.Node) { switch node.kind { case .global: printChildren(node.children) case let .identifier(str): self.stream.write(str) case let .module(str): self.stream.write(str) case .data: let ctx = node.children[0] let name = node.children[1] print(ctx) self.stream.write(".") print(name) case .function: let ctx = node.children[0] let name = node.children[1] let type = node.children[2] print(ctx) self.stream.write(".") print(name) print(type.children[0]) case .argumentTuple: print(node.children[0]) case .type: print(node.children[0]) case .bottomType: self.stream.write("_") case .functionType: let params = node.children[0] let retTy = node.children[1] self.stream.write("(") print(params) if !params.children.isEmpty { self.stream.write(", ") } self.stream.write("(") print(retTy) self.stream.write(") -> _") self.stream.write(")") case .tuple: printChildren(node.children, separator: ", ") case .tupleElement: let type = node.children[0] print(type) case .emptyTuple: self.stream.write("()") default: fatalError("\(node.kind)") } } func printChildren(_ children: [Demangler.Node], separator: String = "") { guard let last = children.last else { return } for child in children.dropLast() { print(child) stream.write(separator) } print(last) } }
8d555a9b8d1eb630428c9ae5ce3f58ae
22.252125
79
0.605933
false
false
false
false
algolia/algoliasearch-client-swift
refs/heads/master
Sources/AlgoliaSearchClient/Client/Search/SearchClient+Wait.swift
mit
1
// // SearchClient+Wait.swift // // // Created by Vladislav Fitc on 22/01/2021. // import Foundation public extension Client { // MARK: - Task status /** Check the current TaskStatus of a given Task. - parameter taskID: of the indexing [Task]. - parameter requestOptions: Configure request locally with [RequestOptions] */ @discardableResult func taskStatus(for taskID: AppTaskID, requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<TaskInfo>) -> Operation & TransportTask { let command = Command.Advanced.AppTaskStatus(taskID: taskID, requestOptions: requestOptions) return execute(command, completion: completion) } /** Check the current TaskStatus of a given Task. - parameter taskID: of the indexing [Task]. - parameter requestOptions: Configure request locally with [RequestOptions] */ @discardableResult func taskStatus(for taskID: AppTaskID, requestOptions: RequestOptions? = nil) throws -> TaskInfo { let command = Command.Advanced.AppTaskStatus(taskID: taskID, requestOptions: requestOptions) return try execute(command) } // MARK: - Wait task /** Wait for a Task to complete before executing the next line of code, to synchronize index updates. All write operations in Algolia are asynchronous by design. It means that when you add or update an object to your index, our servers will reply to your request with a TaskID as soon as they understood the write operation. The actual insert and indexing will be done after replying to your code. You can wait for a task to complete by using the TaskID and this method. - parameter taskID: of the indexing task to wait for. - parameter requestOptions: Configure request locally with RequestOptions */ @discardableResult func waitTask(withID taskID: AppTaskID, timeout: TimeInterval? = nil, requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<TaskStatus>) -> Operation { let task = WaitTask(client: self, taskID: taskID, timeout: timeout, requestOptions: requestOptions, completion: completion) return launch(task) } /** Wait for a Task to complete before executing the next line of code, to synchronize index updates. All write operations in Algolia are asynchronous by design. It means that when you add or update an object to your index, our servers will reply to your request with a TaskID as soon as they understood the write operation. The actual insert and indexing will be done after replying to your code. You can wait for a task to complete by using the TaskID and this method. - parameter taskID: of the indexing task to wait for. - parameter requestOptions: Configure request locally with RequestOptions */ @discardableResult func waitTask(withID taskID: AppTaskID, timeout: TimeInterval? = nil, requestOptions: RequestOptions? = nil) throws -> TaskStatus { let task = WaitTask(client: self, taskID: taskID, timeout: timeout, requestOptions: requestOptions, completion: { _ in }) return try launch(task) } }
a98a08dd40e0003c6ad499c79a2ad7e4
40.686047
116
0.640167
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Controllers/Settings/Passphrase/Views/PassphraseWordView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. import UIKit import SweetUIKit class PassphraseWordView: UIControl { static let height: CGFloat = 35 private lazy var background: UIView = { let view = UIView(withAutoLayout: true) view.layer.cornerRadius = 4 view.clipsToBounds = true view.isUserInteractionEnabled = false view.addDashedBorder() return view }() private lazy var backgroundOverlay: UIView = { let view = UIView(withAutoLayout: true) view.backgroundColor = UIColor.black.withAlphaComponent(0.3) view.isUserInteractionEnabled = false view.layer.cornerRadius = 3 view.clipsToBounds = true view.alpha = 0 return view }() private lazy var wordLabel: UILabel = { let view = UILabel(withAutoLayout: true) view.font = Theme.preferredRegular() view.textColor = Theme.darkTextColor view.textAlignment = .center view.isUserInteractionEnabled = false view.adjustsFontForContentSizeCategory = true return view }() private lazy var feedbackGenerator: UIImpactFeedbackGenerator = { UIImpactFeedbackGenerator(style: .light) }() var word: Word? convenience init(with word: Word) { self.init(withAutoLayout: true) self.word = word wordLabel.text = word.text addSubview(background) background.addSubview(backgroundOverlay) addSubview(wordLabel) NSLayoutConstraint.activate([ self.background.topAnchor.constraint(equalTo: self.topAnchor), self.background.leftAnchor.constraint(equalTo: self.leftAnchor), self.background.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.background.rightAnchor.constraint(equalTo: self.rightAnchor), self.backgroundOverlay.topAnchor.constraint(equalTo: self.topAnchor, constant: 1), self.backgroundOverlay.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 1), self.backgroundOverlay.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -1), self.backgroundOverlay.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -1), self.wordLabel.topAnchor.constraint(equalTo: self.topAnchor), self.wordLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10), self.wordLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.wordLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10), self.heightAnchor.constraint(equalToConstant: PassphraseWordView.height).priority(.defaultHigh) ]) setNeedsLayout() } override func layoutIfNeeded() { super.layoutIfNeeded() layoutBorder() } func layoutBorder() { for shape in shapeLayers { shape.bounds = bounds shape.position = CGPoint(x: bounds.width / 2, y: bounds.height / 2) shape.path = UIBezierPath(roundedRect: bounds, cornerRadius: 4).cgPath } } func setBorder(dashed: Bool) { for shape in shapeLayers { shape.lineDashPattern = dashed ? [5, 5] : nil } } var shapeLayers: [CAShapeLayer] { guard let sublayers = self.background.layer.sublayers else { return [] } return sublayers.compactMap { layer in layer as? CAShapeLayer } } func getSize() -> CGSize { layoutIfNeeded() return frame.size } var isAddedForVerification: Bool = false { didSet { UIView.highlightAnimation { self.wordLabel.alpha = self.isAddedForVerification ? 0 : 1 self.background.backgroundColor = self.isAddedForVerification ? nil : Theme.lightTextColor self.alpha = self.isAddedForVerification ? 0.6 : 1 self.setBorder(dashed: self.isAddedForVerification) } } } override var isHighlighted: Bool { didSet { if isHighlighted != oldValue { feedbackGenerator.impactOccurred() UIView.highlightAnimation { self.backgroundOverlay.alpha = self.isHighlighted ? 1 : 0 } } } } } extension UIView { func addDashedBorder() { let shapeLayer = CAShapeLayer() shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.black.withAlphaComponent(0.1).cgColor shapeLayer.lineWidth = 2 shapeLayer.lineJoin = kCALineJoinRound self.layer.addSublayer(shapeLayer) } }
6ea945dbed292f81d3bd0c07e7c29d23
32.024691
107
0.651215
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
125. TraxPersistence/Trax/GPXViewController.swift
mit
1
// // ViewController.swift // Trax // // Created by jiaxianhua on 15/10/4. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit import MapKit class GPXViewController: UIViewController, MKMapViewDelegate, UIPopoverPresentationControllerDelegate { // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! { didSet { mapView.mapType = .Satellite mapView.delegate = self } } // MARK: - Public API var gpxURL: NSURL? { didSet { clearWaypoints() if let url = gpxURL { GPX.parse(url) { if let gpx = $0 { self.handleWaypoints(gpx.waypoints) } } } } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() let center = NSNotificationCenter.defaultCenter() let queue = NSOperationQueue.mainQueue() let appDelegate = UIApplication.sharedApplication().delegate center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue) { notification in if let url = notification.userInfo?[GPXURL.key] as? NSURL { self.gpxURL = url } } gpxURL = NSURL(string: "http://cs193p.stanford.edu/Vacation.gpx") } // MARK: - Waypoints private func clearWaypoints() { if mapView?.annotations != nil { mapView.removeAnnotations(mapView.annotations as [MKAnnotation]) } } private func handleWaypoints(waypoints: [GPX.Waypoint]) { mapView.addAnnotations(waypoints) mapView.showAnnotations(waypoints, animated: true) } @IBAction func addWaypoint(sender: UILongPressGestureRecognizer) { if sender.state == UIGestureRecognizerState.Began { let coordinate = mapView.convertPoint(sender.locationInView(mapView), toCoordinateFromView: mapView) let waypoint = EditableWaypoint(latitude: coordinate.latitude, longitude: coordinate.longitude) waypoint.name = "Dropped" // waypoint.links.append(GPX.Link(href: "http://iosdevlog.com/assets/images/podcast/iOSDevLog.png")) mapView.addAnnotation(waypoint) } } // MARK: - Constants private struct Constants { static let LeftCalloutFrame = CGRect(x: 0, y: 0, width: 59, height: 59) static let AnnotationViewReuseIdentifier = "waypoint" static let ShowImageSegue = "Show Image" static let EditWaypointSegue = "Edit Waypoint" static let EditWaypointPopoverWidth: CGFloat = 320 } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier) if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier) view!.canShowCallout = true } else { view!.annotation = annotation } view?.draggable = annotation is EditableWaypoint view!.leftCalloutAccessoryView = nil view!.rightCalloutAccessoryView = nil if let waypoint = annotation as? GPX.Waypoint { if waypoint.thumbnailURL != nil { view!.leftCalloutAccessoryView = UIButton(frame: Constants.LeftCalloutFrame) } if annotation is EditableWaypoint { view!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) } } return view } // this had to be adjusted slightly when we added editable waypoints // we can no longer depend on the thumbnailURL being set at "annotation view creation time" // so here we just check to see if there's a thumbnail URL // and, if so, we can lazily create the leftCalloutAccessoryView if needed func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { if let waypoint = view.annotation as? GPX.Waypoint { if let url = waypoint.thumbnailURL { if view.leftCalloutAccessoryView == nil { // a thumbnail must have been added since the annotation view was created view.leftCalloutAccessoryView = UIButton(frame: Constants.LeftCalloutFrame) } if let thumbnailImageButton = view.leftCalloutAccessoryView as? UIButton { if let imageData = NSData(contentsOfURL: url) { // blocks main thread! if let image = UIImage(data: imageData) { thumbnailImageButton.setImage(image, forState: .Normal) } } } } } } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if (control as? UIButton)?.buttonType == UIButtonType.DetailDisclosure { mapView.deselectAnnotation(view.annotation, animated: false) performSegueWithIdentifier(Constants.EditWaypointSegue, sender: view) } else if let waypoint = view.annotation as? GPX.Waypoint { if waypoint.imageURL != nil { performSegueWithIdentifier(Constants.ShowImageSegue, sender: view) } } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Constants.ShowImageSegue { if let waypoint = (sender as? MKAnnotationView)?.annotation as? GPX.Waypoint { if let ivc = segue.destinationViewController.contentViewController as? ImageViewController { ivc.imageURL = waypoint.imageURL ivc.title = waypoint.name } } } else if segue.identifier == Constants.EditWaypointSegue { if let waypoint = (sender as? MKAnnotationView)?.annotation as? EditableWaypoint { if let ewvc = segue.destinationViewController.contentViewController as? EditWaypointViewController { let coordinatePoint = mapView.convertCoordinate(waypoint.coordinate, toPointToView: mapView) if let ppc = ewvc.popoverPresentationController { ppc.sourceRect = (sender as! MKAnnotationView).popoverSourceRectForCoordinatePoint(coordinatePoint) let minimumSize = ewvc.view.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) ewvc.preferredContentSize = CGSize(width: Constants.EditWaypointPopoverWidth, height: minimumSize.height) ppc.delegate = self } ewvc.waypointToEdit = waypoint } } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.OverFullScreen } func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { let navcon = UINavigationController(rootViewController: controller.presentedViewController) let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) visualEffectView.frame = navcon.view.bounds navcon.view.insertSubview(visualEffectView, atIndex: 0) return navcon } } // MARK: - Convenience Extensions extension UIViewController { var contentViewController: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController! } else { return self } } } extension MKAnnotationView { func popoverSourceRectForCoordinatePoint(coordinatePoint: CGPoint) -> CGRect { var popoverSourceRectCenter = coordinatePoint popoverSourceRectCenter.x -= frame.width / 2 - centerOffset.x - calloutOffset.x popoverSourceRectCenter.y -= frame.height / 2 - centerOffset.y - calloutOffset.y return CGRect(origin: popoverSourceRectCenter, size: frame.size) } }
a90547c52a53ccf94f753fcd8bd9eb75
40.567961
168
0.634357
false
false
false
false
grpc/grpc-swift
refs/heads/main
Tests/GRPCTests/EchoHelpers/Interceptors/EchoInterceptorFactories.swift
apache-2.0
1
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoModel import GRPC // MARK: - Client internal final class EchoClientInterceptors: Echo_EchoClientInterceptorFactoryProtocol { #if swift(>=5.6) internal typealias Factory = @Sendable () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #else internal typealias Factory = () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #endif // swift(>=5.6) private let factories: [Factory] internal init(_ factories: Factory...) { self.factories = factories } private func makeInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } } // MARK: - Server internal final class EchoServerInterceptors: Echo_EchoServerInterceptorFactoryProtocol { internal typealias Factory = () -> ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse> private var factories: [Factory] = [] internal init(_ factories: Factory...) { self.factories = factories } internal func register(_ factory: @escaping Factory) { self.factories.append(factory) } private func makeInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } }
7249bf1cd77cc95deda00f3c059dbbae
31.829545
95
0.734856
false
false
false
false
peferron/algo
refs/heads/master
EPI/Linked Lists/Remove the kth last element from a list/swift/test.swift
mit
1
import Darwin func nodes(_ count: Int) -> [Node] { let nodes = (0..<count).map { _ in Node() } for i in 0..<count - 1 { nodes[i].next = nodes[i + 1] } return nodes } ({ let n = nodes(3) let newHead = n[0].removeLast(0) guard newHead === n[0] && n[0].next === n[1] && n[1].next == nil else { print("Failed test removing last node") exit(1) } })() ({ let n = nodes(3) let newHead = n[0].removeLast(1) guard newHead === n[0] && n[0].next === n[2] && n[2].next == nil else { print("Failed test removing 2nd last node") exit(1) } })() ({ let n = nodes(3) let newHead = n[0].removeLast(2) guard newHead === n[1] && n[1].next === n[2] && n[2].next == nil else { print("Failed test removing 3rd last node") exit(1) } })() ({ let n = nodes(1) let newHead = n[0].removeLast(0) guard newHead == nil else { print("Failed test removing only node") exit(1) } })()
11a15797d5bc7613eae1d0cc02b4970e
19.632653
75
0.497527
false
true
false
false
leoMehlig/Charts
refs/heads/master
Charts/Classes/Charts/BarLineChartViewBase.swift
apache-2.0
2
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate { /// the maximum number of entries to which values will be drawn /// (entry numbers greater than this value will cause value-labels to disappear) internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = NSUIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = NSUIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = false /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// Sets the minimum offset (padding) around the chart, defaults to 10 public var minOffset = CGFloat(10.0) /// flag indicating if the chart should stay at the same position after a rotation or not. Default is false. public var keepPositionOnRotation: Bool = false /// the object representing the left y-axis internal var _leftAxis: ChartYAxis! /// the object representing the right y-axis internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: NSUITapGestureRecognizer! internal var _doubleTapGestureRecognizer: NSUITapGestureRecognizer! #if !os(tvOS) internal var _pinchGestureRecognizer: NSUIPinchGestureRecognizer! #endif internal var _panGestureRecognizer: NSUIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .Left) _rightAxis = ChartYAxis(position: .Right) _xAxis = ChartXAxis() _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) self.highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")) _doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2 _panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled _panGestureRecognizer.enabled = _dragEnabled #if !os(tvOS) _pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")) _pinchGestureRecognizer.delegate = self self.addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { //Saving current position of chart. var oldPoint: CGPoint? if (keepPositionOnRotation && (keyPath == "frame" || keyPath == "bounds")) { oldPoint = viewPortHandler.contentRect.origin getTransformer(.Left).pixelToValue(&oldPoint!) } //Superclass transforms chart. super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) //Restoring old position of chart if var newPoint = oldPoint where keepPositionOnRotation { getTransformer(.Left).pointValueToPixel(&newPoint) viewPortHandler.centerViewPort(pt: newPoint, chart: self) } } public override func drawRect(rect: CGRect) { super.drawRect(rect) if _data === nil { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context) CGContextClipToRect(context, _viewPortHandler.contentRect) if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) renderer?.drawData(context: context) if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHighlight) } // Removes clipping rectangle CGContextRestoreGState(context) renderer!.drawExtras(context: context) _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted) } public override func notifyDataSetChanged() { calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) if let data = _data { _xAxisRenderer?.computeAxis(xValAverageLength: data.xValAverageLength, xValues: data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(data) } } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data?.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } var minLeft = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : _data?.getYMin(.Left) ?? 0.0 var maxLeft = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : _data?.getYMax(.Left) ?? 0.0 var minRight = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : _data?.getYMin(.Right) ?? 0.0 var maxRight = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : _data?.getYMax(.Right) ?? 0.0 let leftRange = abs(maxLeft - minLeft) let rightRange = abs(maxRight - minRight) // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0 minLeft = minLeft - 1.0 } if (rightRange == 0.0) { maxRight = maxRight + 1.0 minRight = minRight - 1.0 } let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop) let topSpaceRight = rightRange * Double(_rightAxis.spaceTop) let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom) let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom) _chartXMax = Double((_data?.xVals.count ?? 0) - 1) _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) // Use the values as they are _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft) _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft) _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight) _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight) _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum) _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum) } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled) { let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data?.xValCount ?? 0) * _xAxis.labelRotatedWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { guard let data = _data else { return CGPointZero } let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(e.xIndex) var yPos = CGFloat(e.value) if (self.isKindOfClass(BarChartView)) { let bd = _data as! BarChartData let space = bd.groupSpace let setCount = data.dataSetCount let i = e.xIndex if self is HorizontalBarChartView { // calculate the x-position, depending on datasetcount let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 yPos = y if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { xPos = CGFloat(highlight.range!.to) } else { xPos = CGFloat(e.value) } } } else { let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 xPos = x if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { yPos = CGFloat(highlight.range!.to) } else { yPos = CGFloat(e.value) } } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY) getTransformer(data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context) } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor) CGContextFillRect(context, _viewPortHandler.contentRect) } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth) CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextStrokeRect(context, _viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context) } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.Both private var _closestDataSetToTouch: IChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: NSUIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: NSUITapGestureRecognizer) { if _data === nil { return } if (recognizer.state == NSUIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } let h = getHighlightByTouchPoint(recognizer.locationInView(self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(recognizer: NSUITapGestureRecognizer) { if _data === nil { return } if (recognizer.state == NSUIGestureRecognizerState.Ended) { if _data !== nil && _doubleTapToZoomEnabled { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(recognizer: NSUIPinchGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Began) { stopDeceleration() if _data !== nil && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .Both } else { let x = abs(recognizer.locationInView(self).x - recognizer.nsuiLocationOfTouch(1, inView: self).x) let y = abs(recognizer.locationInView(self).y - recognizer.nsuiLocationOfTouch(1, inView: self).y) if (x > y) { _gestureScaleAxis = .X } else { _gestureScaleAxis = .Y } } } } else if (recognizer.state == NSUIGestureRecognizerState.Ended || recognizer.state == NSUIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == NSUIGestureRecognizerState.Changed) { let isZoomingOut = (recognizer.nsuiScale < 1) var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY if (_isScaling) { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .X); canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y); if canZoomMoreX || canZoomMoreY { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0 let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0 var matrix = CGAffineTransformMakeTranslation(location.x, location.y) matrix = CGAffineTransformScale(matrix, scaleX, scaleY) matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y) matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.nsuiScale = 1.0 } } } #endif @objc private func panGestureRecognized(recognizer: NSUIPanGestureRecognizer) { if (recognizer.state == NSUIGestureRecognizerState.Began && recognizer.nsuiNumberOfTouches() > 0) { stopDeceleration() if _data === nil { // If we have no data, we have nothing to pan and no data to highlight return; } // If drag is enabled and we are in a position where there's something to drag: // * If we're zoomed in, then obviously we have something to drag. // * If we have a drag offset - we always have something to drag if self.isDragEnabled && (!self.hasNoDragOffset || !self.isFullyZoomedOut) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.nsuiLocationOfTouch(0, inView: self)) let translation = recognizer.translationInView(self) let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if (didUserDrag && !performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false } } _lastPanPoint = recognizer.translationInView(self) } else if self.isHighlightPerDragEnabled { // We will only handle highlights on NSUIGestureRecognizerState.Changed _isDragging = false } } else if (recognizer.state == NSUIGestureRecognizerState.Changed) { if (_isDragging) { let originalTranslation = recognizer.translationInView(self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (isHighlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == NSUIGestureRecognizerState.Ended || recognizer.state == NSUIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == NSUIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocityInView(self) _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true _outerScrollView = nil } } } private func performPanChange(var translation translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y) matrix = CGAffineTransformConcat(originalMatrix, matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } private func nsuiGestureRecognizerShouldBegin(gestureRecognizer: NSUIGestureRecognizer) -> Bool { if (gestureRecognizer == _panGestureRecognizer) { if _data === nil || !_dragEnabled || (self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if _data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled) { return false } } #endif } return true } #if !os(OSX) public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } return nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif #if os(OSX) public func gestureRecognizerShouldBegin(gestureRecognizer: NSGestureRecognizer) -> Bool { return nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif public func gestureRecognizer(gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: NSUIGestureRecognizer) -> Bool { #if !os(tvOS) if ((gestureRecognizer.isKindOfClass(NSUIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(NSUIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(NSUIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(NSUIPinchGestureRecognizer))) { return true } #endif if (gestureRecognizer.isKindOfClass(NSUIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(NSUIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !scrollView!.isKindOfClass(NSUIScrollView)) { scrollView = scrollView?.superview } // If there is two scrollview together, we pick the superview of the inner scrollview. // In the case of UITableViewWrepperView, the superview will be UITableView if let superViewOfScrollView = scrollView?.superview where superViewOfScrollView.isKindOfClass(NSUIScrollView) { scrollView = superViewOfScrollView } var foundScrollView = scrollView as? NSUIScrollView if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: NSUIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.nsuiGestureRecognizers! { if (scrollRecognizer.isKindOfClass(NSUIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! NSUIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. public func zoomIn() { let center = _viewPortHandler.contentCenter let matrix = _viewPortHandler.zoomIn(x: center.x, y: -center.y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. public func zoomOut() { let center = _viewPortHandler.contentCenter let matrix = _viewPortHandler.zoomOut(x: center.x, y: -center.y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. /// x and y are the values (**not pixels**) which to zoom to or from (the values of the zoom center). /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: public func zoom( scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let job = ZoomChartViewJob(viewPortHandler: viewPortHandler, scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, transformer: getTransformer(axis), axis: axis, view: self) addViewportJob(job) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func zoomAndCenterViewAnimated( scaleX scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { let origin = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let job = AnimatedZoomChartViewJob( viewPortHandler: viewPortHandler, transformer: getTransformer(axis), view: self, yAxis: getAxis(axis), xValCount: _xAxis.values.count, scaleX: scaleX, scaleY: scaleY, xOrigin: viewPortHandler.scaleX, yOrigin: viewPortHandler.scaleY, zoomCenterX: xIndex, zoomCenterY: CGFloat(yValue), zoomOriginX: origin.x, zoomOriginY: origin.y, duration: duration, easing: easing) addViewportJob(job) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func zoomAndCenterViewAnimated( scaleX scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easingOption: ChartEasingOption) { zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - parameter scaleX: /// - parameter scaleY: /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func zoomAndCenterViewAnimated( scaleX scaleX: CGFloat, scaleY: CGFloat, xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval) { zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .EaseInOutSine) } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMaximum(maxXRange: CGFloat) { let xScale = _deltaX / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no less than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMinimum(minXRange: CGFloat) { let xScale = _deltaX / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = _deltaX / minXRange let minScale = _deltaX / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. /// This also refreshes the chart by calling setNeedsDisplay(). public func moveViewToX(xIndex: CGFloat) { let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: 0.0, transformer: getTransformer(.Left), view: self) addViewportJob(job) } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: 0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewTo(xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func moveViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { let bounds = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let job = AnimatedMoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func moveViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easingOption: ChartEasingOption) { moveViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func moveViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval) { moveViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .EaseInOutSine) } /// This will move the center of the current viewport to the specified x-index and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func centerViewTo( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX let job = MoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex - xsInView / 2.0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func centerViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { let bounds = getValueByTouchPoint( pt: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis) let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX let job = AnimatedMoveChartViewJob( viewPortHandler: viewPortHandler, xIndex: xIndex - xsInView / 2.0, yValue: yValue + Double(valsInView) / 2.0, transformer: getTransformer(axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func centerViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval, easingOption: ChartEasingOption) { centerViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: which axis should be used as a reference for the y-axis /// - parameter duration: the duration of the animation in seconds /// - parameter easing: public func centerViewToAnimated( xIndex xIndex: CGFloat, yValue: Double, axis: ChartYAxis.AxisDependency, duration: NSTimeInterval) { centerViewToAnimated(xIndex: xIndex, yValue: yValue, axis: axis, duration: duration, easingOption: .EaseInOutSine) } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled } } } /// **default**: true /// - returns: true if zooming via double-tap is enabled false if not. public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `NSUIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled } /// **default**: true /// - returns: true if drawing the grid background is enabled, false if not. public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled } /// **default**: false /// - returns: true if drawing the borders rectangle is enabled, false if not. public var isDrawBordersEnabled: Bool { return drawBordersEnabled } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> IBarLineScatterCandleBubbleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data?.getDataSetByIndex(h!.dataSetIndex) as! IBarLineScatterCandleBubbleChartDataSet! } return nil } /// - returns: the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis } else { return _rightAxis } } /// - returns: the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// **default**: false /// - returns: true if pinch-zoom is enabled, false if not public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer public var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer public var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer public var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } public override var chartYMax: Double { return max(leftAxis.axisMaximum, rightAxis.axisMaximum) } public override var chartYMin: Double { return min(leftAxis.axisMinimum, rightAxis.axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes public var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// **default**: false /// - returns: true if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; } /// Sets a minimum width to the specified y axis. public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } public func isInverted(axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(round(pt.x + 1.0)) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint( x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) guard let data = _data else { return Int(round(pt.x)) } return min(data.xValCount - 1, Int(round(pt.x))) } }
dd07ca39ff94ad3ab4e3cc0c54cd9f78
35.429807
238
0.589374
false
false
false
false
AnRanScheme/MagiRefresh
refs/heads/master
Example/MagiRefresh/MagiRefresh/Default/MagiRefreshDefaults.swift
mit
3
// // MagiRefreshDefaults.swift // MagiRefresh // // Created by anran on 2018/9/4. // Copyright © 2018年 anran. All rights reserved. // import UIKit public enum MagiRefreshStyle: Int { case native = 0 case replicatorWoody case replicatorAllen case replicatorCircle case replicatorDot case replicatorArc case replicatorTriangle case animatableRing case animatableArrow } public class MagiRefreshDefaults { public var headerDefaultStyle: MagiRefreshStyle = .animatableArrow public var footerDefaultStyle: MagiRefreshStyle = .native public var themeColor: UIColor = UIColor.blue public var backgroundColor: UIColor = UIColor.white public var headPullingText: String = "继续下拉" public var footPullingText: String = "继续上拉" public var readyText: String = "松开刷新" public var refreshingText: String = "正在加载" public static let shared = MagiRefreshDefaults() }
0838446240364f27266585508b41b1c3
25.138889
70
0.723698
false
false
false
false
teodorpatras/SideMenuController
refs/heads/master
Source/UIKitExtensions.swift
mit
1
// // UIKitExtensions.swift // // Copyright (c) 2015 Teodor Patraş // // 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 let DefaultStatusBarHeight : CGFloat = UIApplication.shared.statusBarFrame.size.height extension UIView { class func panelAnimation(_ duration : TimeInterval, animations : @escaping (()->()), completion : (()->())? = nil) { UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: animations) { _ in completion?() } } } public extension UINavigationController { public func addSideMenuButton(completion: ((UIButton) -> ())? = nil) { guard let image = SideMenuController.preferences.drawing.menuButtonImage else { return } guard let sideMenuController = self.sideMenuController else { return } let button = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) button.accessibilityIdentifier = SideMenuController.preferences.interaction.menuButtonAccessibilityIdentifier button.setImage(image, for: .normal) button.addTarget(sideMenuController, action: #selector(SideMenuController.toggle), for: UIControlEvents.touchUpInside) if SideMenuController.preferences.drawing.sidePanelPosition.isPositionedLeft { let newItems = computeNewItems(sideMenuController: sideMenuController, button: button, controller: self.topViewController, positionLeft: true) self.topViewController?.navigationItem.leftBarButtonItems = newItems } else { let newItems = computeNewItems(sideMenuController: sideMenuController, button: button, controller: self.topViewController, positionLeft: false) self.topViewController?.navigationItem.rightBarButtonItems = newItems } completion?(button) } private func computeNewItems(sideMenuController: SideMenuController, button: UIButton, controller: UIViewController?, positionLeft: Bool) -> [UIBarButtonItem] { var items: [UIBarButtonItem] = (positionLeft ? self.topViewController?.navigationItem.leftBarButtonItems : self.topViewController?.navigationItem.rightBarButtonItems) ?? [] for item in items { if let button = item.customView as? UIButton, button.allTargets.contains(sideMenuController) { return items } } let item:UIBarButtonItem = UIBarButtonItem() item.customView = button let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) spacer.width = -10 items.append(contentsOf: positionLeft ? [spacer, item] : [item, spacer]) return items } } extension UIWindow { func set(_ hidden: Bool, withBehaviour behaviour: SideMenuController.StatusBarBehaviour) { let animations: () -> () switch behaviour { case .fadeAnimation, .horizontalPan: animations = { self.alpha = hidden ? 0 : 1 } case .slideAnimation: animations = { self.transform = hidden ? CGAffineTransform(translationX: 0, y: -1 * DefaultStatusBarHeight) : CGAffineTransform.identity } default: return } if behaviour == .horizontalPan { animations() } else { UIView.animate(withDuration: 0.25, animations: animations) } } } public extension UIViewController { public var sideMenuController: SideMenuController? { return sideMenuControllerForViewController(self) } fileprivate func sideMenuControllerForViewController(_ controller : UIViewController) -> SideMenuController? { if let sideController = controller as? SideMenuController { return sideController } if let parent = controller.parent { return sideMenuControllerForViewController(parent) } else { return nil } } }
eaed658fa10c2f83af7b79b6da80dd1e
39.648438
164
0.667115
false
false
false
false
IngmarStein/swift
refs/heads/master
test/Interpreter/fractal.swift
apache-2.0
17
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-jit-run %s -I %S -enable-source-import | %FileCheck %s // REQUIRES: executable_test // REQUIRES: swift_interpreter // FIXME: iOS: -enable-source-import plus %target-build-swift equals link errors // FIXME: This test uses IRGen with -enable-source-import; it may fail with -g. import complex func printDensity(_ d: Int) { if (d > 40) { print(" ", terminator: "") } else if d > 6 { print(".", terminator: "") } else if d > 4 { print("+", terminator: "") } else if d > 2 { print("*", terminator: "") } else { print("#", terminator: "") } } extension Double { func abs() -> Double { if (self >= 0.0) { return self } return self * -1.0 } } func getMandelbrotIterations(_ c: Complex, maxIterations: Int) -> Int { var n = 0 var z = Complex() while (n < maxIterations && z.magnitude() < 4.0) { z = z*z + c n += 1 } return n } func fractal (_ densityFunc:(_ c: Complex, _ maxIterations: Int) -> Int, xMin:Double, xMax:Double, yMin:Double, yMax:Double, rows:Int, cols:Int, maxIterations:Int) { // Set the spacing for the points in the Mandelbrot set. var dX = (xMax - xMin) / Double(rows) var dY = (yMax - yMin) / Double(cols) // Iterate over the points an determine if they are in the // Mandelbrot set. for row in stride(from: xMin, to: xMax, by: dX) { for col in stride(from: yMin, to: yMax, by: dY) { var c = Complex(real: col, imag: row) printDensity(densityFunc(c, maxIterations)) } print("\n", terminator: "") } } fractal(getMandelbrotIterations, xMin: -1.35, xMax: 1.4, yMin: -2.0, yMax: 1.05, rows: 40, cols: 80, maxIterations: 200) // CHECK: ################################################################################ // CHECK: ##############################********************############################## // CHECK: ########################********************************######################## // CHECK: ####################***************************+++**********#################### // CHECK: #################****************************++...+++**********################# // CHECK: ##############*****************************++++......+************############## // CHECK: ############******************************++++.......+++************############ // CHECK: ##########******************************+++++.... ...++++************########## // CHECK: ########******************************+++++.... ..++++++**********######### // CHECK: #######****************************+++++....... .....++++++**********####### // CHECK: ######*************************+++++....... . .. ............++*********###### // CHECK: #####*********************+++++++++... .. . ... ..++*********##### // CHECK: ####******************++++++++++++..... ..++**********#### // CHECK: ###***************++++++++++++++... . ...+++**********### // CHECK: ##**************+++................. ....+***********## // CHECK: ##***********+++++................. .++***********## // CHECK: #**********++++++..... ..... ..++***********## // CHECK: #*********++++++...... . ..++************# // CHECK: #*******+++++....... ..+++************# // CHECK: #++++............ ...+++************# // CHECK: #++++............ ...+++************# // CHECK: #******+++++........ ..+++************# // CHECK: #********++++++..... . ..++************# // CHECK: #**********++++++..... .... .++************# // CHECK: #************+++++................. ..++***********## // CHECK: ##*************++++................. . ..+***********## // CHECK: ###***************+.+++++++++++..... ....++**********### // CHECK: ###******************+++++++++++++..... ...+++*********#### // CHECK: ####*********************++++++++++.... .. ..++*********##### // CHECK: #####*************************+++++........ . . . .......+*********###### // CHECK: #######***************************+++.......... .....+++++++*********####### // CHECK: ########*****************************++++++.... ...++++++**********######## // CHECK: ##########*****************************+++++..... ....++++***********########## // CHECK: ###########******************************+++++........+++***********############ // CHECK: #############******************************++++.. ...++***********############## // CHECK: ################****************************+++...+++***********################ // CHECK: ###################***************************+.+++**********################### // CHECK: #######################**********************************####################### // CHECK: ############################************************############################ // CHECK: ################################################################################ func getBurningShipIterations(_ c: Complex, maxIterations: Int) -> Int { var n = 0 var z = Complex() while (n < maxIterations && z.magnitude() < 4.0) { var zTmp = Complex(real: z.real.abs(), imag: z.imag.abs()) z = zTmp*zTmp + c n += 1 } return n } print("\n== BURNING SHIP ==\n\n", terminator: "") fractal(getBurningShipIterations, xMin: -2.0, xMax: 1.2, yMin: -2.1, yMax: 1.2, rows: 40, cols: 80, maxIterations: 200) // CHECK: ################################################################################ // CHECK: ################################################################################ // CHECK: ################################################################################ // CHECK: #####################################################################*****###### // CHECK: ################################################################*******+...+*### // CHECK: #############################################################**********+...****# // CHECK: ###########################################################************. .+****# // CHECK: #########################################################***********++....+.**** // CHECK: ######################################################************+++......++*** // CHECK: ##############################*******************###************..... .....+++++ // CHECK: ########################*******+++*******************+ .+++++ . . ........+* // CHECK: ####################**********+.. .+++*******+.+++**+. .....+.+** // CHECK: #################**********++++...+...++ .. . . .+ ...+++++.*** // CHECK: ##############***********++..... . ... . ...++++++****# // CHECK: ############*************....... . . ...+++********# // CHECK: ##########***************. .. ...+++*********# // CHECK: #########***************++. .. . . ...+++*********## // CHECK: #######*****************. ... ...+++**********## // CHECK: ######*****************+. ...+++**********### // CHECK: #####****************+++ . .....++***********### // CHECK: #####**********++..... . ....+++***********### // CHECK: ####*********+++.. . ....+++***********#### // CHECK: ####********++++. ....+++***********#### // CHECK: ###*******++++. ...++++***********#### // CHECK: ###**++*+..+... ...+++************#### // CHECK: ### ...+++************#### // CHECK: ###*********+++++++++......... ...... ..++************#### // CHECK: ####****************++++++.................... .++***********##### // CHECK: #####********************++++++++++++++++........ .+***********##### // CHECK: ########****************************+++++++++....... ++***********##### // CHECK: ###########*******************************++++++...... ..++**********###### // CHECK: ###############*******************************+++++.........++++*********####### // CHECK: ####################****************************++++++++++++++**********######## // CHECK: ##########################*************************+++++++++***********######### // CHECK: ################################**************************************########## // CHECK: ####################################********************************############ // CHECK: ########################################***************************############# // CHECK: ###########################################**********************############### // CHECK: #############################################*****************################## // CHECK: ################################################***********#####################
8881fece11f81102d31c6fcd1888597f
56.654545
90
0.179018
false
false
false
false
xin-wo/kankan
refs/heads/master
kankan/kankan/Class/Home/Controller/JumpViewController.swift
mit
1
// // JumpViewController.swift // kankan // // Created by Xin on 16/11/8. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit import MJRefresh import Alamofire import Kingfisher class JumpViewController: UIViewController, WXCollectionViewProtocol,WXNavigationProtocol { // collectionView 懒加载 lazy var collectionView: UICollectionView = {[unowned self] in // 1.创建 layout let flowLayout = UICollectionViewFlowLayout() // flowLayout.itemSize = self.bounds.size flowLayout.minimumInteritemSpacing = 0 flowLayout.minimumLineSpacing = 0 flowLayout.scrollDirection = .Vertical // 2.创建 collectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y: 64, width: screenWidth, height: screenHeight - 64), collectionViewLayout: flowLayout) collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self // collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] collectionView.registerNib(UINib(nibName: "NormalCell", bundle: nil), forCellWithReuseIdentifier: "normal") collectionView.backgroundColor = UIColor.whiteColor() return collectionView }() //所有电影数据 var dataArray: [HomeAllModel] = [] //单个电影数据 var dataArray1: [HomeSingleModel] = [] var url = "" var currentPage = 1 override func viewDidLoad() { super.viewDidLoad() configUI() loadData() } func configUI() { self.automaticallyAdjustsScrollViewInsets = false self.view.addSubview(collectionView) addBarButton(imageName: "app_nav_back_normal", postion: .left, select: #selector(backAction)) //下拉刷新 addRefresh(collectionView, header: { [unowned self] in self.currentPage = 1 self.loadData() }) { [unowned self] in self.currentPage += 1 self.loadData() } } //加载所有数据 func loadData() { Alamofire.request(.GET, String(format: url, currentPage)).responseJSON { [unowned self] (response) in self.collectionView.mj_header.endRefreshing() self.collectionView.mj_footer.endRefreshing() if self.currentPage == 1 { self.dataArray.removeAll() } if response.result.error == nil { let array = (response.result.value as! NSDictionary)["data"]!["items"] as! [AnyObject] for dic in array { let model = HomeAllModel() model.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) self.dataArray.append(model) } } self.collectionView.reloadData() } } //返回上一个页面 func backAction() { self.navigationController?.popViewControllerAnimated(true) } //跳转web页面 func loadWeb(atIndaxPath indexPath: NSIndexPath) { if indexPath.section < dataArray.count { var webUrl: String = "" let movieId = "\(dataArray[indexPath.row].id)" let singleUrl = homeSingleJson + movieId Alamofire.request(.GET, singleUrl).responseJSON { [unowned self] (response) in if response.result.error == nil { // print((response.result.value as! NSDictionary)["data"] as! NSDictionary) if (response.result.value as! NSDictionary)["data"] != nil { let dic = (response.result.value as! NSDictionary)["data"]! as! NSDictionary let model = HomeSingleModel() model.setValuesForKeysWithDictionary(dic as! [String : AnyObject]) self.dataArray1.append(model) } } if self.dataArray1.count != 0 { let headerUrl = "http://vod.kankan.com/v/" let footerUrl = ".shtml" let remainder = self.dataArray1[0].id let smallUrl = self.dataArray1[0].screen_shot let impUrl = smallUrl.substringToIndex(smallUrl.startIndex.advancedBy(9)) webUrl = headerUrl+impUrl+remainder+footerUrl print(webUrl) self.dataArray1.removeAll() let webVC = WebViewController() webVC.urlString = webUrl webVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(webVC, animated: true) } } } } } //MARK: UICollectionView代理 extension JumpViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("normal", forIndexPath: indexPath) as! NormalCell let model = dataArray[indexPath.row] if model.label == "" { cell.descLabel.text = "正片" } else { cell.descLabel.text = model.label } cell.posterImage.kf_setImageWithURL(NSURL(string:"http://img.movie.kanimg.kankan.com/gallery"+model.poster), placeholderImage: UIImage(named: "default_poster_250_350"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.rankLabel.text = "\(model.score)" cell.titleLabel.text = model.title return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: (screenWidth-20)/3, height: (screenHeight-50)/3) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { //跳转web页面 loadWeb(atIndaxPath: indexPath) } }
a801f9f00c6d26432aadc9206a2e603a
32.990244
238
0.575918
false
false
false
false
boostcode/tori
refs/heads/master
Sources/tori/main.swift
apache-2.0
1
/** * Copyright boostco.de 2016 * * 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 // kitura import KituraSys import KituraNet import Kitura // mongodb orm import MongoKitten // logger import LoggerAPI import HeliumLogger Log.logger = HeliumLogger() #if os(Linux) import Glibc #endif // router setup let router = Router() // roles enum Role: Int { case Admin case Guest // add your extra roles here } // database setup let db = setupDb() setupTori() // MARK: - Start adding here your collections // get config let (_, _, _, toriPort, _, _) = getConfiguration() // setup server let server = HttpServer.listen( port: toriPort, delegate: router ) Log.debug("Tori is running at port \(toriPort)") Server.run()
976f4b3d3f2cddf6a00ee25ef87be83f
18.640625
74
0.719968
false
false
false
false
hankbao/socket.io-client-swift
refs/heads/master
SocketIOClientSwift/SocketIOClient.swift
apache-2.0
1
// // SocketIOClient.swift // Socket.IO-Swift // // Created by Erik Little on 11/23/14. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient { private lazy var params = [String: AnyObject]() private var anyHandler:((SocketAnyEvent) -> Void)? private var _closed = false private var _connected = false private var _connecting = false private var currentReconnectAttempt = 0 private var forcePolling = false private var forceWebsockets = false private var handlers = ContiguousArray<SocketEventHandler>() private var paramConnect = false private var _secure = false private var _sid:String? private var _reconnecting = false private var reconnectTimer:NSTimer? let reconnectAttempts:Int! let logType = "SocketClient" var ackHandlers = SocketAckManager() var currentAck = -1 var log = false var waitingData = ContiguousArray<SocketPacket>() var sessionDelegate:NSURLSessionDelegate? public let socketURL:String public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL) public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL) public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL) public var closed:Bool { return self._closed } public var connected:Bool { return self._connected } public var connecting:Bool { return self._connecting } public var cookies:[NSHTTPCookie]? public var engine:SocketEngine? public var nsp = "/" public var reconnects = true public var reconnecting:Bool { return self._reconnecting } public var reconnectWait = 10 public var secure:Bool { return self._secure } public var sid:String? { return self._sid } /** Create a new SocketIOClient. opts can be omitted */ public init(var socketURL:String, opts:NSDictionary? = nil) { if socketURL["https://"].matches().count != 0 { self._secure = true } socketURL = socketURL["http://"] ~= "" socketURL = socketURL["https://"] ~= "" self.socketURL = socketURL // Set options if opts != nil { if let sessionDelegate = opts!["sessionDelegate"] as? NSURLSessionDelegate { self.sessionDelegate = sessionDelegate } if let cookies = opts!["cookies"] as? [NSHTTPCookie] { self.cookies = cookies } if let log = opts!["log"] as? Bool { self.log = log } if let polling = opts!["forcePolling"] as? Bool { self.forcePolling = polling } if var nsp = opts!["nsp"] as? String { if nsp != "/" && nsp.hasPrefix("/") { nsp.removeAtIndex(nsp.startIndex) } self.nsp = nsp } if let reconnects = opts!["reconnects"] as? Bool { self.reconnects = reconnects } if let reconnectAttempts = opts!["reconnectAttempts"] as? Int { self.reconnectAttempts = reconnectAttempts } else { self.reconnectAttempts = -1 } if let reconnectWait = opts!["reconnectWait"] as? Int { self.reconnectWait = abs(reconnectWait) } if let ws = opts!["forceWebsockets"] as? Bool { self.forceWebsockets = ws } } else { self.reconnectAttempts = -1 } super.init() } public convenience init(socketURL:String, options:NSDictionary?) { self.init(socketURL: socketURL, opts: options) } deinit { SocketLogger.log("Client is being deinit", client: self) } private func addEngine() { SocketLogger.log("Adding engine", client: self) self.engine = SocketEngine(client: self, forcePolling: self.forcePolling, forceWebsockets: self.forceWebsockets, withCookies: self.cookies, logging: self.log, withSessionDelegate: self.sessionDelegate) } /** Closes the socket. Only reopen the same socket if you know what you're doing. Will turn off automatic reconnects. Pass true to fast if you're closing from a background task */ public func close(#fast:Bool) { SocketLogger.log("Closing socket", client: self) self.reconnects = false self._connecting = false self._connected = false self._reconnecting = false self.engine?.close(fast: fast) } /** Connect to the server. */ public func connect() { if self.closed { println("Warning! This socket was previously closed. This might be dangerous!") self._closed = false } if self.connected { return } self.addEngine() self.engine?.open() } /** Connect to the server with params that will be passed on connection. */ public func connectWithParams(params:[String: AnyObject]) { if self.closed { println("Warning! This socket was previously closed. This might be dangerous!") self._closed = false } if self.connected { return } self.params = params self.paramConnect = true self.addEngine() self.engine?.open(opts: params) } private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback { return {[weak self, ack = ++self.currentAck] timeout, callback in if self == nil { return } self?.ackHandlers.addAck(ack, callback: callback) dispatch_async(self!.emitQueue) { self?._emit(event, items, ack: ack) } if timeout != 0 { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { self?.ackHandlers.timeoutAck(ack) } } } } func didConnect() { SocketLogger.log("Socket connected", client: self) self._closed = false self._connected = true self._connecting = false self._reconnecting = false self.currentReconnectAttempt = 0 self.reconnectTimer?.invalidate() self.reconnectTimer = nil self._sid = self.engine?.sid // Don't handle as internal because something crazy could happen where // we disconnect before it's handled self.handleEvent("connect", data: nil, isInternalMessage: false) } /// error public func didError(reason:AnyObject) { SocketLogger.err("Error", client: self) self.handleEvent("error", data: reason as? [AnyObject] ?? [reason], isInternalMessage: true) } /** Same as close */ public func disconnect(#fast:Bool) { self.close(fast: fast) } /** Send a message to the server */ public func emit(event:String, _ items:AnyObject...) { if !self.connected { return } dispatch_async(self.emitQueue) {[weak self] in self?._emit(event, items) } } /** Same as emit, but meant for Objective-C */ public func emit(event:String, withItems items:[AnyObject]) { if !self.connected { return } dispatch_async(self.emitQueue) {[weak self] in self?._emit(event, items) } } /** Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add an ack. */ public func emitWithAck(event:String, _ items:AnyObject...) -> OnAckCallback { if !self.connected { return createOnAck(event, items: items) } return self.createOnAck(event, items: items) } /** Same as emitWithAck, but for Objective-C */ public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback { if !self.connected { return self.createOnAck(event, items: items) } return self.createOnAck(event, items: items) } private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) { if !self.connected { return } let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack) let str:String SocketParser.parseForEmit(packet) str = packet.createMessageForEvent(event) SocketLogger.log("Emitting: \(str)", client: self) if packet.type == SocketPacket.PacketType.BINARY_EVENT { self.engine?.send(str, withData: packet.binary) } else { self.engine?.send(str, withData: nil) } } // If the server wants to know that the client received data func emitAck(ack:Int, withData args:[AnyObject]) { dispatch_async(self.emitQueue) {[weak self] in if self == nil || !self!.connected { return } let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack) let str:String SocketParser.parseForEmit(packet) str = packet.createAck() SocketLogger.log("Emitting Ack: \(str)", client: self!) if packet.type == SocketPacket.PacketType.BINARY_ACK { self?.engine?.send(str, withData: packet.binary) } else { self?.engine?.send(str, withData: nil) } } } /// Server wants us to die public func engineDidForceClose(reason:String) { if self.closed { return } SocketLogger.log("Engine closed", client: self) self._closed = true self._connected = false self.reconnects = false self._connecting = false self._reconnecting = false self.handleEvent("disconnect", data: [reason], isInternalMessage: true) } // Called when the socket gets an ack for something it sent func handleAck(ack:Int, data:AnyObject?) { SocketLogger.log("Handling ack: \(ack) with data: \(data)", client: self) self.ackHandlers.executeAck(ack, items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil)) } /** Causes an event to be handled. Only use if you know what you're doing. */ public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false, wantsAck ack:Int? = nil) { // println("Should do event: \(event) with data: \(data)") if !self.connected && !isInternalMessage { return } SocketLogger.log("Handling event: \(event) with data: \(data)", client: self) if self.anyHandler != nil { dispatch_async(dispatch_get_main_queue()) {[weak self] in self?.anyHandler?(SocketAnyEvent(event: event, items: data)) } } for handler in self.handlers { if handler.event == event { if ack != nil { handler.executeCallback(data, withAck: ack!, withSocket: self) } else { handler.executeCallback(data) } } } } func joinNamespace() { SocketLogger.log("Joining namespace", client: self) if self.nsp != "/" { self.engine?.send("0/\(self.nsp)", withData: nil) } } /** Removes handler(s) */ public func off(event:String) { SocketLogger.log("Removing handler for event: \(event)", client: self) self.handlers = self.handlers.filter {$0.event == event ? false : true} } /** Adds a handler for an event. */ public func on(name:String, callback:NormalCallback) { SocketLogger.log("Adding handler for event: \(name)", client: self) let handler = SocketEventHandler(event: name, callback: callback) self.handlers.append(handler) } /** Adds a handler that will be called on every event. */ public func onAny(handler:(SocketAnyEvent) -> Void) { self.anyHandler = handler } /** Same as connect */ public func open() { self.connect() } public func parseSocketMessage(msg:String) { SocketParser.parseSocketMessage(msg, socket: self) } public func parseBinaryData(data:NSData) { SocketParser.parseBinaryData(data, socket: self) } // Something happened while polling public func pollingDidFail(err:String) { if !self.reconnecting { self._connected = false self.handleEvent("reconnect", data: [err], isInternalMessage: true) self.tryReconnect() } } // We lost connection and should attempt to reestablish func tryReconnect() { if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts { self.engineDidForceClose("Reconnect Failed") return } else if self.connected { self._connecting = false self._reconnecting = false return } if self.reconnectTimer == nil { SocketLogger.log("Starting reconnect", client: self) self._reconnecting = true dispatch_async(dispatch_get_main_queue()) {[weak self] in if self == nil { return } self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait), target: self!, selector: "tryReconnect", userInfo: nil, repeats: true) } } SocketLogger.log("Trying to reconnect", client: self) self.handleEvent("reconnectAttempt", data: [self.reconnectAttempts - self.currentReconnectAttempt], isInternalMessage: true) self.currentReconnectAttempt++ if self.paramConnect { self.connectWithParams(self.params) } else { self.connect() } } // Called when the socket is closed public func webSocketDidCloseWithCode(code:Int, reason:String) { self._connected = false self._connecting = false if self.closed || !self.reconnects { self.engineDidForceClose("WebSocket closed") } else if !self.reconnecting { self.handleEvent("reconnect", data: [reason], isInternalMessage: true) self.tryReconnect() } } // Called when an error occurs. public func webSocketDidFailWithError(error:NSError) { self._connected = false self._connecting = false self.handleEvent("error", data: [error.localizedDescription], isInternalMessage: true) if self.closed || !self.reconnects { self.engineDidForceClose("WebSocket closed with an error \(error)") } else if !self.reconnecting { self.handleEvent("reconnect", data: [error.localizedDescription], isInternalMessage: true) self.tryReconnect() } } }
b5caca2136bb381835ca9f32cd958a0b
31.406015
107
0.565462
false
false
false
false
mflint/ios-tldr-viewer
refs/heads/master
tldr-viewer/ListViewModel.swift
mit
1
// // ListViewModel.swift // tldr-viewer // // Created by Matthew Flint on 30/12/2015. // Copyright © 2015 Green Light. All rights reserved. // import Foundation import UIKit /* The list of commands is loaded by the `DataSource` class, and passes through a series of decorators before arriving at the ListViewModel: +------------+ | DataSource | +------+-----+ | +---------------+--------------+ | FilteringDataSourceDecorator | +---------------+--------------+ | +-----------------------------------+-----------------------------------+ | SwitchingDataSourceDecorator | | | | +------------------------------+ +------------------------------+ | | | SearchingDataSourceDecorator | | FavouriteDataSourceDecorator | | | +------------------------------+ +------------------------------+ | +-----------------------------------+-----------------------------------+ | +-------+-------+ | ListViewModel | +---------------+ `DataSource` loads the raw command data from the `Documents` directory. It can refresh data from the network if necessary. `FilteringDataSourceDecorator` filters the command data, removing commands that the user never wants to see. This might be due to their locale or their preferred platforms. `SwitchingDataSourceDecorator` is a type which can switch between multiple other decorators. Currently is has two, one for each of the segmented controls on the List Commands screen. `SearchableDataSourceDecorator` filters the Command list based on the user's search criteria. `FavouritesDataSourceDecorator` filters the Command list based on the user's favourite commands. */ class ListViewModel: NSObject { // no-op closures until the ViewController provides its own var updateSegmentSignal: () -> Void = {} var updateSignal: (_ indexPath: IndexPath?) -> Void = {(indexPath) in} var showDetail: (_ detailViewModel: DetailViewModel) -> Void = {(vm) in} var cancelSearchSignal: () -> Void = {} var canSearch: Bool { return DataSources.sharedInstance.switchingDataSource.isSearchable } var canRefresh: Bool { return DataSources.sharedInstance.switchingDataSource.isRefreshable } var lastUpdatedString: String { if let lastUpdateTime = DataSources.sharedInstance.baseDataSource.lastUpdateTime() { let lastUpdatedDateTime = dateFormatter.string(from: lastUpdateTime) return Localizations.CommandList.AllCommands.UpdatedDateTime(lastUpdatedDateTime) } return "" } var searchText: String { return DataSources.sharedInstance.searchingDataSource.searchText } let searchPlaceholder = Localizations.CommandList.AllCommands.SearchPlaceholder var itemSelected: Bool = false var requesting: Bool { return DataSources.sharedInstance.baseDataSource.requesting } // TODO: animate tableview contents when this changes // TODO: cache sectionViewModels for each selectable datasource, and only update when we get an update signal from that datasource var sectionViewModels = [SectionViewModel]() var sectionIndexes = [String]() var dataSourceNames: [String]! var detailVisible: Bool = false private let dataSource = DataSources.sharedInstance.switchingDataSource private let dateFormatter = DateFormatter() var selectedDataSourceIndex: Int { get { return DataSources.sharedInstance.switchingDataSource.selectedDataSourceIndex } set { let switcher = DataSources.sharedInstance.switchingDataSource switcher.selectedDataSourceIndex = newValue // update the selected datasource (segment control) in the UI updateSegmentSignal() } } private var cellViewModels = [BaseCellViewModel]() override init() { super.init() dataSource.add(delegate: self) dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short dataSourceNames = DataSources.sharedInstance.switchingDataSource.underlyingDataSources.map({ (switchable) -> String in return switchable.name }) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.externalCommandChange(notification:)), name: Constant.ExternalCommandChangeNotification.name, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.detailShown(notification:)), name: Constant.DetailViewPresence.shownNotificationName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.detailHidden(notification:)), name: Constant.DetailViewPresence.hiddenNotificationName, object: nil) DataSources.sharedInstance.baseDataSource.loadInitialCommands() } deinit { NotificationCenter.default.removeObserver(self) } @objc func externalCommandChange(notification: Notification) { guard let userInfo = notification.userInfo, let commandName = userInfo[Constant.ExternalCommandChangeNotification.commandNameKey] as? String, let command = DataSources.sharedInstance.baseDataSource.commandWith(name: commandName) else { return } showCommand(commandName: command.name) } @objc func detailShown(notification: Notification) { detailVisible = true } @objc func detailHidden(notification: Notification) { detailVisible = false } func refreshData() { DataSources.sharedInstance.baseDataSource.refresh() } private func update() { var vms = [BaseCellViewModel]() let commands = dataSource.commands if dataSource.isRefreshable { if requesting { let cellViewModel = LoadingCellViewModel() vms.append(cellViewModel) } let baseDataSource = DataSources.sharedInstance.baseDataSource if let errorText = baseDataSource.requestError { let cellViewModel = ErrorCellViewModel(errorText: errorText, buttonAction: { baseDataSource.refresh() }) vms.append(cellViewModel) } else if !requesting, let oldIndexCell = OldIndexCellViewModel.create() { vms.append(oldIndexCell) } } if commands.count == 0 { switch dataSource.selectedDataSourceType { case .all: if !DataSources.sharedInstance.searchingDataSource.searchText.isEmpty { // no search results let cellViewModel = NoResultsCellViewModel(searchTerm: searchText, buttonAction: { let url = URL(string: "https://github.com/tldr-pages/tldr/blob/master/CONTRIBUTING.md")! UIApplication.shared.open(url, options: [:], completionHandler: nil) }) vms.append(cellViewModel) } case .favourites: vms.append(NoFavouritesCellViewModel()) } } for command in commands { let cellViewModel = CommandCellViewModel(command: command, action: { let detailViewModel = DetailViewModel(command: command) self.showDetail(detailViewModel) }) vms.append(cellViewModel) } cellViewModels = vms makeSectionsAndCells() updateSignal(nil) } private func makeSectionsAndCells() { // all sections var sections = [SectionViewModel]() // current section var currentSection: SectionViewModel? for cellViewModel in cellViewModels { if currentSection == nil || !currentSection!.accept(cellViewModel: cellViewModel) { currentSection = SectionViewModel(firstCellViewModel: cellViewModel) sections.append(currentSection!) } } sectionViewModels = SectionViewModel.sort(sections: sections) sectionIndexes = sectionViewModels.map({ section in section.title }) } func didSelectRow(at indexPath: IndexPath) { selectRow(indexPath: indexPath) cancelSearchSignal() } private func selectRow(indexPath: IndexPath) { itemSelected = true sectionViewModels[indexPath.section].cellViewModels[indexPath.row].performAction() } func filterTextDidChange(text: String) { setFilter(text: text) } private func setFilter(text: String) { DataSources.sharedInstance.searchingDataSource.searchText = text } func filterCancel() { cancelSearchSignal() setFilter(text: "") } func showCommand(commandName: String) { // kill any search cancelSearchSignal() DataSources.sharedInstance.searchingDataSource.searchText = "" // now find the NSIndexPath for the CommandCellViewModel for this command name var indexPath: IndexPath? for (sectionIndex, sectionViewModel) in sectionViewModels.enumerated() { for (cellIndex, cellViewModel) in sectionViewModel.cellViewModels.enumerated() { if let commandCellViewModel = cellViewModel as? CommandCellViewModel { if commandCellViewModel.command.name == commandName { indexPath = IndexPath(row: cellIndex, section: sectionIndex) } } } } if let indexPath = indexPath { if (!detailVisible) { // this will trigger the segue. If detail already visible, the detail viewmodel will handle it selectRow(indexPath: indexPath) } updateSignal(indexPath) } } func showDetailWhenHorizontallyCompact() -> Bool { return itemSelected } } extension ListViewModel: DataSourceDelegate { func dataSourceDidUpdate(dataSource: DataSourcing) { update() } }
d12a27a7739b29a2e3b01681716f18fa
36.850174
193
0.58888
false
false
false
false
gusrsilva/Picture-Perfect-iOS
refs/heads/master
PicturePerfect/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // PicturePerfect // // Created by Gus Silva on 4/12/17. // Copyright © 2017 Gus Silva. All rights reserved. // import UIKit import CoreData import imglyKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if let licenseURL = Bundle.main.url(forResource: "photoedit_ios_license", withExtension: "") { PESDK.unlockWithLicense(at: licenseURL) } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "PicturePerfect") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
602614760054a7f419f6d9bb4f5e9aed
48.268041
285
0.685081
false
false
false
false
andyyhope/Elbbbird
refs/heads/master
Elbbbird/Model/User.swift
gpl-3.0
1
// // User.swift // Elbbbird // // Created by Andyy Hope on 16/03/2016. // Copyright © 2016 Andyy Hope. All rights reserved. // import Foundation import SwiftyJSON struct Links { let web: String let twitter: String init?(json: JSON) { self.web = json["web"].stringValue self.twitter = json["twitter"].stringValue } } struct User { let id: Int let username: String let name: String? let bio: String? let location: String? let avatarURL: String let htmlURL: String let followers: Count? let following: Count? let likes: Count? let projects: Count? let shots: Count? let teams: Count? init?(json: JSON) { self.id = json["id"].intValue self.username = json["username"].stringValue self.name = json["name"].stringValue self.bio = json["bio"].stringValue self.location = json["location"].stringValue self.avatarURL = json["avatar_url"].stringValue self.htmlURL = json["html_url"].stringValue self.followers = Count(url: json["followers_url"].stringValue, count: json["followers_count"].intValue) self.following = Count(url: json["following_url"].stringValue, count: json["following_count"].intValue) self.likes = Count(url: json["likes_url"].stringValue, count: json["likes_count"].intValue) self.projects = Count(url: json["projects_url"].stringValue, count: json["projects_count"].intValue) self.shots = Count(url: json["shots_url"].stringValue, count: json["shots_count"].intValue) self.teams = Count(url: json["teams_url"].stringValue, count: json["teams_count"].intValue) } }
712cf4c5420b490a66ce114751b3c65b
25.22973
70
0.558763
false
false
false
false
alaphao/gitstatus
refs/heads/master
GitStatus/GitStatus/GitButton2.swift
mit
1
// // GitButton2.swift // GitStatus // // Created by Aleph Retamal on 4/30/15. // Copyright (c) 2015 Guilherme Ferreira de Souza. All rights reserved. // import UIKit @IBDesignable class GitButton2: UIButton { var bgLayer: CAGradientLayer! let colorTop = UIColor(hex: "fcfcfc").CGColor let colorBottom = UIColor(hex: "eeeeee").CGColor override func drawRect(rect: CGRect) { if bgLayer == nil { bgLayer = CAGradientLayer() bgLayer.frame = self.bounds bgLayer.colors = [colorTop, colorBottom] bgLayer.locations = [0.0, 1.0] bgLayer.borderColor = UIColor(hex: "d5d5d5").CGColor bgLayer.borderWidth = 1 bgLayer.cornerRadius = 3 self.layer.insertSublayer(bgLayer, atIndex: 0) } } }
a84a4de1810198fac2083dc970f817b8
23.628571
72
0.586527
false
false
false
false
CryptoKitten/CryptoEssentials
refs/heads/master
Sources/BytesSequence.swift
mit
1
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. import Foundation public struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] public init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } public func makeIterator() -> AnyIterator<ArraySlice<UInt8>> { var offset:Int = 0 return AnyIterator { let end = Swift.min(self.chunkSize, self.data.count - offset) let result = self.data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } }
effa166e456cf14a5e2a53370fe34692
45.176471
216
0.704459
false
false
false
false
mattjgalloway/emoncms-ios
refs/heads/master
EmonCMSiOS/ViewModel/FeedChartViewModel.swift
mit
1
// // FeedChartViewModel.swift // EmonCMSiOS // // Created by Matt Galloway on 19/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RxSwift import RxCocoa final class FeedChartViewModel { private let account: Account private let api: EmonCMSAPI private let feedId: String // Inputs let active = Variable<Bool>(false) let dateRange: Variable<DateRange> let refresh = ReplaySubject<()>.create(bufferSize: 1) // Outputs private(set) var dataPoints: Driver<[DataPoint]> private(set) var isRefreshing: Driver<Bool> init(account: Account, api: EmonCMSAPI, feedId: String) { self.account = account self.api = api self.feedId = feedId self.dateRange = Variable<DateRange>(DateRange.relative(.hour8)) self.dataPoints = Driver.empty() let isRefreshing = ActivityIndicator() self.isRefreshing = isRefreshing.asDriver() let becameActive = self.active.asObservable() .filter { $0 == true } .distinctUntilChanged() .becomeVoid() let refreshSignal = Observable.of(self.refresh, becameActive) .merge() let dateRange = self.dateRange.asObservable() self.dataPoints = Observable.combineLatest(refreshSignal, dateRange) { $1 } .flatMapLatest { [weak self] dateRange -> Observable<[DataPoint]> in guard let strongSelf = self else { return Observable.empty() } let feedId = strongSelf.feedId let (startDate, endDate) = dateRange.calculateDates() let interval = Int(endDate.timeIntervalSince(startDate) / 500) return strongSelf.api.feedData(strongSelf.account, id: feedId, at: startDate, until: endDate, interval: interval) .catchErrorJustReturn([]) .trackActivity(isRefreshing) } .asDriver(onErrorJustReturn: []) } }
04725b253c5143543f86c252bfe1e369
26.727273
121
0.691257
false
false
false
false
safx/iOS9-InterApp-DnD-Demo
refs/heads/master
SampleX/Shape.swift
mit
1
// // Shape.swift // ios9-dnd-demo // // Created by Safx Developer on 2015/09/27. // // import UIKit enum Shape { case Rectangle(pos: CGPoint, size: CGSize, color: UIColor) case Ellipse(pos: CGPoint, size: CGSize, color: UIColor) static func createShape(type: String, size: CGSize, color: String) -> Shape? { let pos = CGPointMake(-10000, -10000) // FIXME let color = Shape.stringToColor(color: color) switch type { case "rectangle": return .Rectangle(pos: pos, size: size, color: color) case "ellipse": return .Ellipse (pos: pos, size: size, color: color) default: return nil } } mutating func changePosition(pos: CGPoint) { switch self { case .Rectangle(let (_, size, color)): self = .Rectangle(pos: pos, size: size, color: color) case .Ellipse(let (_, size, color)): self = .Ellipse(pos: pos, size: size, color: color) } } static func colorToString(color: UIColor) -> String { var c = [CGFloat](count: 4, repeatedValue: 0.0) color.getRed(&c[0], green: &c[1], blue: &c[2], alpha: &c[3]) return c[0...2].map{String(format:"%02X", Int(255 * $0))}.joinWithSeparator("") } static func stringToColor(color c: String) -> UIColor { precondition(c.characters.count == 6) let cs = [ c[Range(start: c.startIndex, end: c.startIndex.advancedBy(2))], c[Range(start: c.startIndex.advancedBy(2), end: c.startIndex.advancedBy(4))], c[Range(start: c.startIndex.advancedBy(4), end: c.startIndex.advancedBy(6))] ].flatMap{ Int($0, radix: 16) } assert(cs.count == 3) let z = cs.map{ CGFloat($0) } return UIColor(red: z[0], green: z[1], blue: z[2], alpha: CGFloat(1.0)) } var position: CGPoint { switch self { case .Rectangle(let (p, _, _)): return p case .Ellipse(let (p, _, _)): return p } } var string: String { switch self { case .Rectangle(let (_, s, c)): return "rectangle,\(Int(s.width)),\(Int(s.height)),\(Shape.colorToString(c))" case .Ellipse(let (_, s, c)): return "ellipse,\(Int(s.width)),\(Int(s.height)),\(Shape.colorToString(c))" } } } protocol Drawable { func draw() } extension Shape: Drawable { func draw() { color.setFill() path.fill() } private var color: UIColor { switch self { case .Rectangle(let (_, _, color)): return color case .Ellipse(let (_, _, color)): return color } } private var path: UIBezierPath { switch self { case .Rectangle(let (pos, size, _)): return UIBezierPath(rect: CGRect(origin: pos, size: size)) case .Ellipse(let (pos, size, _)): return UIBezierPath(ovalInRect: CGRect(origin: pos, size: size)) } } } extension Shape { func isClicked(pos: CGPoint) -> Bool { switch self { case .Rectangle(let (p, s, _)): let rect = CGRect(origin: p, size: s) return CGRectContainsPoint(rect, pos) case .Ellipse(let (p, s, _)): let rw = s.width / 2 let rh = s.height / 2 let c = CGPointMake(p.x + rw, p.y + rh) let x = pos.x - c.x let y = pos.y - c.y let w = rw * rw let h = rh * rh return (x * x) / w + (y * y) / h <= 1.0 } } }
140956a6d14ea79629097220c86ac067
30.468468
117
0.540796
false
false
false
false
JJMoon/MySwiftCheatSheet
refs/heads/master
LogTimerLogic/HtUtilTimers.swift
apache-2.0
1
// // HtUtilTimers.swift // heartisense // // Created by Jongwoo Moon on 2015. 10. 27.. // Copyright © 2015년 gyuchan. All rights reserved. // import Foundation class HtGenTimer : NSObject { var startTime = NSDate.timeIntervalSinceReferenceDate() var endTime = NSDate.timeIntervalSinceReferenceDate() var totalSec: Double { get { return endTime - startTime } } var timeSinceStart: Double { get { return NSDate.timeIntervalSinceReferenceDate() - startTime } } var timeSinceEnd: Double { get { return NSDate.timeIntervalSinceReferenceDate() - endTime } } func markStart() { startTime = NSDate.timeIntervalSinceReferenceDate() } func markEnd() { endTime = NSDate.timeIntervalSinceReferenceDate() } } class HtDelayTimer : NSObject { var defaultDelayTime = 0.1 var theTimer = NSTimer() var theAction: (Void)-> Void = { } func doAction() { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(defaultDelayTime * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), theAction) } func cancel() { theTimer.invalidate() } func setDelay(delay:Double, closure:()->()) { // 딜레이 함수.. theAction = closure theTimer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(HtDelayTimer.doAction), userInfo: nil, repeats: false) // 한번만 실행.. } } ////////////////////////////////////////////////////////////////////// _//////////_ [ Pause .. << >> ] _//////////_ // MARK: - Pause 용 타이머 class HtUnitJob : NSObject { var actTimeInSec:Double = 0 var theAction: (Void)-> Void = { } override init() { super.init() } convenience init(pTime: Double, pAct : ()->()) { self.init() self.actTimeInSec = pTime self.theAction = pAct } } class HtPauseCtrlTimer : HtStopWatch { var arrJobs = [HtUnitJob]() func resetJobs() { resetTime() arrJobs = [HtUnitJob]() } func addJob(pTime: Double, pAct : (Void)->Void) { let newJob = HtUnitJob(pTime: pTime, pAct: pAct) arrJobs.append(newJob) } func updateJob() { setDueTime() if arrJobs.count == 0 || dueTime < arrJobs[0].actTimeInSec { return } let curJob = arrJobs[0] curJob.theAction() arrJobs.removeAtIndex(0) } }
bb0805baed99446b2a8061c7ed9e351d
26.885057
129
0.584501
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/C29Scope.swift
mit
1
// // C29Scope // Copper // This is our work-horse class, holding the logic for all operations dealing with CopperRecords // and talking back to the network about them. // // Created by Doug Williams on 12/18/14. // Copyright (c) 2014 Doug Williams. All rights reserved. // @objc public enum C29Scope: Int { // We must use Ints because these are included in @objc protocols which don't support String backing stores // New and unset case Null = -1 // unset in API terms // Order and these numbers matter in two ways // First: they signify common groupings (see isMulti... and isDynamicRecord() below) // Second: they represent the preferred order of display on the Identity Sheet and Request Sheet // Multi entries -- records that can have 0-N of the same entries // enums can't have stored properties so we leave them here in comments for future reference // let MultiRawValueMin = 1000 // let MultiRawValueMax = 1999 case Name = 1000 case Picture = 1001 case Phone = 1002 case Email = 1003 case Username = 1004 case Address = 1005 case Birthday = 1006 case Signature = 1007 // Set entries case ContactsFavorites = 3001 private static let scopesWithKeys: [C29Scope: String] = [C29Scope.Address: "address", C29Scope.ContactsFavorites: "contacts", C29Scope.Email: "email", C29Scope.Name: "name", C29Scope.Phone: "phone", C29Scope.Picture: "picture", C29Scope.Username: "username", C29Scope.Birthday: "birthday", C29Scope.Signature: "signature"] public static let All = [C29Scope] (scopesWithKeys.keys) public static let DefaultScopes = [C29Scope.Name, C29Scope.Picture, C29Scope.Phone] public static func fromString(scope: String) -> C29Scope? { let keys = scopesWithKeys.filter { $1 == scope }.map { $0.0 } // note: returns an array if keys.count > 0 { return keys.first } return C29Scope?() } public var value: String? { return C29Scope.scopesWithKeys[self] } public var displayName : String { switch self { case .Address: return "Street Address".localized case .ContactsFavorites: return "Favorite People 👪".localized case .Email: return "Email Address".localized case .Name: return "Name".localized case .Phone: return "Phone Number".localized case .Picture: return "Picture".localized case .Username: return "Username".localized case .Birthday: return "Birthday".localized case .Signature: return "Signature".localized case .Null: return "null".localized } } public func sectionTitle(numberOfRecords: Int = 0) -> String { switch self { case .Address: if numberOfRecords < 2 { return "Shipping Address".localized.uppercaseString } else { return "Addresses".localized.uppercaseString } case .ContactsFavorites: return "Contacts".localized.uppercaseString case .Email: if numberOfRecords < 2 { return "Email".localized.uppercaseString } else { return "Emails".localized.uppercaseString } case .Name, .Picture: return "Profile".localized.uppercaseString case .Phone: if numberOfRecords < 2 { return "Number".localized.uppercaseString } else { return "Numbers".localized.uppercaseString } case .Username: return "Username".localized default: return self.displayName.uppercaseString } } public var addRecordString: String { switch self { case .Address: return "add new shipping address".localized case .Email: return "add new email".localized case .Phone: return "add new phone".localized case .Username: return "add your preferred username".localized case .Birthday: return "add your birthday".localized case .Signature: return "add your signature 👆🏾".localized default: return "We don't use addEntry for this scope 🦄" } } public func createRecord() -> CopperRecordObject? { switch self { case .Address: return CopperAddressRecord() case .ContactsFavorites: return CopperContactsRecord() case .Email: return CopperEmailRecord() case .Name: return CopperNameRecord() case .Phone: return CopperPhoneRecord() case .Picture: return CopperPictureRecord() case .Username: return CopperUsernameRecord() case .Birthday: return CopperDateRecord() case .Signature: return CopperSignatureRecord() default: return CopperRecordObject?() } } var dataKeys: [ScopeDataKeys] { switch self { case .Address: return [.AddressStreetOne, .AddressStreetTwo, .AddressCity, .AddressState, .AddressZip, .AddressCountry] case .ContactsFavorites: return [.ContactsContacts] case .Email: return [.EmailAddress] case .Name: return [.NameFirstName, .NameLastName] case .Phone: return [.PhoneNumber] case .Picture: return [.PictureImage, .PictureURL] case .Username: return [.Username] case .Birthday: return [.Date] case .Signature: return [.SignatureImage, .SignatureURL] case .Null: return [] } } public static func getCommaDelinatedString(fromScopes scopes: [C29Scope]?) -> String { guard let scopes = scopes else { return "" } var scopesStrings = [String]() for scopeString in scopes { scopesStrings.append(scopeString.value!) } return scopesStrings.joinWithSeparator(",") } // This is only used for SingleLineEditCell.swift, to set the perferredKeyboard for entry // this could potentially be much more robust for all types but for now we limit it to CopperMultiRecords. // For example, the AddressEditCell programmatically sets it's own, hard coded, since there is only (currently) one address type public var preferredKeyboard: UIKeyboardType? { switch self { case .Email: return .EmailAddress case .Phone: return .PhonePad default: return UIKeyboardType?() } } } enum ScopeDataKeys: String { // .Address case AddressStreetOne = "street_one" case AddressStreetTwo = "street_two" case AddressCity = "city" case AddressState = "state" case AddressZip = "zip" case AddressCountry = "country" // .Email case EmailAddress = "email" // .Contacts favorites case ContactsContacts = "contacts" // .Name case NameFirstName = "first_name" case NameLastName = "last_name" // .Phone case PhoneNumber = "phone_number" // .Picture case PictureImage = "picture" case PictureURL = "url" // .Username case Username = "username" // .Birthdate case Date = "date" // .Signature case SignatureImage = "image" case SignatureURL = "imageUrl" }
b248caaca3011600a4f61c025ee2117d
30.942387
132
0.590903
false
false
false
false
MaartenBrijker/project
refs/heads/back
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Band Pass Filter.xcplaygroundpage/Contents.swift
apache-2.0
2
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Band Pass Filter //: ### Band-pass filters allow audio above a specified frequency range and bandwidth to pass through to an output. The center frequency is the starting point from where the frequency limit is set. Adjusting the bandwidth sets how far out above and below the center frequency the frequency band should be. Anything above that band should pass through. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("mixloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true //: Next, we'll connect the audio sources to a band pass filter var bandPassFilter = AKBandPassFilter(player) //: Set the parameters of the band pass filter here bandPassFilter.centerFrequency = 5000 // Hz bandPassFilter.bandwidth = 600 // Cents AudioKit.output = bandPassFilter AudioKit.start() //: User Interface Set up class PlaygroundView: AKPlaygroundView { //: UI Elements we'll need to be able to access var centerFrequencyLabel: Label? var bandwidthLabel: Label? override func setup() { addTitle("Band Pass Filter") addLabel("Audio Player") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) addLabel("Band Pass Filter Parameters") addButton("Process", action: #selector(process)) addButton("Bypass", action: #selector(bypass)) centerFrequencyLabel = addLabel("Center Frequency: \(bandPassFilter.centerFrequency) Hz") addSlider(#selector(setCenterFrequency), value: bandPassFilter.centerFrequency, minimum: 20, maximum: 22050) bandwidthLabel = addLabel("Bandwidth \(bandPassFilter.bandwidth) Cents") addSlider(#selector(setBandwidth), value: bandPassFilter.bandwidth, minimum: 100, maximum: 12000) } //: Handle UI Events func start() { player.play() } func stop() { player.stop() } func process() { bandPassFilter.play() } func bypass() { bandPassFilter.bypass() } func setCenterFrequency(slider: Slider) { bandPassFilter.centerFrequency = Double(slider.value) let frequency = String(format: "%0.1f", bandPassFilter.centerFrequency) centerFrequencyLabel!.text = "Center Frequency: \(frequency) Hz" } func setBandwidth(slider: Slider) { bandPassFilter.bandwidth = Double(slider.value) let bandwidth = String(format: "%0.1f", bandPassFilter.bandwidth) bandwidthLabel!.text = "Bandwidth: \(bandwidth) Cents" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 550)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
d122bcfcb61a9c413dba0f033223b22a
32.261364
351
0.694909
false
false
false
false
appnexus/mobile-sdk-ios
refs/heads/master
examples/SimpleMediation/SimpleMediation/ANAdAdapterNativeAdMob.swift
apache-2.0
1
// // CustomAdapter.swift // SimpleMediation // // Created by System on 17/05/22. // Copyright © 2022 Xandr. All rights reserved. // import Foundation import AppNexusSDK import GoogleMobileAds @objc(ANAdAdapterNativeAdMob) public class ANAdAdapterNativeAdMob : NSObject , ANNativeCustomAdapter , GADNativeAdLoaderDelegate, GADNativeAdDelegate { var nativeAdLoader: GADAdLoader! var proxyViewController : ANProxyViewController! var nativeAd: GADNativeAd? override init() { super.init() // hasExpired = true proxyViewController = ANProxyViewController() } public func requestNativeAd( withServerParameter parameterString: String?, adUnitId: String?, targetingParameters: ANTargetingParameters? ) { nativeAdLoader = GADAdLoader( adUnitID: adUnitId!, rootViewController: proxyViewController as? UIViewController, adTypes: [GADAdLoaderAdType.native], options: []) nativeAdLoader.delegate = self nativeAdLoader.load(GADRequest()) } public var requestDelegate: ANNativeCustomAdapterRequestDelegate? // @nonobjc public var hasExpired: Bool? public var nativeAdDelegate: ANNativeCustomAdapterAdDelegate? public var expired: ObjCBool? public func hasExpired() -> DarwinBoolean{ return false } public func registerView(forImpressionTrackingAndClickHandling view: UIView, withRootViewController rvc: UIViewController, clickableViews: [Any]?) { print("registerView by Ab") // public func registerView(forImpressionTrackingAndClickHandling view: UIView, withRootViewController rvc: UIViewController, clickableViews: [Any]?) { proxyViewController.rootViewController = rvc proxyViewController.adView = view if (nativeAd != nil) { if view is GADNativeAdView { let nativeContentAdView = view as? GADNativeAdView nativeContentAdView?.nativeAd = nativeAd } return; } } public func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) { // self.hasExpired = false let response = ANNativeMediatedAdResponse( customAdapter: self, networkCode: ANNativeAdNetworkCode.adMob) nativeAd.delegate = self response?.title = nativeAd.headline response?.body = nativeAd.body response?.iconImageURL = nativeAd.icon?.imageURL response?.iconImageURL = nativeAd.icon?.imageURL response?.mainImageURL = (nativeAd.images?.first)?.imageURL response?.callToAction = nativeAd.callToAction response?.rating = ANNativeAdStarRating( value: CGFloat(nativeAd.starRating?.floatValue ?? 0.0), scale: Int(5.0)) response?.customElements = [ kANNativeElementObject: nativeAd ] requestDelegate?.didLoadNativeAd!(response!) } public func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) { requestDelegate?.didFail!(toLoadNativeAd: ANAdResponseCode.unable_TO_FILL()) } public func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) { // The native ad was shown. self.nativeAdDelegate?.adDidLogImpression!() } public func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) { // The native ad was clicked on. self.nativeAdDelegate?.adWasClicked!() } public func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) { // The native ad will present a full screen view. self.nativeAdDelegate?.didPresentAd!() } public func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) { // The native ad will dismiss a full screen view. self.nativeAdDelegate?.willCloseAd!() } public func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) { // The native ad did dismiss a full screen view. self.nativeAdDelegate?.didCloseAd!() } public func nativeAdWillLeaveApplication(_ nativeAd: GADNativeAd) { // The native ad will cause the application to become inactive and // open a new application. self.nativeAdDelegate?.willLeaveApplication!() } // public func hasExpired() -> Bool { // return true // } }
beccf933026b437058fe5ab50f687f4e
31.369565
154
0.659279
false
false
false
false
saitjr/STFakeLabel
refs/heads/master
Example/STFakeLabel-Swift/STFakeLabel-Swift/classes-Swift/STFakeLabel/STFakeAnimation.swift
mit
2
// // STFakeAnimation.swift // STFakeLabel-Swift // // Created by TangJR on 12/4/15. // Copyright © 2015 tangjr. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit /** STFakeAnimation is an Swift extension that adds fake 3D animation to UIlabel object class. It is intended to be simple, lightweight, and easy to use. Animate just need a single line of code 'st_startAnimation' method animate with direction and new text */ extension UILabel { enum STFakeAnimationDirection: Int { case Right = 1 ///< left to right case Left = -1 ///< right to left case Down = -2 ///< up to down case Up = 2 ///< down to up } func st_startAnimation(direction: STFakeAnimationDirection, toText: String!) { if st_isAnimatin! { return } st_isAnimatin = true let fakeLabel = UILabel() fakeLabel.frame = frame fakeLabel.text = toText fakeLabel.textAlignment = textAlignment fakeLabel.textColor = textColor fakeLabel.font = font fakeLabel.backgroundColor = backgroundColor != nil ? backgroundColor : UIColor.clearColor() self.superview!.addSubview(fakeLabel) var labelOffsetX: CGFloat = 0.0 var labelOffsetY: CGFloat = 0.0 var labelScaleX: CGFloat = 0.1 var labelScaleY: CGFloat = 0.1 if direction == .Down || direction == .Up { labelOffsetY = CGFloat(direction.rawValue) * CGRectGetHeight(self.bounds) / 4.0; labelScaleX = 1.0; } if direction == .Left || direction == .Right { labelOffsetX = CGFloat(direction.rawValue) * CGRectGetWidth(self.bounds) / 2.0; labelScaleY = 1.0; } fakeLabel.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(labelScaleX, labelScaleY), CGAffineTransformMakeTranslation(labelOffsetX, labelOffsetY)) UIView.animateWithDuration(Config.STFakeLabelAnimationDuration, animations: { () -> Void in fakeLabel.transform = CGAffineTransformIdentity self.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(labelScaleX, labelScaleY), CGAffineTransformMakeTranslation(-labelOffsetX, -labelOffsetY)) }) { (finish: Bool) -> Void in self.transform = CGAffineTransformIdentity self.text = toText fakeLabel.removeFromSuperview() self.st_isAnimatin = false } } // animation duration private struct Config { static var STFakeLabelAnimationDuration = 0.7 } // st_isAnimating asscoiate key private struct AssociatedKeys { static var STFakeLabelAnimationIsAnimatingKey = "STFakeLabelAnimationIsAnimatingKey" } // default is false private var st_isAnimatin: Bool? { get { let isAnimating = objc_getAssociatedObject(self, &AssociatedKeys.STFakeLabelAnimationIsAnimatingKey) as? Bool // if variable is not set, return false as default guard let _ = isAnimating else { return false } return isAnimating } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.STFakeLabelAnimationIsAnimatingKey, newValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
27cd548737d2b38af000832492709758
39.371681
170
0.656216
false
false
false
false
tbaranes/VersionTrackerSwift
refs/heads/master
VersionTracker Example/tvOS Example/ViewController.swift
mit
1
// // ViewController.swift // VersionTracker Demo tvOS // // Created by Tom Baranes on 18/02/16. // Copyright © 2016 Tom Baranes. All rights reserved. // import UIKit import VersionTracker class ViewController: UIViewController { // MARK: - Properties @IBOutlet weak var labelIsFirstLaunchEver: UILabel! @IBOutlet weak var labelIsFirstVersionLaunch: UILabel! @IBOutlet weak var labelIsFirstBuildLaunch: UILabel! @IBOutlet weak var labelVersionHistory: UILabel! @IBOutlet weak var labelBuildHistory: UILabel! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() VersionTracker.shared.track() labelVersionHistory.text = "Versions history: " + VersionTracker.shared.versionHistory.description labelBuildHistory.text = "Builds history: " + VersionTracker.shared.buildHistory.description labelIsFirstLaunchEver.text = "Is first launch ever: \(VersionTracker.shared.isFirstLaunchEver)" labelIsFirstVersionLaunch.text = "Is first version launch: \(VersionTracker.shared.isFirstVersionLaunch)" labelIsFirstBuildLaunch.text = "Is first build launch: \(VersionTracker.shared.isFirstBuildLaunch)" } }
51d89a28c65184a13486631959f15c35
33.771429
113
0.733772
false
false
false
false
apple/swift-syntax
refs/heads/main
Sources/SwiftParserDiagnostics/Utils.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { /// Remove any leading or trailing spaces. /// This is necessary to avoid depending SwiftParser on Foundation. func trimmingWhitespace() -> String { let charactersToDrop: [Character] = [" ", "\t", "\n", "\r"] var result: Substring = Substring(self) result = result.drop(while: { charactersToDrop.contains($0) }) while let lastCharacter = result.last, charactersToDrop.contains(lastCharacter) { result = result.dropLast(1) } return String(result) } func withFirstLetterUppercased() -> String { if let firstLetter = self.first { return firstLetter.uppercased() + self.dropFirst() } else { return self } } } extension Collection { /// If the collection contains a single element, return it, otherwise `nil`. var only: Element? { if !isEmpty && index(after: startIndex) == endIndex { return self.first! } else { return nil } } }
208a0991b97e528a3fef1c25c0804379
32.227273
85
0.601231
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPosix/Bootstrap.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore #if os(Windows) import ucrt import func WinSDK.GetFileType import let WinSDK.FILE_TYPE_PIPE import let WinSDK.INVALID_HANDLE_VALUE import struct WinSDK.DWORD import struct WinSDK.HANDLE #endif #if swift(>=5.7) /// The type of all `channelInitializer` callbacks. internal typealias ChannelInitializerCallback = @Sendable (Channel) -> EventLoopFuture<Void> #else /// The type of all `channelInitializer` callbacks. internal typealias ChannelInitializerCallback = (Channel) -> EventLoopFuture<Void> #endif /// Common functionality for all NIO on sockets bootstraps. internal enum NIOOnSocketsBootstraps { internal static func isCompatible(group: EventLoopGroup) -> Bool { return group is SelectableEventLoop || group is MultiThreadedEventLoopGroup } } /// A `ServerBootstrap` is an easy way to bootstrap a `ServerSocketChannel` when creating network servers. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = ServerBootstrap(group: group) /// // Specify backlog and enable SO_REUSEADDR for the server itself /// .serverChannelOption(ChannelOptions.backlog, value: 256) /// .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// /// // Set the handlers that are applied to the accepted child `Channel`s. /// .childChannelInitializer { channel in /// // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. /// channel.pipeline.addHandler(BackPressureHandler()).flatMap { () in /// // make sure to instantiate your `ChannelHandlers` inside of /// // the closure as it will be invoked once per connection. /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// } /// /// // Enable SO_REUSEADDR for the accepted Channels /// .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16) /// .childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator()) /// let channel = try! bootstrap.bind(host: host, port: port).wait() /// /* the server will now be accepting connections */ /// /// try! channel.closeFuture.wait() // wait forever as we never close the Channel /// ``` /// /// The `EventLoopFuture` returned by `bind` will fire with a `ServerSocketChannel`. This is the channel that owns the listening socket. /// Each time it accepts a new connection it will fire a `SocketChannel` through the `ChannelPipeline` via `fireChannelRead`: as a result, /// the `ServerSocketChannel` operates on `Channel`s as inbound messages. Outbound messages are not supported on a `ServerSocketChannel` /// which means that each write attempt will fail. /// /// Accepted `SocketChannel`s operate on `ByteBuffer` as inbound data, and `IOData` as outbound data. public final class ServerBootstrap { private let group: EventLoopGroup private let childGroup: EventLoopGroup private var serverChannelInit: Optional<ChannelInitializerCallback> private var childChannelInit: Optional<ChannelInitializerCallback> @usableFromInline internal var _serverChannelOptions: ChannelOptions.Storage @usableFromInline internal var _childChannelOptions: ChannelOptions.Storage private var enableMPTCP: Bool /// Create a `ServerBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ServerBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group, childGroup: group)! } /// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`. /// /// The `EventLoopGroup`s `group` and `childGroup` must be compatible, otherwise the program will crash. /// `ServerBootstrap` is compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. /// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on. public convenience init(group: EventLoopGroup, childGroup: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else { preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with group: \(group) and " + "childGroup: \(childGroup) at least one of which is incompatible.") } self.init(validatingGroup: group, childGroup: childGroup)! } /// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`, validating /// that the `EventLoopGroup`s are compatible with `ServerBootstrap`. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. /// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on. If `nil`, `group` is used. public init?(validatingGroup group: EventLoopGroup, childGroup: EventLoopGroup? = nil) { let childGroup = childGroup ?? group guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else { return nil } self.group = group self.childGroup = childGroup self._serverChannelOptions = ChannelOptions.Storage() self._childChannelOptions = ChannelOptions.Storage() self.serverChannelInit = nil self.childChannelInit = nil self._serverChannelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1) self.enableMPTCP = false } #if swift(>=5.7) /// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The `ServerSocketChannel` uses the accepted `Channel`s as inbound messages. /// /// - note: To set the initializer for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelInitializer`. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. @preconcurrency public func serverChannelInitializer(_ initializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.serverChannelInit = initializer return self } #else /// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The `ServerSocketChannel` uses the accepted `Channel`s as inbound messages. /// /// - note: To set the initializer for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelInitializer`. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. public func serverChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.serverChannelInit = initializer return self } #endif #if swift(>=5.7) /// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. Note that if the `initializer` fails then the error will be /// fired in the *parent* channel. /// /// - warning: The `initializer` will be invoked once for every accepted connection. Therefore it's usually the /// right choice to instantiate stateful `ChannelHandler`s within the closure to make sure they are not /// accidentally shared across `Channel`s. There are expert use-cases where stateful handler need to be /// shared across `Channel`s in which case the user is responsible to synchronise the state access /// appropriately. /// /// The accepted `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. @preconcurrency public func childChannelInitializer(_ initializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.childChannelInit = initializer return self } #else /// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. Note that if the `initializer` fails then the error will be /// fired in the *parent* channel. /// /// - warning: The `initializer` will be invoked once for every accepted connection. Therefore it's usually the /// right choice to instantiate stateful `ChannelHandler`s within the closure to make sure they are not /// accidentally shared across `Channel`s. There are expert use-cases where stateful handler need to be /// shared across `Channel`s in which case the user is responsible to synchronise the state access /// appropriately. /// /// The accepted `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. public func childChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.childChannelInit = initializer return self } #endif /// Specifies a `ChannelOption` to be applied to the `ServerSocketChannel`. /// /// - note: To specify options for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelOption`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func serverChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._serverChannelOptions.append(key: option, value: value) return self } /// Specifies a `ChannelOption` to be applied to the accepted `SocketChannel`s. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func childChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._childChannelOptions.append(key: option, value: value) return self } /// Specifies a timeout to apply to a bind attempt. Currently unsupported. /// /// - parameters: /// - timeout: The timeout that will apply to the bind attempt. public func bindTimeout(_ timeout: TimeAmount) -> Self { return self } /// Enables multi-path TCP support. /// /// This option is only supported on some systems, and will lead to bind /// failing if the system does not support it. Users are recommended to /// only enable this in response to configuration or feature detection. /// /// > Note: Enabling this setting will re-enable Nagle's algorithm, even if it /// > had been disabled. This is a temporary workaround for a Linux kernel /// > limitation. /// /// - parameters: /// - value: Whether to enable MPTCP or not. public func enableMPTCP(_ value: Bool) -> Self { self.enableMPTCP = value // This is a temporary workaround until we get some stable Linux kernel // versions that support TCP_NODELAY and MPTCP. if value { self._serverChannelOptions.remove(key: ChannelOptions.tcpOption(.tcp_nodelay)) } return self } /// Bind the `ServerSocketChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to bind on. /// - port: The port to bind on. public func bind(host: String, port: Int) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Bind the `ServerSocketChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> { return bind0 { address } } /// Bind the `ServerSocketChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system. public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return bind0 { try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } /// Bind the `ServerSocketChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system. /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`. public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> { if cleanupExistingSocketFile { do { try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) } catch { return group.next().makeFailedFuture(error) } } return self.bind(unixDomainSocketPath: unixDomainSocketPath) } #if !os(Windows) /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound stream socket. @available(*, deprecated, renamed: "withBoundSocket(_:)") public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return withBoundSocket(descriptor) } #endif /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound stream socket. public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel { if enableMPTCP { throw ChannelError.operationUnsupported } return try ServerSocketChannel(socket: socket, eventLoop: eventLoop, group: childEventLoopGroup) } return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in let promise = eventLoop.makePromise(of: Void.self) serverChannel.registerAlreadyConfigured0(promise: promise) return promise.futureResult } } private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel { return try ServerSocketChannel(eventLoop: eventLoop, group: childEventLoopGroup, protocolFamily: address.protocol, enableMPTCP: enableMPTCP) } return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in serverChannel.registerAndDoSynchronously { serverChannel in serverChannel.bind(to: address) } } } private func bind0(makeServerChannel: (_ eventLoop: SelectableEventLoop, _ childGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel, _ register: @escaping (EventLoop, ServerSocketChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let eventLoop = self.group.next() let childEventLoopGroup = self.childGroup let serverChannelOptions = self._serverChannelOptions let serverChannelInit = self.serverChannelInit ?? { _ in eventLoop.makeSucceededFuture(()) } let childChannelInit = self.childChannelInit let childChannelOptions = self._childChannelOptions let serverChannel: ServerSocketChannel do { serverChannel = try makeServerChannel(eventLoop as! SelectableEventLoop, childEventLoopGroup, self.enableMPTCP) } catch { return eventLoop.makeFailedFuture(error) } return eventLoop.submit { serverChannelOptions.applyAllChannelOptions(to: serverChannel).flatMap { serverChannelInit(serverChannel) }.flatMap { serverChannel.pipeline.addHandler(AcceptHandler(childChannelInitializer: childChannelInit, childChannelOptions: childChannelOptions), name: "AcceptHandler") }.flatMap { register(eventLoop, serverChannel) }.map { serverChannel as Channel }.flatMapError { error in serverChannel.close0(error: error, mode: .all, promise: nil) return eventLoop.makeFailedFuture(error) } }.flatMap { $0 } } private class AcceptHandler: ChannelInboundHandler { public typealias InboundIn = SocketChannel private let childChannelInit: ((Channel) -> EventLoopFuture<Void>)? private let childChannelOptions: ChannelOptions.Storage init(childChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?, childChannelOptions: ChannelOptions.Storage) { self.childChannelInit = childChannelInitializer self.childChannelOptions = childChannelOptions } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event is ChannelShouldQuiesceEvent { context.channel.close().whenFailure { error in context.fireErrorCaught(error) } } context.fireUserInboundEventTriggered(event) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { let accepted = self.unwrapInboundIn(data) let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } @inline(__always) func setupChildChannel() -> EventLoopFuture<Void> { return self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture<Void> in childEventLoop.assertInEventLoop() return childChannelInit(accepted) } } @inline(__always) func fireThroughPipeline(_ future: EventLoopFuture<Void>) { ctxEventLoop.assertInEventLoop() future.flatMap { (_) -> EventLoopFuture<Void> in ctxEventLoop.assertInEventLoop() guard context.channel.isActive else { return context.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) } context.fireChannelRead(data) return context.eventLoop.makeSucceededFuture(()) }.whenFailure { error in ctxEventLoop.assertInEventLoop() self.closeAndFire(context: context, accepted: accepted, err: error) } } if childEventLoop === ctxEventLoop { fireThroughPipeline(setupChildChannel()) } else { fireThroughPipeline(childEventLoop.flatSubmit { return setupChildChannel() }.hop(to: ctxEventLoop)) } } private func closeAndFire(context: ChannelHandlerContext, accepted: SocketChannel, err: Error) { accepted.close(promise: nil) if context.eventLoop.inEventLoop { context.fireErrorCaught(err) } else { context.eventLoop.execute { context.fireErrorCaught(err) } } } } } #if swift(>=5.6) @available(*, unavailable) extension ServerBootstrap: Sendable {} #endif private extension Channel { func registerAndDoSynchronously(_ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> { // this is pretty delicate at the moment: // In many cases `body` must be _synchronously_ follow `register`, otherwise in our current // implementation, `epoll` will send us `EPOLLHUP`. To have it run synchronously, we need to invoke the // `flatMap` on the eventloop that the `register` will succeed on. self.eventLoop.assertInEventLoop() return self.register().flatMap { self.eventLoop.assertInEventLoop() return body(self) } } } /// A `ClientBootstrap` is an easy way to bootstrap a `SocketChannel` when creating network clients. /// /// Usually you re-use a `ClientBootstrap` once you set it up and called `connect` multiple times on it. /// This way you ensure that the same `EventLoop`s will be shared across all your connections. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = ClientBootstrap(group: group) /// // Enable SO_REUSEADDR. /// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .channelInitializer { channel in /// // always instantiate the handler _within_ the closure as /// // it may be called multiple times (for example if the hostname /// // resolves to both IPv4 and IPv6 addresses, cf. Happy Eyeballs). /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// try! bootstrap.connect(host: "example.org", port: 12345).wait() /// /* the Channel is now connected */ /// ``` /// /// The connected `SocketChannel` will operate on `ByteBuffer` as inbound and on `IOData` as outbound messages. public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { private let group: EventLoopGroup #if swift(>=5.7) private var protocolHandlers: Optional<@Sendable () -> [ChannelHandler]> #else private var protocolHandlers: Optional<() -> [ChannelHandler]> #endif private var _channelInitializer: ChannelInitializerCallback private var channelInitializer: ChannelInitializerCallback { if let protocolHandlers = self.protocolHandlers { let channelInitializer = _channelInitializer return { channel in channelInitializer(channel).flatMap { channel.pipeline.addHandlers(protocolHandlers(), position: .first) } } } else { return self._channelInitializer } } @usableFromInline internal var _channelOptions: ChannelOptions.Storage private var connectTimeout: TimeAmount = TimeAmount.seconds(10) private var resolver: Optional<Resolver> private var bindTarget: Optional<SocketAddress> private var enableMPTCP: Bool /// Create a `ClientBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ClientBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("ClientBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `ClientBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self.group = group self._channelOptions = ChannelOptions.Storage() self._channelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1) self._channelInitializer = { channel in channel.eventLoop.makeSucceededFuture(()) } self.protocolHandlers = nil self.resolver = nil self.bindTarget = nil self.enableMPTCP = false } #if swift(>=5.7) /// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - warning: The `handler` closure may be invoked _multiple times_ so it's usually the right choice to instantiate /// `ChannelHandler`s within `handler`. The reason `handler` may be invoked multiple times is that to /// successfully set up a connection multiple connections might be setup in the process. Assuming a /// hostname that resolves to both IPv4 and IPv6 addresses, NIO will follow /// [_Happy Eyeballs_](https://en.wikipedia.org/wiki/Happy_Eyeballs) and race both an IPv4 and an IPv6 /// connection. It is possible that both connections get fully established before the IPv4 connection /// will be closed again because the IPv6 connection 'won the race'. Therefore the `channelInitializer` /// might be called multiple times and it's important not to share stateful `ChannelHandler`s in more /// than one `Channel`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self._channelInitializer = handler return self } #else /// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - warning: The `handler` closure may be invoked _multiple times_ so it's usually the right choice to instantiate /// `ChannelHandler`s within `handler`. The reason `handler` may be invoked multiple times is that to /// successfully set up a connection multiple connections might be setup in the process. Assuming a /// hostname that resolves to both IPv4 and IPv6 addresses, NIO will follow /// [_Happy Eyeballs_](https://en.wikipedia.org/wiki/Happy_Eyeballs) and race both an IPv4 and an IPv6 /// connection. It is possible that both connections get fully established before the IPv4 connection /// will be closed again because the IPv6 connection 'won the race'. Therefore the `channelInitializer` /// might be called multiple times and it's important not to share stateful `ChannelHandler`s in more /// than one `Channel`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self._channelInitializer = handler return self } #endif #if swift(>=5.7) /// Sets the protocol handlers that will be added to the front of the `ChannelPipeline` right after the /// `channelInitializer` has been called. /// /// Per bootstrap, you can only set the `protocolHandlers` once. Typically, `protocolHandlers` are used for the TLS /// implementation. Most notably, `NIOClientTCPBootstrap`, NIO's "universal bootstrap" abstraction, uses /// `protocolHandlers` to add the required `ChannelHandler`s for many TLS implementations. @preconcurrency public func protocolHandlers(_ handlers: @escaping @Sendable () -> [ChannelHandler]) -> Self { precondition(self.protocolHandlers == nil, "protocol handlers can only be set once") self.protocolHandlers = handlers return self } #else /// Sets the protocol handlers that will be added to the front of the `ChannelPipeline` right after the /// `channelInitializer` has been called. /// /// Per bootstrap, you can only set the `protocolHandlers` once. Typically, `protocolHandlers` are used for the TLS /// implementation. Most notably, `NIOClientTCPBootstrap`, NIO's "universal bootstrap" abstraction, uses /// `protocolHandlers` to add the required `ChannelHandler`s for many TLS implementations. public func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self { precondition(self.protocolHandlers == nil, "protocol handlers can only be set once") self.protocolHandlers = handlers return self } #endif /// Specifies a `ChannelOption` to be applied to the `SocketChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } /// Specifies a timeout to apply to a connection attempt. /// /// - parameters: /// - timeout: The timeout that will apply to the connection attempt. public func connectTimeout(_ timeout: TimeAmount) -> Self { self.connectTimeout = timeout return self } /// Specifies the `Resolver` to use or `nil` if the default should be used. /// /// - parameters: /// - resolver: The resolver that will be used during the connection attempt. public func resolver(_ resolver: Resolver?) -> Self { self.resolver = resolver return self } /// Enables multi-path TCP support. /// /// This option is only supported on some systems, and will lead to bind /// failing if the system does not support it. Users are recommended to /// only enable this in response to configuration or feature detection. /// /// > Note: Enabling this setting will re-enable Nagle's algorithm, even if it /// > had been disabled. This is a temporary workaround for a Linux kernel /// > limitation. /// /// - parameters: /// - value: Whether to enable MPTCP or not. public func enableMPTCP(_ value: Bool) -> Self { self.enableMPTCP = value // This is a temporary workaround until we get some stable Linux kernel // versions that support TCP_NODELAY and MPTCP. if value { self._channelOptions.remove(key: ChannelOptions.tcpOption(.tcp_nodelay)) } return self } /// Bind the `SocketChannel` to `address`. /// /// Using `bind` is not necessary unless you need the local address to be bound to a specific address. /// /// - note: Using `bind` will disable Happy Eyeballs on this `Channel`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> ClientBootstrap { self.bindTarget = address return self } func makeSocketChannel(eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily) throws -> SocketChannel { return try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily, enableMPTCP: self.enableMPTCP) } /// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established. /// /// - parameters: /// - host: The host to connect to. /// - port: The port to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(host: String, port: Int) -> EventLoopFuture<Channel> { let loop = self.group.next() let resolver = self.resolver ?? GetaddrinfoResolver(loop: loop, aiSocktype: .stream, aiProtocol: .tcp) let connector = HappyEyeballsConnector(resolver: resolver, loop: loop, host: host, port: port, connectTimeout: self.connectTimeout) { eventLoop, protocolFamily in return self.initializeAndRegisterNewChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) { $0.eventLoop.makeSucceededFuture(()) } } return connector.resolveAndConnect() } private func connect(freshChannel channel: Channel, address: SocketAddress) -> EventLoopFuture<Void> { let connectPromise = channel.eventLoop.makePromise(of: Void.self) channel.connect(to: address, promise: connectPromise) let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) { connectPromise.fail(ChannelError.connectTimeout(self.connectTimeout)) channel.close(promise: nil) } connectPromise.futureResult.whenComplete { (_: Result<Void, Error>) in cancelTask.cancel() } return connectPromise.futureResult } internal func testOnly_connect(injectedChannel: SocketChannel, to address: SocketAddress) -> EventLoopFuture<Channel> { return self.initializeAndRegisterChannel(injectedChannel) { channel in return self.connect(freshChannel: channel, address: address) } } /// Specify the `address` to connect to for the TCP `Channel` that will be established. /// /// - parameters: /// - address: The address to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { return self.initializeAndRegisterNewChannel(eventLoop: self.group.next(), protocolFamily: address.protocol) { channel in return self.connect(freshChannel: channel, address: address) } } /// Specify the `unixDomainSocket` path to connect to for the UDS `Channel` that will be established. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { do { let address = try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) return self.connect(to: address) } catch { return self.group.next().makeFailedFuture(error) } } #if !os(Windows) /// Use the existing connected socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the connected stream socket. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. @available(*, deprecated, renamed: "withConnectedSocket(_:)") public func withConnectedSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return self.withConnectedSocket(descriptor) } #endif /// Use the existing connected socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the connected stream socket. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { let eventLoop = group.next() let channelInitializer = self.channelInitializer let channel: SocketChannel do { channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, socket: socket) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return self._channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } private func initializeAndRegisterNewChannel(eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, _ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let channel: SocketChannel do { channel = try self.makeSocketChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) } catch { return eventLoop.makeFailedFuture(error) } return self.initializeAndRegisterChannel(channel, body) } private func initializeAndRegisterChannel(_ channel: SocketChannel, _ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let channelInitializer = self.channelInitializer let channelOptions = self._channelOptions let eventLoop = channel.eventLoop @inline(__always) func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { if let bindTarget = self.bindTarget { return channel.bind(to: bindTarget).flatMap { channelInitializer(channel) } } else { return channelInitializer(channel) } }.flatMap { eventLoop.assertInEventLoop() return channel.registerAndDoSynchronously(body) }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension ClientBootstrap: Sendable {} #endif /// A `DatagramBootstrap` is an easy way to bootstrap a `DatagramChannel` when creating datagram clients /// and servers. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = DatagramBootstrap(group: group) /// // Enable SO_REUSEADDR. /// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .channelInitializer { channel in /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// let channel = try! bootstrap.bind(host: "127.0.0.1", port: 53).wait() /// /* the Channel is now ready to send/receive datagrams */ /// /// try channel.closeFuture.wait() // Wait until the channel un-binds. /// ``` /// /// The `DatagramChannel` will operate on `AddressedEnvelope<ByteBuffer>` as inbound and outbound messages. public final class DatagramBootstrap { private let group: EventLoopGroup private var channelInitializer: Optional<ChannelInitializerCallback> @usableFromInline internal var _channelOptions: ChannelOptions.Storage /// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `DatagramBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("DatagramBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self._channelOptions = ChannelOptions.Storage() self.group = group self.channelInitializer = nil } #if swift(>=5.7) /// Initialize the bound `DatagramChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #else /// Initialize the bound `DatagramChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #endif /// Specifies a `ChannelOption` to be applied to the `DatagramChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } #if !os(Windows) /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound datagram socket. @available(*, deprecated, renamed: "withBoundSocket(_:)") public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return self.withBoundSocket(descriptor) } #endif /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound datagram socket. public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, socket: socket) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult } } /// Bind the `DatagramChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to bind on. /// - port: The port to bind on. public func bind(host: String, port: Int) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Bind the `DatagramChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> { return bind0 { address } } /// Bind the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system. public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } /// Bind the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system. /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`. public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> { if cleanupExistingSocketFile { do { try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) } catch { return group.next().makeFailedFuture(error) } } return self.bind(unixDomainSocketPath: unixDomainSocketPath) } private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, protocolFamily: address.protocol, protocolSubtype: .default) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in channel.register().flatMap { channel.bind(to: address) } } } /// Connect the `DatagramChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to connect to. /// - port: The port to connect to. public func connect(host: String, port: Int) -> EventLoopFuture<Channel> { return connect0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Connect the `DatagramChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to connect to. public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { return connect0 { address } } /// Connect the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to connect to. `path` must not exist, it will be created by the system. public func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return connect0 { return try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } private func connect0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, protocolFamily: address.protocol, protocolSubtype: .default) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in channel.register().flatMap { channel.connect(to: address) } } } private func withNewChannel(makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, _ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let eventLoop = self.group.next() let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } let channelOptions = self._channelOptions let channel: DatagramChannel do { channel = try makeChannel(eventLoop as! SelectableEventLoop) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() return bringup(eventLoop, channel) }.map { channel }.flatMapError { error in eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension DatagramBootstrap: Sendable {} #endif /// A `NIOPipeBootstrap` is an easy way to bootstrap a `PipeChannel` which uses two (uni-directional) UNIX pipes /// and makes a `Channel` out of them. /// /// Example bootstrapping a `Channel` using `stdin` and `stdout`: /// /// let channel = try NIOPipeBootstrap(group: group) /// .channelInitializer { channel in /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// .withPipes(inputDescriptor: STDIN_FILENO, outputDescriptor: STDOUT_FILENO) /// public final class NIOPipeBootstrap { private let group: EventLoopGroup private var channelInitializer: Optional<ChannelInitializerCallback> @usableFromInline internal var _channelOptions: ChannelOptions.Storage /// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `NIOPipeBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("NIOPipeBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self._channelOptions = ChannelOptions.Storage() self.group = group self.channelInitializer = nil } #if swift(>=5.7) /// Initialize the connected `PipeChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and outbound messages. Please note that /// `IOData.fileRegion` is _not_ supported for `PipeChannel`s because `sendfile` only works on sockets. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #else /// Initialize the connected `PipeChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and outbound messages. Please note that /// `IOData.fileRegion` is _not_ supported for `PipeChannel`s because `sendfile` only works on sockets. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #endif /// Specifies a `ChannelOption` to be applied to the `PipeChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } private func validateFileDescriptorIsNotAFile(_ descriptor: CInt) throws { #if os(Windows) // NOTE: this is a *non-owning* handle, do *NOT* call `CloseHandle` let hFile: HANDLE = HANDLE(bitPattern: _get_osfhandle(descriptor))! if hFile == INVALID_HANDLE_VALUE { throw IOError(errnoCode: EBADF, reason: "_get_osfhandle") } // The check here is different from other platforms as the file types on // Windows are different. SOCKETs and files are different domains, and // as a result we know that the descriptor is not a socket. The only // other type of file it could be is either character or disk, neither // of which support the operations here. switch GetFileType(hFile) { case DWORD(FILE_TYPE_PIPE): break default: throw ChannelError.operationUnsupported } #else var s: stat = .init() try withUnsafeMutablePointer(to: &s) { ptr in try Posix.fstat(descriptor: descriptor, outStat: ptr) } switch s.st_mode & S_IFMT { case S_IFREG, S_IFDIR, S_IFLNK, S_IFBLK: throw ChannelError.operationUnsupported default: () // Let's default to ok } #endif } /// Create the `PipeChannel` with the provided file descriptor which is used for both input & output. /// /// This method is useful for specialilsed use-cases where you want to use `NIOPipeBootstrap` for say a serial line. /// /// - note: If this method returns a succeeded future, SwiftNIO will close `fileDescriptor` when the `Channel` /// becomes inactive. You _must not_ do any further operations with `fileDescriptor`, including `close`. /// If this method returns a failed future, you still own the file descriptor and are responsible for /// closing it. /// /// - parameters: /// - fileDescriptor: The _Unix file descriptor_ for the input & output. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withInputOutputDescriptor(_ fileDescriptor: CInt) -> EventLoopFuture<Channel> { let inputFD = fileDescriptor let outputFD = try! Posix.dup(descriptor: fileDescriptor) return self.withPipes(inputDescriptor: inputFD, outputDescriptor: outputFD).flatMapErrorThrowing { error in try! Posix.close(descriptor: outputFD) throw error } } /// Create the `PipeChannel` with the provided input and output file descriptors. /// /// The input and output file descriptors must be distinct. If you have a single file descriptor, consider using /// `ClientBootstrap.withConnectedSocket(descriptor:)` if it's a socket or /// `NIOPipeBootstrap.withInputOutputDescriptor` if it is not a socket. /// /// - note: If this method returns a succeeded future, SwiftNIO will close `inputDescriptor` and `outputDescriptor` /// when the `Channel` becomes inactive. You _must not_ do any further operations `inputDescriptor` or /// `outputDescriptor`, including `close`. /// If this method returns a failed future, you still own the file descriptors and are responsible for /// closing them. /// /// - parameters: /// - inputDescriptor: The _Unix file descriptor_ for the input (ie. the read side). /// - outputDescriptor: The _Unix file descriptor_ for the output (ie. the write side). /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withPipes(inputDescriptor: CInt, outputDescriptor: CInt) -> EventLoopFuture<Channel> { precondition(inputDescriptor >= 0 && outputDescriptor >= 0 && inputDescriptor != outputDescriptor, "illegal file descriptor pair. The file descriptors \(inputDescriptor), \(outputDescriptor) " + "must be distinct and both positive integers.") let eventLoop = group.next() do { try self.validateFileDescriptorIsNotAFile(inputDescriptor) try self.validateFileDescriptorIsNotAFile(outputDescriptor) } catch { return eventLoop.makeFailedFuture(error) } let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } let channel: PipeChannel do { let inputFH = NIOFileHandle(descriptor: inputDescriptor) let outputFH = NIOFileHandle(descriptor: outputDescriptor) channel = try PipeChannel(eventLoop: eventLoop as! SelectableEventLoop, inputPipe: inputFH, outputPipe: outputFH) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return self._channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension NIOPipeBootstrap: Sendable {} #endif
6a008d908b8eedfcad357a1cb9df9a7a
44.379729
269
0.637825
false
false
false
false
xuech/OMS-WH
refs/heads/master
OMS-WH/Classes/TakeOrder/线下处理/View/OMSPlaceholdTextView.swift
mit
1
// // OMSPlaceholdTextView.swift // OMS-WH // // Created by xuech on 2017/10/26. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class OMSPlaceholdTextView: UITextView { fileprivate let placeholderLeftMargin: CGFloat = 4.0 fileprivate let placeholderTopMargin: CGFloat = 8.0 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setup() } convenience init() { self.init(frame: CGRect.zero, textContainer: nil) } convenience init(frame: CGRect) { self.init(frame: frame, textContainer: nil) } deinit { NotificationCenter.default.removeObserver(self) } public override func awakeFromNib() { super.awakeFromNib() setup() } fileprivate func setup() { contentInset = UIEdgeInsetsMake(0, 0, 0, 0); font = UIFont.systemFont(ofSize: 12.0) placeholderLabel.font = self.font placeholderLabel.textColor = placeholderColor placeholderLabel.text = placeholder placeholderSizeToFit() addSubview(placeholderLabel) self.sendSubview(toBack: placeholderLabel) let center = NotificationCenter.default center.addObserver(self, selector: #selector(OMSPlaceholdTextView.textChanged(_:)), name: .UITextViewTextDidChange, object: nil) textChanged(nil) } @objc func textChanged(_ notification:Notification?) { placeholderLabel.alpha = self.text.isEmpty ? 1.0 : 0.0 } lazy var placeholderLabel: UILabel = { let label = UILabel() label.lineBreakMode = NSLineBreakMode.byWordWrapping label.numberOfLines = 0 label.backgroundColor = UIColor.clear label.alpha = 1.0 return label }() ///占位文字的颜色 public var placeholderColor: UIColor = UIColor.lightGray { didSet { placeholderLabel.textColor = placeholderColor } } ///占位文字 public var placeholder: String = "" { didSet { placeholderLabel.text = placeholder placeholderSizeToFit() } } override public var text: String! { didSet { textChanged(nil) } } override public var font: UIFont? { didSet { placeholderLabel.font = font placeholderSizeToFit() } } } extension OMSPlaceholdTextView { fileprivate func placeholderSizeToFit() { placeholderLabel.frame = CGRect(x: placeholderLeftMargin, y: placeholderTopMargin, width: frame.width - placeholderLeftMargin * 2, height: 0.0) placeholderLabel.sizeToFit() } }
a7d7e718d1867f1592e81cd52dadf1e4
25.071429
151
0.611986
false
false
false
false
bhajian/raspi-remote
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/Language.swift
mit
1
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Freddy /** **Language** Response object for Language related calls. */ public struct Language: JSONDecodable { /** extracted language */ public let language: String? /** the URL information was requestd for */ public let url: String? /** link to Ethnologue containing information on detected language */ public let ethnologue: String? /** ISO-639-1 code for the detected language */ public let iso6391: String? /** ISO-639-2 code for the detected language */ public let iso6392: String? /** ISO-639-3 code for the detected language */ public let iso6393: String? /** estimated number of persons who natively speak the detected language */ public let nativeSpeakers: String? /** link to the Wikipedia page for the detected language */ public let wikipedia: String? /// Used internally to initialize a Language object public init(json: JSON) throws { language = try? json.string("language") url = try? json.string("url") ethnologue = try? json.string("ethnologue") iso6391 = try? json.string("iso-639-1") iso6392 = try? json.string("iso-639-2") iso6393 = try? json.string("iso-639-3") nativeSpeakers = try? json.string("native-speakers") wikipedia = try? json.string("wikipedia") } }
129a9b09aeb3132848761b5aa7838bc4
29.333333
79
0.668332
false
false
false
false
Where2Go/swiftsina
refs/heads/master
GZWeibo05/Class/Tool/CZNetworkTools.swift
apache-2.0
2
// // CZNetworkTools.swift // GZWeibo05 // // Created by zhangping on 15/10/28. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit import AFNetworking // MARK: - 网络错误枚举 enum CZNetworkError: Int { case emptyToken = -1 case emptyUid = -2 // 枚举里面可以有属性 var description: String { get { // 根据枚举的类型返回对应的错误 switch self { case CZNetworkError.emptyToken: return "accecc token 为空" case CZNetworkError.emptyUid: return "uid 为空" } } } // 枚举可以定义方法 func error() -> NSError { return NSError(domain: "cn.itcast.error.network", code: rawValue, userInfo: ["errorDescription" : description]) } } class CZNetworkTools: NSObject { // 属性 private var afnManager: AFHTTPSessionManager // 创建单例 static let sharedInstance: CZNetworkTools = CZNetworkTools() override init() { let urlString = "https://api.weibo.com/" afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString)) afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain") } // 创建单例 // static let sharedInstance: CZNetworkTools = { // let urlString = "https://api.weibo.com/" // // let tool = CZNetworkTools(baseURL: NSURL(string: urlString)) //// Set // tool.responseSerializer.acceptableContentTypes?.insert("text/plain") // // return tool // }() // MARK: - OAtuh授权 /// 申请应用时分配的AppKey private let client_id = "3769988269" /// 申请应用时分配的AppSecret private let client_secret = "8c30d1e7d3754eca9076689b91531c6a" /// 请求的类型,填写authorization_code private let grant_type = "authorization_code" /// 回调地址 let redirect_uri = "http://www.baidu.com/" // OAtuhURL地址 func oauthRUL() -> NSURL { let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)" return NSURL(string: urlString)! } // 使用闭包回调 // MARK: - 加载AccessToken /// 加载AccessToken func loadAccessToken(code: String, finshed: NetworkFinishedCallback) { // url let urlString = "oauth2/access_token" // NSObject // AnyObject, 任何 class // 参数 let parameters = [ "client_id": client_id, "client_secret": client_secret, "grant_type": grant_type, "code": code, "redirect_uri": redirect_uri ] // 测试返回结果类型 // responseSerializer = AFHTTPResponseSerializer() // result: 请求结果 afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in // let data = String(data: result as! NSData, encoding: NSUTF8StringEncoding) // print("data: \(data)") finshed(result: result as? [String: AnyObject], error: nil) }) { (_, error: NSError) -> Void in finshed(result: nil, error: error) } } // MARK: - 获取用户信息 func loadUserInfo(finshed: NetworkFinishedCallback) { // 守卫,和可选绑定相反 // parameters 代码块里面和外面都能使用 guard var parameters = tokenDict() else { // 能到这里来表示 parameters 没有值 print("没有accessToken") let error = CZNetworkError.emptyToken.error() // 告诉调用者 finshed(result: nil, error: error) return } // 判断uid if CZUserAccount.loadAccount()?.uid == nil { print("没有uid") let error = CZNetworkError.emptyUid.error() // 告诉调用者 finshed(result: nil, error: error) return } // url let urlString = "https://api.weibo.com/2/users/show.json" // 添加元素 parameters["uid"] = CZUserAccount.loadAccount()!.uid! requestGET(urlString, parameters: parameters, finshed: finshed) } /// 判断access token是否有值,没有值返回nil,如果有值生成一个字典 func tokenDict() -> [String: AnyObject]? { if CZUserAccount.loadAccount()?.access_token == nil { return nil } return ["access_token": CZUserAccount.loadAccount()!.access_token!] } // MARK: - 获取微博数据 /** 加载微博数据 - parameter since_id: 若指定此参数,则返回ID比since_id大的微博,默认为0 - parameter max_id: 若指定此参数,则返回ID小于或等于max_id的微博,默认为0 - parameter finished: 回调 */ func loadStatus(since_id: Int, max_id: Int, finished: NetworkFinishedCallback) { guard var parameters = tokenDict() else { // 能到这里来说明token没有值 // 告诉调用者 finished(result: nil, error: CZNetworkError.emptyToken.error()) return } // 添加参数 since_id和max_id // 判断是否有传since_id,max_id if since_id > 0 { parameters["since_id"] = since_id } else if max_id > 0 { parameters["max_id"] = max_id - 1 } // access token 有值 let urlString = "2/statuses/home_timeline.json" // 网络不给力,加载本地数据 if true { requestGET(urlString, parameters: parameters, finshed: finished) } else { loadLocalStatus(finished) } } /// 加载本地微博数据 private func loadLocalStatus(finished: NetworkFinishedCallback) { // 获取路径 let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json") // 加载文件数据 let data = NSData(contentsOfFile: path!) // 转成json do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) // 有数据 finished(result: json as? [String : AnyObject], error: nil) } catch { // 如果do里面的代码出错了,不会崩溃,会走这里 print("出异常了") } // 强制try 如果这句代码有错误,程序立即停止运行 // let statusesJson = try! NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions(rawValue: 0)) } // MARK: - 发布微博 /** 发布微博 - parameter image: 微博图片,可能有可能没有 - parameter status: 微博文本内容 - parameter finished: 回调闭包 */ func sendStatus(image: UIImage?, status: String, finished: NetworkFinishedCallback) { // 判断token guard var parameters = tokenDict() else { // 能到这里来说明token没有值 // 告诉调用者 finished(result: nil, error: CZNetworkError.emptyToken.error()) return } // token有值, 拼接参数 parameters["status"] = status // 判断是否有图片 if let im = image { // 有图片,发送带图片的微博 let urlString = "https://upload.api.weibo.com/2/statuses/upload.json" afnManager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in let data = UIImagePNGRepresentation(im)! // data: 上传图片的2进制 // name: api 上面写的传递参数名称 "pic" // fileName: 上传到服务器后,保存的名称,没有指定可以随便写 // mimeType: 资源类型: // image/png // image/jpeg // image/gif formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png") }, success: { (_, result) -> Void in finished(result: result as? [String: AnyObject], error: nil) }, failure: { (_, error) -> Void in finished(result: nil, error: error) }) } else { // url let urlString = "2/statuses/update.json" // 没有图片 afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in finished(result: result as? [String: AnyObject], error: nil) }) { (_, error) -> Void in finished(result: nil, error: error) } } } // 类型别名 = typedefined typealias NetworkFinishedCallback = (result: [String: AnyObject]?, error: NSError?) -> () // MARK: - 封装AFN.GET func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) { afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in finshed(result: result as? [String: AnyObject], error: nil) }) { (_, error) -> Void in finshed(result: nil, error: error) } } }
e8a1c514b448c872dfeba17d95ceee36
30.255396
125
0.54264
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TargetSelectionPage/Models/TargetSelectionPageSectionModel.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxDataSources enum TargetSelectionPageSectionModel { case source(header: TargetSelectionHeaderBuilder, items: [Item]) case destination(header: TargetSelectionHeaderBuilder, items: [Item]) } extension TargetSelectionPageSectionModel: AnimatableSectionModelType { typealias Item = TargetSelectionPageCellItem var items: [Item] { switch self { case .source(_, let items): return items case .destination(_, let items): return items } } var header: TargetSelectionHeaderBuilder { switch self { case .source(let header, _): return header case .destination(let header, _): return header } } var identity: String { switch self { case .source(let header, _), .destination(let header, _): return header.headerType.id } } init(original: TargetSelectionPageSectionModel, items: [Item]) { switch original { case .source(let header, _): self = .source(header: header, items: items) case .destination(let header, _): self = .destination(header: header, items: items) } } } extension TargetSelectionPageSectionModel: Equatable { static func == (lhs: TargetSelectionPageSectionModel, rhs: TargetSelectionPageSectionModel) -> Bool { switch (lhs, rhs) { case (.source(header: _, items: let left), .source(header: _, items: let right)): return left == right case (.destination(header: _, items: let left), .destination(header: _, items: let right)): return left == right default: return false } } }
e547c6936bfe67c071bf67ffada657f8
29.033333
105
0.606548
false
false
false
false
acalvomartinez/RandomUser
refs/heads/master
RandomUser/APIClientError.swift
apache-2.0
1
// // APIClientError.swift // RandomUser // // Created by Antonio Calvo on 29/06/2017. // Copyright © 2017 Antonio Calvo. All rights reserved. // import Foundation import Result enum APIClientError: Error { case networkError case couldNotDecodeJSON case badStatus(status: Int) case internalServerDrama case unknown(error: Error) } extension APIClientError: Equatable { static func ==(lhs: APIClientError, rhs: APIClientError) -> Bool { return (lhs._domain == rhs._domain) && (lhs._code == rhs._code) } } extension APIClientError { static func build(error: Error) -> APIClientError { switch error._code { case 500: return .internalServerDrama case NSURLErrorNetworkConnectionLost: return .networkError default: return .unknown(error: error) } } }
2316ae1912657d87ca8298ea26f0d522
21
68
0.69656
false
false
false
false
proxpero/Matasano
refs/heads/master
Matasano/Conversions.swift
mit
1
// // Conversions.swift // Cryptopals // // Created by Todd Olsen on 2/13/16. // Copyright © 2016 Todd Olsen. All rights reserved. // import Foundation private let base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".characters.map { String($0) } extension String { /// returns an Unicode code point public var unicodeScalarCodePoint: UInt32 { let scalars = self.unicodeScalars return scalars[scalars.startIndex].value } /// converts a string of ascii text and /// returns an array of bytes /// - precondition: `self` is ascii text (0..<128) public var asciiToBytes: [UInt8] { return unicodeScalars.map { UInt8(ascii: $0) } } /// returns an array of bytes /// - precondition: `self` is hexadecimal text public var hexToBytes: [UInt8] { var items = lowercaseString.characters.map { String($0) } var bytes = [UInt8]() for i in items.startIndex.stride(to: items.endIndex, by: 2) { guard let byte = UInt8(items[i] + (i+1==items.endIndex ? "" : items[i+1]), radix: 16) else { fatalError() } bytes.append(byte) } return bytes } /// returns an array of bytes /// - precondition: `self` is base-64 text public var base64ToBytes: [UInt8] { return characters.map { String($0) }.filter { $0 != "=" }.map { UInt8(base64Chars.indexOf($0)!) }.sextetArrayToBytes } public var asciiToBase64: String { return self.asciiToBytes.base64Representation } public var base64ToAscii: String { return self.base64ToBytes.asciiRepresentation } public var hexToBase64: String { return self.hexToBytes.base64Representation } public var base64ToHex: String { return self.hexToBytes.hexRepresentation } } extension CollectionType where Generator.Element == UInt8, Index == Int { /// return the ascii representation of `self` /// complexity: O(N) public var asciiRepresentation: String { if let result = String(bytes: self, encoding: NSUTF8StringEncoding) { return result } return String(bytes: self, encoding: NSUnicodeStringEncoding)! } /// returns the hexidecimal representation of `self` /// complexity: O(N) public var hexRepresentation: String { var output = "" for byte in self { output += String(byte, radix: 16) } return output } /// returns the base64 representation of `self` /// complexity: O(N) public var base64Representation: String { var output = "" for sixbitInt in (self.bytesToSextetArray.map { Int($0) }) { output += base64Chars[sixbitInt] } while output.characters.count % 4 != 0 { output += "=" } return output } /// private var bytesToSextetArray: [UInt8] { var sixes = [UInt8]() for i in startIndex.stride(to: endIndex, by: 3) { sixes.append(self[i] >> 2) // if there are two missing characters, pad the result with '==' guard i+1 < endIndex else { sixes.appendContentsOf([(self[i] << 6) >> 2]) return sixes } sixes.append((self[i] << 6) >> 2 | self[i+1] >> 4) // if there is one missing character, pad the result with '=' guard i+2 < endIndex else { sixes.append((self[i+1] << 4) >> 2) return sixes } sixes.append((self[i+1] << 4) >> 2 | self[i+2] >> 6) sixes.append((self[i+2] << 2) >> 2) } return sixes } private var sextetArrayToBytes: [UInt8] { var bytes: [UInt8] = [] for i in startIndex.stride(to: endIndex, by: 4) { bytes.append(self[i+0]<<2 | self[i+1]>>4) guard i+2 < endIndex else { return bytes } bytes.append(self[i+1]<<4 | self[i+2]>>2) guard i+3 < endIndex else { return bytes } bytes.append(self[i+2]<<6 | self[i+3]>>0) } return bytes } } // MARK: TESTS func testConversions() { let hobbes = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure." func testUnicodeScalarCodePoint() { assert(" ".unicodeScalarCodePoint == UInt32(32)) // lower bound assert("0".unicodeScalarCodePoint == UInt32(48)) assert("C".unicodeScalarCodePoint == UInt32(67)) assert("a".unicodeScalarCodePoint == UInt32(97)) assert("t".unicodeScalarCodePoint == UInt32(116)) assert("~".unicodeScalarCodePoint == UInt32(126)) // upper bound print("\(#function) passed.") } func testAsciiConversions() { let bytes = [UInt8(77), UInt8(97), UInt8(110)] let text = "Man" assert(text.asciiToBytes == bytes) assert(bytes.asciiRepresentation == text) assert(hobbes.asciiToBytes.asciiRepresentation == hobbes) print("\(#function) passed.") } func testHexConversions() { let text = "deadbeef" assert(text.hexToBytes.hexRepresentation == text) let t1 = "f79" assert(t1.hexToBytes.hexRepresentation == t1) print("\(#function) passed.") } func testBase64Conversions() { let sixes: [UInt8] = [19, 22, 5, 46] let eights: [UInt8] = [77, 97, 110] assert(sixes.sextetArrayToBytes == eights) assert(eights.bytesToSextetArray == sixes) let t1 = "Man" let e1 = "TWFu" assert(t1.asciiToBytes.base64Representation == e1) assert(e1.base64ToBytes.asciiRepresentation == t1) assert(t1.asciiToBase64 == e1) assert(e1.base64ToAscii == t1) assert(t1.asciiToBytes == e1.base64ToBytes) let t2 = "any carnal pleasure." let e2 = "YW55IGNhcm5hbCBwbGVhc3VyZS4=" assert(t2.asciiToBytes.base64Representation == e2) assert(e2.base64ToBytes.asciiRepresentation == t2) assert(t2.asciiToBase64 == e2) assert(e2.base64ToAscii == t2) assert(t2.asciiToBytes == e2.base64ToBytes) let t3 = "any carnal pleasure" let e3 = "YW55IGNhcm5hbCBwbGVhc3VyZQ==" assert(t3.asciiToBytes.base64Representation == e3) assert(e3.base64ToBytes.asciiRepresentation == t3) assert(t3.asciiToBase64 == e3) assert(e3.base64ToAscii == t3) assert(t3.asciiToBytes == e3.base64ToBytes) let t4 = "any carnal pleasur" let e4 = "YW55IGNhcm5hbCBwbGVhc3Vy" assert(t4.asciiToBytes.base64Representation == e4) assert(e4.base64ToBytes.asciiRepresentation == t4) assert(t4.asciiToBase64 == e4) assert(e4.base64ToAscii == t4) assert(t4.asciiToBytes == e4.base64ToBytes) let t5 = "any carnal pleasu" let e5 = "YW55IGNhcm5hbCBwbGVhc3U=" assert(t5.asciiToBytes.base64Representation == e5) assert(e5.base64ToBytes.asciiRepresentation == t5) assert(t5.asciiToBase64 == e5) assert(e5.base64ToAscii == t5) assert(t5.asciiToBytes == e5.base64ToBytes) let t6 = "any carnal pleas" let e6 = "YW55IGNhcm5hbCBwbGVhcw==" assert(t6.asciiToBytes.base64Representation == e6) assert(e6.base64ToBytes.asciiRepresentation == t6) assert(t6.asciiToBase64 == e6) assert(e6.base64ToAscii == t6) assert(t6.asciiToBytes == e6.base64ToBytes) let t7 = "pleasure." let e7 = "cGxlYXN1cmUu" assert(t7.asciiToBytes.base64Representation == e7) assert(e7.base64ToBytes.asciiRepresentation == t7) assert(t7.asciiToBase64 == e7) assert(e7.base64ToAscii == t7) assert(t7.asciiToBytes == e7.base64ToBytes) let t8 = "leasure." let e8 = "bGVhc3VyZS4=" assert(t8.asciiToBytes.base64Representation == e8) assert(e8.base64ToBytes.asciiRepresentation == t8) assert(t8.asciiToBase64 == e8) assert(e8.base64ToAscii == t8) assert(t8.asciiToBytes == e8.base64ToBytes) let t9 = "easure." let e9 = "ZWFzdXJlLg==" assert(t9.asciiToBytes.base64Representation == e9) assert(e9.base64ToBytes.asciiRepresentation == t9) assert(t9.asciiToBase64 == e9) assert(e9.base64ToAscii == t9) assert(t9.asciiToBytes == e9.base64ToBytes) let t10 = "asure." let e10 = "YXN1cmUu" assert(t10.asciiToBytes.base64Representation == e10) assert(e10.base64ToBytes.asciiRepresentation == t10) assert(t10.asciiToBase64 == e10) assert(e10.base64ToAscii == t10) assert(t10.asciiToBytes == e10.base64ToBytes) let t11 = "sure." let e11 = "c3VyZS4=" assert(t11.asciiToBytes.base64Representation == e11) assert(e11.base64ToBytes.asciiRepresentation == t11) assert(t11.asciiToBase64 == e11) assert(e11.base64ToAscii == t11) assert(t11.asciiToBytes == e11.base64ToBytes) let encoded = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" assert(hobbes.asciiToBytes.base64Representation == encoded) assert(hobbes.asciiToBase64 == encoded) let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" assert(input.hexToBytes.base64Representation == output) assert(input.hexToBase64 == output) print("\(#function) passed.") } testUnicodeScalarCodePoint() testAsciiConversions() testHexConversions() testBase64Conversions() print("\(#function) passed.") }
27a0b92a3470e762f630332b4755f677
32.501558
384
0.60173
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Controllers/Payments/View/ReceiptLineView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. import Foundation final class ReceiptLineView: UIStackView { private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.font = Theme.preferredRegular() titleLabel.textColor = Theme.lightGreyTextColor titleLabel.adjustsFontForContentSizeCategory = true return titleLabel }() private lazy var amountLabel: UILabel = { let amountLabel = UILabel() amountLabel.numberOfLines = 0 amountLabel.font = Theme.preferredRegular() amountLabel.textColor = Theme.darkTextColor amountLabel.adjustsFontForContentSizeCategory = true amountLabel.textAlignment = .right return amountLabel }() override init(frame: CGRect) { super.init(frame: frame) axis = .horizontal addArrangedSubview(titleLabel) addArrangedSubview(amountLabel) amountLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTitle(_ title: String) { titleLabel.text = title } func setValue(_ value: String) { amountLabel.text = value } }
c8f086b3882262cbe73999e86217f02d
30.444444
91
0.69258
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
File Management/Saving Objects to File/Saving Objects to File/Person.swift
mit
1
// // Person.swift // Saving Objects to File // // Created by Domenico on 27/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import Foundation class Person: NSObject, NSCoding{ public func encode(with aCoder: NSCoder) { } var firstName: String var lastName: String struct SerializationKey{ static let firstName = "firstName" static let lastName = "lastName" } init(firstName: String, lastName: String){ self.firstName = firstName self.lastName = lastName super.init() } convenience override init(){ self.init(firstName: "Vandad", lastName: "Nahavandipoor") } required init(coder aDecoder: NSCoder) { self.firstName = aDecoder.decodeObject(forKey: SerializationKey.firstName) as! String self.lastName = aDecoder.decodeObject(forKey: SerializationKey.lastName) as! String } func encodewithWithCoder(_ aCoder: NSCoder) { aCoder.encode(self.firstName, forKey: SerializationKey.firstName) aCoder.encode(self.lastName, forKey: SerializationKey.lastName) } } func == (lhs: Person, rhs: Person) -> Bool{ return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName ? true : false }
8a75c86e0ef1b1271fcfca71d57cfbd5
24.5
82
0.631222
false
false
false
false
e78l/swift-corelibs-foundation
refs/heads/master
Foundation/NSLocale.swift
apache-2.0
1
// 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 CoreFoundation open class NSLocale: NSObject, NSCopying, NSSecureCoding, _CFBridgeable { typealias CFType = CFLocale // struct __CFLocale private var _base = _CFInfo(typeID: CFLocaleGetTypeID()) private var _identifier: UnsafeMutableRawPointer? = nil private var _cache: UnsafeMutableRawPointer? = nil private var _prefs: UnsafeMutableRawPointer? = nil private var _lock: CFLock_t = __CFLockInit() private var _nullLocale: Bool = false internal var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } open func object(forKey key: NSLocale.Key) -> Any? { return __SwiftValue.fetch(CFLocaleGetValue(_cfObject, key.rawValue._cfObject)) } open func displayName(forKey key: Key, value: String) -> String? { return CFLocaleCopyDisplayNameForPropertyValue(_cfObject, key.rawValue._cfObject, value._cfObject)?._swiftObject } public init(localeIdentifier string: String) { super.init() _CFLocaleInit(_cfObject, string._cfObject) } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let identifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else { return nil } self.init(localeIdentifier: String._unconditionallyBridgeFromObjectiveC(identifier)) } deinit { _CFDeinit(self) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } override open func isEqual(_ object: Any?) -> Bool { guard let locale = object as? NSLocale else { return false } return locale.localeIdentifier == localeIdentifier } override open var hash: Int { return localeIdentifier.hash } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let identifier = CFLocaleGetIdentifier(self._cfObject)._nsObject aCoder.encode(identifier, forKey: "NS.identifier") } public static var supportsSecureCoding: Bool { return true } } extension NSLocale { open class var current: Locale { return CFLocaleCopyCurrent()._swiftObject } open class var system: Locale { return CFLocaleGetSystem()._swiftObject } } extension NSLocale { public var localeIdentifier: String { return object(forKey: .identifier) as! String } open class var availableLocaleIdentifiers: [String] { return __SwiftValue.fetch(CFLocaleCopyAvailableLocaleIdentifiers()) as? [String] ?? [] } open class var isoLanguageCodes: [String] { return __SwiftValue.fetch(CFLocaleCopyISOLanguageCodes()) as? [String] ?? [] } open class var isoCountryCodes: [String] { return __SwiftValue.fetch(CFLocaleCopyISOCountryCodes()) as? [String] ?? [] } open class var isoCurrencyCodes: [String] { return __SwiftValue.fetch(CFLocaleCopyISOCurrencyCodes()) as? [String] ?? [] } open class var commonISOCurrencyCodes: [String] { return __SwiftValue.fetch(CFLocaleCopyCommonISOCurrencyCodes()) as? [String] ?? [] } open class var preferredLanguages: [String] { return __SwiftValue.fetch(CFLocaleCopyPreferredLanguages()) as? [String] ?? [] } open class func components(fromLocaleIdentifier string: String) -> [String : String] { return __SwiftValue.fetch(CFLocaleCreateComponentsFromLocaleIdentifier(kCFAllocatorSystemDefault, string._cfObject)) as? [String : String] ?? [:] } open class func localeIdentifier(fromComponents dict: [String : String]) -> String { return CFLocaleCreateLocaleIdentifierFromComponents(kCFAllocatorSystemDefault, dict._cfObject)._swiftObject } open class func canonicalLocaleIdentifier(from string: String) -> String { return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } open class func canonicalLanguageIdentifier(from string: String) -> String { return CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } open class func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { return CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(kCFAllocatorSystemDefault, lcid)._swiftObject } open class func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { return CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(localeIdentifier._cfObject) } open class func characterDirection(forLanguage isoLangCode: String) -> NSLocale.LanguageDirection { let dir = CFLocaleGetLanguageCharacterDirection(isoLangCode._cfObject) #if os(macOS) || os(iOS) return NSLocale.LanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocale.LanguageDirection(rawValue: UInt(dir))! #endif } open class func lineDirection(forLanguage isoLangCode: String) -> NSLocale.LanguageDirection { let dir = CFLocaleGetLanguageLineDirection(isoLangCode._cfObject) #if os(macOS) || os(iOS) return NSLocale.LanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocale.LanguageDirection(rawValue: UInt(dir))! #endif } } extension NSLocale { public struct Key : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public static let identifier = NSLocale.Key(rawValue: "kCFLocaleIdentifierKey") public static let languageCode = NSLocale.Key(rawValue: "kCFLocaleLanguageCodeKey") public static let countryCode = NSLocale.Key(rawValue: "kCFLocaleCountryCodeKey") public static let scriptCode = NSLocale.Key(rawValue: "kCFLocaleScriptCodeKey") public static let variantCode = NSLocale.Key(rawValue: "kCFLocaleVariantCodeKey") public static let exemplarCharacterSet = NSLocale.Key(rawValue: "kCFLocaleExemplarCharacterSetKey") public static let calendar = NSLocale.Key(rawValue: "kCFLocaleCalendarKey") public static let collationIdentifier = NSLocale.Key(rawValue: "collation") public static let usesMetricSystem = NSLocale.Key(rawValue: "kCFLocaleUsesMetricSystemKey") public static let measurementSystem = NSLocale.Key(rawValue: "kCFLocaleMeasurementSystemKey") public static let decimalSeparator = NSLocale.Key(rawValue: "kCFLocaleDecimalSeparatorKey") public static let groupingSeparator = NSLocale.Key(rawValue: "kCFLocaleGroupingSeparatorKey") public static let currencySymbol = NSLocale.Key(rawValue: "kCFLocaleCurrencySymbolKey") public static let currencyCode = NSLocale.Key(rawValue: "currency") public static let collatorIdentifier = NSLocale.Key(rawValue: "kCFLocaleCollatorIdentifierKey") public static let quotationBeginDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleQuotationBeginDelimiterKey") public static let quotationEndDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleQuotationEndDelimiterKey") public static let calendarIdentifier = NSLocale.Key(rawValue: "kCFLocaleCalendarIdentifierKey") public static let alternateQuotationBeginDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleAlternateQuotationBeginDelimiterKey") public static let alternateQuotationEndDelimiterKey = NSLocale.Key(rawValue: "kCFLocaleAlternateQuotationEndDelimiterKey") } public enum LanguageDirection : UInt { case unknown case leftToRight case rightToLeft case topToBottom case bottomToTop } } extension NSLocale { public static let currentLocaleDidChangeNotification = NSNotification.Name(rawValue: "kCFLocaleCurrentLocaleDidChangeNotification") } extension CFLocale : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSLocale typealias SwiftType = Locale internal var _nsObject: NSLocale { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Locale { return _nsObject._swiftObject } } extension NSLocale : _SwiftBridgeable { typealias SwiftType = Locale internal var _swiftObject: Locale { return Locale(reference: self) } } extension Locale : _CFBridgeable { typealias CFType = CFLocale internal var _cfObject: CFLocale { return _bridgeToObjectiveC()._cfObject } } extension NSLocale : _StructTypeBridgeable { public typealias _StructType = Locale public func _bridgeToSwift() -> Locale { return Locale._unconditionallyBridgeFromObjectiveC(self) } }
8ddf7f043525f539c43f0c6eedd4dec7
37.398374
154
0.704213
false
false
false
false
mzp/OctoEye
refs/heads/master
Tests/Unit/Store/JsonCacheSpec.swift
mit
1
// // JsonCacheSpec.swift // Tests // // Created by mzp on 2017/09/03. // Copyright © 2017 mzp. All rights reserved. // import Nimble import Quick // swiftlint:disable function_body_length, force_try internal class JsonCacheSpec: QuickSpec { override func spec() { var cache: JsonCache<String>! describe("save and fetch") { beforeEach { JsonCache<String>.clearAll() cache = JsonCache<String>(name: "quick") } it("store root entries") { try! cache.store(parent: [], entries: [ "tmp": "temp dir", "etc": "etc dir" ]) expect(cache[["tmp"]]) == "temp dir" expect(cache[["etc"]]) == "etc dir" } it("store sub entries") { try! cache.store(parent: [], entries: [ "tmp": "temp dir" ]) try! cache.store(parent: ["tmp"], entries: [ "a": "file a" ]) expect(cache[["tmp", "a"]]) == "file a" } it("store sub sub entries") { try! cache.store(parent: ["tmp"], entries: [ "a": "file a" ]) expect(cache[["tmp", "a"]]) == "file a" } } } }
c24f7b9af8c2f88048d20f92a1e14dc5
25.711538
60
0.421886
false
false
false
false
WenkyYuan/SwiftDemo
refs/heads/master
SwiftDemo/Controllers/ViewController.swift
mit
1
// // ViewController.swift // SwiftDemo // // Created by wenky on 15/11/19. // Copyright (c) 2015年 wenky. All rights reserved. // import UIKit class ViewController: UIViewController, CustomTableViewCellDelegate { @IBOutlet weak var tableView: UITableView! var tableData = [String]() //定义一个存放String类型元素的数组,并初始化 let kCustomTableViewCell = "CustomTableViewCell" deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() title = "Swift" setup() observeNotification() } //MARK: private methods func setup() { tableView.registerNib(UINib(nibName: kCustomTableViewCell, bundle: nil), forCellReuseIdentifier: kCustomTableViewCell) } func observeNotification() { NSNotificationCenter.defaultCenter().addObserver(self, selector:"didReceiveNotifiction:", name: "kNotificationName", object: nil) } func didReceiveNotifiction(notifiction: NSNotification) { NSLog("didReceiveNotifiction") //TODO:someting let alert: UIAlertView = UIAlertView(title: "提示", message: "收到通知", delegate: nil, cancelButtonTitle: "确定") alert.show() } //MARK: UITableViewDataSource & UITableViewDelegate func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:CustomTableViewCell! = tableView.dequeueReusableCellWithIdentifier(kCustomTableViewCell, forIndexPath: indexPath) as! CustomTableViewCell cell.leftTitleLabel.text = NSString(format: "%zd.2015.11.13巴黎发生暴恐", indexPath.row) as String cell.iconImageView.image = UIImage(named: "neighbourhood_carpooling") cell.delegate = self cell.tapBlock = { (cell: CustomTableViewCell) ->Void in NSLog("tapBlock%zd", cell.tag) } cell.tag = indexPath.row return cell; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView .deselectRowAtIndexPath(indexPath, animated: true) let vc = NextViewController(nibName: "NextViewController", bundle: nil) vc.bgColor = UIColor.purpleColor() navigationController?.pushViewController(vc, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.min } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.min } //MARK: CustomTableViewCellDelegate func customTableViewCellDidTapIamgeView(cell: CustomTableViewCell) { NSLog("didTapImageViewAtIndex:%zd", cell.tag) } }
34e3485349911bf68fa333953d5f2107
33.077778
154
0.678187
false
false
false
false
jindulys/Wikipedia
refs/heads/master
Wikipedia/Code/SDImageCache+PromiseKit.swift
mit
1
// // SDImageCache+PromiseKit.swift // Wikipedia // // Created by Brian Gerstle on 7/1/15. // Copyright (c) 2015 Wikimedia Foundation. All rights reserved. // import Foundation import PromiseKit import SDWebImage public typealias DiskQueryResult = (cancellable: Cancellable?, promise: Promise<(UIImage, ImageOrigin)>) extension SDImageCache { public func queryDiskCacheForKey(key: String) -> DiskQueryResult { let (promise, fulfill, reject) = Promise<(UIImage, ImageOrigin)>.pendingPromise() // queryDiskCache will return nil if the image is in memory let diskQueryOperation: NSOperation? = self.queryDiskCacheForKey(key, done: { image, cacheType -> Void in if image != nil { fulfill((image, asImageOrigin(cacheType))) } else { reject(WMFImageControllerErrorCode.DataNotFound.error) } }) if let diskQueryOperation = diskQueryOperation { // make sure promise is rejected if the operation is cancelled self.KVOController.observe(diskQueryOperation, keyPath: "isCancelled", options: NSKeyValueObservingOptions.New) { _, _, change in let value = change[NSKeyValueChangeNewKey] as! NSNumber if value.boolValue { reject(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) } } // tear down observation when operation finishes self.KVOController.observe(diskQueryOperation, keyPath: "isFinished", options: NSKeyValueObservingOptions()) { [weak self] _, object, _ in self?.KVOController.unobserve(object) } } return (diskQueryOperation, promise) } }
baf21f11b3ae55278a83adced59ffde5
35.882353
113
0.609782
false
false
false
false
Ericdowney/GameOfGuilds
refs/heads/master
Guilds/Guilds/View.swift
mit
1
// // View.swift // Designables // // Created by Downey, Eric on 11/5/15. // Copyright © 2015 Eric Downey. All rights reserved. // import Foundation import UIKit @IBDesignable public class View: UIView { @IBInspectable public var borderWidth: CGFloat = 0 { didSet { self.setup() } } @IBInspectable public var borderColor: UIColor = UIColor.clearColor() { didSet { self.setup() } } @IBInspectable public var borderRadius: CGFloat = 0.0 { didSet { self.setup() } } @IBInspectable public var fillColor: UIColor = UIColor.whiteColor() { didSet { self.setup() } } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.setup() } public func setup() { self.layer.cornerRadius = self.borderRadius self.layer.borderColor = self.borderColor.CGColor self.layer.borderWidth = self.borderWidth self.layer.backgroundColor = self.fillColor.CGColor } }
3296b3e4d5ef1d3af4c48435d9ac3b85
21.38
75
0.589445
false
false
false
false
0xPr0xy/CoreML
refs/heads/master
ARScanner/Vision/Vision.swift
mit
1
import UIKit import Vision import CoreMedia import AVFoundation typealias Prediction = (String, Double) final class Vision { private let model = MobileNet() private let semaphore = DispatchSemaphore(value: 2) private var camera: Camera! private var request: VNCoreMLRequest! private var startTimes: [CFTimeInterval] = [] private var framesDone = 0 private var frameCapturingStartTime = CACurrentMediaTime() public weak var delegate: VisionOutput? init() { self.setUpCamera() self.setUpVision() } private func setUpCamera() { camera = Camera() camera.delegate = self camera.fps = 50 camera.setUp { success in if success { if let visual = self.camera.previewLayer { self.delegate?.addVideoLayer(visual) } self.camera.start() } } } private func setUpVision() { guard let visionModel = try? VNCoreMLModel(for: model.model) else { print("Error: could not create Vision model") return } request = VNCoreMLRequest(model: visionModel, completionHandler: requestDidComplete) request.imageCropAndScaleOption = .centerCrop } private func predict(pixelBuffer: CVPixelBuffer) { // Measure how long it takes to predict a single video frame. Note that // predict() can be called on the next frame while the previous one is // still being processed. Hence the need to queue up the start times. startTimes.append(CACurrentMediaTime()) let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer) try? handler.perform([request]) } private func requestDidComplete(request: VNRequest, error: Error?) { if let observations = request.results as? [VNClassificationObservation] { // The observations appear to be sorted by confidence already, so we // take the top 5 and map them to an array of (String, Double) tuples. let top5 = observations.prefix(through: 4) .map { ($0.identifier.chopPrefix(9), Double($0.confidence)) } DispatchQueue.main.async { self.show(results: top5) self.semaphore.signal() } } } private func show(results: [Prediction]) { var strings: [String] = [] for (count, pred) in results.enumerated() { strings.append(String(format: "%d: %@ (%3.2f%%)", count + 1, pred.0, pred.1 * 100)) } let predictionLabelText = strings.joined(separator: "\n\n") delegate?.setPredictionLabelText(predictionLabelText) let latency = CACurrentMediaTime() - startTimes.remove(at: 0) let fps = self.measureFPS() let timeLabelText = String(format: "%.2f FPS (latency %.5f seconds)", fps, latency) delegate?.setTimeLabelText(timeLabelText) } private func measureFPS() -> Double { // Measure how many frames were actually delivered per second. framesDone += 1 let frameCapturingElapsed = CACurrentMediaTime() - frameCapturingStartTime let currentFPSDelivered = Double(framesDone) / frameCapturingElapsed if frameCapturingElapsed > 1 { framesDone = 0 frameCapturingStartTime = CACurrentMediaTime() } return currentFPSDelivered } } extension Vision: VisionInput { public func videoCapture(_ capture: Camera, didCaptureVideoFrame pixelBuffer: CVPixelBuffer?, timestamp: CMTime) { if let pixelBuffer = pixelBuffer { // For better throughput, perform the prediction on a background queue // instead of on the VideoCapture queue. We use the semaphore to block // the capture queue and drop frames when Core ML can't keep up. semaphore.wait() DispatchQueue.global().async { self.predict(pixelBuffer: pixelBuffer) } } } }
e31ede1870598b699081602512c6c324
33.905172
118
0.627315
false
false
false
false
nextcloud/ios
refs/heads/master
iOSClient/Account Request/NCAccountRequest.swift
gpl-3.0
1
// // NCAccountRequest.swift // Nextcloud // // Created by Marino Faggiana on 26/02/21. // Copyright © 2021 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // 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, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. // import UIKit import NextcloudKit public protocol NCAccountRequestDelegate: AnyObject { func accountRequestAddAccount() func accountRequestChangeAccount(account: String) } // optional func public extension NCAccountRequestDelegate { func accountRequestAddAccount() {} func accountRequestChangeAccount(account: String) {} } class NCAccountRequest: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var progressView: UIProgressView! public var accounts: [tableAccount] = [] public var activeAccount: tableAccount? public let heightCell: CGFloat = 60 public var enableTimerProgress: Bool = true public var enableAddAccount: Bool = false public var dismissDidEnterBackground: Bool = false public weak var delegate: NCAccountRequestDelegate? private var timer: Timer? private var time: Float = 0 private let secondsAutoDismiss: Float = 3 // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() titleLabel.text = NSLocalizedString("_account_select_", comment: "") closeButton.setImage(NCUtility.shared.loadImage(named: "xmark", color: .label), for: .normal) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)) tableView.separatorStyle = UITableViewCell.SeparatorStyle.none view.backgroundColor = .secondarySystemBackground tableView.backgroundColor = .secondarySystemBackground progressView.trackTintColor = .clear progressView.progress = 1 if enableTimerProgress { progressView.isHidden = false } else { progressView.isHidden = true } NotificationCenter.default.addObserver(self, selector: #selector(startTimer), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let visibleCells = tableView.visibleCells var numAccounts = accounts.count if enableAddAccount { numAccounts += 1 } if visibleCells.count == numAccounts { tableView.isScrollEnabled = false } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() } // MARK: - Action @IBAction func actionClose(_ sender: UIButton) { dismiss(animated: true) } // MARK: - NotificationCenter @objc func applicationDidEnterBackground() { if dismissDidEnterBackground { dismiss(animated: false) } } // MARK: - Progress @objc func startTimer() { if enableTimerProgress { time = 0 timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true) progressView.isHidden = false } else { progressView.isHidden = true } } @objc func updateProgress() { time += 0.1 if time >= secondsAutoDismiss { dismiss(animated: true) } else { progressView.progress = 1 - (time / secondsAutoDismiss) } } } extension NCAccountRequest: UITableViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { timer?.invalidate() progressView.progress = 0 } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { // startTimer() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // startTimer() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return heightCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == accounts.count { dismiss(animated: true) delegate?.accountRequestAddAccount() } else { let account = accounts[indexPath.row] if account.account != activeAccount?.account { dismiss(animated: true) { self.delegate?.accountRequestChangeAccount(account: account.account) } } else { dismiss(animated: true) } } } } extension NCAccountRequest: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if enableAddAccount { return accounts.count + 1 } else { return accounts.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.backgroundColor = tableView.backgroundColor let avatarImage = cell.viewWithTag(10) as? UIImageView let userLabel = cell.viewWithTag(20) as? UILabel let urlLabel = cell.viewWithTag(30) as? UILabel let activeImage = cell.viewWithTag(40) as? UIImageView userLabel?.text = "" urlLabel?.text = "" if indexPath.row == accounts.count { avatarImage?.image = NCUtility.shared.loadImage(named: "plus").image(color: .systemBlue, size: 15) avatarImage?.contentMode = .center userLabel?.text = NSLocalizedString("_add_account_", comment: "") userLabel?.textColor = .systemBlue userLabel?.font = UIFont.systemFont(ofSize: 15) } else { let account = accounts[indexPath.row] avatarImage?.image = NCUtility.shared.loadUserImage( for: account.user, displayName: account.displayName, userBaseUrl: account) if account.alias.isEmpty { userLabel?.text = account.user.uppercased() urlLabel?.text = (URL(string: account.urlBase)?.host ?? "") } else { userLabel?.text = account.alias.uppercased() } if account.active { activeImage?.image = NCUtility.shared.loadImage(named: "checkmark").image(color: .systemBlue, size: 30) } else { activeImage?.image = nil } } return cell } }
5a4b47313a514ee451faa78476a3d921
30.906122
219
0.647563
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/String+Match.swift
apache-2.0
1
// // String+Match.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2020-09-02. // // --------------------------------------------------------------------------- // // © 2020-2022 1024jp // // 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 // // https://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. // extension String { typealias AbbreviatedMatchResult = (ranges: [Range<String.Index>], score: Int) /// Search ranges of the characters contains in the `searchString` in the `searchString` order. /// /// - Parameter searchString: The string to search. /// - Returns: The array of matched character ranges or `nil` if not matched. func abbreviatedMatch(with searchString: String) -> AbbreviatedMatchResult? { guard !searchString.isEmpty, !self.isEmpty else { return nil } let ranges: [Range<String.Index>] = searchString.reduce(into: []) { (ranges, character) in let index = ranges.last?.upperBound ?? self.startIndex guard let range = self.range(of: String(character), options: .caseInsensitive, range: index..<self.endIndex) else { return } ranges.append(range) } guard ranges.count == searchString.count else { return nil } // just simply caluculate the length... let score = self.distance(from: ranges.first!.lowerBound, to: ranges.last!.upperBound) return (ranges, score) } }
8dbff95f75f6e460383245c2df39b8c3
34.909091
136
0.622278
false
false
false
false
timd/ProiOSTableCollectionViews
refs/heads/master
Ch12/DragAndDrop/Final state/DragAndDrop/DragAndDrop/CollectionViewController.swift
mit
1
// // CollectionViewController.swift // DragAndDrop // // Created by Tim on 20/07/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit private let reuseIdentifier = "ReuseIdentifier" class CollectionViewController: UICollectionViewController { private let reuseIdentifier = "ReuseIdentifier" private var dataArray = [String]() private var selectedCell: UICollectionViewCell? override func viewDidLoad() { super.viewDidLoad() // Allow drag-and-drop interaction self.installsStandardGestureForInteractiveMovement = true // Set up data for index in 0...100 { dataArray.append("\(index)") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) collectionView?.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) // Configure the cell let label: UILabel = cell.viewWithTag(1000) as! UILabel label.text = "Cell \(dataArray[indexPath.row])" cell.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor cell.contentView.layer.borderWidth = 2.0 return cell } // MARK: - // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool { // Highlight the cell selectedCell = collectionView.cellForItemAtIndexPath(indexPath) selectedCell?.contentView.layer.borderColor = UIColor.redColor().CGColor return true } override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { // Find object to move let thingToMove = dataArray[sourceIndexPath.row] // Remove old object dataArray.removeAtIndex(sourceIndexPath.row) // insert new copy of thing to move dataArray.insert(thingToMove, atIndex: destinationIndexPath.row) // Set the cell's background to the original light grey selectedCell?.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor // Reload the data collectionView.reloadData() } }
9f728a477efe6713062d720eb958ae6d
29.969697
165
0.673516
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Macie/Macie_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 SotoCore /// Error enum for Macie public struct MacieErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case internalException = "InternalException" case invalidInputException = "InvalidInputException" case limitExceededException = "LimitExceededException" } private let error: Code public let context: AWSErrorContext? /// initialize Macie public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// You do not have required permissions to access the requested resource. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// Internal server error. public static var internalException: Self { .init(.internalException) } /// The request was rejected because an invalid or out-of-range value was supplied for an input parameter. public static var invalidInputException: Self { .init(.invalidInputException) } /// The request was rejected because it attempted to create resources beyond the current AWS account limits. The error code describes the limit exceeded. public static var limitExceededException: Self { .init(.limitExceededException) } } extension MacieErrorType: Equatable { public static func == (lhs: MacieErrorType, rhs: MacieErrorType) -> Bool { lhs.error == rhs.error } } extension MacieErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
dbca91a0866573ea60590ad2b9c990df
36.363636
157
0.663423
false
false
false
false
RamonGilabert/Prodam
refs/heads/master
Prodam/Prodam/BreakWindowController.swift
mit
1
import Cocoa class BreakWindowController: NSWindowController { let breakViewController = BreakViewController() var popoverManager: PopoverManager? // MARK: View lifecycle override func loadWindow() { self.window = BreakWindow(contentRect: self.breakViewController.view.frame, styleMask: NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false) self.window?.contentView = RoundedCornerView(frame: self.breakViewController.view.frame) self.window?.center() self.window?.animationBehavior = NSWindowAnimationBehavior.AlertPanel self.window?.display() self.window?.makeKeyWindow() self.window?.makeMainWindow() NSApp.activateIgnoringOtherApps(true) self.window?.makeKeyAndOrderFront(true) self.breakViewController.popoverManager = self.popoverManager self.popoverManager?.breakController = self (self.window?.contentView as! RoundedCornerView).visualEffectView.addSubview(self.breakViewController.view) } }
e9f9c6df843b98254eb516507bf4c6bc
41.04
170
0.736441
false
false
false
false
timd/ProiOSTableCollectionViews
refs/heads/master
Ch11/NamesApp/NamesApp/ViewController.swift
mit
1
// // ViewController.swift // NamesApp // // Created by Tim on 25/10/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { var collation = UILocalizedIndexedCollation.currentCollation() var tableData: [String]! var sections: Array<Array<String>> = [] //var sections: [[String]] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. parsePlist() configureSectionData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Name for the letter \(collation.sectionTitles[section])" } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return collation.sectionTitles } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) let innerData = sections[indexPath.section] cell.textLabel!.text = innerData[indexPath.row] return cell } // MARK: - // MARK: Header and footer methods func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerFrame = CGRectMake(0, 0, tableView.frame.size.width, 100.0) let headerView = UIView(frame: headerFrame) headerView.backgroundColor = UIColor(red: 0.5, green: 0.2, blue: 0.57, alpha: 1.0) let labelFrame = CGRectMake(15.0, 80.0, view.frame.size.width, 15.0) let headerLabel = UILabel(frame: labelFrame) headerLabel.text = "Section Header" headerLabel.font = UIFont(name: "Courier-Bold", size: 18.0) headerLabel.textColor = UIColor.whiteColor() headerView.addSubview(headerLabel) return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerFrame = CGRectMake(0, 0, tableView.frame.size.width, 50.0) let footerView = UIView(frame: footerFrame) footerView.backgroundColor = UIColor(red: 1.0, green: 0.7, blue: 0.57, alpha: 1.0) let labelFrame = CGRectMake(15.0, 10.0, view.frame.size.width, 15.0) let footerLabel = UILabel(frame: labelFrame) footerLabel.text = "Section Footer" footerLabel.font = UIFont(name: "Times-New-Roman", size: 12.0) footerLabel.textColor = UIColor.blueColor() footerView.addSubview(footerLabel) return footerView } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50.0 } } extension ViewController { func parsePlist() { let bundle = NSBundle.mainBundle() if let plistPath = bundle.pathForResource("Names", ofType: "plist"), let namesDictionary = NSDictionary(contentsOfFile: plistPath), let names = namesDictionary["Names"] { tableData = names as! [String] } } func configureSectionData() { let selector: Selector = "lowercaseString" sections = Array(count: collation.sectionTitles.count, repeatedValue: []) let sortedObjects = collation.sortedArrayFromArray(tableData, collationStringSelector: selector) for object in sortedObjects { let sectionNumber = collation.sectionForObject(object, collationStringSelector: selector) sections[sectionNumber].append(object as! String) } } }
a2ea60f69f299fa572801d5413b059f4
30.553191
109
0.640513
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
IntegrationTests/Tests/IntegrationTests/BasicTests.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic import TSCTestSupport final class BasicTests: XCTestCase { func testVersion() throws { XCTAssertMatch(try sh(swift, "--version").stdout, .contains("Swift version")) } func testExamplePackageDealer() throws { try XCTSkipIf(isSelfHosted, "These packages don't use the latest runtime library, which doesn't work with self-hosted builds.") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "dealer") try sh("git", "clone", "https://github.com/apple/example-package-dealer", packagePath) let build1Output = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertMatch(build1Output, .contains("Build complete")) // Verify that the app works. let dealerOutput = try sh(AbsolutePath(".build/debug/dealer", relativeTo: packagePath), "10").stdout XCTAssertEqual(dealerOutput.filter(\.isPlayingCardSuit).count, 10) // Verify that the 'git status' is clean after a build. try localFileSystem.changeCurrentWorkingDirectory(to: packagePath) let gitOutput = try sh("git", "status").stdout XCTAssertMatch(gitOutput, .contains("nothing to commit, working tree clean")) // Verify that another 'swift build' does nothing. let build2Output = try sh(swiftBuild, "--package-path", packagePath).stdout XCTAssertMatch(build2Output, .contains("Build complete")) XCTAssertNoMatch(build2Output, .contains("Compiling")) } } func testSwiftBuild() throws { try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "tool") try localFileSystem.createDirectory(packagePath) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:4.2 import PackageDescription let package = Package( name: "tool", targets: [ .target(name: "tool", path: "./"), ] ) """)) try localFileSystem.writeFileContents( packagePath.appending(component: "main.swift"), bytes: ByteString(encodingAsUTF8: #"print("HI")"#)) // Check the build. let buildOutput = try sh(swiftBuild, "--package-path", packagePath, "-v").stdout XCTAssertMatch(buildOutput, .regex("swiftc.* -module-name tool")) // Verify that the tool exists and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "tool")).stdout XCTAssertEqual(toolOutput, "HI\n") } } func testSwiftCompiler() throws { try withTemporaryDirectory { tempDir in let helloSourcePath = tempDir.appending(component: "hello.swift") try localFileSystem.writeFileContents( helloSourcePath, bytes: ByteString(encodingAsUTF8: #"print("hello")"#)) let helloBinaryPath = tempDir.appending(component: "hello") try sh(swiftc, helloSourcePath, "-o", helloBinaryPath) // Check the file exists. XCTAssert(localFileSystem.exists(helloBinaryPath)) // Check the file runs. let helloOutput = try sh(helloBinaryPath).stdout XCTAssertEqual(helloOutput, "hello\n") } } func testSwiftPackageInitExec() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") let buildOutput = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertContents(buildOutput) { checker in checker.check(.regex("Compiling .*Project.*")) checker.check(.regex("Linking .*Project")) checker.check(.contains("Build complete")) } // Verify that the tool was built and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "Project")).stdout XCTAssertMatch(toolOutput.lowercased(), .contains("hello, world!")) // Check there were no compile errors or warnings. XCTAssertNoMatch(buildOutput, .contains("error")) XCTAssertNoMatch(buildOutput, .contains("warning")) } } func testSwiftPackageInitExecTests() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") let testOutput = try sh(swiftTest, "--package-path", packagePath).stdout // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.regex("Compiling .*ProjectTests.*")) checker.check("Test Suite 'All tests' passed") checker.checkNext("Executed 1 test") } // Check there were no compile errors or warnings. XCTAssertNoMatch(testOutput, .contains("error")) XCTAssertNoMatch(testOutput, .contains("warning")) } } func testSwiftPackageInitLib() throws { try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") let buildOutput = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertMatch(buildOutput, .regex("Compiling .*Project.*")) XCTAssertMatch(buildOutput, .contains("Build complete")) // Check there were no compile errors or warnings. XCTAssertNoMatch(buildOutput, .contains("error")) XCTAssertNoMatch(buildOutput, .contains("warning")) } } func testSwiftPackageLibsTests() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") let testOutput = try sh(swiftTest, "--package-path", packagePath).stdout // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.regex("Compiling .*ProjectTests.*")) checker.check("Test Suite 'All tests' passed") checker.checkNext("Executed 1 test") } // Check there were no compile errors or warnings. XCTAssertNoMatch(testOutput, .contains("error")) XCTAssertNoMatch(testOutput, .contains("warning")) } } func testSwiftPackageWithSpaces() throws { try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(components: "more spaces", "special tool") try localFileSystem.createDirectory(packagePath, recursive: true) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:4.2 import PackageDescription let package = Package( name: "special tool", targets: [ .target(name: "special tool", path: "./"), ] ) """)) try localFileSystem.writeFileContents( packagePath.appending(component: "main.swift"), bytes: ByteString(encodingAsUTF8: #"foo()"#)) try localFileSystem.writeFileContents( packagePath.appending(component: "some file.swift"), bytes: ByteString(encodingAsUTF8: #"func foo() { print("HI") }"#)) // Check the build. let buildOutput = try sh(swiftBuild, "--package-path", packagePath, "-v").stdout XCTAssertMatch(buildOutput, .regex(#"swiftc.* -module-name special_tool .* ".*/more spaces/special tool/some file.swift""#)) XCTAssertMatch(buildOutput, .contains("Build complete")) // Verify that the tool exists and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "special tool")).stdout XCTAssertEqual(toolOutput, "HI\n") } } func testSwiftRun() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "secho") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") // delete any files generated for entry in try localFileSystem.getDirectoryContents(packagePath.appending(components: "Sources", "secho")) { try localFileSystem.removeFileTree(packagePath.appending(components: "Sources", "secho", entry)) } try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "secho", "main.swift"), bytes: ByteString(encodingAsUTF8: """ import Foundation print(CommandLine.arguments.dropFirst().joined(separator: " ")) """)) let (runOutput, runError) = try sh(swiftRun, "--package-path", packagePath, "secho", "1", #""two""#) // Check the run log. XCTAssertContents(runError) { checker in checker.check(.regex("Compiling .*secho.*")) checker.check(.regex("Linking .*secho")) checker.check(.contains("Build complete")) } XCTAssertEqual(runOutput, "1 \"two\"\n") } } func testSwiftTest() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "swiftTest") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "swiftTestTests", "MyTests.swift"), bytes: ByteString(encodingAsUTF8: """ import XCTest final class MyTests: XCTestCase { func testFoo() { XCTAssertTrue(1 == 1) } func testBar() { XCTAssertFalse(1 == 2) } func testBaz() { } } """)) let testOutput = try sh(swiftTest, "--package-path", packagePath, "--filter", "MyTests.*", "--skip", "testBaz").stderr // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.contains("Test Suite 'MyTests' started")) checker.check(.contains("Test Suite 'MyTests' passed")) checker.check(.contains("Executed 2 tests, with 0 failures")) } } } func testSwiftTestWithResources() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "swiftTestResources") try localFileSystem.createDirectory(packagePath) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:5.3 import PackageDescription let package = Package( name: "AwesomeResources", targets: [ .target(name: "AwesomeResources", resources: [.copy("hello.txt")]), .testTarget(name: "AwesomeResourcesTest", dependencies: ["AwesomeResources"], resources: [.copy("world.txt")]) ] ) """) ) try localFileSystem.createDirectory(packagePath.appending(component: "Sources")) try localFileSystem.createDirectory(packagePath.appending(components: "Sources", "AwesomeResources")) try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "AwesomeResources", "AwesomeResource.swift"), bytes: ByteString(encodingAsUTF8: """ import Foundation public struct AwesomeResource { public init() {} public let hello = try! String(contentsOf: Bundle.module.url(forResource: "hello", withExtension: "txt")!) } """) ) try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "AwesomeResources", "hello.txt"), bytes: ByteString(encodingAsUTF8: "hello") ) try localFileSystem.createDirectory(packagePath.appending(component: "Tests")) try localFileSystem.createDirectory(packagePath.appending(components: "Tests", "AwesomeResourcesTest")) try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "AwesomeResourcesTest", "world.txt"), bytes: ByteString(encodingAsUTF8: "world") ) try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "AwesomeResourcesTest", "MyTests.swift"), bytes: ByteString(encodingAsUTF8: """ import XCTest import Foundation import AwesomeResources final class MyTests: XCTestCase { func testFoo() { XCTAssertTrue(AwesomeResource().hello == "hello") } func testBar() { let world = try! String(contentsOf: Bundle.module.url(forResource: "world", withExtension: "txt")!) XCTAssertTrue(world == "world") } } """)) let testOutput = try sh(swiftTest, "--package-path", packagePath, "--filter", "MyTests.*").stderr // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.contains("Test Suite 'MyTests' started")) checker.check(.contains("Test Suite 'MyTests' passed")) checker.check(.contains("Executed 2 tests, with 0 failures")) } } } } private extension Character { var isPlayingCardSuit: Bool { switch self { case "♠︎", "♡", "♢", "♣︎": return true default: return false } } }
6f3bd61f31e81c1ab1a529367ef6c9ce
44.448549
137
0.579623
false
true
false
false
hw3308/Swift3Basics
refs/heads/master
Swift3Basics/Extension/UIImage+Extension.swift
mit
2
// // UIImage+Extension.swift // SwiftBasics // // Created by 侯伟 on 17/1/11. // Copyright © 2017年 侯伟. All rights reserved. // import Foundation import UIKit // MARK: Data extension UIImage { public var data: Data? { switch contentType { case .jpeg: return UIImageJPEGRepresentation(self, 1) case .png: return UIImagePNGRepresentation(self) //case .GIF: //return UIImageAnimatedGIFRepresentation(self) default: return nil } } } // MARK: Content Type extension UIImage { fileprivate struct AssociatedKey { static var contentType: Int = 0 } public enum ContentType: Int { case unknown = 0, png, jpeg, gif, tiff, webp public var mimeType: String { switch self { case .jpeg: return "image/jpeg" case .png: return "image/png" case .gif: return "image/gif" case .tiff: return "image/tiff" case .webp: return "image/webp" default: return "" } } public var extendName: String { switch self { case .jpeg: return ".jpg" case .png: return ".png" case .gif: return ".gif" case .tiff: return ".tiff" case .webp: return ".webp" default: return "" } } public static func contentType(mimeType: String?) -> ContentType { guard let mime = mimeType else { return .unknown } switch mime { case "image/jpeg": return .jpeg case "image/png": return .png case "image/gif": return .gif case "image/tiff": return .tiff case "image/webp": return .webp default: return .unknown } } public static func contentTypeWithImageData(_ imageData: Data?) -> ContentType { guard let data = imageData else { return .unknown } var c = [UInt32](repeating: 0, count: 1) (data as NSData).getBytes(&c, length: 1) switch (c[0]) { case 0xFF: return .jpeg case 0x89: return .png case 0x47: return .gif case 0x49, 0x4D: return .tiff case 0x52: // R as RIFF for WEBP if data.count >= 12 { if let type = String(data: data.subdata(in: data.startIndex..<data.startIndex.advanced(by: 12)), encoding: String.Encoding.ascii) { if type.hasPrefix("RIFF") && type.hasSuffix("WEBP") { return .webp } } } default: break } return .unknown } } public var contentType: ContentType { get { let value = objc_getAssociatedObject(self, &AssociatedKey.contentType) as? Int ?? 0 if value == 0 { var result: ContentType //if let _ = UIImageAnimatedGIFRepresentation(self) { //result = .GIF //} else if let _ = UIImageJPEGRepresentation(self, 1) { result = .jpeg } else if let _ = UIImagePNGRepresentation(self) { result = .png } else { result = .unknown } objc_setAssociatedObject(self, &AssociatedKey.contentType, result.rawValue, .OBJC_ASSOCIATION_RETAIN) return result } return ContentType(rawValue: value) ?? .unknown } set { objc_setAssociatedObject(self, &AssociatedKey.contentType, newValue.rawValue, .OBJC_ASSOCIATION_RETAIN) } } convenience init?(data: Data, contentType: ContentType) { self.init(data: data) self.contentType = contentType } }
209e22dd9edbe9518437def6097fd461
29.865672
151
0.488878
false
false
false
false
stevewight/DetectorKit
refs/heads/master
DetectorKit/Views/PulseView.swift
mit
1
// // PulseView.swift // DetectorKit // // Created by Steve on 4/12/17. // Copyright © 2017 Steve Wight. All rights reserved. // import UIKit class PulseView: BaseFrameView { var circles = [CAShapeLayer]() override internal func setUp() { setUpCircle() setUpAnimations() } private func setUpCircle() { let baseLayer = createCircle() baseLayer.path = createPath(baseLayer,0) layer.addSublayer(baseLayer) circles.insert(baseLayer, at:0) } private func setUpAnimations() { pulse(circles[0]) } private func pulse(_ circle:CAShapeLayer) { let animation = CirclePulseAnimate(circle) animation.pulse() } private func createCircle()->CAShapeLayer { let circle = CAShapeLayer() circle.frame = layer.bounds circle.fillColor = lineColor circle.strokeColor = lineColor circle.lineWidth = CGFloat(lineWidth) return circle } private func createPath(_ circle:CAShapeLayer,_ index:Int)->CGPath { let size = circle.bounds.size let radius = size.width/2 let rectPath = CGRect( x: 0.0, y: 0.0, width: size.width, height: size.height ) return UIBezierPath( roundedRect: rectPath, cornerRadius: radius ).cgPath } }
3a0f32ebcb206fa7827715524bc78705
22.491803
72
0.578507
false
false
false
false
bykoianko/omim
refs/heads/master
iphone/Maps/UI/Settings/Cells/SettingsTableViewSwitchCell.swift
apache-2.0
1
@objc protocol SettingsTableViewSwitchCellDelegate { func switchCell(_ cell: SettingsTableViewSwitchCell, didChangeValue value: Bool) } @objc final class SettingsTableViewSwitchCell: MWMTableViewCell { @IBOutlet fileprivate weak var title: UILabel! @IBOutlet fileprivate weak var switchButton: UISwitch! { didSet { switchButton.addTarget(self, action: #selector(switchChanged), for: .valueChanged) } } weak var delegate: SettingsTableViewSwitchCellDelegate? @objc var isEnabled = true { didSet { styleTitle() switchButton.isUserInteractionEnabled = isEnabled } } @objc var isOn: Bool { get { return switchButton.isOn } set { switchButton.isOn = newValue } } @objc func config(delegate: SettingsTableViewSwitchCellDelegate, title: String, isOn: Bool) { backgroundColor = UIColor.white() self.delegate = delegate self.title.text = title styleTitle() switchButton.isOn = isOn styleSwitchButton() } @IBAction fileprivate func switchChanged() { delegate?.switchCell(self, didChangeValue: switchButton.isOn) } fileprivate func styleTitle() { title.textColor = isEnabled ? UIColor.blackPrimaryText() : UIColor.blackSecondaryText() title.font = UIFont.regular17() } fileprivate func styleSwitchButton() { switchButton.onTintColor = UIColor.linkBlue() } }
33e365287baedb15a5a752c0a8b0b86d
24.054545
95
0.72061
false
false
false
false
AlexandreCassagne/RuffLife-iOS
refs/heads/master
RuffLife/FoundViewController.swift
mit
1
// // FoundViewController.swift // RuffLife // // Created by Alexandre Cassagne on 21/10/2017. // Copyright © 2017 Cassagne. All rights reserved. // import UIKit import AWSDynamoDB import CoreLocation class FoundViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate { var locationCoordinate: CLLocationCoordinate2D? func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let l = locations[0] locationCoordinate = l.coordinate location.text = "\(locationCoordinate!.latitude, locationCoordinate!.latitude)" } var url: String? var uploadImage: UploadImage? var imagePicker = UIImagePickerController() func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } private func startAzure() { let a = Azure() print("Starting azure...") a.request(url: self.url!) { predictions in print("Got callback.") let top = predictions[0] as! [String: Any] print(top) let p = top["Probability"] as! Double let breed = top["Tag"] as! String if (p > 0.08) { OperationQueue.main.addOperation({ self.breed.text = breed }) } } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } pictureView.image = image uploadImage = UploadImage(image: image) print("Starting upload...") uploadImage?.post { print("Returned: \(self.uploadImage?.publicURL)") self.url = self.uploadImage?.publicURL?.absoluteString self.startAzure() } picker.dismiss(animated: true, completion: nil) } @IBOutlet weak var location: UITextField! @IBOutlet weak var breed: UITextField! // @IBOutlet weak var color: UITextField! @IBOutlet weak var firstName: UITextField! @IBOutlet weak var number: UITextField! @IBOutlet weak var pictureView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.delegate = self // Do any additional setup after loading the view. } @IBAction func submit(_ sender: Any) { guard let coordinate = self.locationCoordinate, let name = firstName.text, let phoneNumber = number.text else { let alert = UIAlertController(title: "Incomplete Form", message: "Please ensure the form is completely filled out before proceeding.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) return } let db = AWSDynamoDBObjectMapper.default() let newPet = RuffLife()! newPet.FirstName = name // newPet.LastName = "Empty" newPet.PhoneNumber = phoneNumber newPet.Breed = breed.text // newPet.Color = color.text newPet.ImageURL = url! newPet.lat = coordinate.latitude as NSNumber newPet.lon = coordinate.longitude as NSNumber newPet.PetID = NSNumber(integerLiteral: Int(arc4random())) db.save(newPet).continueWith(block: { (task:AWSTask<AnyObject>!) -> Any? in DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert) if let error = task.error as NSError? { alert.title = "Failure" alert.message = "The request failed. Error: \(error)" alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { // Do something with task.result or perform other operations. alert.title = "Success" alert.message = "Successfully published to location of this pet!" alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { _ in self.navigationController!.popViewController(animated: true) })) self.present(alert, animated: true, completion: nil) } } return nil }) } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Warning", message: "You don't have a camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func openGallary() { imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } @IBAction func autofill(_ sender: Any) { let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openCamera() })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.openGallary() })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.startUpdatingLocation() self.present(alert, animated: true, completion: nil) // self.show(picker, sender: self) present(imagePicker, animated: true, completion: nil) } let locationManager = CLLocationManager() @IBOutlet weak var autofill: UIButton! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33337430c0982c7a5dbbd5867ef251d5
32.344086
161
0.722025
false
false
false
false
gurenupet/hah-auth-ios-swift
refs/heads/master
hah-auth-ios-swift/hah-auth-ios-swift/AppDelegate.swift
mit
1
// // AppDelegate.swift // hah-auth-ios-swift // // Created by Anton Antonov on 06.07.17. // Copyright © 2017 KRIT. All rights reserved. // import UIKit import Mixpanel @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { configureMixpanel() configureNavigationBar() return true } //MARK: - Mixpanel func configureMixpanel() { let device = UIDevice.current.identifierForVendor?.uuidString Mixpanel.initialize(token: Parameters.MixpanelToken.rawValue) Mixpanel.mainInstance().identify(distinctId: device!) } //MARK: - Interface func configureNavigationBar() { //Title let titleFont = UIFont(name: Fonts.Medium.rawValue, size: 17.0)! let titleColor = UIColor.colorFrom(hex: "333333") UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : titleFont, NSForegroundColorAttributeName : titleColor] //Кастомизация стрелки назад let backArrow = UIImage(named: "Navigation Bar Back Arrow")! UINavigationBar.appearance().backIndicatorImage = backArrow UINavigationBar.appearance().backIndicatorTransitionMaskImage = backArrow //Трюк для скрытия текста в кнопке назад UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clear], for: .normal) UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clear], for: .highlighted) //Тень под панелью UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UINavigationBar.appearance().shadowImage = UIImage(named: "Navigation Bar Shadow") } }
b0a81d434c8042afb0dfff28dc135900
34.509091
144
0.693804
false
true
false
false
renshu16/DouyuSwift
refs/heads/master
DouyuSwift/DouyuSwift/Classes/Home/View/AmuseMenuView.swift
mit
1
// // AmuseMenuView.swift // DouyuSwift // // Created by ToothBond on 16/12/5. // Copyright © 2016年 ToothBond. All rights reserved. // import UIKit private let kMenuViewCellID : String = "MenuViewCellID" class AmuseMenuView: UIView { @IBOutlet weak var collectionView: UICollectionView! var groups : [AnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuViewCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension AmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let pageNum = (groups!.count - 1)/8 + 1 pageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuViewCellID, for: indexPath) as! AmuseMenuViewCell setupCellDataWithCell(cell: cell, indexPath: indexPath) return cell } func setupCellDataWithCell(cell:AmuseMenuViewCell,indexPath:IndexPath) { let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } cell.groups = Array(groups![startIndex...endIndex]) } } extension AmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = Int(scrollView.contentOffset.x / scrollView.bounds.width) print("pageIndex = \(pageIndex)") pageControl.currentPage = pageIndex } } extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView; } }
e8f2fd8ec3ba2d94b0156c34257de2df
28.554217
129
0.660823
false
false
false
false