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
theodinspire/FingerBlade
refs/heads/development
FingerBlade/SampleStore.swift
gpl-3.0
1
// // SampleStore.swift // FingerBlade // // Created by Cormack on 2/10/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import Foundation import UIKit /// An object for storing the gesture sample data as well as organize their collection class SampleStore { private var trails = [CutLine : [[CGPoint]]]() var cutsToMake: Int var current: CutLine? var cutList: [CutLine] var iter: IndexingIterator<[CutLine]> /// First cut of the sequence for the store var first: CutLine? { get { return cutList.first } } /// Consructor /// /// - Parameters: /// - numCuts: Number of gestures to collect for each CutLine /// - cuts: The CutLine guestures collected by the object init(cutsToMake numCuts: Int, cutList cuts: [CutLine]) { cutsToMake = numCuts cutList = cuts iter = cutList.makeIterator() } /// Default constructor, using every CutLine with 10 lines each convenience init () { self.init(cutsToMake: 10, cutList: CutLine.all) //3, cutList: [CutLine.fendManMez, .sotManTut, .punCav]) } /// Add a sample /// /// - Parameters: /// - trail: Sample to be added /// - cut: CutLine described by the sample func put(trail: [CGPoint], into cut: CutLine) { if trails.keys.contains(cut) { trails[cut]?.append(trail) } else { trails[cut] = [trail] } } /// Obtain samples /// /// - Parameter cut: The CutLine which the samples describe /// - Returns: Array of gesture trail samples func get(from cut: CutLine) -> [[CGPoint]]? { return trails[cut] } /// Get the next cut of the sequence /// /// - Returns: Next cut whose samples are to be collected func next() -> CutLine? { current = iter.next() return current } /// Descriptive string of the sample corpus. Organized and labeled by CutLine, each line is a sample consisting of the cartesian coordinates describing the sample /// /// - Returns: A verbose string func getVerboseString() -> String { var text = "" for (cut, trailList) in trails { text += cut.rawValue + "\n" for trail in trailList { for (i, point) in trail.enumerated() { text += (i != 0 ? ", " : "") + String(describing: point) } text += "\n" } text += "\n" } return text } }
00282b61d3a52538a66d99a854eb6d40
27.593407
166
0.558417
false
false
false
false
mengheangrat/Apsara
refs/heads/master
Apsara/Classes/ApsaraButton.swift
mit
1
// // CustomizeButton.swift // Apasara // // Created by Rat Mengheang on 1/27/17. import Foundation @IBDesignable class ApsaraButton: UIButton{ @IBInspectable var cornerRadius: CGFloat = 0 { didSet{ layer.cornerRadius = cornerRadius } } @IBInspectable var borderWidth: CGFloat = 0 { didSet{ layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor = UIColor.gray { didSet{ layer.borderColor = borderColor.cgColor } } }
0d3f0bf62aeefdb92340ec44cc9efbda
17.393939
60
0.546952
false
false
false
false
huyphamthanh8290/HPUIViewExtensions
refs/heads/master
Pod/Classes/ViewExtensions/HPLabel.swift
mit
1
// // HPLabel.swift // Pods // // Created by Huy Pham on 11/2/15. // // import UIKit @IBDesignable public class HPLabel: UILabel { var internalProxy: UIInternalProxy? // MARK: Init override init(frame: CGRect) { super.init(frame: frame) internalProxy = UIInternalProxy(subjectView: self) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) internalProxy = UIInternalProxy(subjectView: self) } // MARK: Text override public var text: String? { get { return super.text } set(newText) { super.text = Utils.localizeWithDefinedMode(text: newText) } } // MARK: Border @IBInspectable public var borderColor: UIColor? { didSet { self.internalProxy?.borderColor = self.borderColor } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { self.internalProxy?.borderWidth = self.borderWidth } } // MARK: Corner @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { self.internalProxy?.cornerRadius = self.cornerRadius } } @IBInspectable public var topLeftRounded: Bool = true { didSet { self.internalProxy?.topLeftRounded = self.topLeftRounded } } @IBInspectable public var topRightRounded: Bool = true { didSet { self.internalProxy?.topRightRounded = self.topRightRounded } } @IBInspectable public var botLeftRounded: Bool = true { didSet { self.internalProxy?.botLeftRounded = self.botLeftRounded } } @IBInspectable public var botRightRounded: Bool = true { didSet { self.internalProxy?.botRightRounded = self.botRightRounded } } // MARK: Padding @IBInspectable public var paddingStart: Float = 0 @IBInspectable public var paddingEnd: Float = 0 @IBInspectable public var paddingTop: Float = 0 @IBInspectable public var paddingBottom: Float = 0 override public func drawText(in rect: CGRect) { super.drawText(in: makeRectInset(bounds: bounds)) } override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { return super.textRect(forBounds: makeRectInset(bounds: bounds), limitedToNumberOfLines: numberOfLines) } private func makeRectInset(bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(CGFloat(paddingTop), CGFloat(paddingStart), CGFloat(paddingBottom), CGFloat(paddingEnd))) } public override func didMoveToWindow() { for ct: NSLayoutConstraint in self.constraints { if type(of: ct) !== NSLayoutConstraint.self { continue } if (ct.firstAttribute == NSLayoutAttribute.height && ct.firstItem as? HPLabel == self) || (ct.secondAttribute == NSLayoutAttribute.height && ct.secondItem as? HPLabel == self) { print(ct.constant) ct.constant += (CGFloat(paddingTop) + CGFloat(paddingBottom)) break } } } }
7fd79ec1bbcad80f9b26ea00d7da5c1e
25.92
189
0.599703
false
false
false
false
danielallsopp/Charts
refs/heads/master
Tests/Charts/BarChartTests.swift
apache-2.0
1
import XCTest import FBSnapshotTestCase @testable import Charts class BarChartTests: FBSnapshotTestCase { var chart: BarChartView! var dataSet: BarChartDataSet! override func setUp() { super.setUp() // Set to `true` to re-capture all snapshots self.recordMode = false // Sample data let values: [Double] = [8, 104, 81, 93, 52, 44, 97, 101, 75, 28, 76, 25, 20, 13, 52, 44, 57, 23, 45, 91, 99, 14, 84, 48, 40, 71, 106, 41, 45, 61] var entries: [ChartDataEntry] = Array() var xValues: [String] = Array() for (i, value) in values.enumerate() { entries.append(BarChartDataEntry.init(value: value, xIndex: i)) xValues.append("\(i)") } dataSet = BarChartDataSet(yVals: entries, label: "Bar chart unit test data") chart = BarChartView(frame: CGRectMake(0, 0, 480, 350)) chart.backgroundColor = NSUIColor.clearColor() chart.leftAxis.axisMinValue = 0.0 chart.rightAxis.axisMinValue = 0.0 chart.data = BarChartData(xVals: xValues, dataSet: dataSet) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDefaultValues() { FBSnapshotVerifyView(chart) } func testHidesValues() { dataSet.drawValuesEnabled = false FBSnapshotVerifyView(chart) } func testHideLeftAxis() { chart.leftAxis.enabled = false FBSnapshotVerifyView(chart) } func testHideRightAxis() { chart.rightAxis.enabled = false FBSnapshotVerifyView(chart) } func testHideHorizontalGridlines() { chart.leftAxis.drawGridLinesEnabled = false chart.rightAxis.drawGridLinesEnabled = false FBSnapshotVerifyView(chart) } func testHideVerticalGridlines() { chart.xAxis.drawGridLinesEnabled = false FBSnapshotVerifyView(chart) } }
e534d19ea4608ce6f7692f242c18b29f
25.926829
111
0.57971
false
true
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/View/CGSSSearchBar.swift
mit
1
// // CGSSSearchBar.swift // DereGuide // // Created by zzk on 2017/1/14. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit class CGSSSearchBar: UISearchBar { override init(frame: CGRect) { super.init(frame: frame) // 为了避免push/pop时闪烁,searchBar的背景图设置为透明的 for sub in self.subviews.first!.subviews { if let iv = sub as? UIImageView { iv.alpha = 0 } } autocapitalizationType = .none autocorrectionType = .no returnKeyType = .search enablesReturnKeyAutomatically = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { // fix a layout issue in iOS 11 if #available(iOS 11.0, *) { return UILayoutFittingExpandedSize } else { return super.intrinsicContentSize } } } class SearchBarWrapper: UIView { let searchBar: CGSSSearchBar init(searchBar: CGSSSearchBar) { self.searchBar = searchBar super.init(frame: .zero) addSubview(searchBar) searchBar.snp.makeConstraints { (make) in make.height.equalTo(44) make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return UILayoutFittingExpandedSize } }
8cc55abe05b98d5eee30d64e84a239e9
23.261538
59
0.599239
false
false
false
false
zhou9734/Warm
refs/heads/master
Warm/Classes/Home/View/CBtnContainerView.swift
mit
1
// // CBtnContainerView.swift // Warm // // Created by zhoucj on 16/9/25. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class CBtnContainerView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ //三个按钮 let btnWidth = (ScreenWidth - 2) / 3 experiDetailBtn.frame = CGRect(x: 0 , y: 0, width: btnWidth, height: 45.0) addSubview(experiDetailBtn) experiDetailBtn.selected = true leftSpliteView.frame = CGRect(x: btnWidth, y: 7, width: 1.0, height: 30.0) addSubview(leftSpliteView) userBtn.frame = CGRect(x: btnWidth + 1, y: 0, width: btnWidth, height: 45.0) addSubview(userBtn) rightSpliteView.frame = CGRect(x: 2*btnWidth + 1, y: 7, width: 1.0, height: 30.0) addSubview(rightSpliteView) contactBtn.frame = CGRect(x: 2*btnWidth + 2, y: 0, width: btnWidth, height: 45.0) addSubview(contactBtn) } private lazy var experiDetailBtn: UIButton = { let btn = UIButton() btn.setTitle("体验详情", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Selected) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.titleLabel?.textAlignment = .Center btn.tag = 1 btn.addTarget(self, action: Selector("experiDetailBtnClick:"), forControlEvents: .TouchUpInside) btn.backgroundColor = Color_GlobalBackground return btn }() private lazy var leftSpliteView : UIView = { let v = UIView() v.backgroundColor = SpliteColor return v }() private lazy var userBtn: UIButton = { let btn = UIButton() btn.setTitle("手艺人", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Selected) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.titleLabel?.textAlignment = .Center btn.tag = 2 btn.addTarget(self, action: Selector("experiDetailBtnClick:"), forControlEvents: .TouchUpInside) btn.backgroundColor = Color_GlobalBackground return btn }() private lazy var rightSpliteView : UIView = { let v = UIView() v.backgroundColor = SpliteColor return v }() private lazy var contactBtn: UIButton = { let btn = UIButton() btn.setTitle("如何体验", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Selected) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.titleLabel?.textAlignment = .Center btn.tag = 3 btn.addTarget(self, action: Selector("experiDetailBtnClick:"), forControlEvents: .TouchUpInside) btn.backgroundColor = Color_GlobalBackground return btn }() @objc private func experiDetailBtnClick(btn: UIButton){ NSNotificationCenter.defaultCenter().postNotificationName(SectionForSectionIndex, object: btn.tag) } }
ab8e6e7efee9e5ac506167e78b5f26f5
36.975904
106
0.643084
false
false
false
false
qasim/CDFLabs
refs/heads/master
CDFLabs/Locations/LocationsViewController.swift
mit
1
// // LocationsViewController.swift // CDFLabs // // Created by Qasim Iqbal on 12/28/15. // Copyright © 2015 Qasim Iqbal. All rights reserved. // import UIKit class LocationsViewController: UINavigationController, UITableViewDelegate, UITableViewDataSource { var contentViewController: UIViewController? var tableView: UITableView? override func loadView() { super.loadView() self.loadContentView() self.pushViewController(contentViewController!, animated: false) /* let infoButton = UIButton(type: .InfoLight) infoButton.tintColor = UIColor.whiteColor() infoButton.addTarget(self, action: #selector(self.info), forControlEvents: .TouchUpInside) let infoBarButton = UIBarButtonItem(customView: infoButton) self.contentViewController!.navigationItem.leftBarButtonItem = infoBarButton */ } func loadContentView() { self.contentViewController = UIViewController() self.contentViewController!.title = "Locations" let contentView = self.contentViewController!.view self.loadTableView() contentView.addSubview(self.tableView!) let viewsDict: [String: AnyObject] = [ "tableView": self.tableView! ] let options = NSLayoutFormatOptions(rawValue: 0) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "|[tableView]|", options: options, metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "V:|[tableView]|", options: options, metrics: nil, views: viewsDict)) } func loadTableView() { self.tableView = CLTableView() self.tableView?.estimatedRowHeight = CLTable.printerCellHeight self.tableView?.rowHeight = UITableViewAutomaticDimension self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { return BahenLocationViewCell() } else { return NXLocationViewCell() } } }
668b1c13a7d2a6d8c35a44341213b715
31.68
109
0.656875
false
false
false
false
CogMachines/arnold
refs/heads/master
FastText/FastTextPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play // MacOS import Cocoa // Local import FastText #if true let fastText = FastText() var trainingData = [TrainingData]() trainingData.append(TrainingData(label: "query_person", data: "Do you know Melanie?")) trainingData.append(TrainingData(label: "query_person", data: "Do you know Reggie?")) print("Begin training...") let modelPath = fastText.trainSupervised(trainingData) print("Training complete: " + modelPath) fastText.predict(modelPath, text: "Do you know Poppy?") #endif #if false //: ## NSLinguisticTagger let text: NSString = "Do you know about Reggie Bird?" // Create a tagger with "nameType" scheme to find named entities let tagger = NSLinguisticTagger(tagSchemes: [.nameType], options: 0) tagger.string = String(text) // Whole range of text. let range: NSRange = NSMakeRange(0, text.length) // Consider compound names, like Apple Inc. as one word. let options: NSLinguisticTagger.Options = [.omitPunctuation, .omitWhitespace, .joinNames] // Interested in all names. //let tags: [NSLinguisticTag] = [.personalName, .placeName, .organizationName] var personals: [String] = [] var places: [String] = [] var organizations: [String] = [] // Enumerate through recognized tokens. tagger.enumerateTags(in: range, unit: .word, scheme: .nameType, options: options) { (tag, tokenRange, stop) in guard let tag = tag else { return } let token = text.substring(with: tokenRange) let word = (text as NSString).substring(with: tokenRange) print("\(word): \(tag)") switch tag { case .personalName: personals.append(token) case .placeName: places.append(token) case .organizationName: organizations.append(token) default: break } } print(""" Persons:\n\(personals)\n\n Places:\n\(places)\n\n Organizations:\n\(organizations)\n\n """) #endif
91394d6af2a9fd452b6a6b6eaa6d29dc
25.355263
89
0.659511
false
false
false
false
peteratseneca/dps923winter2015
refs/heads/master
Week_10/Places/Classes/PlaceList.swift
mit
1
// // PlaceList.swift // Scroll // // Created by Peter McIntyre on 2015-04-11. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit import CoreData // Notice the protocol conformance class PlaceList: UITableViewController, NSFetchedResultsControllerDelegate { // MARK: - Private properties var frc: NSFetchedResultsController! // MARK: - Properties // Passed in by the app delegate during app initialization var model: Model! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = "Places List" // Configure and load the fetched results controller (frc) frc = model.frc_place // This controller will be the frc delegate frc.delegate = self; // No predicate (which means the results will NOT be filtered) frc.fetchRequest.predicate = nil; // Create an error object var error: NSError? = nil // Perform fetch, and if there's an error, log it if !frc.performFetch(&error) { println(error?.description) } } // MARK: - Table view methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.frc.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.frc.sections![section] as! NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item: AnyObject = frc.objectAtIndexPath(indexPath) cell.textLabel!.text = item.valueForKey("address")! as? String } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toPlaceDetail" { // Get a reference to the destination view controller let vc = segue.destinationViewController as! PlaceDetail // From the data source (the fetched results controller)... // Get a reference to the object for the tapped/selected table view row let item = frc.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) as! Place // Pass on the object vc.item = item // Configure the view if you wish vc.title = item.address } } }
eff928bcf8041e4417ea5fdaad0cacb6
30.4
118
0.620181
false
false
false
false
HassanEskandari/Eureka
refs/heads/master
Source/Rows/SuggestionRow/SuggestionCell.swift
mit
1
// // SuggestionCell.swift // // Adapted from Mathias Claassen 4/14/16 by Hélène Martin 8/11/16 // // import Foundation import UIKit /// General suggestion cell. Create a subclass or use SuggestionCollectionCell or SuggestionTableCell. open class SuggestionCell<T: SuggestionValue>: _FieldCell<T>, CellType { let cellReuseIdentifier = "Eureka.SuggestionCellIdentifier" var suggestions: [T]? required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func setup() { super.setup() textField.autocorrectionType = .no textField.autocapitalizationType = .sentences } //MARK: UITextFieldDelegate open override func textFieldDidBeginEditing(_ textField: UITextField) { formViewController()?.beginEditing(of: self) formViewController()?.textInputDidBeginEditing(textField, cell: self) textField.selectAll(nil) if let text = textField.text { setSuggestions(text) } } open override func textFieldDidChange(_ textField: UITextField) { super.textFieldDidChange(textField) if let text = textField.text { setSuggestions(text) } } open override func textFieldDidEndEditing(_ textField: UITextField) { formViewController()?.endEditing(of: self) formViewController()?.textInputDidEndEditing(textField, cell: self) textField.text = row.displayValueFor?(row.value) } func setSuggestions(_ string: String) {} func reload() {} }
82b7def179dd5d1d1956dfbf1193cd0a
29.12069
102
0.670864
false
false
false
false
appzzman/JMCBeaconManager
refs/heads/master
Example/Pods/JMCiBeaconManager/JMCiBeaconManager/Classes/BeaconShape.swift
bsd-2-clause
5
// // BeaconShape.swift // iBeaconManager // // Created by Felipe on 6/23/16. // Copyright © 2016 Janusz Chudzynski. All rights reserved. // import UIKit import CoreLocation class BeaconShape { var shapeLayer : CAShapeLayer! var id = "" var beacon:iBeacon! var speed = 0.0 /// t is a parametric variable in the range 0 to 2π, interpreted geometrically as the angle that the ray from (a, b) to (x, y) makes with the positive x-axis. var t : CGFloat = 0 var blink = false var distance: CLProximity! var point: CGPoint! var radius: CGFloat { get{ if UIScreen.mainScreen().scale > 2{ return 15 } return 10 } set{ } } var color = UIColor(red: 0.392, green: 1.000, blue: 0.050, alpha: 1.000) /// Increments the t value according to the speed func nextT() -> CGFloat{ var s = speed if distance == CLProximity.Unknown{ s += speed * 0.35 } if distance == CLProximity.Far{ s += speed * 0.25 } if distance == CLProximity.Near{ s += speed * 0.12 } t += CGFloat(s) if t > CGFloat(2 * M_PI){ t = 0 } return t } }
18b757fdf17abd5237db28d71dc1e9ba
20.818182
162
0.47811
false
false
false
false
Flinesoft/HandyUIKit
refs/heads/main
Frameworks/HandyUIKit/Extensions/StringExt.swift
mit
1
// Copyright © 2017 Flinesoft. All rights reserved. import UIKit extension String { /// Calculates and returns the height needed to fit the text into a width-constrained rect. /// /// - Parameters: /// - fixedWidth: The fixed width of the rect. /// - font: The font of the text to calculate for. /// - Returns: The height needed to fit the text into a width-constrained rect. public func height(forFixedWidth fixedWidth: CGFloat, font: UIFont) -> CGFloat { let constraintSize = CGSize(width: fixedWidth, height: .greatestFiniteMagnitude) return ceil(rect(for: constraintSize, font: font).height) } /// Calculates and returns the width needed to fit the text into a height-constrained rect. /// /// - Parameters: /// - fixedHeight: The fixed height of the rect. /// - font: The font of the text to calculate for. /// - Returns: The width needed to fit the text into a height-constrained rect. public func width(forFixedHeight fixedHeight: CGFloat, font: UIFont) -> CGFloat { let constraintSize = CGSize(width: .greatestFiniteMagnitude, height: fixedHeight) return ceil(rect(for: constraintSize, font: font).width) } private func rect(for constraintSize: CGSize, font: UIFont) -> CGRect { let attributes = [NSAttributedString.Key.font: font] return (self as NSString).boundingRect(with: constraintSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) } /// - Returns: A hyphenated NSAttributedString with justified alignment and word wrapping line break mode. public func hyphenated() -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.hyphenationFactor = 1.0 paragraphStyle.alignment = .justified paragraphStyle.lineBreakMode = .byWordWrapping return NSAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle]) } /// Superscripts substrings of structure ^{substring} and subscripts substrings of structure _{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// /// - Returns: The resulting attributed string with superscripted and subscripted substrings. public func superAndSubscripted(font: UIFont) -> NSAttributedString { NSAttributedString(string: self).superAndSubscripted(font: font) } /// Superscripts substrings of structure ^{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// /// - Returns: The resulting attributed string with superscripted substrings. public func superscripted(font: UIFont) -> NSAttributedString { NSAttributedString(string: self).superscripted(font: font) } /// Subscripts substrings of structure _{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// /// - Returns: The resulting attributed string with subscripted substrings. public func subscripted(font: UIFont) -> NSAttributedString { NSAttributedString(string: self).subscripted(font: font) } }
4dfba660bca86891fa9f6dfbe89488c0
44.25
140
0.691529
false
false
false
false
box/box-ios-sdk
refs/heads/main
Sources/Responses/DevicePin.swift
apache-2.0
1
// // DevicePin.swift // BoxSDK-iOS // // Created by Cary Cheng on 8/27/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Defines a device pin which allows the enterprise to control devices connecting to it. public class DevicePin: BoxModel { // MARK: - BoxModel private static var resourceType: String = "device_pinner" /// Box item type public var type: String public private(set) var rawData: [String: Any] // MARK: - Properties /// The ID of the device pinner object. public let id: String /// The user that the device pin belongs to. public let ownedBy: User? /// The type of device being pinned. public let productName: String? /// The time the device pin was created. public let createdAt: Date? /// The time the device pin was modified. public let modifiedAt: Date? /// Initializer. /// /// - Parameter json: JSON dictionary. /// - Throws: Decoding error. public required init(json: [String: Any]) throws { guard let itemType = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } guard itemType == DevicePin.resourceType else { throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [DevicePin.resourceType])) } rawData = json type = itemType id = try BoxJSONDecoder.decode(json: json, forKey: "id") ownedBy = try BoxJSONDecoder.optionalDecode(json: json, forKey: "owned_by") productName = try BoxJSONDecoder.optionalDecode(json: json, forKey: "product_name") createdAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "created_at") modifiedAt = try BoxJSONDecoder.optionalDecodeDate(json: json, forKey: "modified_at") } }
2d89d9b7a56839e87b76db2805c8943c
31.578947
129
0.656435
false
false
false
false
xBrux/BXIcon
refs/heads/master
BXIconDemo/ViewController.swift
mit
1
// // ViewController.swift // BXIconDemo // // Created by BRUX on 10/15/15. // Copyright © 2015 Brux. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var iconView: BXIconView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let image = BXIcon().iconImage(iconName:"bowl", imageSize: CGSize(width: 100, height: 100), fillColor: UIColor.redColor()) imageView.image = image } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showButtonTouched(sender: AnyObject) { guard let iconName = textField.text else { return } let image = BXIcon().iconImage(iconName:iconName, imageSize: CGSize(width: 100, height: 100), fillColor: UIColor.redColor()) imageView.image = image iconView.iconName = iconName } }
6bde0b0de43f6fd5d77062a0851a44db
28.973684
132
0.66813
false
false
false
false
Glucosio/glucosio-ios
refs/heads/develop
Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift
apache-2.0
4
// // LineChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet { @objc(LineChartMode) public enum Mode: Int { case linear case stepped case cubicBezier case horizontalBezier } private func initialize() { // default color circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) } public required init() { super.init() initialize() } public override init(values: [ChartDataEntry]?, label: String?) { super.init(values: values, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// The drawing mode for this line dataset /// /// **default**: Linear open var mode: Mode = Mode.linear private var _cubicIntensity = CGFloat(0.2) /// Intensity for cubic lines (min = 0.05, max = 1) /// /// **default**: 0.2 open var cubicIntensity: CGFloat { get { return _cubicIntensity } set { _cubicIntensity = newValue if _cubicIntensity > 1.0 { _cubicIntensity = 1.0 } if _cubicIntensity < 0.05 { _cubicIntensity = 0.05 } } } /// The radius of the drawn circles. open var circleRadius = CGFloat(8.0) /// The hole radius of the drawn circles open var circleHoleRadius = CGFloat(4.0) open var circleColors = [NSUIColor]() /// - returns: The color at the given index of the DataSet's circle-color array. /// Performs a IndexOutOfBounds check by modulus. open func getCircleColor(atIndex index: Int) -> NSUIColor? { let size = circleColors.count let index = index % size if index >= size { return nil } return circleColors[index] } /// Sets the one and ONLY color that should be used for this DataSet. /// Internally, this recreates the colors array and adds the specified color. open func setCircleColor(_ color: NSUIColor) { circleColors.removeAll(keepingCapacity: false) circleColors.append(color) } open func setCircleColors(_ colors: NSUIColor...) { circleColors.removeAll(keepingCapacity: false) circleColors.append(contentsOf: colors) } /// Resets the circle-colors array and creates a new one open func resetCircleColors(_ index: Int) { circleColors.removeAll(keepingCapacity: false) } /// If true, drawing circles is enabled open var drawCirclesEnabled = true /// - returns: `true` if drawing circles for this DataSet is enabled, `false` ifnot open var isDrawCirclesEnabled: Bool { return drawCirclesEnabled } /// The color of the inner circle (the circle-hole). open var circleHoleColor: NSUIColor? = NSUIColor.white /// `true` if drawing circles for this DataSet is enabled, `false` ifnot open var drawCircleHoleEnabled = true /// - returns: `true` if drawing the circle-holes is enabled, `false` ifnot. open var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled } /// This is how much (in pixels) into the dash pattern are we starting from. open var lineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] open var lineDashLengths: [CGFloat]? /// Line cap type, default is CGLineCap.Butt open var lineCapType = CGLineCap.butt /// formatter for customizing the position of the fill-line private var _fillFormatter: IFillFormatter = DefaultFillFormatter() /// Sets a custom IFillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic. open var fillFormatter: IFillFormatter? { get { return _fillFormatter } set { _fillFormatter = newValue ?? DefaultFillFormatter() } } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! LineChartDataSet copy.circleColors = circleColors copy.circleRadius = circleRadius copy.cubicIntensity = cubicIntensity copy.lineDashPhase = lineDashPhase copy.lineDashLengths = lineDashLengths copy.lineCapType = lineCapType copy.drawCirclesEnabled = drawCirclesEnabled copy.drawCircleHoleEnabled = drawCircleHoleEnabled copy.mode = mode return copy } }
a4b86255cc54cd74522c9925acf1c5c6
27.949438
155
0.608772
false
false
false
false
kesun421/firefox-ios
refs/heads/master
Client/Frontend/AuthenticationManager/PasscodeEntryViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import Shared import SwiftKeychainWrapper /// Delegate available for PasscodeEntryViewController consumers to be notified of the validation of a passcode. @objc protocol PasscodeEntryDelegate: class { func passcodeValidationDidSucceed() @objc optional func userDidCancelValidation() } /// Presented to the to user when asking for their passcode to validate entry into a part of the app. class PasscodeEntryViewController: BasePasscodeViewController { weak var delegate: PasscodeEntryDelegate? fileprivate var passcodePane: PasscodePane override init() { let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() passcodePane = PasscodePane(title:nil, passcodeSize:authInfo?.passcode?.count ?? 6) super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = AuthenticationStrings.enterPasscodeTitle view.addSubview(passcodePane) passcodePane.snp.makeConstraints { make in make.bottom.left.right.equalTo(self.view) make.top.equalTo(self.topLayoutGuide.snp.bottom) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) passcodePane.codeInputView.delegate = self // Don't show the keyboard or allow typing if we're locked out. Also display the error. if authenticationInfo?.isLocked() ?? false { displayLockoutError() passcodePane.codeInputView.isUserInteractionEnabled = false } else { passcodePane.codeInputView.becomeFirstResponder() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if authenticationInfo?.isLocked() ?? false { passcodePane.codeInputView.isUserInteractionEnabled = false passcodePane.codeInputView.resignFirstResponder() } else { passcodePane.codeInputView.becomeFirstResponder() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } override func dismissAnimated() { delegate?.userDidCancelValidation?() super.dismissAnimated() } } extension PasscodeEntryViewController: PasscodeInputViewDelegate { func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) { if let passcode = authenticationInfo?.passcode, passcode == code { authenticationInfo?.recordValidation() KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo) delegate?.passcodeValidationDidSucceed() } else { passcodePane.shakePasscode() failIncorrectPasscode(inputView) passcodePane.codeInputView.resetCode() // Store mutations on authentication info object KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo) } } }
c421348bbc1ee938a3aeb61533787aae
35.978261
112
0.694004
false
false
false
false
google/swift-benchmark
refs/heads/main
Sources/Benchmark/BenchmarkState.swift
apache-2.0
1
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Benchmark state is used to collect the /// benchmark measurements and view the settings it /// was configured with. /// /// Apart from the standard benchmark loop, you can also use /// it with customized benchmark measurement sections via either /// `start`/`end` or `measure` functions. public struct BenchmarkState { var startTime: UInt64 var endTime: UInt64 var measurements: [Double] /// A mapping from counters to their corresponding values. public var counters: [String: Double] /// Number of iterations to be run. public let iterations: Int /// Aggregated settings for the current benchmark run. public let settings: BenchmarkSettings @inline(__always) init() { self.init(iterations: 0, settings: BenchmarkSettings()) } @inline(__always) init(iterations: Int, settings: BenchmarkSettings) { self.startTime = 0 self.endTime = 0 self.measurements = [] self.measurements.reserveCapacity(iterations) self.counters = [:] self.iterations = iterations self.settings = settings } /// Explicitly marks the start of the measurement section. @inline(__always) public mutating func start() { self.endTime = 0 self.startTime = now() } /// Explicitly marks the end of the measurement section /// and records the time since start of the benchmark. @inline(__always) public mutating func end() throws { let value = now() if self.endTime == 0 { self.endTime = value try record() } } @inline(__always) mutating func record() throws { if measurements.count < iterations { measurements.append(self.duration) } else { throw BenchmarkTermination() } } @inline(__always) var duration: Double { return Double(self.endTime - self.startTime) } @inline(__always) mutating func loop(_ benchmark: AnyBenchmark) throws { while measurements.count < iterations { benchmark.setUp() start() try benchmark.run(&self) try end() benchmark.tearDown() } } /// Run the closure within within benchmark measurement section. /// It may throw errors to propagate early termination to /// the outer benchmark loop. @inline(__always) public mutating func measure(f: () -> Void) throws { start() f() try end() } /// Increment a counter by a given value (with a default of 1). /// If counter has never been set before, it starts with zero as the /// initial value. @inline(__always) public mutating func increment(counter name: String, by value: Double = 1) { if let oldValue = counters[name] { counters[name] = oldValue + value } else { counters[name] = value } } }
4e7497e4ff32698739d0d733452e0540
29.594828
80
0.629191
false
false
false
false
neonichu/SPMediaKeyTap
refs/heads/master
SPMediaKeys.swift
bsd-3-clause
1
import AppKit public enum SPMediaKey { case PlayPause case Rewind case Forward } public typealias SPMediaKeyObserver = ((mediaKey: SPMediaKey) -> Void) public class SPMediaKeys: NSObject { public override class func initialize() { NSUserDefaults.standardUserDefaults().registerDefaults([kMediaKeyUsingBundleIdentifiersDefaultsKey: SPMediaKeyTap.defaultMediaKeyUserBundleIdentifiers()]) } private var keyTap: SPMediaKeyTap! private var observer: SPMediaKeyObserver? public func watch(newObserver: SPMediaKeyObserver) { keyTap = SPMediaKeyTap(delegate: self) if SPMediaKeyTap.usesGlobalMediaKeyTap() { keyTap.startWatchingMediaKeys() } observer = newObserver } public override func mediaKeyTap(keyTap: SPMediaKeyTap!, receivedMediaKeyEvent event: NSEvent!) { let keyCode = ((event.data1 & 0xFFFF0000) >> 16) let keyFlags = (event.data1 & 0x0000FFFF) let keyIsPressed = (((keyFlags & 0xFF00) >> 8)) == 0xA let keyRepeat = (keyFlags & 0x1) if keyIsPressed { switch Int32(keyCode) { case NX_KEYTYPE_PLAY: observer?(mediaKey:.PlayPause) break case NX_KEYTYPE_FAST: observer?(mediaKey:.Forward) break case NX_KEYTYPE_REWIND: observer?(mediaKey:.Rewind) break default: break // More cases defined in hidsystem/ev_keymap.h } } } }
a2296080287583813a1e18cff0facba6
27
162
0.605263
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Common/Buttons/Close/CloseButton.swift
apache-2.0
1
/* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation final class CloseButton: UIButton, Themable { // MARK: - Constants private enum CircleBackgroundConstants { static let height: CGFloat = 30.0 static let highlightedAlha: CGFloat = 0.5 static let normalAlha: CGFloat = 1.0 } // MARK: - Properties // MARK: Private private var theme: Theme? private var circleBackgroundView: UIView! // MARK: Public override var isHighlighted: Bool { didSet { self.circleBackgroundView.alpha = self.isHighlighted ? CircleBackgroundConstants.highlightedAlha : CircleBackgroundConstants.normalAlha } } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clear self.setImage(Asset.Images.closeButton.image, for: .normal) self.setupCircleView() self.update(theme: ThemeService.shared().theme) } override func layoutSubviews() { super.layoutSubviews() self.sendSubviewToBack(self.circleBackgroundView) self.circleBackgroundView.layer.cornerRadius = self.circleBackgroundView.bounds.height/2 } // MARK: - Private private func setupCircleView() { let rect = CGRect(x: 0, y: 0, width: CircleBackgroundConstants.height, height: CircleBackgroundConstants.height) let view = UIView(frame: rect) view.translatesAutoresizingMaskIntoConstraints = false view.isUserInteractionEnabled = false view.layer.masksToBounds = true self.addSubview(view) NSLayoutConstraint.activate([ view.heightAnchor.constraint(equalToConstant: CircleBackgroundConstants.height), view.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0), view.centerXAnchor.constraint(equalTo: self.centerXAnchor), view.centerYAnchor.constraint(equalTo: self.centerYAnchor) ]) self.sendSubviewToBack(view) self.circleBackgroundView = view } // MARK: - Themable func update(theme: Theme) { self.theme = theme self.circleBackgroundView.backgroundColor = theme.headerTextSecondaryColor } }
c94e69f0c553684825ea7af31cf73cd9
29.8
147
0.661654
false
false
false
false
e-sites/Bluetonium
refs/heads/master
Source/Models/Device.swift
mit
1
// // Device.swift // Bluetonium // // Created by Dominggus Salampessy on 23/12/15. // Copyright © 2015 E-sites. All rights reserved. // import Foundation import CoreBluetooth /** A `Device` will represent a CBPeripheral. When registering ServiceModels on this device it will automaticly map the characteristics to the correct value. */ public class Device: Equatable { // An array of all registered `ServiceModel` subclasses open var registedServiceModels: [ServiceModel] { return serviceModelManager.registeredServiceModels } // The peripheral it represents. private(set) public var peripheral: CBPeripheral // The ServiceModelManager that will manage all registered `ServiceModels` private(set) var serviceModelManager: ServiceModelManager // MARK: Initializers /** Initalize the `Device` with a Peripheral. - parameter peripheral: The peripheral it will represent */ public init(peripheral: CBPeripheral) { self.peripheral = peripheral self.serviceModelManager = ServiceModelManager(peripheral: peripheral) } // MARK: Public functions /** Register a `ServiceModel` subclass. Register before connecting to the device. - parameter serviceModel: The ServiceModel subclass to register. */ public func register(serviceModel: ServiceModel) { serviceModelManager.register(serviceModel: serviceModel) } // MARK: functions /** Register serviceManager as delegate of the peripheral. This should be done just before connecting/ If done at initalizing it will override the existing peripheral delegate. */ func registerServiceManager() { peripheral.delegate = serviceModelManager } /** Equatable support. */ public static func == (lhs: Device, rhs: Device) -> Bool { return lhs.peripheral.identifier == rhs.peripheral.identifier } }
d5ed345e0063cdb24eca2171d89586c0
27.471429
112
0.684395
false
false
false
false
GregoryMaks/RingLabsTestTask
refs/heads/master
RingTask/Classes/Networking/NetworkService.swift
mit
1
// // NetworkService.swift // RingTask // // Created by Hryhorii Maksiuk on 8/5/17. // Copyright © 2017 Gregory M. All rights reserved. // import Foundation enum NetworkError: Error, Descriptable { case unknown case timeOut case networkConnectionLost case cancelled case other(urlError: Error) init(urlError: Error?) { if let urlError = urlError as NSError?, urlError.domain == NSURLErrorDomain { switch urlError.code { case NSURLErrorNotConnectedToInternet, NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost: self = .networkConnectionLost case NSURLErrorTimedOut: self = .timeOut case NSURLErrorCancelled: self = .cancelled default: self = .other(urlError: urlError) } } else { self = .unknown } } var stringDescription: String { switch self { case .unknown: return "Unknown" case .timeOut: return "Timeout" case .networkConnectionLost: return "Network connection lost" case .cancelled: return "Cancelled" case .other(let urlError): return urlError.localizedDescription } } } protocol NetworkServiceProtocol { @discardableResult func perform(request: URLRequest, completion: @escaping (Result<(Data?, HTTPURLResponse), NetworkError>) -> Void) -> URLSessionDataTask } class NetworkService: NetworkServiceProtocol { private let session: URLSession init() { let configuration = URLSessionConfiguration.default session = URLSession(configuration: configuration) } @discardableResult func perform(request: URLRequest, completion: @escaping (Result<(Data?, HTTPURLResponse), NetworkError>) -> Void) -> URLSessionDataTask { let dataTask = session.dataTask(with: request) { data, response, error in guard let response = response as? HTTPURLResponse else { completion(.failure(NetworkError(urlError: error))) return } completion(.success((data, response))) } dataTask.resume() return dataTask } }
ae0f19c27832256b8cf637c6f9c867b7
25.967391
115
0.571141
false
false
false
false
bud-ci/ios
refs/heads/develop
Owncloud iOs Client/Utils/SystemConstants-swift.swift
gpl-3.0
7
// // SystemConstants-swift.swift // Owncloud iOs Client // // Created by Gonzalo Gonzalez on 6/8/15. // /* Copyright (C) 2014, ownCloud, Inc. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>. */ import Foundation import UIKit let IS_IPHONE = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone let IS_PORTRAIT = UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
aedeb8286172e2eb92c98af46593876a
22.4375
109
0.770667
false
false
false
false
djwbrown/swift
refs/heads/master
test/IRGen/big_types_corner_cases.swift
apache-2.0
1
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIxcx_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @_T0SqWy // CHECK: call void @_T0SqWe // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10f3_uses_f2yyF() // CHECK:call swiftcc void @_T022big_types_corner_cases9BigStructVACycfC(%T22big_types_corner_cases9BigStructV* nocapture dereferenceable // CHECK: call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* nocapture dereferenceable({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18f4_tuple_use_of_f2yyF() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* nocapture dereferenceable({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6StructyAA0eH0V0aH0_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) #0 { // CHECK: getelementptr inbounds %T22big_types_corner_cases8BigClassC, %T22big_types_corner_cases8BigClassC* // CHECK: call void @_T0SqWy // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10enumCalleeyAA9LargeEnumOF(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable(34)) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call %swift.type* @_T0ypMa() // CHECK-64: ret void
b286d4984747cde69333cbb142d0173f
40.536232
363
0.702547
false
false
false
false
DAloG/BlueCap
refs/heads/master
BlueCap/Peripheral/PeripheralManagersViewController.swift
mit
2
// // PeripheralManagersViewController.swift // BlueCap // // Created by Troy Stribling on 8/10/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class PeripheralManagersViewController : UITableViewController { struct MainStoryboard { static let peripheralManagerCell = "PeripheralManagerCell" static let peripheralManagerViewSegue = "PeripheralManagerView" static let peripheralManagerAddSegue = "PeripheralManagerAdd" } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.styleNavigationBar() self.navigationItem.leftBarButtonItem = self.editButtonItem() self.navigationItem.leftBarButtonItem?.tintColor = UIColor.blackColor() } override func viewWillAppear(animated:Bool) { super.viewWillAppear(animated) self.tableView.reloadData() self.navigationItem.title = "Peripherals" } override func viewWillDisappear(animated:Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryboard.peripheralManagerViewSegue { if let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell) { let viewController = segue.destinationViewController as! PeripheralManagerViewController let peripherals = PeripheralStore.getPeripheralNames() viewController.peripheral = peripherals[selectedIndex.row] } } else if segue.identifier == MainStoryboard.peripheralManagerAddSegue { let viewController = segue.destinationViewController as! PeripheralManagerViewController viewController.peripheral = nil } } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int { return PeripheralStore.getPeripheralNames().count } override func tableView(tableView:UITableView, editingStyleForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.Delete } override func tableView(tableView:UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let peripherals = PeripheralStore.getPeripheralNames() PeripheralStore.removePeripheral(peripherals[indexPath.row]) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:UITableViewRowAnimation.Fade) } } override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerCell, forIndexPath: indexPath) as! SimpleCell let peripherals = PeripheralStore.getPeripheralNames() cell.nameLabel.text = peripherals[indexPath.row] return cell } // UITableViewDelegate }
c3851323afefec079d5960cb1c6fd240
38.905882
154
0.713149
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Runtime/SymbolTable.swift
apache-2.0
1
// // SymbolTable.swift // LispKit // // Created by Matthias Zenger on 23/01/2016. // Copyright © 2016-2022 ObjectHub. 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. // /// /// Class `SymbolTable` implements the symbol table for LispKit. It is used for managing /// symbols and their textual representations. Instances of `SymbolTable` provide functionality /// for creating interned symbols for a given identifier and for looking up the identifier /// of a given symbol. /// public final class SymbolTable: Sequence { private let lock = EmbeddedUnfairLock() private var symTable = [String : Symbol]() private let gensymLock = EmbeddedUnfairLock() private var gensymCounter: UInt64 = 0 public let undef = Symbol("<undef>") public let dotdotdot = Symbol("…") public let ellipsis = Symbol("...") public let wildcard = Symbol("_") public let append = Symbol("append") public let cons = Symbol("cons") public let list = Symbol("list") public let quote = Symbol("quote") public let quasiquote = Symbol("quasiquote") public let unquote = Symbol("unquote") public let unquoteSplicing = Symbol("unquote-splicing") public let doubleArrow = Symbol("=>") public let `else` = Symbol("else") public let `if` = Symbol("if") public let lambda = Symbol("lambda") public let `let` = Symbol("let") public let letStar = Symbol("let*") public let letrec = Symbol("letrec") public let define = Symbol("define") public let defineValues = Symbol("define-values") public let makePromise = Symbol("make-promise") public let makeStream = Symbol("make-stream") public let begin = Symbol("begin") public let `import` = Symbol("import") public let export = Symbol("export") public let exportOpen = Symbol("export-open") public let extern = Symbol("extern") public let rename = Symbol("rename") public let only = Symbol("only") public let except = Symbol("except") public let prefix = Symbol("prefix") public let library = Symbol("library") public let and = Symbol("and") public let or = Symbol("or") public let not = Symbol("not") public let condExpand = Symbol("cond-expand") public let include = Symbol("include") public let includeCi = Symbol("include-ci") public let includeLibDecls = Symbol("include-library-declarations") public let scheme = Symbol("scheme") public let r5rs = Symbol("r5rs") public let r5rsSyntax = Symbol("r5rs-syntax") public let starOne = Symbol("*1") public let starTwo = Symbol("*2") public let starThree = Symbol("*3") public init() { self.registerNativeSymbols() } deinit { self.lock.release() self.gensymLock.release() } /// Register internally used symbols. public func registerNativeSymbols() { func register(_ sym: Symbol) { self.symTable[sym.identifier] = sym } register(self.undef) register(self.ellipsis) register(self.wildcard) register(self.append) register(self.cons) register(self.list) register(self.quote) register(self.quasiquote) register(self.unquote) register(self.unquoteSplicing) register(self.doubleArrow) register(self.else) register(self.if) register(self.lambda) register(self.let) register(self.letStar) register(self.letrec) register(self.define) register(self.defineValues) register(self.makePromise) register(self.makeStream) register(self.begin) register(self.`import`) register(self.export) register(self.exportOpen) register(self.extern) register(self.rename) register(self.only) register(self.except) register(self.prefix) register(self.library) register(self.and) register(self.or) register(self.not) register(self.condExpand) register(self.include) register(self.includeCi) register(self.includeLibDecls) register(self.scheme) register(self.r5rs) register(self.r5rsSyntax) register(self.starOne) register(self.starTwo) register(self.starThree) } /// Returns true if there is already an interned symbol for identifier `ident`. public func exists(_ ident: String) -> Bool { self.lock.lock() defer { self.lock.unlock() } return self.symTable[ident] != nil } /// Return a new interned symbol for the given identifier `ident`. public func intern(_ ident: String) -> Symbol { self.lock.lock() defer { self.lock.unlock() } if let sym = self.symTable[ident] { return sym } else { let sym = Symbol(ident) self.symTable[ident] = sym return sym } } /// Generates a new interned symbol. public func gensym(_ basename: String) -> Symbol { self.gensymLock.lock() defer { self.gensymLock.unlock() } var ident: String repeat { ident = basename + String(self.gensymCounter) self.gensymCounter &+= 1 } while self.exists(ident) return self.intern(ident) } /// Generates an interned symbol by concatenating `prefix` and `sym`. public func prefix(_ sym: Symbol, with prefix: Symbol) -> Symbol { return self.intern(prefix.identifier + sym.identifier) } /// Returns a generator for iterating over all symbols of this symbol table. public func makeIterator() -> AnyIterator<Symbol> { var generator = self.symTable.values.makeIterator() return AnyIterator { return generator.next() } } /// Reset symbol table. public func release() { self.symTable = [:] self.gensymCounter = 0 self.registerNativeSymbols() } }
7cf45b8c5ea52a78cda163f64e136dfb
32.221649
95
0.645772
false
false
false
false
magnetsystems/max-ios
refs/heads/master
Tests/Tests/MMModuleSpec.swift
apache-2.0
1
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import Foundation import Quick import Nimble import MagnetMax class MMModuleSpec : QuickSpec { override func spec() { describe("MMModuleSpec") { it("allows you to retrieve configuration") { let module = MMX.sharedInstance expect(module.name).to(equal("MMX")) var isSuccess = false let success = { () -> Void in isSuccess = true } let failure = { (error: NSError) -> Void in isSuccess = false } module.shouldInitializeWithConfiguration([:], success: success, failure: failure) expect(isSuccess).to(beTruthy()) // expect(module.appTokenHandler!?(appID: "appID", deviceID: "deviceID", appToken: "appToken")).to(beNil()) // expect(module.userTokenHandler!?(userID: "userID", deviceID: "deviceID", userToken: "userToken")).to(beNil()) } } } }
d817f667db217e7a3ef9c24cb7b17189
36.906977
127
0.614724
false
false
false
false
philipbannon/iOS
refs/heads/master
ColourPlate/ColourPlate/ColorViewController.swift
gpl-2.0
1
// // ColorViewController.swift // ColourPlate // // Created by Philip Bannon on 07/01/2016. // Copyright © 2016 Philip Bannon. All rights reserved. // import UIKit class ColorViewController: UIViewController { @IBOutlet weak var colorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { if (self.view.backgroundColor == UIColor.redColor() ) { self.colorLabel.text = "Red!" } else if (self.view.backgroundColor == UIColor.blueColor()) { self.colorLabel.text = " Blue!!" } else if (self.view.backgroundColor == UIColor.greenColor()) { self.colorLabel.text = "Green!" } else if (self.view.backgroundColor == UIColor.purpleColor()) { self.colorLabel.text = "Purple!" } else if (self.view.backgroundColor == UIColor(red: 255, green: 0, blue: 128, alpha: 1.0)) { self.colorLabel.text = "Pink!" } else if (self.view.backgroundColor == UIColor.yellowColor()) { self.colorLabel.text = "Yellow!" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
5275c96985e84ebde10664a5d7c1a377
31.119048
101
0.616753
false
false
false
false
tensorflow/swift-models
refs/heads/main
PersonLab/Pose.swift
apache-2.0
1
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow struct Keypoint { var y: Float var x: Float let index: KeypointIndex let score: Float init( heatmapY: Int, heatmapX: Int, index: Int, score: Float, offsets: CPUTensor<Float>, outputStride: Int ) { self.y = Float(heatmapY) * Float(outputStride) + offsets[heatmapY, heatmapX, index] self.x = Float(heatmapX) * Float(outputStride) + offsets[heatmapY, heatmapX, index + KeypointIndex.allCases.count] self.index = KeypointIndex(rawValue: index)! self.score = score } init(y: Float, x: Float, index: KeypointIndex, score: Float) { self.y = y self.x = x self.index = index self.score = score } func isWithinRadiusOfCorrespondingKeypoints(in poses: [Pose], radius: Float) -> Bool { return poses.contains { pose in let correspondingKeypoint = pose.getKeypoint(self.index)! let dy = correspondingKeypoint.y - self.y let dx = correspondingKeypoint.x - self.x let squaredDistance = dy * dy + dx * dx return squaredDistance <= radius * radius } } } enum KeypointIndex: Int, CaseIterable { case nose = 0 case leftEye case rightEye case leftEar case rightEar case leftShoulder case rightShoulder case leftElbow case rightElbow case leftWrist case rightWrist case leftHip case rightHip case leftKnee case rightKnee case leftAnkle case rightAnkle } enum Direction { case fwd, bwd } func getNextKeypointIndexAndDirection(_ keypointId: KeypointIndex) -> [(KeypointIndex, Direction)] { switch keypointId { case .nose: return [(.leftEye, .fwd), (.rightEye, .fwd), (.leftShoulder, .fwd), (.rightShoulder, .fwd)] case .leftEye: return [(.nose, .bwd), (.leftEar, .fwd)] case .rightEye: return [(.nose, .bwd), (.rightEar, .fwd)] case .leftEar: return [(.leftEye, .bwd)] case .rightEar: return [(.rightEye, .bwd)] case .leftShoulder: return [(.leftHip, .fwd), (.leftElbow, .fwd), (.nose, .bwd)] case .rightShoulder: return [(.rightHip, .fwd), (.rightElbow, .fwd), (.nose, .bwd)] case .leftElbow: return [(.leftWrist, .fwd), (.leftShoulder, .bwd)] case .rightElbow: return [(.rightWrist, .fwd), (.rightShoulder, .bwd)] case .leftWrist: return [(.leftElbow, .bwd)] case .rightWrist: return [(.rightElbow, .bwd)] case .leftHip: return [(.leftKnee, .fwd), (.leftShoulder, .bwd)] case .rightHip: return [(.rightKnee, .fwd), (.rightShoulder, .bwd)] case .leftKnee: return [(.leftAnkle, .fwd), (.leftHip, .bwd)] case .rightKnee: return [(.rightAnkle, .fwd), (.rightHip, .bwd)] case .leftAnkle: return [(.leftKnee, .bwd)] case .rightAnkle: return [(.rightKnee, .bwd)] } } /// Maps a pair of keypoint indexes to the appropiate index to be used /// in the displacement forward and backward tensors. let keypointPairToDisplacementIndexMap: [Set<KeypointIndex>: Int] = [ Set([.nose, .leftEye]): 0, Set([.leftEye, .leftEar]): 1, Set([.nose, .rightEye]): 2, Set([.rightEye, .rightEar]): 3, Set([.nose, .leftShoulder]): 4, Set([.leftShoulder, .leftElbow]): 5, Set([.leftElbow, .leftWrist]): 6, Set([.leftShoulder, .leftHip]): 7, Set([.leftHip, .leftKnee]): 8, Set([.leftKnee, .leftAnkle]): 9, Set([.nose, .rightShoulder]): 10, Set([.rightShoulder, .rightElbow]): 11, Set([.rightElbow, .rightWrist]): 12, Set([.rightShoulder, .rightHip]): 13, Set([.rightHip, .rightKnee]): 14, Set([.rightKnee, .rightAnkle]): 15, ] public struct Pose { var keypoints: [Keypoint?] = Array(repeating: nil, count: KeypointIndex.allCases.count) var resolution: (height: Int, width: Int) mutating func add(_ keypoint: Keypoint) { keypoints[keypoint.index.rawValue] = keypoint } func getKeypoint(_ index: KeypointIndex) -> Keypoint? { return keypoints[index.rawValue] } mutating func rescale(to newResolution: (height: Int, width: Int)) { for i in 0..<keypoints.count { if var k = keypoints[i] { k.y *= Float(newResolution.height) / Float(resolution.height) k.x *= Float(newResolution.width) / Float(resolution.width) self.keypoints[i] = k } } self.resolution = newResolution } } extension Pose: CustomStringConvertible { public var description: String { var description = "" for keypoint in keypoints { description.append( "\(keypoint!.index) - \(keypoint!.score) | \(keypoint!.y) - \(keypoint!.x)\n") } return description } }
3dc7d4508b113243e707cdb18b77611c
32.171053
100
0.671361
false
false
false
false
DSanzh/GuideMe-iOS
refs/heads/master
GuideMe/View/Profile/History/HistoryCell.swift
mit
1
// // HistoryCell.swift // GuideMe // // Created by Sanzhar on 9/18/17. // Copyright © 2017 Sanzhar Dauylov. All rights reserved. // import UIKit import EasyPeasy class HistoryCell: UITableViewCell { lazy var mainView: UIView = { let _view = UIView() _view.backgroundColor = .white _view.layer.cornerRadius = 3.0 _view.layer.shadowOffset = .zero _view.layer.shadowRadius = 3.0 _view.layer.shadowOpacity = 0.1 return _view }() lazy var mainImage: UIImageView = { let _image = UIImageView() _image.contentMode = .scaleAspectFill _image.layer.cornerRadius = 48.widthProportion()/2 _image.layer.masksToBounds = true return _image }() lazy var mainName: UILabel = { let _label = UILabel() _label.font = FontContant.fontWith(20, type: .bold) return _label }() lazy var mainDate: UILabel = { let _label = UILabel() _label.font = FontContant.fontWith(12, type: .regular) return _label }() lazy var mainSeparator: UIView = { let _view = UIView() _view.backgroundColor = ColorConstants.lightGrey return _view }() lazy var mainStatus: UILabel = { let _label = UILabel() _label.font = FontContant.fontWith(15, type: .regular) return _label }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() setupConstraints() } private func setupViews(){ addSubview(mainView) selectionStyle = .none backgroundColor = .clear [mainImage, mainName, mainDate, mainSeparator, mainStatus].forEach{ mainView.addSubview($0) } } private func setupConstraints(){ mainView.easy.layout([ Top().to(self), Left().to(self), Right().to(self), Height(111.heightProportion()), Bottom(14.heightProportion()).to(self) ]) mainImage.easy.layout([ Top(14.heightProportion()).to(mainView), Left(14.widthProportion()).to(mainView), Width(48.widthProportion()), Height(48.widthProportion()) ]) mainName.easy.layout([ Top().to(mainImage, .top), Left(15.widthProportion()).to(mainImage) ]) mainDate.easy.layout([ Top(4.heightProportion()).to(mainName), Left().to(mainName, .left) ]) mainSeparator.easy.layout([ Top(10.heightProportion()).to(mainDate), Left().to(mainName, .left), Right().to(mainView), Height(3) ]) mainStatus.easy.layout([ Top(8.heightProportion()).to(mainSeparator), Left().to(mainName, .left), Bottom(10.heightProportion()).to(mainView) ]) } func configureCell() { mainImage.image = UIImage(named: "Background.jpg") mainName.text = "Del Papa" mainDate.text = "6 марта, 15:00 на 4 человека" mainStatus.text = "Ожидает подтверждения" } }
735817986eaa7ed327193788ae58c311
28.280702
75
0.566806
false
false
false
false
AlexIzh/Griddle
refs/heads/master
Griddle/Classes/Source/ArraySource.swift
mit
1
// // ArraySource.swift // CollectionPresenter // // Created by Alex on 20/02/16. // Copyright © 2016 Moqod. All rights reserved. // import Foundation public enum ArrayAction<Model> { case insert(index: Int, model: Model) case delete(index: Int) case replace(index: Int, newModel: Model) case move(oldIndex: Int, newIndex: Int) } public struct ArraySection<Element>: DataSection { public var header: Any? { return nil } public var footer: Any? { return nil } public var items: [Element] = [] public init(items: [Element] = []) { self.items = items } } open class ArraySource<Element>: DataSource, ExpressibleByArrayLiteral { public var delegate = DataSourceDelegate() private var section = ArraySection<Element>() public var sectionsCount: Int { return 1 } public var count: Int { return section.items.count } public var items: [Element] { get { return section.items } set { section.items = newValue delegate.didRefreshAll() } } public subscript(index: Int) -> Element { get { return section.items[index] } set { delegate.willBeginEditing() section.items[index] = newValue delegate.didUpdate(.row(.update(.item(section: 0, item: index)))) delegate.didEndEditing() } } // MARK: - Life cycle public required convenience init(arrayLiteral elements: Element...) { self.init(array: elements) } public init(array: [Element]) { section.items = array } // MARK: - Public methods public func append(_ item: Element) { delegate.willBeginEditing() insert(item, at: items.count) delegate.didEndEditing() } public func sections() -> [ArraySection<Element>] { return [section] } public func itemsCount(for section: Int) -> Int { return self.section.items.count } public func item(at section: Int, index: Int) -> Element? { guard section == 0 && index >= 0 && index < self.section.items.count else { return nil } return self.section.items[index] } public func header(at section: Int) -> Any? { return nil } public func footer(at section: Int) -> Any? { return nil } public func perform(actions: [ArrayAction<Element>]) { delegate.willBeginEditing() for action in actions { switch action { case .insert(let index, let model): insert(model, at: index) case .delete(let index): deleteItem(at: index) case .move(let oldIndex, let newIndex): moveItem(from: oldIndex, to: newIndex) case .replace(let index, let newModel): replaceItem(at: index, with: newModel) } } delegate.didEndEditing() } // MARK: - Private methods func replaceItem(at index: Int, with model: Element) { section.items[index] = model delegate.didUpdate(.row(.update(.item(section: 0, item: index)))) } func moveItem(from index: Int, to newIndex: Int) { let item = section.items[index] section.items.remove(at: index) section.items.insert(item, at: newIndex) delegate.didUpdate(.row(.move(from: .item(section: 0, item: index), to: .item(section: 0, item: newIndex)))) } func deleteItem(at index: Int) { section.items.remove(at: index) delegate.didUpdate(.row(.delete(.item(section: 0, item: index)))) } func insert(_ item: Element, at index: Int) { let insertIndex = index > section.items.count ? section.items.count : index section.items.insert(item, at: insertIndex) delegate.didUpdate(.row(.insert(.item(section: 0, item: index)))) } }
18f24e91155425fc325d5104346502b3
25.65942
114
0.631693
false
false
false
false
goRestart/restart-backend-app
refs/heads/develop
Tests/StorageTests/Utils/Validator/EmailValidatorSpec.swift
gpl-3.0
1
import XCTest import Shared @testable import FluentStorage class EmailValidatorSpec: XCTestCase { static let allTests = [ ("testShould_return_false_when_email_is_invalid", testShould_return_false_when_email_is_invalid), ("testShould_return_true_when_email_is_valid", testShould_return_true_when_email_is_valid), ("testShould_return_false_when_email_lenght_is_incorrect", testShould_return_false_when_email_lenght_is_incorrect) ] private let sut = EmailValidator() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testShould_return_false_when_email_is_invalid() { let invalidEmail1 = "despacito@" let invalidEmail2 = "favoritos@com" let invalidEmail3 = "fonsihot.com" XCTAssertFalse(sut.validate(invalidEmail1)) XCTAssertFalse(sut.validate(invalidEmail2)) XCTAssertFalse(sut.validate(invalidEmail3)) } func testShould_return_true_when_email_is_valid() { let validEmail = "[email protected]" XCTAssertTrue(sut.validate(validEmail)) } func testShould_return_false_when_email_lenght_is_incorrect() { let invalidEmail = "[email protected]" XCTAssertFalse(sut.validate(invalidEmail)) } }
ee7267d27512b78a40d9e7c4fc3a9f46
28.613636
122
0.669992
false
true
false
false
jonatascb/Smashtag
refs/heads/master
Smashtag/Twitter/MediaItem.swift
mit
1
// // MediaItem.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // holds the network url and aspectRatio of an image attached to a Tweet // created automatically when a Tweet object is created public struct MediaItem { public var url: NSURL! public var aspectRatio: Double = 0 public var description: String { return (url.absoluteString ?? "no url") + " (aspect ratio = \(aspectRatio))" } // MARK: - Private Implementation init?(data: NSDictionary?) { var valid = false if let urlString = data?.valueForKeyPath(TwitterKey.MediaURL) as? NSString { if let url = NSURL(string: urlString as String) { self.url = url let h = data?.valueForKeyPath(TwitterKey.Height) as? NSNumber let w = data?.valueForKeyPath(TwitterKey.Width) as? NSNumber if h != nil && w != nil && h?.doubleValue != 0 { aspectRatio = w!.doubleValue / h!.doubleValue valid = true } } } if !valid { return nil } } struct TwitterKey { static let MediaURL = "media_url_https" static let Width = "sizes.small.w" static let Height = "sizes.small.h" } }
c36fbc6d3473d9f27cada4a329b3faac
28.913043
115
0.578488
false
false
false
false
haskelash/molad
refs/heads/master
Molad/Views/WeekdayLayer.swift
mit
1
// // WeekdayLayer.swift // Molad // // Created by Haskel Ash on 5/29/17. // Copyright © 2017 HaskelAsh. All rights reserved. // import UIKit class WeekdayLayer: CALayer { private var current = 0 private let textWheel: TextWheel! private let outlineLayer = CAShapeLayer() let startRatio: CGFloat = 0.2 let endRatio: CGFloat = 0.5 override init() { textWheel = TextWheel() textWheel.startRatio = startRatio textWheel.endRatio = endRatio super.init() addSublayer(textWheel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(in ctx: CGContext) { textWheel.frame = bounds textWheel.setNeedsDisplay() func wedgePath(wedgeAngle: CGFloat = -.pi/6) -> CGPath { let path = CGMutablePath() let wedgeStart: CGFloat = startRatio * bounds.width/2 let wedgeEnd: CGFloat = endRatio * bounds.width/2 //start at r = wedgeStart, ø = wedgeAngle path.move(to: CGPoint(x: bounds.midX + wedgeStart*cos(wedgeAngle), y: bounds.midY + wedgeStart*sin(wedgeAngle))) //add line to r = wedgeEnd, ø = wedgeAngle path.addLine(to: CGPoint(x: bounds.midX + wedgeEnd*cos(wedgeAngle), y: bounds.midY + wedgeEnd*sin(wedgeAngle))) //add arc to r = wedgeEnd, ø = -wedgeAngle path.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: wedgeEnd, startAngle: wedgeAngle, endAngle: -wedgeAngle, clockwise: false) //add line to r = wedgeStart, ø = -wedgeAngle path.addLine(to: CGPoint(x: bounds.midX + wedgeStart*cos(-wedgeAngle), y: bounds.midY + wedgeStart*sin(-wedgeAngle))) //add arc to r = wedgeStart, ø = wedgeAngle path.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: wedgeStart, startAngle: -wedgeAngle, endAngle: wedgeAngle, clockwise: true) return path } //draw mask wedge let maskLayer = CAShapeLayer() maskLayer.path = wedgePath() maskLayer.fillColor = UIColor.black.cgColor mask = maskLayer //draw black outline around mask outlineLayer.path = wedgePath() outlineLayer.lineWidth = 4 outlineLayer.fillColor = UIColor.clear.cgColor outlineLayer.strokeColor = UIColor.black.cgColor addSublayer(outlineLayer) } func rotate() { let desired = (self.current + 1) % 7 UIView.animate(withDuration: 1.5) { self.textWheel.transform = CATransform3DMakeRotation( CGFloat.pi*2.0*CGFloat(desired)/7, 0, 0, -1) } self.current = (self.current + 1) % 7 } private class TextWheel: CALayer { var startRatio: CGFloat = 0 var endRatio: CGFloat = 1 override func draw(in ctx: CGContext) { //flip context for text ctx.translateBy(x: 0, y: bounds.height) ctx.scaleBy(x: 1.0, y: -1.0) let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] let dayFont = UIFont(name: "Helvetica Light", size: 11) let dayAttrs = [NSFontAttributeName: dayFont, NSForegroundColorAttributeName: UIColor.black] as CFDictionary //draw weekday text rotated at 1/7 of a cirlce intervals let midWedge = bounds.midX + ((startRatio + endRatio)/2 * bounds.width/2) for day in days { let dayStr = day as CFString let text = CFAttributedStringCreate(nil, dayStr, dayAttrs)! let line = CTLineCreateWithAttributedString(text) let lineBounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds) ctx.setTextDrawingMode(.stroke) let textX = (midWedge - lineBounds.midX) let textY = (bounds.midY - lineBounds.midY) ctx.textPosition = CGPoint(x: textX, y: textY) CTLineDraw(line, ctx) ctx.translateBy(x: bounds.midX, y: bounds.midY) ctx.rotate(by: -.pi*2/7) ctx.translateBy(x: -bounds.midX, y: -bounds.midY) } //done with text, flip context back ctx.translateBy(x: 0, y: bounds.height) ctx.scaleBy(x: 1.0, y: -1.0) } } }
136beb43ea1b53b5db97b5922a53e775
36.178862
92
0.57424
false
false
false
false
jopamer/swift
refs/heads/master
test/Interpreter/algorithms.swift
apache-2.0
2
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test func fib() { var (a, b) = (0, 1) while b < 10 { print(b) (a, b) = (b, a+b) } } fib() // CHECK: 1 // CHECK: 1 // CHECK: 2 // CHECK: 3 // CHECK: 5 // CHECK: 8 // From: <rdar://problem/17796401> // FIXME: <rdar://problem/21993692> type checker too slow let two_oneA = [1, 2, 3, 4].lazy.reversed() let two_one = Array(two_oneA.filter { $0 % 2 == 0 }.map { $0 / 2 }) print(two_one) // CHECK: [2, 1] // rdar://problem/18208283 func flatten<Element, Seq: Sequence, InnerSequence: Sequence where Seq.Iterator.Element == InnerSequence, InnerSequence.Iterator.Element == Element> (_ outerSequence: Seq) -> [Element] { var result = [Element]() for innerSequence in outerSequence { result.append(contentsOf: innerSequence) } return result } // CHECK: [1, 2, 3, 4, 5, 6] let flat = flatten([[1,2,3], [4,5,6]]) print(flat) // rdar://problem/19416848 func observe<T:Sequence, V where V == T.Iterator.Element>(_ g:T) { } observe(["a":1])
bb054f62034a108a46ab12d7e9e5f95d
22.288889
132
0.617366
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
ios_programming_4th/Homepwner-ch10/Homepwner/Item.swift
apache-2.0
1
// // Item.swift // Homepwner // // Created by Xiaoke Zhang on 2017/8/16. // Copyright © 2017年 Xiaoke Zhang. All rights reserved. // import Foundation struct Item : Equatable{ var itemName:String var serialNumber:String var valueInDollars:Int let dateCreated:Date = Date() var description:String { return "\(itemName) (\(serialNumber)) Worth \(valueInDollars), recorded on \(dateCreated)" } public static func ==(lhs: Item, rhs: Item) -> Bool { return lhs.dateCreated == rhs.dateCreated } static func randomItem() -> Item { let adjectives = ["Fluffy", "Rusty", "Shiny"] let nouns = ["Bear", "Spork", "Mac"] let ai = Int(arc4random()) % adjectives.count let ni = Int(arc4random()) % nouns.count let randomName = "\(adjectives[ai]) \(nouns[ni])" let randomValue = Int(arc4random_uniform(100)) let s0 = "0\(arc4random_uniform(10))" let s1 = "A\(arc4random_uniform(26))" let s2 = "0\(arc4random_uniform(10))" let randomSerialNumber = "\(s0)-\(s1)-\(s2)" return Item(itemName:randomName, serialNumber:randomSerialNumber, valueInDollars: randomValue) } }
9ca7c56f3ab3adc1907c82fabd0b3469
29.707317
98
0.592534
false
false
false
false
damoyan/BYRClient
refs/heads/master
FromScratch/ImageDecoder.swift
mit
1
// // ImageDecoder.swift // FromScratch // // Created by Yu Pengyang on 1/13/16. // Copyright © 2016 Yu Pengyang. All rights reserved. // import UIKit import ImageIO protocol ImageDecoder { var firstFrame: UIImage? { get } var frameCount: Int { get } var totalTime: NSTimeInterval { get } func imageAtIndex(index: Int) -> UIImage? func imageDurationAtIndex(index: Int) -> NSTimeInterval } class BYRImageDecoder: ImageDecoder { private let scale: CGFloat private let data: NSData private var source: CGImageSource? private var durations = [NSTimeInterval]() var firstFrame: UIImage? = nil var frameCount: Int = 0 var totalTime: NSTimeInterval = 0 init(data: NSData, scale: CGFloat = UIScreen.mainScreen().scale) { self.data = data self.scale = scale source = CGImageSourceCreateWithData(data, nil) generateImageInfo() } // MARK: - ImageDecoder func imageAtIndex(index: Int) -> UIImage? { guard let source = self.source else { return nil } if let cgimage = CGImageSourceCreateImageAtIndex(source, index, nil) { return decodeCGImage(cgimage, withScale: scale) } return nil } func imageDurationAtIndex(index: Int) -> NSTimeInterval { guard index < durations.count else { return 0 } /* http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ let duration = durations[index] return duration < 0.011 ? 0.1 : duration } // MARK: - Private private func generateImageInfo() { guard let source = self.source else { return } frameCount = CGImageSourceGetCount(source) durations = [NSTimeInterval](count: frameCount, repeatedValue: 0) for index in 0..<frameCount { guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) else { continue } if index == 0, let cgimage = CGImageSourceCreateImageAtIndex(source, index, nil) { firstFrame = decodeCGImage(cgimage, withScale: scale) } if let gifDict = getValue(properties, key: kCGImagePropertyGIFDictionary, type: CFDictionary.self) { if let unclampedDelay = getValue(gifDict, key: kCGImagePropertyGIFUnclampedDelayTime, type: NSNumber.self) { durations[index] = unclampedDelay.doubleValue } else if let delay = getValue(gifDict, key: kCGImagePropertyGIFDelayTime, type: NSNumber.self) { durations[index] = delay.doubleValue } } } } // swift version of SDWebImage decoder (just copy code) private func decodeCGImage(image: CGImage, withScale scale: CGFloat) -> UIImage? { let imageSize = CGSize(width: CGImageGetWidth(image), height: CGImageGetHeight(image)) let imageRect = CGRect(origin: CGPointZero, size: imageSize) let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo = CGImageGetBitmapInfo(image).rawValue let infoMask = bitmapInfo & CGBitmapInfo.AlphaInfoMask.rawValue let anyNonAlpha = (infoMask == CGImageAlphaInfo.None.rawValue || infoMask == CGImageAlphaInfo.NoneSkipFirst.rawValue || infoMask == CGImageAlphaInfo.NoneSkipLast.rawValue) if infoMask == CGImageAlphaInfo.None.rawValue && CGColorSpaceGetNumberOfComponents(colorSpace) > 1 { bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst.rawValue } else if !anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3 { bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask.rawValue bitmapInfo |= CGImageAlphaInfo.PremultipliedFirst.rawValue } guard let context = CGBitmapContextCreate(nil, Int(imageSize.width), Int(imageSize.height), CGImageGetBitsPerComponent(image), 0, colorSpace, bitmapInfo) else { return nil } CGContextDrawImage(context, imageRect, image) guard let newImage = CGBitmapContextCreateImage(context) else { return nil } return UIImage(CGImage: newImage, scale: scale, orientation: .Up) } private func getValue<T>(dict: CFDictionary, key: CFString, type: T.Type) -> T? { let nkey = unsafeBitCast(key, UnsafePointer<Void>.self) let v = CFDictionaryGetValue(dict, nkey) if v == nil { return nil } return unsafeBitCast(v, type) } }
b383c7de85fe877fee113f46ad1d5dd4
41.358333
181
0.651318
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/WordPressShareExtension/UIImageView+Extensions.swift
gpl-2.0
2
import Foundation extension UIImageView { /// Downloads an image and updates the UIImageView Instance /// /// - Parameter url: The URL of the target image /// public func downloadImage(_ url: URL) { // Hit the cache if let cachedImage = Downloader.cache.object(forKey: url as AnyObject) as? UIImage { self.image = cachedImage return } // Cancel any previous OP's if let task = downloadTask { task.cancel() downloadTask = nil } // Helpers let scale = mainScreenScale let size = CGSize(width: blavatarSizeInPoints, height: blavatarSizeInPoints) // Hit the Backend var request = URLRequest(url: url) request.httpShouldHandleCookies = false request.addValue("image/*", forHTTPHeaderField: "Accept") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { [weak self] data, response, error in guard let data = data, let image = UIImage(data: data, scale: scale) else { return } DispatchQueue.main.async { // Resize if needed! var resizedImage = image if image.size.height > size.height || image.size.width > size.width { resizedImage = image.resizedImage(with: .scaleAspectFit, bounds: size, interpolationQuality: .high) } // Update the Cache Downloader.cache.setObject(resizedImage, forKey: url as AnyObject) self?.image = resizedImage } }) downloadTask = task task.resume() } /// Downloads a resized Blavatar, meant to perfectly fit the UIImageView's Dimensions /// /// - Parameter url: The URL of the target blavatar /// public func downloadBlavatar(_ url: URL) { var components = URLComponents(url: url, resolvingAgainstBaseURL: true) components?.query = String(format: Downloader.blavatarResizeFormat, blavatarSize) if let updatedURL = components?.url { downloadImage(updatedURL) } } /// Returns the desired Blavatar Side-Size, in pixels /// fileprivate var blavatarSize: Int { return blavatarSizeInPoints * Int(mainScreenScale) } /// Returns the desired Blavatar Side-Size, in points /// fileprivate var blavatarSizeInPoints: Int { var size = Downloader.defaultImageSize if !bounds.size.equalTo(CGSize.zero) { size = max(bounds.width, bounds.height) } return Int(size) } /// Returns the Main Screen Scale /// fileprivate var mainScreenScale: CGFloat { return UIScreen.main.scale } /// Stores the current DataTask, in charge of downloading the remote Image /// fileprivate var downloadTask: URLSessionDataTask? { get { return objc_getAssociatedObject(self, Downloader.taskKey) as? URLSessionDataTask } set { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(self, Downloader.taskKey, newValue, policy) } } /// Private helper structure /// fileprivate struct Downloader { /// Default Blavatar Image Size /// static let defaultImageSize = CGFloat(40) /// Blavatar Resize Query FormatString /// static let blavatarResizeFormat = "d=404&s=%d" /// Stores all of the previously downloaded images /// static let cache = NSCache<AnyObject, AnyObject>() /// Key used to associate a Download task to the current instance /// static let taskKey = "downloadTaskKey" } }
c3f18d0a850f56923252df3e5e672826
29.937984
108
0.58206
false
false
false
false
Eonil/Editor
refs/heads/develop
Editor4/WorkspaceWindowState.swift
mit
1
// // WorkspaceWindowState.swift // Editor4 // // Created by Hoon H. on 2016/05/14. // Copyright © 2016 Eonil. All rights reserved. // /// We do not keep selection/editing informaiton in navigational state /// except it's really required because it affects performance too much. struct WorkspaceWindowState { var navigatorPane = NavigatorPaneState() var editorPane = EditorPaneState() var utilityPane = UtilityPaneState() var commandPane = CommandPaneState() } //////////////////////////////////////////////////////////////// struct NavigatorPaneState { /// Set `nil` to hide pane. var current: NavigatorPaneID? var file = FileNavigatorPaneState() var issue = IssueNavigatorPaneState() } enum NavigatorPaneID { case files case issues case breakpoints case debug } struct FileNavigatorPaneState { /// Path to a file-node that is currently in editing. var editing: Bool = false var filterExpression: String? var selection = FileNavigatorPaneSelectionState() } struct FileNavigatorPaneSelectionState { /// Currently focused file node. /// This is clicked file while context-menu is running. private(set) var highlighting: FileID2? /// User's most recent focused selection. /// This is rarely required. /// - Parameter current: /// This must be included in `all`. private(set) var current: FileID2? /// This work only in specific time-span. Which means /// accessible only if `version == accessibleVerison`. private(set) var items: TemporalLazyCollection<FileID2> = [] private init() { } mutating func reset() { highlighting = nil current = nil items = [] } mutating func reset(newCurrent: FileID2?) { reset() if let newCurrent = newCurrent { reset(newCurrent) } } mutating func reset(newCurrent: FileID2) { reset(newCurrent, [newCurrent]) } /// You must have a "current" file when you set to a new files. mutating func reset(newCurrent: FileID2, _ newItems: TemporalLazyCollection<FileID2>) { assert(newItems.contains(newCurrent)) highlighting = nil current = newCurrent items = newItems } mutating func highlight(newHighlight: FileID2) { highlighting = newHighlight current = nil // Keeps current selection. } } extension FileNavigatorPaneSelectionState { func getHighlightOrCurrent() -> FileID2? { return highlighting ?? current } /// - Returns: /// A highlighted file ID if highlighted file ID is not a part of selected file IDs. /// All selected file IDs if the highlighted file ID is a part of selected file IDs /// or there's no highlighted file ID. func getHighlightOrItems() -> AnyRandomAccessCollection<FileID2> { if let highlighting = highlighting { if items.contains(highlighting) { return AnyRandomAccessCollection(items) } else { return AnyRandomAccessCollection(CollectionOfOne(highlighting).flatMap({$0})) } } else { return AnyRandomAccessCollection(items) } } } struct IssueNavigatorPaneState { var hideWarnings = false } //////////////////////////////////////////////////////////////// struct EditorPaneState { var current: EditorPaneID? var text = TextEditorPaneState() } enum EditorPaneID { case Text } struct TextEditorPaneState { private(set) var lines = [String]() } struct AutocompletionState { private(set) var candidates = [AutocompletionCandidateState]() } struct AutocompletionCandidateState { private(set) var code: String } //////////////////////////////////////////////////////////////// enum CommandPaneID { case Console case Variables } struct CommandPaneState { /// Set `nil` to hide pane. var current: CommandPaneID? var variable = VariableNavigatorPaneState() var console = ConsoleCommandPaneState() } struct VariableNavigatorPaneState { } struct ConsoleCommandPaneState { } //////////////////////////////////////////////////////////////// struct UtilityPaneState { /// Set `nil` to hide pane. var current: UtilityPaneID? } enum UtilityPaneID { case Inspector case Help } struct InspectorUtilityPaneState { var current: InspectableID? } enum InspectableID { case File(FileNodePath) }
650da0701637e1361b8cec135ca0b86b
22.581152
93
0.625888
false
false
false
false
AngryLi/Onmyouji
refs/heads/master
Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftTestObjects.swift
mit
2
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm class SwiftStringObject: RLMObject { @objc dynamic var stringCol = "" } class SwiftBoolObject: RLMObject { @objc dynamic var boolCol = false } class SwiftIntObject: RLMObject { @objc dynamic var intCol = 0 } class SwiftLongObject: RLMObject { @objc dynamic var longCol: Int64 = 0 } class SwiftObject: RLMObject { @objc dynamic var boolCol = false @objc dynamic var intCol = 123 @objc dynamic var floatCol = 1.23 as Float @objc dynamic var doubleCol = 12.3 @objc dynamic var stringCol = "a" @objc dynamic var binaryCol = "a".data(using: String.Encoding.utf8) @objc dynamic var dateCol = Date(timeIntervalSince1970: 1) @objc dynamic var objectCol = SwiftBoolObject() @objc dynamic var arrayCol = RLMArray<SwiftBoolObject>(objectClassName: SwiftBoolObject.className()) } class SwiftOptionalObject: RLMObject { @objc dynamic var optStringCol: String? @objc dynamic var optNSStringCol: NSString? @objc dynamic var optBinaryCol: Data? @objc dynamic var optDateCol: Date? @objc dynamic var optObjectCol: SwiftBoolObject? } class SwiftDogObject: RLMObject { @objc dynamic var dogName = "" } class SwiftOwnerObject: RLMObject { @objc dynamic var name = "" @objc dynamic var dog: SwiftDogObject? = SwiftDogObject() } class SwiftAggregateObject: RLMObject { @objc dynamic var intCol = 0 @objc dynamic var floatCol = 0 as Float @objc dynamic var doubleCol = 0.0 @objc dynamic var boolCol = false @objc dynamic var dateCol = Date() } class SwiftAllIntSizesObject: RLMObject { @objc dynamic var int8 : Int8 = 0 @objc dynamic var int16 : Int16 = 0 @objc dynamic var int32 : Int32 = 0 @objc dynamic var int64 : Int64 = 0 } class SwiftEmployeeObject: RLMObject { @objc dynamic var name = "" @objc dynamic var age = 0 @objc dynamic var hired = false } class SwiftCompanyObject: RLMObject { @objc dynamic var employees = RLMArray<SwiftEmployeeObject>(objectClassName: SwiftEmployeeObject.className()) } class SwiftArrayPropertyObject: RLMObject { @objc dynamic var name = "" @objc dynamic var array = RLMArray<SwiftStringObject>(objectClassName: SwiftStringObject.className()) @objc dynamic var intArray = RLMArray<SwiftIntObject>(objectClassName: SwiftIntObject.className()) } class SwiftDynamicObject: RLMObject { @objc dynamic var stringCol = "a" @objc dynamic var intCol = 0 } class SwiftUTF8Object: RLMObject { @objc dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا" } class SwiftIgnoredPropertiesObject: RLMObject { @objc dynamic var name = "" @objc dynamic var age = 0 @objc dynamic var runtimeProperty: AnyObject? @objc dynamic var readOnlyProperty: Int { return 0 } override class func ignoredProperties() -> [String]? { return ["runtimeProperty"] } } class SwiftPrimaryStringObject: RLMObject { @objc dynamic var stringCol = "" @objc dynamic var intCol = 0 override class func primaryKey() -> String { return "stringCol" } } class SwiftLinkSourceObject: RLMObject { @objc dynamic var id = 0 @objc dynamic var link: SwiftLinkTargetObject? } class SwiftLinkTargetObject: RLMObject { @objc dynamic var id = 0 @objc dynamic var backlinks: RLMLinkingObjects<SwiftLinkSourceObject>? override class func linkingObjectsProperties() -> [String : RLMPropertyDescriptor] { return ["backlinks": RLMPropertyDescriptor(with: SwiftLinkSourceObject.self, propertyName: "link")] } } class SwiftLazyVarObject : RLMObject { @objc dynamic lazy var lazyProperty : String = "hello world" } class SwiftIgnoredLazyVarObject : RLMObject { @objc dynamic var id = 0 @objc dynamic lazy var ignoredVar : String = "hello world" override class func ignoredProperties() -> [String] { return ["ignoredVar"] } } class SwiftObjectiveCTypesObject: RLMObject { @objc dynamic var stringCol: NSString? @objc dynamic var dateCol: NSDate? @objc dynamic var dataCol: NSData? @objc dynamic var numCol: NSNumber? = 0 }
2fb5ef7b7d258ad838f1dfd0ffb37008
30.219355
113
0.692292
false
false
false
false
Conaaando/swift-hacker-rank
refs/heads/master
00.Warmup/02-large-sum.swift
mit
1
#!/usr/bin/swift /* https://github.com/singledev/swift-hacker-rank 02-large-sum.swift https://www.hackerrank.com/challenges/a-very-big-sum Created by Fernando Fernandes on 07/04/16. Copyright © 2016 SINGLEDEV. All rights reserved. http://stackoverflow.com/users/584548/singledev Instructions: $ chmod a+x 02-large-sum.swift $ ./02-large-sum.swift */ import Foundation print("Type a NUMBER, then press ENTER") var n = Int(readLine()!)! print("Type \(n) numbers separated by spaces, then press ENTER") var arr = readLine()!.characters.split(" ").map(String.init) var sum: Double = 0.0 for (var i = 0; i < n; i++) { sum += Double(arr[i])! } print("The sum is: " + String(format: "%.0f", sum))
daf33517516176446d14873e1a36c464
18.702703
64
0.668038
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Client/Frontend/Browser/SearchEngines.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.browserLogger private let OrderedEngineNames = "search.orderedEngineNames" private let DisabledEngineNames = "search.disabledEngineNames" private let ShowSearchSuggestionsOptIn = "search.suggestions.showOptIn" private let ShowSearchSuggestions = "search.suggestions.show" private let customSearchEnginesFileName = "customEngines.plist" /** * Manage a set of Open Search engines. * * The search engines are ordered. Individual search engines can be enabled and disabled. The * first search engine is distinguished and labeled the "default" search engine; it can never be * disabled. Search suggestions should always be sourced from the default search engine. * * Two additional bits of information are maintained: whether the user should be shown "opt-in to * search suggestions" UI, and whether search suggestions are enabled. * * Consumers will almost always use `defaultEngine` if they want a single search engine, and * `quickSearchEngines()` if they want a list of enabled quick search engines (possibly empty, * since the default engine is never included in the list of enabled quick search engines, and * it is possible to disable every non-default quick search engine). * * The search engines are backed by a write-through cache into a ProfilePrefs instance. This class * is not thread-safe -- you should only access it on a single thread (usually, the main thread)! */ class SearchEngines { fileprivate let prefs: Prefs fileprivate let fileAccessor: FileAccessor init(prefs: Prefs, files: FileAccessor) { self.prefs = prefs // By default, show search suggestions self.shouldShowSearchSuggestions = prefs.boolForKey(ShowSearchSuggestions) ?? true self.fileAccessor = files self.disabledEngineNames = getDisabledEngineNames() self.orderedEngines = getOrderedEngines() } var defaultEngine: OpenSearchEngine { get { return self.orderedEngines[0] } set(defaultEngine) { // The default engine is always enabled. self.enableEngine(defaultEngine) // The default engine is always first in the list. var orderedEngines = self.orderedEngines.filter { engine in engine.shortName != defaultEngine.shortName } orderedEngines.insert(defaultEngine, at: 0) self.orderedEngines = orderedEngines } } func isEngineDefault(_ engine: OpenSearchEngine) -> Bool { return defaultEngine.shortName == engine.shortName } // The keys of this dictionary are used as a set. fileprivate var disabledEngineNames: [String: Bool]! { didSet { self.prefs.setObject(Array(self.disabledEngineNames.keys), forKey: DisabledEngineNames) } } var orderedEngines: [OpenSearchEngine]! { didSet { self.prefs.setObject(self.orderedEngines.map { $0.shortName }, forKey: OrderedEngineNames) } } var quickSearchEngines: [OpenSearchEngine]! { get { return self.orderedEngines.filter({ (engine) in !self.isEngineDefault(engine) && self.isEngineEnabled(engine) }) } } var shouldShowSearchSuggestions: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestions, forKey: ShowSearchSuggestions) } } func isEngineEnabled(_ engine: OpenSearchEngine) -> Bool { return disabledEngineNames.index(forKey: engine.shortName) == nil } func enableEngine(_ engine: OpenSearchEngine) { disabledEngineNames.removeValue(forKey: engine.shortName) } func disableEngine(_ engine: OpenSearchEngine) { if isEngineDefault(engine) { // Can't disable default engine. return } disabledEngineNames[engine.shortName] = true } func deleteCustomEngine(_ engine: OpenSearchEngine) { // We can't delete a preinstalled engine or an engine that is currently the default. if !engine.isCustomEngine || isEngineDefault(engine) { return } customEngines.remove(at: customEngines.index(of: engine)!) saveCustomEngines() orderedEngines = getOrderedEngines() } /// Adds an engine to the front of the search engines list. func addSearchEngine(_ engine: OpenSearchEngine) { customEngines.append(engine) orderedEngines.insert(engine, at: 1) saveCustomEngines() } func queryForSearchURL(_ url: URL?) -> String? { for engine in orderedEngines { guard let searchTerm = engine.queryForSearchURL(url) else { continue } return searchTerm } return nil } fileprivate func getDisabledEngineNames() -> [String: Bool] { if let disabledEngineNames = self.prefs.stringArrayForKey(DisabledEngineNames) { var disabledEngineDict = [String: Bool]() for engineName in disabledEngineNames { disabledEngineDict[engineName] = true } return disabledEngineDict } else { return [String: Bool]() } } fileprivate func customEngineFilePath() -> String { let profilePath = try! self.fileAccessor.getAndEnsureDirectory() as NSString return profilePath.appendingPathComponent(customSearchEnginesFileName) } fileprivate lazy var customEngines: [OpenSearchEngine] = { return NSKeyedUnarchiver.unarchiveObject(withFile: self.customEngineFilePath()) as? [OpenSearchEngine] ?? [] }() fileprivate func saveCustomEngines() { NSKeyedArchiver.archiveRootObject(customEngines, toFile: self.customEngineFilePath()) } /// Return all possible language identifiers in the order of most specific to least specific. /// For example, zh-Hans-CN will return [zh-Hans-CN, zh-CN, zh]. class func possibilitiesForLanguageIdentifier(_ languageIdentifier: String) -> [String] { var possibilities: [String] = [] let components = languageIdentifier.components(separatedBy: "-") possibilities.append(languageIdentifier) if components.count == 3, let first = components.first, let last = components.last { possibilities.append("\(first)-\(last)") } if components.count >= 2, let first = components.first { possibilities.append("\(first)") } return possibilities } /// Get all bundled (not custom) search engines, with the default search engine first, /// but the others in no particular order. class func getUnorderedBundledEnginesFor(locale: Locale) -> [OpenSearchEngine] { let languageIdentifier = locale.identifier let region = locale.regionCode ?? "US" let parser = OpenSearchParser(pluginMode: true) guard let pluginDirectory = Bundle.main.resourceURL?.appendingPathComponent("SearchPlugins") else { assertionFailure("Search plugins not found. Check bundle") return [] } guard let defaultSearchPrefs = DefaultSearchPrefs(with: pluginDirectory.appendingPathComponent("list.json")) else { assertionFailure("Failed to parse List.json") return [] } let possibilities = possibilitiesForLanguageIdentifier(languageIdentifier) let engineNames = defaultSearchPrefs.visibleDefaultEngines(for: possibilities, and: region) let defaultEngineName = defaultSearchPrefs.searchDefault(for: possibilities, and: region) assert(engineNames.count > 0, "No search engines") return engineNames.map({ (name: $0, path: pluginDirectory.appendingPathComponent("\($0).xml").path) }) .filter({ FileManager.default.fileExists(atPath: $0.path) }) .flatMap({ parser.parse($0.path, engineID: $0.name) }) .sorted { e, _ in e.shortName == defaultEngineName } } /// Get all known search engines, possibly as ordered by the user. fileprivate func getOrderedEngines() -> [OpenSearchEngine] { let unorderedEngines = customEngines + SearchEngines.getUnorderedBundledEnginesFor(locale: Locale.current) // might not work to change the default. guard let orderedEngineNames = prefs.stringArrayForKey(OrderedEngineNames) else { // We haven't persisted the engine order, so return whatever order we got from disk. return unorderedEngines } // We have a persisted order of engines, so try to use that order. // We may have found engines that weren't persisted in the ordered list // (if the user changed locales or added a new engine); these engines // will be appended to the end of the list. return unorderedEngines.sorted { engine1, engine2 in let index1 = orderedEngineNames.index(of: engine1.shortName) let index2 = orderedEngineNames.index(of: engine2.shortName) if index1 == nil && index2 == nil { return engine1.shortName < engine2.shortName } // nil < N for all non-nil values of N. if index1 == nil || index2 == nil { return index1 ?? -1 > index2 ?? -1 } return index1! < index2! } } }
ead015e286b097bbe31f1815ee56d89e
40.081545
124
0.671646
false
false
false
false
CMP-Studio/TheWarholOutLoud
refs/heads/master
ios/CMSAccessibilityManager.swift
mit
1
// // CMSAccessibilityManager.swift // AndyWarholAccessibilityProject // // Created by Ruben Niculcea on 6/22/16. // Copyright © 2016 Carnegie Museums of Pittsburgh Innovation Studio. // All rights reserved. // import Foundation import UIKit enum CMSAccessibilityManagerEvents:String { case screenReaderStatusChanged } @objc(CMSAccessibilityManager) class CMSAccessibilityManager: RCTEventEmitter { override func constantsToExport() -> [String: Any] { let screenReaderStatusChanged = CMSAccessibilityManagerEvents.screenReaderStatusChanged.rawValue return [ "Events": [ screenReaderStatusChanged: screenReaderStatusChanged, ] ] } override func supportedEvents() -> [String] { let screenReaderStatusChanged = CMSAccessibilityManagerEvents.screenReaderStatusChanged.rawValue return [ screenReaderStatusChanged, ] } @objc func screenReaderSpeak(_ text:String) { mainThread() { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, text); } } @objc func screenReaderScreenChanged(_ text:String) { mainThread() { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, text) } } @objc func screenReaderForceFocus(_ reactTag:Int) { mainThread() { // How to find the reactTag in JS: // const reactTag = ReactNative.findNodeHandle(this.refs.testView); // !! Note: This is true for react 0.28 but bound to change in the future !! let view = self.bridge.uiManager.view(forReactTag: reactTag as NSNumber!) UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, view) } } @objc func screenReaderReloadLayout() { mainThread() { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil); } } @objc func screenReaderStatus(_ resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) { let screenReaderStatus = UIAccessibilityIsVoiceOverRunning() // This function will never reject but I want to be able // to use promises to make for cleaner JS code resolve([screenReaderStatus]) } override func startObserving() { NotificationCenter.default.addObserver(self, selector:#selector(CMSAccessibilityManager.screenReaderStatusChanged), name: NSNotification.Name(rawValue: UIAccessibilityVoiceOverStatusChanged), object: nil) } func screenReaderStatusChanged() { let screenReaderStatus = UIAccessibilityIsVoiceOverRunning() let eventName = CMSAccessibilityManagerEvents.screenReaderStatusChanged.rawValue let eventData = [ "screenReaderStatus": screenReaderStatus, ] self.sendEvent(withName: eventName, body: eventData) } func mainThread(_ closure:@escaping () -> ()) { DispatchQueue.main.async { closure() } } }
9132f8f74599d1dcc81785fb629fafb2
29.252632
208
0.729993
false
false
false
false
net-a-porter-mobile/XCTest-Gherkin
refs/heads/master
Pod/Core/PageObject.swift
apache-2.0
1
import XCTest /// Base class for PageObject pattern. open class PageObject: NSObject { required public override init() { super.init() let presented = isPresented() XCTAssertTrue(presented, "\(type(of: self).name) is not presented") } /// Name of the screen (or its part) that this page object represent. /// Default is name of this type without "PageObject" suffix, if any. open class var name: String { let name = String(describing: self) if name.lowercased().hasSuffix("pageobject") { return String(name.dropLast(10)).humanReadableString } return name.humanReadableString } /// This method should be overriden by subclasses /// and should return `true` if this PageObject's screen is presented open func isPresented() -> Bool { fatalError("not implemented") } } /// This type defines common steps for all page objects. public class CommonPageObjectsStepDefiner: StepDefiner { /// Format for step expression that validates that PageObject is presented /// Default value matches "I see %@", "I should see %@" or "it is %@" with optional "the" before page object name public static var isPresentedStepFormat = "^(?:I (?:should )?see|it is) (?:the )?%@$" override public func defineSteps() { allSubclassesOf(PageObject.self).forEach { (subclass) in guard subclass != PageObject.self else { return } let name = subclass.name let expression = String(format: CommonPageObjectsStepDefiner.isPresentedStepFormat, name) step(expression) { _ = subclass.init() } } } }
839292edb11c960dc1b1b263c2e9ec62
37.227273
117
0.648633
false
false
false
false
debugsquad/nubecero
refs/heads/master
nubecero/Controller/Home/CHome.swift
mit
1
import UIKit class CHome:CController { private weak var viewHome:VHome! let model:MHome let askAuth:Bool var diskUsed:Int? init(askAuth:Bool) { model = MHome() self.askAuth = askAuth super.init() } deinit { NotificationCenter.default.removeObserver(self) } required init?(coder:NSCoder) { fatalError() } override func loadView() { let viewHome:VHome = VHome(controller:self) self.viewHome = viewHome view = viewHome } override func viewDidLoad() { super.viewDidLoad() if askAuth { guard let shouldAuth:Bool = MSession.sharedInstance.settings.current?.security else { return } if shouldAuth { parentController.presentAuth() parentController.controllerAuth?.askAuth() } } } override func viewDidAppear(_ animated:Bool) { super.viewDidAppear(animated) DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in guard let welf:CHome = self else { return } NotificationCenter.default.removeObserver(welf) NotificationCenter.default.addObserver( welf, selector:#selector(welf.notifiedSessionLoaded(sender:)), name:Notification.sessionLoaded, object:nil) MSession.sharedInstance.user.sendUpdate() } MPhotos.sharedInstance.loadPhotos() } //MARK: notified func notifiedSessionLoaded(sender notification:Notification) { NotificationCenter.default.removeObserver(self) loadUsedDisk() } //MARK: private private func loadUsedDisk() { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { guard let userId:MSession.UserId = MSession.sharedInstance.user.userId else { return } let parentUser:String = FDatabase.Parent.user.rawValue let propertyDiskUsed:String = FDatabaseModelUser.Property.diskUsed.rawValue let pathDiskUsed:String = "\(parentUser)/\(userId)/\(propertyDiskUsed)" FMain.sharedInstance.database.listenOnce( path:pathDiskUsed, modelType:FDatabaseModelUserDiskUsed.self) { [weak self] (diskUsed:FDatabaseModelUserDiskUsed?) in guard let firebaseDiskUsed:FDatabaseModelUserDiskUsed = diskUsed else { return } self?.diskUsed = firebaseDiskUsed.diskUsed DispatchQueue.main.async { [weak self] in self?.usedDiskLoaded() } } } } private func usedDiskLoaded() { viewHome.sessionLoaded() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.checkFullDisk() } } private func checkFullDisk() { guard let fullWarning:Bool = MSession.sharedInstance.settings.current?.fullWarning, let plus:Bool = MSession.sharedInstance.settings.current?.nubeceroPlus else { return } if !plus { if fullWarning { MSession.sharedInstance.settings.current?.fullWarning = false DManager.sharedInstance.save() DispatchQueue.main.async { [weak self] in self?.storeAd() } } } } private func storeAd() { let modelAd:MStoreAdPlus = MStoreAdPlus() let adController:CStoreAd = CStoreAd(model:modelAd) parentController.over( controller:adController, pop:false, animate:true) } //MARK: public func uploadPictures() { let controllerUpload:CHomeUpload = CHomeUpload() parentController.push( controller:controllerUpload, underBar:true) } }
1302148126c09808110a2d023b39c09b
23.545455
89
0.488477
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
Shared/DeviceInfo.swift
mpl-2.0
6
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit open class DeviceInfo { // List of device names that don't support advanced visual settings static let lowGraphicsQualityModels = ["iPad", "iPad1,1", "iPhone1,1", "iPhone1,2", "iPhone2,1", "iPhone3,1", "iPhone3,2", "iPhone3,3", "iPod1,1", "iPod2,1", "iPod2,2", "iPod3,1", "iPod4,1", "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4", "iPad3,1", "iPad3,2", "iPad3,3"] public static var specificModelName: String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = Mirror(reflecting: machine) var identifier = "" // Parses the string for the model name via NSUTF8StringEncoding, refer to // http://stackoverflow.com/questions/26028918/ios-how-to-determine-iphone-model-in-swift for child in mirror.children.enumerated() { if let value = child.1.value as? Int8, value != 0 { identifier.append(String(UnicodeScalar(UInt8(value)))) } } return identifier } /// Return the client name, which can be either "Fennec on Stefan's iPod" or simply "Stefan's iPod" if the application display name cannot be obtained. open class func defaultClientName() -> String { let format = NSLocalizedString("%@ on %@", tableName: "Shared", comment: "A brief descriptive name for this app on this device, used for Send Tab and Synced Tabs. The first argument is the app name. The second argument is the device name.") if ProcessInfo.processInfo.arguments.contains(LaunchArguments.DeviceName) { return String(format: format, AppInfo.displayName, "iOS") } return String(format: format, AppInfo.displayName, UIDevice.current.name) } open class func clientIdentifier(_ prefs: Prefs) -> String { if let id = prefs.stringForKey("clientIdentifier") { return id } let id = UUID().uuidString prefs.setString(id, forKey: "clientIdentifier") return id } open class func deviceModel() -> String { return UIDevice.current.model } open class func isSimulator() -> Bool { return ProcessInfo.processInfo.environment["SIMULATOR_ROOT"] != nil } open class func isBlurSupported() -> Bool { // We've tried multiple ways to make this change visible on simulators, but we // haven't found a solution that worked: // 1. http://stackoverflow.com/questions/21603475/how-can-i-detect-if-the-iphone-my-app-is-on-is-going-to-use-a-simple-transparen // 2. https://gist.github.com/conradev/8655650 // Thus, testing has to take place on actual devices. return !lowGraphicsQualityModels.contains(specificModelName) } open class func hasConnectivity() -> Bool { let status = Reach().connectionStatus() switch status { case .online(.wwan), .online(.wiFi): return true default: return false } } // Reports portrait screen size regardless of the current orientation. open class func screenSizeOrientationIndependent() -> CGSize { let screenSize = UIScreen.main.bounds.size return CGSize(width: min(screenSize.width, screenSize.height), height: max(screenSize.width, screenSize.height)) } }
a3de2f562504e6b3e0a34f2486e7b94f
42.641975
271
0.653748
false
false
false
false
drinkapoint/DrinkPoint-iOS
refs/heads/master
DrinkPoint/DrinkPoint/Bartender/BartenderAddItemTableViewCell.swift
mit
1
// // BartenderAddItemTableViewCell.swift // DrinkPoint // // Created by Paul Kirk Adams on 7/5/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import UIKit class AddItemTableViewCell: UITableViewCell { @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var checkLabel: UILabel! func prefersStatusBarHidden() -> Bool { return true } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.selectionStyle = .None } func setCell(item: Item) { self.nameLabel.text = item.name self.nameLabel.textColor = .whiteColor() switch item.category { case "mixer": self.iconImage.image = UIImage(named: "BartenderMixer") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "hardDrink": self.iconImage.image = UIImage(named: "BartenderHardDrink") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "softDrink": self.iconImage.image = UIImage(named: "BartenderSoftDrink") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "produce": self.iconImage.image = UIImage(named: "BartenderProduce") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "beer": self.iconImage.image = UIImage(named: "BartenderBeer") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "spice": self.iconImage.image = UIImage(named: "BartenderSpice") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "ice": self.iconImage.image = UIImage(named: "BartenderIce") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() case "wine": self.iconImage.image = UIImage(named: "BartenderWine") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() default: self.iconImage.image = UIImage(named: "BartenderMixer") self.iconImage.image = iconImage.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.iconImage.tintColor = .whiteColor() } } }
90af3d9f440b524a84926c282e84670e
39.04878
111
0.644228
false
false
false
false
loveMyAp/ZYNetworkTools
refs/heads/master
NetWorkingTools.swift
mit
1
// // NetWorkingTools.swift // sniaWeiBo // // Created by mac on 15/11/19. // Copyright © 2015年 cn.1069560719@qq. All rights reserved. // import UIKit import AFNetworking private let Domain = "com.baidu.data.error" enum HTTPMothod: String { case POST = "POST" case GET = "GET" } class NetWorkingTools: AFHTTPSessionManager { //定义单例对象 /* 我添加的一个text解析方式,可以根据自己的项目需求自己手动的添加解析方式 tools.responseSerializer.acceptableContentTypes?.insert("text/plain") */ static var sharedTools: NetWorkingTools = { let tools = NetWorkingTools() tools.responseSerializer.acceptableContentTypes?.insert("text/plain") return tools }() //定义网络访问方法 以后所有的网络访问都经过该方法调用 AFN //加载字典数据 /* requestMethod: 发送网络请求的方法类型(枚举) urlString: 网络请求地址 parameters: 拼接网络地址参数 finished: 返回结果回调(result: 字典类型的数据回调,error: 返回错误信息) */ func request(requestMethod: HTTPMothod ,urlString: String,parameters: [String:AnyObject]?,finished:(result: [String:AnyObject]?,error: NSError?) -> ()){ //调用AFN具体的 GET,POST方法 if requestMethod == HTTPMothod.GET{ NetWorkingTools.sharedTools.GET(urlString, parameters: parameters, success: { (_, result) -> Void in if let dict = result as? [String:AnyObject] { finished(result: dict, error: nil) } let dateError = NSError(domain: Domain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据加载错误"]) finished(result: nil, error: dateError) }) { (_, error) -> Void in finished(result: nil, error: error) print(error) } }else if requestMethod == HTTPMothod.POST { NetWorkingTools.sharedTools.POST(urlString, parameters: parameters, success: { (_, result) -> Void in if let dict = result as? [String:AnyObject] { finished(result: dict, error: nil) } let dateError = NSError(domain: Domain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据加载错误"]) finished(result: nil, error: dateError) }) { (_, error) -> Void in finished(result: nil, error: error) print(error) } } } //加载数组数据 func requestArray(requestMethod: HTTPMothod ,urlString: String,parameters: [String:AnyObject]?,finished:(result: [AnyObject]?,error: NSError?) -> ()){ //调用AFN具体的 GET,POST方法 if requestMethod == HTTPMothod.GET{ NetWorkingTools.sharedTools.GET(urlString, parameters: parameters, success: { (_, result) -> Void in if let dict = result as? [AnyObject] { finished(result: dict, error: nil) } let dateError = NSError(domain: Domain, code: -11000, userInfo: [NSLocalizedDescriptionKey:"数据加载错误"]) finished(result: nil, error: dateError) }) { (_, error) -> Void in finished(result: nil, error: error) print(error) } }else if requestMethod == HTTPMothod.POST { NetWorkingTools.sharedTools.POST(urlString, parameters: parameters, success: { (_, result) -> Void in if let dict = result as? [AnyObject] { finished(result: dict, error: nil) } let dateError = NSError(domain: Domain, code: -11000, userInfo: [NSLocalizedDescriptionKey:"数据加载错误"]) finished(result: nil, error: dateError) }) { (_, error) -> Void in finished(result: nil, error: error) print(error) } } } //添加上传图片的方法 func uploadImage(urlString: String,parmaters: [String : AnyObject]?,imageData: NSData,finished: (result: [String : AnyObject]?, error: NSError?) -> ()) { POST(urlString, parameters: parmaters, constructingBodyWithBlock: { (multipartFormData) -> Void in //1.data 要上传的文件的二进制数据 //2.name 表示上传的文件服务器对应的字段 //3.filename 表示服务器接受后 存储的名字 名字可以随便取 //4.上传文件的格式 image/jpeg multipartFormData.appendPartWithFileData(imageData, name: "pic", fileName: "OMG", mimeType: "image/jpeg") }, success: { (_, result) -> Void in if let dict = result as? [String : AnyObject] { finished(result: dict, error: nil) } }) { (_, error) -> Void in finished(result: nil, error: error) print(error) } } }
9e6b21e27832ea601e506677d2baf641
38.798319
157
0.558488
false
false
false
false
khoren93/SwiftHub
refs/heads/master
SwiftHub/Modules/Events/EventCellViewModel.swift
mit
1
// // EventCellViewModel.swift // SwiftHub // // Created by Sygnoos9 on 9/6/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import Foundation import RxSwift import RxCocoa class EventCellViewModel: DefaultTableViewCellViewModel { let event: Event let userSelected = PublishSubject<User>() init(with event: Event) { self.event = event super.init() let actorName = event.actor?.login ?? "" var badgeImage: UIImage? var actionText = "" var body = "" switch event.type { case .fork: actionText = "forked" badgeImage = R.image.icon_cell_badge_fork() case .create: let payload = event.payload as? CreatePayload actionText = ["created", (payload?.refType.rawValue ?? ""), (payload?.ref ?? ""), "in"].joined(separator: " ") badgeImage = payload?.refType.image() case .delete: let payload = event.payload as? DeletePayload actionText = ["deleted", (payload?.refType.rawValue ?? ""), (payload?.ref ?? ""), "in"].joined(separator: " ") badgeImage = payload?.refType.image() case .issueComment: let payload = event.payload as? IssueCommentPayload actionText = ["commented on issue", "#\(payload?.issue?.number ?? 0)", "at"].joined(separator: " ") body = payload?.comment?.body ?? "" badgeImage = R.image.icon_cell_badge_comment() case .issues: let payload = event.payload as? IssuesPayload actionText = [(payload?.action ?? ""), "issue", "in"].joined(separator: " ") body = payload?.issue?.title ?? "" badgeImage = R.image.icon_cell_badge_issue() case .member: let payload = event.payload as? MemberPayload actionText = [(payload?.action ?? ""), "\(payload?.member?.login ?? "")", "as a collaborator to"].joined(separator: " ") badgeImage = R.image.icon_cell_badge_collaborator() case .pullRequest: let payload = event.payload as? PullRequestPayload actionText = [(payload?.action ?? ""), "pull request", "#\(payload?.number ?? 0)", "in"].joined(separator: " ") body = payload?.pullRequest?.title ?? "" badgeImage = R.image.icon_cell_badge_pull_request() case .pullRequestReviewComment: let payload = event.payload as? PullRequestReviewCommentPayload actionText = ["commented on pull request", "#\(payload?.pullRequest?.number ?? 0)", "in"].joined(separator: " ") body = payload?.comment?.body ?? "" badgeImage = R.image.icon_cell_badge_comment() case .push: let payload = event.payload as? PushPayload actionText = ["pushed to", payload?.ref ?? "", "at"].joined(separator: " ") badgeImage = R.image.icon_cell_badge_push() case .release: let payload = event.payload as? ReleasePayload actionText = [payload?.action ?? "", "release", payload?.release?.name ?? "", "in"].joined(separator: " ") body = payload?.release?.body ?? "" badgeImage = R.image.icon_cell_badge_tag() case .star: actionText = "starred" badgeImage = R.image.icon_cell_badge_star() default: break } let repoName = event.repository?.fullname ?? "" title.accept([actorName, actionText, repoName].joined(separator: " ")) detail.accept(event.createdAt?.toRelative()) secondDetail.accept(body) imageUrl.accept(event.actor?.avatarUrl) badge.accept(badgeImage?.template) badgeColor.accept(UIColor.Material.green) } } extension EventCellViewModel { static func == (lhs: EventCellViewModel, rhs: EventCellViewModel) -> Bool { return lhs.event == rhs.event } } extension CreateEventType { func image() -> UIImage? { switch self { case .repository: return R.image.icon_cell_badge_repository() case .branch: return R.image.icon_cell_badge_branch() case .tag: return R.image.icon_cell_badge_tag() } } } extension DeleteEventType { func image() -> UIImage? { switch self { case .repository: return R.image.icon_cell_badge_repository() case .branch: return R.image.icon_cell_badge_branch() case .tag: return R.image.icon_cell_badge_tag() } } }
e6422397ab23b85c2ac72de3b5ce39ca
38.429825
132
0.589766
false
false
false
false
ArthurKK/XCGLogger
refs/heads/master
XCGLogger/DemoApps/iOS/iOSDemo/iOSDemo/AppDelegate.swift
mit
4
// // AppDelegate.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright (c) 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import UIKit import XCGLogger let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let log: XCGLogger = { // Setup XCGLogger let log = XCGLogger.defaultInstance() log.xcodeColorsEnabled = true // Or set the XcodeColors environment variable in your scheme to YES log.xcodeColors = [ .Verbose: .lightGrey, .Debug: .darkGrey, .Info: .darkGreen, .Warning: .orange, .Error: XCGLogger.XcodeColor(fg: UIColor.redColor(), bg: UIColor.whiteColor()), // Optionally use a UIColor .Severe: XCGLogger.XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0)) // Optionally use RGB values directly ] #if USE_NSLOG // Set via Build Settings, under Other Swift Flags log.removeLogDestination(XCGLogger.constants.baseConsoleLogDestinationIdentifier) log.addLogDestination(XCGNSLogDestination(owner: log, identifier: XCGLogger.constants.nslogDestinationIdentifier)) log.logAppDetails() #else let logPath: NSURL = appDelegate.cacheDirectory.URLByAppendingPathComponent("XCGLogger_Log.txt") log.setup(logLevel: .Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath) #endif return log }() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Properties var window: UIWindow? let documentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as! NSURL }() let cacheDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as! NSURL }() // MARK: - Life cycle methods func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } func noop() { // Global no operation function, useful for doing nothing in a switch option, and examples }
68b2e69bbba140ac3c2f6a546057dce4
46.44186
285
0.738235
false
false
false
false
muukii/LightRoom
refs/heads/master
LightRoom/Classes/Operators.swift
mit
2
// // Operators.swift // LightRoom // // Created by Hiroshi Kimura on 2/27/16. // Copyright © 2016 muukii. All rights reserved. // import Foundation import CoreImage /** Connect FilterComponentType to FilterComponentType */ infix operator >>> : MultiplicationPrecedence /** Set inputBackgroundImage on CompositionComponentType */ infix operator --* : MultiplicationPrecedence @discardableResult public func >>> (chain1: FilterChain, chain2: FilterChain) -> FilterChain { chain2.inputImage = chain1.outputImage _ = chain1.connect(chain2) return chain2 } @discardableResult public func >>> (image: CIImage?, chain: FilterChain) -> FilterChain { chain.inputImage = image return chain } @discardableResult public func >>> (image: CIImage?, component: FilterComponentType) -> FilterComponentType { component.inputImage = image return component } @discardableResult public func >>> (chain1: FilterComponentType, component: FilterComponentType) -> FilterComponentType { component.inputImage = chain1.outputImage return component } @discardableResult public func >>> (gen: GeneratorComponent, component: FilterComponentType) -> FilterComponentType { component.inputImage = gen.outputImage return component } @discardableResult public func --* (chain1: FilterComponentType, component: CompositionFilterComponent) -> FilterComponentType { component.inputBackgroundImage = chain1.outputImage return component } @discardableResult public func --* (image: CIImage?, component: CompositionFilterComponent) -> FilterComponentType { component.inputBackgroundImage = image return component } @discardableResult public func --* (gen: GeneratorComponent, component: CompositionFilterComponent) -> FilterComponentType { component.inputBackgroundImage = gen.outputImage return component }
7868d6b24d3094e87bd15292286e9d21
26.205882
109
0.761622
false
false
false
false
yulingtianxia/pbxprojHelper
refs/heads/master
pbxprojHelper/ViewController.swift
gpl-3.0
1
// // ViewController.swift // pbxprojHelper // // Created by 杨萧玉 on 2016/9/24. // Copyright © 2016年 杨萧玉. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var filePathTF: NSTextField! @IBOutlet weak var resultTable: NSOutlineView! @IBOutlet weak var chooseJSONFileBtn: NSButton! @IBOutlet weak var filePathListView: NSView! @IBOutlet weak var filePathListHeightConstraint: NSLayoutConstraint! var propertyListURL: URL? var jsonFileURL: URL? var filterKeyWord = "" var originalPropertyList: [String: Any] = [:] var currentPropertyList: [String: Any] = [:] override func viewDidLoad() { filePathListView.isHidden = true let clickFilePathGesture = NSClickGestureRecognizer(target: self, action: #selector(ViewController.handleClickFilePath(_:))) filePathTF.addGestureRecognizer(clickFilePathGesture) let chooseFilePathGesture = NSClickGestureRecognizer(target: self, action: #selector(ViewController.chooseFilePathGesture(_:))) filePathListView.addGestureRecognizer(chooseFilePathGesture) } func refreshFilePathListView() { if !filePathListView.isHidden { for view in filePathListView.subviews { view.removeFromSuperview() } let textFieldHeight = filePathTF.bounds.size.height filePathListHeightConstraint.constant = CGFloat(recentUsePaths.count) * textFieldHeight var nextOriginY: CGFloat = CGFloat(recentUsePaths.count - 1) * textFieldHeight for key in recentUsePaths { let path = recentUsePaths[key] let textField = NSTextField(string: path!) textField.toolTip = key textField.isBordered = false textField.frame = NSRect(x: CGFloat(0), y: nextOriginY, width: filePathListView.bounds.size.width, height: textFieldHeight) filePathListView.addSubview(textField) nextOriginY -= textFieldHeight } } } func handleSelectProjectFileURL(_ url: URL) { filePathTF.stringValue = url.path propertyListURL = url originalPropertyList = [:] currentPropertyList = [:] if let data = PropertyListHandler.parseProject(fileURL: url) { let shortURL: URL if url.lastPathComponent == "project.pbxproj" { shortURL = url.deletingLastPathComponent() } else { shortURL = url } recentUsePaths[url.path] = shortURL.path originalPropertyList = data currentPropertyList = data resultTable.reloadData() refreshFilePathListView() } } func handleSelectJSONFileURL(_ url: URL) { if let data = PropertyListHandler.parseJSON(fileURL: url) as? [String: Any] { self.jsonFileURL = url self.currentPropertyList = PropertyListHandler.apply(json: data, onProjectData: self.originalPropertyList) self.chooseJSONFileBtn.title = url.lastPathComponent if let projectPath = self.propertyListURL?.path { projectConfigurationPathPairs[projectPath] = url } self.resultTable.reloadData() } } } //MARK: - User Action extension ViewController { @IBAction func selectProjectFile(_ sender: NSButton) { let openPanel = NSOpenPanel() openPanel.prompt = "Select" openPanel.canChooseFiles = true openPanel.canChooseDirectories = false openPanel.allowsMultipleSelection = false openPanel.allowedFileTypes = ["pbxproj", "xcodeproj"] openPanel.begin { (result) in if NSApplication.ModalResponse.OK == result, let url = openPanel.url { storeBookmark(url: url) self.handleSelectProjectFileURL(url) } } } @objc func handleClickFilePath(_ gesture: NSClickGestureRecognizer) { filePathListView.isHidden = !filePathListView.isHidden refreshFilePathListView() } @objc func chooseFilePathGesture(_ gesture: NSClickGestureRecognizer) { let clickPoint = gesture.location(in: gesture.view) for (index, subview) in filePathListView.subviews.enumerated() { let pointInSubview = subview.convert(clickPoint, from: filePathListView) if subview.bounds.contains(pointInSubview) { let path = recentUsePaths[index] handleSelectProjectFileURL(URL(fileURLWithPath: path)) } } filePathListView.isHidden = true } @IBAction func chooseJSONFile(_ sender: NSButton) { let openPanel = NSOpenPanel() openPanel.prompt = "Select" openPanel.allowsMultipleSelection = false openPanel.canChooseFiles = true openPanel.canChooseDirectories = false openPanel.begin { (result) in if NSApplication.ModalResponse.OK == result, let url = openPanel.url { storeBookmark(url: url) self.handleSelectJSONFileURL(url) } } } func handleApplyJson(forward isForward: Bool) { if let propertyURL = propertyListURL, let jsonURL = jsonFileURL { if let propertyListData = PropertyListHandler.parseProject(fileURL: propertyURL), let jsonFileData = PropertyListHandler.parseJSON(fileURL: jsonURL) as? [String: Any]{ originalPropertyList = propertyListData currentPropertyList = PropertyListHandler.apply(json: jsonFileData, onProjectData: originalPropertyList, forward: isForward) resultTable.reloadData() } DispatchQueue.global().async { PropertyListHandler.generateProject(fileURL: propertyURL, withPropertyList: self.currentPropertyList) } } } @IBAction func applyJSONConfiguration(_ sender: NSButton) { handleApplyJson(forward: true) } @IBAction func revertJSONConfiguration(_ sender: NSButton) { handleApplyJson(forward: false) } @IBAction func click(_ sender: NSOutlineView) { if sender.clickedRow >= 0 && sender.clickedColumn >= 0 { let item = sender.item(atRow: sender.clickedRow) let column = sender.tableColumns[sender.clickedColumn] if let selectedString = self.outlineView(sender, objectValueFor: column, byItem: item) as? String { writePasteboard(selectedString) } } } @IBAction func doubleClick(_ sender: NSOutlineView) { if sender.selectedRow >= 0 { let item = sender.item(atRow: sender.clickedRow) let path = keyPath(forItem: item) writePasteboard(path) } } } //MARK: - NSOutlineViewDataSource extension ViewController: NSOutlineViewDataSource { func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if item == nil { if filterKeyWord != "" { return elementsOfDictionary(currentPropertyList, containsKeyWord: filterKeyWord).count } return currentPropertyList.count } let itemValue = (item as? Item)?.value if let dictionary = itemValue as? [String: Any] { if filterKeyWord != "" && !((item as? Item)?.key.lowercased().contains(filterKeyWord.lowercased()) ?? false) { return elementsOfDictionary(dictionary, containsKeyWord: filterKeyWord).count } return dictionary.count } if let array = itemValue as? [Any] { if filterKeyWord != "" && !((item as? Item)?.key.lowercased().contains(filterKeyWord.lowercased()) ?? false) { return elementsOfArray(array, containsKeyWord: filterKeyWord).count } return array.count } return 0 } func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { return self.outlineView(outlineView, numberOfChildrenOfItem: item) > 0 } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { let itemValue = (item as? Item)?.value if var dictionary = item == nil ? currentPropertyList : (itemValue as? [String: Any]) { if filterKeyWord != "" && !((item as? Item)?.key.lowercased().contains(filterKeyWord.lowercased()) ?? false) { dictionary = elementsOfDictionary(dictionary, containsKeyWord: filterKeyWord) } let keys = Array(dictionary.keys) let key = keys[index] let value = dictionary[key] ?? "" let childItem = Item(key: key, value: value, parent: item) return childItem } if var array = (itemValue as? [String]) { if filterKeyWord != "" && !((item as? Item)?.key.lowercased().contains(filterKeyWord.lowercased()) ?? false) { array = elementsOfArray(array, containsKeyWord: filterKeyWord) as! [String] } return Item(key: array[index], value: "", parent: item) } return Item(key: "", value: "", parent: item) } func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? { if let pair = item as? Item { if tableColumn?.identifier.rawValue == "Key" { return pair.key } if tableColumn?.identifier.rawValue == "Value" { if let value = pair.value as? [String: Any] { return "Dictionary (\(value.count) elements)" } if let value = pair.value as? [Any] { return "Array (\(value.count) elements)" } return pair.value } } return nil } } //MARK: - NSOutlineViewDelegate extension ViewController: NSOutlineViewDelegate { func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool { return false } } //MARK: - NSTextFieldDelegate extension ViewController: NSTextFieldDelegate { func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { filterKeyWord = fieldEditor.string resultTable.reloadData() resultTable.expandItem(nil, expandChildren: true) return true } }
e251c0c2aaa2e43017409d3c127c2b12
38.518519
140
0.617807
false
false
false
false
KrishMunot/swift
refs/heads/master
test/decl/func/default-values.swift
apache-2.0
3
// RUN: %target-parse-verify-swift var func5 : (fn : (Int,Int) -> ()) -> () // Default arguments for functions. func foo3(a: Int = 2, b: Int = 3) {} func functionCall() { foo3(a: 4) foo3() foo3(a : 4) foo3(b : 4) foo3(a : 2, b : 4) } func g() {} func h(_ x: () -> () = g) { x() } // Tuple types cannot have default values, but recover well here. func tupleTypes() { typealias ta1 = (a : Int = ()) // expected-error{{default argument not permitted in a tuple type}}{{28-32=}} // expected-error @-1{{cannot create a single-element tuple with an element label}}{{20-24=}} var c1 : (a : Int, b : Int, c : Int = 3, // expected-error{{default argument not permitted in a tuple type}}{{39-42=}} d = 4) = (1, 2, 3, 4) // expected-error{{default argument not permitted in a tuple type}}{{15-18=}} expected-error{{use of undeclared type 'd'}} } func returnWithDefault() -> (a: Int, b: Int = 42) { // expected-error{{default argument not permitted in a tuple type}} {{45-49=}} return 5 // expected-error{{cannot convert return expression of type 'Int' to return type '(a: Int, b: Int)'}} } func selectorStyle(_ i: Int = 1, withFloat f: Float = 2) { } // Default arguments of constructors. struct Ctor { init (i : Int = 17, f : Float = 1.5) { } } Ctor() // expected-warning{{unused}} Ctor(i: 12) // expected-warning{{unused}} Ctor(f:12.5) // expected-warning{{unused}} // Default arguments for nested constructors/functions. struct Outer<T> { struct Inner { // expected-error{{type 'Inner' nested in generic type}} struct VeryInner {// expected-error{{type 'VeryInner' nested in generic type}} init (i : Int = 17, f : Float = 1.5) { } static func f(i: Int = 17, f: Float = 1.5) { } func g(i: Int = 17, f: Float = 1.5) { } } } } Outer<Int>.Inner.VeryInner() // expected-warning{{unused}} Outer<Int>.Inner.VeryInner(i: 12) // expected-warning{{unused}} Outer<Int>.Inner.VeryInner(f:12.5) // expected-warning{{unused}} Outer<Int>.Inner.VeryInner.f() Outer<Int>.Inner.VeryInner.f(i: 12) Outer<Int>.Inner.VeryInner.f(f:12.5) var vi : Outer<Int>.Inner.VeryInner vi.g() vi.g(i: 12) vi.g(f:12.5) // <rdar://problem/14564964> crash on invalid func foo(_ x: WonkaWibble = 17) { } // expected-error{{use of undeclared type 'WonkaWibble'}} // Default arguments for initializers. class SomeClass2 { init(x: Int = 5) {} } class SomeDerivedClass2 : SomeClass2 { init() { super.init() } } func shouldNotCrash(_ a : UndefinedType, bar b : Bool = true) { // expected-error {{use of undeclared type 'UndefinedType'}} } // <rdar://problem/20749423> Compiler crashed while building simple subclass // code class SomeClass3 { init(x: Int = 5, y: Int = 5) {} } class SomeDerivedClass3 : SomeClass3 {} _ = SomeDerivedClass3() // Tuple types with default arguments are not materializable func identity<T>(_ t: T) -> T { return t } func defaultArgTuplesNotMaterializable(_ x: Int, y: Int = 0) {} defaultArgTuplesNotMaterializable(identity(5)) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands defaultArgTuplesNotMaterializable(identity((5, y: 10))) // expected-error@-1 {{cannot convert value of type '(Int, y: Int)' to expected argument type 'Int'}} // rdar://problem/21799331 func foo<T>(_ x: T, y: Bool = true) {} foo(true ? "foo" : "bar") func foo2<T>(_ x: T, y: Bool = true) {} extension Array { func bar(_ x: Element -> Bool) -> Int? { return 0 } } foo2([].bar { $0 == "c" }!) // rdar://problem/21643052 let a = ["1", "2"].map { Int($0) }
d71f8512609f25097747e8721f691cc9
30.40708
156
0.641871
false
false
false
false
darren90/Gankoo_Swift
refs/heads/master
Gankoo/Gankoo/Classes/Me/MeViewController.swift
apache-2.0
1
// // MeViewController.swift // Gankoo // // Created by Fengtf on 2017/2/7. // Copyright © 2017年 ftf. All rights reserved. // import UIKit class MeViewController: BaseViewController { lazy var tableView:UITableView = UITableView(frame: self.view.bounds, style: .plain) var dataArray:[DataModel] = [DataModel](){ didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false initTableView() //最底部的空间,设置距离底部的间距(autolayout),然后再设置这两个属性,就可以自动计算高度 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 tableView.separatorStyle = .none } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dataArray = RMDBTools.shareInstance.getAllDatas() } func initTableView(){ view.addSubview(tableView) tableView.frame = CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.height - 64 - 49) tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.white let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(self.loadNew)) tableView.mj_header = header tableView.mj_header.beginRefreshing() // tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(self.loadMore)) // tableView.isEditing //多行编辑 // tableView.allowsMultipleSelectionDuringEditing = true } func loadNew() { endReresh() dataArray = RMDBTools.shareInstance.getAllDatas() } func endReresh(){ self.tableView.mj_header.endRefreshing() // self.tableView.mj_footer.endRefreshing() } } extension MeViewController : UITableViewDataSource,UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { noDataView.isHidden = !(dataArray.count == 0) return dataArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = DataListCell.cellWithTableView(tableView: tableView) let model = dataArray[indexPath.row] cell.model = model return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = dataArray[indexPath.row] guard let urlStr = model.url else { return } if urlStr.characters.count == 0 { return } let url = URL(string: urlStr) let vc = DataDetailController(url: url!, entersReaderIfAvailable: true) present(vc, animated: true, completion: nil) tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete {//删除操作 } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleAction = UITableViewRowAction(style: .destructive, title: "取消收藏", handler: { (action, indexPath) in let model = self.dataArray[indexPath.row] RMDBTools.shareInstance.deleData(model) self.dataArray.remove(at: indexPath.row) // tableView.deleteRows(at: [indexPath], with: .left) // self.noDataView.isHidden = !(self.dataArray.count == 0) }) return [deleAction] } }
c817eb7a7d410101c16876d532c23dec
25.626761
127
0.653531
false
false
false
false
IvanVorobei/TwitterLaunchAnimation
refs/heads/master
TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/views/SPShadowWithMaskView.swift
mit
1
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 SPShadowWithMaskView: UIView { public let contentView: UIView = UIView() public init() { super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.contentView.layer.masksToBounds = true self.layer.masksToBounds = false self.backgroundColor = UIColor.clear self.addSubview(contentView) self.updateShadow() } public override func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds self.layer.cornerRadius = self.contentView.layer.cornerRadius } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) self.updateShadow() } private var xTranslationFactor: CGFloat = 0 private var yTranslationFactor: CGFloat = 0 private var widthRelativeFactor: CGFloat = 0 private var heightRelativeFactor: CGFloat = 0 private var blurRadiusFactor: CGFloat = 0 private var shadowOpacity: CGFloat = 0 public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) { super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor) self.xTranslationFactor = xTranslationFactor self.yTranslationFactor = yTranslationFactor self.widthRelativeFactor = widthRelativeFactor self.heightRelativeFactor = heightRelativeFactor self.blurRadiusFactor = blurRadiusFactor self.shadowOpacity = shadowOpacity } private func updateShadow() { self.setShadow( xTranslationFactor: self.xTranslationFactor, yTranslationFactor: self.yTranslationFactor, widthRelativeFactor: self.widthRelativeFactor, heightRelativeFactor: self.heightRelativeFactor, blurRadiusFactor: self.blurRadiusFactor, shadowOpacity: self.shadowOpacity ) } } public class SPShadowWithMaskControl: UIControl { public let contentView: UIView = UIView() public init() { super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.contentView.layer.masksToBounds = true self.layer.masksToBounds = false self.backgroundColor = UIColor.clear self.addSubview(contentView) self.updateShadow() } public override func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds self.layer.cornerRadius = self.contentView.layer.cornerRadius } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) self.updateShadow() } private var xTranslationFactor: CGFloat = 0 private var yTranslationFactor: CGFloat = 0 private var widthRelativeFactor: CGFloat = 0 private var heightRelativeFactor: CGFloat = 0 private var blurRadiusFactor: CGFloat = 0 private var shadowOpacity: CGFloat = 0 public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) { super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor) self.xTranslationFactor = xTranslationFactor self.yTranslationFactor = yTranslationFactor self.widthRelativeFactor = widthRelativeFactor self.heightRelativeFactor = heightRelativeFactor self.blurRadiusFactor = blurRadiusFactor self.shadowOpacity = shadowOpacity } private func updateShadow() { self.setShadow( xTranslationFactor: self.xTranslationFactor, yTranslationFactor: self.yTranslationFactor, widthRelativeFactor: self.widthRelativeFactor, heightRelativeFactor: self.heightRelativeFactor, blurRadiusFactor: self.blurRadiusFactor, shadowOpacity: self.shadowOpacity ) } }
51f1ad6625880f769f3f0243a74bfbb6
39.410256
295
0.711136
false
false
false
false
shadanan/mado
refs/heads/master
Antlr4Runtime/Sources/Antlr4/misc/MurmurHash.swift
mit
1
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** * * @author Sam Harwell */ public final class MurmurHash { private static let DEFAULT_SEED: Int = 0 /** * Initialize the hash using the default seed value. * * @return the intermediate hash value */ public static func initialize() -> Int { return initialize(DEFAULT_SEED) } /** * Initialize the hash using the specified {@code seed}. * * @param seed the seed * @return the intermediate hash value */ public static func initialize(_ seed: Int) -> Int { return seed } /** * Update the intermediate hash value for the next input {@code value}. * * @param hash the intermediate hash value * @param value the value to add to the current hash * @return the updated intermediate hash value */ public static func update2(_ hashIn: Int, _ value: Int) -> Int { let c1: Int32 = -862048943//0xCC9E2D51; let c2: Int32 = 0x1B873593 let r1: Int32 = 15 let r2: Int32 = 13 let m: Int32 = 5 let n: Int32 = -430675100//0xE6546B64; var k: Int32 = Int32(truncatingBitPattern: value) k = Int32.multiplyWithOverflow(k, c1).0 // (k,_) = UInt32.multiplyWithOverflow(k, c1) ;//( k * c1); //TODO: CHECKE >>> k = (k << r1) | (k >>> (Int32(32) - r1)) //k = (k << r1) | (k >>> (32 - r1)); //k = UInt32 (truncatingBitPattern:Int64(Int64(k) * Int64(c2)));//( k * c2); //(k,_) = UInt32.multiplyWithOverflow(k, c2) k = Int32.multiplyWithOverflow(k, c2).0 var hash = Int32(hashIn) hash = hash ^ k hash = (hash << r2) | (hash >>> (Int32(32) - r2))//hash = (hash << r2) | (hash >>> (32 - r2)); (hash, _) = Int32.multiplyWithOverflow(hash, m) (hash, _) = Int32.addWithOverflow(hash, n) //hash = hash * m + n; // print("murmur update2 : \(hash)") return Int(hash) } /** * Update the intermediate hash value for the next input {@code value}. * * @param hash the intermediate hash value * @param value the value to add to the current hash * @return the updated intermediate hash value */ public static func update<T:Hashable>(_ hash: Int, _ value: T?) -> Int { return update2(hash, value != nil ? value!.hashValue : 0) // return update2(hash, value); } /** * Apply the final computation steps to the intermediate value {@code hash} * to form the final result of the MurmurHash 3 hash function. * * @param hash the intermediate hash value * @param numberOfWords the number of integer values added to the hash * @return the final hash result */ public static func finish(_ hashin: Int, _ numberOfWordsIn: Int) -> Int { var hash = Int32(hashin) let numberOfWords = Int32(numberOfWordsIn) hash = hash ^ Int32.multiplyWithOverflow(numberOfWords, Int32(4)).0 //(numberOfWords * UInt32(4)); hash = hash ^ (hash >>> Int32(16)) //hash = hash ^ (hash >>> 16); (hash, _) = Int32.multiplyWithOverflow(hash, Int32(-2048144789))//hash * UInt32(0x85EBCA6B); hash = hash ^ (hash >>> Int32(13))//hash = hash ^ (hash >>> 13); //hash = UInt32(truncatingBitPattern: UInt64(hash) * UInt64(0xC2B2AE35)) ; (hash, _) = Int32.multiplyWithOverflow(hash, Int32(-1028477387)) hash = hash ^ (hash >>> Int32(16))// hash = hash ^ (hash >>> 16); //print("murmur finish : \(hash)") return Int(hash) } /** * Utility function to compute the hash code of an array using the * MurmurHash algorithm. * * @param <T> the array element type * @param data the array data * @param seed the seed for the MurmurHash algorithm * @return the hash code of the data */ public static func hashCode<T:Hashable>(_ data: [T], _ seed: Int) -> Int { var hash: Int = initialize(seed) for value: T in data { //var hashValue = value != nil ? value.hashValue : 0 hash = update(hash, value.hashValue) } hash = finish(hash, data.count) return hash } private init() { } }
bc6e4658719c983fb0abb7d843cfa71b
34.095238
107
0.580733
false
false
false
false
Draveness/DKChainableAnimationKit
refs/heads/master
Carthage/Checkouts/DKChainableAnimationKit/DKChainableAnimationKit/Classes/DKChainableAnimationKit+Extra.swift
apache-2.0
3
// // DKChainableAnimationKit+Extra.swift // DKChainableAnimationKit // // Created by Draveness on 15/6/14. // Copyright (c) 2015年 Draveness. All rights reserved. // import Foundation public extension DKChainableAnimationKit { public func makeOpacity(_ opacity: CGFloat) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let opacityAnimation = self.basicAnimationForKeyPath("opacity") opacityAnimation.fromValue = view.alpha as AnyObject! opacityAnimation.toValue = opacity as AnyObject! self.addAnimationFromCalculationBlock(opacityAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.alpha = opacity } return self } public func makeAlpha(_ alpha: CGFloat) -> DKChainableAnimationKit { return makeOpacity(alpha) } public func makeBackground(_ color: UIColor) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let backgroundColorAnimation = self.basicAnimationForKeyPath("backgroundColor") backgroundColorAnimation.fromValue = view.backgroundColor backgroundColorAnimation.toValue = color self.addAnimationFromCalculationBlock(backgroundColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.backgroundColor = color } return self } public func makeBorderColor(_ color: UIColor) -> DKChainableAnimationKit { self.addAnimationCalculationAction { (view: UIView) -> Void in let borderColorAnimation = self.basicAnimationForKeyPath("borderColor") borderColorAnimation.fromValue = UIColor(cgColor: view.layer.borderColor!) borderColorAnimation.toValue = color self.addAnimationFromCalculationBlock(borderColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.borderColor = color.cgColor } return self } public func makeBorderWidth(_ width: CGFloat) -> DKChainableAnimationKit { let width = max(0, width) self.addAnimationCalculationAction { (view: UIView) -> Void in let borderColorAnimation = self.basicAnimationForKeyPath("borderWidth") borderColorAnimation.fromValue = view.layer.borderWidth as AnyObject! borderColorAnimation.toValue = width as AnyObject! self.addAnimationFromCalculationBlock(borderColorAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.borderWidth = width } return self } public func makeCornerRadius(_ cornerRadius: CGFloat) -> DKChainableAnimationKit { let cornerRadius = max(0, cornerRadius) self.addAnimationCalculationAction { (view: UIView) -> Void in let cornerRadiusAnimation = self.basicAnimationForKeyPath("cornerRadius") cornerRadiusAnimation.fromValue = view.layer.cornerRadius as AnyObject! cornerRadiusAnimation.toValue = cornerRadius as AnyObject! self.addAnimationFromCalculationBlock(cornerRadiusAnimation) } self.addAnimationCompletionAction { (view: UIView) -> Void in view.layer.cornerRadius = cornerRadius } return self } }
f270c56f2348dce5d95659754077234c
37.932584
91
0.677633
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Model/LineCourse.swift
gpl-3.0
1
import Foundation class LineCourse { let id: Int let busStop: BBusStop let time: String let active: Bool let pin: Bool let bus: Bool var lineText: NSAttributedString? = nil init(id: Int, busStop: BBusStop, time: String, active: Bool, pin: Bool, bus: Bool) { self.id = id self.busStop = busStop self.time = time self.active = active self.pin = pin self.bus = bus } }
94d3b773c8ca0c4d2582f26d22b8c64b
18
88
0.585526
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
refs/heads/master
Source/BorderStyle.swift
apache-2.0
4
// // BorderStyle.swift // edX // // Created by Akiva Leffert on 6/4/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class BorderStyle { enum Width { case Hairline case Size(CGFloat) var value : CGFloat { switch self { case Hairline: return OEXStyles.dividerSize() case let Size(s): return s } } } enum Radius { case Circle case Size(CGFloat) func value(view: UIView) -> CGFloat { switch self { case Circle: return view.frame.size.height / 2.0 case let Size(s): return s } } } static let defaultCornerRadius = OEXStyles.sharedStyles().boxCornerRadius() let cornerRadius : Radius let width : Width let color : UIColor? init(cornerRadius : Radius = .Size(BorderStyle.defaultCornerRadius), width : Width = .Size(0), color : UIColor? = nil) { self.cornerRadius = cornerRadius self.width = width self.color = color } private func applyToView(view : UIView) { let radius = cornerRadius.value(view) view.layer.cornerRadius = radius view.layer.borderWidth = width.value view.layer.borderColor = color?.CGColor if radius != 0 { view.clipsToBounds = true } } class func clearStyle() -> BorderStyle { return BorderStyle() } } extension UIView { func applyBorderStyle(style : BorderStyle) { style.applyToView(self) } }
9bc05d8b6c588eb1ee5a863bbf2a5a8b
23.149254
124
0.566749
false
false
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Expand/Category/UIDatePicker.swift
mit
1
// // UIDatePicker.swift // YCOA // // Created by Jerry on 2016/12/19. // Copyright © 2016年 com.baochunsteel. All rights reserved. // import Foundation extension UIDatePicker { /// 弹出选择日期的View /// /// - Parameters: /// - minDate: 最小可选日期 /// - maxDate: 最大可选日期 /// - onView: 承载的View /// - datePickerMode: datePickerMode /// - tap: 选择后的回调(Date) class func showDidSelectView(minDate: Date?, maxDate: Date?, onView: UIView, datePickerMode: UIDatePickerMode, tap:@escaping (Date)-> Void) { var date = Date() let superView_ = UIView(frame: CGRect(x: 0, y: 0, width: onView.bounds.width, height: onView.bounds.height / 3 * 2)) superView_.alpha = 0.0 onView.addSubview(superView_) superView_.backgroundColor = UIColor.black let datePicker = UIDatePicker(frame: CGRect(x: 0, y: onView.bounds.height / 3 * 2, width: onView.bounds.width, height: onView.bounds.height / 3)) datePicker.minimumDate = minDate datePicker.maximumDate = maxDate datePicker.datePickerMode = .dateAndTime datePicker.date = Date() datePicker.alpha = 0.0 datePicker.backgroundColor = UIColor.white onView.addSubview(datePicker) UIView.animate(withDuration: 0.5) { superView_.alpha = 0.5 datePicker.alpha = 1.0 } datePicker.rac_signal(for: .valueChanged).subscribeNext { (sender) in date = (sender as! UIDatePicker).date } superView_.isUserInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer { (sender) in tap(date) UIView.animate(withDuration: 0.5, animations: { superView_.alpha = 0.0 datePicker.alpha = 0.0 }, completion: { (isCompletion) in superView_.removeFromSuperview() datePicker.removeFromSuperview() }) } superView_.addGestureRecognizer(tapGestureRecognizer) } }
3fdd58efe1c0fa22a49b9ff4050d0358
34.169492
153
0.598554
false
false
false
false
Virpik/T
refs/heads/master
src/UI/TableView/TableViewModel/TableViewModel.swift
mit
1
// // TImage.swift // TDemo // // Created by Virpik on 26/10/2017. // Copyright © 2017 Virpik. All rights reserved. // import Foundation import UIKit open class TableViewModel: NSObject, UITableViewDelegate, UITableViewDataSource { public let tableView: UITableView public var sections: [[AnyRowModel]] = [] // public var moveHandlers: MoveHandlers? { // set(handlers) { // self._managerMoveCells.handlers = handlers // } // // get { // return self._managerMoveCells.handlers // } // } // public var handlers: Handlers = Handlers() public var cellMoviesPressDuration: TimeInterval { get { return self.managerMoveCells.cellMoviesPressDuration } set(value) { self.managerMoveCells.cellMoviesPressDuration = value } } public lazy var managerMoveCells: ManagerMoveCells = { let ds = TableViewModel.ManagerMoveCells.DataSourse { (indexPath) -> AnyRowModel? in return self.sections[indexPath.section][indexPath.row] } return ManagerMoveCells(tableView: self.tableView, dataSourse: ds) }() private var _cashHeightRows: [IndexPath: CGSize] = [:] public init (tableView: UITableView, handlers: Handlers? = nil) { self.tableView = tableView if let handlers = handlers { self.handlers = handlers } super.init() self.tableView.delegate = self self.tableView.dataSource = self var mHandlers = MoveHandlers() mHandlers.handlerBeginMove = { context in // self.handlers.moveHandlers?.handlerBeginMove?(context) } mHandlers.handlerMove = { atContext, toContext in // self.handlers.moveHandlers?.handlerMove?(atContext, toContext) } mHandlers.handlerDidMove = { atContex, toContext in let atIndexPath = atContex.indexPath let toIndexPath = toContext.indexPath let item = self.sections[atIndexPath.section][atIndexPath.row] self.sections[atIndexPath.section].remove(at: atIndexPath.row) self.sections[toIndexPath.section].insert(item, at: toIndexPath.row) self.handlers.moveHandlers?.handlerDidMove?(atContex, toContext) } mHandlers.handlerEndMove = { atContext, toContext in // self.handlers.moveHandlers?.handlerEndMove?(atContext, toContext) } self.managerMoveCells.handlers = mHandlers } public func set(sections: [[AnyRowModel]]){ self.sections = sections sections.forEach { $0.forEach({ (rowModel) in if rowModel.rowType.self == UITableViewCell.self { return } self.tableView.register(type: rowModel.rowType.self, isNib: rowModel.isNib) }) } self.tableView.reloadData() } public func reload(rows: [Row]) { rows.forEach { (row) in self.sections[row.indexPath.section][row.indexPath.row] = row.rowModel if let cell = self.tableView.cellForRow(at: row.indexPath) { row.rowModel.build(cell: cell, indexPath: row.indexPath) } } } public func remove(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .bottom) { self.tableView.beginUpdates() self.sections = sections self.tableView.deleteRows(at: indexPaths, with: animation) self.tableView.endUpdates() } public func update(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .automatic) { self.tableView.beginUpdates() self.sections = sections self.tableView.reloadRows(at: indexPaths, with: animation) self.tableView.endUpdates() } public func insert(sections: [[AnyRowModel]], indexPaths: [IndexPath], animation: UITableView.RowAnimation = .bottom) { self.tableView.beginUpdates() self.sections = sections self.tableView.insertRows(at: indexPaths, with: animation) self.tableView.endUpdates() } public func insert(rows: [Row]) { self.tableView.beginUpdates() rows.forEach { row in self.sections[row.indexPath.section].insert(row.rowModel, at: row.indexPath.row) self.tableView.insertRows(at: [row.indexPath], with: row.animation) } self.tableView.endUpdates() } public func replace(rows: [Row]) { self.tableView.beginUpdates() rows.forEach { row in self.sections[row.indexPath.section][row.indexPath.row] = row.rowModel self.tableView.reloadRows(at: [row.indexPath], with: row.animation) } self.tableView.endUpdates() } public func remove(rows: [(IndexPath, UITableView.RowAnimation)]) { self.tableView.beginUpdates() rows.forEach { row in self.sections[row.0.section].remove(at: row.0.row) self.tableView.deleteRows(at: [row.0], with: row.1) } self.tableView.endUpdates() } // MARK: - scroll view open func scrollViewDidScroll(_ scrollView: UIScrollView) { // tLog(scrollView.contentOffset) self.handlers.handlerDidScroll?(scrollView) } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { // tLog(scrollView.contentOffset) } // MARK: - Table view delegate && data sourse open func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.sections[indexPath.section][indexPath.row].rowHeight ?? tableView.rowHeight } open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return self._cashHeightRows[indexPath]?.height ?? tableView.estimatedRowHeight } open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { self._cashHeightRows[indexPath] = cell.bounds.size } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sections[section].count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let model = self.sections[indexPath.section][indexPath.row] guard let cell = self.tableView.cell(type: model.rowType) else { return UITableViewCell() } model.build(cell: cell, indexPath: indexPath) return cell } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = self.sections[indexPath.section][indexPath.row] guard let cell = self.tableView.cellForRow(at: indexPath) else { return } model.didSelect(cell: cell, indexPath: indexPath) } }
5fabe4965c6814f1a020da954ce5dfbf
30.021008
126
0.616687
false
false
false
false
kakajika/Brief
refs/heads/master
Brief-OSX/Brief-OSX.swift
apache-2.0
2
// // Brief-OSX.swift // // Created by kakajika on 2015/08/20. // Copyright (c) 2015 INFOCITY, Inc. All rights reserved. // import Cocoa extension NSView { // Frame Origin public var x: CGFloat { get { return self.frame.origin.x } set(x) { self.frame.origin.x = x } } public var y: CGFloat { get { return self.frame.origin.y } set(y) { self.frame.origin.y = y } } // Frame Size public var width: CGFloat { get { return self.frame.width } set(width) { self.frame.size.width = width } } public var height: CGFloat { get { return self.frame.height } set(height) { self.frame.size.height = height } } // Frame Borders public var left: CGFloat { get { return self.frame.minX } set(left) { self.frame.origin.x = left - min(width, 0.0) } } public var top: CGFloat { get { return self.frame.minY } set(top) { self.frame.origin.y = top - min(height, 0.0) } } public var right: CGFloat { get { return self.frame.maxX } set(right) { self.frame.origin.x = right - max(width, 0.0) } } public var bottom: CGFloat { get { return self.frame.maxY } set(bottom) { self.frame.origin.y = bottom - max(height, 0.0) } } // Bounds public var boundsWidth: CGFloat { get { return self.bounds.width } set(boundsWidth) { self.bounds.size.width = boundsWidth } } public var boundsHeight: CGFloat { get { return self.bounds.height } set(boundsHeight) { self.bounds.size.height = boundsHeight } } // Bounds Borders public var boundsLeft: CGFloat { get { return self.bounds.minX } set(boundsLeft) { self.bounds.origin.x = boundsLeft - min(boundsWidth, 0.0) } } public var boundsTop: CGFloat { get { return self.bounds.minY } set(boundsTop) { self.bounds.origin.y = boundsTop - min(boundsHeight, 0.0) } } public var boundsRight: CGFloat { get { return self.bounds.maxX } set(boundsRight) { self.bounds.origin.x = boundsRight - max(boundsWidth, 0.0) } } public var boundsBottom: CGFloat { get { return self.bounds.maxY } set(boundsBottom) { self.bounds.origin.y = boundsBottom - max(boundsHeight, 0.0) } } } extension CALayer { // Frame Origin public var x: CGFloat { get { return self.frame.origin.x } set(x) { self.frame.origin.x = x } } public var y: CGFloat { get { return self.frame.origin.y } set(y) { self.frame.origin.y = y } } // Frame Size public var width: CGFloat { get { return self.frame.width } set(width) { self.frame.size.width = width } } public var height: CGFloat { get { return self.frame.height } set(height) { self.frame.size.height = height } } // Frame Borders public var left: CGFloat { get { return self.frame.minX } set(left) { self.frame.origin.x = left - min(width, 0.0) } } public var top: CGFloat { get { return self.frame.minY } set(top) { self.frame.origin.y = top - min(height, 0.0) } } public var right: CGFloat { get { return self.frame.maxX } set(right) { self.frame.origin.x = right - max(width, 0.0) } } public var bottom: CGFloat { get { return self.frame.maxY } set(bottom) { self.frame.origin.y = bottom - max(height, 0.0) } } // Bounds public var boundsWidth: CGFloat { get { return self.bounds.width } set(boundsWidth) { self.bounds.size.width = boundsWidth } } public var boundsHeight: CGFloat { get { return self.bounds.height } set(boundsHeight) { self.bounds.size.height = boundsHeight } } // Bounds Borders public var boundsLeft: CGFloat { get { return self.bounds.minX } set(boundsLeft) { self.bounds.origin.x = boundsLeft - min(boundsWidth, 0.0) } } public var boundsTop: CGFloat { get { return self.bounds.minY } set(boundsTop) { self.bounds.origin.y = boundsTop - min(boundsHeight, 0.0) } } public var boundsRight: CGFloat { get { return self.bounds.maxX } set(boundsRight) { self.bounds.origin.x = boundsRight - max(boundsWidth, 0.0) } } public var boundsBottom: CGFloat { get { return self.bounds.maxY } set(boundsBottom) { self.bounds.origin.y = boundsBottom - max(boundsHeight, 0.0) } } }
c665261e913a30f2898f6656a945945f
30.027027
90
0.584186
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
133. 16-functional-apis/FunctionalCoreImage/CoreImage.swift
mit
1
// // CoreImage.swift // FunctionalCoreImage // // Created by Florian on 10/09/14. // Copyright (c) 2014 objc.io. All rights reserved. // import UIKit typealias Filter = CIImage -> CIImage typealias Parameters = Dictionary<String, AnyObject> func blur(radius: Double) -> Filter { return { image in let parameters : Parameters = [kCIInputRadiusKey: radius, kCIInputImageKey: image] let filter = CIFilter(name:"CIGaussianBlur", withInputParameters:parameters) return filter!.outputImage! } } func colorGenerator(color: UIColor) -> Filter { return { _ in let filter = CIFilter(name:"CIConstantColorGenerator", withInputParameters: [kCIInputColorKey: CIColor(color: color)]) return filter!.outputImage! } } func compositeSourceOver(overlay: CIImage) -> Filter { return { image in let parameters : Parameters = [ kCIInputBackgroundImageKey: image, kCIInputImageKey: overlay ] let filter = CIFilter(name:"CISourceOverCompositing", withInputParameters: parameters) return filter!.outputImage!.imageByCroppingToRect(image.extent) } } func colorOverlay(color: UIColor) -> Filter { return { image in let overlay = colorGenerator(color)(image) return compositeSourceOver(overlay)(image) } } infix operator >|> { associativity left } func >|> (filter1: Filter, filter2: Filter) -> Filter { return { img in filter2(filter1(img)) } }
b50e5be5ac815915db4d95c2380e6431
26.962264
126
0.680162
false
false
false
false
IngmarStein/swift
refs/heads/master
test/IDE/complete_from_reexport.swift
apache-2.0
17
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-swift-frontend -emit-module -module-name FooSwiftModule %S/Inputs/foo_swift_module.swift -o %t // RUN: %target-swift-frontend -emit-module -module-name FooSwiftModuleOverlay %S/Inputs/foo_swift_module_overlay.swift -I %t -o %t // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 -I %t > %t.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_1 < %t.txt // RUN: %FileCheck %s -check-prefix=NO_DUPLICATES < %t.txt // TOP_LEVEL_1: Begin completions // TOP_LEVEL_1-DAG: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: overlayedFoo()[#Void#]{{; name=.+$}} // TOP_LEVEL_1-DAG: Decl[FreeFunction]/OtherModule[FooSwiftModuleOverlay]: onlyInFooOverlay()[#Void#]{{; name=.+$}} // TOP_LEVEL_1: End completions // FIXME: there should be only one instance of this completion result. // NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}} // NO_DUPLICATES: overlayedFoo()[#Void#]{{; name=.+$}} // NO_DUPLICATES-NOT: overlayedFoo()[#Void#]{{; name=.+$}} import FooSwiftModuleOverlay #^TOP_LEVEL_1^#
2159de1250ddb9ffdf50c3aa9fdac14d
47.347826
131
0.68795
false
false
false
false
v2panda/DaysofSwift
refs/heads/master
swift2.3/My-ImagePickerSheetController/My-ImagePickerSheetController/ImagePickerSheet/AnimationController.swift
mit
1
// // AnimationController.swift // ImagePickerSheet // // Created by Laurin Brandner on 25/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit class AnimationController: NSObject, UIViewControllerAnimatedTransitioning { let imagePickerSheetController: ImagePickerSheetController let presenting: Bool // MARK: - Initialization init(imagePickerSheetController: ImagePickerSheetController, presenting: Bool) { self.imagePickerSheetController = imagePickerSheetController self.presenting = presenting } // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.3 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if presenting { animatePresentation(transitionContext) } else { animateDismissal(transitionContext) } } // MARK: - Animation private func animatePresentation(context: UIViewControllerContextTransitioning) { let containerView = context.containerView()! containerView.addSubview(imagePickerSheetController.view) let tableViewOriginY = imagePickerSheetController.tableView.frame.origin.y imagePickerSheetController.tableView.frame.origin.y = containerView.bounds.maxY imagePickerSheetController.backgroundView.alpha = 0 UIView.animateWithDuration(transitionDuration(context), animations: { self.imagePickerSheetController.tableView.frame.origin.y = tableViewOriginY self.imagePickerSheetController.backgroundView.alpha = 1 }, completion: { _ in context.completeTransition(true) }) } private func animateDismissal(context: UIViewControllerContextTransitioning) { let containerView = context.containerView()! UIView.animateWithDuration(transitionDuration(context), animations: { self.imagePickerSheetController.tableView.frame.origin.y = containerView.bounds.maxY self.imagePickerSheetController.backgroundView.alpha = 0 }, completion: { _ in self.imagePickerSheetController.view.removeFromSuperview() context.completeTransition(true) }) } }
34887a38c893cab6bbea34b5b408193d
34.529412
105
0.700331
false
false
false
false
iOSTestApps/firefox-ios
refs/heads/master
Client/Frontend/Home/ReaderPanel.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import ReadingList import Shared private struct ReadingListTableViewCellUX { static let RowHeight: CGFloat = 86 static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44) static let ReadIndicatorWidth: CGFloat = 12 // image width static let ReadIndicatorHeight: CGFloat = 12 // image height static let ReadIndicatorTopOffset: CGFloat = 36.75 // half of the cell - half of the height of the asset static let ReadIndicatorLeftOffset: CGFloat = 18 static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest static let TitleLabelFont = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium) static let TitleLabelTopOffset: CGFloat = 14 - 4 static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16 static let TitleLabelRightOffset: CGFloat = -40 static let HostnameLabelFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight) static let HostnameLabelBottomOffset: CGFloat = 11 static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035) static let DeleteButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight) static let DeleteButtonTitleColor = UIColor.whiteColor() static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1) static let MarkAsReadButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight) static let MarkAsReadButtonTitleColor = UIColor.whiteColor() static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) // Localizable strings static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item") static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read") static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread") } private struct ReadingListPanelUX { // Welcome Screen static let WelcomeScreenTopPadding: CGFloat = 16 static let WelcomeScreenPadding: CGFloat = 10 static let WelcomeScreenHeaderFont = UIFont.boldSystemFontOfSize(14) static let WelcomeScreenHeaderTextColor = UIColor.darkGrayColor() static let WelcomeScreenItemFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight) static let WelcomeScreenItemTextColor = UIColor.lightGrayColor() static let WelcomeScreenItemWidth = 220 static let WelcomeScreenItemOffset = -20 static let WelcomeScreenCircleWidth = 40 static let WelcomeScreenCircleOffset = 20 static let WelcomeScreenCircleSpacer = 10 } class ReadingListTableViewCell: SWTableViewCell { var title: String = "Example" { didSet { titleLabel.text = title updateAccessibilityLabel() } } var url: NSURL = NSURL(string: "http://www.example.com")! { didSet { hostnameLabel.text = simplifiedHostnameFromURL(url) updateAccessibilityLabel() } } var unread: Bool = true { didSet { readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread") titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal) markAsReadAction.name = markAsReadButton.titleLabel!.text updateAccessibilityLabel() } } private let deleteAction: UIAccessibilityCustomAction private let markAsReadAction: UIAccessibilityCustomAction let readStatusImageView: UIImageView! let titleLabel: UILabel! let hostnameLabel: UILabel! let deleteButton: UIButton! let markAsReadButton: UIButton! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { readStatusImageView = UIImageView() titleLabel = UILabel() hostnameLabel = UILabel() deleteButton = UIButton() markAsReadButton = UIButton() deleteAction = UIAccessibilityCustomAction() markAsReadAction = UIAccessibilityCustomAction() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clearColor() separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0) layoutMargins = UIEdgeInsetsZero preservesSuperviewLayoutMargins = false contentView.addSubview(readStatusImageView) readStatusImageView.contentMode = UIViewContentMode.ScaleAspectFit readStatusImageView.snp_makeConstraints { (make) -> () in make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth) make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight) make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorTopOffset) make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset) } contentView.addSubview(titleLabel) titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor titleLabel.numberOfLines = 2 titleLabel.font = ReadingListTableViewCellUX.TitleLabelFont titleLabel.snp_makeConstraints { (make) -> () in make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset) make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset) make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec } contentView.addSubview(hostnameLabel) hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor hostnameLabel.numberOfLines = 1 hostnameLabel.font = ReadingListTableViewCellUX.HostnameLabelFont hostnameLabel.snp_makeConstraints { (make) -> () in make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset) make.left.right.equalTo(self.titleLabel) } deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor deleteButton.titleLabel?.font = ReadingListTableViewCellUX.DeleteButtonTitleFont deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal) deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets deleteAction.name = deleteButton.titleLabel!.text deleteAction.target = self deleteAction.selector = "deleteActionActivated" rightUtilityButtons = [deleteButton] markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor markAsReadButton.titleLabel?.font = ReadingListTableViewCellUX.MarkAsReadButtonTitleFont markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal) markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets markAsReadAction.name = markAsReadButton.titleLabel!.text markAsReadAction.target = self markAsReadAction.selector = "markAsReadActionActivated" leftUtilityButtons = [markAsReadButton] accessibilityCustomActions = [deleteAction, markAsReadAction] } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."] private func simplifiedHostnameFromURL(url: NSURL) -> String { let hostname = url.host ?? "" for prefix in prefixesToSimplify { if hostname.hasPrefix(prefix) { return hostname.substringFromIndex(advance(hostname.startIndex, count(prefix))) } } return hostname } @objc private func markAsReadActionActivated() -> Bool { self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0) return true } @objc private func deleteActionActivated() -> Bool { self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0) return true } private func updateAccessibilityLabel() { if let hostname = hostnameLabel.text, title = titleLabel.text { let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.") let string = "\(title), \(unreadStatus), \(hostname)" var label: AnyObject if !unread { // mimic light gray visual dimming by "dimming" the speech by reducing pitch let lowerPitchString = NSMutableAttributedString(string: string as String) lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length)) label = NSAttributedString(attributedString: lowerPitchString) } else { label = string } // need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this // see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple // also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly... setValue(label, forKey: "accessibilityLabel") } } } class ReadingListEmptyStateView: UIView { convenience init() { self.init(frame: CGRectZero) } } class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate { weak var homePanelDelegate: HomePanelDelegate? = nil var profile: Profile! private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview() private var records: [ReadingListClientRecord]? init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "firefoxAccountChanged:", name: NotificationFirefoxAccountChanged, object: nil) } required init!(coder aDecoder: NSCoder!) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = ReadingListTableViewCellUX.RowHeight tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.separatorColor = UIConstants.SeparatorColor tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell") // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() view.backgroundColor = UIConstants.PanelBackgroundColor if let result = profile.readingList?.getAvailableRecords() where result.isSuccess { records = result.successValue // If no records have been added yet, we display the empty state if records?.count == 0 { tableView.scrollEnabled = false view.addSubview(emptyStateOverlayView) } } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } func firefoxAccountChanged(notification: NSNotification) { if notification.name == NotificationFirefoxAccountChanged { let prevNumberOfRecords = records?.count if let result = profile.readingList?.getAvailableRecords() where result.isSuccess { records = result.successValue if records?.count == 0 { tableView.scrollEnabled = false if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) } } else { if prevNumberOfRecords == 0 { tableView.scrollEnabled = true emptyStateOverlayView.removeFromSuperview() } } self.tableView.reloadData() } } } private func createEmptyStateOverview() -> UIView { let overlayView = UIView(frame: tableView.bounds) overlayView.backgroundColor = UIColor.whiteColor() // Unknown why this does not work with autolayout overlayView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth let containerView = UIView() overlayView.addSubview(containerView) let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel")) containerView.addSubview(logoImageView) logoImageView.snp_makeConstraints({ (make) -> Void in make.centerX.equalTo(containerView) make.top.equalTo(containerView) }) let welcomeLabel = UILabel() containerView.addSubview(welcomeLabel) welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL") welcomeLabel.textAlignment = NSTextAlignment.Center welcomeLabel.font = ReadingListPanelUX.WelcomeScreenHeaderFont welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp_makeConstraints({ (make) -> Void in make.centerX.equalTo(containerView) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth) make.top.equalTo(logoImageView.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) }) let readerModeLabel = UILabel() containerView.addSubview(readerModeLabel) readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL") readerModeLabel.font = ReadingListPanelUX.WelcomeScreenItemFont readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readerModeLabel.numberOfLines = 0 readerModeLabel.snp_makeConstraints({ (make) -> Void in make.top.equalTo(welcomeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.left.equalTo(welcomeLabel.snp_left) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) }) let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle")) containerView.addSubview(readerModeImageView) readerModeImageView.snp_makeConstraints({ (make) -> Void in make.centerY.equalTo(readerModeLabel) make.right.equalTo(welcomeLabel.snp_right) }) let readingListLabel = UILabel() containerView.addSubview(readingListLabel) readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL") readingListLabel.font = ReadingListPanelUX.WelcomeScreenItemFont readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor readingListLabel.numberOfLines = 0 readingListLabel.snp_makeConstraints({ (make) -> Void in make.top.equalTo(readerModeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding) make.left.equalTo(welcomeLabel.snp_left) make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth) }) let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle")) containerView.addSubview(readingListImageView) readingListImageView.snp_makeConstraints({ (make) -> Void in make.centerY.equalTo(readingListLabel) make.right.equalTo(welcomeLabel.snp_right) }) containerView.snp_makeConstraints({ (make) -> Void in // Let the container wrap around the content make.top.equalTo(overlayView.snp_top).offset(20) make.bottom.equalTo(readingListLabel.snp_bottom) make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset) make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(overlayView) }) return overlayView } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell cell.delegate = self if let record = records?[indexPath.row] { cell.title = record.title cell.url = NSURL(string: record.url)! cell.unread = record.unread } return cell } func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) { if let cell = cell as? ReadingListTableViewCell { cell.hideUtilityButtonsAnimated(true) if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] { if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess { // TODO This is a bit odd because the success value of the update is an optional optional Record if let successValue = result.successValue, updatedRecord = successValue { records?[indexPath.row] = updatedRecord tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } } } } func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) { if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] { if let result = profile.readingList?.deleteRecord(record) where result.isSuccess { records?.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) // reshow empty state if no records left if records?.count == 0 { view.addSubview(emptyStateOverlayView) } } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) { // Reading list items are closest in concept to bookmarks. let visitType = VisitType.Bookmark homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType) } } }
b1595e6a3b610de19a1ebcb8a61aae54
48.710648
333
0.707427
false
false
false
false
visenze/visearch-sdk-swift
refs/heads/master
ViSearchSDK/ViSearchSDK/Classes/Request/ViColorSearchParams.swift
mit
1
// // ViColorSearchParams.swift // ViSearchSDK // // Created by Hung on 3/10/16. // Copyright © 2016 Hung. All rights reserved. // import UIKit /// Construct color search parameter request public class ViColorSearchParams: ViBaseSearchParams { public var color: String public init? (color: String ) { self.color = color //verify that color is exactly 6 digits if self.color.count != 6 { print("\(type(of: self)).\(#function)[line:\(#line)] - error: color length must be 6") return nil } // verify color is of valid format i.e. only a-fA-F0-9 let regex = try! NSRegularExpression(pattern: "[^a-fA-F|0-9]", options: []) let numOfMatches = regex.numberOfMatches(in: self.color, options: [.reportCompletion], range: NSMakeRange(0, self.color.count )) if numOfMatches != 0 { print("\(type(of: self)).\(#function)[line:\(#line)] - error: invalid color format") return nil } } public convenience init (color: UIColor){ self.init(color: color.hexString())! } public override func toDict() -> [String: Any] { var dict = super.toDict() dict["color"] = color return dict; } }
451e4b36e397c77c019b1145fa50ac7c
27.608696
136
0.570669
false
false
false
false
zadr/conservatory
refs/heads/main
Conservatory.playground/Contents.swift
bsd-2-clause
1
import Conservatory import UIKit let length = 2000.0 let canvas = Canvas<CGRenderer>(size: Size(width: length, height: length)) var color = Color.random() canvas.appearance.background = .solid(color) canvas.appearance.border = .solid(color.complement) canvas.appearance.borderWidth = Double.random(in: 50.0 ... 150.0) let add: (Shape) -> Void = { (shape) -> Void in var colors = Color.random().compound() let shapeColor = colors.removeFirst() var shapeDrawer = ShapeDrawer(shape: shape) shapeDrawer.appearance.border = .solid(shapeColor.complement) shapeDrawer.appearance.background = Bool.random() ? .gradient(colors, GradientOptions()) : .solid(shapeColor) shapeDrawer.appearance.borderWidth = Double.random(in: 5.0 ... 30.0) shapeDrawer.appearance.transform = Transform.move(Double.random(in: 0 ... length), y: Double.random(in: 0 ... length)) shapeDrawer.appearance.aura = Aura(color: shapeColor.withAlpha(float: 0.4), offset: Size(width: 0.0, height: -5.0), blur: 25.0) canvas.add(shapeDrawer) } Int.random(in: 5 ... 15).times { (x, _) in let side = Double.random(in: 35.0 ... 350.0) let circle = Shape(circle: side) add(circle) let oval = Shape(oval: Size(width: side / 1.5, height: side * 1.5)) add(oval) let polygon = Shape(sideCount: Int.random(in: 3 ... 8), length: side) add(polygon) } //canvas.currentRepresentation! UIImage(cgImage: canvas.currentRepresentation!) // changes every run! let view = UIView(frame: CGRect(x: 0, y: 0, width: canvas.size.width, height: canvas.size.height))
49e200b36eb2d0416bb269d92a690e4e
37.1
128
0.716535
false
false
false
false
MLSDev/TRON
refs/heads/main
Source/TRON/UploadAPIRequest.swift
mit
1
// // UploadAPIRequest.swift // TRON // // Created by Denys Telezhkin on 11.09.16. // Copyright © 2015 - present MLSDev. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Alamofire /// Types of `UploadAPIRequest` public enum UploadRequestType { /// Will create `NSURLSessionUploadTask` using `uploadTaskWithRequest(_:fromFile:)` method case uploadFromFile(URL) /// Will create `NSURLSessionUploadTask` using `uploadTaskWithRequest(_:fromData:)` method case uploadData(Data) /// Will create `NSURLSessionUploadTask` using `uploadTaskWithStreamedRequest(_)` method case uploadStream(InputStream) // Depending on resulting size of the payload will either stream from disk or from memory case multipartFormData(formData: (MultipartFormData) -> Void, memoryThreshold: UInt64, fileManager: FileManager) } /** `UploadAPIRequest` encapsulates upload request creation logic, stubbing options, and response/error parsing. */ open class UploadAPIRequest<Model, ErrorModel: ErrorSerializable>: BaseRequest<Model, ErrorModel> { /// UploadAPIRequest type let type: UploadRequestType /// Serializes received response into Result<Model> open var responseParser: ResponseParser /// Serializes received error into APIError<ErrorModel> open var errorParser: ErrorParser /// Closure that is applied to request before it is sent. open var validationClosure: (UploadRequest) -> UploadRequest = { $0.validate() } /// Sets `validationClosure` to `validation` parameter and returns configured request /// /// - Parameter validation: validation to perform. /// - Returns: configured request. open func validation(_ validation: @escaping (UploadRequest) -> UploadRequest) -> Self { validationClosure = validation return self } /// Creates `UploadAPIRequest` with specified `type`, `path` and configures it with to be used with `tron`. public init<Serializer: DataResponseSerializerProtocol>(type: UploadRequestType, path: String, tron: TRON, responseSerializer: Serializer) where Serializer.SerializedObject == Model { self.type = type self.responseParser = { request, response, data, error in try responseSerializer.serialize(request: request, response: response, data: data, error: error) } self.errorParser = { request, response, data, error in ErrorModel(request: request, response: response, data: data, error: error) } super.init(path: path, tron: tron) } override func alamofireRequest(from session: Session) -> Request { switch type { case .uploadFromFile(let url): return session.upload(url, to: urlBuilder.url(forPath: path), method: method, headers: headers, interceptor: interceptor, requestModifier: requestModifier) case .uploadData(let data): return session.upload(data, to: urlBuilder.url(forPath: path), method: method, headers: headers, interceptor: interceptor, requestModifier: requestModifier) case .uploadStream(let stream): return session.upload(stream, to: urlBuilder.url(forPath: path), method: method, headers: headers, interceptor: interceptor, requestModifier: requestModifier) case .multipartFormData(let constructionBlock, let memoryThreshold, let fileManager): return session.upload(multipartFormData: appendParametersToMultipartFormDataBlock(constructionBlock), to: urlBuilder.url(forPath: path), usingThreshold: memoryThreshold, method: method, headers: headers, interceptor: interceptor, fileManager: fileManager, requestModifier: requestModifier) } } private func appendParametersToMultipartFormDataBlock(_ block: @escaping (MultipartFormData) -> Void) -> (MultipartFormData) -> Void { return { formData in self.parameters.forEach { key, value in formData.append(String(describing: value).data(using: .utf8) ?? Data(), withName: key) } block(formData) } } @discardableResult /** Send current request. - parameter successBlock: Success block to be executed when request finished - parameter failureBlock: Failure block to be executed if request fails. Nil by default. - returns: Alamofire.Request or nil if request was stubbed. */ open func perform(withSuccess successBlock: ((Model) -> Void)? = nil, failure failureBlock: ((ErrorModel) -> Void)? = nil) -> UploadRequest { return performAlamofireRequest { self.callSuccessFailureBlocks(successBlock, failure: failureBlock, response: $0) } } @discardableResult /** Perform current request with completion block, that contains Alamofire.Response. - parameter completion: Alamofire.Response completion block. - returns: Alamofire.Request or nil if request was stubbed. */ open func performCollectingTimeline(withCompletion completion: @escaping ((Alamofire.DataResponse<Model, AFError>) -> Void)) -> UploadRequest { return performAlamofireRequest(completion) } private func performAlamofireRequest(_ completion : @escaping (DataResponse<Model, AFError>) -> Void) -> UploadRequest { guard let session = tronDelegate?.session else { fatalError("Manager cannot be nil while performing APIRequest") } willSendRequest() guard let request = alamofireRequest(from: session) as? UploadRequest else { fatalError("Failed to receive UploadRequest") } if let stub = apiStub, stub.isEnabled { request.tron_apiStub = stub } willSendAlamofireRequest(request) let uploadRequest = validationClosure(request) .performResponseSerialization(queue: resultDeliveryQueue, responseSerializer: dataResponseSerializer(with: request), completionHandler: { dataResponse in self.didReceiveDataResponse(dataResponse, forRequest: request) completion(dataResponse) }) if !session.startRequestsImmediately { request.resume() } didSendAlamofireRequest(request) return uploadRequest } internal func dataResponseSerializer(with request: Request) -> TRONDataResponseSerializer<Model> { return TRONDataResponseSerializer { urlRequest, response, data, error in self.willProcessResponse((urlRequest, response, data, error), for: request) let parsedModel: Model do { parsedModel = try self.responseParser(urlRequest, response, data, error) } catch let catchedError { let parsedError = self.errorParser(urlRequest, response, data, catchedError) self.didReceiveError(parsedError, for: (urlRequest, response, data, error), request: request) throw parsedError } self.didSuccessfullyParseResponse((urlRequest, response, data, error), creating: parsedModel, forRequest: request) return parsedModel } } internal func didReceiveError(_ error: ErrorModel, for response: (URLRequest?, HTTPURLResponse?, Data?, Error?), request: Alamofire.Request) { allPlugins.forEach { plugin in plugin.didReceiveError(error, forResponse: response, request: request, formedFrom: self) } } }
b8469b0639ed56cee3155923a732733a
45.19898
147
0.658973
false
false
false
false
zeroc-ice/ice
refs/heads/3.7
swift/test/Ice/optional/TestI.swift
gpl-2.0
3
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import TestCommon class InitialI: Initial { func shutdown(current: Ice.Current) throws { current.adapter!.getCommunicator().shutdown() } func pingPong(o: Ice.Value?, current _: Ice.Current) throws -> Ice.Value? { return o } func opOptionalException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { throw OptionalException(req: false, a: a, b: b, o: o) } func opDerivedException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { throw DerivedException(req: false, a: a, b: b, o: o, d1: "d1", ss: b, o2: o, d2: "d2") } func opRequiredException(a: Int32?, b: String?, o: OneOptional?, current _: Ice.Current) throws { let e = RequiredException() e.a = a e.b = b e.o = o if let b = b { e.ss = b } e.o2 = o throw e } func opByte(p1: UInt8?, current _: Ice.Current) throws -> (returnValue: UInt8?, p3: UInt8?) { return (p1, p1) } func opBool(p1: Bool?, current _: Ice.Current) throws -> (returnValue: Bool?, p3: Bool?) { return (p1, p1) } func opShort(p1: Int16?, current _: Ice.Current) throws -> (returnValue: Int16?, p3: Int16?) { return (p1, p1) } func opInt(p1: Int32?, current _: Ice.Current) throws -> (returnValue: Int32?, p3: Int32?) { return (p1, p1) } func opLong(p1: Int64?, current _: Ice.Current) throws -> (returnValue: Int64?, p3: Int64?) { return (p1, p1) } func opFloat(p1: Float?, current _: Ice.Current) throws -> (returnValue: Float?, p3: Float?) { return (p1, p1) } func opDouble(p1: Double?, current _: Ice.Current) throws -> (returnValue: Double?, p3: Double?) { return (p1, p1) } func opString(p1: String?, current _: Ice.Current) throws -> (returnValue: String?, p3: String?) { return (p1, p1) } func opCustomString(p1: String?, current _: Current) throws -> (returnValue: String?, p3: String?) { return (p1, p1) } func opMyEnum(p1: MyEnum?, current _: Ice.Current) throws -> (returnValue: MyEnum?, p3: MyEnum?) { return (p1, p1) } func opSmallStruct(p1: SmallStruct?, current _: Ice.Current) throws -> (returnValue: SmallStruct?, p3: SmallStruct?) { return (p1, p1) } func opFixedStruct(p1: FixedStruct?, current _: Ice.Current) throws -> (returnValue: FixedStruct?, p3: FixedStruct?) { return (p1, p1) } func opVarStruct(p1: VarStruct?, current _: Ice.Current) throws -> (returnValue: VarStruct?, p3: VarStruct?) { return (p1, p1) } func opOneOptional(p1: OneOptional?, current _: Ice.Current) throws -> (returnValue: OneOptional?, p3: OneOptional?) { return (p1, p1) } func opOneOptionalProxy(p1: Ice.ObjectPrx?, current _: Ice.Current) throws -> (returnValue: Ice.ObjectPrx?, p3: Ice.ObjectPrx?) { return (p1, p1) } func opByteSeq(p1: ByteSeq?, current _: Ice.Current) throws -> (returnValue: ByteSeq?, p3: ByteSeq?) { return (p1, p1) } func opBoolSeq(p1: BoolSeq?, current _: Ice.Current) throws -> (returnValue: BoolSeq?, p3: BoolSeq?) { return (p1, p1) } func opShortSeq(p1: ShortSeq?, current _: Ice.Current) throws -> (returnValue: ShortSeq?, p3: ShortSeq?) { return (p1, p1) } func opIntSeq(p1: IntSeq?, current _: Ice.Current) throws -> (returnValue: IntSeq?, p3: IntSeq?) { return (p1, p1) } func opLongSeq(p1: LongSeq?, current _: Ice.Current) throws -> (returnValue: LongSeq?, p3: LongSeq?) { return (p1, p1) } func opFloatSeq(p1: FloatSeq?, current _: Ice.Current) throws -> (returnValue: FloatSeq?, p3: FloatSeq?) { return (p1, p1) } func opDoubleSeq(p1: DoubleSeq?, current _: Ice.Current) throws -> (returnValue: DoubleSeq?, p3: DoubleSeq?) { return (p1, p1) } func opStringSeq(p1: StringSeq?, current _: Ice.Current) throws -> (returnValue: StringSeq?, p3: StringSeq?) { return (p1, p1) } func opSmallStructSeq(p1: SmallStructSeq?, current _: Ice.Current) throws -> (returnValue: SmallStructSeq?, p3: SmallStructSeq?) { return (p1, p1) } func opSmallStructList(p1: SmallStructList?, current _: Ice.Current) throws -> (returnValue: SmallStructList?, p3: SmallStructList?) { return (p1, p1) } func opFixedStructSeq(p1: FixedStructSeq?, current _: Ice.Current) throws -> (returnValue: FixedStructSeq?, p3: FixedStructSeq?) { return (p1, p1) } func opFixedStructList(p1: FixedStructList?, current _: Ice.Current) throws -> (returnValue: FixedStructList?, p3: FixedStructList?) { return (p1, p1) } func opVarStructSeq(p1: VarStructSeq?, current _: Ice.Current) throws -> (returnValue: VarStructSeq?, p3: VarStructSeq?) { return (p1, p1) } func opSerializable(p1: Serializable?, current _: Current) throws -> (returnValue: Serializable?, p3: Serializable?) { return (p1, p1) } func opIntIntDict(p1: [Int32: Int32]?, current _: Ice.Current) throws -> (returnValue: [Int32: Int32]?, p3: [Int32: Int32]?) { return (p1, p1) } func opStringIntDict(p1: [String: Int32]?, current _: Ice.Current) throws -> (returnValue: [String: Int32]?, p3: [String: Int32]?) { return (p1, p1) } func opCustomIntStringDict(p1: IntStringDict?, current _: Current) throws -> (returnValue: IntStringDict?, p3: IntStringDict?) { return (p1, p1) } func opIntOneOptionalDict(p1: [Int32: OneOptional?]?, current _: Ice.Current) throws -> (returnValue: [Int32: OneOptional?]?, p3: [Int32: OneOptional?]?) { return (p1, p1) } func opClassAndUnknownOptional(p _: A?, current _: Ice.Current) throws {} func sendOptionalClass(req _: Bool, o _: OneOptional?, current _: Ice.Current) throws {} func returnOptionalClass(req _: Bool, current _: Ice.Current) throws -> OneOptional? { return OneOptional(a: 53) } func opG(g: G?, current _: Ice.Current) throws -> G? { return g } func opVoid(current _: Ice.Current) throws {} func supportsRequiredParams(current _: Ice.Current) throws -> Bool { return false } func supportsJavaSerializable(current _: Ice.Current) throws -> Bool { return false } func supportsCsharpSerializable(current _: Ice.Current) throws -> Bool { return false } func supportsCppStringView(current _: Ice.Current) throws -> Bool { return false } func supportsNullOptional(current _: Ice.Current) throws -> Bool { return false } func opMStruct1(current _: Current) throws -> SmallStruct? { return SmallStruct() } func opMStruct2(p1: SmallStruct?, current _: Current) throws -> (returnValue: SmallStruct?, p2: SmallStruct?) { return (p1, p1) } func opMSeq1(current _: Current) throws -> StringSeq? { return [] } func opMSeq2(p1: StringSeq?, current _: Current) throws -> (returnValue: StringSeq?, p2: StringSeq?) { return (p1, p1) } func opMDict1(current _: Current) throws -> StringIntDict? { return [:] } func opMDict2(p1: StringIntDict?, current _: Current) throws -> (returnValue: StringIntDict?, p2: StringIntDict?) { return (p1, p1) } func opMG1(current _: Current) throws -> G? { return G() } func opMG2(p1: G?, current _: Current) throws -> (returnValue: G?, p2: G?) { return (p1, p1) } }
9208d477044b8824e95993991a5d1adb
34.061303
119
0.511966
false
false
false
false
sstanic/Shopfred
refs/heads/master
Shopfred/Shopfred/View Controller/GenericSelectionViewController.swift
mit
1
// // GenericSelectionViewController.swift // Shopfred // // Created by Sascha Stanic on 7/1/17. // Copyright © 2017 Sascha Stanic. All rights reserved. // import UIKit import CoreData /** Shows a list of core data entities. These entities are managed by the view controller: - *Unit* - *Category* - *Context* The entity type is defined by the generic type parameter of the class. */ class GenericSelectionViewController<T: NSManagedObject>: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Private Attributes private var setSelection: ((_ o: T) -> Void)! private var myTableView: UITableView! private var myLabel: UILabel! private var myStackView: UIStackView! private var myToolBar: UIToolbar! private var list = [ManagedObjectName]() private var info: String! private var selectedName: String? // MARK: - Initializer convenience init(setSelection: @escaping (_ o: T) -> Void) { self.init(nibName: nil, bundle: nil) self.setSelection = setSelection self.info = "" self.selectedName = "" } convenience init(info: String, setSelection: @escaping (_ o: T) -> Void) { self.init(setSelection: setSelection) self.info = info self.selectedName = "" } convenience init(info: String, selectedName: String?, setSelection: @escaping (_ o: T) -> Void) { self.init(info: info, setSelection: setSelection) self.selectedName = selectedName } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.createElementList() self.initializeView() self.setStyle() } override func viewWillAppear(_ animated: Bool) { self.myTableView.reloadData() if let navController = self.navigationController { navController.isToolbarHidden = false } } override func viewWillDisappear(_ animated: Bool) { if let navController = self.navigationController { navController.isToolbarHidden = true } } // MARK: - Styling private func setStyle() { self.myTableView.style(style: ViewStyle.TableListView.standard) self.myTableView.separatorColor = UIColor.clear self.myTableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) self.myLabel.style(style: TextStyle.title) self.view.style(style: ViewStyle.TableListView.standard) } // MARK: - Initialize View private func createElementList() { let shoppingSpace = DataStore.sharedInstance().shoppingStore.shoppingSpace let request: NSFetchRequest = T.fetchRequest() let predicate = NSPredicate(format: "shoppingSpace.id == %@", shoppingSpace?.id ?? "") request.predicate = predicate do { self.list = try DataStore.sharedInstance().stack.context.fetch(request) as! [ManagedObjectName] } catch { print("fetch request for \(T.self) failed.") } } private func initializeView() { self.myStackView = UIStackView() self.myStackView.translatesAutoresizingMaskIntoConstraints=false self.view.addSubview(myStackView) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-64-[stackView]-0-|", options: NSLayoutFormatOptions.alignAllLeading, metrics: nil, views: ["stackView":self.myStackView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[stackView]-0-|", options: NSLayoutFormatOptions.alignAllLeading, metrics: nil, views: ["stackView":self.myStackView])) self.myStackView.axis = .vertical self.myStackView.alignment = .fill self.myStackView.distribution = .fill self.myStackView.spacing = 5 self.myLabel = UILabel() self.myLabel.text = info self.myLabel.textAlignment = .center self.myLabel.backgroundColor = UIColor.groupTableViewBackground let height : CGFloat = 40.0 let heightConstraint = NSLayoutConstraint(item: self.myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: height) self.myStackView.addArrangedSubview(self.myLabel) NSLayoutConstraint.activate([heightConstraint]) // tableView self.myTableView = UITableView() self.myTableView.register(GenericSelectionTableViewCell.self, forCellReuseIdentifier: "genericSelectionTableViewCell") self.myTableView.dataSource = self self.myTableView.delegate = self self.myStackView.addArrangedSubview(self.myTableView) var items = [UIBarButtonItem]() items.append(UIBarButtonItem(title: "Manage entries", style: .plain, target: self, action: #selector(navigateToSettings))) self.toolbarItems = items } // MARK: - Navigation @objc private func navigateToSettings() { let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "SettingsListViewController") as! SettingsListViewController vc.type = T.self vc.titleText = "Manage entries" if let navController = self.navigationController { navController.pushViewController(vc, animated: true) } } private func navigateBack() { if let navController = self.navigationController { navController.popViewController(animated: true) } else { Utils.showAlert(self, alertMessage: "Sorry, something went wrong. Please restart the app.", completion: nil) } } // MARK: - UITableViewDataSource, UITableViewDelegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "genericSelectionTableViewCell", for: indexPath) as! GenericSelectionTableViewCell let selectionItem = self.list[indexPath.row] if let txtLbl = cell.textLabel { txtLbl.text = selectionItem.name } if (selectionItem.name == self.selectedName) { cell.accessoryType = .checkmark } cell.setStyle() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.setSelection(list[indexPath.row] as! T) DataStore.sharedInstance().saveContext() { success, error in // completion parameters not used self.navigateBack() } } }
89bc96226a35eecb90e1c1bc9b9940ff
31.976959
232
0.635551
false
false
false
false
zyhndesign/SDX_DG
refs/heads/master
sdxdg/sdxdg/ClientDetailViewController.swift
apache-2.0
1
// // ClientDetailViewController.swift // sdxdg // // Created by lotusprize on 16/12/26. // Copyright © 2016年 geekTeam. All rights reserved. // import UIKit class ClientDetailViewController: UIViewController { @IBOutlet var baseInfoBtn: UIButton! @IBOutlet var consumeBtn: UIButton! @IBOutlet var feedbackBtn: UIButton! let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height var baseInfoPanel:UIView? var consumePanel:UIView? var feedbackPanel:UIView? var vipUser:VipUser? override func viewDidLoad() { super.viewDidLoad() self.initBaseInfoPanel() self.initPushHistoryPanel() self.initFeedbackPanel() consumePanel?.isHidden = true feedbackPanel?.isHidden = true } func initBaseInfoPanel(){ baseInfoPanel = UIView.init(frame: CGRect.init(x: 0, y: 113, width: screenWidth, height: screenHeight - 113)) let icon:UIImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 20, width: 130, height: 130)) icon.image = UIImage.init(named: "customerIcon5") icon.contentMode = UIViewContentMode.scaleAspectFit baseInfoPanel!.addSubview(icon) let nameLabel:UILabel = UILabel.init(frame: CGRect.init(x: 160, y: 20, width: 100, height: 25)) nameLabel.text = "VIP会员姓名:" nameLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(nameLabel) let nameLabelValue:UILabel = UILabel.init(frame: CGRect.init(x: 240, y: 20, width: 100, height: 25)) nameLabelValue.text = vipUser?.vipname nameLabelValue.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(nameLabelValue) let birthdayLabel:UILabel = UILabel.init(frame: CGRect.init(x: 160, y: 60, width: 100, height: 25)) birthdayLabel.text = "生日:" birthdayLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(birthdayLabel) let valueBirthdayLabel:UILabel = UILabel.init(frame: CGRect.init(x: 240, y: 60, width: 100, height: 25)) valueBirthdayLabel.text = vipUser?.birthday valueBirthdayLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(valueBirthdayLabel) let levelLabel:UILabel = UILabel.init(frame: CGRect.init(x: 160, y: 90, width: 100, height: 25)) levelLabel.text = "级别:" levelLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(levelLabel) let valueLevelLabel:UILabel = UILabel.init(frame: CGRect.init(x: 240, y: 90, width: 100, height: 25)) valueLevelLabel.text = vipUser?.rank valueLevelLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(valueLevelLabel) let mobileLabel:UILabel = UILabel.init(frame: CGRect.init(x: 160, y: 125, width: 100, height: 25)) mobileLabel.text = "手机号码:" mobileLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(mobileLabel) let valueMobileLabel:UILabel = UILabel.init(frame: CGRect.init(x: 240, y: 125, width: 100, height: 25)) valueMobileLabel.text = vipUser?.phonenumber valueMobileLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(valueMobileLabel) let line1:UIView = UIView.init(frame: CGRect.init(x: 15, y: 170, width: screenWidth - 30, height: 1)) line1.backgroundColor = UIColor.lightGray baseInfoPanel!.addSubview(line1) let consumeLabel:UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 180, width: 110, height: 30)) consumeLabel.text = "目前消费额度:" consumeLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(consumeLabel) let valueConsumeLabel:UILabel = UILabel.init(frame: CGRect.init(x: 120, y: 180, width: 110, height: 30)) valueConsumeLabel.text = String.init(format: "%i", (vipUser?.consumesum!)!) valueConsumeLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(valueConsumeLabel) let line2:UIView = UIView.init(frame: CGRect.init(x: 15, y: 210, width: screenWidth - 30, height: 1)) line2.backgroundColor = UIColor.lightGray baseInfoPanel!.addSubview(line2) let consumeValueLabel:UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 220, width: 110, height: 30)) consumeValueLabel.text = "累计消费次数:" consumeValueLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(consumeValueLabel) let valueConsumeValueLabel:UILabel = UILabel.init(frame: CGRect.init(x: 120, y: 220, width: 110, height: 30)) valueConsumeValueLabel.text = String.init(format: "%i", (vipUser?.consumenumber!)!) valueConsumeValueLabel.font = UIFont.systemFont(ofSize: 12) baseInfoPanel!.addSubview(valueConsumeValueLabel) let line3:UIView = UIView.init(frame: CGRect.init(x: 15, y: 250, width: screenWidth - 30, height: 1)) line3.backgroundColor = UIColor.lightGray baseInfoPanel!.addSubview(line3) self.view.addSubview(baseInfoPanel!) } func initPushHistoryPanel(){ let consumerController:ConsumeListViewController = ConsumeListViewController.init(storyBoard: self.storyboard!, naviController: self.navigationController!, vipName:(vipUser?.vipname)!) consumerController.view.frame = CGRect.init(x: 0, y: 113, width: screenWidth, height: screenHeight - 113) consumePanel = consumerController.view self.view.addSubview(consumePanel!) self.addChildViewController(consumerController) } func initFeedbackPanel(){ let feedbackController:FeedbackListViewController = FeedbackListViewController.init(sBoard: self.storyboard!, naviController: self.navigationController!, vipName:(vipUser?.vipname)!, vipId:(vipUser?.id)!) feedbackController.view.frame = CGRect.init(x: 0, y: 113, width: screenWidth, height: screenHeight - 113) feedbackPanel = feedbackController.view self.view.addSubview(feedbackPanel!) self.addChildViewController(feedbackController) } @IBAction func baseInfoBtnClick(_ sender: Any) { baseInfoBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal) consumeBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) feedbackBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) baseInfoPanel?.isHidden = false consumePanel?.isHidden = true feedbackPanel?.isHidden = true } @IBAction func consumeBtnClick(_ sender: Any) { consumeBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal) baseInfoBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) feedbackBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) baseInfoPanel?.isHidden = true consumePanel?.isHidden = false feedbackPanel?.isHidden = true } @IBAction func feedbackBtnClick(_ sender: Any) { feedbackBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal) consumeBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) baseInfoBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal) baseInfoPanel?.isHidden = true consumePanel?.isHidden = true feedbackPanel?.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a37c1b90b499e2fe04d5aac86180ae90
46.04142
212
0.677862
false
false
false
false
boylee1111/BLCircularProgress-Swift
refs/heads/master
BLCircularProgress-Swift/ViewController.swift
mit
1
// // ViewController.swift // BLCircularProgress-Swift // // Created by Boyi on 4/3/15. // Copyright (c) 2015 boyi. All rights reserved. // import UIKit class ViewController: UIViewController, BLCircularProgressViewProtocol { @IBOutlet weak var circularProgress: BLCircularProgressView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.circularProgress.progress = 30 self.circularProgress.maximaProgress = 90 self.circularProgress.minimaProgress = 20 self.circularProgress.delegate = self; NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "updateProgress", userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateProgress() { var randomValue = self.randomDoubleBetween(0, bigValue: 100) println("random value = \(randomValue)") self.circularProgress.animateProgress(randomValue, completion: nil) } func randomDoubleBetween(smallValue: Double, bigValue: Double) -> Double { var diff = bigValue - smallValue return Double(arc4random_uniform(UInt32(diff))) + smallValue } func circularAnimationBegan(circularProgressView: BLCircularProgressView, progress: Double) { println("Animation Began") } func circularAnimationDuring(circularProgressView: BLCircularProgressView, progress: Double) { println("Animation During, Current Progress = \(progress)") } func circularAnimationEnded(circularProgressView: BLCircularProgressView, progress: Double) { println("Animation Ended") } }
cbdd765f54a0a545eb6b6e91532dbf3b
32.327273
121
0.692853
false
false
false
false
tsolomko/SWCompression
refs/heads/develop
Sources/Common/Container/DosAttributes.swift
mit
1
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation /// Represents file attributes in DOS format. public struct DosAttributes: OptionSet { /// Raw bit flags value. public let rawValue: UInt32 /// Initializes attributes with bit flags. public init(rawValue: UInt32) { self.rawValue = rawValue } /// File is archive or archived. public static let archive = DosAttributes(rawValue: 0b00100000) /// File is a directory. public static let directory = DosAttributes(rawValue: 0b00010000) /// File is a volume. public static let volume = DosAttributes(rawValue: 0b00001000) /// File is a system file. public static let system = DosAttributes(rawValue: 0b00000100) /// File is hidden. public static let hidden = DosAttributes(rawValue: 0b00000010) /// File is read-only. public static let readOnly = DosAttributes(rawValue: 0b00000001) }
cb4d9ce1ca070102c457c9638b69d560
25.837838
69
0.700906
false
false
false
false
kuhippo/swift-vuejs-starter
refs/heads/master
Sources/swift-vue-start/configuration/Config.swift
mit
1
// // Config.swift // swiftStartKit // // Created by mubin on 2017/8/17. // // import Foundation import PostgreSQL import PerfectLib let postgresTestConnInfo = "host=localhost dbname=postgres" func config(){ let p = PGConnection() let status = p.connectdb(postgresTestConnInfo) guard status != .bad else{ //连接失败 fatalError("\(p.errorMessage())") } //添加测试数据 let userres = p.exec(statement: "CREATE TABLE users ( id serial PRIMARY KEY, username varchar(20) NOT NULL, age integer)") let topicres = p.exec(statement: "CREATE TABLE topics ( id serial PRIMARY KEY, user_id integer ,title varchar(20) NULL, content varchar(20))") guard userres.status() == .commandOK && topicres.status() == .commandOK else { Log.error(message: "\(userres.errorMessage())\(topicres.errorMessage())") userres.clear() topicres.clear() return } let _ = p.exec(statement: "INSERT INTO users(username,age) values('john',10)") let _ = p.exec(statement: "INSERT INTO topics(user_id,title,content) values(10,'文章1','fffffccckkk')") let _ = p.exec(statement: "INSERT INTO topics(user_id,title,content) values(10,'文章2','seven color')") let _ = p.exec(statement: "INSERT INTO topics(user_id,title,content) values(10,'文章3',':-D :-D :-D')") userres.clear() topicres.clear() p.finish() }
604b7c2fe9dfc6072896f0fb4c7cfa2c
27.54
146
0.627891
false
false
false
false
thankmelater23/relliK
refs/heads/master
Pods/SwiftyBeaver/Sources/Filter.swift
unlicense
1
// // Filter.swift // SwiftyBeaver // // Created by Jeff Roberts on 5/31/16. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation /// FilterType is a protocol that describes something that determines /// whether or not a message gets logged. A filter answers a Bool when it /// is applied to a value. If the filter passes, it shall return true, /// false otherwise. /// /// A filter must contain a target, which identifies what it filters against /// A filter can be required meaning that all required filters against a specific /// target must pass in order for the message to be logged. At least one non-required /// filter must pass in order for the message to be logged public protocol FilterType: class { func apply(_ value: Any) -> Bool func getTarget() -> Filter.TargetType func isRequired() -> Bool func isExcluded() -> Bool func reachedMinLevel(_ level: SwiftyBeaver.Level) -> Bool } /// Filters is syntactic sugar used to easily construct filters public class Filters { public static let Path = PathFilterFactory.self public static let Function = FunctionFilterFactory.self public static let Message = MessageFilterFactory.self } /// Filter is an abstract base class for other filters public class Filter { public enum TargetType { case Path(Filter.ComparisonType) case Function(Filter.ComparisonType) case Message(Filter.ComparisonType) } public enum ComparisonType { case StartsWith([String], Bool) case Contains([String], Bool) case Excludes([String], Bool) case EndsWith([String], Bool) case Equals([String], Bool) } let targetType: Filter.TargetType let required: Bool let minLevel: SwiftyBeaver.Level public init(_ target: Filter.TargetType, required: Bool, minLevel: SwiftyBeaver.Level) { self.targetType = target self.required = required self.minLevel = minLevel } public func getTarget() -> Filter.TargetType { return self.targetType } public func isRequired() -> Bool { return self.required } public func isExcluded() -> Bool { return false } /// returns true of set minLevel is >= as given level public func reachedMinLevel(_ level: SwiftyBeaver.Level) -> Bool { //print("checking if given level \(level) >= \(minLevel)") return level.rawValue >= minLevel.rawValue } } /// CompareFilter is a FilterType that can filter based upon whether a target /// starts with, contains or ends with a specific string. CompareFilters can be /// case sensitive. public class CompareFilter: Filter, FilterType { private var filterComparisonType: Filter.ComparisonType? override public init(_ target: Filter.TargetType, required: Bool, minLevel: SwiftyBeaver.Level) { super.init(target, required: required, minLevel: minLevel) let comparisonType: Filter.ComparisonType? switch self.getTarget() { case let .Function(comparison): comparisonType = comparison case let .Path(comparison): comparisonType = comparison case let .Message(comparison): comparisonType = comparison /*default: comparisonType = nil*/ } self.filterComparisonType = comparisonType } public func apply(_ value: Any) -> Bool { guard let value = value as? String else { return false } guard let filterComparisonType = self.filterComparisonType else { return false } let matches: Bool switch filterComparisonType { case let .Contains(strings, caseSensitive): matches = !strings.filter { string in return caseSensitive ? value.contains(string) : value.lowercased().contains(string.lowercased()) }.isEmpty case let .Excludes(strings, caseSensitive): matches = !strings.filter { string in return caseSensitive ? !value.contains(string) : !value.lowercased().contains(string.lowercased()) }.isEmpty case let .StartsWith(strings, caseSensitive): matches = !strings.filter { string in return caseSensitive ? value.hasPrefix(string) : value.lowercased().hasPrefix(string.lowercased()) }.isEmpty case let .EndsWith(strings, caseSensitive): matches = !strings.filter { string in return caseSensitive ? value.hasSuffix(string) : value.lowercased().hasSuffix(string.lowercased()) }.isEmpty case let .Equals(strings, caseSensitive): matches = !strings.filter { string in return caseSensitive ? value == string : value.lowercased() == string.lowercased() }.isEmpty } return matches } override public func isExcluded() -> Bool { guard let filterComparisonType = self.filterComparisonType else { return false } switch filterComparisonType { case .Excludes(_, _): return true default: return false } } } // Syntactic sugar for creating a function comparison filter public class FunctionFilterFactory { public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Function(.StartsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel) } public static func contains(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Function(.Contains(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func excludes(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Function(.Excludes(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Function(.EndsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel) } public static func equals(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Function(.Equals(strings, caseSensitive)), required: required, minLevel: minLevel) } } // Syntactic sugar for creating a message comparison filter public class MessageFilterFactory { public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Message(.StartsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel) } public static func contains(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Message(.Contains(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func excludes(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Message(.Excludes(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Message(.EndsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel) } public static func equals(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Message(.Equals(strings, caseSensitive)), required: required, minLevel: minLevel) } } // Syntactic sugar for creating a path comparison filter public class PathFilterFactory { public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Path(.StartsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel) } public static func contains(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Path(.Contains(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func excludes(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Path(.Excludes(strings, caseSensitive)), required: required, minLevel: minLevel) } public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Path(.EndsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel) } public static func equals(_ strings: String..., caseSensitive: Bool = false, required: Bool = false, minLevel: SwiftyBeaver.Level = .verbose) -> FilterType { return CompareFilter(.Path(.Equals(strings, caseSensitive)), required: required, minLevel: minLevel) } } extension Filter.TargetType: Equatable { } // The == does not compare associated values for each enum. Instead == evaluates to true // if both enums are the same "types", ignoring the associated values of each enum public func == (lhs: Filter.TargetType, rhs: Filter.TargetType) -> Bool { switch (lhs, rhs) { case (.Path(_), .Path(_)): return true case (.Function(_), .Function(_)): return true case (.Message(_), .Message(_)): return true default: return false } }
6cd1b3f17734f2cb58497f535a4fa3a5
39.643123
117
0.642916
false
false
false
false
clark-new/Animated
refs/heads/master
swiftSnows/swiftSnows/ViewController.swift
mit
1
// // ViewController.swift // swiftSnows // // Created by Clark on 2017/2/23. // Copyright © 2017年 Clark. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let snowEmitter = CAEmitterLayer() snowEmitter.emitterPosition = CGPoint(x: self.view.bounds.size.width/2.0, y: -30) snowEmitter.emitterSize = CGSize(width: self.view.bounds.size.width * 2.0, height: 0.0) snowEmitter.emitterShape = kCAEmitterLayerLine snowEmitter.emitterMode = kCAEmitterLayerOutline let snowflake = CAEmitterCell() snowflake.birthRate = 1.0 snowflake.lifetime = 120.0 snowflake.velocity = -10 snowflake.velocityRange = 10 snowflake.yAcceleration = 2 snowflake.emissionRange = CGFloat(0.5 * M_PI) snowflake.spinRange = CGFloat(0.25 * M_PI) snowflake.contents = UIImage(named: "snow")?.cgImage snowflake.color = UIColor(red: 0.600, green: 0.658, blue: 0.743, alpha: 1.000).cgColor snowEmitter.shadowOpacity = 1.0 snowEmitter.shadowRadius = 0.0 snowEmitter.shadowOffset = CGSize(width: 0.0, height: 1.0) snowEmitter.shadowColor = UIColor.white.cgColor snowEmitter.emitterCells = Array(arrayLiteral: snowflake) view.layer.insertSublayer(snowEmitter, at: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a9b5208469405cc025bd298e39a8c47c
30.86
95
0.650973
false
false
false
false
mogstad/liechtensteinklamm
refs/heads/master
example/view_controller.swift
mit
1
import UIKit class ViewController: UIViewController { let label = UILabel(frame: .zero) let index: Int init(index: Int) { self.index = index super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "View \(index)" self.label.text = "\(index)" self.label.font = UIFont.systemFontOfSize(70, weight: UIFontWeightThin) self.label.textColor = UIColor.lightGrayColor() self.label.sizeToFit() self.view.addSubview(self.label) self.view.addConstraintsForCenteredSubview(self.label) self.view.backgroundColor = UIColor.greenColor() if let button = self.splitViewController?.displayModeButtonItem() { self.navigationItem.leftBarButtonItem = button self.navigationItem.leftItemsSupplementBackButton = true } } }
b374bf4e99c58de7223537eb2d26c510
24.861111
75
0.701396
false
false
false
false
ludagoo/Perfect
refs/heads/master
Examples/Authenticator/Authenticator Client/LoginViewController.swift
agpl-3.0
2
// // LoginViewController.swift // Authenticator // // Created by Kyle Jessup on 2015-11-12. // Copyright © 2015 PerfectlySoft. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import UIKit let LOGIN_SEGUE_ID = "loginSegue" class LoginViewController: UIViewController, NSURLSessionDelegate, UITextFieldDelegate { @IBOutlet var emailAddressText: UITextField? @IBOutlet var passwordText: UITextField? var message = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.emailAddressText?.delegate = self self.passwordText?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == LOGIN_SEGUE_ID { // start login process tryLogin() return false } return true } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let dest = segue.destinationViewController as? ResultViewController { dest.message = self.message } } func tryLogin() { let urlSessionDelegate = URLSessionDelegate(username: self.emailAddressText!.text!, password: self.passwordText!.text!) { (d:NSData?, res:NSURLResponse?, e:NSError?) -> Void in if let _ = e { self.message = "Failed with error \(e!)" } else if let httpRes = res as? NSHTTPURLResponse where httpRes.statusCode != 200 { self.message = "Failed with HTTP code \(httpRes.statusCode)" } else { let deserialized = try! NSJSONSerialization.JSONObjectWithData(d!, options: NSJSONReadingOptions.AllowFragments) self.message = "Logged in \(deserialized["firstName"]!!) \(deserialized["lastName"]!!)" } dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier(LOGIN_SEGUE_ID, sender: nil) } } let sessionConfig = NSURLSession.sharedSession().configuration let session = NSURLSession(configuration: sessionConfig, delegate: urlSessionDelegate, delegateQueue: nil) let req = NSMutableURLRequest(URL: NSURL(string: END_POINT + "login")!) req.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(req) task.resume() } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
fde8652ca6b6227726d955d54e9ba0ca
33.495146
123
0.720799
false
false
false
false
qingtianbuyu/Mono
refs/heads/master
Moon/Classes/Main/Model/MNCollection.swift
mit
1
// // MNCollection.swift // Moon // // Created by YKing on 16/6/4. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNCollection: NSObject { var thumb: MNThumb? var banner_img_url: String? var title: String? var id: Int = 0 var is_program: Bool = false var content_num: Int = 0 var logo_url: String? var type: String? var fav_num: Int = 0 var banner_img_url_thumb: MNThumb? var logo_url_thumb: MNThumb? init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "thumb" { thumb = MNThumb(dict: value as! [String: AnyObject]) return } if key == "logo_url_thumb" { logo_url_thumb = MNThumb(dict: value as! [String: AnyObject]) return } if key == "banner_img_url_thumb" { banner_img_url_thumb = MNThumb(dict: value as! [String: AnyObject]) return } super.setValue(value, forKey: key) } }
b86bf6e18773b970472f977448e324ac
19.918367
73
0.607805
false
false
false
false
insidegui/WWDC
refs/heads/master
WWDC/FeaturedCommunityCollectionViewItem.swift
bsd-2-clause
1
// // FeaturedCommunityCollectionViewItem.swift // WWDC // // Created by Guilherme Rambo on 01/06/20. // Copyright © 2020 Guilherme Rambo. All rights reserved. // import Cocoa final class FeaturedCommunityCollectionViewItem: NSCollectionViewItem { var clickHandler: () -> Void = { } var newsItem: CommunityNewsItemViewModel? { didSet { guard newsItem != oldValue else { return } updateUI() } } private lazy var titleLabel: NSTextField = { let v = NSTextField(labelWithString: "") v.font = NSFont.wwdcRoundedSystemFont(ofSize: 24, weight: .semibold) v.textColor = .primaryText v.setContentCompressionResistancePriority(.required, for: .vertical) v.translatesAutoresizingMaskIntoConstraints = false v.allowsDefaultTighteningForTruncation = true v.maximumNumberOfLines = 1 v.lineBreakMode = .byTruncatingTail v.isSelectable = false return v }() private static let placeholderImage: NSImage? = { NSImage(named: .init("featured-placeholder")) }() private lazy var imageContainerView: NSView = { let v = NSView() v.translatesAutoresizingMaskIntoConstraints = false return v }() private lazy var imageLayer: CALayer = { let l = CALayer() l.contentsGravity = .resizeAspectFill l.contents = Self.placeholderImage return l }() private var imageDownloadOperation: Operation? override func loadView() { view = NSView() view.wantsLayer = true view.layer?.backgroundColor = NSColor.contentBackground.cgColor view.addSubview(titleLabel) view.addSubview(imageContainerView) imageLayer.frame = imageContainerView.bounds imageContainerView.wantsLayer = true imageContainerView.layer?.cornerRadius = 8 imageContainerView.layer?.masksToBounds = true imageContainerView.layer?.cornerCurve = .continuous imageContainerView.layer?.addSublayer(imageLayer) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor), titleLabel.topAnchor.constraint(equalTo: view.topAnchor), imageContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), imageContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), imageContainerView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 12), imageContainerView.heightAnchor.constraint(equalToConstant: 166) ]) let click = NSClickGestureRecognizer(target: self, action: #selector(clicked)) view.addGestureRecognizer(click) } @objc private func clicked() { clickHandler() } override func viewDidLayout() { super.viewDidLayout() imageLayer.frame = imageContainerView.bounds } private func updateUI() { guard let item = newsItem, let imageUrl = item.image else { return } imageLayer.contents = Self.placeholderImage imageDownloadOperation?.cancel() imageDownloadOperation = ImageDownloadCenter.shared.downloadImage(from: imageUrl, thumbnailHeight: Constants.thumbnailHeight) { [weak self] url, result in guard let self = self else { return } guard url == imageUrl, result.original != nil else { return } self.imageLayer.contents = result.original } titleLabel.stringValue = item.title titleLabel.toolTip = item.title } }
93010c62cfed486e2fce37c6dd4fd2ea
29.991597
162
0.670282
false
false
false
false
xiaowinner/YXWShineButton
refs/heads/master
YXWShineButton.swift
mit
1
import UIKit @objc public class YXWShineButton: UIControl { /// 更多的配置参数 public var params: YXWShineParams { didSet { clickLayer.animDuration = params.animDuration/3 shineLayer.params = params } } /// 未点击的颜色 public var color: UIColor = UIColor.lightGray { willSet { clickLayer.color = newValue } } /// 点击后的颜色 public var fillColor: UIColor = UIColor(rgb: (255, 102, 102)) { willSet { clickLayer.fillColor = newValue shineLayer.fillColor = newValue } } /// button的图片 public var image: YXWShineImage = .heart { willSet { clickLayer.image = newValue } } /// 是否点击的状态 public override var isSelected:Bool { didSet { clickLayer.clicked = isSelected } } public var currentSelected:Bool = false { willSet { clickLayer.clicked = currentSelected } } private var clickLayer = YXWShineClickLayer() private var shineLayer = YXWShineLayer() //MARK: Initial Methods public init(frame: CGRect, params: YXWShineParams) { self.params = params super.init(frame: frame) initLayers() } public override init(frame: CGRect) { params = YXWShineParams() super.init(frame: frame) initLayers() } required public init?(coder aDecoder: NSCoder) { params = YXWShineParams() super.init(coder: aDecoder) layoutIfNeeded() initLayers() } public override func sendActions(for controlEvents: UIControlEvents) { super.sendActions(for: controlEvents) weak var weakSelf = self if clickLayer.clicked == false { shineLayer.endAnim = { Void in weakSelf?.clickLayer.clicked = !(weakSelf?.clickLayer.clicked ?? false) weakSelf?.clickLayer.startAnim() weakSelf?.currentSelected = weakSelf?.clickLayer.clicked ?? false } shineLayer.startAnim() }else { clickLayer.clicked = !clickLayer.clicked currentSelected = clickLayer.clicked } } //MARK: Override override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) weak var weakSelf = self if clickLayer.clicked == false { shineLayer.endAnim = { Void in weakSelf?.clickLayer.clicked = !(weakSelf?.clickLayer.clicked ?? false) weakSelf?.clickLayer.startAnim() weakSelf?.currentSelected = weakSelf?.clickLayer.clicked ?? false } shineLayer.startAnim() }else { clickLayer.clicked = !clickLayer.clicked currentSelected = clickLayer.clicked } } //MARK: Privater Methods private func initLayers() { clickLayer.animDuration = params.animDuration/3 shineLayer.params = params clickLayer.frame = bounds shineLayer.frame = bounds layer.addSublayer(clickLayer) layer.addSublayer(shineLayer) } }
83b07eb901e724830c32b06e6d29d281
25.230769
87
0.553079
false
false
false
false
alblue/swift
refs/heads/master
test/stmt/yield.swift
apache-2.0
9
// RUN: %target-typecheck-verify-swift struct YieldRValue { var property: String { _read { yield "hello" } } } struct YieldVariables { var property: String { _read { yield "" } _modify { var x = "" yield &x } } var wrongTypes: String { _read { yield 0 // expected-error {{cannot convert value of type 'Int' to expected yield type 'String'}} } _modify { var x = 0 yield &x // expected-error {{cannot yield immutable value of type 'Int' as an inout yield of type 'String'}} } } var rvalue: String { get {} _modify { yield &"" // expected-error {{cannot yield immutable value of type 'String' as an inout yield}} } } var missingAmp: String { get {} _modify { var x = "" yield x // expected-error {{yielding mutable value of type 'String' requires explicit '&'}} } } } protocol HasProperty { associatedtype Value var property: Value { get set } } struct GenericTypeWithYields<T> : HasProperty { var storedProperty: T? var property: T { _read { yield storedProperty! } _modify { yield &storedProperty! } } subscript<U>(u: U) -> (T,U) { _read { yield ((storedProperty!, u)) } _modify { var temp = (storedProperty!, u) yield &temp } } } // 'yield' is a context-sensitive keyword. func yield(_: Int) {} func call_yield() { yield(0) } struct YieldInDefer { var property: String { _read { defer { // expected-warning {{'defer' statement before end of scope always executes immediately}}{{7-12=do}} // FIXME: this recovery is terrible yield "" // expected-error@-1 {{expression resolves to an unused function}} // expected-error@-2 {{consecutive statements on a line must be separated by ';'}} // expected-warning@-3 {{string literal is unused}} } } } }
75d2c36798376979c3da74884cc25bd9
19.638298
114
0.580412
false
false
false
false
hjanuschka/fastlane
refs/heads/master
fastlane/swift/main.swift
mit
1
// // main.swift // FastlaneSwiftRunner // // Created by Joshua Liebowitz on 8/26/17. // Copyright © 2017 Joshua Liebowitz. All rights reserved. // import Foundation let argumentProcessor = ArgumentProcessor(args: CommandLine.arguments) let timeout = argumentProcessor.commandTimeout class MainProcess { var doneRunningLane = false var thread: Thread! @objc func connectToFastlaneAndRunLane() { runner.startSocketThread() let completedRun = Fastfile.runLane(named: argumentProcessor.currentLane, parameters: argumentProcessor.laneParameters()) if completedRun { runner.disconnectFromFastlaneProcess() } doneRunningLane = true } func startFastlaneThread() { thread = Thread(target: self, selector: #selector(connectToFastlaneAndRunLane), object: nil) thread.name = "worker thread" thread.start() } } let process: MainProcess = MainProcess() process.startFastlaneThread() while (!process.doneRunningLane && (RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 2)))) { // no op } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
c5f8ca4ea3b5e52ec669c41f25f3833a
27.377778
136
0.700078
false
false
false
false
ap4y/JsonSerialize
refs/heads/master
JSONSerialize/JSONDecoder.swift
mit
1
public class JSONDecoder { var stack: [JSON] public init(json: JSON) { stack = [json] } public convenience init(jsonString: String) { self.init(json: JSON.jsonWithJSONString(jsonString)) } public func readObject<T>(block: () -> T?) -> T? { let value = block() pop() return value } public func readValueForKey<T: JSONDecodable>(key: String) -> T? { let json = stack[stack.endIndex - 1] if let value = json.object?[key] { stack.append(value) return T.decode(self) } return nil } public func readArrayForKey<T: JSONDecodable>(key: String) -> [T]? { let json = stack[stack.endIndex - 1] if let value = json.object?[key] { switch value { case let .Array(array): var result = [T]() for item in array { stack.append(item) if let item = T.decode(self) { result.append(item) } } return result default: return nil } } return nil } public func readDictionaryForKey<V: JSONDecodable>(key: String) -> [String: V]? { let json = stack[stack.endIndex - 1] if let value = json.object?[key] { switch value { case let .Object(object): var result = Dictionary<String, V>() for (key, item) in object { stack.append(item) if let value = V.decode(self) { result[key as String] = value } } return result default: return nil } } return nil } func pop() -> JSON { return stack.removeLast() } }
3aed97e8c02c5fdb97d39777bd285916
25.56338
85
0.469247
false
false
false
false
Panl/Gank.lu
refs/heads/master
Gank.lu/UIKit/PageViewUI.swift
gpl-3.0
1
// // PageViewUI.swift // Gank.lu // // Created by Lei Pan on 2020/3/24. // Copyright © 2020 smartalker. All rights reserved. // import SwiftUI import UIKit import struct Kingfisher.KFImage import struct Kingfisher.DownsamplingImageProcessor struct PageViewUI: UIViewControllerRepresentable { var controllers: [UIViewController] @Binding var currentPage: Int func makeCoordinator() -> PageViewUI.Coordinator { Coordinator(self) } func makeUIViewController(context: Context) -> UIPageViewController { let pageViewController = UIPageViewController( transitionStyle: .scroll, navigationOrientation: .horizontal) pageViewController.dataSource = context.coordinator pageViewController.delegate = context.coordinator return pageViewController } func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) { pageViewController.setViewControllers( [controllers[currentPage]], direction: .forward, animated: true) } class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var parent: PageViewUI init(_ pageViewUI: PageViewUI) { self.parent = pageViewUI } func pageViewController( _ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = parent.controllers.firstIndex(of: viewController) else { return nil } if index == 0 { return parent.controllers.last } return parent.controllers[index - 1] } func pageViewController( _ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = parent.controllers.firstIndex(of: viewController) else { return nil } if index + 1 == parent.controllers.count { return parent.controllers.first } return parent.controllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed, let visibleViewController = pageViewController.viewControllers?.first, let index = parent.controllers.firstIndex(of: visibleViewController) { parent.currentPage = index } } } } struct BannerCard: View { var url: String var title: String init(url: String, title: String) { self.url = url self.title = title } var body: some View { HStack { ZStack(alignment: .bottomLeading) { KFImage(URL(string: url), options: [ .transition(.fade(0.2)), .processor( DownsamplingImageProcessor(size: CGSize(width: 375 * 1.5, height: 180 * 1.5)) ), .cacheOriginalImage ]) .resizable() .aspectRatio(contentMode: .fill) .frame(height: 180) LinearGradient(gradient: Gradient(colors: [.clear, Color.black.opacity(0.6)]), startPoint: .top, endPoint: .bottom) .cornerRadius(8) Text(title).font(.headline) .fontWeight(.semibold) .padding(EdgeInsets.init(top: 0, leading: 16, bottom: 32, trailing: 16)).foregroundColor(.white) } .cornerRadius(8) .shadow(radius: 4) }.padding(16) } } struct PageView<Page: View>: View { var viewControllers: [UIHostingController<Page>] @State var currentPage = 0 init(_ views: [Page]) { self.viewControllers = views.map { UIHostingController(rootView: $0) } } var body: some View { ZStack(alignment: .bottom) { PageViewUI(controllers: viewControllers, currentPage: $currentPage) .frame(maxWidth: .infinity, minHeight: 196, alignment: .center) PageControl(numberOfPages: viewControllers.count, currentPage: $currentPage) .padding(.trailing) } } } var features = [1, 2, 3] struct PageView_Previews: PreviewProvider { static var previews: some View { PageView(features.map { _ in BannerCard(url: "", title: "-念念不忘,必有回响, -念念不忘,必有回响") }) } }
7bd0640efd5ade12e6bf5b21f5a254f7
29.333333
190
0.678691
false
false
false
false
fernandomarins/food-drivr-pt
refs/heads/master
hackathon-for-hunger/Modules/Driver/Dashboards/Views/DonationHistoryViewController.swift
mit
1
// // DonationHistoryViewController.swift // hackathon-for-hunger // // Created by Ian Gristock on 20/05/2016. // Copyright © 2016 Hacksmiths. All rights reserved. // import UIKit import RealmSwift class DonationHistoryViewController: UIViewController { @IBOutlet weak var noDonationsView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var tableView: UITableView! private var refreshControl: UIRefreshControl! var activityIndicator : ActivityIndicatorView! private let dashboardPresenter = DashboardPresenter(donationService: DonationService()) var pendingDonations: Results<Donation>? @IBOutlet weak var refreshTriggered: UIButton! @IBAction func refreshDonations(sender: AnyObject) { self.refresh(self) } override func viewDidLoad() { self.refreshTriggered.layer.cornerRadius = 0.5 * self.refreshTriggered.bounds.width self.refreshTriggered.layer.shadowColor = UIColor.blackColor().CGColor self.refreshTriggered.layer.shadowOffset = CGSizeMake(2, 2) self.refreshTriggered.layer.shadowRadius = 2 self.refreshTriggered.layer.shadowOpacity = 0.5 super.viewDidLoad() noDonationsView.hidden = true dashboardPresenter.attachView(self) activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Syncing") refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(PendingDonationsDashboard.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshControl) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dashboardPresenter.fetch([DonationStatus.DroppedOff.rawValue, DonationStatus.Suspended.rawValue ]) } func refresh(sender: AnyObject) { self.startLoading() dashboardPresenter.fetchRemotely([DonationStatus.DroppedOff.rawValue, DonationStatus.Suspended.rawValue]) refreshControl?.endRefreshing() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toDriverMapDetailPendingFromDashboard") { if let donation = sender as? Donation { let donationVC = segue.destinationViewController as! DriverMapDetailPendingVC donationVC.mapViewPresenter = MapViewPresenter(donationService: DonationService(), donation: donation) } } if (segue.identifier == "acceptedDonation") { if let donation = sender as? Donation { let donationVC = segue.destinationViewController as! DriverMapPickupVC donationVC.donation = donation } } } deinit { print("DEINITIALIZING") } } extension DonationHistoryViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pendingDonations?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "pendingDonation" let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! PendingDonationsDashboardTableViewCell cell.indexPath = indexPath cell.information = pendingDonations![indexPath.row] cell.selectionStyle = .None; return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } } extension DonationHistoryViewController: DashboardView { func startLoading() { self.activityIndicator.startAnimating() } func finishLoading() { self.activityIndicator.stopAnimating() self.activityIndicator.title = "Syncing" } func donations(sender: DashboardPresenter, didSucceed donations: Results<Donation>) { self.finishLoading() self.pendingDonations = donations if(donations.isEmpty) { self.tableView.hidden = true self.noDonationsView.hidden = false } else { self.tableView.hidden = false self.noDonationsView.hidden = true self.tableView.reloadData() } } func donations(sender: DashboardPresenter, didFail error: NSError) { self.finishLoading() if error.code == 401 { let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.logout() })) presentViewController(refreshAlert, animated: true, completion: nil) } } func donationStatusUpdate(sender: DashboardPresenter, didSucceed donation: Donation) { self.finishLoading() let index = pendingDonations!.indexOf(donation) self.performSegueWithIdentifier("acceptedDonation", sender: donation) let indexPath = NSIndexPath(forRow: index!, inSection: 0) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } func donationStatusUpdate(sender: DashboardPresenter, didFail error: NSError) { self.finishLoading() if error.code == 401 { let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.logout() })) presentViewController(refreshAlert, animated: true, completion: nil) } else { let refreshAlert = UIAlertController(title: "Unable To Accept.", message: "Donation might have already been accepted. Resync your donations?.", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in self.startLoading() self.dashboardPresenter.fetchRemotely([DonationStatus.Pending.rawValue]) })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in })) presentViewController(refreshAlert, animated: true, completion: nil) } } }
e263fe7908dbd91c9a9d1ec96345858c
39.890805
201
0.673085
false
false
false
false
jhwayne/Minimo
refs/heads/master
SwifferApp/SwifferApp/ComposeViewController.swift
mit
1
// // ComposeViewController.swift // SwifferApp // // Created by Training on 29/06/14. // Copyright (c) 2014 Training. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet var sweetTextView: UITextView! = UITextView() @IBOutlet var charRemainingLabel: UILabel! = UILabel() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() sweetTextView.layer.borderColor = UIColor.blackColor().CGColor sweetTextView.layer.borderWidth = 0.5 sweetTextView.layer.cornerRadius = 5 sweetTextView.delegate = self sweetTextView.becomeFirstResponder() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendSweet(sender: AnyObject) { var query = PFQuery(className:"Posts") query.whereKey("DisplayToday", equalTo:"Yes") query.getFirstObjectInBackgroundWithBlock { (object: PFObject!, error: NSError!) -> Void in if (error != nil || object == nil) { } else { // The find succeeded. let ID = object["PostID"] as Int var sweet:PFObject = PFObject(className: "Sweets") sweet["content"] = self.sweetTextView.text sweet["sweeter"] = PFUser.currentUser() sweet["PostID"] = ID sweet.saveInBackground() self.navigationController?.popToRootViewControllerAnimated(true) } } } func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String!) -> Bool{ var newLength:Int = (textView.text as NSString).length + (text as NSString).length - range.length var remainingChar:Int = 140 - newLength charRemainingLabel.text = "\(remainingChar)" return (newLength > 140) ? false : true } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
e3c1582f52a1a0ec4b3d9dcb83b4d284
29.5
109
0.599044
false
false
false
false
MaartenBrijker/project
refs/heads/back
project/External/AudioKit-master/AudioKit/Common/Nodes/Playback/Phase-Locked Vocoder/AKPhaseLockedVocoder.swift
apache-2.0
1
// // AKPhaseLockedVocoder.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This is a phase locked vocoder. It has the ability to play back an audio /// file loaded into an ftable like a sampler would. Unlike a typical sampler, /// mincer allows time and pitch to be controlled separately. /// /// - parameter audioFileURL: Location of the audio file to use. /// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time. /// - parameter amplitude: Amplitude. /// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc. /// public class AKPhaseLockedVocoder: AKNode { // MARK: - Properties internal var internalAU: AKPhaseLockedVocoderAudioUnit? internal var token: AUParameterObserverToken? private var positionParameter: AUParameter? private var amplitudeParameter: AUParameter? private var pitchRatioParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet(newValue) { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Position in time. When non-changing it will do a spectral freeze of a the current point in time. public var position: Double = 0 { willSet(newValue) { if position != newValue { if internalAU!.isSetUp() { positionParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.position = Float(newValue) } } } } /// Amplitude. public var amplitude: Double = 1 { willSet(newValue) { if amplitude != newValue { if internalAU!.isSetUp() { amplitudeParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.amplitude = Float(newValue) } } } } /// Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc. public var pitchRatio: Double = 1 { willSet(newValue) { if pitchRatio != newValue { if internalAU!.isSetUp() { pitchRatioParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.pitchRatio = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } private var audioFileURL: CFURL // MARK: - Initialization /// Initialize this Phase-Locked Vocoder node /// /// - parameter audioFileURL: Location of the audio file to use. /// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time. /// - parameter amplitude: Amplitude. /// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc. /// public init( audioFileURL: NSURL, position: Double = 0, amplitude: Double = 1, pitchRatio: Double = 1) { self.position = position self.amplitude = amplitude self.pitchRatio = pitchRatio self.audioFileURL = audioFileURL var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x6d696e63 /*'minc'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKPhaseLockedVocoderAudioUnit.self, asComponentDescription: description, name: "Local AKPhaseLockedVocoder", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPhaseLockedVocoderAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } positionParameter = tree.valueForKey("position") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter pitchRatioParameter = tree.valueForKey("pitchRatio") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.positionParameter!.address { self.position = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } else if address == self.pitchRatioParameter!.address { self.pitchRatio = Double(value) } } } internalAU?.position = Float(position) internalAU?.amplitude = Float(amplitude) internalAU?.pitchRatio = Float(pitchRatio) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { Exit: do { var err: OSStatus = noErr var theFileLengthInFrames: Int64 = 0 var theFileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription() var thePropertySize: UInt32 = UInt32(strideofValue(theFileFormat)) var extRef: ExtAudioFileRef = nil var theData: UnsafeMutablePointer<CChar> = nil var theOutputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription() err = ExtAudioFileOpenURL(self.audioFileURL, &extRef) if err != 0 { print("ExtAudioFileOpenURL FAILED, Error = \(err)"); break Exit } // Get the audio data format err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat) if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = \(err)"); break Exit } if theFileFormat.mChannelsPerFrame > 2 { print("Unsupported Format, channel count is greater than stereo"); break Exit } theOutputFormat.mSampleRate = AKSettings.sampleRate theOutputFormat.mFormatID = kAudioFormatLinearPCM theOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat theOutputFormat.mBitsPerChannel = UInt32(strideof(Float)) * 8 theOutputFormat.mChannelsPerFrame = 1; // Mono theOutputFormat.mBytesPerFrame = theOutputFormat.mChannelsPerFrame * UInt32(strideof(Float)) theOutputFormat.mFramesPerPacket = 1 theOutputFormat.mBytesPerPacket = theOutputFormat.mFramesPerPacket * theOutputFormat.mBytesPerFrame // Set the desired client (output) data format err = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, UInt32(strideofValue(theOutputFormat)), &theOutputFormat) if err != 0 { print("ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = \(err)"); break Exit } // Get the total frame count thePropertySize = UInt32(strideofValue(theFileLengthInFrames)) err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames) if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = \(err)"); break Exit } // Read all the data into memory let dataSize = UInt32(theFileLengthInFrames) * theOutputFormat.mBytesPerFrame theData = UnsafeMutablePointer.alloc(Int(dataSize)) if theData != nil { var theDataBuffer: AudioBufferList = AudioBufferList() theDataBuffer.mNumberBuffers = 1 theDataBuffer.mBuffers.mDataByteSize = dataSize theDataBuffer.mBuffers.mNumberChannels = theOutputFormat.mChannelsPerFrame theDataBuffer.mBuffers.mData = UnsafeMutablePointer(theData) // Read the data into an AudioBufferList var ioNumberFrames: UInt32 = UInt32(theFileLengthInFrames) err = ExtAudioFileRead(extRef, &ioNumberFrames, &theDataBuffer) if err == noErr { // success let data=UnsafeMutablePointer<Float>(theDataBuffer.mBuffers.mData) internalAU?.setupAudioFileTable(data, size: ioNumberFrames) internalAU!.start() } else { // failure theData.dealloc(Int(dataSize)) theData = nil // make sure to return NULL print("Error = \(err)"); break Exit; } } } } /// Function to stop or bypass the node, both are equivalent public func stop() { internalAU!.stop() } }
d97733be2424bdcfb718acadb7d51958
42.039648
147
0.620164
false
false
false
false
gvsucis/mobile-app-dev-book
refs/heads/master
iOS/ch04/TraxyApp/TraxyApp/UIViewController+Validation.swift
gpl-3.0
4
// // UIViewController+Validation.swift // TraxyApp // // Created by Jonathan Engelsma on 2/7/17. // Copyright © 2017 Jonathan Engelsma. All rights reserved. // import UIKit extension UIViewController { func isValidPassword(password: String?) -> Bool { guard let s = password, s.lowercased().range(of: "traxy") != nil else { return false } return true } func isEmptyOrNil(password: String?) -> Bool { guard let s = password, s != "" else { return false } return true } func isValidEmail(emailStr : String? ) -> Bool { var emailOk = false if let email = emailStr { let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", regex) emailOk = emailPredicate.evaluate(with: email) } return emailOk } }
0ce1a70b787a6eedacc6033b2acae652
23.846154
79
0.54386
false
false
false
false
mdznr/Keyboard
refs/heads/master
KeyboardExtension/Spacebar.swift
mit
2
// // Spacebar.swift // Keyboard // // Created by Matt Zanchelli on 6/16/14. // Copyright (c) 2014 Matt Zanchelli. All rights reserved. // import UIKit class Spacebar: MetaKey { override func refreshAppearance() { UIView.animateWithDuration(0.18, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .BeginFromCurrentState | .AllowUserInteraction, animations: { if self.highlighted { self.horizontalLine.backgroundColor = self.enabledTintColor self.horizontalLine.frame.size.height = 3 } else { self.horizontalLine.backgroundColor = self.disabledTintColor self.horizontalLine.frame.size.height = 1 } // Center the line vertically self.horizontalLine.frame.origin.y = CGRectGetMidY(self.bounds) - (self.horizontalLine.frame.size.height/2) }, completion: nil) } let horizontalLine: UIView = { let view = UIView() view.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin | .FlexibleBottomMargin return view }() override init(frame: CGRect) { super.init(frame: frame) // Initialization code horizontalLine.frame = CGRect(x: 0, y: CGRectGetMidY(self.bounds) - 0.5, width: self.bounds.size.width, height: 1) self.addSubview(horizontalLine) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
72767aadf2ad48e0c071608980c8db7c
28.733333
174
0.713752
false
false
false
false
lemonkey/iOS
refs/heads/master
ContactsPro/CheckBoxLayer.swift
mit
3
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A `CALayer` subclass that draws a check box within its layer. This is shared between ListerKit on iOS and OS X to to draw their respective `CheckBox` controls. */ import QuartzCore class CheckBoxLayer: CALayer { // MARK: Types struct SharedColors { static let defaultTintColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.5, 0.5, 0.5]) } // MARK: Properties var tintColor: CGColor = SharedColors.defaultTintColor { didSet { setNeedsDisplay() } } var isChecked: Bool = false { didSet { setNeedsDisplay() } } var strokeFactor: CGFloat = 0.07 { didSet { setNeedsDisplay() } } var insetFactor: CGFloat = 0.17 { didSet { setNeedsDisplay() } } var markInsetFactor: CGFloat = 0.34 { didSet { setNeedsDisplay() } } // The method that does the heavy lifting of check box drawing code. override func drawInContext(context: CGContext) { super.drawInContext(context) let size = min(bounds.width, bounds.height) var transform = affineTransform() var xTranslate: CGFloat = 0 var yTranslate: CGFloat = 0 if bounds.size.width < bounds.size.height { yTranslate = (bounds.height - size) / 2.0 } else { xTranslate = (bounds.width - size) / 2.0 } transform = CGAffineTransformTranslate(transform, xTranslate, yTranslate) let strokeWidth: CGFloat = strokeFactor * size let checkBoxInset: CGFloat = insetFactor * size // Create the outer border for the check box. let outerDimension: CGFloat = size - 2.0 * checkBoxInset var checkBoxRect = CGRect(x: checkBoxInset, y: checkBoxInset, width: outerDimension, height: outerDimension) checkBoxRect = CGRectApplyAffineTransform(checkBoxRect, transform) // Make the desired width of the outer box. CGContextSetLineWidth(context, strokeWidth) // Set the tint color of the outer box. CGContextSetStrokeColorWithColor(context, tintColor) // Draw the outer box. CGContextStrokeRect(context, checkBoxRect) // Draw the inner box if it's checked. if isChecked { let markInset: CGFloat = markInsetFactor * size let markDimension: CGFloat = size - 2.0 * markInset var markRect = CGRect(x: markInset, y: markInset, width: markDimension, height: markDimension) markRect = CGRectApplyAffineTransform(markRect, transform) CGContextSetFillColorWithColor(context, tintColor) CGContextFillRect(context, markRect) } } }
cc271f985cd2cbdc22b80d02ce98b54e
29.663265
164
0.604326
false
false
false
false
SwifterSwift/SwifterSwift
refs/heads/master
Tests/UIKitTests/UIBarButtonExtensionsTests.swift
mit
1
// UIBarButtonExtensionsTests.swift - Copyright 2020 SwifterSwift @testable import SwifterSwift import XCTest #if canImport(UIKit) && !os(watchOS) import UIKit final class UIBarButtonExtensionsTests: XCTestCase { func testFlexibleSpace() { let space1 = UIBarButtonItem.flexibleSpace let space2 = UIBarButtonItem.flexibleSpace // Make sure two different instances are created XCTAssert(space1 !== space2) } func testSelector() {} func testAddTargetForAction() { let barButton = UIBarButtonItem() let selector = #selector(testSelector) barButton.addTargetForAction(self, action: selector) let target = barButton.target as? UIBarButtonExtensionsTests XCTAssertEqual(target, self) XCTAssertEqual(barButton.action, selector) } func testFixedSpace() { let width: CGFloat = 120 let barButtonItem = UIBarButtonItem.fixedSpace(width: width) XCTAssertEqual(barButtonItem.width, width) } } #endif
9641a430aab762c9ff370f1e09aa7d24
26.052632
68
0.698444
false
true
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Display information/Graphics overlay (dictionary renderer) 3D/GraphicsOverlayDictionaryRenderer3DViewController.swift
apache-2.0
1
// // Copyright © 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import ArcGIS /// A view controller that manages the interface of the Graphics Overlay /// (Dictionary Renderer) 3D sample. class GraphicsOverlayDictionaryRenderer3DViewController: UIViewController { /// The scene view managed by the view controller. @IBOutlet weak var sceneView: AGSSceneView! { didSet { sceneView.scene = AGSScene(basemapStyle: .arcGISTopographic) sceneView.graphicsOverlays.add(makeGraphicsOverlay()) } } /// Creates a graphics overlay configured to display MIL-STD-2525D /// symbology. /// - Returns: A new `AGSGraphicsOverlay` object. func makeGraphicsOverlay() -> AGSGraphicsOverlay { let graphicsOverlay = AGSGraphicsOverlay() // Create the style from Joint Military Symbology MIL-STD-2525D // portal item. let dictionarySymbolStyle = AGSDictionarySymbolStyle( portalItem: AGSPortalItem( portal: .arcGISOnline(withLoginRequired: false), itemID: "d815f3bdf6e6452bb8fd153b654c94ca" ) ) dictionarySymbolStyle.load { [weak self, weak graphicsOverlay] error in guard let self = self, let graphicsOverlay = graphicsOverlay else { return } if let error = error { self.presentAlert(error: error) } else { let camera = AGSCamera(lookAt: graphicsOverlay.extent.center, distance: 15_000, heading: 0, pitch: 70, roll: 0) self.sceneView.setViewpointCamera(camera) // Use Ordered Anchor Points for the symbol style draw rule. if let drawRuleConfiguration = dictionarySymbolStyle.configurations.first(where: { $0.name == "model" }) { drawRuleConfiguration.value = "ORDERED ANCHOR POINTS" } graphicsOverlay.renderer = AGSDictionaryRenderer(dictionarySymbolStyle: dictionarySymbolStyle) } } // Read the messages and add a graphic to the overlay for each messages. if let messagesURL = Bundle.main.url(forResource: "Mil2525DMessages", withExtension: "xml") { do { let messagesData = try Data(contentsOf: messagesURL) let messages = try MessageParser().parseMessages(from: messagesData) let graphics = messages.map { AGSGraphic(geometry: AGSMultipoint(points: $0.points), symbol: nil, attributes: $0.attributes) } graphicsOverlay.graphics.addObjects(from: graphics) } catch { print("Error reading or decoding messages: \(error)") } } else { preconditionFailure("Missing Mil2525DMessages.xml") } return graphicsOverlay } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["GraphicsOverlayDictionaryRenderer3DViewController"] } } struct Message { var points: [AGSPoint] var attributes: [String: Any] } class MessageParser: NSObject { struct ControlPoint { var x: Double var y: Double } private var controlPoints = [ControlPoint]() private var wkid: Int? private var attributes = [String: Any]() private var contentsOfCurrentElement = "" private var parsedMessages = [Message]() func didFinishParsingMessage() { let spatialReference = AGSSpatialReference(wkid: wkid!) let points = controlPoints.map { AGSPoint(x: $0.x, y: $0.y, spatialReference: spatialReference) } let message = Message(points: points, attributes: attributes) parsedMessages.append(message) wkid = nil controlPoints.removeAll() attributes.removeAll() } func parseMessages(from data: Data) throws -> [Message] { defer { parsedMessages.removeAll() } let parser = XMLParser(data: data) parser.delegate = self let parsingSucceeded = parser.parse() if parsingSucceeded { return parsedMessages } else if let error = parser.parserError { throw error } else { return [] } } } extension MessageParser: XMLParserDelegate { func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) { contentsOfCurrentElement.removeAll() } func parser(_ parser: XMLParser, foundCharacters string: String) { contentsOfCurrentElement.append(contentsOf: string) } enum Element: String { case controlPoints = "_control_points" case message case messages case wkid = "_wkid" } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if let element = Element(rawValue: elementName) { switch element { case .controlPoints: controlPoints = contentsOfCurrentElement.split(separator: ";").map { (pair) in let coordinates = pair.split(separator: ",") return ControlPoint(x: Double(coordinates.first!)!, y: Double(coordinates.last!)!) } case .message: didFinishParsingMessage() case .messages: break case .wkid: wkid = Int(contentsOfCurrentElement) } } else { attributes[elementName] = contentsOfCurrentElement } contentsOfCurrentElement.removeAll() } }
2efdef3244196b7fe29ae87834ce6f68
37.301775
178
0.628148
false
false
false
false
huonw/swift
refs/heads/master
test/SILGen/synthesized_conformance_enum.swift
apache-2.0
1
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-silgen %s -swift-version 4 | %FileCheck %s enum Enum<T> { case a(T), b(T) } // CHECK-LABEL: enum Enum<T> { // CHECK: case a(T), b(T) // CHECK: } enum NoValues { case a, b } // CHECK-LABEL: enum NoValues { // CHECK: case a, b // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Enum : Equatable where T : Equatable { // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Enum : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension NoValues : CaseIterable { // CHECK: typealias AllCases = [NoValues] // CHECK: static var allCases: [NoValues] { get } // CHECK: } extension Enum: Equatable where T: Equatable {} // CHECK-LABEL: // static Enum<A>.__derived_enum_equals(_:_:) // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs9EquatableRzlE010__derived_C7_equalsySbACyxG_AFtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { extension Enum: Hashable where T: Hashable {} // CHECK-LABEL: // Enum<A>.hashValue.getter // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs8HashableRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int { // CHECK-LABEL: // Enum<A>.hash(into:) // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum4EnumOAAs8HashableRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () { extension NoValues: CaseIterable {} // CHECK-LABEL: // static NoValues.allCases.getter // CHECK-NEXT: sil hidden @$S28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> { // Witness tables for Enum // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum { // CHECK-NEXT: method #Equatable."=="!1: <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$S28synthesized_conformance_enum4EnumOyxGs9EquatableAAsAERzlsAEP2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum { // CHECK-NEXT: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum // CHECK-NEXT: method #Hashable.hashValue!getter.1: <Self where Self : Hashable> (Self) -> () -> Int : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A> // CHECK-NEXT: method #Hashable.hash!1: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A> // CHECK-NEXT: method #Hashable._rawHashValue!1: <Self where Self : Hashable> (Self) -> ((UInt64, UInt64)) -> Int : @$S28synthesized_conformance_enum4EnumOyxGs8HashableAAsAERzlsAEP13_rawHashValue4seedSis6UInt64V_AJt_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Hashable): dependent // CHECK-NEXT: } // Witness tables for NoValues // CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum { // CHECK-NEXT: associated_type AllCases: Array<NoValues> // CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift) // CHECK-NEXT: method #CaseIterable.allCases!getter.1: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$S28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues // CHECK-NEXT: }
61c44490224b93843ddd3a442f7048fc
60.671233
303
0.723456
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNMModel/Frequency.swift
gpl-2.0
1
// // Frequency.swift // denm_model // // Created by James Bean on 8/12/15. // Copyright © 2015 James Bean. All rights reserved. // import Foundation // TODO: convert to FloatLiteralConvertible /** Frequency of Pitch */ public struct Frequency: CustomStringConvertible { // MARK: String Representation /// Printed description of Frequency public var description: String { get { return "Freq: \(value)" } } // MARK: Attribute /// Value of Frequency as Float (middle-c = 261.6) public var value: Float // MARK: Create a Frequency /** Create a Frequency with value - parameter value: Value of Frequency as Float (middle-c = 261.6) - returns: Initialized Frequency object */ public init(_ value: Float) { self.value = value } /* /** Create a Frequency with a value and resolultion - parameter value: Value of Frequency - parameter resolution: Resolution - returns: (0.25 = 1/8th tone, 0.5 = 1/4-tone, 1 = chromatic) */ public init(value: Float, resolution: Float? = nil) { if let resolution = resolution { self.value = round(value / resolution) * resolution } else { self.value = value } } */ /** Create a Frequency with MIDI - parameter midi: MIDI representation of Pitch (middle-c = 60.0) - returns: Initialized Frequency object */ public init(midi: MIDI) { self.value = 440 * pow(2.0, (midi.value - 69.0) / 12.0) } /** Quantizes Frequency to the desired resolution (chromatic = 1.0, 1/4-tone = 0.5, 1/8th-tone = 0.25) - parameter resolution: MIDI object */ public mutating func quantizeToResolution(resolution: Float) { var midi = MIDI(frequency: self) midi.quantizeToResolution(resolution) self = Frequency(midi: midi) } } func ==(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value == rhs.value } func !=(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value != rhs.value } func <(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value < rhs.value } func >(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value > rhs.value } func <=(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value <= rhs.value } func >=(lhs: Frequency, rhs: Frequency) -> Bool { return lhs.value >= rhs.value } // MARK: Modify Frequency func +(lhs: Frequency, rhs: Frequency) -> Frequency { return Frequency(lhs.value + rhs.value) } func -(lhs: Frequency, rhs: Frequency) -> Frequency { return Frequency(lhs.value - rhs.value) } func *(lhs: Frequency, rhs: Float) -> Frequency { return Frequency(lhs.value * rhs) } /* func %(lhs: Frequency, rhs: Float) -> Frequency { return Frequency(lhs.value % rhs) } */
56c08c0336193860f3b00fca698729e5
22
70
0.607525
false
false
false
false
JaySonGD/SwiftDayToDay
refs/heads/master
获取通信录3/获取通信录3/ViewController.swift
mit
1
// // ViewController.swift // 获取通信录3 // // Created by czljcb on 16/3/18. // Copyright © 2016年 lQ. All rights reserved. // import UIKit import ContactsUI class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if #available(iOS 9.0, *) { let vc = CNContactPickerViewController() vc.delegate = self presentViewController(vc, animated: true, completion: nil) } } } @available(iOS 9.0, *) extension ViewController: CNContactPickerDelegate{ func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) { let name = contact.familyName + contact.middleName + contact.givenName print(name) let phones = contact.phoneNumbers for phone in phones{ print(phone.label) let value: CNPhoneNumber = phone.value as! CNPhoneNumber print(value.stringValue) } } }
14ea57a559739ea1750a0509daaff86f
23.6
100
0.607811
false
false
false
false
colemancda/Pedido
refs/heads/master
Pedido Admin/Pedido Admin/NewMenuItemViewController.swift
mit
1
// // NewMenuItemViewController.swift // Pedido Admin // // Created by Alsey Coleman Miller on 12/27/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import UIKit class NewMenuItemViewController: NewManagedObjectViewController { // MARK: - IB Outlets @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var priceTextfield: UITextField! @IBOutlet weak var currencySymbolLabel: UILabel! // MARK: - Properties override var entityName: String { return "MenuItem" } var currencyLocale: NSLocale = NSLocale.currentLocale() { didSet { // update UI self.currencySymbolLabel.text = currencyLocale.objectForKey(NSLocaleCurrencySymbol) as? String // set locale on number formatter self.numberFormatter.locale = self.currencyLocale } } // MARK: - Private Properties lazy var numberFormatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle numberFormatter.locale = self.currencyLocale numberFormatter.currencySymbol = "" return numberFormatter }() // MARK: - Methods override func getNewValues() -> [String : AnyObject]? { // attributes let name = self.nameTextField.text let price = self.numberFormatter.numberFromString(self.priceTextfield.text) // invalid price text if price == nil { self.showErrorAlert(NSLocalizedString("Invalid value for price.", comment: "Invalid value for price.")) return nil } return ["name": name, "price": price!, "currencyLocaleIdentifier": self.currencyLocale.localeIdentifier] } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch MainStoryboardSegueIdentifier(rawValue: segue.identifier!)! { case .NewMenuItemPickCurrencyLocale: let currencyLocalePickerVC = segue.destinationViewController as CurrencyLocalePickerViewController currencyLocalePickerVC.selectedCurrencyLocale = self.currencyLocale // set handler currencyLocalePickerVC.selectionHandler = { self.currencyLocale = currencyLocalePickerVC.selectedCurrencyLocale! } default: return } } }
6c1adf7f4a8086515ee0f99fdc654390
26.6
115
0.595143
false
false
false
false
WebAPIKit/WebAPIKit
refs/heads/master
Sources/WebAPIKit/Response/ResponseHeaderKey.swift
mit
1
/** * WebAPIKit * * Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows: * * 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 /// Wrapper for http response header keys. public struct ResponseHeaderKey: RawValueWrapper { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } } extension HTTPURLResponse { /// Get header response header value by key as `ResponseHeaderKey`. public func value(forHeaderKey key: ResponseHeaderKey) -> String? { return allHeaderFields[key.rawValue] as? String } } extension WebAPIResponse { /// Get header response header value by key as `ResponseHeaderKey`. public func value(forHeaderKey key: ResponseHeaderKey) -> String? { return headers[key.rawValue] as? String } } // MARK: Common used keys extension ResponseHeaderKey { /// Valid actions for a specified resource. To be used for a 405 Method not allowed. /// - `Allow: GET, HEAD` public static let allow = ResponseHeaderKey("Allow") /// Where in a full body message this partial message belongs. /// - `Content-Range: bytes 21010-47021/47022` public static let contentRange = ResponseHeaderKey("Content-Range") /// An identifier for a specific version of a resource, often a message digest. /// - `ETag: "737060cd8c284d8af7ad3082f209582d"` public static let eTag = ResponseHeaderKey("ETag") /// An HTTP cookie. /// - `Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=` public static let setCookie = ResponseHeaderKey("Set-Cookie") }
6616053d45daf061c65b584929c6d2bc
34.972973
88
0.719384
false
false
false
false
walokra/Haikara
refs/heads/master
Haikara/Models/Paywall.swift
mit
1
// // PaywallType.swift // highkara // // The MIT License (MIT) // // Copyright (c) 2018 Marko Wallin <[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 var paywallTextAll: String = NSLocalizedString("PAYWALL_TEXT_ALL", comment: "News source paywall type") var paywallTextFree: String = NSLocalizedString("PAYWALL_TEXT_FREE", comment: "News source paywall type") var paywallTextPartial: String = NSLocalizedString("PAYWALL_TEXT_PARTIAL", comment: "News source paywall type") var paywallTextMonthly: String = NSLocalizedString("PAYWALL_TEXT_MONTHLY", comment: "News source paywall type") var paywallTextStrict: String = NSLocalizedString("PAYWALL_TEXT_STRICT", comment: "News source paywall type") enum Paywall: String { case All = "all" case Free = "free" case Partial = "partial" case Monthly = "monthly-limit" case Strict = "strict-paywall" // func type() -> String { // return self.rawValue // } var type: String { switch self { case .All: return "all" case .Free: return "free" case .Partial: return "partial" case .Monthly: return "monthly-limit" case .Strict: return "strict-paywall" } } var description: String { switch self { case .All: return paywallTextAll case .Free: return paywallTextFree case .Partial: return paywallTextPartial case .Monthly: return paywallTextMonthly case .Strict: return paywallTextStrict } } }
c4a2e3fff67adf7edaf267d7839352d6
38.030303
111
0.701475
false
false
false
false
4faramita/TweeBox
refs/heads/master
TweeBox/ImageContainerViewController.swift
mit
1
// // ImageContainerViewController.swift // TweeBox // // Created by 4faramita on 2017/8/21. // Copyright © 2017年 4faramita. All rights reserved. // import UIKit import SnapKit import Kingfisher class ImageContainerViewController: UIViewController { public var tweet: Tweet? { didSet { setLayout() } } private var media: [TweetMedia]? { return tweet?.entities?.realMedia } private var clickedIndex = 0 private var images = [UIImage]() private var imageViews = [UIImageView]() private let placeholder = R.image.picPlaceholder() // UIImage(named: "picPlaceholder")! private let cutPoint = CGPoint(x: 0.5, y: 0.5) override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() for (index, imageView) in imageViews.enumerated() { if imageView.bounds.height > 0 && imageView.bounds.width > 0 { addGesture(index, imageView) } } } private func setLayout() { if let media = media { switch media.count { case 1: let firstImageView = addImageView(at: 0) firstImageView.snp.makeConstraints({ (make) in make.size.equalTo(view) make.center.equalTo(view) }) case 2: let firstImageView = addImageView(at: 0) firstImageView.snp.makeConstraints({ (make) in make.width.equalTo(view).multipliedBy(0.5) make.height.equalTo(view) make.top.equalTo(view) make.leading.equalTo(view) }) let secondImageView = addImageView(at: 1) secondImageView.snp.makeConstraints({ (make) in make.size.equalTo(firstImageView) make.top.equalTo(firstImageView) make.trailing.equalTo(view) }) case 3: let firstImageView = addImageView(at: 0) firstImageView.snp.makeConstraints({ (make) in make.width.equalTo(view).multipliedBy(0.5) make.height.equalTo(view) make.top.equalTo(view) make.leading.equalTo(view) }) let secondImageView = addImageView(at: 1) secondImageView.snp.makeConstraints({ (make) in make.width.equalTo(firstImageView) make.height.equalTo(firstImageView).multipliedBy(0.5) make.top.equalTo(firstImageView) make.trailing.equalTo(view) }) let thirdImageView = addImageView(at: 2) thirdImageView.snp.makeConstraints({ (make) in make.size.equalTo(secondImageView) make.bottom.equalTo(firstImageView) make.trailing.equalTo(view) }) case 4: let firstImageView = addImageView(at: 0) firstImageView.snp.makeConstraints({ (make) in make.width.equalTo(view).multipliedBy(0.5) make.height.equalTo(view).multipliedBy(0.5) make.top.equalTo(view) make.leading.equalTo(view) }) let secondImageView = addImageView(at: 1) secondImageView.snp.makeConstraints({ (make) in make.size.equalTo(firstImageView) make.top.equalTo(firstImageView) make.trailing.equalTo(view) }) let thirdImageView = addImageView(at: 2) thirdImageView.snp.makeConstraints({ (make) in make.size.equalTo(firstImageView) make.bottom.equalTo(view) make.leading.equalTo(view) }) let fourthImageView = addImageView(at: 3) fourthImageView.snp.makeConstraints({ (make) in make.size.equalTo(firstImageView) make.bottom.equalTo(view) make.trailing.equalTo(view) }) default: break } } } private func addImageView(at index: Int) -> UIImageView { let imageView = UIImageView() view.addSubview(imageView) imageView.contentMode = .scaleAspectFit var ratio: CGFloat { let total = media!.count if (total == 2) || (total == 3 && index == 0) { return Constants.thinAspectRatio } else { return Constants.normalAspectRatio } } let cutSize = media![index].getCutSize(with: ratio, at: Constants.picQuality) // let processor = CroppingImageProcessor(size: cutSize, anchor: cutPoint) KingfisherManager.shared.retrieveImage(with: media![index].mediaURL!, options: nil, progressBlock: nil) { [weak self] (image, error, cacheType, url) in if let image = image, let cutPoint = self?.cutPoint { self?.images.append(image) let cuttedImage = image.kf.crop(to: cutSize, anchorOn: cutPoint) imageView.image = cuttedImage } } // imageView.kf.setImage( // with: media![index].mediaURL, // placeholder: placeholder, // options: [ // .transition(.fade(Constants.picFadeInDuration)), // .processor(processor) // ] // ) // { [weak self] (image, error, cacheType, url) in // if let image = image { // self?.images.append(image) // } // } imageViews.append(imageView) return imageView } private func addGesture(_ index: Int, _ imageView: ImageView) { imageView.isUserInteractionEnabled = true // add tap gesture let gestures = [#selector(tapOnFirstImage(_:)), #selector(tapOnSecondImage(_:)), #selector(tapOnThirdImage(_:)), #selector(tapOnFourthImage(_:))] let tapGesture = UITapGestureRecognizer(target: self, action: gestures[index]) tapGesture.numberOfTapsRequired = 1 tapGesture.numberOfTouchesRequired = 1 imageView.addGestureRecognizer(tapGesture) } @IBAction private func tapOnFirstImage(_ sender: UIGestureRecognizer) { clickedIndex = 0 if media?.count == 1, media?[0].type != "photo" { performSegue(withIdentifier: "Video Tapped", sender: nil) } performSegue(withIdentifier: "Image Tapped", sender: imageViews[0]) } @IBAction private func tapOnSecondImage(_ sender: UIGestureRecognizer) { clickedIndex = 1 performSegue(withIdentifier: "Image Tapped", sender: imageViews[1]) } @IBAction private func tapOnThirdImage(_ sender: UIGestureRecognizer) { clickedIndex = 2 performSegue(withIdentifier: "Image Tapped", sender: imageViews[2]) } @IBAction private func tapOnFourthImage(_ sender: UIGestureRecognizer) { clickedIndex = 3 performSegue(withIdentifier: "Image Tapped", sender: imageViews[3]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case "Video Tapped": if let videoViewer = segue.destination.content as? VideoViewerViewController { videoViewer.tweetMedia = media![0] } case "Image Tapped": if let imageViewer = segue.destination as? ImageViewerViewController { imageViewer.image = images[clickedIndex] imageViewer.imageURL = tweet?.entities?.mediaToShare?[clickedIndex].mediaURL } default: return } } } }
9bcc86ebd9aebac1b861a95b3aa6a7bd
32.963855
159
0.527374
false
false
false
false