repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
trvslhlt/games-for-impact-final
projects/WinkWink_11/WinkWink/Nodes/SelectVulvasChallengeNode.swift
1
4197
// // SelectVulvasChallengeNode.swift // WinkWink_11 // // Created by trvslhlt on 4/15/17. // Copyright © 2017 travis holt. All rights reserved. // import UIKit class SelectVulvasChallengeNode: ChallengeNode { private let challengeLabelContainerNode = AppSpriteNode() private let optionsContainerNode = AppSpriteNode(color: .clear, size: CGSize.zero) private var optionNodes = [AppSpriteNode]() private let rows = 2 private let columns = 2 private var selectedOptions = Set<AppSpriteNode>() private let submitNode = AppSpriteNode() private let submitNodeHeight: CGFloat = 50 override func commonInit() { super.commonInit() potentialValue = 50 var challengeLabelNode = AppLabelNode(text: "Select all of the\nnormal looking vulvas") challengeLabelNode = AppLabelNode.multipleLineText(labelInPut: challengeLabelNode) challengeLabelNode.verticalAlignmentMode = .center challengeLabelContainerNode.addChild(challengeLabelNode) addChild(challengeLabelContainerNode) for i in 0..<(rows * columns) { let optionNode = getNewOptionNode(imageName: "normal_vulva_0\(i)" ) optionsContainerNode.addChild(optionNode) optionNodes.append(optionNode) } addChild(optionsContainerNode) submitNode.didTap = { self.didSubmitAnswer(correct: false) } let submitLabel = AppLabelNode(text: "Next >>>") submitLabel.verticalAlignmentMode = .center submitNode.addChild(submitLabel) addChild(submitNode) } private func getNewOptionNode(imageName: String?) -> AppSpriteNode { let optionNode = AppSpriteNode(color: .clear, size: CGSize.zero) let vulvaNode: AppSpriteNode if let name = imageName { vulvaNode = AppSpriteNode(imageNamed: name) } else { vulvaNode = AppSpriteNode(color: .green, size: CGSize(width: 50, height: 50)) } vulvaNode.position = optionNode.size.centerPoint() optionNode.addChild(vulvaNode) optionNode.didTap = { optionNode.alpha = 0.5 self.selectedOptions.insert(vulvaNode) if self.selectedOptions.count == (self.rows * self.columns) { self.didSubmitAnswer(correct: true) } } return optionNode } override func didUpdate(parentSize: CGSize) { super.didUpdate(parentSize: parentSize) size = parentSize challengeLabelContainerNode.size = size.portionOf(w: 1, h: 0.2) optionsContainerNode.size = size.portionOf(w: 0.8, h: 0.6) submitNode.size = size.portionOf(w: 1, h: 0.2) challengeLabelContainerNode.position = size.pointAtPortion(x: 0, y: 0.4) optionsContainerNode.position = CGPoint.zero submitNode.position = size.pointAtPortion(x: 0, y: -0.4) let optionNodeSize = self.optionNodeSize() let origin = CGPoint(x: -1 * (optionsContainerNode.size.width / 2), y: -1 * (optionsContainerNode.size.height / 2)) let optionNodeCenterInset = CGPoint(x: optionNodeSize.width / 2, y: optionNodeSize.height / 2) for row in 0..<rows { for column in 0..<columns { let idx = (rows * column) + row let node = optionNodes[idx] node.size = optionNodeSize let positionalOffset = CGPoint( x: optionNodeSize.width * CGFloat(column), y: optionNodeSize.height * CGFloat(row)) let nodePosition = origin + optionNodeCenterInset + positionalOffset node.position = nodePosition } } } private func optionNodeSize() -> CGSize { let nodeWidth: CGFloat = optionsContainerNode.size.width / CGFloat(columns) let nodeHeight: CGFloat = optionsContainerNode.size.height / CGFloat(rows) return CGSize(width: nodeWidth, height: nodeHeight) } override func start() { print("Vulva:start") } override func stop() { print("Vulva:stop") } }
mit
ec6ba0136626677fec216f8445f28fc2
36.801802
123
0.629886
4.325773
false
false
false
false
theodinspire/FingerBlade
FingerBlade/Transmitter.swift
1
1352
// // Transmitter.swift // FingerBlade // // Created by Cormack on 2/16/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import Foundation import AWSS3 class Transmitter { static let transferUtility = AWSS3TransferUtility.default() static let expression = AWSS3TransferUtilityUploadExpression() static var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock = { (task, error) -> Void in DispatchQueue.main.async { if let error = error { print("Failed with error: \(error)") } else { print("Successful upload") } } } /// Sends data to AWS S3 bucket /// /// - Parameters: /// - data: Data to be uploaded /// - filename: Key to place the data under static func upload(data: Data?, named filename: String) { if KeyRing.setup { if let data = data { transferUtility.uploadData(data, bucket: KeyRing.bucket!, key: filename, contentType: "text/plain", expression: expression, completionHandler: completionHandler) } else { print("Data not valid") } } else { print("The AWS connection has not been established. Transmission aborted") } } }
gpl-3.0
5c5efcde30166ced68840944814d72ce
29.704545
177
0.583272
4.773852
false
false
false
false
Malecks/PALette
Palette/YPMagnifyingView.swift
1
2734
// // YPMagnifyingView.swift // YPMagnifyingGlass // // Created by Geert-Jan Nilsen on 02/06/15. // Copyright (c) 2015 Yuppielabel.com All rights reserved. // import UIKit public class YPMagnifyingView: UIView { private var magnifyingGlassShowDelay: TimeInterval = 0.2 private var touchTimer: Timer! var magnifyingGlass: YPMagnifyingGlass? var touchesRecieved: ((_ touch: UITouch) -> ())? override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Touch Events public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch: UITouch = touches.first { let y: CGFloat = touch.location(in: self).y if y < self.frame.height && y > 0 { self.touchTimer = Timer.scheduledTimer( timeInterval: magnifyingGlassShowDelay, target: self, selector: #selector(YPMagnifyingView.addMagnifyingGlassTimer(timer:)), userInfo: NSValue(cgPoint: touch.location(in: self)), repeats: false ) self.touchesRecieved?(touch) } } } public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch: UITouch = touches.first { let y: CGFloat = touch.location(in: self).y if y < self.frame.height && y > 0 { self.updateMagnifyingGlassAtPoint(point: touch.location(in: self)) self.touchesRecieved?(touch) } } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchTimer.invalidate() self.touchTimer = nil self.removeMagnifyingGlass() } // MARK: - Private Functions private func addMagnifyingGlassAtPoint(point: CGPoint) { guard let mag = self.magnifyingGlass else { return } mag.touchPoint = point self.addSubview(mag) mag.setNeedsDisplay() } private func removeMagnifyingGlass() { self.magnifyingGlass?.removeFromSuperview() } private func updateMagnifyingGlassAtPoint(point: CGPoint) { guard let mag = self.magnifyingGlass else { return } mag.touchPoint = point mag.setNeedsDisplay() } public func addMagnifyingGlassTimer(timer: Timer) { let value: AnyObject? = timer.userInfo as AnyObject? if let point = value?.cgPointValue { self.addMagnifyingGlassAtPoint(point: point) } } }
mit
b9bf477c319753e475f0ff2ebcc6da93
30.790698
90
0.596928
4.460033
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Comment/CommentsResponseHandler.swift
1
2309
// // CommentsResponseHandler.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import ObjectMapper public class CommentsResponseHandler: ResponseHandler { fileprivate let completion: CommentsClosure? public init(completion: CommentsClosure?) { self.completion = completion } public override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) { if let response = response, let mappers = Mapper<CommentMapper>().mapArray(JSONObject: response["data"]) { let metadata = MappingUtils.metadataFromResponse(response) let pageInfo = MappingUtils.pagingInfoFromResponse(response) let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata) let comments = mappers.map({ Comment(mapper: $0, dataMapper: dataMapper, metadata: metadata) }) executeOnMainQueue { self.completion?(comments, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) } } else { executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) } } } }
mit
d1333168118801042dc2adbeb565dfd4
46.122449
131
0.728021
4.780538
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClientUnitTests/Spec/Gallery/UpdateGalleryRequestSpec.swift
1
2694
// // UpdateGalleryRequestSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Quick import Nimble @testable import CreatubblesAPIClient class UpdateGalleryRequestSpec: QuickSpec { override func spec() { describe("Update gallery request") { it("Should have proper method") { let data = UpdateGalleryData(galleryId: "12345", name: nil, galleryDescription: nil, openForAll: nil) let request = UpdateGalleryRequest(data: data) expect(request.method) == RequestMethod.put } it("Should have proper endpoint") { let galleryId = "12345" let data = UpdateGalleryData(galleryId: galleryId, name: nil, galleryDescription: nil, openForAll: nil) let request = UpdateGalleryRequest(data: data) expect(request.endpoint) == "galleries/\(galleryId)" } it("Should have proper parameters") { let galleryId = "12345" let title = "sampleTitle" let description = "sampleDescription" let data = UpdateGalleryData(galleryId: galleryId, name: title, galleryDescription: description, openForAll: true) let request = UpdateGalleryRequest(data: data) expect(request.parameters["name"] as? String) == title expect(request.parameters["description"] as? String) == description expect(request.parameters["open_for_all"] as? Bool).to(beTrue()) } } } }
mit
2dbd04e30106827bdbdb89a2099f8bfc
43.9
130
0.664811
4.668977
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00074-swift-typeloc-iserror.swift
1
886
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func i<r>() -> (r, r -> r) -> r { x cb x.c = { } { r) { w } } q i { } class x: i{ class func c {} q l { } struct b<w> : l { func b(b: b.dc) { } } class y<g>: d { p(cb: g) { } } struct l<g> { } struct x<i : cb, r: cb u r.w == i.w> { } q cb { } struct r<x : w> { } func f<x>() -> [r<x>] { } q f { } class b<w : r, j w.r == c> : f { } x> { } q r { } class l: l { } class cb : n { } func ^(f: i, u) f<i : b, r : b u i.x == r> { } q b { } struct r<w : b> : b
apache-2.0
4eb30e5c9df9c29dd6de9136433fbc87
15.109091
79
0.537246
2.414169
false
false
false
false
OrdnanceSurvey/search-swift
OSSearch/SearchResult.swift
1
9490
// // SearchResult.swift // Search // // Created by Dave Hardiman on 11/03/2016 // Copyright (c) Ordnance Survey. All rights reserved. // import Foundation import OSJSON @objc(OSSearchResult) public class SearchResult: NSObject, Decodable { // MARK: Properties public let language: String public let lastUpdateDate: String? public let rpc: String public let buildingNumber: String? public let postcode: String public let uprn: String public let matchDescription: String public let entryDate: String? public let postalAddressCode: String? public let localCustodianCode: Int? public let status: String public let blpuStateCode: String? public let organisationName: String? public let postalAddressCodeDescription: String? public let classificationCodeDescription: String? public let xCoordinate: Float public let match: Float public let classificationCode: String? public let topographyLayerToid: String? public let localCustodianCodeDescription: String? public let blpuStateCodeDescription: String public let dependentLocality: String? public let logicalStatusCode: String? public let yCoordinate: Float public let thoroughfareName: String? public let address: String public let postTown: String public let blpuStateDate: String? init(language: String, lastUpdateDate: String?, rpc: String, buildingNumber: String?, postcode: String, uprn: String, matchDescription: String, entryDate: String?, postalAddressCode: String?, localCustodianCode: Int?, status: String, blpuStateCode: String?, organisationName: String?, postalAddressCodeDescription: String?, classificationCodeDescription: String?, xCoordinate: Float, match: Float, classificationCode: String?, topographyLayerToid: String?, localCustodianCodeDescription: String?, blpuStateCodeDescription: String, dependentLocality: String?, logicalStatusCode: String?, yCoordinate: Float, thoroughfareName: String?, address: String, postTown: String, blpuStateDate: String?) { self.language = language self.lastUpdateDate = lastUpdateDate self.rpc = rpc self.buildingNumber = buildingNumber self.postcode = postcode self.uprn = uprn self.matchDescription = matchDescription self.entryDate = entryDate self.postalAddressCode = postalAddressCode self.localCustodianCode = localCustodianCode self.status = status self.blpuStateCode = blpuStateCode self.organisationName = organisationName self.postalAddressCodeDescription = postalAddressCodeDescription self.classificationCodeDescription = classificationCodeDescription self.xCoordinate = xCoordinate self.match = match self.classificationCode = classificationCode self.topographyLayerToid = topographyLayerToid self.localCustodianCodeDescription = localCustodianCodeDescription self.blpuStateCodeDescription = blpuStateCodeDescription self.dependentLocality = dependentLocality self.logicalStatusCode = logicalStatusCode self.yCoordinate = yCoordinate self.thoroughfareName = thoroughfareName self.address = address self.postTown = postTown self.blpuStateDate = blpuStateDate } //MARK: JSON initialiser convenience required public init?(json: JSON) { guard let dpa = json.jsonForKey("DPA"), language = dpa.stringValueForKey(SearchResult.LanguageKey), rpc = dpa.stringValueForKey(SearchResult.RpcKey), postcode = dpa.stringValueForKey(SearchResult.PostcodeKey), uprn = dpa.stringValueForKey(SearchResult.UprnKey), matchDescription = dpa.stringValueForKey(SearchResult.MatchDescriptionKey), status = dpa.stringValueForKey(SearchResult.StatusKey), blpuStateCodeDescription = dpa.stringValueForKey(SearchResult.BlpuStateCodeDescriptionKey), address = dpa.stringValueForKey(SearchResult.AddressKey), postTown = dpa.stringValueForKey(SearchResult.PostTownKey) else { return nil } let logicalStatusCode = dpa.stringValueForKey(SearchResult.LogicalStatusCodeKey) let classificationCodeDescription = dpa.stringValueForKey(SearchResult.ClassificationCodeDescriptionKey) let classificationCode = dpa.stringValueForKey(SearchResult.ClassificationCodeKey) let localCustodianCodeDescription = dpa.stringValueForKey(SearchResult.LocalCustodianCodeDescriptionKey) let postalAddressCode = dpa.stringValueForKey(SearchResult.PostalAddressCodeKey) let postalAddressCodeDescription = dpa.stringValueForKey(SearchResult.PostalAddressCodeDescriptionKey) let entryDate = dpa.stringValueForKey(SearchResult.EntryDateKey) let lastUpdateDate = dpa.stringValueForKey(SearchResult.LastUpdateDateKey) let topographyLayerToid = dpa.stringValueForKey(SearchResult.TopographyLayerToidKey) let blpuStateCode = dpa.stringValueForKey(SearchResult.BlpuStateCodeKey) let blpuStateDate = dpa.stringValueForKey(SearchResult.BlpuStateDateKey) let organisationName = dpa.stringValueForKey(SearchResult.OrganisationNameKey) let localCustodianCode = dpa.intValueForKey(SearchResult.LocalCustodianCodeKey) let xCoordinate = dpa.floatValueForKey(SearchResult.XCoordinateKey) let match = dpa.doubleValueForKey(SearchResult.MatchKey) let yCoordinate = dpa.floatValueForKey(SearchResult.YCoordinateKey) let buildingNumber = dpa.stringValueForKey(SearchResult.BuildingNumberKey) let dependentLocality = dpa.stringValueForKey(SearchResult.DependentLocalityKey) let thoroughfareName = dpa.stringValueForKey(SearchResult.ThoroughfareNameKey) self.init( language: language, lastUpdateDate: lastUpdateDate, rpc: rpc, buildingNumber: buildingNumber, postcode: postcode, uprn: uprn, matchDescription: matchDescription, entryDate: entryDate, postalAddressCode: postalAddressCode, localCustodianCode: localCustodianCode, status: status, blpuStateCode: blpuStateCode, organisationName: organisationName, postalAddressCodeDescription: postalAddressCodeDescription, classificationCodeDescription: classificationCodeDescription, xCoordinate: xCoordinate, match: Float(match), classificationCode: classificationCode, topographyLayerToid: topographyLayerToid, localCustodianCodeDescription: localCustodianCodeDescription, blpuStateCodeDescription: blpuStateCodeDescription, dependentLocality: dependentLocality, logicalStatusCode: logicalStatusCode, yCoordinate: yCoordinate, thoroughfareName: thoroughfareName, address: address, postTown: postTown, blpuStateDate: blpuStateDate ) } } extension SearchResult { // MARK: Declaration for string constants to be used to decode and also serialize. @nonobjc internal static let LanguageKey: String = "LANGUAGE" @nonobjc internal static let LastUpdateDateKey: String = "LAST_UPDATE_DATE" @nonobjc internal static let RpcKey: String = "RPC" @nonobjc internal static let BuildingNumberKey: String = "BUILDING_NUMBER" @nonobjc internal static let PostcodeKey: String = "POSTCODE" @nonobjc internal static let UprnKey: String = "UPRN" @nonobjc internal static let MatchDescriptionKey: String = "MATCH_DESCRIPTION" @nonobjc internal static let EntryDateKey: String = "ENTRY_DATE" @nonobjc internal static let PostalAddressCodeKey: String = "POSTAL_ADDRESS_CODE" @nonobjc internal static let LocalCustodianCodeKey: String = "LOCAL_CUSTODIAN_CODE" @nonobjc internal static let StatusKey: String = "STATUS" @nonobjc internal static let BlpuStateCodeKey: String = "BLPU_STATE_CODE" @nonobjc internal static let OrganisationNameKey: String = "ORGANISATION_NAME" @nonobjc internal static let PostalAddressCodeDescriptionKey: String = "POSTAL_ADDRESS_CODE_DESCRIPTION" @nonobjc internal static let ClassificationCodeDescriptionKey: String = "CLASSIFICATION_CODE_DESCRIPTION" @nonobjc internal static let XCoordinateKey: String = "X_COORDINATE" @nonobjc internal static let MatchKey: String = "MATCH" @nonobjc internal static let ClassificationCodeKey: String = "CLASSIFICATION_CODE" @nonobjc internal static let TopographyLayerToidKey: String = "TOPOGRAPHY_LAYER_TOID" @nonobjc internal static let LocalCustodianCodeDescriptionKey: String = "LOCAL_CUSTODIAN_CODE_DESCRIPTION" @nonobjc internal static let BlpuStateCodeDescriptionKey: String = "BLPU_STATE_CODE_DESCRIPTION" @nonobjc internal static let DependentLocalityKey: String = "DEPENDENT_LOCALITY" @nonobjc internal static let LogicalStatusCodeKey: String = "LOGICAL_STATUS_CODE" @nonobjc internal static let YCoordinateKey: String = "Y_COORDINATE" @nonobjc internal static let ThoroughfareNameKey: String = "THOROUGHFARE_NAME" @nonobjc internal static let AddressKey: String = "ADDRESS" @nonobjc internal static let PostTownKey: String = "POST_TOWN" @nonobjc internal static let BlpuStateDateKey: String = "BLPU_STATE_DATE" }
apache-2.0
80bb8b52a5f6c7fc9648b5d347d41b56
53.228571
698
0.739621
4.761666
false
false
false
false
TorinKwok/NSRegExNamedCaptureGroup
Sources/_Core.swift
1
2723
import Foundation /// Returns a range equivalent to the given `NSRange`, /// or `nil` if the range can't be converted. /// /// - Parameters: /// - nsRange: The Foundation range to convert. /// /// - Returns: A Swift range equivalent to `nsRange` /// if it is able to be converted. Otherwise, `nil`. fileprivate extension String { func range( from nsRange: NSRange ) -> Range<Index>? { guard let swiftRange = nsRange.toRange() else { return nil } let utf16start = UTF16Index( swiftRange.lowerBound ) let utf16end = UTF16Index( swiftRange.upperBound ) guard let start = Index( utf16start, within: self ) , let end = Index( utf16end, within: self ) else { return nil } return start..<end } } // Matches all types of capture groups, including // named capture (?<Name> ... ), atomic grouping (?> ... ), // conditional (? if then|else) and so on, except for // grouping-only parentheses (?: ... ). fileprivate let GenericCaptureGroupsPattern = try! NSRegularExpression( pattern: "\\((?!\\?:).*?>" , options: .dotMatchesLineSeparators ) // Further refinement. // We will only work on Named Capture Groups (?<Name> ... ). fileprivate let NamedCaptureGroupsPattern = try! NSRegularExpression( pattern: "^\\(\\?<([\\w\\a_-]*)>$" , options: .dotMatchesLineSeparators ) extension NSRegularExpression /* _NamedCaptureGroupsSupport */ { func _resultsOfNamedCaptures() -> [ String: Int ] { var groupNames = [ String: Int ]() var index = 0 GenericCaptureGroupsPattern.enumerateMatches( in: self.pattern , options: .withTransparentBounds , range: NSMakeRange( 0, self.pattern.utf16.count ) ) { ordiGroup, _, stopToken in guard let ordiGroup = ordiGroup else { stopToken.pointee = ObjCBool( true ) return } // Extract the sub-expression nested in `self.pattern` let genericCaptureGroupExpr: String = self.pattern[ self.pattern.range( from: ordiGroup.range )! ] // Extract the part of Named Capture Group sub-expressions // nested in `genericCaptureGroupExpr`. let namedCaptureGroupsMatched = NamedCaptureGroupsPattern.matches( in: genericCaptureGroupExpr , options: .anchored , range: NSMakeRange( 0, genericCaptureGroupExpr.utf16.count ) ) if namedCaptureGroupsMatched.count > 0 { let firstNamedCaptureGroup = namedCaptureGroupsMatched[ 0 ] let groupName: String = genericCaptureGroupExpr[ genericCaptureGroupExpr.range( from: firstNamedCaptureGroup.rangeAt( 1 ) )! ] groupNames[ groupName ] = index + 1 index += 1 } } return groupNames } }
apache-2.0
66c23e8d2ed3f641e41f3e7bb5b52a15
29.943182
134
0.653691
4.322222
false
false
false
false
megabitsenmzq/PomoNow-iOS
PomoNow/PomoNow/Dialog.swift
1
15765
// // NavigationController.swift // PomoNow // // Created by Megabits on 15/10/3. // Copyright © 2015年 Jinyu Meng. All rights reserved. // import UIKit class Dialog: UIView, UIPickerViewDelegate, UIPickerViewDataSource{ typealias DatePickerCallback = (_ timer: TimeInterval) -> Void typealias PickerCallback = (_ rowSelect:Int) -> Void /* Consts */ fileprivate let kDatePickerDialogDefaultButtonHeight: CGFloat = 50 fileprivate let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1 fileprivate let kDatePickerDialogCornerRadius: CGFloat = 7 fileprivate let kDatePickerDialogDoneButtonTag: Int = 1 fileprivate let kPickerDialogDefaultButtonHeight: CGFloat = 50 fileprivate let kPickerDialogDefaultButtonSpacerHeight: CGFloat = 1 fileprivate let kPickerDialogCornerRadius: CGFloat = 7 fileprivate let kPickerDialogDoneButtonTag: Int = 1 /* Views */ fileprivate var dialogView: UIView! fileprivate var titleLabel: UILabel! fileprivate var datePicker: UIDatePicker! fileprivate var cancelButton: UIButton! fileprivate var doneButton: UIButton! fileprivate var Picker: UIPickerView! fileprivate var selected = false fileprivate var nowDialog = 0 fileprivate var taskAdd: UIView! /* Vars */ fileprivate var defaultTime: TimeInterval? fileprivate var datePickerMode: UIDatePickerMode? fileprivate var callback: DatePickerCallback? fileprivate var maxKeyBoardHeight: CGFloat = 0 fileprivate var dialogHeight: CGFloat = 0 var rowSelected = 0 var defaultRow:Int! var numbers = ["1","2","3","4","5","6","7","8","9","10"] fileprivate var pcallback: PickerCallback? //delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 10 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return numbers[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { rowSelected = row selected = true } /* Overrides */ init() { super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.main.scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(self.dialogView!) dialogHeight = dialogView.frame.origin.y NotificationCenter.default.addObserver(self, selector:#selector(Dialog.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil); NotificationCenter.default.addObserver(self, selector:#selector(Dialog.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil); } //根据键盘状态调整对话框位置 @objc func keyboardWillShow(_ notif:Notification){ let userInfo:NSDictionary = notif.userInfo! as NSDictionary; let keyBoardInfo: AnyObject? = userInfo.object(forKey: UIKeyboardFrameEndUserInfoKey) as AnyObject; let keyBoardHeight = (keyBoardInfo?.cgRectValue.size.height)!; //键盘最终的高度 if keyBoardHeight > 10 { maxKeyBoardHeight = keyBoardHeight dialogView.frame.origin.y = dialogHeight - maxKeyBoardHeight/3 } } @objc func keyboardWillHide(_ notif:Notification){ dialogView.frame.origin.y = dialogHeight } /* Create the dialog view, and animate opening the dialog */ func showDatePicker(_ title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultTime: TimeInterval = TimeInterval(), datePickerMode: UIDatePickerMode = .dateAndTime, callback: @escaping DatePickerCallback) { //此处设置传入参数 nowDialog = 0 setupView() self.titleLabel.text = title self.doneButton.setTitle(doneButtonTitle, for: UIControlState()) self.cancelButton.setTitle(cancelButtonTitle, for: UIControlState()) self.datePickerMode = datePickerMode self.callback = callback self.defaultTime = defaultTime self.datePicker.datePickerMode = self.datePickerMode ?? .date self.datePicker.countDownDuration = self.defaultTime ?? TimeInterval() showDialogInSame() } func showPicker(_ title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaults: Int = 1, callback: @escaping PickerCallback) { //此处设置传入参数 nowDialog = 1 setupView() self.titleLabel.text = title self.doneButton.setTitle(doneButtonTitle, for: UIControlState()) self.cancelButton.setTitle(cancelButtonTitle, for: UIControlState()) self.pcallback = callback self.defaultRow = defaults self.Picker.selectRow(defaults, inComponent: 0, animated: true) showDialogInSame() } func showAddTask(_ title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", callback: @escaping DatePickerCallback) { //此处设置传入参数 nowDialog = 2 setupView() self.titleLabel.text = title self.doneButton.setTitle(doneButtonTitle, for: UIControlState()) self.cancelButton.setTitle(cancelButtonTitle, for: UIControlState()) self.callback = callback showDialogInSame() } func showDialogInSame() { //显示不同对话框时的相同代码 /* */ UIApplication.shared.windows.first!.addSubview(self) UIApplication.shared.windows.first!.endEditing(true) /* Anim */ UIView.animate( withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } /* Dialog close animation then cleaning and removing the view from the parent */ fileprivate func close() { NotificationCenter.default.removeObserver(self) let currentTransform = self.dialogView.layer.transform let startRotation = (self.value(forKeyPath: "layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + Double.pi * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animate( withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ fileprivate func createContainerView() -> UIView { let screenSize = countScreenSize() var dialogSize = CGSize( width: 300, height: 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) if nowDialog == 2 { dialogSize = CGSize( width: 300, height: 130 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) } // For the black background self.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRect(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).cgColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor] let cornerRadius = kDatePickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, at: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSize(width: 0 - (cornerRadius + 5) / 2, height: 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.black.cgColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).cgPath // There is a line above the button let lineView = UIView(frame: CGRect(x: 0, y: dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, width: dialogContainer.bounds.size.width, height: kDatePickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 280, height: 30)) self.titleLabel.textAlignment = NSTextAlignment.center self.titleLabel.font = UIFont.boldSystemFont(ofSize: 17) dialogContainer.addSubview(self.titleLabel) self.datePicker = UIDatePicker(frame: CGRect(x: 0, y: 30, width: 0, height: 0)) self.datePicker.autoresizingMask = UIViewAutoresizing.flexibleRightMargin self.datePicker.frame.size.width = 300 self.Picker = UIPickerView(frame: CGRect(x: 0, y: 30, width: 0, height: 0)) self.Picker.delegate = self self.Picker.autoresizingMask = UIViewAutoresizing.flexibleRightMargin self.Picker.frame.size.width = 300 self.taskAdd = TagSelectView.instanceFromNib() self.taskAdd.frame = CGRect(x: 0, y: 30, width: 300, height: 100) if nowDialog == 0 { dialogContainer.addSubview(self.datePicker) } else if nowDialog == 1 { dialogContainer.addSubview(self.Picker) } else if nowDialog == 2 { dialogContainer.addSubview(self.taskAdd) } // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ fileprivate func addButtonsToView(_ container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton(type: UIButtonType.custom) as UIButton self.cancelButton.frame = CGRect( x: 0, y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, width: buttonWidth, height: kDatePickerDialogDefaultButtonHeight ) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), for: UIControlState()) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), for: UIControlState.highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14) self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.cancelButton.addTarget(self, action: #selector(Dialog.buttonTapped(_:)), for: UIControlEvents.touchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton(type: UIButtonType.custom) as UIButton self.doneButton.frame = CGRect( x: buttonWidth, y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, width: buttonWidth, height: kDatePickerDialogDefaultButtonHeight ) if nowDialog == 0 { self.doneButton.tag = kDatePickerDialogDoneButtonTag } else if nowDialog == 1 { self.doneButton.tag = kPickerDialogDoneButtonTag } else if nowDialog == 2 { self.doneButton.tag = kDatePickerDialogDoneButtonTag } self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), for: UIControlState()) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), for: UIControlState.highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14) self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.doneButton.addTarget(self, action: #selector(Dialog.buttonTapped(_:)), for: UIControlEvents.touchUpInside) container.addSubview(self.doneButton) } @objc func buttonTapped(_ sender: UIButton!) { if sender.tag == kDatePickerDialogDoneButtonTag { self.callback?(self.datePicker.countDownDuration) } if sender.tag == kPickerDialogDoneButtonTag { if selected { self.pcallback?(rowSelected) } else { self.pcallback?(defaultRow) } } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { let screenWidth = UIScreen.main.applicationFrame.size.width let screenHeight = UIScreen.main.bounds.size.height return CGSize(width: screenWidth, height: screenHeight) } }
mit
4bbf058a301c8338932d769af2c7bacd
43.635569
267
0.635666
5.087805
false
false
false
false
poksi592/MDCNetworking
MDCNetworkingTests/NetworkingErrorTests.swift
1
6469
// // NetworkingErrorTests.swift // MDCNetworking // // Created by Despotovic, Mladen on 16/12/2016. // Copyright © 2016 Despotovic, Mladen. All rights reserved. // import XCTest @testable import MDCNetworking class NetworkingErrorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testErrors400() { // Test 400 // Prepare let mockedResponse400 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 400, httpVersion: nil, headerFields: nil) let networkError400 = NetworkError(error: nil, response: mockedResponse400!, payload: nil) // Test and execute if case .badRequest400(_, let response, _) = networkError400! { XCTAssertEqual(response?.statusCode, 400) } else { XCTAssertTrue(false, "error") } // Test 401 // Prepare let mockedResponse401 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 401, httpVersion: nil, headerFields: nil) let networkError401 = NetworkError(error: nil, response: mockedResponse401!, payload: nil) // Test and execute if case .unauthorized401(_, let response, _) = networkError401! { XCTAssertEqual(response?.statusCode, 401) } else { XCTAssertTrue(false, "error") } // Test 403 // Prepare let mockedResponse403 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 403, httpVersion: nil, headerFields: nil) let networkError403 = NetworkError(error: nil, response: mockedResponse403!, payload: nil) // Test and execute if case .forbidden403(_, let response, _) = networkError403! { XCTAssertEqual(response?.statusCode, 403) } else { XCTAssertTrue(false, "error") } // Test 404 // Prepare let mockedResponse404 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 404, httpVersion: nil, headerFields: nil) let networkError404 = NetworkError(error: nil, response: mockedResponse404!, payload: nil) // Test and execute if case .notFound404(_, let response, _) = networkError404! { XCTAssertEqual(response?.statusCode, 404) } else { XCTAssertTrue(false, "error") } } func testErrors500() { // Test 500 // Prepare let mockedResponse500 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 500, httpVersion: nil, headerFields: nil) let networkError500 = NetworkError(error: nil, response: mockedResponse500!, payload: nil) // Test and execute if case .serverError500(_, let response, _) = networkError500! { XCTAssertEqual(response?.statusCode, 500) } else { XCTAssertTrue(false, "error") } // Test 600 // Prepare let mockedResponse600 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 600, httpVersion: nil, headerFields: nil) let networkError600 = NetworkError(error: nil, response: mockedResponse600!, payload: nil) // Test and execute guard case .other = networkError600! else { XCTAssertTrue(false, "error") return } } func testErrorsNotRecognised() { // Test -1 // Prepare let mockedResponseMinusOne = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: -1, httpVersion: nil, headerFields: nil) let networkErrorMinusOne = NetworkError(error: nil, response: mockedResponseMinusOne!, payload: nil) // Test and execute guard case .other = networkErrorMinusOne! else { XCTAssertTrue(false, "error") return } // Test 999 // Prepare let mockedResponse999 = MockedHTTPURLResponseErrorHandling(url: URL.init(string: "https://someurl")!, statusCode: 999, httpVersion: nil, headerFields: nil) let networkError999 = NetworkError(error: nil, response: mockedResponse999!, payload: nil) // Test and execute guard case .other = networkError999! else { XCTAssertTrue(false, "error") return } } }
mit
542f13ede0a03e23a3ddd3dca57a13d4
41.834437
114
0.465523
6.297955
false
true
false
false
JuanjoArreola/AsyncRequest
Tests/AsyncRequestTests/URLSessionRequestTests.swift
1
1475
import XCTest import AsyncRequest class URLSessionRequestTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCancel() { let expectation: XCTestExpectation = self.expectation(description: "testCompletion") let request = URLSessionRequest<String>() request.fail { error in DispatchQueue.main.async { XCTAssertEqual(request.dataTask?.state, URLSessionTask.State.canceling) expectation.fulfill() } } let url = URL(string: "https://placeholdit.imgix.net/~text?txtsize=33&txt=AR&w=400&h=200&bg=0000ff")! request.dataTask = self.request(url: url, completion: { (_, _, _) in }) request.cancel() wait(for: [expectation], timeout: 1.0) } func request(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> URLSessionDataTask { var request = URLRequest(url: url) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request, completionHandler: completion) task.resume() return task } }
mit
14635af99259b941a2b35c0d5301c1f4
34.119048
140
0.617627
4.623824
false
true
false
false
Sharelink/Bahamut
Bahamut/BahamutUIKit/Integer+FriendlyString.swift
1
838
// // Integer+FriendlyString.swift // Vessage // // Created by Alex Chow on 2016/11/26. // Copyright © 2016年 Bahamut. All rights reserved. // import Foundation func intToBadgeString(_ value:Int!) -> String?{ if value == nil { return nil } if value <= 0 { return nil } if value > 99 { return "99+" } return "\(value!)" } extension Int64{ var friendString:String{ if self >= 1000 { return "\(self / 1000)k" } return "\(self)" } } extension Int32{ var friendString:String{ if self >= 1000 { return "\(self / 1000)k" } return "\(self)" } } extension Int{ var friendString:String{ if self >= 1000 { return "\(self / 1000)k" } return "\(self)" } }
mit
3f3fda687af1d119274c423068e485b2
16.040816
51
0.502994
3.744395
false
false
false
false
linchaosheng/CSSwiftWB
SwiftCSWB 3/SwiftCSWB/Class/Home/V/WBHomePicCollection.swift
1
2214
// // WBHomePicCollection.swift // SwiftCSWB // // Created by LCS on 16/7/4. // Copyright © 2016年 Apple. All rights reserved. // import UIKit class WBHomePicCollection: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate { let reuseID = "picCell" var status : WBStatus? { didSet{ reloadData() } } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) dataSource = self delegate = self backgroundColor = UIColor.white isScrollEnabled = false register(UINib(nibName: "WBHomePicCell", bundle: Bundle.main), forCellWithReuseIdentifier: reuseID) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class func picCollectionView(_ collectionViewLayout: UICollectionViewLayout) -> WBHomePicCollection{ let collectionView : WBHomePicCollection = WBHomePicCollection(frame: CGRect.zero, collectionViewLayout: collectionViewLayout) return collectionView } } extension WBHomePicCollection { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return status?.pic_urls?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell : WBHomePicCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! WBHomePicCell let picStr = status?.pic_urls![indexPath.item]["thumbnail_pic"] as? String cell.picUrl = picStr return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let bmiddle_pic = status?.bmiddle_pic // 发送通知给HomeViewController NotificationCenter.default.post(name: Notification.Name(rawValue: CSShowPhotoBrowserController), object: self, userInfo: ["bmiddle_pic" : bmiddle_pic!, "index" : indexPath.item]) } }
apache-2.0
4004a1735858673ec1b5127fa3f20927
31.850746
186
0.678782
5.421182
false
false
false
false
davedelong/DDMathParser
MathParser/Sources/MathParser/MathParserErrors.swift
1
3672
// // MathParserErrors.swift // DDMathParser // // Created by Dave DeLong on 5/6/16. // // import Foundation public struct MathParserError: Error { public enum Kind { // Tokenization Errors case cannotParseNumber case cannotParseHexNumber // can also occur during Resolution case cannotParseOctalNumber // can also occur during Resolution case cannotParseFractionalNumber case cannotParseExponent case cannotParseIdentifier case cannotParseVariable case cannotParseQuotedVariable case cannotParseOperator case zeroLengthVariable // Resolution Errors case cannotParseLocalizedNumber case unknownOperator case ambiguousOperator // Grouping Errors case missingOpenParenthesis case missingCloseParenthesis case emptyFunctionArgument case emptyGroup // Expression Errors case invalidFormat case missingLeftOperand(Operator) case missingRightOperand(Operator) // Evaluation Errors case unknownFunction(String) case unknownVariable(String) case divideByZero case invalidArguments } public let kind: Kind // the location within the original source string where the error was found public let range: Range<Int> public init(kind: Kind, range: Range<Int>) { self.kind = kind self.range = range } } extension MathParserError.Kind: Equatable { } public func ==(lhs: MathParserError.Kind, rhs: MathParserError.Kind) -> Bool { switch (lhs, rhs) { case (.cannotParseNumber, .cannotParseNumber): return true case (.cannotParseHexNumber, .cannotParseHexNumber): return true case (.cannotParseOctalNumber, .cannotParseOctalNumber): return true case (.cannotParseExponent, .cannotParseExponent): return true case (.cannotParseIdentifier, .cannotParseIdentifier): return true case (.cannotParseVariable, .cannotParseVariable): return true case (.cannotParseQuotedVariable, .cannotParseQuotedVariable): return true case (.cannotParseOperator, .cannotParseOperator): return true case (.zeroLengthVariable, .zeroLengthVariable): return true // Resolution Errors case (.cannotParseLocalizedNumber, .cannotParseLocalizedNumber): return true case (.unknownOperator, .unknownOperator): return true case (.ambiguousOperator, .ambiguousOperator): return true // Grouping Errors case (.missingOpenParenthesis, .missingOpenParenthesis): return true case (.missingCloseParenthesis, .missingCloseParenthesis): return true case (.emptyFunctionArgument, .emptyFunctionArgument): return true case (.emptyGroup, .emptyGroup): return true // Expression Errors case (.invalidFormat, .invalidFormat): return true case (.missingLeftOperand(let leftOp), .missingLeftOperand(let rightOp)): return leftOp == rightOp case (.missingRightOperand(let leftOp), .missingRightOperand(let rightOp)): return leftOp == rightOp // Evaluation Errors case (.unknownFunction(let leftString), .unknownFunction(let rightString)): return leftString == rightString case (.unknownVariable(let leftString), .unknownVariable(let rightString)): return leftString == rightString case (.divideByZero, .divideByZero): return true case (.invalidArguments, .invalidArguments): return true default: return false } }
mit
2f37df7355a1bca5b5d8fa19abcc5b5f
36.090909
116
0.676198
5.298701
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOS/Model/DataPoint.swift
1
584
// // DataPoint.swift // EmonCMSiOS // // Created by Matt Galloway on 13/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation struct DataPoint { let time: Date let value: Double } extension DataPoint { static func from(json: [Any]) -> DataPoint? { guard json.count == 2 else { return nil } guard let timeDouble = Double(json[0]) else { return nil } guard let value = Double(json[1]) else { return nil } let time = Date(timeIntervalSince1970: timeDouble / 1000) return DataPoint(time: time, value: value) } }
mit
e7d01b05290fe7211d5c66bcdecb5339
17.806452
62
0.663808
3.470238
false
false
false
false
DavidSkrundz/Lua
Sources/Lua/Lua/LuaVM+Get.swift
1
3938
// // LuaVM+Get.swift // Lua // import CLua extension LuaVM { /// Convert the item at `Index` to a `Double` /// /// - Returns: A `Double` or `nil` if the value is not convertible internal func getDouble(atIndex index: Index) -> Double? { var isNumber: Index = 0 let value = lua_tonumberx(self.state, index, &isNumber) return (isNumber == 1) ? value : nil } /// Convert the item at `Index` to an `Int` /// /// - Returns: An `Int` or `nil` if the value is not convertible internal func getInt(atIndex index: Index) -> Int? { var isInteger: Index = 0 let value = lua_tointegerx(self.state, index, &isInteger) return (isInteger == 1) ? value : nil } /// Convert the item at `Index` to a UInt32 /// /// - Returns: A `UInt32` or `nil` if the value is not convertible internal func getUInt(atIndex index: Index) -> UInt32? { var isUInteger: Index = 0 let value = lua_tounsignedx(self.state, index, &isUInteger) return (isUInteger == 1) ? value : nil } /// Convert the item at `Index` to a `String` /// /// Cannot contain embedded zeros /// /// - Note: If the value is a number, then the actual value in the stack is /// changed to a string. /// /// - Returns: A `String` or `nil` if the value is not convertible internal func getString(atIndex index: Index) -> String? { var length = 0 guard let cstring = lua_tolstring(self.state, index, &length) else { return nil } return String(cString: cstring) } /// Convert the item at `Index` to a pointer /// /// - Returns: Either a pointer to the `UserData`, `LightUserData` or `nil` internal func getUserData(atIndex index: Index) -> UnsafeMutableRawPointer? { return lua_touserdata(self.state, index) } } extension LuaVM { /// Push onto the stack the value `T[k]` where `T` is the table at `index` /// and `k` is the top value of the stack /// /// May trigger a metamethod for the "index" event /// /// - Note: The top value of the stack is replaced by the result /// /// - Parameter index: The `Index` of the table on the stack internal func getTable(atIndex index: Index) { lua_gettable(self.state, index) } /// Push onto the stack the value `T[field]` where `T` is the `Table` at /// `Index` /// /// Does not use metamethods /// /// - Parameter field: The `Index` of the `Table` that should be fetched /// - Parameter index: The `Index` on the stack of the `Table` to fetch from internal func getFieldRaw(_ field: Index, atIndex index: Index) { lua_rawgeti(self.state, index, field) } /// Create a new empty `Table` and push it onto the stack /// /// - Parameter size: An estimate of how many elements the table will have /// as a sequence /// - Parameter count: An estimate of how many other elements the table will /// have internal func createTable(size: Count, count: Count) { lua_createtable(self.state, size, count) } /// Create a new table, add it to the registry with key `name` and push it /// onto the stack /// /// - Throws: `LuaError.TypeCreation` if the key is already in use internal func createMetatable(name: String) throws { guard luaL_newmetatable(self.state, name) == 1 else { throw LuaError.TypeCreation("Metatable with name '\(name)' already exists") } } /// Allocate a new block of memory of `size` bytes, and push a full userdata /// onto the stack /// /// - Parameter size: The size of the block in bytes /// /// - Returns: A pointer to the new block of memory internal func createUserData(size: Int) -> UnsafeMutableRawPointer { return lua_newuserdata(self.state, size)! } /// Push the metatable of the value at `index` onto the stack /// /// If the value does not have a metatable nothing happens /// /// - Returns: `true` if a metatable was pushed onto the stack internal func getMetatable(atIndex index: Index) -> Bool { return lua_getmetatable(self.state, index) == 1 } }
lgpl-3.0
f7e5a1be1e75f7a277fef7a0c4086f27
31.278689
78
0.662519
3.317607
false
false
false
false
Hovo-Infinity/radio
Radio/SimpleViewController.swift
1
6768
// // SimpleViewController.swift // Radio // // Created by Hovhannes Stepanyan on 2/15/18. // Copyright © 2018 Hovhannes Stepanyan. All rights reserved. // import UIKit import AVFoundation class SimpleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate { private var path:String! private var songName:String = "" private var musicURLs:Array<URL> { get { do { return try FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: path)) } catch { return [] } } } init(path aPath:String!) { super.init(nibName: nil, bundle: nil) path = aPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() let session = AVAudioSession.sharedInstance() do { if #available(iOS 10.0, *) { try session.setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeMoviePlayback, options: []) } else { // Fallback on earlier versions try session.setMode(AVAudioSessionModeMoviePlayback) try session.setCategory(AVAudioSessionCategoryPlayback) } do { try session.setActive(true) } catch { print("Unable to activate audio session: \(error.localizedDescription)") } } catch let error as NSError { print ("Failed to set the audio session category and mode : \(String(describing: error.localizedFailureReason))") } tableView = UITableView(frame: self.view.bounds) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "directoryCell") tableView.register(MusicTableViewCell.self, forCellReuseIdentifier: "MusicCell") tableView.dataSource = self tableView.delegate = self view.addSubview(tableView) self.edgesForExtendedLayout = [] } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.musicURLs.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let url = self.musicURLs[indexPath.row] if FileManager.default.directoryExcist(atPath: url.path) { let cell = tableView.dequeueReusableCell(withIdentifier: "directoryCell", for: indexPath) cell.textLabel?.text = url.lastPathComponent return cell } else { let cell:MusicTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MusicCell", for: indexPath) as! MusicTableViewCell cell.setURL(_url: self.musicURLs[indexPath.row]); return cell } } private func swipeGestureOnCell(_ cell:UITableViewCell) { let leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeHandler(_:))) leftSwipeGesture.direction = .left cell.addGestureRecognizer(leftSwipeGesture) let rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeHandler(_:))) rightSwipeGesture.direction = .right cell.addGestureRecognizer(rightSwipeGesture) } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let url = self.musicURLs[indexPath.row] if FileManager.default.directoryExcist(atPath: url.path) { let viewController = SimpleViewController(path: url.path) viewController.navigationItem.title = url.lastPathComponent self.navigationController?.pushViewController(viewController, animated: true) } } public func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { } public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let groupAction = UITableViewRowAction(style: .default, title: NSLocalizedString("move_to", comment: "")) { (action, indexPath) in let cell:MusicTableViewCell = tableView.cellForRow(at: indexPath) as! MusicTableViewCell if FileManager.default.createSubdirectoryOfSongPath(maned: "Rap") { do { try FileManager.default.moveItem(at: cell.url!, to: FileManager.songPath().appendingPathComponent("Rap").appendingPathComponent((cell.url?.lastPathComponent)!)) } catch { print(error.localizedDescription) } } } groupAction.backgroundColor = .gray let deleteAction = UITableViewRowAction(style: .destructive, title: NSLocalizedString("delete", comment: "")) { [unowned self](action, indexPath) in do { try FileManager.default.removeItem(at: self.musicURLs[indexPath.row]); tableView .deleteRows(at: [indexPath], with: .fade) } catch { print(error.localizedDescription) } } deleteAction.backgroundColor = .red return [groupAction, deleteAction] } public func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return true; } public func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 64; } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete) { do { try FileManager.default.removeItem(at: self.musicURLs[indexPath.row]); tableView .deleteRows(at: [indexPath], with: .fade) } catch { print(error.localizedDescription) } } } @objc func swipeHandler(_ sender:UISwipeGestureRecognizer?) { if (sender?.direction == .left) { tableView.setEditing(true, animated: true) } else if (sender?.direction == .right) { tableView.setEditing(false, animated: true) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
gpl-3.0
114dc6d35d484b3a7c3b378e0eb6db18
40.262195
180
0.633368
5.457258
false
false
false
false
Eric217/-OnSale
打折啦/打折啦/必备-内容.swift
1
1589
// // 必备-内容.swift // 打折啦 // // Created by Eric on 11/09/2017. // Copyright © 2017 INGStudio. All rights reserved. // import Foundation ///嵌套的collectionView里的cell class DoubleDeckerCell: UICollectionViewCell { var txt: AttributedLabel! var img: UIImageView! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white txt = AttributedLabel() txt.font = .systemFont(ofSize: 12) txt.textColor = .gray txt.contentAlignment = .center img = UIImageView() img.contentMode = .scaleAspectFit setUpDownConstr() } func setTxt(_ str: String = "测试", size: CGFloat = 13) { txt.text = str if size == 13 { return } txt.font = UIFont.systemFont(ofSize: size) } func setImg_(_ str: String = "tool1") { img.image = UIImage(named: str) } func setUpDownConstr(_ txtH: CGFloat = 30, _ imgH: CGFloat = 60) { addSubview(img) addSubview(txt) txt.snp.makeConstraints{ make in make.width.centerX.equalTo(self) make.height.equalTo(21) make.bottom.equalTo(self).offset(-12) } img.snp.makeConstraints{ make in make.centerX.equalTo(self) make.width.height.equalTo(ScreenWidth*0.25*0.25) make.bottom.equalTo(txt.snp.top).offset(-12) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
596c705892230de1ada5ef28d1d17fb3
24.57377
70
0.576923
3.969466
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Data Plugs/HATDataPlugInformation.swift
1
2402
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ // MARK: Struct public struct HATDataPlugInformation: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `plugID` in JSON is `uuid` * `providerID` in JSON is `providerId` * `dateCreated` in JSON is `crated` * `name` in JSON is `name` * `description` in JSON is `description` * `url` in JSON is `url` * `imageURL` in JSON is `illustrationUrl` * `passwordHash` in JSON is `passwordHash` * `isApproved` in JSON is `approved` * `shouldShowCheckMark` in JSON is `showCheckMark` */ private enum CodingKeys: String, CodingKey { case plugID = "uuid" case providerID = "providerId" case dateCreated = "created" case name = "name" case description = "description" case url = "url" case imageURL = "illustrationUrl" case passwordHash = "passwordHash" case isApproved = "approved" case shouldShowCheckMark = "showCheckMark" } // MARK: - Variables /// The uuid of the `Data Plug` public var plugID: String = "" /// The provider ID for the `Data Plug` public var providerID: String = "" /// The date the `Data Plug` was created as unix time stamp public var dateCreated: Int = 0 /// The name of the `Data Plug` public var name: String = "" /// A short description of the `Data Plug`. What it does and why it is a cool `Data Plug` public var description: String = "" /// The url of the `Data Plug` public var url: String = "" /// The image url of the `Data Plug`, in order to fetch it public var imageURL: String = "" /// The password hash value of the `Data Plug` public var passwordHash: String = "" /// A flag indicatinf if the `Data Plug` is approved for use public var isApproved: Bool = false /// A flag indicating if the `Data Plug` is connected, if it is show checkmark public var shouldShowCheckMark: Bool? = false }
mpl-2.0
26b65438abd767d955506bb6cfbb9dae
32.830986
93
0.626978
3.924837
false
false
false
false
AntonTheDev/CoreFlightAnimation
CoreFlightAnimation/CoreFlightAnimationDemo/Source/FASequence/FASequenceAnimation.swift
1
2678
// // FASequenceTrigger.swift // CoreFlightAnimation // // Created by Anton on 9/3/16. // // import Foundation import UIKit public func ==(lhs:FASequenceAnimation, rhs:FASequenceAnimation) -> Bool { return lhs.animationKey == rhs.animationKey } public class FASequenceAnimation : FASequence, FAAnimatable { public var animationKey : String? public var animatingLayer : CALayer? public var isTimeRelative = true public var progessValue : CGFloat = 0.0 public var triggerOnRemoval : Bool = false required public init(onView view : UIView) { super.init() animatingLayer = view.layer animationKey = String(NSUUID().UUIDString) } convenience required public init(onView view : UIView, withAnimation anim: FAAnimatable, forKey key : String? = nil) { self.init(onView: view) animation = anim animatingLayer = view.layer animationKey = key ?? String(NSUUID().UUIDString) } internal func shouldTriggerRelativeTo(parent : FASequenceAnimation?, forceAnimation : Bool = false) -> Bool { if parent == nil { animation?.animatingLayer = animatingLayer animation?.animationKey = animationKey animation?.applyFinalState(true) return true } if let animKey = parent?.animation?.animationKey, let animationgLayer = parent?.animation?.animatingLayer, let runningAnimationGroup = animationgLayer.animationForKey(animKey) as? FAAnimationGroup { let fireTimeTrigger = isTimeRelative && runningAnimationGroup.timeProgress() >= progessValue let fireValueTrigger = isTimeRelative == false && runningAnimationGroup.valueProgress() >= progessValue if fireTimeTrigger || fireValueTrigger || forceAnimation { animation?.animationKey = animationKey animation?.animatingLayer = animatingLayer animation?.applyFinalState(true) return true } } return false } override public func startSequence() { guard isAnimating == false else { return } animation?.animatingLayer = animatingLayer animation?.animationKey = animationKey super.startSequence() } override public func applyFinalState(animated : Bool) { animation?.animatingLayer = animatingLayer animation?.animationKey = animationKey animation?.applyFinalState(animated) } }
mit
4ee98bd67e93434031fd6fa973ce5433
32.475
115
0.619866
5.421053
false
false
false
false
andrew804/vapor-apns-1.2.2
Sources/VaporAPNS/String+APNS.swift
1
5368
// // String+APNS.swift // VaporAPNS // // Created by Nathan Flurry on 9/26/16. // // import Foundation import CLibreSSL import Core extension String { private func newECKey() throws -> OpaquePointer { guard let ecKey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) else { fatalError() } return ecKey } /// Converts the string (which is a path for the auth key) to a token string func tokenString() throws -> (privateKey: String, publicKey: String) { guard FileManager.default.fileExists(atPath: self) else { throw TokenError.invalidAuthKey } // Fold p8 file and write it back to the file let fileString = try String.init(contentsOfFile: self, encoding: .utf8) guard let privateKeyString = fileString.collapseWhitespace().trimmingCharacters(in: .whitespaces).between( "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----" )?.trimmingCharacters(in: .whitespaces) else { throw TokenError.invalidTokenString } let splittedText = privateKeyString.splitByLength(64) let newText = "-----BEGIN PRIVATE KEY-----\n\(splittedText.joined(separator: "\n"))\n-----END PRIVATE KEY-----" try newText.write(toFile: self, atomically: false, encoding: .utf8) var pKey = EVP_PKEY_new() let fp = fopen(self, "r") PEM_read_PrivateKey(fp, &pKey, nil, nil) fclose(fp) let ecKey = EVP_PKEY_get1_EC_KEY(pKey) EC_KEY_set_conv_form(ecKey, POINT_CONVERSION_UNCOMPRESSED) var pub: UnsafeMutablePointer<UInt8>? = nil let pub_len = i2o_ECPublicKey(ecKey, &pub) var publicKey = "" if let pub = pub { var publicBytes = Bytes(repeating: 0, count: Int(pub_len)) for i in 0..<Int(pub_len) { publicBytes[i] = Byte(pub[i]) } let publicData = Data(bytes: publicBytes) // print("public key: \(publicData.hexString)") publicKey = publicData.hexString } else { publicKey = "" } let bn = EC_KEY_get0_private_key(ecKey!) let privKeyBigNum = BN_bn2hex(bn) let privateKey = "00\(String.init(validatingUTF8: privKeyBigNum!)!)" // print (privateKey) let privData = privateKey.dataFromHexadecimalString()! let privBase64String = try String.init(bytes: privData.base64Encoded) let pubData = publicKey.dataFromHexadecimalString()! let pubBase64String = try String.init(bytes: pubData.base64Encoded) return (privBase64String, pubBase64String) } /// Create `NSData` from hexadecimal string representation /// /// This takes a hexadecimal representation and creates a `NSData` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed. /// /// - returns: Data represented by this hexadecimal string. func dataFromHexadecimalString() -> Data? { var data = Data(capacity: characters.count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in let range = self.range(from: match!.range) let byteString = self.substring(with: range!) var num = UInt8(byteString, radix: 16) data.append(&num!, count: 1) } return data } func splitByLength(_ length: Int) -> [String] { var result = [String]() var collectedCharacters = [Character]() collectedCharacters.reserveCapacity(length) var count = 0 for character in self.characters { collectedCharacters.append(character) count += 1 if (count == length) { // Reached the desired length count = 0 result.append(String(collectedCharacters)) collectedCharacters.removeAll(keepingCapacity: true) } } // Append the remainder if !collectedCharacters.isEmpty { result.append(String(collectedCharacters)) } return result } } extension String { func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } } extension Data { func hexString() -> String { var hexString = "" for byte in self { hexString += String(format: "%02X", byte) } return hexString } }
mit
f53674fccb656ffaa56cfff162a31b02
33.632258
235
0.566319
4.46589
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorSpace/ColorSpaceBase/PredefinedColorSpace.swift
1
13473
// // PredefinedColorSpace.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // extension ColorSpace where Model == XYZColorModel { @inlinable public static var genericXYZ: ColorSpace { return .cieXYZ(illuminant: CIE1931.D50) } @inlinable public static var `default`: ColorSpace { return .genericXYZ } } extension ColorSpace where Model == YxyColorModel { @inlinable public static var genericYxy: ColorSpace { return .cieYxy(illuminant: CIE1931.D50) } @inlinable public static var `default`: ColorSpace { return .genericYxy } } extension ColorSpace where Model == LabColorModel { @inlinable public static var genericLab: ColorSpace { return .cieLab(illuminant: CIE1931.D50) } @inlinable public static var `default`: ColorSpace { return .genericLab } } extension ColorSpace where Model == LuvColorModel { @inlinable public static var genericLuv: ColorSpace { return .cieLuv(illuminant: CIE1931.D50) } @inlinable public static var `default`: ColorSpace { return .genericLuv } } extension ColorSpace where Model == GrayColorModel { @inlinable public static var genericGamma22Gray: ColorSpace { return .calibratedGray(illuminant: CIE1931.D65, gamma: 2.2) } @inlinable public static var `default`: ColorSpace { return .genericGamma22Gray } } extension ColorSpace where Model == RGBColorModel { @inlinable public static var `default`: ColorSpace { return .sRGB } } extension AnyColorSpace { @inlinable public static var genericXYZ: AnyColorSpace { return AnyColorSpace(ColorSpace.genericXYZ) } @inlinable public static var genericYxy: AnyColorSpace { return AnyColorSpace(ColorSpace.genericYxy) } @inlinable public static var genericLab: AnyColorSpace { return AnyColorSpace(ColorSpace.genericLab) } @inlinable public static var genericLuv: AnyColorSpace { return AnyColorSpace(ColorSpace.genericLuv) } @inlinable public static var genericGamma22Gray: AnyColorSpace { return AnyColorSpace(ColorSpace.genericGamma22Gray) } @inlinable public static var sRGB: AnyColorSpace { return AnyColorSpace(ColorSpace.sRGB) } @inlinable public static var adobeRGB: AnyColorSpace { return AnyColorSpace(ColorSpace.adobeRGB) } @inlinable public static var displayP3: AnyColorSpace { return AnyColorSpace(ColorSpace.displayP3) } } extension AnyColorSpace { @inlinable public static func cieXYZ(white: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieXYZ(white: white)) } @inlinable public static func cieYxy(white: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieYxy(white: white)) } @inlinable public static func cieLab(white: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLab(white: white)) } @inlinable public static func cieLuv(white: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLuv(white: white)) } @inlinable public static func cieXYZ(white: XYZColorModel, black: XYZColorModel) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieXYZ(white: white, black: black)) } @inlinable public static func cieYxy(white: XYZColorModel, black: XYZColorModel) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieYxy(white: white, black: black)) } @inlinable public static func cieLab(white: XYZColorModel, black: XYZColorModel) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLab(white: white, black: black)) } @inlinable public static func cieLuv(white: XYZColorModel, black: XYZColorModel) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLuv(white: white, black: black)) } @inlinable public static func cieXYZ(white: Point, luminance: Double, contrastRatio: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieXYZ(white: white, luminance: luminance, contrastRatio: contrastRatio)) } @inlinable public static func cieYxy(white: Point, luminance: Double, contrastRatio: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieYxy(white: white, luminance: luminance, contrastRatio: contrastRatio)) } @inlinable public static func cieLab(white: Point, luminance: Double, contrastRatio: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLab(white: white, luminance: luminance, contrastRatio: contrastRatio)) } @inlinable public static func cieLuv(white: Point, luminance: Double, contrastRatio: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLuv(white: white, luminance: luminance, contrastRatio: contrastRatio)) } @inlinable public static func calibratedGray(white: Point, gamma: Double = 1) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedGray(white: white, gamma: gamma)) } @inlinable public static func calibratedGray(white: XYZColorModel, black: XYZColorModel, gamma: Double = 1) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedGray(white: white, black: black, gamma: gamma)) } @inlinable public static func calibratedGray(white: Point, luminance: Double, contrastRatio: Double, gamma: Double = 1) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedGray(white: white, luminance: luminance, contrastRatio: contrastRatio, gamma: gamma)) } @inlinable public static func calibratedRGB(white: Point, red: Point, green: Point, blue: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, red: red, green: green, blue: blue)) } @inlinable public static func calibratedRGB(white: Point, red: Point, green: Point, blue: Point, gamma: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB(white: Point, red: Point, green: Point, blue: Point, gamma: (Double, Double, Double)) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB(white: XYZColorModel, black: XYZColorModel, red: Point, green: Point, blue: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, black: black, red: red, green: green, blue: blue)) } @inlinable public static func calibratedRGB(white: XYZColorModel, black: XYZColorModel, red: Point, green: Point, blue: Point, gamma: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, black: black, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB(white: XYZColorModel, black: XYZColorModel, red: Point, green: Point, blue: Point, gamma: (Double, Double, Double)) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, black: black, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB(white: Point, luminance: Double, contrastRatio: Double, red: Point, green: Point, blue: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, luminance: luminance, contrastRatio: contrastRatio, red: red, green: green, blue: blue)) } @inlinable public static func calibratedRGB(white: Point, luminance: Double, contrastRatio: Double, red: Point, green: Point, blue: Point, gamma: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, luminance: luminance, contrastRatio: contrastRatio, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB(white: Point, luminance: Double, contrastRatio: Double, red: Point, green: Point, blue: Point, gamma: (Double, Double, Double)) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(white: white, luminance: luminance, contrastRatio: contrastRatio, red: red, green: green, blue: blue, gamma: gamma)) } } extension ColorSpace where Model == XYZColorModel { @inlinable public static func cieXYZ<I: Illuminant>(illuminant: I) -> ColorSpace { return .cieXYZ(white: illuminant.rawValue) } } extension ColorSpace where Model == YxyColorModel { @inlinable public static func cieYxy<I: Illuminant>(illuminant: I) -> ColorSpace { return .cieYxy(white: illuminant.rawValue) } } extension ColorSpace where Model == LabColorModel { @inlinable public static func cieLab<I: Illuminant>(illuminant: I) -> ColorSpace { return .cieLab(white: illuminant.rawValue) } } extension ColorSpace where Model == LuvColorModel { @inlinable public static func cieLuv<I: Illuminant>(illuminant: I) -> ColorSpace { return .cieLuv(white: illuminant.rawValue) } } extension ColorSpace where Model == GrayColorModel { @inlinable public static func calibratedGray<I: Illuminant>(illuminant: I, gamma: Double = 1) -> ColorSpace { return .calibratedGray(white: illuminant.rawValue, gamma: gamma) } } extension ColorSpace where Model == RGBColorModel { @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point) -> ColorSpace { return .calibratedRGB(white: illuminant.rawValue, red: red, green: green, blue: blue) } @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point, gamma: Double) -> ColorSpace { return .calibratedRGB(white: illuminant.rawValue, red: red, green: green, blue: blue, gamma: (gamma, gamma, gamma)) } @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point, gamma: (Double, Double, Double)) -> ColorSpace { return .calibratedRGB(white: illuminant.rawValue, red: red, green: green, blue: blue, gamma: gamma) } } extension AnyColorSpace { @inlinable public static func cieXYZ<I: Illuminant>(illuminant: I) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieXYZ(illuminant: illuminant)) } @inlinable public static func cieYxy<I: Illuminant>(illuminant: I) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieYxy(illuminant: illuminant)) } @inlinable public static func cieLab<I: Illuminant>(illuminant: I) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLab(illuminant: illuminant)) } @inlinable public static func cieLuv<I: Illuminant>(illuminant: I) -> AnyColorSpace { return AnyColorSpace(ColorSpace.cieLuv(illuminant: illuminant)) } @inlinable public static func calibratedGray<I: Illuminant>(illuminant: I, gamma: Double = 1) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedGray(illuminant: illuminant, gamma: gamma)) } @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(illuminant: illuminant, red: red, green: green, blue: blue)) } @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point, gamma: Double) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(illuminant: illuminant, red: red, green: green, blue: blue, gamma: gamma)) } @inlinable public static func calibratedRGB<I: Illuminant>(illuminant: I, red: Point, green: Point, blue: Point, gamma: (Double, Double, Double)) -> AnyColorSpace { return AnyColorSpace(ColorSpace.calibratedRGB(illuminant: illuminant, red: red, green: green, blue: blue, gamma: gamma)) } }
mit
cde94af00324c9565ad77267d42acb6d
37.827089
183
0.697617
4.126493
false
false
false
false
schneppd/com.schneppd.lab.ui
RabbitTracker/RabbitTracker/RabbitTableViewController.swift
1
3140
// // RabbitTableViewController.swift // RabbitTracker // // Created by cdsm on 05/04/2017. // Copyright © 2017 com.schneppd.lab. All rights reserved. // import UIKit class RabbitTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
aa3fdd1d1c0d7ce03677802504d05c3a
32.042105
136
0.671551
5.27563
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Example/Pods/QuickLayout/QuickLayout/QLUtils.swift
9
2332
// // QLUtils.swift // QuickLayout // // Created by Daniel Huri on 11/21/17. // import Foundation #if os(OSX) import AppKit #else import UIKit #endif /** Typealias for dictionary that contains multiple constraints */ public typealias QLMultipleConstraints = [QLAttribute: NSLayoutConstraint] /** Extends layout priority to other readable types */ public extension QLPriority { static let must = QLPriority(rawValue: 999) static let zero = QLPriority(rawValue: 0) } /** Represents pair of attributes */ public struct QLAttributePair { public let first: QLAttribute public let second: QLAttribute } /** Represents size constraints */ public struct QLSizeConstraints { public let width: NSLayoutConstraint public let height: NSLayoutConstraint } /** Represents center constraints */ public struct QLCenterConstraints { public let x: NSLayoutConstraint public let y: NSLayoutConstraint } /** Represents axis constraints (might be .top and .bottom, .left and .right, .leading and .trailing) */ public struct QLAxisConstraints { public let first: NSLayoutConstraint public let second: NSLayoutConstraint } /** Represents center and size constraints */ public struct QLFillConstraints { public let center: QLCenterConstraints public let size: QLSizeConstraints } /** Represents pair of priorities */ public struct QLPriorityPair { public let horizontal: QLPriority public let vertical: QLPriority public static var required: QLPriorityPair { return QLPriorityPair(.required, .required) } public static var must: QLPriorityPair { return QLPriorityPair(.must, .must) } public init(_ horizontal: QLPriority, _ vertical: QLPriority) { self.horizontal = horizontal self.vertical = vertical } } /** Represents axis description */ public enum QLAxis { case horizontally case vertically public var attributes: QLAttributePair { let first: QLAttribute let second: QLAttribute switch self { case .horizontally: first = .left second = .right case .vertically: first = .top second = .bottom } return QLAttributePair(first: first, second: second) } }
apache-2.0
cd7df0b5a6b2d4a3c135319e72755b43
20.009009
98
0.680961
4.581532
false
false
false
false
a736220388/FinestFood
FinestFood/FinestFood/classes/FoodSubject/homePage/controllers/FoodSubjectViewController.swift
1
12624
// // FoodSubjectViewController.swift // FinestFood // // Created by qianfeng on 16/8/16. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit import XWSwiftRefresh class FoodSubjectViewController: HomeTarbarViewController { lazy var scrollViewArray = NSMutableArray() lazy var titleScrollViewArray = NSMutableArray() private var titleScrollView:UIScrollView? private var contentScrollView = UIScrollView() private var foodSujectListView:FoodSubjectListView? lazy var foodListArray = NSMutableArray() private var shoppingView:FoodMoreListView? private var courseView:FoodMoreListView? private var tourView:FoodMoreListView? private var eatingView:FoodMoreListView? private var diyCourseView:FoodMoreListView? private var diyCookingView:FoodMoreListView? private var moivingView:FoodMoreListView? var foodMoreListViewsArray:[FoodMoreListView?]? lazy var titleLabelArray = Array<UILabel>() override func viewDidLoad() { super.viewDidLoad() title = "食不厌精" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(searchAction)) createTitleScrollView() createFoodSujectListView() downloadScrollViewData() downloadFoodListData() } func searchAction(){ let searchCtrl = FSSearchViewController() self.navigationController?.pushViewController(searchCtrl, animated: true) } func createFoodSujectListView(){ contentScrollView.delegate = self view.addSubview(contentScrollView) contentScrollView.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64+40, 0, 49, 0)) } let containerView = UIView.createUIView() contentScrollView.addSubview(containerView) containerView.snp_makeConstraints { (make) in make.edges.equalTo(contentScrollView) make.height.equalTo(contentScrollView) } foodSujectListView = FoodSubjectListView() containerView.addSubview(foodSujectListView!) foodSujectListView?.snp_makeConstraints(closure: {(make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo(containerView) }) foodSujectListView?.tbView!.headerView = XWRefreshNormalHeader(target: self, action: #selector(firstPageAction)) foodSujectListView?.tbView!.footerView = XWRefreshAutoNormalFooter(target: self, action: #selector(refreshAction)) let viewsArray = [shoppingView,courseView,tourView,eatingView,diyCourseView,diyCookingView,moivingView] foodMoreListViewsArray = viewsArray var lastView:UIView = foodSujectListView! for i in 0..<titleScrollViewArray.count-1{ var view = viewsArray[i] view = FoodMoreListView() view?.downloadFoodMoreListData(12+i, limit: 20, offset: 0) containerView.addSubview(view!) view?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((lastView.snp_right)) }) lastView = view! view?.convertListIdClosure = { id in let detailCtrl = FoodDetailViewController() detailCtrl.id = Int(id) self.navigationController?.pushViewController(detailCtrl, animated: true) } } containerView.snp_makeConstraints { (make) in make.right.equalTo(lastView) } contentScrollView.pagingEnabled = true contentScrollView.showsHorizontalScrollIndicator = false foodSujectListView?.convertIdClosure = { [weak self] id,type in if type == "CELL"{ let detailCtrl = FoodDetailViewController() detailCtrl.id = Int(id) self!.navigationController?.pushViewController(detailCtrl, animated: true) }else if type == "AD"{ let scrollViewListCtrl = FSScrollViewListViewController() scrollViewListCtrl.targetId = Int(id) self!.navigationController?.pushViewController(scrollViewListCtrl, animated: true) } } } func createTitleScrollView(){ automaticallyAdjustsScrollViewInsets = false titleScrollViewArray = ["精选","周末逛店","尝美食","体验课","周边游","DIY","自制美食","电影动漫"] titleScrollView = UIScrollView() titleScrollView?.showsHorizontalScrollIndicator = false titleScrollView?.backgroundColor = UIColor.whiteColor() view.addSubview(titleScrollView!) titleScrollView?.snp_makeConstraints(closure: { [weak self] (make) in make.left.right.equalTo(self!.view) make.height.equalTo(40) make.top.equalTo(self!.view.snp_top).offset(64) }) let containerView = UIView.createUIView() titleScrollView!.addSubview(containerView) containerView.snp_makeConstraints { [weak self] (make) in make.edges.equalTo((self?.titleScrollView)!) make.height.equalTo((self?.titleScrollView)!) } var lastLabel:UILabel? = nil for i in 0..<titleScrollViewArray.count{ let label = UILabel.createLabel(titleScrollViewArray[i] as? String, font: UIFont.systemFontOfSize(17), textAlignment: .Center, textColor: UIColor.blackColor()) containerView.addSubview(label) titleLabelArray.append(label) label.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(80) if i == 0{ make.left.equalTo(containerView) }else{ make.left.equalTo((lastLabel?.snp_right)!) } }) lastLabel = label label.userInteractionEnabled = true label.tag = 500 + i let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:))) label.addGestureRecognizer(g) if i == 0{ label.textColor = UIColor.greenColor() } } containerView.snp_makeConstraints { (make) in make.right.equalTo((lastLabel?.snp_right)!) } } func tapAction(g:UITapGestureRecognizer){ for subView in (g.view?.superview?.subviews)!{ if subView.isKindOfClass(UILabel.self){ let tmpLabel = subView as! UILabel tmpLabel.textColor = UIColor.blackColor() } } let index = (g.view?.tag)! - 500 let label = g.view as! UILabel label.textColor = UIColor.greenColor() UIView.beginAnimations("animate", context: nil) UIView.setAnimationDuration(0.5) UIView.setAnimationRepeatCount(1) UIView.setAnimationDelegate(self) if index == 1 || index == 2{ titleScrollView?.contentOffset = CGPointMake(0, 0) }else if index == 3 || index == 4 || index == 5 || index == 6{ titleScrollView?.contentOffset = CGPointMake(CGFloat(40)*CGFloat(index), 0) }else if index == 7{ titleScrollView?.contentOffset = CGPointMake(CGFloat(40)*7, 0) } self.contentScrollView.contentOffset = CGPointMake(kScreenWidth*CGFloat(index), 0) UIView.commitAnimations() } func firstPageAction(){ limit = 20 offset = 0 downloadFoodListData() } func refreshAction(){ limit = 20 offset += 20 downloadFoodListData() } func downloadScrollViewData(){ let downloader = MyDownloader() downloader.downloadWithUrlString(FSScrollViewUrl) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! NSDictionary let dataDict = dict["data"] as! NSDictionary let bannersArray = dataDict["banners"] as! Array<Dictionary<String,AnyObject>> for bannersDict in bannersArray{ let bannerModel = FSScrollViewDataModel() bannerModel.setValuesForKeysWithDictionary(bannersDict) let targetDict = bannersDict["target"] as! Dictionary<String,AnyObject> let targetModel = FSTargetModel() targetModel.setValuesForKeysWithDictionary(targetDict) bannerModel.target = targetModel self!.scrollViewArray.addObject(bannerModel) } dispatch_async(dispatch_get_main_queue(), { self!.foodSujectListView!.scrollViewArray = self!.scrollViewArray }) } } } func downloadFoodListData(){ let downloader = MyDownloader() let url = String(format: FSFoodListUrl,gender,generation,limit,offset) downloader.downloadWithUrlString(url) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in if self!.limit == 20 && self!.offset == 0{ self!.foodListArray.removeAllObjects() } let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! NSDictionary let dataDict = dict["data"] as! NSDictionary let itemsArray = dataDict["items"] as! Array<Dictionary<String,AnyObject>> for itemDict in itemsArray{ let model = FSFoodListModel() model.setValuesForKeysWithDictionary(itemDict) self!.foodListArray.addObject(model) } dispatch_async(dispatch_get_main_queue(), { self?.foodSujectListView?.tbView?.headerView?.endRefreshing() self?.foodSujectListView?.tbView?.footerView?.endRefreshing() self!.foodSujectListView!.foodListArray = self!.foodListArray }) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension FoodSubjectViewController:UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let contView = scrollView.subviews.last let index = Int((contView?.frame.origin.x)!/kScreenWidth) for i in 0..<titleLabelArray.count{ let label = titleLabelArray[i] label.textColor = UIColor.blackColor() if label.tag - 500 == index{ label.textColor = UIColor.greenColor() } UIView.beginAnimations("animate", context: nil) UIView.setAnimationDuration(0.5) UIView.setAnimationRepeatCount(1) UIView.setAnimationDelegate(self) if index == 1 || index == 2{ titleScrollView?.contentOffset = CGPointMake(0, 0) }else if index == 3 || index == 4 || index == 5 || index == 6{ titleScrollView?.contentOffset = CGPointMake(CGFloat(35)*CGFloat(index), 0) }else if index == 7{ titleScrollView?.contentOffset = CGPointMake(CGFloat(40)*7, 0) } UIView.commitAnimations() } } }
mit
747b7936eadf07259b336836c3c32da1
39.934853
171
0.608896
5.21236
false
false
false
false
lingoslinger/SwiftLibraries
SwiftLibraries/Data Models/Library.swift
1
1765
// // LibraryList.swift // SwiftLibraries // // Created by Allan Evans on 7/21/16. // Copyright © 2016 - 2021 Allan Evans. All rights reserved. import Foundation struct Library : Codable { let address : String? let city : String? let cybernavigator : String? let hoursOfOperation : String? let location : Location? let name : String? let phone : String? let state : String? let teacherInTheLibrary : String? let website : Website? let zip : String? enum CodingKeys: String, CodingKey { case address = "address" case city = "city" case cybernavigator = "cybernavigator" case hoursOfOperation = "hours_of_operation" case location = "location" case name = "name_" case phone = "phone" case state = "state" case teacherInTheLibrary = "teacher_in_the_library" case website = "website" case zip = "zip" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) address = try values.decodeIfPresent(String.self, forKey: .address) city = try values.decodeIfPresent(String.self, forKey: .city) cybernavigator = try values.decodeIfPresent(String.self, forKey: .cybernavigator) hoursOfOperation = try values.decodeIfPresent(String.self, forKey: .hoursOfOperation) location = try values.decodeIfPresent(Location.self, forKey: .location) name = try values.decodeIfPresent(String.self, forKey: .name) phone = try values.decodeIfPresent(String.self, forKey: .phone) state = try values.decodeIfPresent(String.self, forKey: .state) teacherInTheLibrary = try values.decodeIfPresent(String.self, forKey: .teacherInTheLibrary) website = try values.decodeIfPresent(Website.self, forKey: .website) zip = try values.decodeIfPresent(String.self, forKey: .zip) } }
mit
b156490fd1c64de022870f6c68ae50c1
32.923077
93
0.731859
3.549296
false
false
false
false
Tj3n/TVNExtensions
DemoTest/DemoTest/RxGithub/RepoListViewController.swift
1
7543
// // ViewController.swift // RxGithub // // Created by TienVu on 1/23/19. // Copyright © 2019 TienVu. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa import RxDataSources class RepoListViewController: UIViewController { let bag = DisposeBag() var viewModel: RepoListViewModel! var refreshControl: UIRefreshControl = { let view = UIRefreshControl(frame: .zero) return view }() let tableView: UITableView = { var tableView = UITableView(frame: .zero) tableView.estimatedRowHeight = 10 tableView.rowHeight = UITableView.automaticDimension tableView.tableFooterView = UIView() tableView.register(RepoListCell.self, forCellReuseIdentifier: RepoListCell.reuseIdentifier) return tableView }() let searchController: UISearchController = { var view = UISearchController(searchResultsController: nil) view.dimsBackgroundDuringPresentation = false return view }() let indicatorView = UIActivityIndicatorView(style: .gray) let footerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40)) let dataSource = RxTableViewSectionedAnimatedDataSource<AnimatableSectionModel<String, Repo>>( configureCell: { (_, tableView, ip, repository: Repo) in let cell = tableView.dequeueReusableCell(RepoListCell.self, for: ip) cell.configure(repo: repository) return cell }) init(viewModel: RepoListViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = UIView() view.backgroundColor = .white view.addSubview(tableView) tableView.tableFooterView = footerView footerView.addSubview(indicatorView) indicatorView.startAnimating() indicatorView.snp.makeConstraints({ (make) in make.center.equalToSuperview() }) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "RxGithub" definesPresentationContext = true if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .automatic navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false } else { tableView.addSubview(refreshControl) tableView.tableHeaderView = searchController.searchBar } assert(viewModel != nil) bindViewModel(vm: viewModel) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 11.0, *) { tableView.refreshControl = refreshControl extendedLayoutIncludesOpaqueBars = true } } func bindViewModel(vm: RepoListViewModel) { let tableView: UITableView = self.tableView let pull = refreshControl.rx .controlEvent(.valueChanged) .withLatestFrom(searchController.searchBar.rx.text.orEmpty) //To not trigger when searching .filter({ $0.count == 0 }) .map({ _ in }) .asDriver(onErrorRecover: { _ in return Driver.empty() }) .startWith(()) //Disable to use Driver.merged with viewWillAppear, .startWith emit 1 event from start //first version of loadMoreTrigger is in last commit let loadMoreTrigger2: (Driver<Bool>) -> (Driver<Void>) = { isLoading in tableView.rx.willEndDragging.asDriver() .withLatestFrom(isLoading) .flatMap({ (loading) in let currentOffset = tableView.contentOffset.y let maximumOffset = tableView.contentSize.height - tableView.frame.size.height // Change 10.0 to adjust the distance from bottom if maximumOffset - currentOffset <= 30.0 && !loading { return Driver.just(()) } return Driver.empty() }) } let searchTrigger = searchController.searchBar.rx.text.orEmpty .throttle(DispatchTimeInterval.milliseconds(500), scheduler: MainScheduler.instance) .distinctUntilChanged() .filter({ $0.count != 0 }) .asDriver { (_) in return Driver.empty() } let searchDidDismiss = searchController.rx.didDismiss .asDriver { (_) in return Driver.empty() } let input = RepoListViewModel.Input(refresh: Driver.merge(pull, searchDidDismiss), selection: tableView.rx.itemSelected.asDriver(), loadMoreTrigger: loadMoreTrigger2, searchTrigger: searchTrigger) let output = vm.transform(input: input) output.repos .map { [AnimatableSectionModel(model: "Repositories", items: $0)] } .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: bag) output.selectedRepo .map { (repo) in return RepoDetailViewController(viewModel: RepoDetailViewModel(repo: repo)) } .do(onNext: { [weak self] (vc) in self?.navigationController?.pushViewController(vc, animated: true) }) .drive() .disposed(by: bag) output.loading .drive(indicatorView.rx.isAnimating) .disposed(by: bag) output.loading .drive(refreshControl.rx.isRefreshing) .disposed(by: bag) output.loading .drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible) .disposed(by: bag) output.error .map { (error) -> UIAlertController in print(error) let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) return alert } .drive(onNext: { [weak self] (alert) in self?.present(alert, animated: true, completion: nil) }) .disposed(by: bag) } } class RepoListCell: UITableViewCell { static let reuseIdentifier = "RepoListCell" override func layoutSubviews() { super.layoutSubviews() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(repo: Repo) { textLabel?.text = repo.name detailTextLabel?.text = repo.owner.login } }
mit
842ac89467f84fbb50793a8bed5ad929
34.575472
122
0.590294
5.457308
false
false
false
false
jovito-royeca/Decktracker
ios/old/Decktracker/View/Card Quiz/CardQuizLeaderboardViewController.swift
1
7098
// // CardQuizLeaderboardViewController.swift // Decktracker // // Created by Jovit Royeca on 4/14/15. // Copyright (c) 2015 Jovito Royeca. All rights reserved. // import UIKit import AVFoundation class CardQuizLeaderboardViewController: UIViewController, MBProgressHUDDelegate { var hud:MBProgressHUD? var btnClose:UIImageView? var webView:UIWebView? var backgroundSoundPlayer:AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. hidesBottomBarWhenPushed = true NSNotificationCenter.defaultCenter().removeObserver(self, name:kParseLeaderboardDone, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"fetchLeaderboardDone:", name:kParseLeaderboardDone, object:nil) // load the sounds backgroundSoundPlayer = try? AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("/audio/cardquiz_leaderboard", ofType: "caf")!), fileTypeHint: AVFileTypeCoreAudioFormat) backgroundSoundPlayer!.prepareToPlay() backgroundSoundPlayer!.volume = 1.0 setupBackground() fetchLeaderboard(nil) #if !DEBUG // send the screen to Google Analytics if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: "Leaderboard") tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]) } #endif } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return true } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.None } // MARK: UI code func setupBackground() { // play the background sound infinitely backgroundSoundPlayer!.numberOfLoops = -1 backgroundSoundPlayer!.play() var dX = CGFloat(5) var dY = CGFloat(5) var dWidth = CGFloat(30) var dHeight = CGFloat(30) var dFrame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) btnClose = UIImageView(frame: dFrame) btnClose!.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "closeTapped:")) btnClose!.userInteractionEnabled = true btnClose!.contentMode = UIViewContentMode.ScaleAspectFill btnClose!.image = UIImage(named: "cancel.png") self.view.addSubview(btnClose!) self.view.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")!) dX = CGFloat(0) dY = btnClose!.frame.origin.y + btnClose!.frame.size.height + 10 dWidth = self.view.frame.size.width dHeight = self.view.frame.height - dY - 125 dFrame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) let circleImage = UIImageView(frame: dFrame) circleImage.contentMode = UIViewContentMode.ScaleAspectFill circleImage.image = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Card_Circles.png") self.view.addSubview(circleImage) dHeight = self.view.frame.height - dY dFrame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) webView = UIWebView(frame: dFrame) webView!.backgroundColor = UIColor.clearColor() webView!.opaque = false self.view.addSubview(webView!) } // MARK: Logic code func fetchLeaderboard(sender: AnyObject?) { hud = MBProgressHUD(view: view) hud!.delegate = self view.addSubview(hud!) hud!.show(true) Database.sharedInstance().fetchLeaderboard() } func fetchLeaderboardDone(sender: AnyObject) { let dict = sender.userInfo as Dictionary? let leaderboard = dict?["leaderboard"] as? Array<PFObject> let baseURL = NSURL(fileURLWithPath: "\(NSBundle.mainBundle().bundlePath)/web") var html = try? NSString(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/web/leaderboard.html", encoding: NSUTF8StringEncoding) var frag = String() var i = 1 for leader in leaderboard! { let user = leader.objectForKey("user") as! PFUser let black = leader.objectForKey("black") as! NSNumber let blue = leader.objectForKey("blue") as! NSNumber let green = leader.objectForKey("green") as! NSNumber let red = leader.objectForKey("red") as! NSNumber let white = leader.objectForKey("white") as! NSNumber let colorless = leader.objectForKey("colorless") as! NSNumber let totalCMC = leader.objectForKey("totalCMC") as! NSNumber var name:String? if let x = user.objectForKey("name") as? String { name = x } else { name = user.objectForKey("username") as? String } frag += "<tr><td class='td_rank'>\(i)</td><td class='td_player' colspan='12'>\(name!)</td></tr>" frag += "<tr><td>&nbsp;</td><td class='td_player' colspan='12'>Score: \(totalCMC)</td></tr>" frag += "<tr><td>&nbsp;</td>" frag += "<td><img src='../images/mana/B/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(black)</td>" frag += "<td><img src='../images/mana/U/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(blue)</td>" frag += "<td><img src='../images/mana/G/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(green)</td>" frag += "<td><img src='../images/mana/R/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(red)</td>" frag += "<td><img src='../images/mana/W/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(white)</td>" frag += "<td><img src='../images/mana/Colorless/32.png' width='16' height='16'></td>" frag += "<td class='td_score'>\(colorless)</td>" frag += "</tr><tr><td colspan='13'>&nbsp;</td></tr>" i++ } html = html!.stringByReplacingOccurrencesOfString("#_PLACEHOLDER_#", withString: frag) webView!.loadHTMLString(html as! String, baseURL: baseURL) hud!.hide(true) } // MARK: Event handlers func closeTapped(sender: AnyObject) { self.backgroundSoundPlayer!.stop() self.dismissViewControllerAnimated(false, completion: nil) } // MARK: MBProgressHUDDelegate func hudWasHidden(hud: MBProgressHUD) { hud.removeFromSuperview() } }
apache-2.0
79a60b6b20e25c85cbc291fa74ec12c9
39.101695
216
0.6051
4.588235
false
false
false
false
Nexmind/Swiftizy
Swiftizy/Classes/Utility/Translations.swift
1
4112
import Foundation public class Translations { struct Static { static var instance = Translations() } var currentLangCode : String var defaultLanguage: String var currentHm : [String : String] init(){ currentLangCode = "" defaultLanguage = "" currentHm = [String : String]() } public static func translate(forKey: String) -> String { return Static.instance.get(clef: forKey) } /** initialize the Translation with the good language. - return: nothing - parameter defaultLang: the default language which the app is translation (example: "en") - parameter: currentLang: specific language you want. If you want the language of the user's device, set it to nil */ public static func initialize(defaultLang: String, currentLang: String?) { var current = Locale.preferredLanguages[0] if currentLang != nil { current = currentLang! } Static.instance.loadLanguageInHashMap(currentLang: current, defaultLanguage: defaultLang) } /*if(lang == Translations.getInstance().get("language_lbl_fr")){ Translations.getInstance().currentLangCode = "fr" } else if(lang == Translations.getInstance().get("language_lbl_en")){ Translations.getInstance().currentLangCode = "en" } else if(lang == Translations.getInstance().get("language_lbl_de")){ Translations.getInstance().currentLangCode = "de" } else if(lang == Translations.getInstance().get("language_lbl_nl")){ Translations.getInstance().currentLangCode = "nl" } NSUserDefaults.standardUserDefaults().setObject([Translations.getInstance().currentLangCode], forKey: "AppleLanguages") NSUserDefaults.standardUserDefaults().synchronize() Translations.getInstance().loadLanguageInHashMap(NSLocale.preferredLanguages()[0])*/ func loadLanguageInHashMap(currentLang : String, defaultLanguage: String){ self.defaultLanguage = defaultLanguage currentLangCode = currentLang let bundle = Bundle.main let langPath = bundle.path(forResource: self.currentLangCode, ofType: "txt") let defaultPath = bundle.path(forResource: defaultLanguage, ofType: "txt") var result : [String : String] = [String : String]() if langPath != nil { if let aStreamReader = StreamReader(path: langPath!) { self.readAndPutFileInHm(aStreamReader: aStreamReader) } else { if let aStreamReader = StreamReader(path: defaultPath!) { self.readAndPutFileInHm(aStreamReader: aStreamReader) } } } else { if defaultPath != nil { if let aStreamReader = StreamReader(path: defaultPath!) { self.readAndPutFileInHm(aStreamReader: aStreamReader) } } else { print("-----< Translations >----- Error when searching traductions files '\(currentLang).txt' or '\(defaultLanguage).txt'") } } } func getCurrentLanguageInTwoLettersFormat() -> String{ //return Locale.preferredLanguages()[0].subStr(0, length: 2) return ""; } func readAndPutFileInHm(aStreamReader : StreamReader){ /* while let line = aStreamReader.nextLine() { var index = 0 if let idx = line.characters.index(of: "=") { index = line.startIndex.distance(from: idx, to: idx) } let clef = line.subStr(0, length: index) let valeur = line.subStr(index + 1, length: line.length - (index + 1)) currentHm.updateValue(valeur, forKey: clef) } aStreamReader.close()*/ } func get(clef : String) -> String{ if let value = self.currentHm[clef]{ return value } else { return clef } } func getHm() -> [String : String]{ return currentHm } func setLangCode(newCode : String){ self.currentLangCode = newCode } }
mit
4a2a6dbd997c9d07a430eaf395fa90f9
36.724771
139
0.613084
4.579065
false
false
false
false
swordmanboy/KeychainGroupBySMB
_Main/DMPKeyChain-For-Master_Main_swift/DMPKeyChain-For-Master_Main_swift/CustomView/SMBUITextView.swift
2
694
// // SMBUITextView.swift // KeychainSampleMain // // Created by Apinun Wongintawang on 9/1/17. // Copyright © 2017 True. All rights reserved. // import UIKit class SMBUITextView : UITextView{ //cornor radius @IBInspectable var cornorRadius : CGFloat = 0.0 { didSet{ self.layer.cornerRadius = cornorRadius } } //width border @IBInspectable var borderWidth : CGFloat = 0.0 { didSet{ self.layer.borderWidth = borderWidth } } //color of Boder @IBInspectable var colorBorder : UIColor = UIColor.clear { didSet{ self.layer.borderColor = colorBorder.cgColor } } }
mit
cab0a4dea80f01eab975ad4150d9c022
21.354839
62
0.600289
4.149701
false
false
false
false
LiulietLee/Pick-Color
Pick Color/TutorialViewController.swift
1
2747
// // TutorialViewController.swift // Pick Color // // Created by Liuliet.Lee on 25/8/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit class TutorialViewController: UIViewController, UIPageViewControllerDataSource { fileprivate var pageController = UIPageViewController() fileprivate let gifs = [ UIImage.gif(name: "tut1"), UIImage.gif(name: "tut2"), UIImage.gif(name: "tut3"), UIImage.gif(name: "tut4") ] fileprivate let labels = [ tutorialStr1, tutorialStr2, tutorialStr3, tutorialStr4 ] override func viewDidLoad() { super.viewDidLoad() pageController = self.storyboard?.instantiateViewController(withIdentifier: "page") as! UIPageViewController pageController.dataSource = self let viewControllers = [viewControllerAt(index: 0)] pageController.setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil) let size = view.bounds.size pageController.view.frame = CGRect(x: 0, y: 20.0, width: size.width, height: size.height - 80.0) self.addChildViewController(pageController) view.addSubview(pageController.view) pageController.didMove(toParentViewController: self) } fileprivate func viewControllerAt(index: Int) -> TutorialContentViewController { if index >= gifs.count || index < 0 { return TutorialContentViewController() } let vc = self.storyboard?.instantiateViewController(withIdentifier: "content") as! TutorialContentViewController vc.index = index vc.gif = gifs[index]! vc.text = labels[index] return vc } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let vc = viewController as! TutorialContentViewController if vc.index == gifs.count - 1 { return nil } return viewControllerAt(index: vc.index + 1) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let vc = viewController as! TutorialContentViewController if vc.index == 0 { return nil } return viewControllerAt(index: vc.index - 1) } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return 0 } func presentationCount(for pageViewController: UIPageViewController) -> Int { return gifs.count } @IBAction func goBack() { self.dismiss(animated: true, completion: nil) } }
mit
4bd27bac0decf1d5ff2a1754e293f00f
34.205128
149
0.668609
5.104089
false
false
false
false
trivago/Heimdallr.swift
HeimdallrTests/OAuthAccessTokenKeychainStoreSpec.swift
3
5525
@testable import Heimdallr import Nimble import Quick class OAuthAccessTokenKeychainStoreSpec: QuickSpec { override func spec() { let accessToken = "01234567-89ab-cdef-0123-456789abcdef" let tokenType = "bearer" let expiresAt = Date(timeIntervalSince1970: 0) let refreshToken = "fedcba98-7654-3210-fedc-ba9876543210" var keychain = Keychain(service: "de.rheinfabrik.heimdallr.oauth.unit-tests") var store: OAuthAccessTokenKeychainStore! beforeEach { store = OAuthAccessTokenKeychainStore(service: "de.rheinfabrik.heimdallr.oauth.unit-tests") } // Since there is a bug with writing to the keychain within the iOS10 simulator we had to // disable some test until the bug is fixed by apple. Radar: https://openradar.appspot.com/27844971 xdescribe("func storeAccessToken(accessToken: OAuthAccessToken?)") { let token = OAuthAccessToken(accessToken: accessToken, tokenType: tokenType, expiresAt: expiresAt, refreshToken: refreshToken) it("stores the access token, token type, expiration date, and refresh token in the keychain") { store.storeAccessToken(token) expect(keychain["access_token"]).to(equal(accessToken)) expect(keychain["token_type"]).to(equal(tokenType)) expect(keychain["expires_at"]).to(equal(expiresAt.timeIntervalSince1970.description)) expect(keychain["refresh_token"]).to(equal(refreshToken)) } context("when the access token does not have an expiration date") { let tokenWithoutExpirationDate = OAuthAccessToken(accessToken: accessToken, tokenType: tokenType, expiresAt: nil, refreshToken: refreshToken) it("removes the expiration date from the keychain") { keychain["expires_at"] = expiresAt.description store.storeAccessToken(tokenWithoutExpirationDate) expect(keychain["expires_at"]).to(beNil()) } } context("when the access token does not have a refresh token") { let tokenWithoutRefreshToken = OAuthAccessToken(accessToken: accessToken, tokenType: tokenType, expiresAt: expiresAt, refreshToken: nil) it("removes the refresh token date from the keychain") { keychain["refresh_token"] = refreshToken store.storeAccessToken(tokenWithoutRefreshToken) expect(keychain["refresh_token"]).to(beNil()) } } context("when the access token is nil") { it("removes the access token, token type, expiration date, and refresh token from the keychain") { store.storeAccessToken(nil) expect(keychain["access_token"]).to(beNil()) expect(keychain["token_type"]).to(beNil()) expect(keychain["expires_at"]).to(beNil()) expect(keychain["refresh_token"]).to(beNil()) } } } xdescribe("func retrieveAccessToken() -> OAuthAccessToken?") { context("when the keychain contains an access token") { beforeEach { keychain["access_token"] = accessToken keychain["token_type"] = tokenType keychain["expires_at"] = expiresAt.timeIntervalSince1970.description keychain["refresh_token"] = refreshToken } it("retrieves and returns the access token from the keychain") { let token = store.retrieveAccessToken() expect(token).toNot(beNil()) expect(token?.accessToken).to(equal(accessToken)) expect(token?.tokenType).to(equal(tokenType)) expect(token?.expiresAt).to(equal(expiresAt)) expect(token?.refreshToken).to(equal(refreshToken)) } context("without an expiration date") { beforeEach { keychain["expires_at"] = nil } it("returns an access token without expiration date") { let token = store.retrieveAccessToken() expect(token).toNot(beNil()) expect(token?.expiresAt).to(beNil()) } } context("without a refresh token") { beforeEach { keychain["refresh_token"] = nil } it("returns an access token without refresh token") { let token = store.retrieveAccessToken() expect(token).toNot(beNil()) expect(token?.refreshToken).to(beNil()) } } } context("when the keychain does not contain an access token") { beforeEach { keychain["access_token"] = nil keychain["token_type"] = nil keychain["expires_at"] = nil keychain["refresh_token"] = nil } it("returns nil") { let token = store.retrieveAccessToken() expect(token).to(beNil()) } } } } }
apache-2.0
a037c529f9acfebf7b82633c93a3e538
43.918699
157
0.548054
5.55835
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/extensionVCMain.swift
1
9837
// // extensionsViewControllertabMain.swift // RsyncOSX // // Created by Thomas Evensen on 31.05.2018. // Copyright © 2018 Thomas Evensen. All rights reserved. // import Cocoa import Foundation // Get output from rsync command extension ViewControllerMain: GetOutput { // Get information from rsync output. func getoutput() -> [String] { return TrimTwo(outputprocess?.getOutput() ?? []).trimmeddata } } // Scheduled task are changed, read schedule again og redraw table extension ViewControllerMain: Reloadandrefresh { // Refresh tableView in main func reloadtabledata() { globalMainQueue.async { () in self.mainTableView.reloadData() } } } // Get index of selected row extension ViewControllerMain: GetSelecetedIndex { func getindex() -> Int? { return localindex } } // New profile is loaded. extension ViewControllerMain: NewProfile { // Function is called from profiles when new or default profiles is seleceted func newprofile(profile: String?, selectedindex: Int?) { if let index = selectedindex { profilepopupbutton.selectItem(at: index) } else { initpopupbutton() } reset() singletask = nil deselect() // Read configurations configurations = createconfigurationsobject(profile: profile) // Make sure loading profile displayProfile() reloadtabledata() } func reloadprofilepopupbutton() { globalMainQueue.async { () in self.displayProfile() } } func createconfigurationsobject(profile: String?) -> Configurations? { configurations = nil configurations = Configurations(profile: profile) return configurations } } // Check for remote connections, reload table when completed. extension ViewControllerMain: Connections { func displayConnections() { globalMainQueue.async { () in self.mainTableView.reloadData() } } } extension ViewControllerMain: NewVersionDiscovered { func notifyNewVersion() { globalMainQueue.async { () in self.info.stringValue = Infoexecute().info(num: 9) } } } extension ViewControllerMain: DismissViewController { func dismiss_view(viewcontroller: NSViewController) { dismiss(viewcontroller) globalMainQueue.async { () in self.mainTableView.reloadData() self.displayProfile() } } } // Deselect a row extension ViewControllerMain: DeselectRowTable { // deselect a row after row is deleted func deselect() { if let index = localindex { SharedReference.shared.process = nil localindex = nil mainTableView.deselectRow(index) } } } // If rsync throws any error extension ViewControllerMain: RsyncError { func rsyncerror() { // Set on or off in user configuration globalMainQueue.async { () in self.info.stringValue = "Rsync error, see logfile..." self.info.textColor = self.setcolor(nsviewcontroller: self, color: .red) self.info.isHidden = false guard SharedReference.shared.haltonerror == true else { return } self.deselect() _ = InterruptProcess() self.singletask?.error() } } } // If, for any reason, handling files or directory throws an error extension ViewControllerMain: ErrorMessage { func errormessage(errorstr: String, error errortype: RsyncOSXTypeErrors) { globalMainQueue.async { () in if errortype == .logfilesize { self.info.stringValue = "Reduce size logfile, filesize is: " + errorstr self.info.textColor = self.setcolor(nsviewcontroller: self, color: .red) self.info.isHidden = false } else { self.outputprocess?.addlinefromoutput(str: errorstr + "\n" + errorstr) self.info.stringValue = "Some error: see logfile." self.info.textColor = self.setcolor(nsviewcontroller: self, color: .red) self.info.isHidden = false } var message = [String]() message.append(errorstr) _ = Logfile(message, error: true) } } } // Abort task from progressview extension ViewControllerMain: Abort { // Abort the task func abortOperations() { _ = InterruptProcess() working.stopAnimation(nil) localindex = nil info.stringValue = "" } } // Extensions from here are used in newSingleTask extension ViewControllerMain: StartStopProgressIndicatorSingleTask { func startIndicatorExecuteTaskNow() { working.startAnimation(nil) } func startIndicator() { working.startAnimation(nil) } func stopIndicator() { working.stopAnimation(nil) } } extension ViewControllerMain: GetConfigurationsObject { func getconfigurationsobject() -> Configurations? { guard configurations != nil else { return nil } return configurations } } extension ViewControllerMain: ErrorOutput { func erroroutput() { info.stringValue = Infoexecute().info(num: 2) } } extension ViewControllerMain: SendOutputProcessreference { func sendoutputprocessreference(outputprocess: OutputfromProcess?) { self.outputprocess = outputprocess } } extension ViewControllerMain: OpenQuickBackup { func openquickbackup() { globalMainQueue.async { () in self.presentAsSheet(self.viewControllerQuickBackup!) } } } extension ViewControllerMain: Count { func maxCount() -> Int { return TrimTwo(outputprocess?.getOutput() ?? []).maxnumber } func inprogressCount() -> Int { return outputprocess?.getOutput()?.count ?? 0 } } extension ViewControllerMain: ViewOutputDetails { func getalloutput() -> [String] { return outputprocess?.getOutput() ?? [] } func reloadtable() { weak var localreloadDelegate: Reloadandrefresh? localreloadDelegate = SharedReference.shared.getvcref(viewcontroller: .vcalloutput) as? ViewControllerAllOutput localreloadDelegate?.reloadtabledata() } func appendnow() -> Bool { if SharedReference.shared.getvcref(viewcontroller: .vcalloutput) != nil { return true } else { return false } } func outputfromrsync(data: [String]?) { if outputprocess == nil { outputprocess = OutputfromProcess() } if let data = data { for i in 0 ..< data.count { outputprocess?.addlinefromoutput(str: data[i]) } } else { outputprocess?.output = [] } } } enum Color { case red case white case green case black } protocol Setcolor: AnyObject { func setcolor(nsviewcontroller: NSViewController, color: Color) -> NSColor } extension Setcolor { private func isDarkMode(view: NSView) -> Bool { return view.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua } func setcolor(nsviewcontroller: NSViewController, color: Color) -> NSColor { let darkmode = isDarkMode(view: nsviewcontroller.view) switch color { case .red: return .red case .white: if darkmode { return .white } else { return .black } case .green: if darkmode { return .green } else { return .blue } case .black: if darkmode { return .white } else { return .black } } } } protocol Checkforrsync: AnyObject { func checkforrsync() -> Bool } extension Checkforrsync { func checkforrsync() -> Bool { if SharedReference.shared.norsync == true { _ = Norsync() return true } else { return false } } } // Protocol for start,stop, complete progressviewindicator protocol StartStopProgressIndicator: AnyObject { func start() func stop() } // Protocol for either completion of work or update progress when Process discovers a // process termination and when filehandler discover data protocol UpdateProgress: AnyObject { func processTermination() func fileHandler() } protocol ViewOutputDetails: AnyObject { func reloadtable() func appendnow() -> Bool func getalloutput() -> [String] func outputfromrsync(data: [String]?) } // Get multiple selected indexes protocol GetMultipleSelectedIndexes: AnyObject { func getindexes() -> [Int] func multipleselection() -> Bool } extension ViewControllerMain: GetMultipleSelectedIndexes { func multipleselection() -> Bool { return multipeselection } func getindexes() -> [Int] { if let indexes = indexset { return indexes.map { $0 } } else { return [] } } } extension ViewControllerMain: DeinitExecuteTaskNow { func deinitexecutetasknow() { executetasknow = nil info.stringValue = Infoexecute().info(num: 0) } } extension ViewControllerMain: DisableEnablePopupSelectProfile { func enableselectpopupprofile() { profilepopupbutton.isEnabled = true } func disableselectpopupprofile() { profilepopupbutton.isEnabled = false } } extension ViewControllerMain: Sidebarbuttonactions { func sidebarbuttonactions(action: Sidebaractionsmessages) { switch action { case .Delete: delete() default: return } } }
mit
e3d51fe52602cb302fafb229d140bcc3
25.947945
119
0.622814
4.63525
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataEntry.swift
21
2134
// // PieChartDataEntry.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 PieChartDataEntry: ChartDataEntry { public required init() { super.init() } /// - parameter value: The value on the y-axis. /// - parameter label: The label for the x-axis /// - parameter data: Spot for additional data this Entry represents. public init(value: Double, label: String?, data: AnyObject?) { super.init(x: 0.0, y: value, data: data) self.label = label } /// - parameter value: The value on the y-axis. /// - parameter label: The label for the x-axis public convenience init(value: Double, label: String?) { self.init(value: value, label: label, data: nil) } /// - parameter value: The value on the y-axis. /// - parameter data: Spot for additional data this Entry represents. public convenience init(value: Double, data: AnyObject?) { self.init(value: value, label: nil, data: data) } /// - parameter value: The value on the y-axis. public convenience init(value: Double) { self.init(value: value, label: nil, data: nil) } // MARK: Data property accessors open var label: String? open var value: Double { get { return y } set { y = value } } @available(*, deprecated: 1.0, message: "Pie entries do not have x values") open override var x: Double { get { print("Pie entries do not have x values") return super.x } set { super.x = newValue print("Pie entries do not have x values") } } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! PieChartDataEntry copy.label = label return copy } }
mit
7e9d8245af2a50e0b68ab8c54214687f
24.105882
79
0.583411
4.225743
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/SessionUsernameProviderTests.swift
2
2089
// // SessionUsernameProviderTests.swift // edX // // Created by Akiva Leffert on 3/25/16. // Copyright © 2016 edX. All rights reserved. // import XCTest import edX class SessionUsernameProviderTests: XCTestCase { var user : OEXUserDetails! override func setUp() { super.setUp() user = OEXUserDetails.freshUser() } override func tearDown() { super.tearDown() let path = OEXFileUtility.t_pathForUserName(user.username!) try! NSFileManager.defaultManager().removeItemAtPath(path) } func providerForUsername(user : OEXUserDetails) -> SessionUsernameProvider { let storage = OEXMockCredentialStorage() storage.storedAccessToken = OEXAccessToken.fakeToken() storage.storedUserDetails = user let session = OEXSession(credentialStore: storage) session.loadTokenFromStore() let provider = SessionUsernameProvider(session: session) return provider } func testReturnsUserAppropriatePath() { let provider = providerForUsername(user) let path = provider.pathForRequestKey("123") XCTAssertTrue(path?.absoluteString?.containsString(user.username!.oex_md5) ?? false) } func testWorksWithResponseCache() { let provider = providerForUsername(user) let cache = PersistentResponseCache(provider: provider) let URL = NSURL(string:"http://example.com")! let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: nil, headerFields: nil)! let request = NSURLRequest(URL: URL) let responseData = ("test" as NSString).dataUsingEncoding(NSUTF8StringEncoding) cache.setCacheResponse(response, withData: responseData, forRequest: request) let expectation = expectationWithDescription("cache fulfilled") cache.fetchCacheEntryWithRequest(request) { (entry) -> Void in XCTAssertEqual(entry?.statusCode, 200) XCTAssertEqual(entry?.data, responseData) expectation.fulfill() } waitForExpectations() } }
apache-2.0
7a81b9563138bdb91348017d63a590a0
32.677419
105
0.68295
4.901408
false
true
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/HLHotelDetailsRatingDetailsCell.swift
1
4661
class HLHotelDetailsRatingDetailsCell: HLHotelDetailsColumnBaseCell { private static var cellInstance: HLHotelDetailsColumnBaseCell = { let views = Bundle.main.loadNibNamed("HLHotelDetailsRatingDetailsCell", owner: nil, options: nil) as! [UIView] return views.first! as! HLHotelDetailsColumnBaseCell }() @IBOutlet weak var moreButtonLeadingConstaint: NSLayoutConstraint! @IBOutlet weak var moreButton: UIButton! @IBOutlet weak var firstRatingView: UIView! @IBOutlet weak var firstScoreLabel: UILabel! @IBOutlet weak var secondRatingView: UIView! @IBOutlet weak var secondTitleLabel: UILabel! @IBOutlet weak var secondScoreLabel: UILabel! @IBOutlet weak var threeDotsImageView: UIImageView! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! @IBOutlet var betweenConstraint: NSLayoutConstraint! private var moreHandler: (() -> Void)? private var showMoreItem = false { didSet { updateCellStyle() } } class func estimatedHeight(_ first: Bool, last: Bool) -> CGFloat { var height: CGFloat = 41.0 height += first ? 6 : 0.0 height += last ? 15 : 0.0 return height } override var first: Bool { didSet { self.topConstraint.constant = self.first ? 15.0 : 5 self.setNeedsLayout() } } override var last: Bool { didSet { self.bottomConstraint.constant = self.last ? 15.0 : 7 self.setNeedsLayout() } } override func awakeFromNib() { super.awakeFromNib() firstScoreLabel.font = UIFont.systemFont(ofSize: 14.0) secondScoreLabel.font = UIFont.systemFont(ofSize: 14.0) moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 15.0, weight: UIFont.Weight.medium) firstRatingView.layer.cornerRadius = 15.0 firstRatingView.clipsToBounds = true secondRatingView.layer.cornerRadius = 15.0 secondRatingView.clipsToBounds = true } @IBAction func moreButtonTap(_ sender: Any) { moreHandler?() } func configureForRatingDetails(_ ratingDetailsItem: RatingItem) { self.firstTitleLabel.text = ratingDetailsItem.name self.firstRatingView.backgroundColor = JRColorScheme.ratingColor(ratingDetailsItem.score) self.firstScoreLabel.text = StringUtils.shortRatingString(ratingDetailsItem.score) showMoreItem = false self.columnCellStyle = .oneColumn } func configureForRatingDetailsPair(_ firstItem: RatingDetailItem, secondItem: RatingDetailItem?) { self.firstTitleLabel.text = firstItem.name self.firstRatingView.backgroundColor = JRColorScheme.ratingColor(firstItem.score) self.firstScoreLabel.text = StringUtils.shortRatingString(firstItem.score) self.secondTitleLabel.text = secondItem?.name self.secondRatingView.backgroundColor = JRColorScheme.ratingColor(secondItem?.score ?? 0) self.secondScoreLabel.text = StringUtils.shortRatingString(secondItem?.score ?? 0) self.secondScoreLabel.textColor = UIColor.white showMoreItem = false self.columnCellStyle = .twoColumns } func configureForMoreItem(_ moreItem: MoreRatingDetailsItem, columnCellStyle: HLHotelDetailsColumnCellStyle) { moreButton.setTitle(moreItem.name, for: .normal) moreHandler = moreItem.moreHandler showMoreItem = true self.columnCellStyle = columnCellStyle } override func updateCellStyle() { let shouldHideSecondColumn = columnCellStyle == .oneColumn || showMoreItem secondRatingView.isHidden = shouldHideSecondColumn secondTitleLabel.isHidden = shouldHideSecondColumn betweenConstraint.isActive = columnCellStyle != .oneColumn let shouldHideFirstColumn = columnCellStyle == .oneColumn && showMoreItem firstRatingView.isHidden = shouldHideFirstColumn firstTitleLabel.isHidden = shouldHideFirstColumn moreButton.isHidden = !showMoreItem contentView.removeConstraint(moreButtonLeadingConstaint) switch columnCellStyle { case .oneColumn: moreButtonLeadingConstaint = moreButton.autoPinEdge(.leading, to: .leading, of: firstRatingView) case .twoColumns: moreButtonLeadingConstaint = moreButton.autoPinEdge(.leading, to: .leading, of: secondRatingView) } setNeedsLayout() } override class func fakeCellInstance() -> HLHotelDetailsColumnBaseCell { return cellInstance } }
mit
774a7da3383f051a8513ab9dd1ce819f
35.700787
122
0.696417
4.9375
false
false
false
false
kreshikhin/scituner
SciTuner/ViewController.swift
1
857
// // ViewController.swift // oscituner // // Created by Denis Kreshikhin on 11.12.14. // Copyright (c) 2014 Denis Kreshikhin. All rights reserved. // import UIKit class ViewController: UINavigationController { var tunerViewController = TunerViewController() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Style.background pushViewController(tunerViewController, animated: false) UINavigationBar.appearance().tintColor = Style.text UINavigationBar.appearance().barTintColor = Style.background UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: Style.text] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9b46272e8d84f4201b68615207bae688
27.566667
103
0.70245
5.458599
false
false
false
false
tardieu/swift
test/Compatibility/protocol_composition.swift
10
2130
// RUN: rm -rf %t && mkdir -p %t // RUN: %utils/split_file.py -o %t %s // RUN: %target-swift-frontend -typecheck -primary-file %t/swift3.swift %t/common.swift -verify -swift-version 3 // RUN: %target-swift-frontend -typecheck -primary-file %t/swift4.swift %t/common.swift -verify -swift-version 4 // BEGIN common.swift protocol P1 { static func p1() -> Int } protocol P2 { static var p2: Int { get } } // BEGIN swift3.swift // Warning for mistakenly accepted protocol composition production. func foo(x: P1 & Any & P2.Type?) { // expected-warning @-1 {{protocol composition with postfix '.Type' is ambiguous and will be rejected in future version of Swift}} {{13-13=(}} {{26-26=)}} let _: (P1 & P2).Type? = x let _: (P1 & P2).Type = x! let _: Int = x!.p1() let _: Int? = x?.p2 } // Type expression func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-warning @-1 {{protocol composition with postfix '?' is ambiguous and will be rejected in future version of Swift}} {{12-12=(}} {{19-19=)}} return x } // Non-ident type at non-last position are rejected anyway. typealias A1 = P1.Type & P2 // expected-error {{type 'P1.Type' cannot be used within a protocol composition}} // BEGIN swift4.swift func foo(x: P1 & Any & P2.Type?) { // expected-error {{non-protocol type 'P2.Type?' cannot be used within a protocol composition}} let _: (P1 & P2).Type? = x // expected-error {{cannot convert value of type 'P1' to specified type '(P1 & P2).Type?'}} let _: (P1 & P2).Type = x! // expected-error {{cannot force unwrap value of non-optional type 'P1'}} let _: Int = x!.p1() // expected-error {{cannot force unwrap value of non-optional type 'P1'}} let _: Int? = x?.p2 // expected-error {{cannot use optional chaining on non-optional value of type 'P1'}} } func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-error {{non-protocol type 'P2?' cannot be used within a protocol composition}} return x // expected-error {{cannot convert return expression}} } typealias A1 = P1.Type & P2 // expected-error {{type 'P1.Type' cannot be used within a protocol composition}}
apache-2.0
59c047cff8cf617970b8a5eee08324cb
42.469388
156
0.658216
3.193403
false
false
false
false
remirobert/Dotzu-Objective-c
Pods/Dotzu/Dotzu/LogBadgeView.swift
3
1925
// // LogBadgeView.swift // exampleWindow // // Created by Remi Robert on 20/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class LogBadgeView: UILabel { private var count: Int = 0 private var obsResetBadge: NotificationObserver<Void>! private var obsRefreshLogs: NotificationObserver<Void>! override func sizeToFit() { super.sizeToFit() frame.size.width += 15 frame.size.height += 5 } private func initText() { textColor = UIColor.white textAlignment = .center font = UIFont.boldSystemFont(ofSize: 17) text = "\(count)" } private func initBadge() { backgroundColor = UIColor.red layer.cornerRadius = (bounds.size.height + 5) / 2 layer.masksToBounds = true isHidden = true initText() obsRefreshLogs = NotificationObserver(notification: LogNotificationApp.refreshLogs, block: { [weak self] _ in guard let weakSelf = self else { return } weakSelf.count += 1 DispatchQueue.main.async { weakSelf.updateText() } }) obsResetBadge = NotificationObserver(notification: LogNotificationApp.resetCountBadge, block: { [weak self] _ in guard let weakSelf = self else { return } weakSelf.count = 0 DispatchQueue.main.async { weakSelf.updateText() } }) } private func updateText() { if count == 0 { isHidden = true return } isHidden = false text = "\(count)" sizeToFit() layer.cornerRadius = frame.size.height / 2 } override init(frame: CGRect) { super.init(frame: frame) initBadge() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initBadge() } }
mit
6f3a694634e3640bf7ab6530e9af23fb
25
120
0.578482
4.681265
false
false
false
false
lwg123/swift_LWGWB
LWGWB/LWGWB/classes/Compose/PicPicker/PicPickerCollectionView.swift
1
1871
// // PicPickerCollectionView.swift // LWGWB // // Created by weiguang on 2017/5/4. // Copyright © 2017年 weiguang. All rights reserved. // import UIKit private let picPickerCell = "picPickerCell" private let margin: CGFloat = 15 class PicPickerCollectionView: UICollectionView { // 传递数据源过来,并进行监听,一旦发生改变就重新加载 var dataImages: [UIImage] = [UIImage]() { didSet { reloadData() } } override func awakeFromNib() { super.awakeFromNib() // 设置collectionView的layout let layout = collectionViewLayout as! UICollectionViewFlowLayout let itemH = (SCREEN_WIDTH - 4 * margin) / 3 layout.itemSize = CGSize(width: itemH, height: itemH) layout.minimumLineSpacing = margin layout.minimumInteritemSpacing = margin register(UINib.init(nibName: "PicPickerViewCell", bundle: nil), forCellWithReuseIdentifier: picPickerCell) dataSource = self // 设置内边距 contentInset = UIEdgeInsetsMake(margin, margin, 0, margin) } } extension PicPickerCollectionView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataImages.count + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picPickerCell, for: indexPath) as! PicPickerViewCell cell.backgroundColor = UIColor.red // 此处需判断一下,不然数组会越界 cell.image = indexPath.item <= dataImages.count - 1 ? dataImages[indexPath.item] : nil return cell } }
mit
a9bfbb0b578f79a19857adb34e50d3e0
28.533333
127
0.660271
4.922222
false
false
false
false
AlvinL33/TownHunt
TownHunt-1.1 (LoginScreen)/TownHunt/LoginPageViewController.swift
1
3853
// // LoginPageViewController.swift // TownHunt // // Created by Alvin Lee on 18/02/2017. // Copyright © 2017 LeeTech. All rights reserved. // import UIKit class LoginPageViewController: UIViewController { @IBOutlet weak var userEmailTextField: UITextField! @IBOutlet weak var userPasswordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "loginBackgroundImage")?.draw(in: self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginButtonTapped(_ sender: Any) { let userEmail = userEmailTextField.text let userPassword = userPasswordTextField.text if((userEmail?.isEmpty)! || (userPassword?.isEmpty)!) { //Display error message displayAlertMessage(alertTitle: "Data Entry Error", alertMessage: "All fields must be complete") return } //Sends data to be posted and receives a response let responseJSON = DatabaseInteraction().postToDatabase(apiName: "loginUser.php", postData: "userEmail=\(userEmail!)&userPassword=\(userPassword!)"){ (dbResponse: NSDictionary) in //If there is an error, the error is presented to the user var alertTitle = "ERROR" var alertMessage = "JSON File Invalid" var isAccountFound = false if dbResponse["error"]! as! Bool{ print("error: \(dbResponse["error"]!)") alertTitle = "ERROR" alertMessage = dbResponse["message"]! as! String } else if !(dbResponse["error"]! as! Bool){ alertTitle = "Thank You" alertMessage = "Successfully Logged In" isAccountFound = true let accountDetails = dbResponse["accountInfo"]! as! NSDictionary print(accountDetails["Email"] as! String) UserDefaults.standard.set(true, forKey: "isUserLoggedIn") UserDefaults.standard.set(accountDetails["UserID"]! as! String, forKey: "UserID") UserDefaults.standard.set(accountDetails["Username"]! as! String, forKey: "Username") UserDefaults.standard.set(accountDetails["Email"]! as! String, forKey: "UserEmail") UserDefaults.standard.synchronize() } else{ alertTitle = "ERROR" alertMessage = "JSON File Invalid" } DispatchQueue.main.async(execute: { let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in if isAccountFound{ self.dismiss(animated: true, completion: nil) }})) self.present(alertCon, animated: true, completion: nil) }) } } func displayAlertMessage(alertTitle: String, alertMessage: String){ let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertCon, animated: true, completion: nil) } }
apache-2.0
e5710db841232bc35d4c93013fc220fb
37.138614
187
0.588266
5.61516
false
false
false
false
lorentey/swift
stdlib/public/core/ErrorType.swift
12
8063
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// A type representing an error value that can be thrown. /// /// Any type that declares conformance to the `Error` protocol can be used to /// represent an error in Swift's error handling system. Because the `Error` /// protocol has no requirements of its own, you can declare conformance on /// any custom type you create. /// /// Using Enumerations as Errors /// ============================ /// /// Swift's enumerations are well suited to represent simple errors. Create an /// enumeration that conforms to the `Error` protocol with a case for each /// possible error. If there are additional details about the error that could /// be helpful for recovery, use associated values to include that /// information. /// /// The following example shows an `IntParsingError` enumeration that captures /// two different kinds of errors that can occur when parsing an integer from /// a string: overflow, where the value represented by the string is too large /// for the integer data type, and invalid input, where nonnumeric characters /// are found within the input. /// /// enum IntParsingError: Error { /// case overflow /// case invalidInput(Character) /// } /// /// The `invalidInput` case includes the invalid character as an associated /// value. /// /// The next code sample shows a possible extension to the `Int` type that /// parses the integer value of a `String` instance, throwing an error when /// there is a problem during parsing. /// /// extension Int { /// init(validating input: String) throws { /// // ... /// let c = _nextCharacter(from: input) /// if !_isValid(c) { /// throw IntParsingError.invalidInput(c) /// } /// // ... /// } /// } /// /// When calling the new `Int` initializer within a `do` statement, you can use /// pattern matching to match specific cases of your custom error type and /// access their associated values, as in the example below. /// /// do { /// let price = try Int(validating: "$100") /// } catch IntParsingError.invalidInput(let invalid) { /// print("Invalid character: '\(invalid)'") /// } catch IntParsingError.overflow { /// print("Overflow error") /// } catch { /// print("Other error") /// } /// // Prints "Invalid character: '$'" /// /// Including More Data in Errors /// ============================= /// /// Sometimes you may want different error states to include the same common /// data, such as the position in a file or some of your application's state. /// When you do, use a structure to represent errors. The following example /// uses a structure to represent an error when parsing an XML document, /// including the line and column numbers where the error occurred: /// /// struct XMLParsingError: Error { /// enum ErrorKind { /// case invalidCharacter /// case mismatchedTag /// case internalError /// } /// /// let line: Int /// let column: Int /// let kind: ErrorKind /// } /// /// func parse(_ source: String) throws -> XMLDoc { /// // ... /// throw XMLParsingError(line: 19, column: 5, kind: .mismatchedTag) /// // ... /// } /// /// Once again, use pattern matching to conditionally catch errors. Here's how /// you can catch any `XMLParsingError` errors thrown by the `parse(_:)` /// function: /// /// do { /// let xmlDoc = try parse(myXMLData) /// } catch let e as XMLParsingError { /// print("Parsing error: \(e.kind) [\(e.line):\(e.column)]") /// } catch { /// print("Other error: \(error)") /// } /// // Prints "Parsing error: mismatchedTag [19:5]" public protocol Error { var _domain: String { get } var _code: Int { get } // Note: _userInfo is always an NSDictionary, but we cannot use that type here // because the standard library cannot depend on Foundation. However, the // underscore implies that we control all implementations of this requirement. var _userInfo: AnyObject? { get } #if _runtime(_ObjC) func _getEmbeddedNSError() -> AnyObject? #endif } #if _runtime(_ObjC) extension Error { /// Default implementation: there is no embedded NSError. public func _getEmbeddedNSError() -> AnyObject? { return nil } } #endif #if _runtime(_ObjC) // Helper functions for the C++ runtime to have easy access to embedded error, // domain, code, and userInfo as Objective-C values. @_silgen_name("") internal func _getErrorDomainNSString<T: Error>(_ x: UnsafePointer<T>) -> AnyObject { return x.pointee._domain._bridgeToObjectiveCImpl() } @_silgen_name("") internal func _getErrorCode<T: Error>(_ x: UnsafePointer<T>) -> Int { return x.pointee._code } @_silgen_name("") internal func _getErrorUserInfoNSDictionary<T: Error>(_ x: UnsafePointer<T>) -> AnyObject? { return x.pointee._userInfo.map { $0 } } // Called by the casting machinery to extract an NSError from an Error value. @_silgen_name("") internal func _getErrorEmbeddedNSErrorIndirect<T: Error>( _ x: UnsafePointer<T>) -> AnyObject? { return x.pointee._getEmbeddedNSError() } /// Called by compiler-generated code to extract an NSError from an Error value. public // COMPILER_INTRINSIC func _getErrorEmbeddedNSError<T: Error>(_ x: T) -> AnyObject? { return x._getEmbeddedNSError() } /// Provided by the ErrorObject implementation. @_silgen_name("_swift_stdlib_getErrorDefaultUserInfo") internal func _getErrorDefaultUserInfo<T: Error>(_ error: T) -> AnyObject? /// Provided by the ErrorObject implementation. /// Called by the casting machinery and by the Foundation overlay. @_silgen_name("_swift_stdlib_bridgeErrorToNSError") public func _bridgeErrorToNSError(_ error: __owned Error) -> AnyObject #endif /// Invoked by the compiler when the subexpression of a `try!` expression /// throws an error. @_silgen_name("swift_unexpectedError") public func _unexpectedError( _ error: __owned Error, filenameStart: Builtin.RawPointer, filenameLength: Builtin.Word, filenameIsASCII: Builtin.Int1, line: Builtin.Word ) { preconditionFailure( "'try!' expression unexpectedly raised an error: \(String(reflecting: error))", file: StaticString( _start: filenameStart, utf8CodeUnitCount: filenameLength, isASCII: filenameIsASCII), line: UInt(line)) } /// Invoked by the compiler when code at top level throws an uncaught error. @_silgen_name("swift_errorInMain") public func _errorInMain(_ error: Error) { fatalError("Error raised at top level: \(String(reflecting: error))") } /// Runtime function to determine the default code for an Error-conforming type. /// Called by the Foundation overlay. @_silgen_name("_swift_stdlib_getDefaultErrorCode") public func _getDefaultErrorCode<T: Error>(_ error: T) -> Int extension Error { public var _code: Int { return _getDefaultErrorCode(self) } public var _domain: String { return String(reflecting: type(of: self)) } public var _userInfo: AnyObject? { #if _runtime(_ObjC) return _getErrorDefaultUserInfo(self) #else return nil #endif } } extension Error where Self: RawRepresentable, Self.RawValue: FixedWidthInteger { // The error code of Error with integral raw values is the raw value. public var _code: Int { if Self.RawValue.isSigned { return numericCast(self.rawValue) } let uintValue: UInt = numericCast(self.rawValue) return Int(bitPattern: uintValue) } }
apache-2.0
8092ad5b81f6e037a1e57a28b9922d41
33.165254
83
0.656331
4.275186
false
false
false
false
skutnii/4swivl
TestApp/TestApp/PeopleViewController+TableView.swift
1
2393
// // ViewController+TableView.swift // TestApp // // Created by Serge Kutny on 9/17/15. // Copyright © 2015 skutnii. All rights reserved. // import UIKit extension PeopleViewController : UITableViewDataSource, UITableViewDelegate, AvatarViewer { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return max(people.count, maxCells) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (indexPath.row == people.count - 1) { dispatch_async(dispatch_get_main_queue(), { [weak self] in self?.requestNextUsers() }) } guard indexPath.row < people.count else { let cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"Cell") cell.textLabel?.text = "Loading..." cell.textLabel?.textColor = UIColor.whiteColor() cell.contentView.backgroundColor = UIColor.blackColor() return cell } var cell : PersonCell? = tableView.dequeueReusableCellWithIdentifier("PersonCell") as? PersonCell if nil == cell { cell = PersonCell() } cell?.avatarViewDelegate = self let person = people[indexPath.row] cell?.person = person if nil == person.avatar.preview[] { Github.getAvatar(preview: true, forPerson: person) } return cell! } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110 } func viewAvatar(forPerson person: Person?) { contentOffset = tableView?.contentOffset ?? CGPointMake(0, 0) let viewer = AvatarController(nibName:"AvatarController", bundle:nil) viewer.person = person viewer.view.alpha = 0 presentViewController(viewer, animated: false, completion: { UIView.animateWithDuration(0.25, animations: { viewer.view.alpha = 1.0 }) }) } }
mit
4365f84650ccd882f4422a972859ee6f
32.690141
103
0.571906
5.375281
false
false
false
false
alblue/swift
stdlib/public/core/LazyCollection.swift
1
8142
//===--- LazyCollection.swift ---------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection on which normally-eager operations such as `map` and /// `filter` are implemented lazily. /// /// Please see `LazySequenceProtocol` for background; `LazyCollectionProtocol` /// is an analogous component, but for collections. /// /// To add new lazy collection operations, extend this protocol with /// methods that return lazy wrappers that are themselves /// `LazyCollectionProtocol`s. public protocol LazyCollectionProtocol: Collection, LazySequenceProtocol { /// A `Collection` that can contain the same elements as this one, /// possibly with a simpler type. /// /// - See also: `elements` associatedtype Elements : Collection = Self } extension LazyCollectionProtocol { // Lazy things are already lazy @inlinable // protocol-only public var lazy: LazyCollection<Elements> { return elements.lazy } } extension LazyCollectionProtocol where Elements: LazyCollectionProtocol { // Lazy things are already lazy @inlinable // protocol-only public var lazy: Elements { return elements } } /// A collection containing the same elements as a `Base` collection, /// but on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceProtocol`, `LazyCollection` @_fixed_layout public struct LazyCollection<Base : Collection> { /// Creates an instance with `base` as its underlying Collection /// instance. @inlinable internal init(_base: Base) { self._base = _base } @usableFromInline internal var _base: Base } extension LazyCollection: LazyCollectionProtocol { /// The type of the underlying collection. public typealias Elements = Base /// The underlying collection. @inlinable public var elements: Elements { return _base } } /// Forward implementations to the base collection, to pick up any /// optimizations it might implement. extension LazyCollection : Sequence { public typealias Iterator = Base.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public __consuming func makeIterator() -> Iterator { return _base.makeIterator() } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public var underestimatedCount: Int { return _base.underestimatedCount } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Base.Element> { return _base._copyToContiguousArray() } @inlinable public __consuming func _copyContents( initializing buf: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { return _base._copyContents(initializing: buf) } @inlinable public func _customContainsEquatableElement( _ element: Base.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } } extension LazyCollection : Collection { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Element = Base.Element public typealias Index = Base.Index public typealias Indices = Base.Indices /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable public var startIndex: Index { return _base.startIndex } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @inlinable public var endIndex: Index { return _base.endIndex } @inlinable public var indices: Indices { return _base.indices } // TODO: swift-3-indexing-model - add docs @inlinable public func index(after i: Index) -> Index { return _base.index(after: i) } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable public subscript(position: Index) -> Element { return _base[position] } /// A Boolean value indicating whether the collection is empty. @inlinable public var isEmpty: Bool { return _base.isEmpty } /// Returns the number of elements. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if `Self` conforms to `RandomAccessCollection`; /// O(*n*) otherwise. @inlinable public var count: Int { return _base.count } // The following requirement enables dispatching for firstIndex(of:) and // lastIndex(of:) when the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `Optional(nil)` if the element doesn't exist in the collection; /// `nil` if a search was not performed. /// /// - Complexity: Better than O(*n*) @inlinable public func _customIndexOfEquatableElement( _ element: Element ) -> Index?? { return _base._customIndexOfEquatableElement(element) } /// Returns `Optional(Optional(index))` if an element was found; /// `Optional(nil)` if the element doesn't exist in the collection; /// `nil` if a search was not performed. /// /// - Complexity: Better than O(*n*) @inlinable public func _customLastIndexOfEquatableElement( _ element: Element ) -> Index?? { return _base._customLastIndexOfEquatableElement(element) } // TODO: swift-3-indexing-model - add docs @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _base.index(i, offsetBy: n) } // TODO: swift-3-indexing-model - add docs @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _base.index(i, offsetBy: n, limitedBy: limit) } // TODO: swift-3-indexing-model - add docs @inlinable public func distance(from start: Index, to end: Index) -> Int { return _base.distance(from:start, to: end) } } extension LazyCollection : BidirectionalCollection where Base : BidirectionalCollection { @inlinable public func index(before i: Index) -> Index { return _base.index(before: i) } } extension LazyCollection : RandomAccessCollection where Base : RandomAccessCollection {} /// Augment `self` with lazy methods such as `map`, `filter`, etc. extension Collection { /// A view onto this collection that provides lazy implementations of /// normally eager operations, such as `map` and `filter`. /// /// Use the `lazy` property when chaining operations to prevent /// intermediate operations from allocating storage, or when you only /// need a part of the final collection to avoid unnecessary computation. @inlinable public var lazy: LazyCollection<Self> { return LazyCollection(_base: self) } } extension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { } extension Slice: LazyCollectionProtocol where Base: LazyCollectionProtocol { } extension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { } extension ReversedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol { }
apache-2.0
3ea764775eb63fca0cea55a2aeb03aa4
31.055118
91
0.697249
4.561345
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Settings/DeviceManagement/ClientTableViewCell.swift
1
7809
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import CoreLocation import Contacts import WireDataModel import WireCommonComponents class ClientTableViewCell: UITableViewCell, DynamicTypeCapable { // MARK: - Properties let nameLabel = DynamicFontLabel(fontSpec: .normalSemiboldFont, color: .textForeground) let labelLabel = DynamicFontLabel(fontSpec: .smallSemiboldFont, color: .textForeground) let activationLabel = UILabel(frame: CGRect.zero) let fingerprintLabel = UILabel(frame: CGRect.zero) let verifiedLabel = DynamicFontLabel(fontSpec: .smallFont, color: .textForeground) private let activationLabelFont = FontSpec.smallLightFont private let activationLabelDateFont = FontSpec.smallSemiboldFont var showVerified: Bool = false { didSet { updateVerifiedLabel() } } var showLabel: Bool = false { didSet { updateLabel() } } var fingerprintLabelFont: FontSpec? { didSet { updateFingerprint() } } var fingerprintLabelBoldFont: FontSpec? { didSet { updateFingerprint() } } var fingerprintTextColor: UIColor? { didSet { updateFingerprint() } } var userClient: UserClient? { didSet { guard let userClient = userClient else { return } if let userClientModel = userClient.model { nameLabel.text = userClientModel } else if userClient.isLegalHoldDevice { nameLabel.text = L10n.Localizable.Device.Class.legalhold } updateLabel() activationLabel.text = "" if let date = userClient.activationDate?.formattedDate { let text = L10n.Localizable.Registration.Devices.activated(date) var attrText = NSAttributedString(string: text) && activationLabelFont.font attrText = attrText.adding(font: activationLabelDateFont.font!, to: date) activationLabel.attributedText = attrText } updateFingerprint() updateVerifiedLabel() } } var wr_editable: Bool var variant: ColorSchemeVariant? // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { wr_editable = true super.init(style: style, reuseIdentifier: reuseIdentifier) createConstraints() setupStyle() } @available(*, unavailable) required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Override method override func setEditing(_ editing: Bool, animated: Bool) { if wr_editable { super.setEditing(editing, animated: animated) } } // MARK: - Methods func setupStyle() { nameLabel.accessibilityIdentifier = "device name" labelLabel.accessibilityIdentifier = "device label" activationLabel.accessibilityIdentifier = "device activation date" fingerprintLabel.accessibilityIdentifier = "device fingerprint" verifiedLabel.accessibilityIdentifier = "device verification status" activationLabel.numberOfLines = 0 backgroundColor = SemanticColors.View.backgroundUserCell fingerprintLabelFont = .smallLightFont fingerprintLabelBoldFont = .smallSemiboldFont let textColor = SemanticColors.Label.textDefault fingerprintTextColor = textColor [nameLabel, labelLabel, verifiedLabel, activationLabel].forEach { $0.textColor = textColor} addBorder(for: .bottom) } private func createConstraints() { [nameLabel, labelLabel, activationLabel, fingerprintLabel, verifiedLabel].forEach(contentView.addSubview) [nameLabel, labelLabel, activationLabel, fingerprintLabel, verifiedLabel].prepareForLayout() // Setting the constraints for the view NSLayoutConstraint.activate([ nameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16), nameLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), nameLabel.rightAnchor.constraint(lessThanOrEqualTo: contentView.rightAnchor, constant: -16), labelLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 2), labelLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), labelLabel.rightAnchor.constraint(lessThanOrEqualTo: contentView.rightAnchor, constant: -16), fingerprintLabel.topAnchor.constraint(equalTo: labelLabel.bottomAnchor, constant: 4), fingerprintLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), fingerprintLabel.rightAnchor.constraint(lessThanOrEqualTo: contentView.rightAnchor, constant: -16), fingerprintLabel.heightAnchor.constraint(equalToConstant: 16), activationLabel.topAnchor.constraint(equalTo: fingerprintLabel.bottomAnchor, constant: 8), activationLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), activationLabel.rightAnchor.constraint(lessThanOrEqualTo: contentView.rightAnchor, constant: -16), verifiedLabel.topAnchor.constraint(equalTo: activationLabel.bottomAnchor, constant: 4), verifiedLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16), verifiedLabel.rightAnchor.constraint(lessThanOrEqualTo: contentView.rightAnchor, constant: -16), verifiedLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16) ]) } private func updateVerifiedLabel() { if let userClient = userClient, showVerified { if userClient.verified { verifiedLabel.text = L10n.Localizable.Device.verified.capitalized } else { verifiedLabel.text = L10n.Localizable.Device.notVerified.capitalized } } else { verifiedLabel.text = "" } } private func updateFingerprint() { if let fingerprintLabelBoldMonoFont = fingerprintLabelBoldFont?.font?.monospaced(), let fingerprintLabelMonoFont = fingerprintLabelFont?.font?.monospaced(), let fingerprintLabelTextColor = fingerprintTextColor, let userClient = userClient, userClient.remoteIdentifier != nil { fingerprintLabel.attributedText = userClient.attributedRemoteIdentifier( [.font: fingerprintLabelMonoFont, .foregroundColor: fingerprintLabelTextColor], boldAttributes: [.font: fingerprintLabelBoldMonoFont, .foregroundColor: fingerprintLabelTextColor], uppercase: true ) } } private func updateLabel() { if let userClientLabel = userClient?.label, showLabel { labelLabel.text = userClientLabel } else { labelLabel.text = "" } } func redrawFont() { updateFingerprint() updateLabel() } }
gpl-3.0
b25db6c7a5900fe27bc4cb8bae1f33c3
37.092683
115
0.675375
5.255047
false
false
false
false
kreactive/JSONWebToken
JSONWebToken/ClaimValidator.swift
1
4724
// // JSONWebToken // // Created by Antoine Palazzolo on 20/11/15. // import Foundation public struct ClaimValidatorError : Error { public let message : String public init(message : String) { self.message = message } } public func ClaimTransformString(_ value : Any) throws -> String { if let result = value as? String { return result } else { throw ClaimValidatorError(message: "\(value) is not a String type value") } } public func ClaimTransformDate(_ value : Any) throws -> Date { return try Date(timeIntervalSince1970: ClaimTransformNumber(value).doubleValue) } public func ClaimTransformNumber(_ value : Any) throws -> NSNumber { if let numberValue = value as? NSNumber { return numberValue } else { throw ClaimValidatorError(message: "\(value) is not a Number type value") } } public func ClaimTransformArray<U>(_ elementTransform : (Any) throws -> U, value : Any) throws -> [U] { if let array = value as? NSArray { return try array.map(elementTransform) } else { throw ClaimValidatorError(message: "\(value) is not an Array type value") } } public struct ClaimValidator<T> : JSONWebTokenValidatorType { fileprivate var isOptional : Bool = false fileprivate var validator : (T) -> ValidationResult = {_ in return .success} public let key : String public let transform : (Any) throws -> T public init(key : String, transform : @escaping (Any) throws -> T) { self.key = key self.transform = transform } public init(claim : JSONWebToken.Payload.RegisteredClaim, transform : @escaping (Any) throws -> T) { self.init(key : claim.rawValue,transform : transform) } public func withValidator(_ validator : @escaping (T) -> ValidationResult) -> ClaimValidator<T> { var result = self result.validator = { input in let validationResult = self.validator(input) guard case ValidationResult.success = validationResult else { return validationResult } return validator(input) } return result } public func withValidator(_ validator : @escaping (T) -> Bool) -> ClaimValidator<T> { return self.withValidator { return validator($0) ? .success : .failure(ClaimValidatorError(message: "custom validation failed for key \(self.key)")) } } public var optional : ClaimValidator<T> { var result = self result.isOptional = true return result } public func validateToken(_ token : JSONWebToken) -> ValidationResult { guard let initialValue = token.payload[self.key] else { if self.isOptional { return .success } else { return .failure(ClaimValidatorError(message: "missing value for claim with key \(self.key)")) } } do { return try self.validator(self.transform(initialValue)) } catch { return .failure(error) } } } public struct RegisteredClaimValidator { public static let issuer = ClaimValidator(claim: .Issuer, transform: ClaimTransformString) public static let subject = ClaimValidator(claim: .Subject, transform: ClaimTransformString) public static let audience = ClaimValidator(claim: .Audience, transform: { value throws -> [String] in if let singleAudience = try? ClaimTransformString(value) { return [singleAudience] } else if let multiple = try? ClaimTransformArray(ClaimTransformString,value : value) { return multiple } else { throw ClaimValidatorError(message: "audience value \(value) is not an array or string value") } }) public static let expiration = ClaimValidator(claim: .ExpirationTime, transform: ClaimTransformDate).withValidator { date -> ValidationResult in if date.timeIntervalSinceNow >= 0.0 { return .success } else { return .failure(ClaimValidatorError(message: "token is expired")) } } public static let notBefore = ClaimValidator(claim: .NotBefore, transform: ClaimTransformDate).withValidator { date -> ValidationResult in if date.timeIntervalSinceNow <= 0.0 { return .success } else { return .failure(ClaimValidatorError(message: "token cannot be used before \(date)")) } } public static let issuedAt = ClaimValidator(claim: .IssuedAt, transform: ClaimTransformDate) public static let jwtIdentifier = ClaimValidator(claim: .JWTIdentifier, transform: ClaimTransformString) }
mit
71fb94a323ccb6f96758f88729e1fff6
35.338462
149
0.642676
4.645034
false
false
false
false
tiagomartinho/swift-corelibs-xctest
Sources/XCTest/Public/XCTestCase.swift
1
6177
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // // XCTestCase.swift // Base class for test cases // /// A block with the test code to be invoked when the test runs. /// /// - Parameter testCase: the test case associated with the current test code. public typealias XCTestCaseClosure = (XCTestCase) throws -> Void /// This is a compound type used by `XCTMain` to represent tests to run. It combines an /// `XCTestCase` subclass type with the list of test case methods to invoke on the class. /// This type is intended to be produced by the `testCase` helper function. /// - seealso: `testCase` /// - seealso: `XCTMain` public typealias XCTestCaseEntry = (testCaseClass: XCTestCase.Type, allTests: [(String, XCTestCaseClosure)]) // A global pointer to the currently running test case. This is required in // order for XCTAssert functions to report failures. internal var XCTCurrentTestCase: XCTestCase? /// An instance of this class represents an individual test case which can be /// run by the framework. This class is normally subclassed and extended with /// methods containing the tests to run. /// - seealso: `XCTMain` open class XCTestCase: XCTest { private let testClosure: XCTestCaseClosure /// The name of the test case, consisting of its class name and the method /// name it will run. open override var name: String { return _name } /// A private setter for the name of this test case. private var _name: String open override var testCaseCount: Int { return 1 } /// The set of expectations made upon this test case. internal var _allExpectations = [XCTestExpectation]() /// An internal object implementing performance measurements. internal var _performanceMeter: PerformanceMeter? open override var testRunClass: AnyClass? { return XCTestCaseRun.self } open override func perform(_ run: XCTestRun) { guard let testRun = run as? XCTestCaseRun else { fatalError("Wrong XCTestRun class.") } XCTCurrentTestCase = self testRun.start() invokeTest() failIfExpectationsNotWaitedFor(_allExpectations) testRun.stop() XCTCurrentTestCase = nil } /// The designated initializer for SwiftXCTest's XCTestCase. /// - Note: Like the designated initializer for Apple XCTest's XCTestCase, /// `-[XCTestCase initWithInvocation:]`, it's rare for anyone outside of /// XCTest itself to call this initializer. public required init(name: String, testClosure: @escaping XCTestCaseClosure) { _name = "\(type(of: self)).\(name)" self.testClosure = testClosure } /// Invoking a test performs its setUp, invocation, and tearDown. In /// general this should not be called directly. open func invokeTest() { setUp() do { try testClosure(self) } catch { recordFailure( withDescription: "threw error \"\(error)\"", inFile: "<EXPR>", atLine: 0, expected: false) } tearDown() } /// Records a failure in the execution of the test and is used by all test /// assertions. /// - Parameter description: The description of the failure being reported. /// - Parameter filePath: The file path to the source file where the failure /// being reported was encountered. /// - Parameter lineNumber: The line number in the source file at filePath /// where the failure being reported was encountered. /// - Parameter expected: `true` if the failure being reported was the /// result of a failed assertion, `false` if it was the result of an /// uncaught exception. open func recordFailure(withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool) { testRun?.recordFailure( withDescription: description, inFile: filePath, atLine: lineNumber, expected: expected) _performanceMeter?.abortMeasuring() // FIXME: Apple XCTest does not throw a fatal error and crash the test // process, it merely prevents the remainder of a testClosure // from executing after it's been determined that it has already // failed. The following behavior is incorrect. if !continueAfterFailure { tearDown() print("Terminating execution due to test failure") abort() } } /// Setup method called before the invocation of any test method in the /// class. open class func setUp() {} /// Teardown method called after the invocation of every test method in the /// class. open class func tearDown() {} open var continueAfterFailure = true } /// Wrapper function allowing an array of static test case methods to fit /// the signature required by `XCTMain` /// - seealso: `XCTMain` public func testCase<T: XCTestCase>(_ allTests: [(String, (T) -> () throws -> Void)]) -> XCTestCaseEntry { let tests: [(String, XCTestCaseClosure)] = allTests.map { ($0.0, test($0.1)) } return (T.self, tests) } /// Wrapper function for the non-throwing variant of tests. /// - seealso: `XCTMain` public func testCase<T: XCTestCase>(_ allTests: [(String, (T) -> () -> Void)]) -> XCTestCaseEntry { let tests: [(String, XCTestCaseClosure)] = allTests.map { ($0.0, test($0.1)) } return (T.self, tests) } private func test<T: XCTestCase>(_ testFunc: @escaping (T) -> () throws -> Void) -> XCTestCaseClosure { return { testCaseType in guard let testCase = testCaseType as? T else { fatalError("Attempt to invoke test on class \(T.self) with incompatible instance type \(type(of: testCaseType))") } try testFunc(testCase)() } }
apache-2.0
bcb3e05d38dd241b609b33adad4df6f6
37.36646
131
0.660677
4.708079
false
true
false
false
niekang/WeiBo
WeiBo/Class/Utils/Emotion/View/EmotionTipView.swift
1
2263
// // EmotionTipView.swift // WeiBo // // Created by 聂康 on 2017/6/29. // Copyright © 2017年 com.nk. All rights reserved. // import UIKit import pop class EmotionTipView: UIImageView { /// 之前选择的表情 private var preEmoticon: Emotion? /// 提示视图的表情模型 var emoticon: Emotion? { didSet { // 判断表情是否变化 if emoticon == preEmoticon { return } // 记录当前的表情 preEmoticon = emoticon // 设置表情数据 tipButton.setTitle(emoticon?.emoji, for: []) tipButton.setImage(emoticon?.image, for: []) // 表情的动画 - 弹力动画的结束时间是根据速度自动计算的,不需要也不能指定 duration let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) anim.fromValue = 30 anim.toValue = 8 anim.springBounciness = 20 anim.springSpeed = 20 tipButton.layer.pop_add(anim, forKey: nil) // print("设置表情...") } } // MARK: - 私有控件 private lazy var tipButton = UIButton() // MARK: - 构造函数 init() { let bundle = EmotionManager.shared.bundle let image = UIImage(named: "emoticon_keyboard_magnifier", in: bundle, compatibleWith: nil) // [[UIImageView alloc] initWithImage: image] => 会根据图像大小设置图像视图的大小! super.init(image: image) // 设置锚点 layer.anchorPoint = CGPoint(x: 0.5, y: 1.2) // 添加按钮 tipButton.layer.anchorPoint = CGPoint(x: 0.5, y: 0) tipButton.frame = CGRect(x: 0, y: 8, width: 36, height: 36) tipButton.center.x = bounds.width * 0.5 tipButton.setTitle("😄", for: []) tipButton.titleLabel?.font = UIFont.systemFont(ofSize: 32) addSubview(tipButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f149dc61ff68c07f84e36baa06f3b861
25.141026
98
0.528691
4.274633
false
false
false
false
Tornquist/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_06_Action+JavaScript_Begin/CocoaConf Photo Editing/PhotoEditingViewController.swift
4
4673
// // PhotoEditingViewController.swift // CocoaConf Photo Editing // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit import Photos import PhotosUI import CoreImage class PhotoEditingViewController: UIViewController, PHContentEditingController { @IBOutlet weak var imagePreview: UIImageView! @IBOutlet weak var pixellationScaleSlider: UISlider! var pixellateFilter: CIFilter! var input: PHContentEditingInput? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. pixellateFilter = CIFilter(name: "CIPixellate") pixellateFilter.setDefaults() updateFilteredPreview() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func updateFilteredPreview() { if var ciImage = CIImage(CGImage: input?.displaySizeImage.CGImage) { imagePreview.image = UIImage (CIImage: applyPixellateFilterToCIImage (ciImage)) } else { NSLog ("couldn't get CIImage") } } private func applyPixellateFilterToCIImage (ciImage: CIImage) -> CIImage { pixellateFilter.setValue(NSNumber (float: pixellationScaleSlider.value), forKey: "inputScale") pixellateFilter.setValue(ciImage, forKey: "inputImage") return pixellateFilter.outputImage } @IBAction func pixellationScaleSliderValueChanged(sender: AnyObject) { updateFilteredPreview() } // MARK: - PHContentEditingController func canHandleAdjustmentData(adjustmentData: PHAdjustmentData?) -> Bool { // Inspect the adjustmentData to determine whether your extension can work with past edits. // (Typically, you use its formatIdentifier and formatVersion properties to do this.) return false } func startContentEditingWithInput(contentEditingInput: PHContentEditingInput?, placeholderImage: UIImage) { // Present content for editing, and keep the contentEditingInput for use when closing the edit session. // If you returned YES from canHandleAdjustmentData:, contentEditingInput has the original image and adjustment data. // If you returned NO, the contentEditingInput has past edits "baked in". input = contentEditingInput imagePreview.image = input?.displaySizeImage updateFilteredPreview() } func finishContentEditingWithCompletionHandler(completionHandler: ((PHContentEditingOutput!) -> Void)!) { // Update UI to reflect that editing has finished and output is being rendered. // Render and provide output on a background queue. dispatch_async(dispatch_get_global_queue(CLong(DISPATCH_QUEUE_PRIORITY_DEFAULT), 0)) { // Create editing output from the editing input. let output = PHContentEditingOutput(contentEditingInput: self.input) // Provide new adjustments and render output to given location. // output.adjustmentData = <#new adjustment data#> // let renderedJPEGData = <#output JPEG#> // renderedJPEGData.writeToURL(output.renderedContentURL, atomically: true) let adjustmentDict = ["pixellateScale" : NSNumber(float: self.pixellationScaleSlider.value)] let adjustmentData = PHAdjustmentData (formatIdentifier: "CocoaConfPixellator", formatVersion: "1.0", data: NSKeyedArchiver.archivedDataWithRootObject(adjustmentDict)) output.adjustmentData = adjustmentData let fullCIImage = CIImage (contentsOfURL: self.input!.fullSizeImageURL) let fullFilteredImage = self.applyPixellateFilterToCIImage (fullCIImage) let myCIContext = CIContext (EAGLContext: EAGLContext (API: .OpenGLES2)) let myCGImage = myCIContext.createCGImage(fullFilteredImage, fromRect: fullFilteredImage.extent()) let myUIImage = UIImage(CGImage: myCGImage) let fullFilteredJPEG = UIImageJPEGRepresentation (myUIImage, 1.0) fullFilteredJPEG!.writeToURL(output.renderedContentURL, atomically: true) // Call completion handler to commit edit to Photos. completionHandler?(output) // Clean up temporary files, etc. } } var shouldShowCancelConfirmation: Bool { // Determines whether a confirmation to discard changes should be shown to the user on cancel. // (Typically, this should be "true" if there are any unsaved changes.) return false } func cancelContentEditing() { // Clean up temporary files, etc. // May be called after finishContentEditingWithCompletionHandler: while you prepare output. } }
cc0-1.0
627f7543352f6524790494c1a52fb90c
37.941667
125
0.727584
4.773238
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/User/UserAccountSettingsViews.swift
1
31568
// // Copyright (c) 2017 Google 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 MaterialComponents class UserAccountSettingsView: UIView { // This is nullable and gross because we don't control cell initialization // (the collection view does), but we'd like to inject this anyway. var settingsViewModel: SettingsViewModel? private struct Constants { static let labelTextColor = UIColor(red: 42 / 255, green: 42 / 255, blue: 42 / 255, alpha: 1) static let switchOnTintColor = UIColor(red: 82 / 255, green: 108 / 255, blue: 254 / 255, alpha: 1) static let switchTintColor = UIColor(red: 189 / 255, green: 189 / 255, blue: 189 / 255, alpha: 1) static let analyticsText = NSLocalizedString("Send anonymous usage statistics", comment: "Short description of the analytics setting. Text should not be too long or it will display incorrectly") static let eventTimesText = NSLocalizedString("Event times in Pacific time zone", comment: "Short description of the event times in pacific time setting. Text should not be too long or it will display incorrectly") static let notificationsText = NSLocalizedString("Enable notifications", comment: "Short description of the notifications setting. Text should not be too long or it will display incorrectly") static let labelFont = { () -> UIFont in return UIFont.preferredFont(forTextStyle: .subheadline) } // duplicated constraint code to calculate content size static let topInset: CGFloat = 20 static let interItemVerticalSpacing: CGFloat = 30 static let bottomInset: CGFloat = 20 } let eventTimesLabel = UILabel() let notificationsLabel = UILabel() let analyticsLabel = UILabel() let eventTimesSwitch = UISwitch() let notificationsSwitch = UISwitch() let analyticsSwitch = UISwitch() init(_ viewModel: SettingsViewModel) { super.init(frame: CGRect.zero) self.settingsViewModel = viewModel [eventTimesLabel, notificationsLabel, analyticsLabel].forEach { self.self.addSubview($0) } [eventTimesSwitch, notificationsSwitch, analyticsSwitch].forEach { self.self.addSubview($0) } setupLabels() setupSwitches() setupConstraints() backgroundColor = UIColor(hex: 0xf8f9fa) eventTimesSwitch.isOn = viewModel.shouldDisplayEventsInPDT notificationsSwitch.isOn = viewModel.isNotificationsEnabled analyticsSwitch.isOn = viewModel.isAnalyticsEnabled } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: UserAccountSettingsView.heightForContents()) } static func heightForContents() -> CGFloat { let textHeights = [ Constants.eventTimesText, Constants.notificationsText, Constants.analyticsText ].reduce(0 as CGFloat) { (result, string) -> CGFloat in return result + string.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: Constants.labelFont()], context: nil).size.height } return textHeights + Constants.topInset + Constants.bottomInset + Constants.interItemVerticalSpacing * 2 } func setupLabels() { [eventTimesLabel, notificationsLabel, analyticsLabel].forEach { label in label.translatesAutoresizingMaskIntoConstraints = false label.font = Constants.labelFont() label.numberOfLines = 1 label.textColor = Constants.labelTextColor // The accessibility label is on the switch control directly so VoiceOver reads them // as one unit. label.isAccessibilityElement = false } eventTimesLabel.text = Constants.eventTimesText notificationsLabel.text = Constants.notificationsText analyticsLabel.text = Constants.analyticsText } func setupSwitches() { [eventTimesSwitch, notificationsSwitch, analyticsSwitch].forEach { $0.translatesAutoresizingMaskIntoConstraints = false $0.onTintColor = Constants.switchOnTintColor $0.addTarget(self, action: #selector(didTapSwitch(_:)), for: .touchUpInside) } eventTimesSwitch.accessibilityLabel = Constants.eventTimesText notificationsSwitch.accessibilityLabel = Constants.notificationsText analyticsSwitch.accessibilityLabel = Constants.analyticsText } func setupConstraints() { var constraints: [NSLayoutConstraint] = [] // event times label top constraints.append(NSLayoutConstraint(item: eventTimesLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: Constants.topInset)) // event times label left constraints.append(NSLayoutConstraint(item: eventTimesLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 16)) // notifications label top constraints.append(NSLayoutConstraint(item: notificationsLabel, attribute: .top, relatedBy: .equal, toItem: eventTimesLabel, attribute: .bottom, multiplier: 1, constant: Constants.interItemVerticalSpacing)) // notifications label left constraints.append(NSLayoutConstraint(item: notificationsLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 16)) // analytics label top constraints.append(NSLayoutConstraint(item: analyticsLabel, attribute: .top, relatedBy: .equal, toItem: notificationsLabel, attribute: .bottom, multiplier: 1, constant: Constants.interItemVerticalSpacing)) // analytics label left constraints.append(NSLayoutConstraint(item: analyticsLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 16)) // event times switch centerY constraints.append(NSLayoutConstraint(item: eventTimesSwitch, attribute: .centerY, relatedBy: .equal, toItem: eventTimesLabel, attribute: .centerY, multiplier: 1, constant: 0)) // event times switch right constraints.append(NSLayoutConstraint(item: eventTimesSwitch, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -16)) // notifications switch centerY constraints.append(NSLayoutConstraint(item: notificationsSwitch, attribute: .centerY, relatedBy: .equal, toItem: notificationsLabel, attribute: .centerY, multiplier: 1, constant: 0)) // notifications switch right constraints.append(NSLayoutConstraint(item: notificationsSwitch, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -16)) // analytics switch centerY constraints.append(NSLayoutConstraint(item: analyticsSwitch, attribute: .centerY, relatedBy: .equal, toItem: analyticsLabel, attribute: .centerY, multiplier: 1, constant: 0)) // analytics switch right constraints.append(NSLayoutConstraint(item: analyticsSwitch, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -16)) self.addConstraints(constraints) } @objc func didTapSwitch(_ anySender: Any) { guard let sender = anySender as? UISwitch else { return } guard let viewModel = settingsViewModel else { return } switch sender { case eventTimesSwitch: viewModel.toggleEventsInPacificTime() case notificationsSwitch: viewModel.toggleNotificationsEnabled() // App doesn't have the permissions to display notifications, even though we can // still receive them through FCM. Deep link to Settings.app here so user can change // permissions easily. if !viewModel.hasNotificationPermissions && viewModel.isNotificationsEnabled { viewModel.presentSettingsDeepLinkAlert { _ in viewModel.isNotificationsEnabled = false self.notificationsSwitch.setOn(false, animated: true) } } case analyticsSwitch: viewModel.toggleAnalyticsEnabled() case _: return } } override func layoutSubviews() { super.layoutSubviews() let font = Constants.labelFont() if font.pointSize != analyticsLabel.font.pointSize { eventTimesLabel.font = font notificationsLabel.font = font analyticsLabel.font = font } notificationsSwitch.isOn = settingsViewModel?.isNotificationsEnabled ?? false } @available(*, unavailable) required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported for cell of type \(WifiInfoCollectionViewCell.self)") } } class UserAccountSettingsBuiltWithView: UIView { private struct Constants { static let builtText = "Built with" static let materialComponentsText = "Material Components" } let builtWith: UILabel = { let builtWith = UILabel() builtWith.translatesAutoresizingMaskIntoConstraints = false builtWith.text = Constants.builtText builtWith.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .subheadline) builtWith.enableAdjustFontForContentSizeCategory() builtWith.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity()) builtWith.textAlignment = .left return builtWith }() let logo: MDCLogo = { let logo = MDCLogo() logo.translatesAutoresizingMaskIntoConstraints = false return logo }() let materialComponents: UILabel = { let materialComponents = UILabel() materialComponents.translatesAutoresizingMaskIntoConstraints = false materialComponents.text = Constants.materialComponentsText materialComponents.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .headline) materialComponents.enableAdjustFontForContentSizeCategory() materialComponents.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity()) materialComponents.textAlignment = .left materialComponents.adjustsFontSizeToFitWidth = true return materialComponents }() class MDCLogo: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) drawLogo(frame: rect) } func drawLogo(frame: CGRect) { // Generated code. Do not alter by hand. // This non-generic function dramatically improves compilation times of complex expressions. func fastFloor(_ x: CGFloat) -> CGFloat { return floor(x) } let black = UIColor(red: 0.129, green: 0.129, blue: 0.129, alpha: 1.000) let lightGreen = UIColor(red: 0.698, green: 1.000, blue: 0.349, alpha: 1.000) let mediumGreen = UIColor(red: 0.000, green: 0.902, blue: 0.463, alpha: 1.000) let mDCGroup: CGRect = CGRect(x: frame.minX + 2, y: frame.minY + 2, width: fastFloor((frame.width - 2) * 0.97959 + 0.5), height: fastFloor((frame.height - 2) * 0.97959 + 0.5)) let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: mDCGroup.minX + 0.00000 * mDCGroup.width, y: mDCGroup.minY + 0.66667 * mDCGroup.height)) bezierPath.addLine(to: CGPoint(x: mDCGroup.minX + 0.33333 * mDCGroup.width, y: mDCGroup.minY + 0.66667 * mDCGroup.height)) bezierPath.addLine(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.33333 * mDCGroup.height)) bezierPath.addLine(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.00000 * mDCGroup.height)) bezierPath.addLine(to: CGPoint(x: mDCGroup.minX + 0.00000 * mDCGroup.width, y: mDCGroup.minY + 0.00000 * mDCGroup.height)) bezierPath.addLine(to: CGPoint(x: mDCGroup.minX + 0.00000 * mDCGroup.width, y: mDCGroup.minY + 0.66667 * mDCGroup.height)) bezierPath.close() black.setFill() bezierPath.fill() let ovalPath = UIBezierPath(ovalIn: CGRect(x: mDCGroup.minX + fastFloor(mDCGroup.width * 0.33333 + 0.5), y: mDCGroup.minY + fastFloor(mDCGroup.height * 0.33333 + 0.5), width: fastFloor(mDCGroup.width * 1.00000 + 0.5) - fastFloor(mDCGroup.width * 0.33333 + 0.5), height: fastFloor(mDCGroup.height * 1.00000 + 0.5) - fastFloor(mDCGroup.height * 0.33333 + 0.5))) lightGreen.setFill() ovalPath.fill() let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.33333 * mDCGroup.height)) bezier2Path.addLine(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.33333 * mDCGroup.height)) bezier2Path.addCurve(to: CGPoint(x: mDCGroup.minX + 0.33333 * mDCGroup.width, y: mDCGroup.minY + 0.66667 * mDCGroup.height), controlPoint1: CGPoint(x: mDCGroup.minX + 0.48257 * mDCGroup.width, y: mDCGroup.minY + 0.33333 * mDCGroup.height), controlPoint2: CGPoint(x: mDCGroup.minX + 0.33333 * mDCGroup.width, y: mDCGroup.minY + 0.48257 * mDCGroup.height)) bezier2Path.addLine(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.66667 * mDCGroup.height)) bezier2Path.addLine(to: CGPoint(x: mDCGroup.minX + 0.66667 * mDCGroup.width, y: mDCGroup.minY + 0.33333 * mDCGroup.height)) bezier2Path.close() mediumGreen.setFill() bezier2Path.fill() } } override init(frame: CGRect) { super.init(frame: frame) setupLayout() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupLayout() { self.addSubview(logo) self.addSubview(builtWith) self.addSubview(materialComponents) NSLayoutConstraint(item: logo, attribute: .width, relatedBy: .equal, toItem: logo, attribute: .height, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: logo, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60).isActive = true NSLayoutConstraint(item: logo, attribute: .centerY, relatedBy: .equal, toItem: logo.superview, attribute: .centerY, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: logo, attribute: .leading, relatedBy: .equal, toItem: logo.superview, attribute: .leading, multiplier: 1, constant: 20).isActive = true NSLayoutConstraint(item: builtWith, attribute: .leading, relatedBy: .equal, toItem: logo, attribute: .trailing, multiplier: 1, constant: 15).isActive = true NSLayoutConstraint(item: materialComponents, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: materialComponents.superview, attribute: .trailing, multiplier: 1, constant: -16).isActive = true NSLayoutConstraint(item: materialComponents, attribute: .leading, relatedBy: .equal, toItem: logo, attribute: .trailing, multiplier: 1, constant: 15).isActive = true NSLayoutConstraint(item: builtWith, attribute: .top, relatedBy: .equal, toItem: builtWith.superview, attribute: .top, multiplier: 1, constant: 24).isActive = true NSLayoutConstraint(item: materialComponents, attribute: .top, relatedBy: .equal, toItem: builtWith, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } static func heightForContents() -> CGFloat { return 100 } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: UserAccountSettingsBuiltWithView.heightForContents()) } } protocol UserAccountSettingsInfoViewDelegate: NSObjectProtocol { func didTapOpenSourceLicenses(view: UIView) } class UserAccountSettingsInfoView: UIView { weak var delegate: UserAccountSettingsInfoViewDelegate? fileprivate struct Constants { static let contents = NSLocalizedString("<p><a href='https://www.google.com/policies/terms/'>Terms of Service</a><br /><a href='https://www.google.com/policies/privacy/'>Privacy Policy</a><br /><a href='\(Constants.acknowledgementsURL.absoluteString)'>Open Source Licenses</a></p><p>Version \(Constants.versionString), Build \(Constants.buildString)<p/>", comment: "Localized HTML listing Terms of Service, Open Source Licenses, and version number") static let font = { () -> UIFont in return UIFont.preferredFont(forTextStyle: .body) } // We don't have an official url scheme, but the app knows how to open this url. // This exists so we can insert these urls into attributed strings in our app // and link to them without having to make special method calls. static let acknowledgementsURL: URL = URL(string: "iosched://acknowledgements")! static let versionString: String = { () -> String in // Failing to fetch the version from the info plist is a programmer error (my error) and // should never happen, but doesn't seem like big enough an issue warrant a fatalError. let unknownVersion = "999.0.0" let version = Bundle.main.url(forResource: "Info", withExtension: "plist").flatMap { return NSDictionary(contentsOf: $0) as? [String: Any] } .flatMap { return $0["CFBundleShortVersionString"] as? String } ?? unknownVersion return version }() static let buildString: String = { () -> String in // Failing to fetch the version from the info plist is a programmer error (my error) and // should never happen, but doesn't seem like big enough an issue warrant a fatalError. let unknownBuild = "42" let build = Bundle.main.url(forResource: "Info", withExtension: "plist").flatMap { return NSDictionary(contentsOf: $0) as? [String: Any] } .flatMap { return $0["CFBundleVersion"] as? String } ?? unknownBuild return build }() static let linkColor = UIColor(red: 61 / 255, green: 90 / 255, blue: 254 / 255, alpha: 1) } let textView = UITextView() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(textView) setupTextView() setupConstraints() } private func setupTextView() { textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false textView.isEditable = false textView.attributedText = InfoDetailView.attributedText(forDetailText: Constants.contents) textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsets(top: 24, left: 16, bottom: 24, right: 16) textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: Constants.linkColor] textView.font = Constants.font() textView.delegate = self } private func setupConstraints() { var constraints: [NSLayoutConstraint] = [] // text view top constraints.append(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) // text view left constraints.append(NSLayoutConstraint(item: textView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) // text view right constraints.append(NSLayoutConstraint(item: textView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) // text view bottom constraints.append(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraints(constraints) } static func heightForContents(maxWidth: CGFloat) -> CGFloat { return InfoDetailView.height(forDetailText: Constants.contents, maxWidth: maxWidth) } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: UserAccountSettingsInfoView.heightForContents( maxWidth: min(superview!.frame.width, superview!.frame.height))) } override func layoutSubviews() { super.layoutSubviews() // Support dynamic type let font = Constants.font() if font.pointSize != textView.font?.pointSize { textView.font = font } } @available(*, unavailable) required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported for cell of type \(WifiInfoCollectionViewCell.self)") } } extension UserAccountSettingsInfoView: UITextViewDelegate { @available(iOS 10.0, *) func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { if url == Constants.acknowledgementsURL { if let delegate = delegate { delegate.didTapOpenSourceLicenses(view: textView) } return false } return true } @available(iOS, deprecated: 10.0) func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool { if url == Constants.acknowledgementsURL { if let delegate = delegate { delegate.didTapOpenSourceLicenses(view: textView) } return false } return true } } class ManageYourGoogleAccountButtonContainer: UIView { var isEnabled: Bool { get { return manageYourAccountButton.isEnabled } set { manageYourAccountButton.isEnabled = newValue manageYourAccountButton.isHidden = !newValue removeConstraints(constraints) if newValue { heightConstraint.isActive = false setupConstraints() } else { heightConstraint.isActive = true } setNeedsLayout() } } private let manageYourAccountButton: MDCButton = { let button = MDCFlatButton() button.translatesAutoresizingMaskIntoConstraints = false let font = UIFont.preferredFont(forTextStyle: .caption1) button.setTitleFont(font, for: .normal) let title = NSLocalizedString("Manage your Google account", comment: "Button text. Tapping the button navigates users to an account management screen.") button.setTitle(title, for: .normal) let titleColor = UIColor(red: 32 / 255, green: 33 / 255, blue: 36 / 255, alpha: 1) button.setTitleColor(titleColor, for: .normal) button.titleLabel?.numberOfLines = 0 button.addTarget(self, action: #selector(manageAccountButtonTapped(_:)), for: .touchUpInside) button.addTarget(self, action: #selector(buttonTapCanceled(_:)), for: .touchCancel) button.isUppercaseTitle = false return button }() override init(frame: CGRect) { super.init(frame: frame) addSubview(manageYourAccountButton) setupConstraints() } override var intrinsicContentSize: CGSize { let buttonSize = manageYourAccountButton.intrinsicContentSize return CGSize(width: buttonSize.width + 32, height: buttonSize.height + 4) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() manageYourAccountButton.layer.cornerRadius = manageYourAccountButton.frame.size.height / 2 manageYourAccountButton.titleLabel?.preferredMaxLayoutWidth = manageYourAccountButton.titleLabel?.frame.size.width ?? 0 manageYourAccountButton.layer.borderColor = UIColor(red: 218 / 255, green: 220 / 255, blue: 224 / 255, alpha: 1).cgColor manageYourAccountButton.layer.borderWidth = 1 super.layoutSubviews() } @objc private func manageAccountButtonTapped(_ sender: Any) { guard let url = URL(string: "https://myaccount.google.com/") else { return } UIApplication.shared.openURL(url) } @objc private func buttonTapCanceled(_ sender: Any) { setNeedsLayout() } private func setupConstraints() { let constraints = [ NSLayoutConstraint(item: manageYourAccountButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 2), NSLayoutConstraint(item: manageYourAccountButton, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .leading, multiplier: 1, constant: 16), NSLayoutConstraint(item: manageYourAccountButton, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: self, attribute: .trailing, multiplier: 1, constant: -16), NSLayoutConstraint(item: manageYourAccountButton, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: manageYourAccountButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 2) ] addConstraints(constraints) } private lazy var heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) }
apache-2.0
393fff0b895f6712c0dd951964ca418a
40.922975
453
0.571116
5.362324
false
false
false
false
LGKKTeam/FlagKits
FlagKits/Classes/FKFlagHolderView.swift
1
4244
// // FKFlagHolderView.swift // FlagKits // // Created by Nguyen Minh on 4/3/17. // Copyright © 2017 LGKKTeam. All rights reserved. // import UIKit import Reusable public protocol FKFlagHolderDelegate: class { func countryPhoneShouldReturn() -> Bool } open class FKFlagHolderView: UIView, NibOwnerLoadable { @IBOutlet fileprivate weak var btnFlag: UIButton! @IBOutlet fileprivate weak var lblPhoneCode: UILabel! @IBOutlet fileprivate weak var tfPhone: UITextField! open var backgroundPickerColor: UIColor? = .white open weak var delegate: FKFlagHolderDelegate? fileprivate var hiddenTfChooseCountry: UITextField? open var phoneCode: String? = "+1" // US default open var phone: String? { return tfPhone.text } open var fullPhone: String? { if let phoneCode = phoneCode, let text = tfPhone.text { return "\(phoneCode)\(text)" } else { return nil } } public override init(frame: CGRect) { super.init(frame: frame) self.loadNibContent() setUI() } init() { let rect = CGRect(x: 0, y: 0, width: 100, height: 30) super.init(frame: rect) self.loadNibContent() setUI() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.loadNibContent() setUI() } override open func becomeFirstResponder() -> Bool { return tfPhone.becomeFirstResponder() } func setUI() { backgroundColor = .clear tfPhone.delegate = self tfPhone.placeholder = "Phone number" tfPhone.keyboardType = .phonePad phoneCode = "+1" setFlag(with: "us") } fileprivate func setFlag(with code: String) { if let flagSheet = FKIcons.sharedInstance.spriteSheet { let image = flagSheet.getImageFor(code) btnFlag.setImage(image, for: .normal) } } @IBAction func btnFlag_Tapped(_ sender: Any) { endEditing(true) let screenWidth = UIScreen.main.bounds.width let countryPicker = FKFKCountryPicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 260)) countryPicker.backgroundColor = backgroundPickerColor countryPicker.countryPhoneCodeDelegate = self countryPicker.setCountry(code: "us") // Trick: hiddenTfChooseCountry = UITextField() hiddenTfChooseCountry?.delegate = self if let hiddenTfChooseCountry = hiddenTfChooseCountry { addSubview(hiddenTfChooseCountry) } hiddenTfChooseCountry?.inputView = countryPicker hiddenTfChooseCountry?.becomeFirstResponder() } fileprivate func removeHiddenTf() { hiddenTfChooseCountry?.removeFromSuperview() hiddenTfChooseCountry = nil } } // MARK: - Country picker delegate extension FKFlagHolderView: FKCountryPickerDelegate { func countryPhoneCodePicker(picker: FKFKCountryPicker, didSelectCountryCountryWithName name: String, countryCode: String, phoneCode: String) { setFlag(with: countryCode) self.phoneCode = phoneCode lblPhoneCode.text = phoneCode } } // MARK: - UITextFieldDelegate extension FKFlagHolderView: UITextFieldDelegate { // Pair becomeFirstResponder & countryPhoneShouldReturn public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let delegate = delegate, textField == tfPhone { return delegate.countryPhoneShouldReturn() } return true } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == tfPhone, let text = textField.text { return text.characters.count + (string.characters.count - range.length) <= 15 } return true } public func textFieldDidEndEditing(_ textField: UITextField) { removeHiddenTf() } }
mit
32c50b6c95864037f72a5bdebd6bb448
29.092199
105
0.619609
4.871412
false
false
false
false
nohana/NohanaImagePicker
NohanaImagePicker/MomentInfoSectionCreater.swift
1
3482
/* * Copyright (C) 2021 nohana, 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 &quot;AS IS&quot; 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 Photos final class MomentInfoSectionCreater { func createSections(mediaType: MediaType) -> [MomentInfoSection] { if case .video = mediaType { fatalError("not supported .Video and .Any yet") } var momentInfoSectionList = [MomentInfoSection]() let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .none let allPhotosOptions = PHFetchOptions() allPhotosOptions.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.image.rawValue) allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let fetchAssetlist = PHAsset.fetchAssets(with: allPhotosOptions) // MEMO: run faster create temp list than reference creationDate of fetchAssetlist. var creationDateList = [Date]() var dateList = [String]() for index in 0..<fetchAssetlist.count { if let creationDate = fetchAssetlist[index].creationDate { let formattedDate = formatter.string(from: creationDate) if !dateList.contains(formattedDate) { dateList.append(formattedDate) creationDateList.append(creationDate) if let section = fetchInfoSection(date: creationDate, fetchOptions: allPhotosOptions) { momentInfoSectionList.append(section) } } } } return momentInfoSectionList } private func fetchInfoSection(date: Date, fetchOptions: PHFetchOptions) -> MomentInfoSection? { if let startDate = createDate(forDay: date, forHour: 0, forMinute: 0, forSecond: 0), let endDate = createDate(forDay: date, forHour: 23, forMinute: 59, forSecond: 59) { fetchOptions.predicate = NSPredicate(format: "creationDate => %@ AND creationDate < %@ && mediaType == %ld", startDate as NSDate, endDate as NSDate, PHAssetMediaType.image.rawValue) let assetsPhotoFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) return MomentInfoSection(creationDate: date, assetResult: assetsPhotoFetchResult) } return nil } private func createDate(forDay date: Date, forHour hour: Int, forMinute minute: Int, forSecond second: Int) -> Date? { var dateComponents = DateComponents() let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let tempDate = calendar.dateComponents(in: TimeZone.current, from: date) dateComponents.day = tempDate.day dateComponents.month = tempDate.month dateComponents.year = tempDate.year dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = second return calendar.date(from: dateComponents) } }
apache-2.0
323c2f8bd510c84819c53f26219a39cd
47.361111
193
0.67174
4.897328
false
false
false
false
KrishMunot/swift
test/Interpreter/SDK/CALayer.swift
1
1027
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // <rdar://problem/17014037> // REQUIRES: OS=macosx import QuartzCore class Canary: NSObject { deinit { print("died") } } var CanaryAssocObjectHandle: UInt8 = 0 // Attach an associated object with a loud deinit so we can see that the // error died. func hangCanary(_ o: AnyObject) { objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } class FooLayer: CALayer { var black: CGColor var white: CGColor = CGColor.constantColorForName(kCGColorWhite)! override init() { black = CGColor.constantColorForName(kCGColorBlack)! super.init() hangCanary(self) } required init?(coder: NSCoder) { black = coder.decodeObject(forKey: "black") as! CGColor super.init(coder: coder) } override var description: String { return "FooLayer" } } if true { let layer = FooLayer() print("\(layer)") } // CHECK: FooLayer // CHECK: died
apache-2.0
fd5d6a87224430959f635f94d034cfaa
19.959184
72
0.676728
3.694245
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Tools/Time Zone/Views/TimeZoneSearchHeaderView.swift
1
1800
import UIKit final class TimeZoneSearchHeaderView: UIView { @IBOutlet private weak var searchWrapperView: SearchWrapperView! @IBOutlet private weak var searchWrapperViewHeightConstraint: NSLayoutConstraint! @IBOutlet private weak var suggestionLabel: UILabel! @IBOutlet private weak var suggestionButton: UIButton! /// Callback called when the button is tapped var tapped: (() -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } class func makeFromNib(searchBar: UISearchBar, timezone: String) -> TimeZoneSearchHeaderView? { guard let view = Bundle.main.loadNibNamed(Constants.nibIdentifier, owner: self, options: nil)?.first as? TimeZoneSearchHeaderView else { assertionFailure("Failed to load view from nib named \(Constants.nibIdentifier)") return nil } view.searchWrapperView.addSubview(searchBar) view.searchWrapperViewHeightConstraint.constant = searchBar.frame.height view.suggestionLabel.text = Localization.suggestion view.suggestionButton.setTitle(timezone, for: .normal) view.suggestionButton.addTarget(view, action: #selector(buttonTapped), for: .touchUpInside) return view } @objc private func buttonTapped() { tapped?() } } // MARK: - Constants private extension TimeZoneSearchHeaderView { enum Constants { static let nibIdentifier = "TimeZoneSearchHeaderView" } enum Localization { static let suggestion = NSLocalizedString("Suggestion:", comment: "Label displayed to the user left of the time zone suggestion button") } }
gpl-2.0
478baeecdee3c1f068e5855e159da1c5
30.578947
129
0.658333
5.572755
false
false
false
false
IGRSoft/IGRPhotoTweaks
IGRPhotoTweaks/PhotoTweakView/CropView/IGRCropView+AspectRatio.swift
1
1306
// // IGRCropView+AspectRatio.swift // Pods // // Created by Vitalii Parovishnyk on 4/26/17. // // import Foundation extension IGRCropView { public func resetAspectRect() { self.aspectRatioWidth = self.frame.size.width self.aspectRatioHeight = self.frame.size.height } public func setCropAspectRect(aspect: String, maxSize: CGSize) { let elements = aspect.components(separatedBy: ":") self.aspectRatioWidth = CGFloat(Float(elements.first!)!) self.aspectRatioHeight = CGFloat(Float(elements.last!)!) var size = maxSize let mW = size.width / self.aspectRatioWidth let mH = size.height / self.aspectRatioHeight if (mH < mW) { size.width = size.height / self.aspectRatioHeight * self.aspectRatioWidth } else if(mW < mH) { size.height = size.width / self.aspectRatioWidth * self.aspectRatioHeight } let x = (self.frame.size.width - size.width).half let y = (self.frame.size.height - size.height).half self.frame = CGRect(x:x, y:y, width: size.width, height: size.height) } public func lockAspectRatio(_ lock: Bool) { resetAspectRect() self.isAspectRatioLocked = lock } }
mit
70d391684b9ebfa30a939fad2dd7ebc8
28.681818
85
0.612557
4.006135
false
false
false
false
xwu/swift
test/SILGen/optional-cast.swift
1
8683
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class A {} class B : A {} // CHECK-LABEL: sil hidden [ossa] @$s4main3fooyyAA1ACSgF : $@convention(thin) (@guaranteed Optional<A>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<A>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // Check whether the temporary holds a value. // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $Optional<A>, case #Optional.some!enumelt: [[IS_PRESENT:bb[0-9]+]], case #Optional.none!enumelt: [[NOT_PRESENT:bb[0-9]+]] // // If so, pull the value out and check whether it's a B. // CHECK: [[IS_PRESENT]]([[VAL:%.*]] : // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $A to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, materialize that and inject it into x. // CHECK: [[IS_B]]([[T0:%.*]] : @owned $B): // CHECK-NEXT: store [[T0]] to [init] [[X_VALUE]] : $*B // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: br [[CONT:bb[0-9]+]] // // If not, destroy_value the A and inject nothing into x. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none // CHECK-NEXT: br [[CONT]] // // Finish the present path. // CHECK: [[CONT]]: // CHECK-NEXT: br [[RETURN_BB:bb[0-9]+]] // // Finish. // CHECK: [[RETURN_BB]]: // CHECK-NEXT: destroy_value [[X]] // CHECK-NOT: destroy_value [[ARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return // // Finish the not-present path. // CHECK: [[NOT_PRESENT]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[RETURN_BB]] func foo(_ y : A?) { var x = (y as? B) } // CHECK-LABEL: sil hidden [ossa] @$s4main3baryyAA1ACSgSgSgSgF : $@convention(thin) (@guaranteed Optional<Optional<Optional<Optional<A>>>>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<Optional<Optional<Optional<A>>>>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // -- Check for some(...) // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: switch_enum [[ARG_COPY]] : ${{.*}}, case #Optional.some!enumelt: [[P:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_1:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_1]]: // CHECK: br [[FINISH_NIL_0:bb[0-9]+]] // // If so, drill down another level and check for some(some(...)). // CHECK: [[P]]([[VALUE_OOOA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OOOA]] : ${{.*}}, case #Optional.some!enumelt: [[PP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_2:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_2]]: // CHECK: br [[FINISH_NIL_0]] // // If so, drill down another level and check for some(some(some(...))). // CHECK: [[PP]]([[VALUE_OOA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OOA]] : ${{.*}}, case #Optional.some!enumelt: [[PPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_3:bb[0-9]+]] // // If so, drill down another level and check for some(some(some(some(...)))). // CHECK: [[PPP]]([[VALUE_OA:%.*]] : // CHECK-NEXT: switch_enum [[VALUE_OA]] : ${{.*}}, case #Optional.some!enumelt: [[PPPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_4:bb[0-9]+]] // // If so, pull out the A and check whether it's a B. // CHECK: [[PPPP]]([[VAL:%.*]] : // CHECK-NEXT: checked_cast_br [[VAL]] : $A to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, inject it back into an optional. // TODO: We're going to switch back out of this; we really should peephole it. // CHECK: [[IS_B]]([[T0:%.*]] : @owned $B): // CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt, [[T0]] // CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]]( // // If not, inject nothing into an optional. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[SWITCH_OB2]]( // // Switch out on the value in [[OB2]]. // CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : @owned $Optional<B>): // CHECK-NEXT: switch_enum [[VAL]] : ${{.*}}, case #Optional.some!enumelt: [[HAVE_B:bb[0-9]+]], case #Optional.none!enumelt: [[FINISH_NIL_4:bb[0-9]+]] // // CHECK: [[FINISH_NIL_4]]: // CHECK: br [[FINISH_NIL_0]] // // CHECK: [[HAVE_B]]([[UNWRAPPED_VAL:%.*]] : // CHECK: [[REWRAPPED_VAL:%.*]] = enum $Optional<B>, #Optional.some!enumelt, [[UNWRAPPED_VAL]] // CHECK: br [[DONE_DEPTH0:bb[0-9]+]] // // CHECK: [[DONE_DEPTH0]]( // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt, // CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]] // // Set X := some(OOB). // CHECK: [[DONE_DEPTH1]] // CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt, // CHECK: br [[DONE_DEPTH2:bb[0-9]+]] // CHECK: [[DONE_DEPTH2]] // CHECK-NEXT: destroy_value [[X]] // CHECK-NOT: destroy_value %0 // CHECK: return // // On various failure paths, set OOB := nil. // CHECK: [[NIL_DEPTH_4]]: // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH0]] // // CHECK: [[NIL_DEPTH_3]]: // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH1]] // // On various failure paths, set X := nil. // CHECK: [[FINISH_NIL_0]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[DONE_DEPTH2]] // Done. func bar(_ y : A????) { var x = (y as? B??) } // CHECK-LABEL: sil hidden [ossa] @$s4main3bazyyyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<AnyObject>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] // CHECK: bb1([[VAL:%.*]] : @owned $AnyObject): // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // CHECK: [[IS_B]]([[CASTED_VALUE:%.*]] : @owned $B): // CHECK: store [[CASTED_VALUE]] to [init] [[X_VALUE]] // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $AnyObject): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: } // end sil function '$s4main3bazyyyXlSgF' func baz(_ y : AnyObject?) { var x = (y as? B) } // <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B8_trivialySiSgACF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x" // CHECK-NEXT: return %0 : $Optional<Int> // CHECK-NEXT:} func opt_to_opt_trivial(_ x: Int?) -> Int! { return x } // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B10_referenceyAA1CCSgAEF // CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<C>): // CHECK: debug_value [[ARG]] : $Optional<C>, let, name "x" // CHECK: [[RESULT:%.*]] = copy_value [[ARG]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[RESULT]] : $Optional<C> // CHECK: } // end sil function '$s4main07opt_to_B10_referenceyAA1CCSgAEF' func opt_to_opt_reference(_ x : C!) -> C? { return x } // CHECK-LABEL: sil hidden [ossa] @$s4main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $*Optional<T>): // CHECK-NEXT: debug_value %1 : $*Optional<T>, let, name "x", {{.*}} expr op_deref // CHECK-NEXT: copy_addr %1 to [initialization] %0 // CHECK-NOT: destroy_addr %1 func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x } class C {} public struct TestAddressOnlyStruct<T> { func f(_ a : T?) {} // CHECK-LABEL: sil hidden [ossa] @$s4main21TestAddressOnlyStructV8testCall{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $TestAddressOnlyStruct<T>): // CHECK: apply {{.*}}<T>(%0, %1) func testCall(_ a : T!) { f(a) } } // CHECK-LABEL: sil hidden [ossa] @$s4main35testContextualInitOfNonAddrOnlyTypeyySiSgF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: store %0 to [trivial] [[PB]] : $*Optional<Int> // CHECK-NEXT: destroy_value [[X]] : ${ var Optional<Int> } func testContextualInitOfNonAddrOnlyType(_ a : Int?) { var x: Int! = a }
apache-2.0
14f1f330b6a9c3bd973707f039982a29
41.563725
163
0.579293
2.867569
false
false
false
false
kstaring/swift
stdlib/public/core/String.swift
1
30398
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // FIXME: complexity documentation for most of methods on String is ought to be // qualified with "amortized" at least, as Characters are variable-length. /// A Unicode string value. /// /// A string is a series of characters, such as `"Swift"`. Strings in Swift are /// Unicode correct, locale insensitive, and designed to be efficient. The /// `String` type bridges with the Objective-C class `NSString` and offers /// interoperability with C functions that works with strings. /// /// You can create new strings using string literals or string interpolations. /// A string literal is a series of characters enclosed in quotes. /// /// let greeting = "Welcome!" /// /// String interpolations are string literals that evaluate any included /// expressions and convert the results to string form. String interpolations /// are an easy way to build a string from multiple pieces. Wrap each /// expression in a string interpolation in parentheses, prefixed by a /// backslash. /// /// let name = "Rosa" /// let personalizedGreeting = "Welcome, \(name)!" /// /// let price = 2 /// let number = 3 /// let cookiePrice = "\(number) cookies: $\(price * number)." /// /// Combine strings using the concatenation operator (`+`). /// /// let longerGreeting = greeting + " We're glad you're here!" /// print(longerGreeting) /// // Prints "Welcome! We're glad you're here!" /// /// Modifying and Comparing Strings /// =============================== /// /// Strings always have value semantics. Modifying a copy of a string leaves /// the original unaffected. /// /// var otherGreeting = greeting /// otherGreeting += " Have a nice time!" /// print(otherGreeting) /// // Prints "Welcome! Have a nice time!" /// /// print(greeting) /// // Prints "Welcome!" /// /// Comparing strings for equality using the equal-to operator (`==`) or a /// relational operator (like `<` and `>=`) is always performed using the /// Unicode canonical representation. This means that different /// representations of a string compare as being equal. /// /// let cafe1 = "Cafe\u{301}" /// let cafe2 = "Café" /// print(cafe1 == cafe2) /// // Prints "true" /// /// The Unicode code point `"\u{301}"` modifies the preceding character to /// include an accent, so `"e\u{301}"` has the same canonical representation /// as the single Unicode code point `"é"`. /// /// Basic string operations are not sensitive to locale settings. This ensures /// that string comparisons and other operations always have a single, stable /// result, allowing strings to be used as keys in `Dictionary` instances and /// for other purposes. /// /// Representing Strings: Views /// =========================== /// /// A string is not itself a collection. Instead, it has properties that /// present its contents as meaningful collections. Each of these collections /// is a particular type of *view* of the string's visible and data /// representation. /// /// To demonstrate the different views available for every string, the /// following examples use this `String` instance: /// /// let cafe = "Cafe\u{301} du 🌍" /// print(cafe) /// // Prints "Café du 🌍" /// /// Character View /// -------------- /// /// A string's `characters` property is a collection of *extended grapheme /// clusters*, which approximate human-readable characters. Many individual /// characters, such as "é", "김", and "🇮🇳", can be made up of multiple Unicode /// code points. These code points are combined by Unicode's boundary /// algorithms into extended grapheme clusters, represented by Swift's /// `Character` type. Each element of the `characters` view is represented by /// a `Character` instance. /// /// print(cafe.characters.count) /// // Prints "9" /// print(Array(cafe.characters)) /// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]" /// /// Each visible character in the `cafe` string is a separate element of the /// `characters` view. /// /// Unicode Scalar View /// ------------------- /// /// A string's `unicodeScalars` property is a collection of Unicode scalar /// values, the 21-bit codes that are the basic unit of Unicode. Each scalar /// value is represented by a `UnicodeScalar` instance and is equivalent to a /// UTF-32 code unit. /// /// print(cafe.unicodeScalars.count) /// // Prints "10" /// print(Array(cafe.unicodeScalars)) /// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]" /// print(cafe.unicodeScalars.map { $0.value }) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]" /// /// The `unicodeScalars` view's elements comprise each Unicode scalar value in /// the `cafe` string. In particular, because `cafe` was declared using the /// decomposed form of the `"é"` character, `unicodeScalars` contains the code /// points for both the letter `"e"` (101) and the accent character `"´"` /// (769). /// /// UTF-16 View /// ----------- /// /// A string's `utf16` property is a collection of UTF-16 code units, the /// 16-bit encoding form of the string's Unicode scalar values. Each code unit /// is stored as a `UInt16` instance. /// /// print(cafe.utf16.count) /// // Prints "11" /// print(Array(cafe.utf16)) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]" /// /// The elements of the `utf16` view are the code units for the string when /// encoded in UTF-16. /// /// The elements of this collection match those accessed through indexed /// `NSString` APIs. /// /// let nscafe = cafe as NSString /// print(nscafe.length) /// // Prints "11" /// print(nscafe.character(at: 3)) /// // Prints "101" /// /// UTF-8 View /// ---------- /// /// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit /// encoding form of the string's Unicode scalar values. Each code unit is /// stored as a `UInt8` instance. /// /// print(cafe.utf8.count) /// // Prints "14" /// print(Array(cafe.utf8)) /// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]" /// /// The elements of the `utf8` view are the code units for the string when /// encoded in UTF-8. This representation matches the one used when `String` /// instances are passed to C APIs. /// /// let cLength = strlen(cafe) /// print(cLength) /// // Prints "14" /// /// Counting the Length of a String /// =============================== /// /// When you need to know the length of a string, you must first consider what /// you'll use the length for. Are you measuring the number of characters that /// will be displayed on the screen, or are you measuring the amount of /// storage needed for the string in a particular encoding? A single string /// can have greatly differing lengths when measured by its different views. /// /// For example, an ASCII character like the capital letter *A* is represented /// by a single element in each of its four views. The Unicode scalar value of /// *A* is `65`, which is small enough to fit in a single code unit in both /// UTF-16 and UTF-8. /// /// let capitalA = "A" /// print(capitalA.characters.count) /// // Prints "1" /// print(capitalA.unicodeScalars.count) /// // Prints "1" /// print(capitalA.utf16.count) /// // Prints "1" /// print(capitalA.utf8.count) /// // Prints "1" /// /// On the other hand, an emoji flag character is constructed from a pair of /// Unicode scalars values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of /// these scalar values, in turn, is too large to fit into a single UTF-16 or /// UTF-8 code unit. As a result, each view of the string `"🇵🇷"` reports a /// different length. /// /// let flag = "🇵🇷" /// print(flag.characters.count) /// // Prints "1" /// print(flag.unicodeScalars.count) /// // Prints "2" /// print(flag.utf16.count) /// // Prints "4" /// print(flag.utf8.count) /// // Prints "8" /// /// To check whether a string is empty, use its `isEmpty` property instead /// of comparing the length of one of the views to `0`. Unlike `isEmpty`, /// calculating a view's `count` property requires iterating through the /// elements of the string. /// /// Accessing String View Elements /// ============================== /// /// To find individual elements of a string, use the appropriate view for your /// task. For example, to retrieve the first word of a longer string, you can /// search the `characters` view for a space and then create a new string from /// a prefix of the `characters` view up to that point. /// /// let name = "Marie Curie" /// let firstSpace = name.characters.index(of: " ")! /// let firstName = String(name.characters.prefix(upTo: firstSpace)) /// print(firstName) /// // Prints "Marie" /// /// You can convert an index into one of a string's views to an index into /// another view. /// /// let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8) /// print(Array(name.utf8.prefix(upTo: firstSpaceUTF8))) /// // Prints "[77, 97, 114, 105, 101]" /// /// Performance Optimizations /// ========================= /// /// Although strings in Swift have value semantics, strings use a copy-on-write /// strategy to store their data in a buffer. This buffer can then be shared /// by different copies of a string. A string's data is only copied lazily, /// upon mutation, when more than one string instance is using the same /// buffer. Therefore, the first in any sequence of mutating operations may /// cost O(*n*) time and space. /// /// When a string's contiguous storage fills up, a new buffer must be allocated /// and data must be moved to the new storage. String buffers use an /// exponential growth strategy that makes appending to a string a constant /// time operation when averaged over many append operations. /// /// Bridging between String and NSString /// ==================================== /// /// Any `String` instance can be bridged to `NSString` using the type-cast /// operator (`as`), and any `String` instance that originates in Objective-C /// may use an `NSString` instance as its storage. Because any arbitrary /// subclass of `NSString` can become a `String` instance, there are no /// guarantees about representation or efficiency when a `String` instance is /// backed by `NSString` storage. Because `NSString` is immutable, it is just /// as though the storage was shared by a copy: The first in any sequence of /// mutating operations causes elements to be copied into unique, contiguous /// storage which may cost O(*n*) time and space, where *n* is the length of /// the string's encoded representation (or more, if the underlying `NSString` /// has unusual performance characteristics). /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters], /// [Unicode scalar values][scalars], and [canonical equivalence][equivalence]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value /// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent /// /// - SeeAlso: `String.CharacterView`, `String.UnicodeScalarView`, /// `String.UTF16View`, `String.UTF8View` @_fixed_layout public struct String { /// Creates an empty string. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { public // @testable static func _fromWellFormedCodeUnitSequence<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> String where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { return String._fromCodeUnitSequence(encoding, input: input)! } public // @testable static func _fromCodeUnitSequence<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> String? where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: false) return stringBufferOptional.map { String(_storage: $0) } } public // @testable static func _fromCodeUnitSequenceWithRepair<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _ExpressibleByBuiltinUnicodeScalarLiteral { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : ExpressibleByUnicodeScalarLiteral { /// Creates an instance initialized to the given Unicode scalar value. /// /// Do not call this initializer directly. It may be used by the compiler when /// you initialize a string using a string literal that contains a single /// Unicode scalar value. public init(unicodeScalarLiteral value: String) { self = value } } extension String : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } extension String : ExpressibleByExtendedGraphemeClusterLiteral { /// Creates an instance initialized to the given extended grapheme cluster /// literal. /// /// Do not call this initializer directly. It may be used by the compiler when /// you initialize a string using a string literal containing a single /// extended grapheme cluster. public init(extendedGraphemeClusterLiteral value: String) { self = value } } extension String : _ExpressibleByBuiltinUTF16StringLiteral { @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf16CodeUnitCount), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _ExpressibleByBuiltinStringLiteral { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf8CodeUnitCount), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } } extension String : ExpressibleByStringLiteral { /// Creates an instance initialized to the given string value. /// /// Do not call this initializer directly. It is used by the compiler when you /// initialize a string using a string literal. For example: /// /// let nextStop = "Clark & Lake" /// /// This assignment to the `nextStop` constant calls this string literal /// initializer behind the scenes. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A representation of the string that is suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escaped(asASCII: false) } result += "\"" return result } } extension String { /// Returns the number of code units occupied by this string /// in the given encoding. func _encodedLength< Encoding: UnicodeCodec >(_ encoding: Encoding.Type) -> Int { var codeUnitCount = 0 self._encode(encoding, into: { _ in codeUnitCount += 1 }) return codeUnitCount } // FIXME: this function does not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode< Encoding: UnicodeCodec >( _ encoding: Encoding.Type, into processCodeUnit: (Encoding.CodeUnit) -> Void ) { return _core.encode(encoding, into: processCodeUnit) } } // Support for copy-on-write extension String { /// Appends the given string to this string. /// /// The following example builds a customized greeting by using the /// `append(_:)` method: /// /// var greeting = "Hello, " /// if let name = getUserName() { /// greeting.append(name) /// } else { /// greeting.append("friend") /// } /// print(greeting) /// // Prints "Hello, friend" /// /// - Parameter other: Another string. public mutating func append(_ other: String) { _core.append(other._core) } /// Appends the given Unicode scalar to the string. /// /// - Parameter x: A Unicode scalar value. /// /// - Complexity: Appending a Unicode scalar to a string averages to O(1) /// over many additions. @available(*, unavailable, message: "Replaced by append(_: String)") public mutating func append(_ x: UnicodeScalar) { Builtin.unreachable() } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } extension String { @effects(readonly) @_semantics("string.concat") public static func + (lhs: String, rhs: String) -> String { if lhs.isEmpty { return rhs } var lhs = lhs lhs._core.append(rhs._core) return lhs } // String append public static func += (lhs: inout String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( _ resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8CodeUnitCount: Int ) { resultStorage.initialize(to: String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount))) } } extension Sequence where Iterator.Element == String { /// Returns a new string by concatenating the elements of the sequence, /// adding the given separator between each element. /// /// The following example shows how an array of strings can be joined to a /// single, comma-separated string: /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let list = cast.joined(separator: ", ") /// print(list) /// // Prints "Vivien, Marlon, Kim, Karl" /// /// - Parameter separator: A string to insert between each of the elements /// in this sequence. The default separator is an empty string. /// - Returns: A single, concatenated string. public func joined(separator: String = "") -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { () -> Int in var r = 0 for chunk in self { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize == 0 { for x in self { result.append(x) } return result } var iter = makeIterator() if let first = iter.next() { result.append(first) while let next = iter.next() { result.append(separator) result.append(next) } } return result } } #if _runtime(_ObjC) @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString #else internal func _nativeUnicodeLowercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } internal func _nativeUnicodeUppercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } /// Returns a lowercase version of the string. /// /// Here's an example of transforming a string to all lowercase letters. /// /// let cafe = "Café 🍵" /// print(cafe.lowercased()) /// // Prints "café 🍵" /// /// - Returns: A lowercase copy of the string. /// /// - Complexity: O(*n*) public func lowercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isUpper & 0x1) << 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest.storeBytes(of: value &+ UInt8(truncatingBitPattern: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } /// Returns an uppercase version of the string. /// /// The following example transforms a string to uppercase letters: /// /// let cafe = "Café 🍵" /// print(cafe.uppercased()) /// // Prints "CAFÉ 🍵" /// /// - Returns: An uppercase copy of the string. /// /// - Complexity: O(*n*) public func uppercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isLower & 0x1) << 5 dest.storeBytes(of: value &- UInt8(truncatingBitPattern: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } /// Creates an instance from the description of a given /// `LosslessStringConvertible` instance. public init<T : LosslessStringConvertible>(_ value: T) { self = value.description } } extension String : CustomStringConvertible { public var description: String { return self } } extension String : LosslessStringConvertible { public init?(_ description: String) { self = description } } extension String { @available(*, unavailable, renamed: "append(_:)") public mutating func appendContentsOf(_ other: String) { Builtin.unreachable() } @available(*, unavailable, renamed: "append(contentsOf:)") public mutating func appendContentsOf<S : Sequence>(_ newElements: S) where S.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "insert(contentsOf:at:)") public mutating func insertContentsOf<S : Collection>( _ newElements: S, at i: Index ) where S.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange<C : Collection>( _ subRange: Range<Index>, with newElements: C ) where C.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange( _ subRange: Range<Index>, with newElements: String ) { Builtin.unreachable() } @available(*, unavailable, renamed: "remove(at:)") public mutating func removeAtIndex(_ i: Index) -> Character { Builtin.unreachable() } @available(*, unavailable, renamed: "removeSubrange") public mutating func removeRange(_ subRange: Range<Index>) { Builtin.unreachable() } @available(*, unavailable, renamed: "lowercased()") public var lowercaseString: String { Builtin.unreachable() } @available(*, unavailable, renamed: "uppercased()") public var uppercaseString: String { Builtin.unreachable() } @available(*, unavailable, renamed: "init(describing:)") public init<T>(_: T) { Builtin.unreachable() } } extension Sequence where Iterator.Element == String { @available(*, unavailable, renamed: "joined(separator:)") public func joinWithSeparator(_ separator: String) -> String { Builtin.unreachable() } }
apache-2.0
f3f52dab1f3cef374ecbf37d509902f3
33.134983
94
0.65834
4.159836
false
false
false
false
JojoSc/OverTheEther
OverTheEther/Classes/Handshake.swift
1
1298
// // CommunicationProtocol.swift // PartyMasterSwift // // Created by Johannes Schreiber on 15/12/15. // Copyright © 2015 Johannes Schreiber. All rights reserved. // import Foundation @objc public enum Reason : Int { case RequiresPasscode = 2 case Other = 3 } enum MessageType : String { case REQAskIfPinIsNeeded = "REQAskIfPinIsNeeded" case ACKNoPinIsNotNeeded = "ACKNoPinIsNotNeeded" case ACKYesPinIsNeeded = "ACKYesPinIsNeeded" case ACKClientIsAbleToSend = "ACKClientIsAbleToSend" //Handled in client, since the server sends the pin //case REQSendingPin = "REQSendingPin" //case ACKPinIsCorrect = "ACKPinIsCorrect" //case ACKPinIsFalse = "ACKPinIsFalse" } class HandShake : NSObject, NSCoding { var type:MessageType // Optional Payload var passcode:String? required init(type:MessageType) { self.type = type } required init(coder aDecoder:NSCoder) { type = MessageType(rawValue: aDecoder.decodeObjectForKey("type") as! String)! passcode = aDecoder.decodeObjectForKey("passcode") as? String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(type.rawValue, forKey: "type") aCoder.encodeObject(passcode, forKey: "passcode") } }
mit
b2e2c28e98ebaa85069f5882b2973bc6
23.471698
85
0.686199
4.02795
false
false
false
false
PezHead/tiny-tennis-scoreboard
Tiny Tennis/Config.swift
1
481
// // Config.swift // Tiny Tennis // // Created by David Bireta on 10/15/16. // Copyright © 2016 David Bireta. All rights reserved. // struct Config { static let slackToken = "<SLACK_TOKEN>" // static let slackChannel = "#tabletennis" static let slackChannel = "#thundercat" static let apiKey = "<API_KEY>" static let urlScheme = "tinytennis" static let fruitAddress = "<PI_SERVER_ADDRESS>" static let fruitPort: UInt32 = 1234 }
mit
e8c036ce7de12b582224d69e8d85f961
23
55
0.639583
3.72093
false
true
false
false
muneebm/AsterockX
Pods/NEOWS/Pod/Classes/OrbitalData.swift
2
2890
// // OrbitalData.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/10/16. // Copyright © 2016 beenum. All rights reserved. // import Foundation public class OrbitalData { public let orbitId: String? public let orbitDeterminationDate: NSDate? public let orbitUncertainty: String? public let minimumOrbitIntersection: String? public let jupiterTisserandInvariant: String? public let epochOsculation: String? public let eccentricity: String? public let semiMajorAxis: String? public let inclination: String? public let ascendingNodeLongitude: String? public let orbitalPeriod: String? public let perihelionDistance: String? public let perihelionArgument: String? public let aphelionDistance: String? public let perihelionTime: String? public let meanAnomaly: String? public let meanMotion: String? public let equinox: String? init(dictionary: [String : AnyObject]) { orbitId = dictionary[NeoWs.JSONResponseKeys.OrbitId] as? String if let date = dictionary[NeoWs.JSONResponseKeys.OrbitDetetminationDate] as? String { let formatter = NSDateFormatter() formatter.dateFormat = NeoWs.Constants.OrbitDeterminationDateFormat orbitDeterminationDate = formatter.dateFromString(date) } else { orbitDeterminationDate = nil } orbitUncertainty = dictionary[NeoWs.JSONResponseKeys.OrbitUncertainty] as? String minimumOrbitIntersection = dictionary[NeoWs.JSONResponseKeys.MinimumOrbitIntersection] as? String jupiterTisserandInvariant = dictionary[NeoWs.JSONResponseKeys.JupiterTisserandInvariant] as? String epochOsculation = dictionary[NeoWs.JSONResponseKeys.EpochOsculation] as? String eccentricity = dictionary[NeoWs.JSONResponseKeys.Eccentricity] as? String semiMajorAxis = dictionary[NeoWs.JSONResponseKeys.SemiMajorAxis] as? String inclination = dictionary[NeoWs.JSONResponseKeys.Inclination] as? String ascendingNodeLongitude = dictionary[NeoWs.JSONResponseKeys.AscendingNodeLongitude] as? String orbitalPeriod = dictionary[NeoWs.JSONResponseKeys.OrbitalPeriod] as? String perihelionDistance = dictionary[NeoWs.JSONResponseKeys.PerihelionDistance] as? String perihelionArgument = dictionary[NeoWs.JSONResponseKeys.PerihelionArgument] as? String aphelionDistance = dictionary[NeoWs.JSONResponseKeys.AphelionDistance] as? String perihelionTime = dictionary[NeoWs.JSONResponseKeys.PerihelionTime] as? String meanAnomaly = dictionary[NeoWs.JSONResponseKeys.MeanAnomaly] as? String meanMotion = dictionary[NeoWs.JSONResponseKeys.MeanMotion] as? String equinox = dictionary[NeoWs.JSONResponseKeys.Equinox] as? String } }
mit
b8c3acff892bc72dbdb1b5b3add314ad
44.140625
107
0.731395
4.5
false
false
false
false
skyefreeman/OnTap
Example/OnTap/ViewController.swift
1
3491
// // ViewController.swift // OnTap // // Created by Skye Freeman on 1/27/17. // Copyright © 2017 Skye Freeman. All rights reserved. // import UIKit import OnTap extension UIView { var x: CGFloat { return frame.origin.x } var y: CGFloat { return frame.origin.y } var width: CGFloat { return frame.size.width } var height: CGFloat { return frame.size.height } var bottom: CGFloat { return frame.origin.y + frame.size.height } var right: CGFloat { return frame.origin.x + frame.size.width } func addSubviews(_ subviews: UIView...) { subviews.forEach { subview in addSubview(subview) } } } class ViewController: UIViewController { lazy var button: UIButton = { let button = UIButton() button.backgroundColor = UIColor.blue button.setTitle(NSLocalizedString("UIButton", comment: ""), for: .normal) return button .on(.touchDown) { print("touch down happend!!!") } .on(.touchDownRepeat) { print("touch down repeated!!!") } .on(.touchUpInside) { print("touch up inside happend!!!") } .on(.touchUpOutside) { print("touch up outside happend!!!") } }() lazy var slider: UISlider = { return UISlider().on(.valueChanged) { [unowned self] in print("slider new value: \(self.slider.value)") } }() lazy var switchView: UISwitch = { return UISwitch().on(.valueChanged) { [unowned self] in print("switch new value: \(self.switchView.isOn)") } }() lazy var label: UILabel = { let label = UILabel() label.backgroundColor = UIColor.red label.text = NSLocalizedString("Tap me!", comment: "") label.textColor = UIColor.white label.textAlignment = .center return label .on(.tap, touches: 1) { label.text = "tapped" } .on(.leftSwipe, touches: 1) { label.text = "left" } .on(.rightSwipe, touches: 1) { label.text = "right" } .on(.upSwipe, touches: 1) { label.text = "up" } .on(.downSwipe, touches: 1) { label.text = "down" } }() lazy var leftBarButtonItem: UIBarButtonItem = { return UIBarButtonItem(title: NSLocalizedString("Left", comment: ""), style: .plain) { print("left barButtonItem tapped!") } }() lazy var rightBarButtonItem: UIBarButtonItem = { return UIBarButtonItem(title: NSLocalizedString("Right", comment: ""), style: .plain) { print("right barButtonItem tapped!") } }() override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let sharedSize = CGSize(width: view.width/2, height: view.height/2) button.frame = CGRect(x: 0, y: 0, width: sharedSize.width, height: sharedSize.height) slider.frame = CGRect(x: view.width/2, y: 0, width: sharedSize.width, height: sharedSize.height) switchView.center = CGPoint(x: sharedSize.width/2, y: button.bottom + sharedSize.height/2) label.frame = CGRect(x: view.width/2, y: slider.bottom, width: sharedSize.width, height: sharedSize.height) } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = leftBarButtonItem navigationItem.rightBarButtonItem = rightBarButtonItem view.addSubviews(button, slider, switchView, label) edgesForExtendedLayout = [] } }
mit
b153b39628efa38561ca86bd8eb8adbd
34.979381
115
0.610029
4.3625
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/FernandoPreciado/Practica #7.swift
1
1798
// Alumno: Fernando Preciado Salman // Numero de Control: 12211415 // Patrones de diseño // Practica: 3 capitulo 5 // Realizar un programa que simule 1000 tiros de 6 monedas import Foundation let m1c let m1cr let m2c let m2cr let m3c let m3cr let m4c let m4cr let m5c let m5cr let m6c let m6cr print("Moneda 1") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m1c+1 } else { m1cr = m1cr+1 } } print("Moneda 2") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m2c+1 } else { m1cr = m2cr+1 } } print("Moneda 3") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m3c+1 } else { m1cr = m3cr+1 } } print("Moneda 4") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m4c+1 } else { m1cr = m4cr+1 } } print("Moneda 5") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m5c+1 } else { m1cr = m5cr+1 } } print("Moneda 6") for index in 1...1000 { let coinflip = Int(arc4random_uniform(UInt32(2))) if (coinflip == 1) { m1c = m6c+1 } else { m1cr = m6cr+1 } } print("Moneda 1 caras: \(m1c)") print("Moneda 1 cruz: \(m1cr)") print("Moneda 2 caras: \(m2c)") print("Moneda 2 cruz: \(m2cr)") print("Moneda 3 caras: \(m3c)") print("Moneda 3 cruz: \(m3cr)") print("Moneda 4 caras: \(m4c)") print("Moneda 4 cruz: \(m4cr)") print("Moneda 5 caras: \(m5c)") print("Moneda 5 cruz: \(m5cr)") print("Moneda 6 caras: \(m6c)") print("Moneda 6 cruz: \(m6cr)")
gpl-3.0
0a6121ee8d25c35320b1ff0490e480cb
12.867769
60
0.579299
2.149522
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Scenes/Statistics/StatisticsViewController.swift
1
2066
// // Created by Maxim Pervushin on 20/11/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import UIKit class StatisticsViewController: UIViewController, Themed { // MARK: StatisticsViewController @IB @IBOutlet weak var calendarView: MXCalendarView! // MARK: StatisticsViewController private let dataSource = StatisticsDataSource(dataProvider: App.dataProvider) private var selectedDate: NSDate? override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) calendarView?.scrollToDate(NSDate(), animated: false) } override func viewDidLoad() { super.viewDidLoad() dataSource.changedHandler = updateUI calendarView?.cellConfigurationHandler = calendarViewCellConfiguration calendarView?.willDisplayMonthHandler = calendarViewWillDisplayMonth } override func preferredStatusBarStyle() -> UIStatusBarStyle { return App.themeManager.theme.statusBarStyle } deinit { themedDeinit() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) themedInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) themedInit() } private func updateUI() { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.calendarView?.updateUI() } } private func calendarViewCellConfiguration(cell: UICollectionViewCell) { if let dayCell = cell as? MXDayCell, let date = dayCell.date { let reports = dataSource.reportsForDate(date) let completedCount = reports.reduce(0, combine: { return $1.completed ? $0 + 1 : $0 }) dayCell.accessoryView?.maxValue = reports.count dayCell.accessoryView?.value = completedCount } } private func calendarViewWillDisplayMonth(month: NSDate) { dataSource.month = month } }
mit
45a55308760d30f3ee5988cf9d8207c4
28.098592
84
0.662149
5.126551
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/IoTEvents/IoTEvents_Shapes.swift
1
73883
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension IoTEvents { // MARK: Enums public enum DetectorModelVersionStatus: String, CustomStringConvertible, Codable { case activating = "ACTIVATING" case active = "ACTIVE" case deprecated = "DEPRECATED" case draft = "DRAFT" case failed = "FAILED" case inactive = "INACTIVE" case paused = "PAUSED" public var description: String { return self.rawValue } } public enum EvaluationMethod: String, CustomStringConvertible, Codable { case batch = "BATCH" case serial = "SERIAL" public var description: String { return self.rawValue } } public enum InputStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case creating = "CREATING" case deleting = "DELETING" case updating = "UPDATING" public var description: String { return self.rawValue } } public enum LoggingLevel: String, CustomStringConvertible, Codable { case debug = "DEBUG" case error = "ERROR" case info = "INFO" public var description: String { return self.rawValue } } public enum PayloadType: String, CustomStringConvertible, Codable { case json = "JSON" case string = "STRING" public var description: String { return self.rawValue } } // MARK: Shapes public struct Action: AWSEncodableShape & AWSDecodableShape { /// Information needed to clear the timer. public let clearTimer: ClearTimerAction? /// Writes to the DynamoDB table that you created. The default action payload contains all attribute-value pairs that have the information about the detector model instance and the event that triggered the action. You can also customize the payload. One column of the DynamoDB table receives all attribute-value pairs in the payload that you specify. For more information, see Actions in AWS IoT Events Developer Guide. public let dynamoDB: DynamoDBAction? /// Writes to the DynamoDB table that you created. The default action payload contains all attribute-value pairs that have the information about the detector model instance and the event that triggered the action. You can also customize the payload. A separate column of the DynamoDB table receives one attribute-value pair in the payload that you specify. For more information, see Actions in AWS IoT Events Developer Guide. public let dynamoDBv2: DynamoDBv2Action? /// Sends information about the detector model instance and the event that triggered the action to an Amazon Kinesis Data Firehose delivery stream. public let firehose: FirehoseAction? /// Sends AWS IoT Events input, which passes information about the detector model instance and the event that triggered the action. public let iotEvents: IotEventsAction? /// Sends information about the detector model instance and the event that triggered the action to an asset property in AWS IoT SiteWise . public let iotSiteWise: IotSiteWiseAction? /// Publishes an MQTT message with the given topic to the AWS IoT message broker. public let iotTopicPublish: IotTopicPublishAction? /// Calls a Lambda function, passing in information about the detector model instance and the event that triggered the action. public let lambda: LambdaAction? /// Information needed to reset the timer. public let resetTimer: ResetTimerAction? /// Information needed to set the timer. public let setTimer: SetTimerAction? /// Sets a variable to a specified value. public let setVariable: SetVariableAction? /// Sends an Amazon SNS message. public let sns: SNSTopicPublishAction? /// Sends information about the detector model instance and the event that triggered the action to an Amazon SQS queue. public let sqs: SqsAction? public init(clearTimer: ClearTimerAction? = nil, dynamoDB: DynamoDBAction? = nil, dynamoDBv2: DynamoDBv2Action? = nil, firehose: FirehoseAction? = nil, iotEvents: IotEventsAction? = nil, iotSiteWise: IotSiteWiseAction? = nil, iotTopicPublish: IotTopicPublishAction? = nil, lambda: LambdaAction? = nil, resetTimer: ResetTimerAction? = nil, setTimer: SetTimerAction? = nil, setVariable: SetVariableAction? = nil, sns: SNSTopicPublishAction? = nil, sqs: SqsAction? = nil) { self.clearTimer = clearTimer self.dynamoDB = dynamoDB self.dynamoDBv2 = dynamoDBv2 self.firehose = firehose self.iotEvents = iotEvents self.iotSiteWise = iotSiteWise self.iotTopicPublish = iotTopicPublish self.lambda = lambda self.resetTimer = resetTimer self.setTimer = setTimer self.setVariable = setVariable self.sns = sns self.sqs = sqs } public func validate(name: String) throws { try self.clearTimer?.validate(name: "\(name).clearTimer") try self.dynamoDB?.validate(name: "\(name).dynamoDB") try self.dynamoDBv2?.validate(name: "\(name).dynamoDBv2") try self.firehose?.validate(name: "\(name).firehose") try self.iotEvents?.validate(name: "\(name).iotEvents") try self.iotTopicPublish?.validate(name: "\(name).iotTopicPublish") try self.lambda?.validate(name: "\(name).lambda") try self.resetTimer?.validate(name: "\(name).resetTimer") try self.setTimer?.validate(name: "\(name).setTimer") try self.setVariable?.validate(name: "\(name).setVariable") try self.sns?.validate(name: "\(name).sns") try self.sqs?.validate(name: "\(name).sqs") } private enum CodingKeys: String, CodingKey { case clearTimer case dynamoDB case dynamoDBv2 case firehose case iotEvents case iotSiteWise case iotTopicPublish case lambda case resetTimer case setTimer case setVariable case sns case sqs } } public struct AssetPropertyTimestamp: AWSEncodableShape & AWSDecodableShape { /// The nanosecond offset converted from timeInSeconds. The valid range is between 0-999999999. You can also specify an expression. public let offsetInNanos: String? /// The timestamp, in seconds, in the Unix epoch format. The valid range is between 1-31556889864403199. You can also specify an expression. public let timeInSeconds: String public init(offsetInNanos: String? = nil, timeInSeconds: String) { self.offsetInNanos = offsetInNanos self.timeInSeconds = timeInSeconds } private enum CodingKeys: String, CodingKey { case offsetInNanos case timeInSeconds } } public struct AssetPropertyValue: AWSEncodableShape & AWSDecodableShape { /// The quality of the asset property value. The value must be GOOD, BAD, or UNCERTAIN. You can also specify an expression. public let quality: String? /// The timestamp associated with the asset property value. The default is the current event time. public let timestamp: AssetPropertyTimestamp? /// The value to send to an asset property. public let value: AssetPropertyVariant public init(quality: String? = nil, timestamp: AssetPropertyTimestamp? = nil, value: AssetPropertyVariant) { self.quality = quality self.timestamp = timestamp self.value = value } private enum CodingKeys: String, CodingKey { case quality case timestamp case value } } public struct AssetPropertyVariant: AWSEncodableShape & AWSDecodableShape { /// The asset property value is a Boolean value that must be TRUE or FALSE. You can also specify an expression. If you use an expression, the evaluated result should be a Boolean value. public let booleanValue: String? /// The asset property value is a double. You can also specify an expression. If you use an expression, the evaluated result should be a double. public let doubleValue: String? /// The asset property value is an integer. You can also specify an expression. If you use an expression, the evaluated result should be an integer. public let integerValue: String? /// The asset property value is a string. You can also specify an expression. If you use an expression, the evaluated result should be a string. public let stringValue: String? public init(booleanValue: String? = nil, doubleValue: String? = nil, integerValue: String? = nil, stringValue: String? = nil) { self.booleanValue = booleanValue self.doubleValue = doubleValue self.integerValue = integerValue self.stringValue = stringValue } private enum CodingKeys: String, CodingKey { case booleanValue case doubleValue case integerValue case stringValue } } public struct Attribute: AWSEncodableShape & AWSDecodableShape { /// An expression that specifies an attribute-value pair in a JSON structure. Use this to specify an attribute from the JSON payload that is made available by the input. Inputs are derived from messages sent to AWS IoT Events (BatchPutMessage). Each such message contains a JSON payload. The attribute (and its paired value) specified here are available for use in the condition expressions used by detectors. Syntax: &lt;field-name&gt;.&lt;field-name&gt;... public let jsonPath: String public init(jsonPath: String) { self.jsonPath = jsonPath } public func validate(name: String) throws { try self.validate(self.jsonPath, name: "jsonPath", parent: name, max: 128) try self.validate(self.jsonPath, name: "jsonPath", parent: name, min: 1) try self.validate(self.jsonPath, name: "jsonPath", parent: name, pattern: "^((`[\\w\\- ]+`)|([\\w\\-]+))(\\.((`[\\w- ]+`)|([\\w\\-]+)))*$") } private enum CodingKeys: String, CodingKey { case jsonPath } } public struct ClearTimerAction: AWSEncodableShape & AWSDecodableShape { /// The name of the timer to clear. public let timerName: String public init(timerName: String) { self.timerName = timerName } public func validate(name: String) throws { try self.validate(self.timerName, name: "timerName", parent: name, max: 128) try self.validate(self.timerName, name: "timerName", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case timerName } } public struct CreateDetectorModelRequest: AWSEncodableShape { /// Information that defines how the detectors operate. public let detectorModelDefinition: DetectorModelDefinition /// A brief description of the detector model. public let detectorModelDescription: String? /// The name of the detector model. public let detectorModelName: String /// Information about the order in which events are evaluated and how actions are executed. public let evaluationMethod: EvaluationMethod? /// The input attribute key used to identify a device or system to create a detector (an instance of the detector model) and then to route each input received to the appropriate detector (instance). This parameter uses a JSON-path expression in the message payload of each input to specify the attribute-value pair that is used to identify the device associated with the input. public let key: String? /// The ARN of the role that grants permission to AWS IoT Events to perform its operations. public let roleArn: String /// Metadata that can be used to manage the detector model. public let tags: [Tag]? public init(detectorModelDefinition: DetectorModelDefinition, detectorModelDescription: String? = nil, detectorModelName: String, evaluationMethod: EvaluationMethod? = nil, key: String? = nil, roleArn: String, tags: [Tag]? = nil) { self.detectorModelDefinition = detectorModelDefinition self.detectorModelDescription = detectorModelDescription self.detectorModelName = detectorModelName self.evaluationMethod = evaluationMethod self.key = key self.roleArn = roleArn self.tags = tags } public func validate(name: String) throws { try self.detectorModelDefinition.validate(name: "\(name).detectorModelDefinition") try self.validate(self.detectorModelDescription, name: "detectorModelDescription", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.key, name: "key", parent: name, pattern: "^((`[\\w\\- ]+`)|([\\w\\-]+))(\\.((`[\\w- ]+`)|([\\w\\-]+)))*$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } } private enum CodingKeys: String, CodingKey { case detectorModelDefinition case detectorModelDescription case detectorModelName case evaluationMethod case key case roleArn case tags } } public struct CreateDetectorModelResponse: AWSDecodableShape { /// Information about how the detector model is configured. public let detectorModelConfiguration: DetectorModelConfiguration? public init(detectorModelConfiguration: DetectorModelConfiguration? = nil) { self.detectorModelConfiguration = detectorModelConfiguration } private enum CodingKeys: String, CodingKey { case detectorModelConfiguration } } public struct CreateInputRequest: AWSEncodableShape { /// The definition of the input. public let inputDefinition: InputDefinition /// A brief description of the input. public let inputDescription: String? /// The name you want to give to the input. public let inputName: String /// Metadata that can be used to manage the input. public let tags: [Tag]? public init(inputDefinition: InputDefinition, inputDescription: String? = nil, inputName: String, tags: [Tag]? = nil) { self.inputDefinition = inputDefinition self.inputDescription = inputDescription self.inputName = inputName self.tags = tags } public func validate(name: String) throws { try self.inputDefinition.validate(name: "\(name).inputDefinition") try self.validate(self.inputDescription, name: "inputDescription", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, min: 1) try self.validate(self.inputName, name: "inputName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } } private enum CodingKeys: String, CodingKey { case inputDefinition case inputDescription case inputName case tags } } public struct CreateInputResponse: AWSDecodableShape { /// Information about the configuration of the input. public let inputConfiguration: InputConfiguration? public init(inputConfiguration: InputConfiguration? = nil) { self.inputConfiguration = inputConfiguration } private enum CodingKeys: String, CodingKey { case inputConfiguration } } public struct DeleteDetectorModelRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "detectorModelName", location: .uri(locationName: "detectorModelName")) ] /// The name of the detector model to be deleted. public let detectorModelName: String public init(detectorModelName: String) { self.detectorModelName = detectorModelName } public func validate(name: String) throws { try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") } private enum CodingKeys: CodingKey {} } public struct DeleteDetectorModelResponse: AWSDecodableShape { public init() {} } public struct DeleteInputRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "inputName", location: .uri(locationName: "inputName")) ] /// The name of the input to delete. public let inputName: String public init(inputName: String) { self.inputName = inputName } public func validate(name: String) throws { try self.validate(self.inputName, name: "inputName", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, min: 1) try self.validate(self.inputName, name: "inputName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: CodingKey {} } public struct DeleteInputResponse: AWSDecodableShape { public init() {} } public struct DescribeDetectorModelRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "detectorModelName", location: .uri(locationName: "detectorModelName")), AWSMemberEncoding(label: "detectorModelVersion", location: .querystring(locationName: "version")) ] /// The name of the detector model. public let detectorModelName: String /// The version of the detector model. public let detectorModelVersion: String? public init(detectorModelName: String, detectorModelVersion: String? = nil) { self.detectorModelName = detectorModelName self.detectorModelVersion = detectorModelVersion } public func validate(name: String) throws { try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.detectorModelVersion, name: "detectorModelVersion", parent: name, max: 128) try self.validate(self.detectorModelVersion, name: "detectorModelVersion", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct DescribeDetectorModelResponse: AWSDecodableShape { /// Information about the detector model. public let detectorModel: DetectorModel? public init(detectorModel: DetectorModel? = nil) { self.detectorModel = detectorModel } private enum CodingKeys: String, CodingKey { case detectorModel } } public struct DescribeInputRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "inputName", location: .uri(locationName: "inputName")) ] /// The name of the input. public let inputName: String public init(inputName: String) { self.inputName = inputName } public func validate(name: String) throws { try self.validate(self.inputName, name: "inputName", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, min: 1) try self.validate(self.inputName, name: "inputName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: CodingKey {} } public struct DescribeInputResponse: AWSDecodableShape { /// Information about the input. public let input: Input? public init(input: Input? = nil) { self.input = input } private enum CodingKeys: String, CodingKey { case input } } public struct DescribeLoggingOptionsRequest: AWSEncodableShape { public init() {} } public struct DescribeLoggingOptionsResponse: AWSDecodableShape { /// The current settings of the AWS IoT Events logging options. public let loggingOptions: LoggingOptions? public init(loggingOptions: LoggingOptions? = nil) { self.loggingOptions = loggingOptions } private enum CodingKeys: String, CodingKey { case loggingOptions } } public struct DetectorDebugOption: AWSEncodableShape & AWSDecodableShape { /// The name of the detector model. public let detectorModelName: String /// The value of the input attribute key used to create the detector (the instance of the detector model). public let keyValue: String? public init(detectorModelName: String, keyValue: String? = nil) { self.detectorModelName = detectorModelName self.keyValue = keyValue } public func validate(name: String) throws { try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.keyValue, name: "keyValue", parent: name, max: 128) try self.validate(self.keyValue, name: "keyValue", parent: name, min: 1) try self.validate(self.keyValue, name: "keyValue", parent: name, pattern: "^[a-zA-Z0-9\\-_:]+$") } private enum CodingKeys: String, CodingKey { case detectorModelName case keyValue } } public struct DetectorModel: AWSDecodableShape { /// Information about how the detector is configured. public let detectorModelConfiguration: DetectorModelConfiguration? /// Information that defines how a detector operates. public let detectorModelDefinition: DetectorModelDefinition? public init(detectorModelConfiguration: DetectorModelConfiguration? = nil, detectorModelDefinition: DetectorModelDefinition? = nil) { self.detectorModelConfiguration = detectorModelConfiguration self.detectorModelDefinition = detectorModelDefinition } private enum CodingKeys: String, CodingKey { case detectorModelConfiguration case detectorModelDefinition } } public struct DetectorModelConfiguration: AWSDecodableShape { /// The time the detector model was created. public let creationTime: Date? /// The ARN of the detector model. public let detectorModelArn: String? /// A brief description of the detector model. public let detectorModelDescription: String? /// The name of the detector model. public let detectorModelName: String? /// The version of the detector model. public let detectorModelVersion: String? /// Information about the order in which events are evaluated and how actions are executed. public let evaluationMethod: EvaluationMethod? /// The value used to identify a detector instance. When a device or system sends input, a new detector instance with a unique key value is created. AWS IoT Events can continue to route input to its corresponding detector instance based on this identifying information. This parameter uses a JSON-path expression to select the attribute-value pair in the message payload that is used for identification. To route the message to the correct detector instance, the device must send a message payload that contains the same attribute-value. public let key: String? /// The time the detector model was last updated. public let lastUpdateTime: Date? /// The ARN of the role that grants permission to AWS IoT Events to perform its operations. public let roleArn: String? /// The status of the detector model. public let status: DetectorModelVersionStatus? public init(creationTime: Date? = nil, detectorModelArn: String? = nil, detectorModelDescription: String? = nil, detectorModelName: String? = nil, detectorModelVersion: String? = nil, evaluationMethod: EvaluationMethod? = nil, key: String? = nil, lastUpdateTime: Date? = nil, roleArn: String? = nil, status: DetectorModelVersionStatus? = nil) { self.creationTime = creationTime self.detectorModelArn = detectorModelArn self.detectorModelDescription = detectorModelDescription self.detectorModelName = detectorModelName self.detectorModelVersion = detectorModelVersion self.evaluationMethod = evaluationMethod self.key = key self.lastUpdateTime = lastUpdateTime self.roleArn = roleArn self.status = status } private enum CodingKeys: String, CodingKey { case creationTime case detectorModelArn case detectorModelDescription case detectorModelName case detectorModelVersion case evaluationMethod case key case lastUpdateTime case roleArn case status } } public struct DetectorModelDefinition: AWSEncodableShape & AWSDecodableShape { /// The state that is entered at the creation of each detector (instance). public let initialStateName: String /// Information about the states of the detector. public let states: [State] public init(initialStateName: String, states: [State]) { self.initialStateName = initialStateName self.states = states } public func validate(name: String) throws { try self.validate(self.initialStateName, name: "initialStateName", parent: name, max: 128) try self.validate(self.initialStateName, name: "initialStateName", parent: name, min: 1) try self.states.forEach { try $0.validate(name: "\(name).states[]") } try self.validate(self.states, name: "states", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case initialStateName case states } } public struct DetectorModelSummary: AWSDecodableShape { /// The time the detector model was created. public let creationTime: Date? /// A brief description of the detector model. public let detectorModelDescription: String? /// The name of the detector model. public let detectorModelName: String? public init(creationTime: Date? = nil, detectorModelDescription: String? = nil, detectorModelName: String? = nil) { self.creationTime = creationTime self.detectorModelDescription = detectorModelDescription self.detectorModelName = detectorModelName } private enum CodingKeys: String, CodingKey { case creationTime case detectorModelDescription case detectorModelName } } public struct DetectorModelVersionSummary: AWSDecodableShape { /// The time the detector model version was created. public let creationTime: Date? /// The ARN of the detector model version. public let detectorModelArn: String? /// The name of the detector model. public let detectorModelName: String? /// The ID of the detector model version. public let detectorModelVersion: String? /// Information about the order in which events are evaluated and how actions are executed. public let evaluationMethod: EvaluationMethod? /// The last time the detector model version was updated. public let lastUpdateTime: Date? /// The ARN of the role that grants the detector model permission to perform its tasks. public let roleArn: String? /// The status of the detector model version. public let status: DetectorModelVersionStatus? public init(creationTime: Date? = nil, detectorModelArn: String? = nil, detectorModelName: String? = nil, detectorModelVersion: String? = nil, evaluationMethod: EvaluationMethod? = nil, lastUpdateTime: Date? = nil, roleArn: String? = nil, status: DetectorModelVersionStatus? = nil) { self.creationTime = creationTime self.detectorModelArn = detectorModelArn self.detectorModelName = detectorModelName self.detectorModelVersion = detectorModelVersion self.evaluationMethod = evaluationMethod self.lastUpdateTime = lastUpdateTime self.roleArn = roleArn self.status = status } private enum CodingKeys: String, CodingKey { case creationTime case detectorModelArn case detectorModelName case detectorModelVersion case evaluationMethod case lastUpdateTime case roleArn case status } } public struct DynamoDBAction: AWSEncodableShape & AWSDecodableShape { /// The name of the hash key (also called the partition key). public let hashKeyField: String /// The data type for the hash key (also called the partition key). You can specify the following values: STRING - The hash key is a string. NUMBER - The hash key is a number. If you don't specify hashKeyType, the default value is STRING. public let hashKeyType: String? /// The value of the hash key (also called the partition key). public let hashKeyValue: String /// The type of operation to perform. You can specify the following values: INSERT - Insert data as a new item into the DynamoDB table. This item uses the specified hash key as a partition key. If you specified a range key, the item uses the range key as a sort key. UPDATE - Update an existing item of the DynamoDB table with new data. This item's partition key must match the specified hash key. If you specified a range key, the range key must match the item's sort key. DELETE - Delete an existing item of the DynamoDB table. This item's partition key must match the specified hash key. If you specified a range key, the range key must match the item's sort key. If you don't specify this parameter, AWS IoT Events triggers the INSERT operation. public let operation: String? public let payload: Payload? /// The name of the DynamoDB column that receives the action payload. If you don't specify this parameter, the name of the DynamoDB column is payload. public let payloadField: String? /// The name of the range key (also called the sort key). public let rangeKeyField: String? /// The data type for the range key (also called the sort key), You can specify the following values: STRING - The range key is a string. NUMBER - The range key is number. If you don't specify rangeKeyField, the default value is STRING. public let rangeKeyType: String? /// The value of the range key (also called the sort key). public let rangeKeyValue: String? /// The name of the DynamoDB table. public let tableName: String public init(hashKeyField: String, hashKeyType: String? = nil, hashKeyValue: String, operation: String? = nil, payload: Payload? = nil, payloadField: String? = nil, rangeKeyField: String? = nil, rangeKeyType: String? = nil, rangeKeyValue: String? = nil, tableName: String) { self.hashKeyField = hashKeyField self.hashKeyType = hashKeyType self.hashKeyValue = hashKeyValue self.operation = operation self.payload = payload self.payloadField = payloadField self.rangeKeyField = rangeKeyField self.rangeKeyType = rangeKeyType self.rangeKeyValue = rangeKeyValue self.tableName = tableName } public func validate(name: String) throws { try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case hashKeyField case hashKeyType case hashKeyValue case operation case payload case payloadField case rangeKeyField case rangeKeyType case rangeKeyValue case tableName } } public struct DynamoDBv2Action: AWSEncodableShape & AWSDecodableShape { public let payload: Payload? /// The name of the DynamoDB table. public let tableName: String public init(payload: Payload? = nil, tableName: String) { self.payload = payload self.tableName = tableName } public func validate(name: String) throws { try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case payload case tableName } } public struct Event: AWSEncodableShape & AWSDecodableShape { /// The actions to be performed. public let actions: [Action]? /// Optional. The Boolean expression that, when TRUE, causes the actions to be performed. If not present, the actions are performed (=TRUE). If the expression result is not a Boolean value, the actions are not performed (=FALSE). public let condition: String? /// The name of the event. public let eventName: String public init(actions: [Action]? = nil, condition: String? = nil, eventName: String) { self.actions = actions self.condition = condition self.eventName = eventName } public func validate(name: String) throws { try self.actions?.forEach { try $0.validate(name: "\(name).actions[]") } try self.validate(self.condition, name: "condition", parent: name, max: 512) try self.validate(self.eventName, name: "eventName", parent: name, max: 128) } private enum CodingKeys: String, CodingKey { case actions case condition case eventName } } public struct FirehoseAction: AWSEncodableShape & AWSDecodableShape { /// The name of the Kinesis Data Firehose delivery stream where the data is written. public let deliveryStreamName: String /// You can configure the action payload when you send a message to an Amazon Kinesis Data Firehose delivery stream. public let payload: Payload? /// A character separator that is used to separate records written to the Kinesis Data Firehose delivery stream. Valid values are: '\n' (newline), '\t' (tab), '\r\n' (Windows newline), ',' (comma). public let separator: String? public init(deliveryStreamName: String, payload: Payload? = nil, separator: String? = nil) { self.deliveryStreamName = deliveryStreamName self.payload = payload self.separator = separator } public func validate(name: String) throws { try self.payload?.validate(name: "\(name).payload") try self.validate(self.separator, name: "separator", parent: name, pattern: "([\\n\\t])|(\\r\\n)|(,)") } private enum CodingKeys: String, CodingKey { case deliveryStreamName case payload case separator } } public struct Input: AWSDecodableShape { /// Information about the configuration of an input. public let inputConfiguration: InputConfiguration? /// The definition of the input. public let inputDefinition: InputDefinition? public init(inputConfiguration: InputConfiguration? = nil, inputDefinition: InputDefinition? = nil) { self.inputConfiguration = inputConfiguration self.inputDefinition = inputDefinition } private enum CodingKeys: String, CodingKey { case inputConfiguration case inputDefinition } } public struct InputConfiguration: AWSDecodableShape { /// The time the input was created. public let creationTime: Date /// The ARN of the input. public let inputArn: String /// A brief description of the input. public let inputDescription: String? /// The name of the input. public let inputName: String /// The last time the input was updated. public let lastUpdateTime: Date /// The status of the input. public let status: InputStatus public init(creationTime: Date, inputArn: String, inputDescription: String? = nil, inputName: String, lastUpdateTime: Date, status: InputStatus) { self.creationTime = creationTime self.inputArn = inputArn self.inputDescription = inputDescription self.inputName = inputName self.lastUpdateTime = lastUpdateTime self.status = status } private enum CodingKeys: String, CodingKey { case creationTime case inputArn case inputDescription case inputName case lastUpdateTime case status } } public struct InputDefinition: AWSEncodableShape & AWSDecodableShape { /// The attributes from the JSON payload that are made available by the input. Inputs are derived from messages sent to the AWS IoT Events system using BatchPutMessage. Each such message contains a JSON payload, and those attributes (and their paired values) specified here are available for use in the condition expressions used by detectors that monitor this input. public let attributes: [Attribute] public init(attributes: [Attribute]) { self.attributes = attributes } public func validate(name: String) throws { try self.attributes.forEach { try $0.validate(name: "\(name).attributes[]") } try self.validate(self.attributes, name: "attributes", parent: name, max: 200) try self.validate(self.attributes, name: "attributes", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case attributes } } public struct InputSummary: AWSDecodableShape { /// The time the input was created. public let creationTime: Date? /// The ARN of the input. public let inputArn: String? /// A brief description of the input. public let inputDescription: String? /// The name of the input. public let inputName: String? /// The last time the input was updated. public let lastUpdateTime: Date? /// The status of the input. public let status: InputStatus? public init(creationTime: Date? = nil, inputArn: String? = nil, inputDescription: String? = nil, inputName: String? = nil, lastUpdateTime: Date? = nil, status: InputStatus? = nil) { self.creationTime = creationTime self.inputArn = inputArn self.inputDescription = inputDescription self.inputName = inputName self.lastUpdateTime = lastUpdateTime self.status = status } private enum CodingKeys: String, CodingKey { case creationTime case inputArn case inputDescription case inputName case lastUpdateTime case status } } public struct IotEventsAction: AWSEncodableShape & AWSDecodableShape { /// The name of the AWS IoT Events input where the data is sent. public let inputName: String /// You can configure the action payload when you send a message to an AWS IoT Events input. public let payload: Payload? public init(inputName: String, payload: Payload? = nil) { self.inputName = inputName self.payload = payload } public func validate(name: String) throws { try self.validate(self.inputName, name: "inputName", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, min: 1) try self.validate(self.inputName, name: "inputName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case inputName case payload } } public struct IotSiteWiseAction: AWSEncodableShape & AWSDecodableShape { /// The ID of the asset that has the specified property. You can specify an expression. public let assetId: String? /// A unique identifier for this entry. You can use the entry ID to track which data entry causes an error in case of failure. The default is a new unique identifier. You can also specify an expression. public let entryId: String? /// The alias of the asset property. You can also specify an expression. public let propertyAlias: String? /// The ID of the asset property. You can specify an expression. public let propertyId: String? /// The value to send to the asset property. This value contains timestamp, quality, and value (TQV) information. public let propertyValue: AssetPropertyValue public init(assetId: String? = nil, entryId: String? = nil, propertyAlias: String? = nil, propertyId: String? = nil, propertyValue: AssetPropertyValue) { self.assetId = assetId self.entryId = entryId self.propertyAlias = propertyAlias self.propertyId = propertyId self.propertyValue = propertyValue } private enum CodingKeys: String, CodingKey { case assetId case entryId case propertyAlias case propertyId case propertyValue } } public struct IotTopicPublishAction: AWSEncodableShape & AWSDecodableShape { /// The MQTT topic of the message. You can use a string expression that includes variables ($variable.&lt;variable-name&gt;) and input values ($input.&lt;input-name&gt;.&lt;path-to-datum&gt;) as the topic string. public let mqttTopic: String /// You can configure the action payload when you publish a message to an AWS IoT Core topic. public let payload: Payload? public init(mqttTopic: String, payload: Payload? = nil) { self.mqttTopic = mqttTopic self.payload = payload } public func validate(name: String) throws { try self.validate(self.mqttTopic, name: "mqttTopic", parent: name, max: 128) try self.validate(self.mqttTopic, name: "mqttTopic", parent: name, min: 1) try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case mqttTopic case payload } } public struct LambdaAction: AWSEncodableShape & AWSDecodableShape { /// The ARN of the Lambda function that is executed. public let functionArn: String /// You can configure the action payload when you send a message to a Lambda function. public let payload: Payload? public init(functionArn: String, payload: Payload? = nil) { self.functionArn = functionArn self.payload = payload } public func validate(name: String) throws { try self.validate(self.functionArn, name: "functionArn", parent: name, max: 2048) try self.validate(self.functionArn, name: "functionArn", parent: name, min: 1) try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case functionArn case payload } } public struct ListDetectorModelVersionsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "detectorModelName", location: .uri(locationName: "detectorModelName")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The name of the detector model whose versions are returned. public let detectorModelName: String /// The maximum number of results to return at one time. public let maxResults: Int? /// The token for the next set of results. public let nextToken: String? public init(detectorModelName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.detectorModelName = detectorModelName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 250) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListDetectorModelVersionsResponse: AWSDecodableShape { /// Summary information about the detector model versions. public let detectorModelVersionSummaries: [DetectorModelVersionSummary]? /// A token to retrieve the next set of results, or null if there are no additional results. public let nextToken: String? public init(detectorModelVersionSummaries: [DetectorModelVersionSummary]? = nil, nextToken: String? = nil) { self.detectorModelVersionSummaries = detectorModelVersionSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case detectorModelVersionSummaries case nextToken } } public struct ListDetectorModelsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The maximum number of results to return at one time. public let maxResults: Int? /// The token for the next set of results. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 250) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListDetectorModelsResponse: AWSDecodableShape { /// Summary information about the detector models. public let detectorModelSummaries: [DetectorModelSummary]? /// A token to retrieve the next set of results, or null if there are no additional results. public let nextToken: String? public init(detectorModelSummaries: [DetectorModelSummary]? = nil, nextToken: String? = nil) { self.detectorModelSummaries = detectorModelSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case detectorModelSummaries case nextToken } } public struct ListInputsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The maximum number of results to return at one time. public let maxResults: Int? /// The token for the next set of results. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 250) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListInputsResponse: AWSDecodableShape { /// Summary information about the inputs. public let inputSummaries: [InputSummary]? /// A token to retrieve the next set of results, or null if there are no additional results. public let nextToken: String? public init(inputSummaries: [InputSummary]? = nil, nextToken: String? = nil) { self.inputSummaries = inputSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case inputSummaries case nextToken } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .querystring(locationName: "resourceArn")) ] /// The ARN of the resource. public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { /// The list of tags assigned to the resource. public let tags: [Tag]? public init(tags: [Tag]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct LoggingOptions: AWSEncodableShape & AWSDecodableShape { /// Information that identifies those detector models and their detectors (instances) for which the logging level is given. public let detectorDebugOptions: [DetectorDebugOption]? /// If TRUE, logging is enabled for AWS IoT Events. public let enabled: Bool /// The logging level. public let level: LoggingLevel /// The ARN of the role that grants permission to AWS IoT Events to perform logging. public let roleArn: String public init(detectorDebugOptions: [DetectorDebugOption]? = nil, enabled: Bool, level: LoggingLevel, roleArn: String) { self.detectorDebugOptions = detectorDebugOptions self.enabled = enabled self.level = level self.roleArn = roleArn } public func validate(name: String) throws { try self.detectorDebugOptions?.forEach { try $0.validate(name: "\(name).detectorDebugOptions[]") } try self.validate(self.detectorDebugOptions, name: "detectorDebugOptions", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case detectorDebugOptions case enabled case level case roleArn } } public struct OnEnterLifecycle: AWSEncodableShape & AWSDecodableShape { /// Specifies the actions that are performed when the state is entered and the condition is TRUE. public let events: [Event]? public init(events: [Event]? = nil) { self.events = events } public func validate(name: String) throws { try self.events?.forEach { try $0.validate(name: "\(name).events[]") } } private enum CodingKeys: String, CodingKey { case events } } public struct OnExitLifecycle: AWSEncodableShape & AWSDecodableShape { /// Specifies the actions that are performed when the state is exited and the condition is TRUE. public let events: [Event]? public init(events: [Event]? = nil) { self.events = events } public func validate(name: String) throws { try self.events?.forEach { try $0.validate(name: "\(name).events[]") } } private enum CodingKeys: String, CodingKey { case events } } public struct OnInputLifecycle: AWSEncodableShape & AWSDecodableShape { /// Specifies the actions performed when the condition evaluates to TRUE. public let events: [Event]? /// Specifies the actions performed, and the next state entered, when a condition evaluates to TRUE. public let transitionEvents: [TransitionEvent]? public init(events: [Event]? = nil, transitionEvents: [TransitionEvent]? = nil) { self.events = events self.transitionEvents = transitionEvents } public func validate(name: String) throws { try self.events?.forEach { try $0.validate(name: "\(name).events[]") } try self.transitionEvents?.forEach { try $0.validate(name: "\(name).transitionEvents[]") } } private enum CodingKeys: String, CodingKey { case events case transitionEvents } } public struct Payload: AWSEncodableShape & AWSDecodableShape { /// The content of the payload. You can use a string expression that includes quoted strings ('&lt;string&gt;'), variables ($variable.&lt;variable-name&gt;), input values ($input.&lt;input-name&gt;.&lt;path-to-datum&gt;), string concatenations, and quoted strings that contain ${} as the content. The recommended maximum size of a content expression is 1 KB. public let contentExpression: String /// The value of the payload type can be either STRING or JSON. public let type: PayloadType public init(contentExpression: String, type: PayloadType) { self.contentExpression = contentExpression self.type = type } public func validate(name: String) throws { try self.validate(self.contentExpression, name: "contentExpression", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case contentExpression case type } } public struct PutLoggingOptionsRequest: AWSEncodableShape { /// The new values of the AWS IoT Events logging options. public let loggingOptions: LoggingOptions public init(loggingOptions: LoggingOptions) { self.loggingOptions = loggingOptions } public func validate(name: String) throws { try self.loggingOptions.validate(name: "\(name).loggingOptions") } private enum CodingKeys: String, CodingKey { case loggingOptions } } public struct ResetTimerAction: AWSEncodableShape & AWSDecodableShape { /// The name of the timer to reset. public let timerName: String public init(timerName: String) { self.timerName = timerName } public func validate(name: String) throws { try self.validate(self.timerName, name: "timerName", parent: name, max: 128) try self.validate(self.timerName, name: "timerName", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case timerName } } public struct SNSTopicPublishAction: AWSEncodableShape & AWSDecodableShape { /// You can configure the action payload when you send a message as an Amazon SNS push notification. public let payload: Payload? /// The ARN of the Amazon SNS target where the message is sent. public let targetArn: String public init(payload: Payload? = nil, targetArn: String) { self.payload = payload self.targetArn = targetArn } public func validate(name: String) throws { try self.payload?.validate(name: "\(name).payload") try self.validate(self.targetArn, name: "targetArn", parent: name, max: 2048) try self.validate(self.targetArn, name: "targetArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case payload case targetArn } } public struct SetTimerAction: AWSEncodableShape & AWSDecodableShape { /// The duration of the timer, in seconds. You can use a string expression that includes numbers, variables ($variable.&lt;variable-name&gt;), and input values ($input.&lt;input-name&gt;.&lt;path-to-datum&gt;) as the duration. The range of the duration is 1-31622400 seconds. To ensure accuracy, the minimum duration is 60 seconds. The evaluated result of the duration is rounded down to the nearest whole number. public let durationExpression: String? /// The name of the timer. public let timerName: String public init(durationExpression: String? = nil, timerName: String) { self.durationExpression = durationExpression self.timerName = timerName } public func validate(name: String) throws { try self.validate(self.durationExpression, name: "durationExpression", parent: name, max: 1024) try self.validate(self.durationExpression, name: "durationExpression", parent: name, min: 1) try self.validate(self.timerName, name: "timerName", parent: name, max: 128) try self.validate(self.timerName, name: "timerName", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case durationExpression case timerName } } public struct SetVariableAction: AWSEncodableShape & AWSDecodableShape { /// The new value of the variable. public let value: String /// The name of the variable. public let variableName: String public init(value: String, variableName: String) { self.value = value self.variableName = variableName } public func validate(name: String) throws { try self.validate(self.value, name: "value", parent: name, max: 1024) try self.validate(self.value, name: "value", parent: name, min: 1) try self.validate(self.variableName, name: "variableName", parent: name, max: 128) try self.validate(self.variableName, name: "variableName", parent: name, min: 1) try self.validate(self.variableName, name: "variableName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: String, CodingKey { case value case variableName } } public struct SqsAction: AWSEncodableShape & AWSDecodableShape { /// You can configure the action payload when you send a message to an Amazon SQS queue. public let payload: Payload? /// The URL of the SQS queue where the data is written. public let queueUrl: String /// Set this to TRUE if you want the data to be base-64 encoded before it is written to the queue. Otherwise, set this to FALSE. public let useBase64: Bool? public init(payload: Payload? = nil, queueUrl: String, useBase64: Bool? = nil) { self.payload = payload self.queueUrl = queueUrl self.useBase64 = useBase64 } public func validate(name: String) throws { try self.payload?.validate(name: "\(name).payload") } private enum CodingKeys: String, CodingKey { case payload case queueUrl case useBase64 } } public struct State: AWSEncodableShape & AWSDecodableShape { /// When entering this state, perform these actions if the condition is TRUE. public let onEnter: OnEnterLifecycle? /// When exiting this state, perform these actions if the specified condition is TRUE. public let onExit: OnExitLifecycle? /// When an input is received and the condition is TRUE, perform the specified actions. public let onInput: OnInputLifecycle? /// The name of the state. public let stateName: String public init(onEnter: OnEnterLifecycle? = nil, onExit: OnExitLifecycle? = nil, onInput: OnInputLifecycle? = nil, stateName: String) { self.onEnter = onEnter self.onExit = onExit self.onInput = onInput self.stateName = stateName } public func validate(name: String) throws { try self.onEnter?.validate(name: "\(name).onEnter") try self.onExit?.validate(name: "\(name).onExit") try self.onInput?.validate(name: "\(name).onInput") try self.validate(self.stateName, name: "stateName", parent: name, max: 128) try self.validate(self.stateName, name: "stateName", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case onEnter case onExit case onInput case stateName } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// The tag's key. public let key: String /// The tag's value. public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.value, name: "value", parent: name, max: 256) try self.validate(self.value, name: "value", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case key case value } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .querystring(locationName: "resourceArn")) ] /// The ARN of the resource. public let resourceArn: String /// The new or modified tags for the resource. public let tags: [Tag] public init(resourceArn: String, tags: [Tag]) { self.resourceArn = resourceArn self.tags = tags } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.tags.forEach { try $0.validate(name: "\(name).tags[]") } } private enum CodingKeys: String, CodingKey { case tags } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct TransitionEvent: AWSEncodableShape & AWSDecodableShape { /// The actions to be performed. public let actions: [Action]? /// Required. A Boolean expression that when TRUE causes the actions to be performed and the nextState to be entered. public let condition: String /// The name of the transition event. public let eventName: String /// The next state to enter. public let nextState: String public init(actions: [Action]? = nil, condition: String, eventName: String, nextState: String) { self.actions = actions self.condition = condition self.eventName = eventName self.nextState = nextState } public func validate(name: String) throws { try self.actions?.forEach { try $0.validate(name: "\(name).actions[]") } try self.validate(self.condition, name: "condition", parent: name, max: 512) try self.validate(self.eventName, name: "eventName", parent: name, max: 128) try self.validate(self.nextState, name: "nextState", parent: name, max: 128) try self.validate(self.nextState, name: "nextState", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case actions case condition case eventName case nextState } } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .querystring(locationName: "resourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] /// The ARN of the resource. public let resourceArn: String /// A list of the keys of the tags to be removed from the resource. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) } } private enum CodingKeys: CodingKey {} } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } public struct UpdateDetectorModelRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "detectorModelName", location: .uri(locationName: "detectorModelName")) ] /// Information that defines how a detector operates. public let detectorModelDefinition: DetectorModelDefinition /// A brief description of the detector model. public let detectorModelDescription: String? /// The name of the detector model that is updated. public let detectorModelName: String /// Information about the order in which events are evaluated and how actions are executed. public let evaluationMethod: EvaluationMethod? /// The ARN of the role that grants permission to AWS IoT Events to perform its operations. public let roleArn: String public init(detectorModelDefinition: DetectorModelDefinition, detectorModelDescription: String? = nil, detectorModelName: String, evaluationMethod: EvaluationMethod? = nil, roleArn: String) { self.detectorModelDefinition = detectorModelDefinition self.detectorModelDescription = detectorModelDescription self.detectorModelName = detectorModelName self.evaluationMethod = evaluationMethod self.roleArn = roleArn } public func validate(name: String) throws { try self.detectorModelDefinition.validate(name: "\(name).detectorModelDefinition") try self.validate(self.detectorModelDescription, name: "detectorModelDescription", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, max: 128) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, min: 1) try self.validate(self.detectorModelName, name: "detectorModelName", parent: name, pattern: "^[a-zA-Z0-9_-]+$") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case detectorModelDefinition case detectorModelDescription case evaluationMethod case roleArn } } public struct UpdateDetectorModelResponse: AWSDecodableShape { /// Information about how the detector model is configured. public let detectorModelConfiguration: DetectorModelConfiguration? public init(detectorModelConfiguration: DetectorModelConfiguration? = nil) { self.detectorModelConfiguration = detectorModelConfiguration } private enum CodingKeys: String, CodingKey { case detectorModelConfiguration } } public struct UpdateInputRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "inputName", location: .uri(locationName: "inputName")) ] /// The definition of the input. public let inputDefinition: InputDefinition /// A brief description of the input. public let inputDescription: String? /// The name of the input you want to update. public let inputName: String public init(inputDefinition: InputDefinition, inputDescription: String? = nil, inputName: String) { self.inputDefinition = inputDefinition self.inputDescription = inputDescription self.inputName = inputName } public func validate(name: String) throws { try self.inputDefinition.validate(name: "\(name).inputDefinition") try self.validate(self.inputDescription, name: "inputDescription", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, max: 128) try self.validate(self.inputName, name: "inputName", parent: name, min: 1) try self.validate(self.inputName, name: "inputName", parent: name, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$") } private enum CodingKeys: String, CodingKey { case inputDefinition case inputDescription } } public struct UpdateInputResponse: AWSDecodableShape { /// Information about the configuration of the input. public let inputConfiguration: InputConfiguration? public init(inputConfiguration: InputConfiguration? = nil) { self.inputConfiguration = inputConfiguration } private enum CodingKeys: String, CodingKey { case inputConfiguration } } }
apache-2.0
6fb696382193dd93420fb3feccb187bc
43.135603
769
0.639931
5.024687
false
false
false
false
timestocome/DirectionOrientation
DeviceMotionViewController.swift
1
6886
// // DeviceMotionViewController.swift // Sensors // // Created by Linda Cobb on 9/22/14. // Copyright (c) 2014 TimesToCome Mobile. All rights reserved. // import Foundation import UIKit import CoreMotion // rotation with bias removed along x, y, z // calibrated magnetic field minus device's magnetic field - earth's field plus surrounding fields gives total magnetic field // attitude - orientation of device in space // gravity - acceleration in device's reference frame - earth's gravity plue device acceleration // user acceleration - gravity plus device acceleration class DeviceMotionViewController: UIViewController { @IBOutlet var xLabel: UILabel! @IBOutlet var yLabel: UILabel! @IBOutlet var zLabel: UILabel! @IBOutlet var updateIntervalSlider: UISlider! @IBOutlet var updateIntervalLabel: UILabel! @IBOutlet var scaleSlider: UISlider! @IBOutlet var scaleLabel: UILabel! @IBOutlet var stopButton: UIButton! @IBOutlet var startButton: UIButton! @IBOutlet var segmentedControl: UISegmentedControl! var motionType = 0 // attitude, rotation rate, device acceleration, magnetic field var motionManager: CMMotionManager! var stopUpdates = false required init( coder aDecoder: NSCoder ){ super.init(coder: aDecoder) } convenience override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { self.init(nibName: nil, bundle: nil) } convenience override init() { self.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate motionManager = appDelegate.sharedManager updateIntervalSlider.value = 10.0 updateIntervalLabel.text = NSString(format: "%.0lf", updateIntervalSlider.value) scaleSlider.value = 1.0 scaleLabel.text = NSString(format: "%.1lf", scaleSlider.value) } @IBAction func selectionChanged(sender: UISegmentedControl) { motionType = segmentedControl.selectedSegmentIndex startUpdatesWithSliderValue(updateIntervalSlider.value) } @IBAction func intervalChanged(sender: UISlider){ let interval = Int(sender.value) updateIntervalLabel.text = NSString(format: "%.0lf", updateIntervalSlider.value) startUpdatesWithSliderValue(updateIntervalSlider.value) } @IBAction func scaleChanged(sender: UISlider){ let scale = sender.value scaleLabel.text = NSString(format: "%.0lf", scale) } @IBAction func stop(){ stopUpdates = true } @IBAction func start(){ stopUpdates = false startUpdatesWithSliderValue(updateIntervalSlider.value) } func startUpdatesWithSliderValue(sliderValue: NSNumber){ let updateInterval = 1.0/Double(updateIntervalSlider.value) as NSTimeInterval motionManager.deviceMotionUpdateInterval = updateInterval let dataQueue = NSOperationQueue() if motionType < 3 { motionManager.startDeviceMotionUpdatesToQueue(dataQueue, withHandler: { data, error in NSOperationQueue.mainQueue().addOperationWithBlock({ if self.motionType == 0 { // attitude in degrees // update labels self.xLabel.text = NSString(format: "Roll: %.6lf' ", data.attitude.roll * 57.2957795) self.yLabel.text = NSString(format: "Pitch: %.6lf' ", data.attitude.pitch * 57.2957795) self.zLabel.text = NSString(format: "Yaw: %.6lf' ", data.attitude.yaw * 57.2956695) }else if self.motionType == 1 { // rotation rate // update labels self.xLabel.text = NSString(format: "RotX: %.6lf' ", data.rotationRate.x * 57.2957795) self.yLabel.text = NSString(format: "RotY: %.6lf' ", data.rotationRate.y * 57.2957795) self.zLabel.text = NSString(format: "RotZ: %.6lf' ", data.rotationRate.z * 57.2956695) }else if self.motionType == 2 { // user accel // update labels self.xLabel.text = NSString(format: "Acc x: %.6lf g", data.gravity.x) self.yLabel.text = NSString(format: "Acc y: %.6lf g", data.gravity.y) self.zLabel.text = NSString(format: "Acc z: %.6lf g", data.gravity.z) } if ( self.stopUpdates ){ self.motionManager.stopDeviceMotionUpdates() NSOperationQueue.mainQueue().cancelAllOperations() } }) }) }else if motionType == 3 { // magnetic field motionManager.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrameXTrueNorthZVertical, toQueue: dataQueue, withHandler: { data, error in NSOperationQueue.mainQueue().addOperationWithBlock({ // update labels self.xLabel.text = NSString(format: "X: %.6lf mTesla", data.magneticField.field.x) self.yLabel.text = NSString(format: "Y: %.6lf mTesla", data.magneticField.field.y) self.zLabel.text = NSString(format: "Z: %.6lf mTesla", data.magneticField.field.z) if ( self.stopUpdates ){ self.motionManager.stopDeviceMotionUpdates() NSOperationQueue.mainQueue().cancelAllOperations() } }) }) } } override func viewDidDisappear(animated: Bool){ super.viewDidDisappear(animated) stop() } }
mit
dc75c7ca2c68b7b045082548e73ba5b4
30.737327
149
0.525414
5.630417
false
false
false
false
barteljan/VISPER
VISPER-Wireframe/Classes/RoutingOptions/RoutingOptionBackTo.swift
1
638
// // RoutingOptionBackTo.swift // VISPER-Wireframe // // Created by bartel on 28.12.17. // import Foundation import VISPER_Core public protocol RoutingOptionBackTo: AnimatedRoutingOption { } public struct DefaultRoutingBackTo: RoutingOptionBackTo { public let animated: Bool public init(animated: Bool = true) { self.animated = animated } public func isEqual(otherOption: RoutingOption?) -> Bool { guard let otherOption = otherOption as? RoutingOptionBackTo else { return false } return self.animated == otherOption.animated } }
mit
21094bb4ff534aa9088eab2de04b3aff
19.580645
74
0.648903
4.310811
false
false
false
false
Ryan-Vanderhoef/Antlers
AppIdea/Frameworks/Bond/Bond/Bond+UIProgressView.swift
1
1997
// // Bond+UIProgressView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit private var progressDynamicHandleUIProgressView: UInt8 = 0; extension UIProgressView: Bondable { public var dynProgress: Dynamic<Float> { if let d: AnyObject = objc_getAssociatedObject(self, &progressDynamicHandleUIProgressView) { return (d as? Dynamic<Float>)! } else { let d = InternalDynamic<Float>(self.progress, faulty: false) let bond = Bond<Float>() { [weak self] v in if let s = self { s.progress = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &progressDynamicHandleUIProgressView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } public var designatedBond: Bond<Float> { return self.dynProgress.valueBond } }
mit
b9b97d52d5790148c3691e8e4ef4fd13
39.755102
136
0.72659
4.195378
false
false
false
false
wistia/WistiaKit
Pod/Classes/Playback/public/WistiaFlatPlayerView.swift
1
1050
// // WistiaFlatPlayerView.swift // WistiaKit // // Created by Daniel Spinosa on 11/15/15. // Copyright © 2016 Wistia, Inc. All rights reserved. // // A View backed by an AVPlayerLayer. // // Set the wistiaPlayer and this view will pass its AVPlayer through to the backing AVPlayerLayer. // import UIKit import AVKit import AVFoundation public class WistiaFlatPlayerView: UIView { private var detachedAVPlayer: AVPlayer? override public class var layerClass: AnyClass { get { return AVPlayerLayer.self } } public var wistiaPlayer:WistiaPlayer? { didSet { (self.layer as! AVPlayerLayer).player = wistiaPlayer?.avPlayer } } public func prepareForBackgroundPlayback() { let playerLayer = layer as! AVPlayerLayer detachedAVPlayer = playerLayer.player playerLayer.player = nil } public func returnToForegroundPlayback() { (layer as! AVPlayerLayer).player = detachedAVPlayer detachedAVPlayer = nil } }
mit
711aebea0a3168534f7ece01e565269e
23.395349
99
0.666349
4.482906
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTSystemID.swift
1
5292
// // GATTSystemID.swift // Bluetooth // // Created by Carlos Duclos on 6/21/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** System ID The SYSTEM ID characteristic consists of a structure with two fields. The first field are the LSOs and the second field contains the MSOs. This is a 64-bit structure which consists of a 40-bit manufacturer-defined identifier concatenated with a 24 bit unique Organizationally Unique Identifier (OUI). The OUI is issued by the [IEEE Registration Authority](http://standards.ieee.org/regauth/index.html) and is required to be used in accordance with IEEE Standard 802-2001.6 while the least significant 40 bits are manufacturer defined. [System ID](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.system_id.xml) */ @frozen public struct GATTSystemID: GATTCharacteristic, RawRepresentable, Equatable, Hashable { public static var uuid: BluetoothUUID { return .systemId } internal static let length = MemoryLayout<UInt64>.size public var rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } public init(manufacturerIdentifier: UInt40, organizationallyUniqueIdentifier: UInt24) { let manufacturerIdentifierBytes = manufacturerIdentifier.bigEndian.bytes let organizationallyUniqueIdentifierBytes = organizationallyUniqueIdentifier.bigEndian.bytes self.rawValue = UInt64(bigEndian: UInt64(bytes: (organizationallyUniqueIdentifierBytes.0, organizationallyUniqueIdentifierBytes.1, organizationallyUniqueIdentifierBytes.2, manufacturerIdentifierBytes.0, manufacturerIdentifierBytes.1, manufacturerIdentifierBytes.2, manufacturerIdentifierBytes.3, manufacturerIdentifierBytes.4 ))) } public var manufacturerIdentifier: UInt40 { let bytes = rawValue.bigEndian.bytes return UInt40(bigEndian: UInt40(bytes: (bytes.3, bytes.4, bytes.5, bytes.6, bytes.7))) } public var organizationallyUniqueIdentifier: UInt24 { let bytes = rawValue.bigEndian.bytes return UInt24(bigEndian: UInt24(bytes: (bytes.0, bytes.1, bytes.2))) } /// Initialize a System ID based on a Bluetooth Device Address. public init(address: BluetoothAddress) { /** If System ID generated based on a Bluetooth Device Address, it is required to be done as follows. System ID and the Bluetooth Device Address have a very similar structure: a Bluetooth Device Address is 48 bits in length and consists of a 24 bit Company Assigned Identifier (manufacturer defined identifier) concatenated with a 24 bit Company Identifier (OUI). In order to encapsulate a Bluetooth Device Address as System ID, the Company Identifier is concatenated with 0xFFFE followed by the Company Assigned Identifier of the Bluetooth Address. Example: If the system ID is based of a Bluetooth Device Address with a Company Identifier (OUI) is 0x123456 and the Company Assigned Identifier is 0x9ABCDE, then the System Identifier is required to be 0x123456FFFE9ABCDE */ let manufacturerIdentifierPrefix = UInt16(0xFFFE).bigEndian.bytes let addressBytes = address.bigEndian.bytes self.rawValue = UInt64(bigEndian: UInt64(bytes: (addressBytes.0, addressBytes.1, addressBytes.2, manufacturerIdentifierPrefix.0, manufacturerIdentifierPrefix.1, addressBytes.3, addressBytes.4, addressBytes.5))) } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let rawValue = UInt64(littleEndian: UInt64(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]))) self.init(rawValue: rawValue) } public var data: Data { let bytes = rawValue.littleEndian.bytes return Data([ bytes.0, bytes.1, bytes.2, bytes.3, bytes.4, bytes.5, bytes.6, bytes.7 ]) } } // MARK: - CustomStringConvertible extension GATTSystemID: CustomStringConvertible { public var description: String { return rawValue.toHexadecimal() } }
mit
e533c6920b57f969de2ee051e490e0d3
42.01626
554
0.57664
5.540314
false
false
false
false
DarielChen/DemoCode
iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/1.cook/3.Cook/Cook/PopAnimator.swift
1
3320
// // PopAnimator.swift // Cook // // Created by Dariel on 16/7/25. // Copyright © 2016年 Dariel. All rights reserved. // import UIKit // 转场动画的原理: /** 当两个控制器发生push或dismiss的时候,系统会把原始的view放到负责转场的控制器容器中,也会把目的的view也放进去,但是是不可见的,因此我们要做的就是把新的view显现出来,把老的view移除掉 */ // 遵守协议 class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning { let duration = 0.5 var presenting = true var originFrame = CGRect.zero var dismissCompletion: (()->())? // 动画持续时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } // func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 获得容器 let containerView = transitionContext.containerView()! // 获得目标view // viewForKey 获取新的和老的控制器的view // viewControllerForKey 获取新的和老的控制器 let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! // 一直是需要做动画的view let herbView = presenting ? toView : fromView // 获取初始和最终的frame let initialFrame = presenting ? originFrame : herbView.frame let finalFrame = presenting ? herbView.frame : originFrame // 设置缩放比率 let xScaleFactor = presenting ? initialFrame.width / finalFrame.width : finalFrame.width / initialFrame.width let yScaleFactor = presenting ? initialFrame.height / finalFrame.height : finalFrame.height / initialFrame.height let scaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor) if presenting { herbView.transform = scaleTransform herbView.center = CGPoint(x: CGRectGetMidX(initialFrame), y: CGRectGetMidY(initialFrame)) herbView.clipsToBounds = true } containerView.addSubview(toView) containerView.bringSubviewToFront(herbView) UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in herbView.transform = self.presenting ? CGAffineTransformIdentity : scaleTransform herbView.center = CGPoint(x: CGRectGetMidX(finalFrame), y: CGRectGetMidY(finalFrame)) }) { (_) -> Void in if !self.presenting { self.dismissCompletion?() } transitionContext.completeTransition(true) } // 设置圆角 let round = CABasicAnimation(keyPath: "cornerRadius") round.fromValue = !presenting ? 0.0 : 20.0/xScaleFactor round.toValue = presenting ? 0.0 : 20.0/xScaleFactor round.duration = duration / 2 herbView.layer.addAnimation(round, forKey: nil) herbView.layer.cornerRadius = presenting ? 0.0 : 20.0/xScaleFactor } }
mit
db9f6dec8964d5a0c50ed2974af2589a
33.816092
152
0.645097
5.133898
false
false
false
false
apple/swift-syntax
Sources/SwiftParser/Directives.swift
1
8215
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension Parser { /// Parse a conditional compilation block. /// /// This function should be used to parse conditional compilation statements, /// declarations, and expressions. It is generic over the particular kind of /// parse that must occur for these elements, and allows a context-specific /// syntax kind to be emitted to collect the results. For example, declaration /// parsing parses items and collects the items into a `MemberDeclListSyntax` /// node. /// /// Grammar /// ======= /// /// conditional-compilation-block → if-directive-clause elseif-directive-clauses? else-directive-clause? endif-directive /// /// if-directive-clause → if-directive compilation-condition statements? /// elseif-directive-clauses → elseif-directive-clause elseif-directive-clauses? /// elseif-directive-clause → elseif-directive compilation-condition statements? /// else-directive-clause → else-directive statements? /// if-directive → '#if' /// elseif-directive → '#elseif' /// else-directive → '#else' /// endif-directive → '#endif' /// /// compilation-condition → platform-condition /// compilation-condition → identifier /// compilation-condition → boolean-literal /// compilation-condition → '(' compilation-condition ')' /// compilation-condition → '!' compilation-condition /// compilation-condition → compilation-condition '&&' compilation-condition /// compilation-condition → compilation-condition '||' compilation-condition /// /// platform-condition → 'os' '(' operating-system ')' /// platform-condition → 'arch' '(' architecture ')' /// platform-condition → 'swift' '(' '>=' swift-version ')' | 'swift' ( < swift-version ) /// platform-condition → 'compiler' '(' '>=' swift-version ')' | 'compiler' ( < swift-version ) /// platform-condition → 'canImport' '(' import-path ')' /// platform-condition → 'targetEnvironment' '(' environment ')' /// /// operating-system → 'macOS' | 'iOS' | 'watchOS' | 'tvOS' | 'Linux' | 'Windows' /// architecture → 'i386' | 'x86_64' | 'arm' | 'arm64' /// swift-version → decimal-digits swift-version-continuation? /// swift-version-continuation → '.' decimal-digits swift-version-continuation? /// environment → 'simulator' | 'macCatalyst' /// /// - Parameters: /// - parseElement: Parse an element of the conditional compilation block. /// - addSemicolonIfNeeded: If elements need to be separated by a newline, this /// allows the insertion of missing semicolons to the /// previous element. /// - syntax: A function that aggregates the parsed conditional elements /// into a syntax collection. @_spi(RawSyntax) public mutating func parsePoundIfDirective<Element: RawSyntaxNodeProtocol>( _ parseElement: (inout Parser) -> Element?, addSemicolonIfNeeded: (_ lastElement: Element, _ newItemAtStartOfLine: Bool, _ parser: inout Parser) -> Element? = { _, _, _ in nil }, syntax: (inout Parser, [Element]) -> RawIfConfigClauseSyntax.Elements? ) -> RawIfConfigDeclSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawIfConfigDeclSyntax( remainingTokens, clauses: RawIfConfigClauseListSyntax(elements: [], arena: self.arena), poundEndif: missingToken(.poundEndifKeyword), arena: self.arena ) } var clauses = [RawIfConfigClauseSyntax]() do { var firstIteration = true var loopProgress = LoopProgressCondition() while let poundIfHandle = self.canRecoverTo(any: firstIteration ? [.poundIfKeyword] : [.poundIfKeyword, .poundElseifKeyword, .poundElseKeyword]), loopProgress.evaluate(self.currentToken) { let (unexpectedBeforePoundIf, poundIf) = self.eat(poundIfHandle) firstIteration = false // Parse the condition. let condition: RawExprSyntax? switch poundIf.tokenKind { case .poundIfKeyword, .poundElseifKeyword: condition = RawExprSyntax(self.parseSequenceExpression(.basic, forDirective: true)) case .poundElseKeyword: condition = nil default: preconditionFailure("The loop condition should guarantee that we are at one of these tokens") } var elements = [Element]() do { var elementsProgress = LoopProgressCondition() while !self.at(any: [.eof, .poundElseKeyword, .poundElseifKeyword, .poundEndifKeyword]) && elementsProgress.evaluate(currentToken) { let newItemAtStartOfLine = self.currentToken.isAtStartOfLine guard let element = parseElement(&self), !element.isEmpty else { break } if let lastElement = elements.last, let fixedUpLastItem = addSemicolonIfNeeded(lastElement, newItemAtStartOfLine, &self) { elements[elements.count - 1] = fixedUpLastItem } elements.append(element) } } clauses.append(RawIfConfigClauseSyntax( unexpectedBeforePoundIf, poundKeyword: poundIf, condition: condition, elements: syntax(&self, elements), arena: self.arena)) } } let (unexpectedBeforePoundEndIf, poundEndIf) = self.expect(.poundEndifKeyword) return RawIfConfigDeclSyntax( clauses: RawIfConfigClauseListSyntax(elements: clauses, arena: self.arena), unexpectedBeforePoundEndIf, poundEndif: poundEndIf, arena: self.arena) } } extension Parser { /// Parse a line control directive. /// /// Grammar /// ======= /// /// line-control-statement → '#sourceLocation' '(' 'file' ':' file-path ',' 'line' ':' line-number ')' /// line-control-statement → '#sourceLocation' '(' ')' /// line-number → `A decimal integer greater than zero` /// file-path → static-string-literal @_spi(RawSyntax) public mutating func parsePoundSourceLocationDirective() -> RawPoundSourceLocationSyntax { let line = self.consumeAnyToken() let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) let args: RawPoundSourceLocationArgsSyntax? if !self.at(.rightParen) { let (unexpectedBeforeFile, file) = self.expectIdentifier() let (unexpectedBeforeFileColon, fileColon) = self.expect(.colon) let (unexpectedBeforeFileName, fileName) = self.expect(.stringLiteral) let (unexpectedBeforeComma, comma) = self.expect(.comma) let (unexpectedBeforeLine, line) = self.expectIdentifier() let (unexpectedBeforeLineColon, lineColon) = self.expect(.colon) let lineNumber = self.expectWithoutRecovery(.integerLiteral) args = RawPoundSourceLocationArgsSyntax( unexpectedBeforeFile, fileArgLabel: file, unexpectedBeforeFileColon, fileArgColon: fileColon, unexpectedBeforeFileName, fileName: fileName, unexpectedBeforeComma, comma: comma, unexpectedBeforeLine, lineArgLabel: line, unexpectedBeforeLineColon, lineArgColon: lineColon, lineNumber: lineNumber, arena: self.arena ) } else { args = nil } let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawPoundSourceLocationSyntax( poundSourceLocation: line, unexpectedBeforeLParen, leftParen: lparen, args: args, unexpectedBeforeRParen, rightParen: rparen, arena: self.arena ) } }
apache-2.0
0a051bb74f7777d4f4db5e2a54a6a9b5
42.137566
151
0.647246
4.664188
false
false
false
false
vvw/XWebView
XWebViewTests/XWVLoaderTest.swift
1
1635
/* Copyright 2015 XWebView 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 WebKit import XCTest import XWebView class XWVLoaderTest: XWVTestCase { class Plugin: NSObject { dynamic var property = 123 } private let namespace = "xwvtest" func testLoader() { let desc = "loader" let script = "if (XWVPlugin.load instanceof Function) fulfill('\(desc)');" let expectation = expectationWithDescription(desc) loadPlugin(XWVLoader(inventory: XWVInventory()), namespace: "XWVPlugin.load", script: script) waitForExpectationsWithTimeout(2, handler: nil) } func testLoading() { let inventory = XWVInventory() inventory.registerPlugin(Plugin.self, namespace: namespace) let loader = XWVLoader(inventory: inventory) let desc = "loading" let script = "XWVPlugin.load('\(namespace)').then(function(o){if (o.property==123) fulfill('\(desc)');})" let expectation = expectationWithDescription(desc) loadPlugin(loader, namespace: "XWVPlugin.load", script: script) waitForExpectationsWithTimeout(2, handler: nil) } }
apache-2.0
15a8ef026dfa3038f79c993d66973f13
33.787234
113
0.705199
4.567039
false
true
false
false
Friend-LGA/LGSideMenuController
Demo/_shared_files/SideMenuController/LeftViewController/LeftViewController.swift
1
8898
// // LeftViewController.swift // LGSideMenuControllerDemo // import Foundation import UIKit private let cellIdentifier = "cell" private let tableViewInset: CGFloat = 44.0 * 2.0 private let cellHeight: CGFloat = 44.0 class LeftViewController: UITableViewController { private var type: DemoType? private let sections: [[SideViewCellItem]] = [ [.close, .openRight], [.changeRootVC], [.pushVC(title: "Profile"), .pushVC(title: "News"), .pushVC(title: "Friends"), .pushVC(title: "Music"), .pushVC(title: "Video"), .pushVC(title: "Articles")] ] // For NonStoryboard Demo init(type: DemoType) { self.type = type super.init(style: .grouped) } required init?(coder: NSCoder) { super.init(coder: coder) } // For Storyboard Demo func setup(type: DemoType) { self.type = type } // MARK: - Lifecycle - override func viewDidLoad() { super.viewDidLoad() struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewDidLoad(), counter: \(Counter.count)") // For iOS < 11.0 use this property to avoid artefacts if necessary // automaticallyAdjustsScrollViewInsets = false tableView.register(LeftViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.separatorStyle = .none tableView.contentInset = UIEdgeInsets(top: tableViewInset, left: 0.0, bottom: tableViewInset, right: 0.0) tableView.showsVerticalScrollIndicator = false tableView.backgroundColor = .clear tableView.contentInsetAdjustmentBehavior = .never tableView.contentOffset = CGPoint(x: 0.0, y: -tableViewInset) } // MARK: - Status Bar - override var prefersStatusBarHidden: Bool { switch type?.demoRow { case .statusBarHidden, .statusBarOnlyRoot: return true default: return false } } override var preferredStatusBarStyle: UIStatusBarStyle { switch type?.demoRow { case .statusBarDifferentStyles: if isLightTheme() { return .lightContent } else { if #available(iOS 13.0, *) { return .darkContent } else { return .default } } default: return .default } } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LeftViewCell let item = sections[indexPath.section][indexPath.row] cell.textLabel!.text = item.description cell.isFirst = (indexPath.row == 0) cell.isLast = (indexPath.row == sections[indexPath.section].count - 1) cell.isFillColorInverted = sideMenuController?.leftViewPresentationStyle == .slideAboveBlurred return cell } // MARK: - UITableViewDelegate - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let sideMenuController = sideMenuController else { return } let item = sections[indexPath.section][indexPath.row] func getNavigationController() -> UINavigationController { if type?.demoRow == .usageInsideNavigationController { return sideMenuController.parent as! RootNavigationController } else if type?.demoRow == .usageAsContainerForTabBarController { let tabBarController = sideMenuController.rootViewController as! RootTabBarController return tabBarController.selectedViewController as! RootNavigationController } else { return sideMenuController.rootViewController as! RootNavigationController } } switch item { case .close: sideMenuController.hideLeftView(animated: true) case .openRight: sideMenuController.showRightView(animated: true) case .changeRootVC: let viewController = RootViewController(imageName: getBackgroundImageNameRandom()) if type?.demoRow == .usageInsideNavigationController { sideMenuController.rootViewController = viewController UIView.transition(with: sideMenuController.rootViewWrapperView!, duration: sideMenuController.leftViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } else { let navigationController = getNavigationController() navigationController.setViewControllers([viewController], animated: false) UIView.transition(with: navigationController.view, duration: sideMenuController.leftViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } sideMenuController.hideLeftView(animated: true) case .pushVC(let title): let viewController = RootViewControllerWithTextLabel(title: title, imageName: getBackgroundImageNameRandom()) if type?.demoRow == .usageInsideNavigationController { sideMenuController.rootViewController = viewController UIView.transition(with: sideMenuController.rootViewWrapperView!, duration: sideMenuController.leftViewAnimationDuration, options: [.transitionCrossDissolve], animations: nil) } else { let navigationController = getNavigationController() navigationController.pushViewController(viewController, animated: true) } sideMenuController.hideLeftView(animated: true) default: return } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.0 } return cellHeight / 2.0 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } // MARK: - Logging - deinit { struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.deinit(), counter: \(Counter.count)") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewWillAppear(\(animated)), counter: \(Counter.count)") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewDidAppear(\(animated)), counter: \(Counter.count)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewWillDisappear(\(animated)), counter: \(Counter.count)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewDidDisappear(\(animated)), counter: \(Counter.count)") } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() struct Counter { static var count = 0 } Counter.count += 1 print("LeftViewController.viewWillLayoutSubviews(), counter: \(Counter.count)") } }
mit
8eeb7ee8c14ea1ec3b2be22b642347f6
35.170732
113
0.616993
5.755498
false
false
false
false
curiousurick/Rye
Login/LogViewController.swift
1
9609
// // LoginViewController.swift // Login // // Created by Jason Kwok on 2/7/15. // Copyright (c) 2015 Jason Kwok. All rights reserved. // import UIKit import Parse class LogViewController: UIViewController, UITextFieldDelegate { @IBOutlet var loginButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var facebookButton: UIButton! @IBOutlet var signupButton: UIButton! @IBOutlet weak var Email: UITextField! @IBOutlet weak var Password: UITextField! func checkInput() -> Bool{ var u = setUsername(Email.text) var p = setPassword(Password.text) var ErrorAlert: UIAlertView = UIAlertView() var isGood: Bool if u == "Good" && p == "Good" { isGood = true } else { if u == "Bad" { ErrorAlert.title = "Invalid Email! 😫" ErrorAlert.message = "Please enter a valid email address" isGood = false } else if p == "Short" { ErrorAlert.title = "Too Short! 😫" ErrorAlert.message = "Password requires 8 or more characters." isGood = false } else if p == "Letters" { ErrorAlert.title = "No Letters! 😫" ErrorAlert.message = "Password requires a letter." isGood = false } else if p == "Numbers" { ErrorAlert.title = "No Numbers! 😫" ErrorAlert.message = "Password requires a number." isGood = false } else { ErrorAlert.title = "I have no idea what happened" ErrorAlert.message = "I guess try again?" isGood = false } ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } return isGood } @IBAction func loginButtonClicked(sender: AnyObject) { PFUser.logInWithUsernameInBackground(Email.text, password:Password.text) { (user: PFUser!, error: NSError!) -> Void in if user != nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { // The login failed. Check error to see why. } } } @IBAction func facebookButtonClicked(sender: AnyObject) { var permissions = ["email"] PFFacebookUtils.logInWithPermissions(permissions, { (user: PFUser!, error: NSError!) -> Void in if user == nil { NSLog("Uh oh. The user cancelled the Facebook login.") } else if user.isNew { NSLog("User signed up and logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { NSLog("User logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) //NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } }) } @IBAction func signupButtonClicked(sender: AnyObject) { var user = PFUser() if(checkInput()) { user.username = Email.text user.password = Password.text user.email = Email.text // other fields can be set just like with PFObject var ErrorAlert: UIAlertView = UIAlertView() user.signUpInBackgroundWithBlock { (succeeded: Bool!, error: NSError!) -> Void in if error == nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") //self.performSegueWithIdentifier("main", sender: nil) // Hooray! Let them use the app now. } else { ErrorAlert.title = "You already have an account!" ErrorAlert.message = "Try signing in!" // Show the errorString somewhere and let the user try again. ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } func setUsername(newValue: String) -> String { var hasAt: Bool = false var hasDot: Bool = false for letter in newValue { if letter == "@" { hasAt = true } if letter == "." { hasDot = true } } if hasAt && hasDot { return "Good" } else { return "Bad" } } func addDoneButtonOnKeyboard() { var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50)) doneToolbar.barStyle = UIBarStyle.BlackTranslucent var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction")) var items = NSMutableArray() items.addObject(flexSpace) items.addObject(done) doneToolbar.items = items doneToolbar.sizeToFit() self.Email.inputAccessoryView = doneToolbar self.Password.inputAccessoryView = doneToolbar } func doneButtonAction() { self.view.endEditing(true) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true) } func setPassword(newValue: String) -> String { let letters = NSCharacterSet.letterCharacterSet() let digits = NSCharacterSet.decimalDigitCharacterSet() //Password Constraint Variables var hasLetters: Bool = false var hasNumb: Bool = false let length = countElements(newValue) //Check Password Constraints for letter in newValue.unicodeScalars { if letters.longCharacterIsMember(letter.value) { hasLetters = true } if digits.longCharacterIsMember(letter.value) { hasNumb = true } } if length >= 8 && hasLetters && hasNumb { return "Good" } else if length < 8 { return "Short" } else if !hasLetters { return "Letters" } else { return "Numbers" } } override func viewDidLoad() { super.viewDidLoad() Email.delegate = self Password.delegate = self loginButton.layer.masksToBounds = true loginButton.layer.cornerRadius = 10 cancelButton.layer.masksToBounds = true cancelButton.layer.cornerRadius = 10 facebookButton.layer.masksToBounds = true facebookButton.layer.cornerRadius = 10 signupButton.layer.masksToBounds = true signupButton.layer.cornerRadius = 10 addDoneButtonOnKeyboard() // Do any additional setup after loading the view. } func loginViewShowingLoggedInUser(loginView: FBLoginView!) { } func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!) { } func loginViewShowingLoggedOutUser(loginView: FBLoginView!) { } func loginView(loginView: FBLoginView!, handleError error: NSError!) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { if(textField == self.Email) { self.Password.becomeFirstResponder() } else if(textField == self.Password) { self.loginButtonClicked(loginButton) } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
bde37128d0baf2be1e885fdfd65f43ed
31.979381
152
0.563509
5.553819
false
false
false
false
czechboy0/Buildasaur
BuildaKit/SyncPairExtensions.swift
2
3742
// // SyncPairExtensions.swift // Buildasaur // // Created by Honza Dvorsky on 19/05/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK import BuildaGitServer import BuildaUtils extension SyncPair { public struct Actions { public let integrationsToCancel: [Integration]? public let statusToSet: (status: StatusAndComment, commit: String, issue: IssueType?)? public let startNewIntegrationBot: Bot? //if non-nil, starts a new integration on this bot } func performActions(actions: Actions, completion: Completion) { let group = dispatch_group_create() var lastGroupError: NSError? if let integrationsToCancel = actions.integrationsToCancel { dispatch_group_enter(group) self.syncer.cancelIntegrations(integrationsToCancel, completion: { () -> () in dispatch_group_leave(group) }) } if let newStatus = actions.statusToSet { let status = newStatus.status let commit = newStatus.commit let issue = newStatus.issue dispatch_group_enter(group) self.syncer.updateCommitStatusIfNecessary(status, commit: commit, issue: issue, completion: { (error) -> () in if let error = error { lastGroupError = error } dispatch_group_leave(group) }) } if let startNewIntegrationBot = actions.startNewIntegrationBot { let bot = startNewIntegrationBot dispatch_group_enter(group) self.syncer._xcodeServer.postIntegration(bot.id, completion: { (integration, error) -> () in if let integration = integration where error == nil { Log.info("Bot \(bot.name) successfully enqueued Integration #\(integration.number)") } else { let e = Error.withInfo("Bot \(bot.name) failed to enqueue an integration", internalError: error) lastGroupError = e } dispatch_group_leave(group) }) } dispatch_group_notify(group, dispatch_get_main_queue(), { completion(error: lastGroupError) }) } //MARK: Utility functions func getIntegrations(bot: Bot, completion: (integrations: [Integration], error: NSError?) -> ()) { let syncer = self.syncer /* TODO: we should establish some reliable and reasonable plan for how many integrations to fetch. currently it's always 20, but some setups might have a crazy workflow with very frequent commits on active bots etc. */ let query = [ "last": "20" ] syncer._xcodeServer.getBotIntegrations(bot.id, query: query, completion: { (integrations, error) -> () in if let error = error { let e = Error.withInfo("Bot \(bot.name) failed return integrations", internalError: error) completion(integrations: [], error: e) return } if let integrations = integrations { completion(integrations: integrations, error: nil) } else { let e = Error.withInfo("Getting integrations", internalError: Error.withInfo("Nil integrations even after returning nil error!")) completion(integrations: [], error: e) } }) } }
mit
2e2f70c655489b7802ee4f288854b861
33.971963
145
0.558525
5.384173
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureActivity/Sources/FeatureActivityUI/MainScreen/ActivityCell/ActivityItemInteractor.swift
1
1560
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import PlatformUIKit final class ActivityItemInteractor { let event: ActivityItemEvent let balanceViewInteractor: AssetBalanceViewInteracting init(activityItemEvent: ActivityItemEvent, pairExchangeService: PairExchangeServiceAPI) { event = activityItemEvent switch activityItemEvent { case .buySell(let buySellActivityItem) where buySellActivityItem.isBuy: balanceViewInteractor = SimpleBalanceViewInteractor( fiatValue: activityItemEvent.inputAmount, cryptoValue: buySellActivityItem.outputValue ) case .buySell(let buySellActivityItem) where !buySellActivityItem.isBuy: balanceViewInteractor = SimpleBalanceViewInteractor( fiatValue: buySellActivityItem.outputValue, cryptoValue: activityItemEvent.inputAmount ) case .fiat(let fiatActivityItem): balanceViewInteractor = SimpleBalanceViewInteractor( fiatValue: .init(fiatValue: fiatActivityItem.amount), cryptoValue: nil ) default: balanceViewInteractor = ActivityItemBalanceViewInteractor( activityItemBalanceFetching: ActivityItemBalanceFetcher( pairExchangeService: pairExchangeService, moneyValue: activityItemEvent.inputAmount, at: event.creationDate ) ) } } }
lgpl-3.0
bb9233bee517845eda25f48f6f1548bd
38.974359
93
0.663246
5.774074
false
false
false
false
nicemohawk/nmf-ios
nmf/Artist.swift
1
2258
// // Artists.swift // nmf // // Created by Daniel Pagan on 3/30/16. // Copyright © 2017 Nelsonville Music Festival. All rights reserved. // import Foundation import Kingfisher @objcMembers class Artist : NSObject, NSCoding, Resource { var objectId: String? var artistName: String? var bio: String? var picture: String? var url: String? var youTube: String? // local-only var _updated: Bool = true override init() { super.init() } required init?(coder aDecoder: NSCoder) { objectId = aDecoder.decodeObject(forKey: "oid") as? String artistName = aDecoder.decodeObject(forKey: "name") as? String bio = aDecoder.decodeObject(forKey: "bio") as? String picture = aDecoder.decodeObject(forKey: "picture") as? String url = aDecoder.decodeObject(forKey: "url") as? String youTube = aDecoder.decodeObject(forKey: "youtube") as? String _updated = aDecoder.decodeBool(forKey: "updated") } func encode(with aCoder: NSCoder) { aCoder.encode(objectId, forKey: "oid") aCoder.encode(artistName, forKey: "name") aCoder.encode(bio, forKey: "bio") aCoder.encode(picture, forKey: "picture") aCoder.encode(url, forKey: "url") aCoder.encode(youTube, forKey: "youtube") aCoder.encode(_updated, forKey: "updated") } func update(_ otherItem: Artist) { guard objectId == otherItem.objectId else { return } artistName = otherItem.artistName bio = otherItem.bio picture = otherItem.picture url = otherItem.url youTube = otherItem.youTube _updated = true } var downloadURL: URL { get { guard let pictureURLString = picture, let picturURL = Foundation.URL(string: pictureURLString) else { return Foundation.URL(string: "https://api.backendless.com/19C02337-07D4-7BF5-FFD0-FCC0E93A1700/832D9A9C-39B2-3993-FF36-2217A956EA00/files/images-2018/empty.jpg")! } return picturURL } } var cacheKey: String { return downloadURL.absoluteString } }
apache-2.0
eff2f6d147e819700df915133da70401
25.869048
179
0.604785
4.17963
false
false
false
false
troystribling/BlueCap
Examples/BlueCap/BlueCap/Central/PeripheralViewController.swift
1
11026
// // PeripheralViewController.swift // BlueCap // // Created by Troy Stribling on 6/16/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import BlueCapKit class PeripheralViewController : UITableViewController { weak var peripheral: Peripheral? var peripheralDiscoveryFuture: FutureStream<[Void]>? var peripheralAdvertisements: PeripheralAdvertisements? let progressView = ProgressView() var isUpdatingeRSSIAndPeripheralProperties = false let dateFormatter = DateFormatter() @IBOutlet var uuidLabel: UILabel! @IBOutlet var rssiLabel: UILabel! @IBOutlet var stateLabel: UILabel! @IBOutlet var serviceLabel: UILabel! @IBOutlet var serviceCount: UILabel! @IBOutlet var discoveredAtLabel: UILabel! @IBOutlet var connectedAtLabel: UILabel! @IBOutlet var connectionsLabel: UILabel! @IBOutlet var disconnectionsLabel: UILabel! @IBOutlet var timeoutsLabel: UILabel! @IBOutlet var secondsConnectedLabel: UILabel! @IBOutlet var avgSecondsConnected: UILabel! struct MainStoryBoard { static let peripheralServicesSegue = "PeripheralServices" static let peripehralAdvertisementsSegue = "PeripheralAdvertisements" } required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short } override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) guard let peripheral = peripheral else { _ = self.navigationController?.popToRootViewController(animated: false) return } navigationItem.title = peripheral.name discoveredAtLabel.text = dateFormatter.string(from: peripheral.discoveredAt) connect() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(PeripheralViewController.didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object :nil) guard peripheral != nil else { _ = self.navigationController?.popToRootViewController(animated: false) return } updateConnectionStateLabel() resumeRSSIUpdatesAndPeripheralPropertiesUpdates() } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) pauseRSSIUpdatesAndPeripheralPropertiesUpdates() } override func didMove(toParent parent: UIViewController?) { if parent == nil { disconnect() } } override func prepare(for segue:UIStoryboardSegue, sender:Any!) { if segue.identifier == MainStoryBoard.peripheralServicesSegue { let viewController = segue.destination as! PeripheralServicesViewController viewController.peripheral = peripheral viewController.peripheralDiscoveryFuture = peripheralDiscoveryFuture } else if segue.identifier == MainStoryBoard.peripehralAdvertisementsSegue { let viewController = segue.destination as! PeripheralAdvertisementsViewController viewController.peripheralAdvertisements = peripheralAdvertisements } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { guard let peripheral = peripheral else { return false } if identifier == MainStoryBoard.peripheralServicesSegue { return peripheral.services.count > 0 && peripheral.state == .connected } else if identifier == MainStoryBoard.peripehralAdvertisementsSegue { return true } else { return false } } @objc func didEnterBackground() { disconnect() _ = navigationController?.popToRootViewController(animated: false) } func updatePeripheralProperties() { guard let peripheral = peripheral else { return } if let connectedAt = peripheral.connectedAt { connectedAtLabel.text = dateFormatter.string(from: connectedAt) } rssiLabel.text = "\(peripheral.RSSI)" connectionsLabel.text = "\(peripheral.connectionCount)" secondsConnectedLabel.text = "\(Int(peripheral.cumlativeSecondsConnected))" if peripheral.connectionCount > 0 { avgSecondsConnected.text = "\(UInt(peripheral.cumlativeSecondsConnected) / peripheral.connectionCount)" } else { avgSecondsConnected.text = "0" } disconnectionsLabel.text = "\(peripheral.disconnectionCount)" timeoutsLabel.text = "\(peripheral.timeoutCount)" } func updateRSSIUpdatesAndPeripheralPropertiesIfConnected() { guard isUpdatingeRSSIAndPeripheralProperties else { return } guard let peripheral = peripheral else { return } guard peripheral.state == .connected else { peripheral.stopPollingRSSI() return } let rssiFuture = peripheral.startPollingRSSI(period: Params.peripheralViewRSSIPollingInterval, capacity: Params.peripheralRSSIFutureCapacity) rssiFuture.onSuccess { [weak self] _ in self?.updatePeripheralProperties() } } func pauseRSSIUpdatesAndPeripheralPropertiesUpdates() { guard isUpdatingeRSSIAndPeripheralProperties else { return } guard let peripheral = peripheral else { return } isUpdatingeRSSIAndPeripheralProperties = false peripheral.stopPollingRSSI() } func resumeRSSIUpdatesAndPeripheralPropertiesUpdates() { guard !isUpdatingeRSSIAndPeripheralProperties else { return } isUpdatingeRSSIAndPeripheralProperties = true updateRSSIUpdatesAndPeripheralPropertiesIfConnected() } func updateConnectionStateLabel() { guard let peripheral = peripheral else { return } switch peripheral.state { case .connected: stateLabel.text = "Connected" stateLabel.textColor = UIColor(red: 0.1, green: 0.7, blue: 0.1, alpha: 1.0) default: stateLabel.text = "Connecting" stateLabel.textColor = UIColor(red: 0.7, green: 0.1, blue: 0.1, alpha: 1.0) } serviceCount.text = "\(peripheral.services.count)" } func connect() { guard let peripheral = peripheral else { return } Logger.debug("Connect peripheral: '\(peripheral.name)'', \(peripheral.identifier.uuidString)") progressView.show() let connectionTimeout = ConfigStore.getPeripheralConnectionTimeoutEnabled() ? Double(ConfigStore.getPeripheralConnectionTimeout()) : Double.infinity let scanTimeout = TimeInterval(ConfigStore.getCharacteristicReadWriteTimeout()) peripheralDiscoveryFuture = peripheral.connect(connectionTimeout: connectionTimeout, capacity: 1).flatMap { [weak self, weak peripheral] () -> Future<Void> in guard let peripheral = peripheral else { throw AppError.unlikelyFailure } self?.updateConnectionStateLabel() return peripheral.discoverAllServices(timeout: scanTimeout) }.flatMap { [weak peripheral] () -> Future<[Void]> in guard let peripheral = peripheral else { throw AppError.unlikelyFailure } return peripheral.services.map { $0.discoverAllCharacteristics(timeout: scanTimeout) }.sequence() } peripheralDiscoveryFuture?.onSuccess { [weak self] _ -> Void in self.forEach { strongSelf in _ = strongSelf.progressView.remove() strongSelf.updateConnectionStateLabel() strongSelf.updateRSSIUpdatesAndPeripheralPropertiesIfConnected() } } peripheralDiscoveryFuture?.onFailure { [weak self] (error) -> Void in self.forEach { strongSelf in let maxTimeouts = ConfigStore.getPeripheralMaximumTimeoutsEnabled() ? ConfigStore.getPeripheralMaximumTimeouts() : UInt.max let maxDisconnections = ConfigStore.getPeripheralMaximumDisconnectionsEnabled() ? ConfigStore.getPeripheralMaximumDisconnections() : UInt.max switch error { case PeripheralError.forcedDisconnect: Logger.debug("Connection force disconnect: '\(peripheral.name)', \(peripheral.identifier.uuidString)") case PeripheralError.connectionTimeout: if peripheral.timeoutCount < maxTimeouts { Logger.debug("Connection timeout: '\(peripheral.name)', \(peripheral.identifier.uuidString)") strongSelf.updateConnectionStateLabel() peripheral.reconnect(withDelay: 1.0) return } case PeripheralError.serviceDiscoveryTimeout: Logger.debug("Service discovery timeout: '\(peripheral.name)', \(peripheral.identifier.uuidString)") peripheral.disconnect() return case ServiceError.characteristicDiscoveryTimeout: Logger.debug("Characteristic discovery timeout: '\(peripheral.name)', \(peripheral.identifier.uuidString)") peripheral.disconnect() return default: if peripheral.disconnectionCount < maxDisconnections { peripheral.reconnect(withDelay: 1.0) strongSelf.updateConnectionStateLabel() Logger.debug("Disconnected: '\(error)', '\(peripheral.name)', \(peripheral.identifier.uuidString)") return } } strongSelf.stateLabel.text = "Disconnected" strongSelf.stateLabel.textColor = UIColor.lightGray strongSelf.updateConnectionStateLabel() strongSelf.updateRSSIUpdatesAndPeripheralPropertiesIfConnected() let progressViewFuture = strongSelf.progressView.remove() progressViewFuture.onSuccess { _ in strongSelf.present(UIAlertController.alert(title: "Connection error", error: error) { _ in _ = strongSelf.navigationController?.popToRootViewController(animated: true) }, animated: true) } } } } func disconnect() { guard let peripheral = peripheral, peripheral.state != .disconnected else { return } peripheral.stopPollingRSSI() peripheral.disconnect() } // MARK: UITableViewDataSource }
mit
5fdc08e9a038bf2e4ec46700b8fb8e09
39.837037
183
0.644749
5.648566
false
false
false
false
sahandnayebaziz/Dana-Hills
Dana Hills/NewsTableViewCell.swift
1
1530
// // NewsTableViewCell.swift // Dana Hills // // Created by Sahand Nayebaziz on 10/2/16. // Copyright © 2016 Nayebaziz, Sahand. All rights reserved. // import UIKit class NewsTableViewCell: UITableViewCell { var titleLabel: UILabel? = nil var publishDateLabel: UILabel? = nil func set(forNewsArticle article: NewsArticle) { createSubviews() titleLabel?.text = "" publishDateLabel?.text = "" titleLabel?.text = article.title publishDateLabel?.text = article.datePublished.toStringWithRelativeTime() } private func createSubviews() { if titleLabel == nil { titleLabel = UILabel() titleLabel?.numberOfLines = 0 titleLabel!.font = UIFont.preferredFont(forTextStyle: .headline) addSubview(titleLabel!) } if publishDateLabel == nil { publishDateLabel = UILabel() publishDateLabel!.font = UIFont.preferredFont(forTextStyle: .caption1) publishDateLabel!.textColor = UIColor.lightGray addSubview(publishDateLabel!) } titleLabel!.snp.makeConstraints { make in make.left.equalTo(16) make.right.equalTo(-12) make.top.equalTo(16) make.bottom.equalTo(publishDateLabel!.snp.top).offset(-4) } publishDateLabel!.snp.makeConstraints { make in make.left.equalTo(16) make.bottom.equalTo(-16) } } }
mit
ae31452a6b019222596523d819a976c2
27.849057
82
0.59843
4.748447
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/BlinkingView.swift
1
835
// // BlinkingView.swift // breadwallet // // Created by Adrian Corscadden on 2017-04-16. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class BlinkingView: UIView { init(blinkColor: UIColor) { self.blinkColor = blinkColor super.init(frame: .zero) } func startBlinking() { timer = Timer.scheduledTimer(timeInterval: 0.53, target: self, selector: #selector(update), userInfo: nil, repeats: true) } func stopBlinking() { timer?.invalidate() } @objc private func update() { backgroundColor = backgroundColor == .clear ? blinkColor : .clear } private let blinkColor: UIColor private var timer: Timer? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
8439b1a31372074328025a3372d38368
22.166667
129
0.645084
4.108374
false
false
false
false
fastred/IBAnalyzer
Pods/SourceKittenFramework/Source/SourceKittenFramework/File.swift
1
21712
// // File.swift // SourceKitten // // Created by JP Simard on 2015-01-03. // Copyright (c) 2015 SourceKitten. All rights reserved. // import Foundation #if SWIFT_PACKAGE import SourceKit #endif import SWXMLHash // swiftlint:disable file_length // This file could easily be split up /// Represents a source file. public final class File { /// File path. Nil if initialized directly with `File(contents:)`. public let path: String? /// File contents. public var contents: String { get { if _contents == nil { _contents = try! String(contentsOfFile: path!, encoding: .utf8) } return _contents! } set { _contents = newValue } } /// File lines. public var lines: [Line] { get { if _lines == nil { _lines = contents.bridge().lines() } return _lines! } set { _lines = newValue } } private var _contents: String? private var _lines: [Line]? /** Failable initializer by path. Fails if file contents could not be read as a UTF8 string. - parameter path: File path. */ public init?(path: String) { self.path = path.bridge().absolutePathRepresentation() do { contents = try String(contentsOfFile: path, encoding: .utf8) lines = contents.bridge().lines() } catch { fputs("Could not read contents of `\(path)`\n", stderr) return nil } } public init(pathDeferringReading path: String) { self.path = path.bridge().absolutePathRepresentation() } /** Initializer by file contents. File path is nil. - parameter contents: File contents. */ public init(contents: String) { path = nil self.contents = contents lines = contents.bridge().lines() } /// Formats the file. /// /// - Parameters: /// - trimmingTrailingWhitespace: Boolean /// - useTabs: Boolean /// - indentWidth: Int /// - Returns: formatted String /// - Throws: Request.Error public func format(trimmingTrailingWhitespace: Bool, useTabs: Bool, indentWidth: Int) throws -> String { guard let path = path else { return contents } _ = try Request.editorOpen(file: self).send() var newContents = [String]() var offset = 0 for line in lines { let formatResponse = try Request.format(file: path, line: Int64(line.index), useTabs: useTabs, indentWidth: Int64(indentWidth)).send() let newText = formatResponse["key.sourcetext"] as! String newContents.append(newText) guard newText != line.content else { continue } _ = try Request.replaceText(file: path, offset: Int64(line.byteRange.location + offset), length: Int64(line.byteRange.length - 1), sourceText: newText).send() let oldLength = line.byteRange.length let newLength = newText.lengthOfBytes(using: .utf8) offset += 1 + newLength - oldLength } if trimmingTrailingWhitespace { newContents = newContents.map { $0.bridge().trimmingTrailingCharacters(in: .whitespaces) } } return newContents.joined(separator: "\n") + "\n" } /** Parse source declaration string from SourceKit dictionary. - parameter dictionary: SourceKit dictionary to extract declaration from. - returns: Source declaration if successfully parsed. */ public func parseDeclaration(_ dictionary: [String: SourceKitRepresentable]) -> String? { guard shouldParseDeclaration(dictionary), let start = SwiftDocKey.getOffset(dictionary).map({ Int($0) }) else { return nil } let substring: String? if let end = SwiftDocKey.getBodyOffset(dictionary) { substring = contents.bridge().substringStartingLinesWithByteRange(start: start, length: Int(end) - start) } else { substring = contents.bridge().substringLinesWithByteRange(start: start, length: 0) } return substring?.removingCommonLeadingWhitespaceFromLines() .trimmingWhitespaceAndOpeningCurlyBrace() } /** Parse line numbers containing the declaration's implementation from SourceKit dictionary. - parameter dictionary: SourceKit dictionary to extract declaration from. - returns: Line numbers containing the declaration's implementation. */ public func parseScopeRange(_ dictionary: [String: SourceKitRepresentable]) -> (start: Int, end: Int)? { if !shouldParseDeclaration(dictionary) { return nil } return SwiftDocKey.getOffset(dictionary).flatMap { start in let start = Int(start) let end = SwiftDocKey.getBodyOffset(dictionary).flatMap { bodyOffset in return SwiftDocKey.getBodyLength(dictionary).map { bodyLength in return Int(bodyOffset + bodyLength) } } ?? start let length = end - start return contents.bridge().lineRangeWithByteRange(start: start, length: length) } } /** Extract mark-style comment string from doc dictionary. e.g. '// MARK: - The Name' - parameter dictionary: Doc dictionary to parse. - returns: Mark name if successfully parsed. */ private func parseMarkName(_ dictionary: [String: SourceKitRepresentable]) -> String? { precondition(SwiftDocKey.getKind(dictionary)! == SyntaxKind.commentMark.rawValue) let offset = Int(SwiftDocKey.getOffset(dictionary)!) let length = Int(SwiftDocKey.getLength(dictionary)!) let fileContentsData = contents.data(using: .utf8) let subdata = fileContentsData?.subdata(in: offset..<(offset + length)) return subdata.flatMap { String(data: $0, encoding: .utf8) } } /** Returns a copy of the input dictionary with comment mark names, cursor.info information and parsed declarations for the top-level of the input dictionary and its substructures. - parameter dictionary: Dictionary to process. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ public func process(dictionary: [String: SourceKitRepresentable], cursorInfoRequest: sourcekitd_object_t? = nil, syntaxMap: SyntaxMap? = nil) -> [String: SourceKitRepresentable] { var dictionary = dictionary if let cursorInfoRequest = cursorInfoRequest { dictionary = merge( dictionary, dictWithCommentMarkNamesCursorInfo(dictionary, cursorInfoRequest: cursorInfoRequest) ) } // Parse declaration and add to dictionary if let parsedDeclaration = parseDeclaration(dictionary) { dictionary[SwiftDocKey.parsedDeclaration.rawValue] = parsedDeclaration } // Parse scope range and add to dictionary if let parsedScopeRange = parseScopeRange(dictionary) { dictionary[SwiftDocKey.parsedScopeStart.rawValue] = Int64(parsedScopeRange.start) dictionary[SwiftDocKey.parsedScopeEnd.rawValue] = Int64(parsedScopeRange.end) } // Parse `key.doc.full_as_xml` and add to dictionary if let parsedXMLDocs = (SwiftDocKey.getFullXMLDocs(dictionary).flatMap(parseFullXMLDocs)) { dictionary = merge(dictionary, parsedXMLDocs) } // Update substructure if let substructure = newSubstructure(dictionary, cursorInfoRequest: cursorInfoRequest, syntaxMap: syntaxMap) { dictionary[SwiftDocKey.substructure.rawValue] = substructure } return dictionary } /** Returns a copy of the input dictionary with additional cursorinfo information at the given `documentationTokenOffsets` that haven't yet been documented. - parameter dictionary: Dictionary to insert new docs into. - parameter documentedTokenOffsets: Offsets that are likely documented. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ internal func furtherProcess(dictionary: [String: SourceKitRepresentable], documentedTokenOffsets: [Int], cursorInfoRequest: sourcekitd_object_t, syntaxMap: SyntaxMap) -> [String: SourceKitRepresentable] { var dictionary = dictionary let offsetMap = makeOffsetMap(documentedTokenOffsets: documentedTokenOffsets, dictionary: dictionary) for offset in offsetMap.keys.reversed() { // Do this in reverse to insert the doc at the correct offset if let rawResponse = Request.send(cursorInfoRequest: cursorInfoRequest, atOffset: Int64(offset)), case let response = process(dictionary: rawResponse, cursorInfoRequest: nil, syntaxMap: syntaxMap), let kind = SwiftDocKey.getKind(response), SwiftDeclarationKind(rawValue: kind) != nil, let parentOffset = offsetMap[offset].flatMap({ Int64($0) }), let inserted = insert(doc: response, parent: dictionary, offset: parentOffset) { dictionary = inserted } } return dictionary } /** Update input dictionary's substructure by running `processDictionary(_:cursorInfoRequest:syntaxMap:)` on its elements, only keeping comment marks and declarations. - parameter dictionary: Input dictionary to process its substructure. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. - returns: A copy of the input dictionary's substructure processed by running `processDictionary(_:cursorInfoRequest:syntaxMap:)` on its elements, only keeping comment marks and declarations. */ private func newSubstructure(_ dictionary: [String: SourceKitRepresentable], cursorInfoRequest: sourcekitd_object_t?, syntaxMap: SyntaxMap?) -> [SourceKitRepresentable]? { return SwiftDocKey.getSubstructure(dictionary)? .map({ $0 as! [String: SourceKitRepresentable] }) .filter(isDeclarationOrCommentMark) .map { process(dictionary: $0, cursorInfoRequest: cursorInfoRequest, syntaxMap: syntaxMap) } } /** Returns an updated copy of the input dictionary with comment mark names and cursor.info information. - parameter dictionary: Dictionary to update. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ private func dictWithCommentMarkNamesCursorInfo(_ dictionary: [String: SourceKitRepresentable], cursorInfoRequest: sourcekitd_object_t) -> [String: SourceKitRepresentable]? { guard let kind = SwiftDocKey.getKind(dictionary) else { return nil } // Only update dictionaries with a 'kind' key if kind == SyntaxKind.commentMark.rawValue, let markName = parseMarkName(dictionary) { // Update comment marks return [SwiftDocKey.name.rawValue: markName] } else if let decl = SwiftDeclarationKind(rawValue: kind), decl != .varParameter { // Update if kind is a declaration (but not a parameter) let innerTypeNameOffset = SwiftDocKey.getName(dictionary)?.byteOffsetOfInnerTypeName() ?? 0 var updateDict = Request.send(cursorInfoRequest: cursorInfoRequest, atOffset: SwiftDocKey.getNameOffset(dictionary)! + innerTypeNameOffset) ?? [:] File.untrustedCursorInfoKeys.forEach { updateDict.removeValue(forKey: $0.rawValue) } return updateDict } return nil } /// Keys to ignore from cursorinfo when already have dictionary from editor.open private static let untrustedCursorInfoKeys: [SwiftDocKey] = [ .kind, // values from editor.open are more accurate than cursorinfo .offset, // usually same as nameoffset, but for extension, value locates **type's declaration** in type's file .length, // usually same as namelength, but for extension, value locates **type's declaration** in type's file .name // for extensions of nested types has just the inner name, prefer fully-qualified name ] /** Returns whether or not a doc should be inserted into a parent at the provided offset. - parameter parent: Parent dictionary to evaluate. - parameter offset: Offset to search for in parent dictionary. - returns: True if a doc should be inserted in the parent at the provided offset. */ private func shouldInsert(parent: [String: SourceKitRepresentable], offset: Int64) -> Bool { return SwiftDocKey.getSubstructure(parent) != nil && ((offset == 0) || SwiftDocKey.getNameOffset(parent) == offset) } /** Inserts a document dictionary at the specified offset. Parent will be traversed until the offset is found. Returns nil if offset could not be found. - parameter doc: Document dictionary to insert. - parameter parent: Parent to traverse to find insertion point. - parameter offset: Offset to insert document dictionary. - returns: Parent with doc inserted if successful. */ private func insert(doc: [String: SourceKitRepresentable], parent: [String: SourceKitRepresentable], offset: Int64) -> [String: SourceKitRepresentable]? { var parent = parent if shouldInsert(parent: parent, offset: offset) { var substructure = SwiftDocKey.getSubstructure(parent) as! [[String: SourceKitRepresentable]] let docOffset = SwiftDocKey.getBestOffset(doc)! let insertIndex = substructure.index(where: { structure in SwiftDocKey.getBestOffset(structure)! > docOffset }) ?? substructure.endIndex substructure.insert(doc, at: insertIndex) parent[SwiftDocKey.substructure.rawValue] = substructure return parent } for key in parent.keys { guard var subArray = parent[key] as? [SourceKitRepresentable] else { continue } for i in 0..<subArray.count { let subDict = insert(doc: doc, parent: subArray[i] as! [String: SourceKitRepresentable], offset: offset) if let subDict = subDict { subArray[i] = subDict parent[key] = subArray return parent } } } return nil } /** Returns true if path is nil or if path has the same last path component as `key.filepath` in the input dictionary. - parameter dictionary: Dictionary to parse. */ internal func shouldTreatAsSameFile(_ dictionary: [String: SourceKitRepresentable]) -> Bool { return path == SwiftDocKey.getFilePath(dictionary) } /** Returns true if the input dictionary contains a parseable declaration. - parameter dictionary: Dictionary to parse. */ private func shouldParseDeclaration(_ dictionary: [String: SourceKitRepresentable]) -> Bool { // swiftlint:disable operator_usage_whitespace let sameFile = shouldTreatAsSameFile(dictionary) let hasTypeName = SwiftDocKey.getTypeName(dictionary) != nil let hasAnnotatedDeclaration = SwiftDocKey.getAnnotatedDeclaration(dictionary) != nil let hasOffset = SwiftDocKey.getOffset(dictionary) != nil let isntExtension = SwiftDocKey.getKind(dictionary) != SwiftDeclarationKind.extension.rawValue // swiftlint:enable operator_usage_whitespace return sameFile && hasTypeName && hasAnnotatedDeclaration && hasOffset && isntExtension } /** Add doc comment attributes to an otherwise complete set of declarations for a file. - parameter dictionary: dictionary of file declarations - parameter syntaxMap: syntaxmap for the file - returns: dictionary of declarations with comments */ internal func addDocComments(dictionary: [String: SourceKitRepresentable], syntaxMap: SyntaxMap) -> [String: SourceKitRepresentable] { return addDocComments(dictionary: dictionary, finder: syntaxMap.createDocCommentFinder()) } /** Add doc comment attributes to a declaration and its children - parameter dictionary: declaration to update - parameter finder: current state of doc comment location - returns: updated version of declaration dictionary */ internal func addDocComments(dictionary: [String: SourceKitRepresentable], finder: SyntaxMap.DocCommentFinder) -> [String: SourceKitRepresentable] { var dictionary = dictionary // special-case skip 'enumcase': has same offset as child 'enumelement' if let kind = SwiftDocKey.getKind(dictionary).flatMap(SwiftDeclarationKind.init), kind != .enumcase, let offset = SwiftDocKey.getBestOffset(dictionary), let commentRange = finder.getRangeForDeclaration(atOffset: Int(offset)), case let start = commentRange.lowerBound, case let end = commentRange.upperBound, let nsRange = contents.bridge().byteRangeToNSRange(start: start, length: end - start), let commentBody = contents.commentBody(range: nsRange) { dictionary[SwiftDocKey.documentationComment.rawValue] = commentBody } if let substructure = SwiftDocKey.getSubstructure(dictionary) { dictionary[SwiftDocKey.substructure.rawValue] = substructure.map { addDocComments(dictionary: $0 as! [String: SourceKitRepresentable], finder: finder) } } return dictionary } } /** Returns true if the dictionary represents a source declaration or a mark-style comment. - parameter dictionary: Dictionary to parse. */ private func isDeclarationOrCommentMark(_ dictionary: [String: SourceKitRepresentable]) -> Bool { if let kind = SwiftDocKey.getKind(dictionary) { return kind != SwiftDeclarationKind.varParameter.rawValue && (kind == SyntaxKind.commentMark.rawValue || SwiftDeclarationKind(rawValue: kind) != nil) } return false } /** Parse XML from `key.doc.full_as_xml` from `cursor.info` request. - parameter xmlDocs: Contents of `key.doc.full_as_xml` from SourceKit. - returns: XML parsed as an `[String: SourceKitRepresentable]`. */ public func parseFullXMLDocs(_ xmlDocs: String) -> [String: SourceKitRepresentable]? { let cleanXMLDocs = xmlDocs.replacingOccurrences(of: "<rawHTML>", with: "") .replacingOccurrences(of: "</rawHTML>", with: "") .replacingOccurrences(of: "<codeVoice>", with: "`") .replacingOccurrences(of: "</codeVoice>", with: "`") return SWXMLHash.parse(cleanXMLDocs).children.first.map { rootXML in var docs = [String: SourceKitRepresentable]() docs[SwiftDocKey.docType.rawValue] = rootXML.element?.name docs[SwiftDocKey.docFile.rawValue] = rootXML.element?.allAttributes["file"]?.text docs[SwiftDocKey.docLine.rawValue] = (rootXML.element?.allAttributes["line"]?.text).flatMap { Int64($0) } docs[SwiftDocKey.docColumn.rawValue] = (rootXML.element?.allAttributes["column"]?.text).flatMap { Int64($0) } docs[SwiftDocKey.docName.rawValue] = rootXML["Name"].element?.text docs[SwiftDocKey.usr.rawValue] = rootXML["USR"].element?.text docs[SwiftDocKey.docDeclaration.rawValue] = rootXML["Declaration"].element?.text // XML before swift 3.2 does not have CommentParts container let commentPartsXML = (try? rootXML.byKey("CommentParts")) ?? rootXML let parameters = commentPartsXML["Parameters"].children if !parameters.isEmpty { func docParameters(from indexer: XMLIndexer) -> [String: SourceKitRepresentable] { return [ "name": (indexer["Name"].element?.text ?? ""), "discussion": (indexer["Discussion"].childrenAsArray() ?? []) ] } docs[SwiftDocKey.docParameters.rawValue] = parameters.map(docParameters(from:)) as [SourceKitRepresentable] } docs[SwiftDocKey.docDiscussion.rawValue] = commentPartsXML["Discussion"].childrenAsArray() docs[SwiftDocKey.docResultDiscussion.rawValue] = commentPartsXML["ResultDiscussion"].childrenAsArray() return docs } } private extension XMLIndexer { /** Returns an `[SourceKitRepresentable]` of `[String: SourceKitRepresentable]` items from `indexer` children, if any. */ func childrenAsArray() -> [SourceKitRepresentable]? { if children.isEmpty { return nil } let elements = children.flatMap { $0.element } func dictionary(from element: SWXMLHash.XMLElement) -> [String: SourceKitRepresentable] { return [element.name: element.text] } return elements.map(dictionary(from:)) as [SourceKitRepresentable] } }
mit
d22be6db6e653cd5b9e828e6a6970f5c
42.079365
158
0.64135
5.106303
false
false
false
false
veeman961/Flicks
Flicks/MenuViewController.swift
1
7526
// // MainViewController.swift // Flicks // // Created by Kevin Rajan on 1/12/16. // Copyright © 2016 veeman961. All rights reserved. // import UIKit class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! weak var containerViewController: ContainerViewController? weak var mainViewController: TabBarViewController? var count: Int = 0 //var checked: [[Bool]]! var checkedKey:String = "CHECKED_CATEGORIES" let CellIdentifier = "CategoryCell" let categories = [["Now Playing","Popular","Top Rated", "Upcoming"],["On the Air", "Airing Today", "Top Rated", "Popular"]] override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "appDidEnterBackground", name: "appDidEnterBackground", object: nil) tableView.dataSource = self tableView.delegate = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: CellIdentifier) self.navigationController?.navigationBar.barStyle = .BlackTranslucent //Configures checked: [[Bool]] //let defaults = NSUserDefaults.standardUserDefaults() //self.checked = defaults.objectForKey(checkedKey) as! [[Bool]] //print(myVariables.checked) for i in 0 ..< myVariables.checked.count { for j in 0 ..< myVariables.checked[i].count { if (myVariables.checked[i][j]) { ++count } //print(count) } } } /* func appDidEnterBackground() { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(myVariables.checked, forKey: checkedKey) defaults.synchronize() } */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: TableView - Configure the UITableView // tableview contains 2 sections func numberOfSectionsInTableView(tableView: UITableView) -> Int { return categories.count } // title for each section func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if(section == 0) { return "Movie Categories" } else { return "TV Show Categories" } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.contentView.backgroundColor = UIColor.blackColor() header.textLabel!.textColor = UIColor.whiteColor() header.alpha = 0.55 } // numberOfRowsInSection func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories[section].count } // didselectrow func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell")! myVariables.checked[indexPath.section][indexPath.row] = !(myVariables.checked[indexPath.section][indexPath.row]) if myVariables.checked[indexPath.section][indexPath.row] { cell.accessoryType = .Checkmark ++count } else { cell.accessoryType = .None --count } if count == 4 { tableViewHandler(self.tableView, maxChecked: true, minChecked: false) } else if count == 1 { tableViewHandler(self.tableView, maxChecked: false, minChecked: true) } else { tableViewHandler(self.tableView, maxChecked: false, minChecked: false) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) /* if(containerViewController != nil) { containerViewController!.checked = self.checked } */ //print(count) //print("menu") //print(checked) //print("container") //print(containerViewController!.checked) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell")! cell.textLabel?.text = categories[indexPath.section][indexPath.row] cell.backgroundColor = UIColor.darkGrayColor() cell.tintColor = UIColor.orangeColor() cell.textLabel?.textColor = UIColor.whiteColor() if count == 4 { if myVariables.checked[indexPath.section][indexPath.row] { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None disableCell(cell) } } else if count == 1 { if myVariables.checked[indexPath.section][indexPath.row] { cell.accessoryType = .Checkmark disableCell(cell) } else { cell.accessoryType = .None } } else { if myVariables.checked[indexPath.section][indexPath.row] { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } } return cell } // MARK: Helper methods func disableCell(cell: UITableViewCell) { cell.userInteractionEnabled = false cell.backgroundColor = UIColor.blackColor() } func enableCell(cell: UITableViewCell) { cell.backgroundColor = UIColor.darkGrayColor() cell.userInteractionEnabled = true } func tableViewHandler(tableView: UITableView, maxChecked: Bool, minChecked: Bool) { if maxChecked { for i in 0 ..< myVariables.checked.count { for j in 0 ..< myVariables.checked[i].count { if !(myVariables.checked[i][j]) { disableCell(tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i))!) } } } } else if minChecked { for i in 0 ..< myVariables.checked.count { for j in 0 ..< myVariables.checked[i].count { if (myVariables.checked[i][j]) { disableCell(tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i))!) } } } } else { for i in 0 ..< myVariables.checked.count { for j in 0 ..< myVariables.checked[i].count { enableCell(tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i))!) } } } } /* // 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. } */ }
apache-2.0
58a82cbee84973ad8b14343402817b5a
33.049774
141
0.592558
5.367332
false
false
false
false
alobanov/Dribbble
Dribbble/helpers/RxModel/RxViewModel.swift
1
2314
// // RxViewModel.swift // Dribbble // // Created by Lobanov Aleksey on 08.09.16. // Copyright © 2016 Lobanov Aleksey. All rights reserved. // import Foundation import RxSwift // MARK: - Enum Values public enum LoadingState: Equatable { /// Content is available and not loading any content case normal /// No Content is available case empty /// Got an error loading content case error /// Is loading content case loading // Prepearing state case unknown // MARK: Properties var description: String { switch self { case .normal: return "Loading success" /// No Content is available case .empty: return "Empty results" /// Got an error loading content case .error: return "Loading failure" /// Is loading content case .loading: return "Loading in process..." // Prepearing state case .unknown: return "Not defined loading state" } } } // MARK: - Equatable public func == (lhs: LoadingState, rhs: LoadingState) -> Bool { switch (lhs, rhs) { case (.normal, .normal): return true case (.empty, .empty): return true case (.error, .error): return true case (.loading, .loading): return true default: return false } } protocol RxViewModelType { associatedtype InputDependencies associatedtype Input associatedtype Output func configure(input: Input) -> Output } protocol RxViewModelModuleType { associatedtype ModuleInput associatedtype ModuleOutput func configureModule(input: ModuleInput) -> ModuleOutput } protocol RxModelOutput { var loadingState: Observable<LoadingState> {get} var displayError: Observable<NSError> {get} } protocol ViewModelType { associatedtype InputDependencies } class RxViewModel { let bag = DisposeBag() var displayError: Observable<NSError> { return _displayError.asObservable().skip(1) } var loadingState: Observable<LoadingState> { return _loadingState.asObservable() } internal var _loadingState = Variable<LoadingState>(.unknown) internal var _displayError = Variable<NSError>(NSError(domain: "", code: 0, userInfo: nil)) init() { } func isRequestInProcess() -> Bool { guard _loadingState.value != .loading else { return true } _loadingState.value = .loading return false } }
mit
85ea8d16cd15bceba0f8f90bbbd0d020
21.028571
93
0.688716
4.372401
false
false
false
false
jegumhon/URMovingTransitionAnimator
Source/URMovingTransitionAnimator/URMoveBlurredTransitioningAnimator.swift
1
3632
// // URMoveBlurredTransitioningAnimator.swift // URMovingTransitionAnimator // // Created by jegumhon on 2017. 2. 16.. // Copyright © 2017년 chbreeze. All rights reserved. // import UIKit public class URMoveBlurredTransitioningAnimator: URMoveTransitioningAnimator { var fromViewSnapShot: UIView? var blurView: UIVisualEffectView? override func makeMovingKeyframe(_ movingView: UIView?, _ finishingFrame: CGRect, withRelativeStartTime: Double, relativeDuration: Double) { super.makeMovingKeyframe(movingView, finishingFrame, withRelativeStartTime: withRelativeStartTime, relativeDuration: relativeDuration) UIView.addKeyframe(withRelativeStartTime: withRelativeStartTime, relativeDuration: relativeDuration / 2.0) { let blurEffect = UIBlurEffect(style: .light) // let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect) self.blurView?.effect = blurEffect } UIView.addKeyframe(withRelativeStartTime: withRelativeStartTime + relativeDuration / 2.0, relativeDuration: relativeDuration / 2.0) { self.blurView?.effect = nil } UIView.addKeyframe(withRelativeStartTime: withRelativeStartTime, relativeDuration: relativeDuration) { self.fromViewSnapShot?.transform = CGAffineTransform(scaleX: 0.97, y: 0.97) self.fromViewSnapShot?.alpha = 0.0 } } func initBlurredView() { self.blurView = UIVisualEffectView() self.transitionCompletion = { (transitionContext) in print("begin ====> transitionCompletion:") let finishDuration = self.transitionDirection == .push ? self.transitionFinishDuration : self.transitionFinishDurationForPop if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), toViewController is URMovingTransitionReceivable && !self.isLazyCompletion { (toViewController as! URMovingTransitionReceivable).removeTransitionView(duration: finishDuration, completion: nil) } UIView.animate(withDuration: finishDuration, animations: { if !transitionContext.transitionWasCancelled { self.movingView?.alpha = 0.1 } }, completion: { (finish) in self.movingView?.removeFromSuperview() self.blurView?.removeFromSuperview() self.fromViewSnapShot?.removeFromSuperview() print("end ====> transitionCompletion:") if let postAction = self.transitionPostAction { postAction() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } override func initAnimationDescriptor(using transitionContext: UIViewControllerContextTransitioning) -> CGRect { let finishingFrame = super.initAnimationDescriptor(using: transitionContext) self.initBlurredView() guard let blurredView = self.blurView, let movedView = self.movingView else { return finishingFrame } blurredView.frame = UIScreen.main.bounds transitionContext.containerView.insertSubview(blurredView, belowSubview: movedView) if let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) { self.fromViewSnapShot = fromViewController.view.snapshotView(afterScreenUpdates: false)! transitionContext.containerView.insertSubview(self.fromViewSnapShot!, belowSubview: blurredView) } return finishingFrame } }
mit
15573f27323c957aa5921fb3394420eb
43.256098
197
0.7035
5.635093
false
false
false
false
PumpMagic/ostrich
gameboy/gameboy/Source/CPUs/Instructions/SUB.swift
1
5221
// // SUB.swift // ostrichframework // // Created by Ryan Conway on 3/31/16. // Copyright © 2016 Ryan Conway. All rights reserved. // import Foundation func sub<T: Integer>(_ v1: T, _ v2: T) -> T { return v1 &- v2 } func subWithoutStore <T: Readable & Writeable, U: Readable> (_ op1: T, _ op2: U) -> (T.ReadType, U.ReadType, T.WriteType) where T.WriteType == U.ReadType, T.ReadType == T.WriteType, T.ReadType: Integer { let op1v = op1.read() let op2v = op2.read() let result = sub(op1v, op2v) return (op1v, op2v, result) } func subWithoutStore <T: Readable & Writeable, U: Readable> (_ op1: T, _ op2: U, _ op3: Bool) -> (T.ReadType, U.ReadType, T.ReadType, T.WriteType) where T.WriteType == U.ReadType, T.ReadType == T.WriteType, T.ReadType: Integer { let op1v = op1.read() let op2v = op2.read() let op3v: T.ReadType = op3 ? 1 : 0 let result = sub(sub(op1v, op2v), op3v) return (op1v, op2v, op3v, result) } private func subAndStore <T: Readable & Writeable, U: Readable> (_ op1: T, _ op2: U) -> (T.ReadType, U.ReadType, T.WriteType) where T.WriteType == U.ReadType, T.ReadType == T.WriteType, T.ReadType: Integer { let (op1v, op2v, result) = subWithoutStore(op1, op2) op1.write(result) return (op1v, op2v, result) } private func subAndStore <T: Readable & Writeable, U: Readable> (_ op1: T, _ op2: U, _ op3: Bool) -> (T.ReadType, U.ReadType, T.ReadType, T.WriteType) where T.WriteType == U.ReadType, T.ReadType == T.WriteType, T.ReadType: Integer { let (op1v, op2v, op3v, result) = subWithoutStore(op1, op2, op3) op1.write(result) return (op1v, op2v, op3v, result) } /// Subtract from the accumulator an 8-bit operand; overwrite the accumulator with the result struct SUB <T: Readable & OperandType>: Z80Instruction, LR35902Instruction where T.ReadType == UInt8 { let op: T let cycleCount = 0 func runOn(_ cpu: Z80) { let (op1v, op2v, result) = subAndStore(cpu.A, op) modifyFlags(cpu, op1: op1v, op2: op2v, result: result) } func runOn(_ cpu: LR35902) { let (op1v, op2v, result) = subAndStore(cpu.A, op) modifyFlags(cpu, op1: op1v, op2: op2v, result: result) } fileprivate func modifyCommonFlags(_ cpu: Intel8080Like, op1: UInt8, op2: T.ReadType, result: UInt8) { // Z is set if result is 0; otherwise, it is reset. // H is set if borrow from bit 4; otherwise, it is reset. // N is set. // C is set if borrow; otherwise, it is reset cpu.ZF.write(result == 0x00) cpu.HF.write(subHalfBorrowProne(op1, op2)) cpu.NF.write(true) cpu.CF.write(subBorrowProne(op1, op2)) } fileprivate func modifyFlags(_ cpu: Z80, op1: UInt8, op2: T.ReadType, result: UInt8) { modifyCommonFlags(cpu, op1: op1, op2: op2, result: result) // S is set if result is negative; otherwise, it is reset. // P/V is set if overflow; otherwise, it is reset. cpu.SF.write(numberIsNegative(result)) cpu.PVF.write(subOverflowOccurred(op1, op2: op2, result: result)) } fileprivate func modifyFlags(_ cpu: LR35902, op1: UInt8, op2: T.ReadType, result: UInt8) { modifyCommonFlags(cpu, op1: op1, op2: op2, result: result) } } /// Subtract from the accumulator an 8-bit operand and the carry flag; overwrite the accumulator with the result struct SBC <T: Readable & OperandType>: Z80Instruction, LR35902Instruction where T.ReadType == UInt8 { let op: T let cycleCount = 0 func runOn(_ cpu: Z80) { let (op1v, op2v, op3v, result) = subAndStore(cpu.A, op, cpu.CF.read()) modifyFlags(cpu, op1: op1v, op2: op2v, op3: op3v, result: result) } func runOn(_ cpu: LR35902) { let (op1v, op2v, op3v, result) = subAndStore(cpu.A, op, cpu.CF.read()) modifyFlags(cpu, op1: op1v, op2: op2v, op3: op3v, result: result) } fileprivate func modifyCommonFlags(_ cpu: Intel8080Like, op1: UInt8, op2: T.ReadType, op3: UInt8, result: UInt8) { // Z is set if result is 0; otherwise, it is reset. // H is set if borrow from bit 4; otherwise, it is reset. // N is set. // C is set if borrow; otherwise, it is reset. cpu.ZF.write(result == 0x00) cpu.HF.write(subHalfBorrowProne(op1, op2, op3)) cpu.NF.write(true) cpu.CF.write(subBorrowProne(op1, op2, op3)) } fileprivate func modifyFlags(_ cpu: Z80, op1: UInt8, op2: T.ReadType, op3: UInt8, result: UInt8) { modifyCommonFlags(cpu, op1: op1, op2: op2, op3: op3, result: result) // S is set if result is negative; otherwise, it is reset. // P/V is reset if overflow; otherwise, it is reset. cpu.SF.write(numberIsNegative(result)) cpu.PVF.write(subOverflowOccurred(op1, op2: op2, result: result)) } fileprivate func modifyFlags(_ cpu: LR35902, op1: UInt8, op2: T.ReadType, op3: UInt8, result: UInt8) { modifyCommonFlags(cpu, op1: op1, op2: op2, op3: op3, result: result) } }
mit
f69bac5d88b5d74c6eaf0902f9589f26
31.830189
118
0.615326
2.984563
false
false
false
false
shajrawi/swift
test/ParseableInterface/conformances.swift
1
9305
// RUN: %target-swift-frontend-typecheck -emit-parseable-module-interface-path %t.swiftinterface %s // RUN: %FileCheck %s < %t.swiftinterface // RUN: %FileCheck -check-prefix CHECK-END %s < %t.swiftinterface // RUN: %FileCheck -check-prefix NEGATIVE %s < %t.swiftinterface // NEGATIVE-NOT: BAD // CHECK-LABEL: public protocol SimpleProto { public protocol SimpleProto { // CHECK: associatedtype Element associatedtype Element // CHECK: associatedtype Inferred associatedtype Inferred func inference(_: Inferred) } // CHECK: {{^}$}} // CHECK-LABEL: public struct SimpleImpl<Element> : SimpleProto { public struct SimpleImpl<Element>: SimpleProto { // NEGATIVE-NOT: typealias Element = // CHECK: public func inference(_: Int){{$}} public func inference(_: Int) {} // CHECK: public typealias Inferred = Swift.Int } // CHECK: {{^}$}} public protocol PublicProto {} private protocol PrivateProto {} // CHECK: public struct A1 : PublicProto { // NEGATIVE-NOT: extension conformances.A1 public struct A1: PublicProto, PrivateProto {} // CHECK: public struct A2 : PublicProto { // NEGATIVE-NOT: extension conformances.A2 public struct A2: PrivateProto, PublicProto {} // CHECK: public struct A3 { // CHECK-END: extension conformances.A3 : conformances.PublicProto {} public struct A3: PublicProto & PrivateProto {} // CHECK: public struct A4 { // CHECK-END: extension conformances.A4 : conformances.PublicProto {} public struct A4: PrivateProto & PublicProto {} public protocol PublicBaseProto {} private protocol PrivateSubProto: PublicBaseProto {} // CHECK: public struct B1 { // CHECK-END: extension conformances.B1 : conformances.PublicBaseProto {} public struct B1: PrivateSubProto {} // CHECK: public struct B2 : PublicBaseProto { // NEGATIVE-NOT: extension conformances.B2 public struct B2: PublicBaseProto, PrivateSubProto {} // CHECK: public struct B3 { // CHECK-END: extension conformances.B3 : conformances.PublicBaseProto {} public struct B3: PublicBaseProto & PrivateSubProto {} // CHECK: public struct B4 : PublicBaseProto { // NEGATIVE-NOT: extension B4 { // NEGATIVE-NOT: extension conformances.B4 public struct B4: PublicBaseProto {} extension B4: PrivateSubProto {} // CHECK: public struct B5 { // CHECK: extension B5 : PublicBaseProto { // NEGATIVE-NOT: extension conformances.B5 public struct B5: PrivateSubProto {} extension B5: PublicBaseProto {} // CHECK: public struct B6 { // NEGATIVE-NOT: extension B6 { // CHECK: extension B6 : PublicBaseProto { // NEGATIVE-NOT: extension conformances.B6 public struct B6 {} extension B6: PrivateSubProto {} extension B6: PublicBaseProto {} // CHECK: public struct B7 { // CHECK: extension B7 : PublicBaseProto { // NEGATIVE-NOT: extension B7 { // NEGATIVE-NOT: extension conformances.B7 public struct B7 {} extension B7: PublicBaseProto {} extension B7: PrivateSubProto {} // CHECK-LABEL: public struct OuterGeneric<T> { public struct OuterGeneric<T> { // CHECK-NEXT: public struct Inner { public struct Inner: PrivateSubProto {} // CHECK-NEXT: {{^ }$}} } // CHECK-NEXT: {{^}$}} public protocol ConditionallyConformed {} public protocol ConditionallyConformedAgain {} // CHECK-END: @available(*, unavailable) // CHECK-END-NEXT: extension conformances.OuterGeneric : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {} extension OuterGeneric: ConditionallyConformed where T: PrivateProto {} extension OuterGeneric: ConditionallyConformedAgain where T == PrivateProto {} // CHECK-END: extension conformances.OuterGeneric.Inner : conformances.PublicBaseProto {} // CHECK-END: @available(*, unavailable) // CHECK-END-NEXT: extension conformances.OuterGeneric.Inner : conformances.ConditionallyConformed, conformances.ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {} extension OuterGeneric.Inner: ConditionallyConformed where T: PrivateProto {} extension OuterGeneric.Inner: ConditionallyConformedAgain where T == PrivateProto {} private protocol AnotherPrivateSubProto: PublicBaseProto {} // CHECK: public struct C1 { // CHECK-END: extension conformances.C1 : conformances.PublicBaseProto {} public struct C1: PrivateSubProto, AnotherPrivateSubProto {} // CHECK: public struct C2 { // CHECK-END: extension conformances.C2 : conformances.PublicBaseProto {} public struct C2: PrivateSubProto & AnotherPrivateSubProto {} // CHECK: public struct C3 { // NEGATIVE-NOT: extension C3 { // CHECK-END: extension conformances.C3 : conformances.PublicBaseProto {} public struct C3: PrivateSubProto {} extension C3: AnotherPrivateSubProto {} public protocol PublicSubProto: PublicBaseProto {} public protocol APublicSubProto: PublicBaseProto {} // CHECK: public struct D1 : PublicSubProto { // NEGATIVE-NOT: extension conformances.D1 public struct D1: PublicSubProto, PrivateSubProto {} // CHECK: public struct D2 : PublicSubProto { // NEGATIVE-NOT: extension conformances.D2 public struct D2: PrivateSubProto, PublicSubProto {} // CHECK: public struct D3 { // CHECK-END: extension conformances.D3 : conformances.PublicBaseProto {} // CHECK-END: extension conformances.D3 : conformances.PublicSubProto {} public struct D3: PrivateSubProto & PublicSubProto {} // CHECK: public struct D4 { // CHECK-END: extension conformances.D4 : conformances.APublicSubProto {} // CHECK-END: extension conformances.D4 : conformances.PublicBaseProto {} public struct D4: APublicSubProto & PrivateSubProto {} // CHECK: public struct D5 { // CHECK: extension D5 : PublicSubProto { // NEGATIVE-NOT: extension conformances.D5 public struct D5: PrivateSubProto {} extension D5: PublicSubProto {} // CHECK: public struct D6 : PublicSubProto { // NEGATIVE-NOT: extension D6 { // NEGATIVE-NOT: extension conformances.D6 public struct D6: PublicSubProto {} extension D6: PrivateSubProto {} private typealias PrivateProtoAlias = PublicProto // CHECK: public struct E1 { // CHECK-END: extension conformances.E1 : conformances.PublicProto {} public struct E1: PrivateProtoAlias {} private typealias PrivateSubProtoAlias = PrivateSubProto // CHECK: public struct F1 { // CHECK-END: extension conformances.F1 : conformances.PublicBaseProto {} public struct F1: PrivateSubProtoAlias {} private protocol ClassConstrainedProto: PublicProto, AnyObject {} public class G1: ClassConstrainedProto {} // CHECK: public class G1 { // CHECK-END: extension conformances.G1 : conformances.PublicProto {} public class Base {} private protocol BaseConstrainedProto: Base, PublicProto {} public class H1: Base, ClassConstrainedProto {} // CHECK: public class H1 : Base { // CHECK-END: extension conformances.H1 : conformances.PublicProto {} public struct MultiGeneric<T, U, V> {} extension MultiGeneric: PublicProto where U: PrivateProto {} // CHECK: public struct MultiGeneric<T, U, V> { // CHECK-END: @available(*, unavailable) // CHECK-END-NEXT: extension conformances.MultiGeneric : conformances.PublicProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {} internal struct InternalImpl_BAD: PrivateSubProto {} internal struct InternalImplConstrained_BAD<T> {} extension InternalImplConstrained_BAD: PublicProto where T: PublicProto {} internal struct InternalImplConstrained2_BAD<T> {} extension InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {} public struct WrapperForInternal { internal struct InternalImpl_BAD: PrivateSubProto {} internal struct InternalImplConstrained_BAD<T> {} internal struct InternalImplConstrained2_BAD<T> {} } extension WrapperForInternal.InternalImplConstrained_BAD: PublicProto where T: PublicProto {} extension WrapperForInternal.InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {} internal protocol ExtraHashable: Hashable {} extension Bool: ExtraHashable {} @available(iOS, unavailable) @available(macOS, unavailable) public struct CoolTVType: PrivateSubProto {} // CHECK: public struct CoolTVType { // CHECK-END: @available(OSX, unavailable) // CHECK-END-NEXT: @available(iOS, unavailable) // CHECK-END-NEXT: extension conformances.CoolTVType : conformances.PublicBaseProto {} @available(macOS 10.99, *) public struct VeryNewMacType: PrivateSubProto {} // CHECK: public struct VeryNewMacType { // CHECK-END: @available(OSX, introduced: 10.99) // CHECK-END-NEXT: extension conformances.VeryNewMacType : conformances.PublicBaseProto {} public struct VeryNewMacProto {} @available(macOS 10.98, *) extension VeryNewMacProto: PrivateSubProto {} // CHECK: public struct VeryNewMacProto { // CHECK-END: @available(OSX, introduced: 10.98) // CHECK-END-NEXT: extension conformances.VeryNewMacProto : conformances.PublicBaseProto {} public struct PrivateProtoConformer {} extension PrivateProtoConformer : PrivateProto { public var member: Int { return 0 } } // CHECK: public struct PrivateProtoConformer { // CHECK: extension PrivateProtoConformer { // CHECK-NEXT: public var member: Int { // CHECK-NEXT: get // CHECK-NEXT: } // CHECK-NEXT: {{^}$}} // NEGATIVE-NOT: extension conformances.PrivateProtoConformer // NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Hashable // NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Equatable // CHECK-END: @usableFromInline // CHECK-END-NEXT: internal protocol _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
apache-2.0
80c6587a715bca3791535111e55c2243
39.107759
199
0.768189
4.387082
false
false
false
false
alessandrostone/AttributedLabel
AttributedLabel/AttributedLabel.swift
2
6415
// // AttributedLabel.swift // AttributedLabel // // Created by Kyohei Ito on 2015/07/17. // Copyright © 2015年 Kyohei Ito. All rights reserved. // import UIKit public class AttributedLabel: UIView { public enum ContentAlignment: Int { case Center case Top case Bottom case Left case Right case TopLeft case TopRight case BottomLeft case BottomRight func alignOffset(#viewSize: CGSize, containerSize: CGSize) -> CGPoint { let xMargin = viewSize.width - containerSize.width let yMargin = viewSize.height - containerSize.height switch self { case Center: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin / 2, 0)) case Top: return CGPoint(x: max(xMargin / 2, 0), y: 0) case Bottom: return CGPoint(x: max(xMargin / 2, 0), y: max(yMargin, 0)) case Left: return CGPoint(x: 0, y: max(yMargin / 2, 0)) case Right: return CGPoint(x: max(xMargin, 0), y: max(yMargin / 2, 0)) case TopLeft: return CGPoint(x: 0, y: 0) case TopRight: return CGPoint(x: max(xMargin, 0), y: 0) case BottomLeft: return CGPoint(x: 0, y: max(yMargin, 0)) case BottomRight: return CGPoint(x: max(xMargin, 0), y: max(yMargin, 0)) } } } /// default is `0`. public var numberOfLines: Int = 0 { didSet { setNeedsDisplay() } } /// default is `Left`. public var contentAlignment: ContentAlignment = .Left { didSet { setNeedsDisplay() } } /// default is system font 17 plain. public var font = UIFont.systemFontOfSize(17) { didSet { setNeedsDisplay() } } /// default is `ByTruncatingTail`. public var lineBreakMode: NSLineBreakMode = .ByTruncatingTail { didSet { setNeedsDisplay() } } /// default is nil (text draws black). public var textColor: UIColor? { didSet { setNeedsDisplay() } } /// default is nil. public var paragraphStyle: NSParagraphStyle? { didSet { setNeedsDisplay() } } /// default is nil. public var shadow: NSShadow? { didSet { setNeedsDisplay() } } /// default is nil. public var attributedText: NSAttributedString? { didSet { setNeedsDisplay() } } /// default is nil. public var text: String? { get { return attributedText?.string } set { if let value = newValue { attributedText = NSAttributedString(string: value) } else { attributedText = nil } } } private var mergedAttributedText: NSAttributedString? { if let attributedText = attributedText { return mergeAttributes(attributedText) } return nil } public override func awakeFromNib() { super.awakeFromNib() opaque = false contentMode = .Redraw } public override func drawRect(rect: CGRect) { if let attributedText = mergedAttributedText { let container = textContainer(rect.size) let manager = layoutManager(container) let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(manager) let frame = manager.usedRectForTextContainer(container) let point = contentAlignment.alignOffset(viewSize: rect.size, containerSize: CGRectIntegral(frame).size) let glyphRange = manager.glyphRangeForTextContainer(container) manager.drawBackgroundForGlyphRange(glyphRange, atPoint: point) manager.drawGlyphsForGlyphRange(glyphRange, atPoint: point) } } public override func sizeThatFits(size: CGSize) -> CGSize { if let attributedText = mergedAttributedText { let container = textContainer(size) let manager = layoutManager(container) let storage = NSTextStorage(attributedString: attributedText) storage.addLayoutManager(manager) let frame = manager.usedRectForTextContainer(container) return CGRectIntegral(frame).size } return super.sizeThatFits(size) } public override func sizeToFit() { super.sizeToFit() frame.size = sizeThatFits(CGSize(width: bounds.width, height: CGFloat.max)) } private func textContainer(size: CGSize) -> NSTextContainer { let container = NSTextContainer(size: size) container.lineBreakMode = lineBreakMode container.lineFragmentPadding = 0 container.maximumNumberOfLines = numberOfLines return container } private func layoutManager(container: NSTextContainer) -> NSLayoutManager { let layoutManager = NSLayoutManager() layoutManager.addTextContainer(container) return layoutManager } private func mergeAttributes(attributedText: NSAttributedString) -> NSAttributedString { let attrString = NSMutableAttributedString(attributedString: attributedText) addAttribute(attrString, attrName: NSFontAttributeName, attr: font) if let textColor = textColor { addAttribute(attrString, attrName: NSForegroundColorAttributeName, attr: textColor) } if let paragraphStyle = paragraphStyle { addAttribute(attrString, attrName: NSParagraphStyleAttributeName, attr: paragraphStyle) } if let shadow = shadow { addAttribute(attrString, attrName: NSShadowAttributeName, attr: shadow) } return attrString } private func addAttribute(attrString: NSMutableAttributedString, attrName: String, attr: AnyObject) { let range = NSRange(location: 0, length: attrString.length) attrString.enumerateAttribute(attrName, inRange: range, options: .Reverse) { object, range, pointer in if object == nil { attrString.addAttributes([attrName: attr], range: range) } } } }
mit
1ccaad3bd1b31f3117d51b934e0d881d
32.747368
116
0.594666
5.352254
false
false
false
false
alexanderedge/European-Sports
EurosportPlayerTV/Views/LiveStreamCollectionViewCell.swift
1
895
// // LiveStreamCollectionViewCell.swift // EurosportPlayer // // Created by Alexander Edge on 29/05/2016. import UIKit class LiveStreamCollectionViewCell: ImageCollectionViewCell { @IBOutlet var sportLabel: UILabel! @IBOutlet var titleLabel: UILabel! @IBOutlet var detailLabel: UILabel! @IBOutlet var logoImageView: WebImageView! override func awakeFromNib() { super.awakeFromNib() imageView.backgroundColor = .red imageView.adjustsImageWhenAncestorFocused = true logoImageView.adjustsImageWhenAncestorFocused = false sportLabel.textColor = UIColor.lightGray titleLabel.textColor = UIColor.white detailLabel.textColor = UIColor.lightGray } override func prepareForReuse() { super.prepareForReuse() logoImageView.cancelCurrentImageLoad() logoImageView.image = nil } }
mit
ea68bb0b60c872f4e9adadbc4c64f882
22.552632
61
0.70838
5.233918
false
false
false
false
smittytone/FightingFantasy
FightingFantasy/FFBookmarkView.swift
1
1617
// FightingFantasy // Created by Tony Smith on 02/11/2017. // Software © 2017 Tony Smith. All rights reserved. // Software ONLY issued under MIT Licence // Fighting Fantasy © 2016 Steve Jackson and Ian Livingstone import Cocoa class FFBookmarkView: NSImageView { // The 'place' property is a gamebook paragraph set by the player var place: Int = -1 override func awakeFromNib() { place = -1 } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if place != -1 { // A bookmark has been set and passed to the view via the 'place' property // NOTE A value of -1 indicates no bookmark has been set var stringOrigin: NSPoint = NSMakePoint(0, 0) // Set up an attributed string that's grey text, Bold and 20pt let stringAttributes: [NSAttributedStringKey : Any] = [ NSAttributedStringKey.foregroundColor : NSColor.init(white: 0.9, alpha: 0.9), NSAttributedStringKey.font: NSFont.init(name: "Apple Chancery", size: 20)! ] // Convert the value of place to an attrributed string let lString = "\(place)" as NSString let stringSize = lString.size(withAttributes: stringAttributes) // Draw the string over the background ribbon image stringOrigin.x = self.bounds.origin.x + (self.bounds.size.width - stringSize.width)/2; stringOrigin.y = self.bounds.origin.y + 40 - (stringSize.height / 2); lString.draw(at: stringOrigin, withAttributes: stringAttributes) } } }
mit
26c075945ec580fd51e0d8fafdd6edb5
33.361702
98
0.635294
4.329759
false
false
false
false
AngryLi/ResourceSummary
iOS/Demos/Assignments_swift/assignment-final/SwiftFinal/SwiftFinal/Classes/doodle/CollectionView/Controller/LsCollectionViewController.swift
3
2760
// // LsCollectionViewController.swift // 01-collectionview // // Created by 李亚洲 on 15/6/19. // Copyright (c) 2015年 angryli. All rights reserved. // import UIKit let reuseIdentifier = "Cell" class LsCollectionViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { var imagesCollectionView : UICollectionView! private var images : [UIImage]! override func viewDidLoad() { super.viewDidLoad() //初始化imagesCollectionView setCollectionView() images = LsDBOperator().getAllHisrory() } private func setCollectionView() { let device_width = UIScreen.mainScreen().bounds.size.width let device_hight = UIScreen.mainScreen().bounds.size.height let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSizeMake(150, 150) flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical//设置垂直显示 flowLayout.sectionInset = UIEdgeInsetsMake(10, 5, 0, 5)//设置边距 flowLayout.minimumLineSpacing = 0.0 //每个相邻layout的上下 flowLayout.minimumInteritemSpacing = 0.0 //每个相邻layout的左右 flowLayout.headerReferenceSize = CGSizeMake(0, 0) self.imagesCollectionView = UICollectionView(frame: CGRectMake(0,0,device_width, device_hight), collectionViewLayout: flowLayout) self.imagesCollectionView.backgroundColor = UIColor.whiteColor() self.imagesCollectionView.alwaysBounceVertical = true self.imagesCollectionView.delegate = self self.imagesCollectionView.dataSource = self self.view.addSubview(self.imagesCollectionView) self.imagesCollectionView.registerNib(UINib(nibName: "LsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return images.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let mycell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LsCollectionViewCell // Configure the cell mycell.imageView.image = images[indexPath.row] // cell.backgroundColor = UIColor.redColor() return mycell } }
mit
91e319f6a526b2b725643accfd9d3b72
42.516129
143
0.728688
5.374502
false
false
false
false
LogTenSafe/MacOSX
LogTenSafe/Source/Views/Main View/Backup List/BackupItemView.swift
1
2640
import SwiftUI struct BackupItemView: View { let backup: Backup @EnvironmentObject private var viewController: MainViewController private static let titleDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .short return formatter }() private static let flightDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none return formatter }() private static let hoursFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 1 return formatter }() private static let sizeFormatter = ByteCountFormatter() var body: some View { HStack(alignment: .top) { VStack(alignment: .leading) { Text(Self.titleDateFormatter.string(from: backup.createdAt!)).font(.headline) Text("from \(backup.hostname)").controlSize(.small) if backup.lastFlight != nil { Text("Last flight: \(flightString(backup.lastFlight!))") } } Spacer() VStack(alignment: .trailing) { HStack { Text(Self.sizeFormatter.string(fromByteCount: Int64(backup.logbook.size))).controlSize(.small) Button("Restore") { self.viewController.restoreBackup(self.backup) } .controlSize(.small) .disabled(viewController.restoringBackup || !self.backup.logbook.analyzed) } Text("\(Self.hoursFormatter.string(from: NSNumber(value: backup.totalHours))!) hr").controlSize(.small) } } } private func flightString(_ flight: Flight) -> String { guard let hoursString = Self.hoursFormatter.string(from: NSNumber(value: flight.duration)) else { preconditionFailure("Couldn’t format flight duration") } return "\(Self.flightDateFormatter.string(from: flight.date!)) \(airport(identifier: flight.origin)) → \(airport(identifier: flight.destination)) (\(hoursString) hr)" } private func airport(identifier: String?) -> String { return identifier ?? "???" } } struct BackupItemView_Previews: PreviewProvider { static var previews: some View { BackupItemView(backup: exampleBackups()[0]).environmentObject(MainViewController()) } }
mit
3bd918e5b7dbc0b304a632fc0d28425a
36.126761
174
0.605083
5.325253
false
false
false
false
ianrahman/HackerRankChallenges
Swift/Algorithms/Warmup/plus-minus.swift
1
527
import Foundation // number of elements let n = Int(readLine()!)! // read array and map the elements to integer let arr = readLine()!.components(separatedBy: " ").map{ Int($0)! } let nFloat: Float = Float(n) var pos: Float = 0 var neg: Float = 0 var zero: Float = 0 for num in arr { if num > 0 { pos += 1 } else if num < 0 { neg += 1 } else { zero += 1 } } print(String(format: "%.6f", pos/nFloat)) print(String(format: "%.6f", neg/nFloat)) print(String(format: "%.6f", zero/nFloat))
mit
69d38b7bd88d53fae9cba916c3e33b6b
20.958333
66
0.588235
3.136905
false
false
false
false
ZevEisenberg/Padiddle
Padiddle/Padiddle/Model/ColorManager.swift
1
2848
// // ColorManager.swift // Padiddle // // Created by Zev Eisenberg on 9/15/15. // Copyright © 2015 Zev Eisenberg. All rights reserved. // import UIKit.UIColor enum ColorMode { case thetaIncreasing case thetaIncreasingAndDecreasing case velocityOut case velocityIn case manual(CGFloat) } enum ColorModel { case hsv(h: ColorMode, s: ColorMode, v: ColorMode) case rgb(r: ColorMode, g: ColorMode, b: ColorMode) } struct ColorManager { var radius: CGFloat = 0 var theta: CGFloat = 0 { didSet { theta = theta.truncatingRemainder(dividingBy: twoPi) } } var maxRadius: CGFloat = 0 let colorModel: ColorModel var title: String var currentColor: UIColor { ColorManager.color(colorModel: colorModel, radius: radius, maxRadius: maxRadius, theta: theta) } init(colorModel: ColorModel, title: String) { self.colorModel = colorModel self.title = title } private static func color(colorModel: ColorModel, radius: CGFloat, maxRadius: CGFloat, theta: CGFloat) -> UIColor { let color: UIColor switch colorModel { case let .hsv(hMode, sMode, vMode): let h = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: hMode) let s = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: sMode) let v = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: vMode) color = UIColor(hue: h, saturation: s, brightness: v, alpha: 1) case let .rgb(rMode, gMode, bMode): let r = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: rMode) let g = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: gMode) let b = channelValue(radius, maxRadius: maxRadius, theta: theta, colorMode: bMode) color = UIColor(red: r, green: g, blue: b, alpha: 1) } return color } private static func channelValue(_ radius: CGFloat, maxRadius: CGFloat, theta: CGFloat, colorMode: ColorMode) -> CGFloat { let channelValue: CGFloat switch colorMode { case .thetaIncreasing: channelValue = theta / twoPi case .thetaIncreasingAndDecreasing: var value: CGFloat if theta > .pi { value = twoPi - theta } else { value = theta } channelValue = value / .pi case .velocityOut: assert(maxRadius > 0) channelValue = radius / maxRadius case .velocityIn: assert(maxRadius > 0) channelValue = 1 - (radius / maxRadius) case let .manual(value): channelValue = value } return channelValue } }
mit
0770d52222b8b04d1325b0d78e95e6b0
27.188119
126
0.607657
4.294118
false
false
false
false
dduan/swift
benchmark/utils/main.swift
1
7996
//===--- main.swift -------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is automatically generated from templates and should not // be directly modified. Instead, make changes to // scripts/generate_harness/main.swift_template and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySubscript import BitCount import ByteSwap import Calculator import CaptureProp import Chars import ClassArrayGetter import DeadArray import DictTest import DictTest2 import DictTest3 import DictionaryBridge import DictionaryLiteral import DictionaryRemove import DictionarySwap import ErrorHandling import Fibonacci import GlobalClass import Hanoi import Hash import Histogram import Integrate import Join import LinkedList import MapReduce import Memset import MonteCarloE import MonteCarloPi import NSDictionaryCastToSwift import NSError import NSStringConversion import NopDeinit import ObjectAllocation import ObjectiveCBridging import ObjectiveCBridgingStubs import OpenClose import Phonebook import PolymorphicCalls import PopFront import PopFrontGeneric import Prims import ProtocolDispatch import ProtocolDispatch2 import RC4 import RGBHistogram import RangeAssignment import RecursiveOwnedParameter import SetTests import SevenBoom import Sim2DArray import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringInterpolation import StringTests import StringWalk import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import XorLoop precommitTests = [ "AngryPhonebook": run_AngryPhonebook, "Array2D": run_Array2D, "ArrayAppend": run_ArrayAppend, "ArrayAppendReserved": run_ArrayAppendReserved, "ArrayInClass": run_ArrayInClass, "ArrayLiteral": run_ArrayLiteral, "ArrayOfGenericPOD": run_ArrayOfGenericPOD, "ArrayOfGenericRef": run_ArrayOfGenericRef, "ArrayOfPOD": run_ArrayOfPOD, "ArrayOfRef": run_ArrayOfRef, "ArraySubscript": run_ArraySubscript, "ArrayValueProp": run_ArrayValueProp, "ArrayValueProp2": run_ArrayValueProp2, "ArrayValueProp3": run_ArrayValueProp3, "ArrayValueProp4": run_ArrayValueProp4, "BitCount": run_BitCount, "ByteSwap": run_ByteSwap, "Calculator": run_Calculator, "CaptureProp": run_CaptureProp, "Chars": run_Chars, "ClassArrayGetter": run_ClassArrayGetter, "DeadArray": run_DeadArray, "Dictionary": run_Dictionary, "DictionaryOfObjects": run_DictionaryOfObjects, "Dictionary2": run_Dictionary2, "Dictionary2OfObjects": run_Dictionary2OfObjects, "Dictionary3": run_Dictionary3, "Dictionary3OfObjects": run_Dictionary3OfObjects, "DictionaryBridge": run_DictionaryBridge, "DictionaryLiteral": run_DictionaryLiteral, "DictionaryRemove": run_DictionaryRemove, "DictionaryRemoveOfObjects": run_DictionaryRemoveOfObjects, "DictionarySwap": run_DictionarySwap, "DictionarySwapOfObjects": run_DictionarySwapOfObjects, "ErrorHandling": run_ErrorHandling, "GlobalClass": run_GlobalClass, "Hanoi": run_Hanoi, "HashTest": run_HashTest, "Histogram": run_Histogram, "Integrate": run_Integrate, "Join": run_Join, "LinkedList": run_LinkedList, "MapReduce": run_MapReduce, "Memset": run_Memset, "MonteCarloE": run_MonteCarloE, "MonteCarloPi": run_MonteCarloPi, "NSDictionaryCastToSwift": run_NSDictionaryCastToSwift, "NSError": run_NSError, "NSStringConversion": run_NSStringConversion, "NopDeinit": run_NopDeinit, "ObjectAllocation": run_ObjectAllocation, "ObjectiveCBridgeFromNSString": run_ObjectiveCBridgeFromNSString, "ObjectiveCBridgeFromNSStringForced": run_ObjectiveCBridgeFromNSStringForced, "ObjectiveCBridgeToNSString": run_ObjectiveCBridgeToNSString, "ObjectiveCBridgeFromNSArrayAnyObject": run_ObjectiveCBridgeFromNSArrayAnyObject, "ObjectiveCBridgeFromNSArrayAnyObjectForced": run_ObjectiveCBridgeFromNSArrayAnyObjectForced, "ObjectiveCBridgeToNSArray": run_ObjectiveCBridgeToNSArray, "ObjectiveCBridgeFromNSArrayAnyObjectToString": run_ObjectiveCBridgeFromNSArrayAnyObjectToString, "ObjectiveCBridgeFromNSArrayAnyObjectToStringForced": run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced, "ObjectiveCBridgeFromNSDictionaryAnyObject": run_ObjectiveCBridgeFromNSDictionaryAnyObject, "ObjectiveCBridgeFromNSDictionaryAnyObjectForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced, "ObjectiveCBridgeFromNSDictionaryAnyObjectToString": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString, "ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced, "ObjectiveCBridgeToNSDictionary": run_ObjectiveCBridgeToNSDictionary, "ObjectiveCBridgeFromNSSetAnyObject": run_ObjectiveCBridgeFromNSSetAnyObject, "ObjectiveCBridgeFromNSSetAnyObjectForced": run_ObjectiveCBridgeFromNSSetAnyObjectForced, "ObjectiveCBridgeFromNSSetAnyObjectToString": run_ObjectiveCBridgeFromNSSetAnyObjectToString, "ObjectiveCBridgeFromNSSetAnyObjectToStringForced": run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced, "ObjectiveCBridgeToNSSet": run_ObjectiveCBridgeToNSSet, "ObjectiveCBridgeStubFromNSString": run_ObjectiveCBridgeStubFromNSString, "ObjectiveCBridgeStubToNSString": run_ObjectiveCBridgeStubToNSString, "ObjectiveCBridgeStubFromArrayOfNSString": run_ObjectiveCBridgeStubFromArrayOfNSString, "ObjectiveCBridgeStubToArrayOfNSString": run_ObjectiveCBridgeStubToArrayOfNSString, "OpenClose": run_OpenClose, "Phonebook": run_Phonebook, "PolymorphicCalls": run_PolymorphicCalls, "PopFrontArray": run_PopFrontArray, "PopFrontArrayGeneric": run_PopFrontArrayGeneric, "PopFrontUnsafePointer": run_PopFrontUnsafePointer, "Prims": run_Prims, "ProtocolDispatch": run_ProtocolDispatch, "ProtocolDispatch2": run_ProtocolDispatch2, "RC4": run_RC4, "RGBHistogram": run_RGBHistogram, "RGBHistogramOfObjects": run_RGBHistogramOfObjects, "RangeAssignment": run_RangeAssignment, "RecursiveOwnedParameter": run_RecursiveOwnedParameter, "SetExclusiveOr": run_SetExclusiveOr, "SetIntersect": run_SetIntersect, "SetIsSubsetOf": run_SetIsSubsetOf, "SetUnion": run_SetUnion, "SetExclusiveOr_OfObjects": run_SetExclusiveOr_OfObjects, "SetIntersect_OfObjects": run_SetIntersect_OfObjects, "SetIsSubsetOf_OfObjects": run_SetIsSubsetOf_OfObjects, "SetUnion_OfObjects": run_SetUnion_OfObjects, "SevenBoom": run_SevenBoom, "Sim2DArray": run_Sim2DArray, "SortLettersInPlace": run_SortLettersInPlace, "SortStrings": run_SortStrings, "StackPromo": run_StackPromo, "StaticArray": run_StaticArray, "StrComplexWalk": run_StrComplexWalk, "StrToInt": run_StrToInt, "StringBuilder": run_StringBuilder, "StringInterpolation": run_StringInterpolation, "StringWalk": run_StringWalk, "StringWithCString": run_StringWithCString, "SuperChars": run_SuperChars, "TwoSum": run_TwoSum, "TypeFlood": run_TypeFlood, "UTF8Decode": run_UTF8Decode, "Walsh": run_Walsh, "XorLoop": run_XorLoop, ] otherTests = [ "Ackermann": run_Ackermann, "Fibonacci": run_Fibonacci, ] main()
apache-2.0
910af169b106d2ed350a2f76634a4020
35.018018
121
0.788269
5.125641
false
false
false
false
poetmountain/PapersPlease
Demo/PapersPlease/ViewController.swift
1
3070
// // ViewController.swift // PapersPlease // // Created by Brett Walker on 7/6/14. // Copyright (c) 2014-2016 Poet & Mountain, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var textField:UITextField! = nil @IBOutlet var matchTextField:UITextField! = nil var validationUnit:ValidationUnit! var validationManager:ValidationManager! override func viewDidLoad() { super.viewDidLoad() self.matchTextField.backgroundColor = UIColor.greenColor() let email_type:ValidatorEmailType = ValidatorEmailType() let unit_validator_types = [email_type] self.validationUnit = ValidationUnit(validatorTypes: unit_validator_types, identifier: "email") NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.validationUnitStatusChange(_:)), name: ValidationUnitUpdateNotification, object: self.validationUnit) self.validationUnit.validateText("you@somewhere") let length_type:ValidatorLengthType = ValidatorLengthType(minimumCharacters:3, maximumCharacters:20) let compare_type:ValidatorUITextCompareType = ValidatorUITextCompareType() compare_type.registerTextFieldToMatch(self.matchTextField) self.validationManager = ValidationManager() self.validationManager.registerTextField(self.textField, validationTypes: [length_type, compare_type], identifier: "textfield") NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.validationManagerStatusChange(_:)), name: ValidationStatusNotification, object: self.validationManager) } @objc func validationUnitStatusChange(notification:NSNotification) { let unit:ValidationUnit = notification.object as! ValidationUnit print("email validation: \(unit.identifier) is \(unit.valid) for \(unit.lastTextValue)") } @objc func validationManagerStatusChange(notification:NSNotification) { if let user_info = notification.userInfo { if let status_num:NSNumber = user_info["status"] as? NSNumber { let is_valid: Bool = status_num.boolValue ?? false print("manager is \(is_valid)") if (is_valid) { self.matchTextField.backgroundColor = UIColor.greenColor() } else { self.matchTextField.backgroundColor = UIColor.redColor() let all_errors:NSDictionary = user_info["errors"] as! NSDictionary let textfield:NSDictionary = all_errors["textfield"] as! NSDictionary let text_errors:NSDictionary = textfield["errors"] as! NSDictionary print("textfield errors: \(text_errors)") } } } } }
mit
9b672836311425d54e47ef8fc8d8574a
38.87013
201
0.633876
5.320624
false
false
false
false
mownier/photostream
Photostream/Modules/Comment Writer/Interactor/CommentWriterInteractor.swift
1
2306
// // CommentWriterInteractor.swift // Photostream // // Created by Mounir Ybanez on 30/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // protocol CommentWriterInteractorInput: BaseModuleInteractorInput { func write(with postId: String, and content: String) } protocol CommentWriterInteractorOutput: BaseModuleInteractorOutput { func interactorDidFinish(with comment: CommentWriterData) func interactorDidFinish(with error: CommentServiceError) } protocol CommentWriterInteractorInterface: BaseModuleInteractor { var service: CommentService! { set get } init(service: CommentService) } class CommentWriterInteractor: CommentWriterInteractorInterface { typealias Output = CommentWriterInteractorOutput weak var output: Output? var service: CommentService! required init(service: CommentService) { self.service = service } } extension CommentWriterInteractor: CommentWriterInteractorInput { func write(with postId: String, and content: String) { service.writeComment(postId: postId, message: content) { (result) in guard result.error == nil else { self.output?.interactorDidFinish(with: result.error!) return } guard let list = result.comments, list.comments.count > 0 else { let error: CommentServiceError = .failedToWrite(message: "New comment not found") self.output?.interactorDidFinish(with: error) return } let comment = list.comments[0] guard let user = list.users[comment.userId] else { let error: CommentServiceError = .failedToWrite(message: "Author not found") self.output?.interactorDidFinish(with: error) return } var data = CommentWriterDataItem() data.id = comment.id data.content = comment.message data.timestamp = comment.timestamp data.authorName = user.displayName data.authorAvatar = user.avatarUrl data.authorId = user.id self.output?.interactorDidFinish(with: data) } } }
mit
ac3f0cab412bdec0c247958829685827
30.148649
97
0.629935
5.323326
false
false
false
false
khillman84/music-social
music-social/music-social/PostCell.swift
1
2908
// // PostCell.swift // music-social // // Created by Kyle Hillman on 4/23/17. // Copyright © 2017 Kyle Hillman. All rights reserved. // import UIKit import Firebase class PostCell: UITableViewCell { @IBOutlet weak var caption: UITextView! @IBOutlet weak var postImg: UIImageView! @IBOutlet weak var likesLabel: UILabel! @IBOutlet weak var profileImg: CircleView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var likeImg: UIImageView! var post : Post! var likesRef : FIRDatabaseReference! override func awakeFromNib() { super.awakeFromNib() let tap = UITapGestureRecognizer(target: self, action: #selector(likeTapped)) tap.numberOfTapsRequired = 1 likeImg.addGestureRecognizer(tap) likeImg.isUserInteractionEnabled = true } func configureCell(post: Post, img: UIImage? = nil) { self.post = post likesRef = DataService.dataService.ref_user_current.child("likes").child(post.postKey) self.caption.text = post.caption self.likesLabel.text = "\(post.likes)" // self.date.text = "\(post.date)" // Check if image is stored, download it if not if img != nil { self.postImg.image = img } else { let ref = FIRStorage.storage().reference(forURL: post.imageUrl) ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, error) in if error != nil { print ("Unable to download image from Firebase storage") } else { print ("Image downloaded from Firebase storage") if let imgData = data { if let img = UIImage(data: imgData) { self.postImg.image = img FeedViewController.imageCache.setObject(img, forKey: post.imageUrl as NSString) } } } }) } likesRef.observeSingleEvent(of: .value, with: { (snapshot) in if let _ = snapshot.value as? NSNull { self.likeImg.image = UIImage(named: "empty-heart") } else { self.likeImg.image = UIImage(named: "filled-heart") } }) } func likeTapped(sender: UITapGestureRecognizer) { likesRef.observeSingleEvent(of: .value, with: { (snapshot) in if let _ = snapshot.value as? NSNull { self.likeImg.image = UIImage(named: "filled-heart") self.post.adjustLikes(addLike: true) self.likesRef.setValue(true) } else { self.likeImg.image = UIImage(named: "empty-heart") self.post.adjustLikes(addLike: false) self.likesRef.removeValue() } }) } }
mit
7111ccbdb235e9a893a7e6bc6dafcfe9
29.6
107
0.55762
4.6512
false
false
false
false
jasnig/ScrollPageView
ScrollViewController/ScrollPageView/ScrollPageView.swift
2
4651
// // ScrollPageView.swift // ScrollViewController // // Created by jasnig on 16/4/6. // Copyright © 2016年 ZeroJ. All rights reserved. // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles // // 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 ScrollPageView: UIView { static let cellId = "cellId" private var segmentStyle = SegmentStyle() /// 附加按钮点击响应 public var extraBtnOnClick: ((extraBtn: UIButton) -> Void)? { didSet { segView.extraBtnOnClick = extraBtnOnClick } } private(set) var segView: ScrollSegmentView! private(set) var contentView: ContentView! private var titlesArray: [String] = [] /// 所有的子控制器 private var childVcs: [UIViewController] = [] // 这里使用weak避免循环引用 private weak var parentViewController: UIViewController? public init(frame:CGRect, segmentStyle: SegmentStyle, titles: [String], childVcs:[UIViewController], parentViewController: UIViewController) { self.parentViewController = parentViewController self.childVcs = childVcs self.titlesArray = titles self.segmentStyle = segmentStyle assert(childVcs.count == titles.count, "标题的个数必须和子控制器的个数相同") super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { backgroundColor = UIColor.whiteColor() segView = ScrollSegmentView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44), segmentStyle: segmentStyle, titles: titlesArray) guard let parentVc = parentViewController else { return } contentView = ContentView(frame: CGRect(x: 0, y: CGRectGetMaxY(segView.frame), width: bounds.size.width, height: bounds.size.height - 44), childVcs: childVcs, parentViewController: parentVc) contentView.delegate = self addSubview(segView) addSubview(contentView) // 避免循环引用 segView.titleBtnOnClick = {[unowned self] (label: UILabel, index: Int) in // 切换内容显示(update content) self.contentView.setContentOffSet(CGPoint(x: self.contentView.bounds.size.width * CGFloat(index), y: 0), animated: self.segmentStyle.changeContentAnimated) } } deinit { parentViewController = nil print("\(self.debugDescription) --- 销毁") } } //MARK: - public helper extension ScrollPageView { /// 给外界设置选中的下标的方法(public method to set currentIndex) public func selectedIndex(selectedIndex: Int, animated: Bool) { // 移动滑块的位置 segView.selectedIndex(selectedIndex, animated: animated) } /// 给外界重新设置视图内容的标题的方法,添加新的childViewControllers /// (public method to reset childVcs) /// - parameter titles: newTitles /// - parameter newChildVcs: newChildVcs public func reloadChildVcsWithNewTitles(titles: [String], andNewChildVcs newChildVcs: [UIViewController]) { self.childVcs = newChildVcs self.titlesArray = titles segView.reloadTitlesWithNewTitles(titlesArray) contentView.reloadAllViewsWithNewChildVcs(childVcs) } } extension ScrollPageView: ContentViewDelegate { public var segmentView: ScrollSegmentView { return segView } }
mit
6f08ecc51008b18ebec783e7edf5a8be
35.483607
198
0.693708
4.476861
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSData.swift
1
36534
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif extension NSData { public struct ReadingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let dataReadingMappedIfSafe = ReadingOptions(rawValue: UInt(1 << 0)) public static let dataReadingUncached = ReadingOptions(rawValue: UInt(1 << 1)) public static let dataReadingMappedAlways = ReadingOptions(rawValue: UInt(1 << 2)) } public struct WritingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let dataWritingAtomic = WritingOptions(rawValue: UInt(1 << 0)) public static let dataWritingWithoutOverwriting = WritingOptions(rawValue: UInt(1 << 1)) } public struct SearchOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let backwards = SearchOptions(rawValue: UInt(1 << 0)) public static let anchored = SearchOptions(rawValue: UInt(1 << 1)) } public struct Base64EncodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let encoding64CharacterLineLength = Base64EncodingOptions(rawValue: UInt(1 << 0)) public static let encoding76CharacterLineLength = Base64EncodingOptions(rawValue: UInt(1 << 1)) public static let encodingEndLineWithCarriageReturn = Base64EncodingOptions(rawValue: UInt(1 << 4)) public static let encodingEndLineWithLineFeed = Base64EncodingOptions(rawValue: UInt(1 << 5)) } public struct Base64DecodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ignoreUnknownCharacters = Base64DecodingOptions(rawValue: UInt(1 << 0)) } } private final class _NSDataDeallocator { var handler: (UnsafeMutablePointer<Void>, Int) -> Void = {_,_ in } } private let __kCFMutable: CFOptionFlags = 0x01 private let __kCFGrowable: CFOptionFlags = 0x02 private let __kCFMutableVarietyMask: CFOptionFlags = 0x03 private let __kCFBytesInline: CFOptionFlags = 0x04 private let __kCFUseAllocator: CFOptionFlags = 0x08 private let __kCFDontDeallocate: CFOptionFlags = 0x10 private let __kCFAllocatesCollectable: CFOptionFlags = 0x20 public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { typealias CFType = CFData private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 private var _deallocator: UnsafeMutablePointer<Void>? = nil // for CF only private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift private var _bytes: UnsafeMutablePointer<UInt8>? = nil internal var _cfObject: CFType { if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { return unsafeBitCast(self, to: CFType.self) } else { return CFDataCreate(kCFAllocatorSystemDefault, UnsafePointer<UInt8>(self.bytes), self.length) } } public override required convenience init() { let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer<Void>.self) self.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } public override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } public override func isEqual(_ object: AnyObject?) -> Bool { if let data = object as? NSData { return self.isEqual(to: data._swiftObject) } else { return false } } deinit { if let allocatedBytes = _bytes { _deallocHandler?.handler(allocatedBytes, _length) } if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { _CFDeinit(self._cfObject) } } internal init(bytes: UnsafeMutablePointer<Void>?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init() let options : CFOptionFlags = (self.dynamicType == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0 if copy { _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, UnsafeMutablePointer<UInt8>(bytes), length, false) if let handler = deallocator { handler(bytes!, length) } } else { if let handler = deallocator { _deallocHandler!.handler = handler } // The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, UnsafeMutablePointer<UInt8>(bytes), length, true) } } public var length: Int { return CFDataGetLength(_cfObject) } public var bytes: UnsafePointer<Void> { return UnsafePointer<Void>(CFDataGetBytePtr(_cfObject)) } public override func copy() -> AnyObject { return copy(with: nil) } public func copy(with zone: NSZone? = nil) -> AnyObject { return self } public override func mutableCopy() -> AnyObject { return mutableCopy(with: nil) } public func mutableCopy(with zone: NSZone? = nil) -> AnyObject { return NSMutableData(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.data") } else { aCoder.encodeBytes(UnsafePointer<UInt8>(self.bytes), length: self.length) } } public required convenience init?(coder aDecoder: NSCoder) { if !aDecoder.allowsKeyedCoding { if let data = aDecoder.decodeDataObject() { self.init(data: data) } else { return nil } } else if aDecoder.dynamicType == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.data") { guard let data = aDecoder._decodePropertyListForKey("NS.data") as? NSData else { return nil } self.init(data: data._swiftObject) } else { let result : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") { guard let buffer = $0 else { return nil } return Data(buffer: buffer) } guard let r = result else { return nil } self.init(data: r) } } public static func supportsSecureCoding() -> Bool { return true } private func byteDescription(limit: Int? = nil) -> String { var s = "" let buffer = UnsafePointer<UInt8>(bytes) var i = 0 while i < self.length { if i > 0 && i % 4 == 0 { // if there's a limit, and we're at the barrier where we'd add the ellipses, don't add a space. if let limit = limit where self.length > limit && i == self.length - (limit / 2) { /* do nothing */ } else { s += " " } } let byte = buffer[i] var byteStr = String(byte, radix: 16, uppercase: false) if byte <= 0xf { byteStr = "0\(byteStr)" } s += byteStr // if we've hit the midpoint of the limit, skip to the last (limit / 2) bytes. if let limit = limit where self.length > limit && i == (limit / 2) - 1 { s += " ... " i = self.length - (limit / 2) } else { i += 1 } } return s } override public var debugDescription: String { return "<\(byteDescription(limit: 1024))>" } override public var description: String { return "<\(byteDescription())>" } override public var _cfTypeID: CFTypeID { return CFDataGetTypeID() } } extension NSData { public convenience init(bytes: UnsafePointer<Void>?, length: Int) { self.init(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int) { self.init(bytes: bytes, length: length, copy: false, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, freeWhenDone b: Bool) { self.init(bytes: bytes, length: length, copy: false) { buffer, length in if b { free(buffer) } } } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { self.init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } internal struct NSDataReadResult { var bytes: UnsafeMutablePointer<Void> var length: Int var deallocator: ((buffer: UnsafeMutablePointer<Void>, length: Int) -> Void)? } internal static func readBytesFromFileWithExtendedAttributes(_ path: String, options: ReadingOptions) throws -> NSDataReadResult { let fd = _CFOpenFile(path, O_RDONLY) if fd < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } defer { close(fd) } var info = stat() let ret = withUnsafeMutablePointer(&info) { infoPointer -> Bool in if fstat(fd, infoPointer) < 0 { return false } return true } if !ret { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let length = Int(info.st_size) if options.contains(.dataReadingMappedAlways) { let data = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0) // Swift does not currently expose MAP_FAILURE if data != UnsafeMutablePointer<Void>(bitPattern: -1) { return NSDataReadResult(bytes: data!, length: length) { buffer, length in munmap(buffer, length) } } } let data = malloc(length)! var remaining = Int(info.st_size) var total = 0 while remaining > 0 { let amt = read(fd, data.advanced(by: total), remaining) if amt < 0 { break } remaining -= amt total += amt } if remaining != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } return NSDataReadResult(bytes: data, length: length) { buffer, length in free(buffer) } } public convenience init(contentsOfFile path: String, options readOptionsMask: ReadingOptions) throws { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } public convenience init?(contentsOfFile path: String) { do { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: []) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } catch { return nil } } public convenience init(data: Data) { self.init(bytes:data._nsObject.bytes, length: data.count) } public convenience init(contentsOf url: URL, options readOptionsMask: ReadingOptions) throws { if url.isFileURL { try self.init(contentsOfFile: url.path!, options: readOptionsMask) } else { let session = URLSession(configuration: URLSessionConfiguration.defaultSessionConfiguration()) let cond = Condition() var resError: NSError? var resData: Data? let task = session.dataTaskWithURL(url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in resData = data resError = error cond.broadcast() }) task.resume() cond.wait() if resData == nil { throw resError! } self.init(data: resData!) } } public convenience init?(contentsOfURL url: URL) { do { try self.init(contentsOf: url, options: []) } catch { return nil } } } extension NSData { public func getBytes(_ buffer: UnsafeMutablePointer<Void>, length: Int) { CFDataGetBytes(_cfObject, CFRangeMake(0, length), UnsafeMutablePointer<UInt8>(buffer)) } public func getBytes(_ buffer: UnsafeMutablePointer<Void>, range: NSRange) { CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), UnsafeMutablePointer<UInt8>(buffer)) } public func isEqual(to other: Data) -> Bool { if length != other.count { return false } return other.withUnsafeBytes { (bytes2: UnsafePointer<Void>) -> Bool in let bytes1 = bytes return memcmp(bytes1, bytes2, length) == 0 } } public func subdata(with range: NSRange) -> Data { if range.length == 0 { return Data() } if range.location == 0 && range.length == self.length { return Data(_bridged: self) } return Data(bytes: bytes.advanced(by: range.location), count: range.length) } internal func makeTemporaryFileInDirectory(_ dirPath: String) throws -> (Int32, String) { let template = dirPath._nsObject.stringByAppendingPathComponent("tmp.XXXXXX") let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: maxLength) let _ = template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dirPath) } let pathResult = FileManager.default().string(withFileSystemRepresentation:buf, length: Int(strlen(buf))) return (fd, pathResult) } internal class func writeToFileDescriptor(_ fd: Int32, path: String? = nil, buf: UnsafePointer<Void>, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int repeat { #if os(OSX) || os(iOS) bytesWritten = Darwin.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #elseif os(Linux) bytesWritten = Glibc.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #endif } while (bytesWritten < 0 && errno == EINTR) if bytesWritten <= 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else { bytesRemaining -= bytesWritten } } } public func write(toFile path: String, options writeOptionsMask: WritingOptions = []) throws { var fd : Int32 var mode : mode_t? = nil let useAuxiliaryFile = writeOptionsMask.contains(.dataWritingAtomic) var auxFilePath : String? = nil if useAuxiliaryFile { // Preserve permissions. var info = stat() if lstat(path, &info) == 0 { mode = info.st_mode } else if errno != ENOENT && errno != ENAMETOOLONG { throw _NSErrorWithErrno(errno, reading: false, path: path) } let (newFD, path) = try self.makeTemporaryFileInDirectory(path._nsObject.stringByDeletingLastPathComponent) fd = newFD auxFilePath = path fchmod(fd, 0o666) } else { var flags = O_WRONLY | O_CREAT | O_TRUNC if writeOptionsMask.contains(.dataWritingWithoutOverwriting) { flags |= O_EXCL } fd = _CFOpenFileWithMode(path, flags, 0o666) } if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } defer { close(fd) } try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in if range.length > 0 { do { try NSData.writeToFileDescriptor(fd, path: path, buf: buf, length: range.length) if fsync(fd) < 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } catch let err { if let auxFilePath = auxFilePath { do { try FileManager.default().removeItem(atPath: auxFilePath) } catch _ {} } throw err } } } if let auxFilePath = auxFilePath { if rename(auxFilePath, path) != 0 { do { try FileManager.default().removeItem(atPath: auxFilePath) } catch _ {} throw _NSErrorWithErrno(errno, reading: false, path: path) } if let mode = mode { chmod(path, mode) } } } public func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { do { try write(toFile: path, options: useAuxiliaryFile ? .dataWritingAtomic : []) } catch { return false } return true } public func write(to url: URL, atomically: Bool) -> Bool { if url.isFileURL { if let path = url.path { return write(toFile: path, atomically: atomically) } } return false } /// Write the contents of the receiver to a location specified by the given file URL. /// /// - parameter url: The location to which the receiver’s contents will be written. /// - parameter writeOptionsMask: An option set specifying file writing options. /// /// - throws: This method returns Void and is marked with the `throws` keyword to indicate that it throws an error in the event of failure. /// /// This method is invoked in a `try` expression and the caller is responsible for handling any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42) in [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097) and [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) in [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216). public func write(to url: URL, options writeOptionsMask: WritingOptions = []) throws { guard let path = url.path where url.isFileURL == true else { let userInfo = [NSLocalizedDescriptionKey : "The folder at “\(url)” does not exist or is not a file URL.", // NSLocalizedString() not yet available NSURLErrorKey : url.absoluteString ?? ""] as Dictionary<String, Any> throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: userInfo) } try write(toFile: path, options: writeOptionsMask) } public func range(of searchData: Data, options mask: SearchOptions = [], in searchRange: NSRange) -> NSRange { let dataToFind = searchData._nsObject guard dataToFind.length > 0 else {return NSRange(location: NSNotFound, length: 0)} guard let searchRange = searchRange.toRange() else {fatalError("invalid range")} precondition(searchRange.endIndex <= self.length, "range outside the bounds of data") let baseData = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(self.bytes), count: self.length)[searchRange] let search = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(dataToFind.bytes), count: dataToFind.length) let location : Int? let anchored = mask.contains(.anchored) if mask.contains(.backwards) { location = NSData.searchSubSequence(search.reversed(), inSequence: baseData.reversed(),anchored : anchored).map {$0.base-search.count} } else { location = NSData.searchSubSequence(search, inSequence: baseData,anchored : anchored) } return location.map {NSRange(location: $0, length: search.count)} ?? NSRange(location: NSNotFound, length: 0) } private static func searchSubSequence<T : Collection, T2 : Sequence where T.Iterator.Element : Equatable, T.Iterator.Element == T2.Iterator.Element, T.SubSequence.Iterator.Element == T.Iterator.Element, T.Indices.Iterator.Element == T.Index>(_ subSequence : T2, inSequence seq: T,anchored : Bool) -> T.Index? { for index in seq.indices { if seq.suffix(from: index).starts(with: subSequence) { return index } if anchored {return nil} } return nil } internal func enumerateByteRangesUsingBlockRethrows(_ block: @noescape (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws { var err : Swift.Error? = nil self.enumerateBytes() { (buf, range, stop) -> Void in do { try block(buf, range, stop) } catch let e { err = e } } if let err = err { throw err } } public func enumerateBytes(_ block: @noescape (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) -> Void) { var stop = false withUnsafeMutablePointer(&stop) { stopPointer in block(bytes, NSMakeRange(0, length), stopPointer) } } } extension NSData : _CFBridgable, _SwiftBridgable { typealias SwiftType = Data internal var _swiftObject: SwiftType { return Data(_bridged: self) } public func bridge() -> Data { return _swiftObject } } extension Data : _NSBridgable, _CFBridgable { typealias CFType = CFData typealias NSType = NSData internal var _cfObject: CFType { return _nsObject._cfObject } internal var _nsObject: NSType { return _bridgeToObjectiveC() } public func bridge() -> NSData { return _nsObject } } extension CFData : _NSBridgable, _SwiftBridgable { typealias NSType = NSData typealias SwiftType = Data internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: SwiftType { return Data(_bridged: self._nsObject) } } extension NSMutableData { internal var _cfMutableObject: CFMutableData { return unsafeBitCast(self, to: CFMutableData.self) } } public class NSMutableData : NSData { public required convenience init() { self.init(bytes: nil, length: 0) } internal override init(bytes: UnsafeMutablePointer<Void>?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } public var mutableBytes: UnsafeMutablePointer<Void> { return UnsafeMutablePointer(CFDataGetMutableBytePtr(_cfMutableObject)) } public override var length: Int { get { return CFDataGetLength(_cfObject) } set { CFDataSetLength(_cfMutableObject, newValue) } } public override func copy(with zone: NSZone? = nil) -> AnyObject { return NSData(bytes: bytes, length: length) } } extension NSData { /* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64Encoded base64String: String, options: Base64DecodingOptions) { let encodedBytes = Array(base64String.utf8) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ public func base64EncodedString(_ options: Base64EncodingOptions = []) -> String { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) let characters = encodedBytes.map { Character(UnicodeScalar($0)) } return String(characters) } /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64Encoded base64Data: Data, options: Base64DecodingOptions) { var encodedBytes = [UInt8](repeating: 0, count: base64Data.count) base64Data._nsObject.getBytes(&encodedBytes, length: encodedBytes.count) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ public func base64EncodedData(_ options: Base64EncodingOptions = []) -> Data { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) return Data(bytes: encodedBytes, count: encodedBytes.count) } /** The ranges of ASCII characters that are used to encode data in Base64. */ private static let base64ByteMappings: [Range<UInt8>] = [ 65 ..< 91, // A-Z 97 ..< 123, // a-z 48 ..< 58, // 0-9 43 ..< 44, // + 47 ..< 48, // / ] /** Padding character used when the number of bytes to encode is not divisible by 3 */ private static let base64Padding : UInt8 = 61 // = /** This method takes a byte with a character from Base64-encoded string and gets the binary value that the character corresponds to. - parameter byte: The byte with the Base64 character. - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) */ private enum Base64DecodedByte { case valid(UInt8) case invalid case padding } private static func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { guard byte != base64Padding else {return .padding} var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { let result = decodedStart + (byte - range.lowerBound) return .valid(result) } decodedStart += range.upperBound - range.lowerBound } return .invalid } /** This method takes six bits of binary data and encodes it as a character in Base64. The value in the byte must be less than 64, because a Base64 character can only represent 6 bits. - parameter byte: The byte to encode - returns: The ASCII value for the encoded character. */ private static func base64EncodeByte(_ byte: UInt8) -> UInt8 { assert(byte < 64) var decodedStart: UInt8 = 0 for range in base64ByteMappings { let decodedRange = decodedStart ..< decodedStart + (range.upperBound - range.lowerBound) if decodedRange.contains(byte) { return range.lowerBound + (byte - decodedStart) } decodedStart += range.upperBound - range.lowerBound } return 0 } /** This method decodes Base64-encoded data. If the input contains any bytes that are not valid Base64 characters, this will return nil. - parameter bytes: The Base64 bytes - parameter options: Options for handling invalid input - returns: The decoded bytes. */ private static func base64DecodeBytes(_ bytes: [UInt8], options: Base64DecodingOptions = []) -> [UInt8]? { var decodedBytes = [UInt8]() decodedBytes.reserveCapacity((bytes.count/3)*2) var currentByte : UInt8 = 0 var validCharacterCount = 0 var paddingCount = 0 var index = 0 for base64Char in bytes { let value : UInt8 switch base64DecodeByte(base64Char) { case .valid(let v): value = v validCharacterCount += 1 case .invalid: if options.contains(.ignoreUnknownCharacters) { continue } else { return nil } case .padding: paddingCount += 1 continue } //padding found in the middle of the sequence is invalid if paddingCount > 0 { return nil } switch index%4 { case 0: currentByte = (value << 2) case 1: currentByte |= (value >> 4) decodedBytes.append(currentByte) currentByte = (value << 4) case 2: currentByte |= (value >> 2) decodedBytes.append(currentByte) currentByte = (value << 6) case 3: currentByte |= value decodedBytes.append(currentByte) default: fatalError() } index += 1 } guard (validCharacterCount + paddingCount)%4 == 0 else { //invalid character count return nil } return decodedBytes } /** This method encodes data in Base64. - parameter bytes: The bytes you want to encode - parameter options: Options for formatting the result - returns: The Base64-encoding for those bytes. */ private static func base64EncodeBytes(_ bytes: [UInt8], options: Base64EncodingOptions = []) -> [UInt8] { var result = [UInt8]() result.reserveCapacity((bytes.count/3)*4) let lineOptions : (lineLength : Int, separator : [UInt8])? = { let lineLength: Int if options.contains(.encoding64CharacterLineLength) { lineLength = 64 } else if options.contains(.encoding76CharacterLineLength) { lineLength = 76 } else { return nil } var separator = [UInt8]() if options.contains(.encodingEndLineWithCarriageReturn) { separator.append(13) } if options.contains(.encodingEndLineWithLineFeed) { separator.append(10) } //if the kind of line ending to insert is not specified, the default line ending is Carriage Return + Line Feed. if separator.count == 0 {separator = [13,10]} return (lineLength,separator) }() var currentLineCount = 0 let appendByteToResult : (UInt8) -> () = { result.append($0) currentLineCount += 1 if let options = lineOptions where currentLineCount == options.lineLength { result.append(contentsOf: options.separator) currentLineCount = 0 } } var currentByte : UInt8 = 0 for (index,value) in bytes.enumerated() { switch index%3 { case 0: currentByte = (value >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 6) >> 2) case 1: currentByte |= (value >> 4) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 4) >> 2) case 2: currentByte |= (value >> 6) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 2) >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) default: fatalError() } } //add padding switch bytes.count%3 { case 0: break //no padding needed case 1: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) appendByteToResult(self.base64Padding) case 2: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) default: fatalError() } return result } } extension NSMutableData { public func append(_ bytes: UnsafePointer<Void>, length: Int) { CFDataAppendBytes(_cfMutableObject, UnsafePointer<UInt8>(bytes), length) } public func append(_ other: Data) { let otherLength = other.count other.withUnsafeBytes { append($0, length: otherLength) } } public func increaseLength(by extraLength: Int) { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } public func replaceBytes(in range: NSRange, withBytes bytes: UnsafePointer<Void>) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), length) } public func resetBytes(in range: NSRange) { bzero(mutableBytes.advanced(by: range.location), range.length) } public func setData(_ data: Data) { length = data.count data.withUnsafeBytes { replaceBytes(in: NSMakeRange(0, length), withBytes: $0) } } public func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafePointer<Void>, length replacementLength: Int) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), replacementLength) } } extension NSMutableData { public convenience init?(capacity: Int) { self.init(bytes: nil, length: 0) } public convenience init?(length: Int) { self.init(bytes: nil, length: 0) self.length = length } }
apache-2.0
894338d7d3e37d40f9cdcb4b60ecf0e2
37.77707
924
0.596857
4.831107
false
false
false
false
bitjammer/swift
test/decl/func/constructor.swift
39
2283
// RUN: %target-typecheck-verify-swift // User-written default constructor struct X { init() {} } X() // expected-warning{{unused}} // User-written memberwise constructor struct Y { var i : Int, f : Float init(i : Int, f : Float) {} } Y(i: 1, f: 1.5) // expected-warning{{unused}} // User-written memberwise constructor with default struct Z { var a : Int var b : Int init(a : Int, b : Int = 5) { self.a = a self.b = b } } Z(a: 1, b: 2) // expected-warning{{unused}} // User-written init suppresses implicit constructors. struct A { var i, j : Int init(x : Int) { // expected-note {{'init(x:)' declared here}} i = x j = x } } A() // expected-error{{missing argument for parameter 'x'}} A(x: 1) // expected-warning{{unused}} A(1, 1) // expected-error{{extra argument in call}} // No user-written constructors; implicit constructors are available. struct B { var i : Int = 0, j : Float = 0.0 } extension B { init(x : Int) { self.i = x self.j = 1.5 } } B() // expected-warning{{unused}} B(x: 1) // expected-warning{{unused}} B(i: 1, j: 2.5) // expected-warning{{unused}} struct F { // expected-note {{'init(d:b:c:)' declared here}} var d : D var b : B var c : C } struct C { var d : D // suppress implicit initializers init(d : D) { } // expected-note {{'init(d:)' declared here}} } struct D { var i : Int init(i : Int) { } } extension D { init() { i = 17 } } F() // expected-error{{missing argument for parameter 'd'}} D() // okay // expected-warning{{unused}} B() // okay // expected-warning{{unused}} C() // expected-error{{missing argument for parameter 'd'}} struct E { init(x : Wonka) { } // expected-error{{use of undeclared type 'Wonka'}} } var e : E //---------------------------------------------------------------------------- // Argument/parameter name separation //---------------------------------------------------------------------------- class ArgParamSep { init(_ b: Int, _: Int, forInt int: Int, c _: Int, d: Int) { } } // Tests for crashes. // rdar://14082378 struct NoCrash1a { init(_: NoCrash1b) {} // expected-error {{use of undeclared type 'NoCrash1b'}} } var noCrash1c : NoCrash1a class MissingDef { init() // expected-error{{initializer requires a body}} }
apache-2.0
71503baf32efa6a9856de623e7cfbb68
19.754545
80
0.56855
3.201964
false
false
false
false