repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hejunbinlan/MonkeyKing
refs/heads/master
China/ViewController.swift
mit
1
// // ViewController.swift // China // // Created by NIX on 15/9/11. // Copyright © 2015年 nixWork. All rights reserved. // import UIKit import MonkeyKing let weChatAppID = "wxd930ea5d5a258f4f" let qqAppID = "1103194207" class ViewController: UIViewController { @IBAction func shareURLToWeChatSession(sender: UIButton) { MonkeyKing.registerAccount(.WeChat(appID: weChatAppID)) let message = MonkeyKing.Message.WeChat(.Session(info: ( title: "Session", description: "Hello Session", thumbnail: UIImage(named: "rabbit"), media: .URL(NSURL(string: "http://www.apple.com/cn")!) ))) MonkeyKing.shareMessage(message) { success in print("shareURLToWeChatSession success: \(success)") } } @IBAction func shareImageToWeChatTimeline(sender: UIButton) { MonkeyKing.registerAccount(.WeChat(appID: weChatAppID)) let message = MonkeyKing.Message.WeChat(.Timeline(info: ( title: "Timeline", description: "Hello Timeline", thumbnail: nil, media: .Image(UIImage(named: "rabbit")!) ))) MonkeyKing.shareMessage(message) { success in print("shareImageToWeChatTimeline success: \(success)") } } @IBAction func shareURLToQQFriends(sender: UIButton) { MonkeyKing.registerAccount(.QQ(appID: qqAppID)) let message = MonkeyKing.Message.QQ(.Friends(info: ( title: "Friends", description: "helloworld", thumbnail: UIImage(named: "rabbit")!, media: .URL(NSURL(string: "http://www.apple.com/cn")!) ))) MonkeyKing.shareMessage(message) { success in print("shareURLToQQFriends success: \(success)") } } @IBAction func shareImageToQQZone(sender: UIButton) { MonkeyKing.registerAccount(.QQ(appID: qqAppID)) let message = MonkeyKing.Message.QQ(.Zone(info: ( title: "Zone", description: "helloworld", thumbnail: UIImage(named: "rabbit")!, media: .Image(UIImage(named: "rabbit")!) ))) MonkeyKing.shareMessage(message) { success in print("shareImageToQQZone success: \(success)") } } @IBAction func systemShare(sender: UIButton) { let shareURL = NSURL(string: "http://www.apple.com/cn/iphone/compare/")! let info = MonkeyKing.Info( title: "iPhone Compare", description: "iPhone 机型比较", thumbnail: UIImage(named: "rabbit"), media: .URL(shareURL) ) // WeChat Session let weChatSessionMessage = MonkeyKing.Message.WeChat(.Session(info: info)) let weChatSessionActivity = WeChatActivity(type: .Session, message: weChatSessionMessage, finish: { success in print("systemShare WeChat Session success: \(success)") }) // WeChat Timeline let weChatTimelineMessage = MonkeyKing.Message.WeChat(.Timeline(info: info)) let weChatTimelineActivity = WeChatActivity(type: .Timeline, message: weChatTimelineMessage, finish: { success in print("systemShare WeChat Timeline success: \(success)") }) // QQ Friends let qqFriendsMessage = MonkeyKing.Message.QQ(.Friends(info: info)) let qqFriendsActivity = QQActivity(type: .Friends, message: qqFriendsMessage, finish: { success in print("systemShare QQ Friends success: \(success)") }) // QQ Zone let qqZoneMessage = MonkeyKing.Message.QQ(.Zone(info: info)) let qqZoneActivity = QQActivity(type: .Zone, message: qqZoneMessage, finish: { success in print("systemShare QQ Zone success: \(success)") }) let activityViewController = UIActivityViewController(activityItems: [shareURL], applicationActivities: [weChatSessionActivity, weChatTimelineActivity, qqFriendsActivity, qqZoneActivity]) presentViewController(activityViewController, animated: true, completion: nil) } }
f3cfac5a015362c9751d3966bc955d60
30.821705
195
0.628502
false
false
false
false
masters3d/xswift
refs/heads/master
exercises/tournament/Sources/TournamentExample.swift
mit
1
import Foundation private extension String { func trimWhiteSpace() -> String { let removeSpaces = trimCharacters(" ", sourceText: self) if removeSpaces.hasSuffix("\n") { return String(removeSpaces.characters.dropLast()) } return removeSpaces } func trimCharacters(_ charToTrim: Character, sourceText: String) -> String { var editCharacterView = sourceText.characters var editString = String(editCharacterView) let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } return editString } } struct Tournament { enum Outcome { case loss case draw case win case err } struct TeamResult { var losses: Int = 0 var draws: Int = 0 var wins: Int = 0 var played: Int { return losses + draws + wins } var score: Int { return wins * 3 + draws } mutating func addOutcome( _ outcome: Outcome ) { switch outcome { case .loss : losses += 1 case .draw : draws += 1 case .win : wins += 1 default : print("Error addOutcome") } } } private var teams = [String: TeamResult]() private mutating func addResult(_ team1: String, team2: String, outcome: Outcome) { // Invert outcome for the second team. let outcome2: Outcome = (outcome == Outcome.win) ? Outcome.loss : (outcome == Outcome.loss) ? Outcome.win : Outcome.draw addTeamOutcome(team1, outcome) addTeamOutcome(team2, outcome2) } private var teamResult = TeamResult() private mutating func addTeamOutcome(_ team: String, _ outcome: Outcome) { if teams[team] != nil { teamResult = teams[team]! teamResult.addOutcome(outcome) teams[team] = teamResult } else { teamResult = TeamResult() teamResult.addOutcome(outcome) teams[team] = teamResult } } private mutating func writeResults() -> String { // swiftlint:disable:next function_parameter_count func formarter (_ team: String, mp: String, w: String, d: String, l: String, p: String) -> String { func wsChars(_ text: String, spacing: Int = 31) -> String { return repeatElement( " ", count: abs(spacing - Array(text.characters).count)).joined(separator: "") } func spacing(_ text: String, columnWith: Int = 4) -> String { let textCount = Array(text.characters).count let space = Int(round(Double(textCount) / Double(columnWith))) return wsChars(text, spacing: columnWith - space - textCount) + text + wsChars(text, spacing: space ) } let text = "\(team)" + wsChars(team) + "|" + spacing(mp) + "|" + spacing(w) + "|" + spacing(d) + "|" + spacing(l) + "|" + spacing(p) return text.trimWhiteSpace() + "\n" } var textOutput: String = "" let header = formarter("Team", mp: "MP", w: "W", d: "D", l: "L", p: "P") textOutput += header func sortKeysByValue() -> [String] { var sortByValue = [(team : String, score: Int, mp: Int)]() for each in Array(teams.keys) { let tempVal = teams[each]! sortByValue.append((each, tempVal.score, tempVal.played)) } sortByValue.sort { $0.score == $1.score ? $0.mp > $1.mp : $0.score > $1.score } var sortedKeys = [String]() for each in sortByValue { sortedKeys.append(each.0) } return sortedKeys } for team in sortKeysByValue() { let result = teams[team]! let mp = result.played let w = result.wins let d = result.draws let l = result.losses let p = result.score let line = formarter( team, mp: "\(mp)", w: "\(w)", d: "\(d)", l: "\(l)", p: "\(p)" ) textOutput += line } return textOutput.trimWhiteSpace() } func tally(_ inStream: String) -> String { // Create New Tournament var tournament = Tournament() var outcome: Outcome = Outcome.err // alternative to .componentsSeparatedByString let textArrayLines = inStream.characters.split { $0 == "\n" }.map { String($0) } for line in textArrayLines { let parts = line.trimWhiteSpace().components(separatedBy: ";") if parts.count == 3 { switch parts[2].lowercased() { case "loss": outcome = Outcome.loss case "draw": outcome = Outcome.draw case "win": outcome = Outcome.win default: outcome = Outcome.err } if outcome != Outcome.err { tournament.addResult(parts[0], team2: parts[1], outcome: outcome) } } } return tournament.writeResults() } }
b7e3fe4d52eaa5f8100e2a37cde10aa9
29.670213
144
0.51717
false
false
false
false
Szaq/swift-cl
refs/heads/master
SwiftCL/Buffer.swift
mit
1
// // Buffer.swift // ReceiptRecognizer // // Created by Lukasz Kwoska on 04/12/14. // Copyright (c) 2014 Spinal Development. All rights reserved. // import Foundation import OpenCL public class Buffer<T : IntegerLiteralConvertible>: Memory { public private(set) var objects: [T] public init(context:Context, count:Int, readOnly: Bool = false) throws { let flags = readOnly ? CL_MEM_READ_ONLY : CL_MEM_READ_WRITE objects = [T](count:count, repeatedValue:0) try super.init(context: context, flags: flags, size: UInt(sizeof(T) * count), hostPtr: &objects) } public init(context:Context, copyFrom:[T], readOnly: Bool = false) throws { let flags = CL_MEM_USE_HOST_PTR | (readOnly ? CL_MEM_READ_ONLY : CL_MEM_READ_WRITE) objects = copyFrom try super.init(context: context, flags: flags, size: UInt(sizeof(T) * objects.count), hostPtr: &objects) } }
23a2f04b2089bd188e9c8195135796c0
29.233333
108
0.678808
false
false
false
false
naokits/bluemix-swift-demo-ios
refs/heads/master
Bluemix/bluemix-mobile-app-demo/client/Pods/BMSSecurity/Source/mca/internal/Utils.swift
mit
2
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import Foundation import BMSCore extension Dictionary where Key : Any { subscript(caseInsensitive key : Key) -> Value? { get { if let stringKey = key as? String { let searchKeyLowerCase = stringKey.lowercaseString for currentKey in self.keys { if let stringCurrentKey = currentKey as? String { let currentKeyLowerCase = stringCurrentKey.lowercaseString if currentKeyLowerCase == searchKeyLowerCase { return self[currentKey] } } } } return nil } } } public class Utils { internal static func concatenateUrls(rootUrl:String, path:String) -> String { guard !rootUrl.isEmpty else { return path } var retUrl = rootUrl if !retUrl.hasSuffix("/") { retUrl += "/" } if path.hasPrefix("/") { retUrl += path.substringWithRange(Range<String.Index>(start: path.startIndex.advancedBy(1), end: path.endIndex)) } else { retUrl += path } return retUrl } internal static func getParameterValueFromQuery(query:String?, paramName:String, caseSensitive:Bool) -> String? { guard let myQuery = query else { return nil } let paramaters = myQuery.componentsSeparatedByString("&") for val in paramaters { let pairs = val.componentsSeparatedByString("=") if (pairs.endIndex != 2) { continue } if(caseSensitive) { if let normal = pairs[0].stringByRemovingPercentEncoding where normal == paramName { return pairs[1].stringByRemovingPercentEncoding } } else { if let normal = pairs[0].stringByRemovingPercentEncoding?.lowercaseString where normal == paramName.lowercaseString { return pairs[1].stringByRemovingPercentEncoding } } } return nil } internal static func JSONStringify(value: AnyObject, prettyPrinted:Bool = false) throws -> String{ let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0) if NSJSONSerialization.isValidJSONObject(value) { do{ let data = try NSJSONSerialization.dataWithJSONObject(value, options: options) guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String else { throw JsonUtilsErrors.JsonIsMalformed } return string } catch { throw JsonUtilsErrors.JsonIsMalformed } } return "" } public static func parseJsonStringtoDictionary(jsonString:String) throws ->[String:AnyObject] { do { guard let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding), responseJson = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] else { throw JsonUtilsErrors.JsonIsMalformed } return responseJson as [String:AnyObject] } } internal static func extractSecureJson(response: Response?) throws -> [String:AnyObject?] { guard let responseText:String = response?.responseText where (responseText.hasPrefix(BMSSecurityConstants.SECURE_PATTERN_START) && responseText.hasSuffix(BMSSecurityConstants.SECURE_PATTERN_END)) else { throw JsonUtilsErrors.CouldNotExtractJsonFromResponse } let jsonString : String = responseText.substringWithRange(Range<String.Index>(start: responseText.startIndex.advancedBy(BMSSecurityConstants.SECURE_PATTERN_START.characters.count), end: responseText.endIndex.advancedBy(-BMSSecurityConstants.SECURE_PATTERN_END.characters.count))) do { let responseJson = try parseJsonStringtoDictionary(jsonString) return responseJson } } //Return the App Name and Version internal static func getApplicationDetails() -> (name:String, version:String) { var version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String var name = NSBundle(forClass:object_getClass(self)).bundleIdentifier if name == nil { AuthorizationProcessManager.logger.error("Could not retrieve application name. Application name is set to nil") name = "nil" } if version == nil { AuthorizationProcessManager.logger.error("Could not retrieve application version. Application version is set to nil") version = "nil" } return (name!, version!) } internal static func getDeviceDictionary() -> [String : AnyObject] { let deviceIdentity = MCADeviceIdentity() let appIdentity = MCAAppIdentity() var device = [String : AnyObject]() device[BMSSecurityConstants.JSON_DEVICE_ID_KEY] = deviceIdentity.id device[BMSSecurityConstants.JSON_MODEL_KEY] = deviceIdentity.model device[BMSSecurityConstants.JSON_OS_KEY] = deviceIdentity.OS device[BMSSecurityConstants.JSON_APPLICATION_ID_KEY] = appIdentity.id device[BMSSecurityConstants.JSON_APPLICATION_VERSION_KEY] = appIdentity.version device[BMSSecurityConstants.JSON_ENVIRONMENT_KEY] = BMSSecurityConstants.JSON_IOS_ENVIRONMENT_VALUE return device } /** Decode base64 code - parameter strBase64: strBase64 the String to decode - returns: return decoded String */ internal static func decodeBase64WithString(strBase64:String) -> NSData? { guard let objPointerHelper = strBase64.cStringUsingEncoding(NSASCIIStringEncoding), objPointer = String(UTF8String: objPointerHelper) else { return nil } let intLengthFixed:Int = (objPointer.characters.count) var result:[Int8] = [Int8](count: intLengthFixed, repeatedValue : 1) var i:Int=0, j:Int=0, k:Int var count = 0 var intLengthMutated:Int = (objPointer.characters.count) var current:Character for current = objPointer[objPointer.startIndex.advancedBy(count++)] ; current != "\0" && intLengthMutated-- > 0 ; current = objPointer[objPointer.startIndex.advancedBy(count++)] { if current == "=" { if count < intLengthFixed && objPointer[objPointer.startIndex.advancedBy(count)] != "=" && i%4 == 1 { return nil } if count == intLengthFixed { break } continue } let stringCurrent = String(current) let singleValueArrayCurrent: [UInt8] = Array(stringCurrent.utf8) let intCurrent:Int = Int(singleValueArrayCurrent[0]) let int8Current = BMSSecurityConstants.base64DecodingTable[intCurrent] if int8Current == -1 { continue } else if int8Current == -2 { return nil } switch (i % 4) { case 0: result[j] = int8Current << 2 case 1: result[j++] |= int8Current >> 4 result[j] = (int8Current & 0x0f) << 4 case 2: result[j++] |= int8Current >> 2 result[j] = (int8Current & 0x03) << 6 case 3: result[j++] |= int8Current default: break } i++ if count == intLengthFixed { break } } // mop things up if we ended on a boundary k = j if (current == "=") { switch (i % 4) { case 1: // Invalid state return nil case 2: k++ result[k] = 0 case 3: result[k] = 0 default: break } } // Setup the return NSData return NSData(bytes: result, length: j) } internal static func base64StringFromData(data:NSData, length:Int, isSafeUrl:Bool) -> String { var ixtext:Int = 0 var ctremaining:Int var input:[Int] = [Int](count: 3, repeatedValue: 0) var output:[Int] = [Int](count: 4, repeatedValue: 0) var i:Int, charsonline:Int = 0, ctcopy:Int guard data.length >= 1 else { return "" } var result:String = "" let count = data.length / sizeof(Int8) var raw = [Int8](count: count, repeatedValue: 0) data.getBytes(&raw, length:count * sizeof(Int8)) while (true) { ctremaining = data.length - ixtext if ctremaining <= 0 { break } for i = 0; i < 3; i++ { let ix:Int = ixtext + i if ix < data.length { input[i] = Int(raw[ix]) } else { input[i] = 0 } } output[0] = (input[0] & 0xFC) >> 2 output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4) output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6) output[3] = input[2] & 0x3F ctcopy = 4 switch (ctremaining) { case 1: ctcopy = 2 case 2: ctcopy = 3 default: break } for i = 0; i < ctcopy; i++ { let toAppend = isSafeUrl ? BMSSecurityConstants.base64EncodingTableUrlSafe[output[i]]: BMSSecurityConstants.base64EncodingTable[output[i]] result.append(toAppend) } for i = ctcopy; i < 4; i++ { result += "=" } ixtext += 3 charsonline += 4 if (length > 0) && (charsonline >= length) { charsonline = 0 } } return result } internal static func base64StringFromData(data:NSData, isSafeUrl:Bool) -> String { let length = data.length return base64StringFromData(data, length: length, isSafeUrl: isSafeUrl) } }
e83766249bab24176d97d93167ff9d52
36.508251
287
0.549718
false
false
false
false
kylef/JSONSchema.swift
refs/heads/master
Tests/JSONSchemaTests/ValidationErrorTests.swift
bsd-3-clause
1
import Foundation import Spectre @testable import JSONSchema public let testValidationError: ((ContextType) -> Void) = { $0.it("can be converted to JSON") { let error = ValidationError( "example description", instanceLocation: JSONPointer(path: "/test/1"), keywordLocation: JSONPointer(path: "#/example") ) let jsonData = try JSONEncoder().encode(error) let json = try! JSONSerialization.jsonObject(with: jsonData) as! NSDictionary try expect(json) == [ "error": "example description", "instanceLocation": "/test/1", "keywordLocation": "#/example", ] } }
842f6c2d3596386e9b9e871604718516
26.086957
81
0.659711
false
true
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Model/Protocol/RemoteRefreshable.swift
mit
2
// // RemoteModifiable.swift // DereGuide // // Created by zzk on 2017/7/17. // Copyright © 2017 zzk. All rights reserved. // import CoreData import CloudKit private let MarkedForRemoteModificationKey = "markedForLocalChange" /// can upload to refresh remote record protocol RemoteRefreshable: class { var localTrackedKeys: [String] { get } var markedForLocalChange: Bool { get set } func markForRemoteModification() } extension RemoteRefreshable { public static var notMarkedForRemoteModificationPredicate: NSPredicate { return NSPredicate(format: "%K == false", MarkedForRemoteModificationKey) } public static var markedForRemoteModificationPredicate: NSPredicate { return NSCompoundPredicate(notPredicateWithSubpredicate: notMarkedForRemoteModificationPredicate) } } extension RemoteRefreshable where Self: NSManagedObject { var hasLocalTrackedChanges: Bool { return changedValues().keys.contains(where: { localTrackedKeys.contains($0) }) } func markForRemoteModification() { guard changedValue(forKey: MarkedForRemoteModificationKey) == nil && !markedForLocalChange else { return } markedForLocalChange = true } func unmarkForRemoteModification() { markedForLocalChange = false } } extension RemoteRefreshable where Self: RemoteUploadable & RemoteDeletable & DelayedDeletable { static var waitingForRemoteModificationPredicate: NSPredicate { return NSCompoundPredicate(andPredicateWithSubpredicates: [markedForRemoteModificationPredicate, uploadedPredicate, notMarkedForDeletionPredicate]) } }
d190043ee436f7aeffcd33f090d0e8ed
28.910714
155
0.73791
false
false
false
false
kang77649119/DouYuDemo
refs/heads/master
DouYuDemo/DouYuDemo/Classes/Home/View/PageTitleView.swift
mit
1
// // MenuView.swift // DouYuDemo // // Created by 也许、 on 16/10/7. // Copyright © 2016年 K. All rights reserved. // import UIKit protocol PageTitleViewDelegate : class { // 菜单点击 func pageTitleViewClick(_ index:Int) } class PageTitleView: UIView { weak var delegate:PageTitleViewDelegate? // 上一个选中的菜单 var storedMenuLabel:UILabel? // 菜单标题 var titles:[String]? // 存储菜单项 var menuItems:[UILabel]? // 选中颜色 let selectedColor : (CGFloat,CGFloat,CGFloat) = (255, 128, 0) // 普通颜色 let normalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) // 存放菜单内容的scrollView lazy var menuScrollView:UIScrollView = { let scrollView = UIScrollView() scrollView.bounces = false scrollView.showsHorizontalScrollIndicator = false return scrollView }() // 底部分隔条 lazy var menuScrollBottomLine:UIView = { let view = UIView() view.backgroundColor = UIColor.darkGray let h:CGFloat = 0.5 let y:CGFloat = menuH - h view.frame = CGRect(x: 0, y: y, width: screenW, height: h) return view }() // 选中菜单标识view lazy var selectedMenuLine:UIView = { let view = UIView() view.backgroundColor = UIColor.orange let w:CGFloat = screenW / CGFloat(self.titles!.count) let h:CGFloat = 2 let y:CGFloat = menuH - h view.frame = CGRect(x: 0, y: y, width: w, height: h) return view }() init(titles:[String], frame: CGRect) { self.titles = titles super.init(frame: frame) // 初始化UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { // 初始化UI func setupUI() { // 1.添加菜单项 addMenuScrollView() // 2.添加菜单与轮播视图之间的分隔线 addMenuScrollViewBottomLine() // 3.添加菜单选中时的标识线 addSelectedLine() } // 添加菜单项 func addMenuScrollView() { var labelX:CGFloat = 0 let labelY:CGFloat = 0 let labelW:CGFloat = frame.width / CGFloat(self.titles!.count) // 存储菜单项,切换菜单时需要用到 menuItems = [UILabel]() for (index,title) in titles!.enumerated() { let label = UILabel() label.text = title label.tag = index label.textColor = UIColor.darkGray label.font = UIFont.systemFont(ofSize: 13) labelX = labelW * CGFloat(index) label.textAlignment = .center label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: menuH) label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.menuClick(_:))) label.addGestureRecognizer(tapGes) menuItems?.append(label) menuScrollView.addSubview(label) } self.addSubview(menuScrollView) menuScrollView.frame = bounds } // 添加底部分隔条 func addMenuScrollViewBottomLine() { self.addSubview(menuScrollBottomLine) } // 添加选中标识 func addSelectedLine() { // 设置第一个菜单项选中 self.menuItems!.first!.textColor = UIColor.orange // 存储选中的菜单项 self.storedMenuLabel = self.menuItems!.first // 添加选中标识 self.addSubview(selectedMenuLine) } // 菜单点击(切换选中的菜单项以及对应菜单的视图) func menuClick(_ ges:UITapGestureRecognizer) { // 1.恢复上次选中的菜单项颜色 self.storedMenuLabel!.textColor = UIColor.darkGray // 2.获取点击的菜单项,设置文字颜色 let targetLabel = ges.view as! UILabel targetLabel.textColor = UIColor.orange // 3.存储本次点击的菜单项 self.storedMenuLabel = targetLabel // 4.选中标识线滑动至本次点击的菜单项位置上 UIView.animate(withDuration: 0.15) { self.selectedMenuLine.frame.origin.x = targetLabel.frame.origin.x } // 5.显示对应的控制器view delegate?.pageTitleViewClick(targetLabel.tag) } } extension PageTitleView { // 滑动视图时,菜单项从选中渐变至非选中状态 func setSelectedMenuLineOffset(_ progress:CGFloat, sourceIndex:Int, targetIndex:Int) { // 已选中的label let sourceLabel = self.menuItems![sourceIndex] // 滑动过程中即将选中的label let targetLabel = self.menuItems![targetIndex] // 1.选中标识移动 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x // 两个label的间距 乘以 进度 获得滑动过程中的位置偏移量 let moveX = moveTotalX * progress // 设置选中标识的位置 self.selectedMenuLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 2.文字颜色渐变 let colorRange = (selectedColor.0 - normalColor.0, g: selectedColor.1 - normalColor.1, b: selectedColor.2 - normalColor.2) // 已经选中的菜单项颜色逐渐变浅 sourceLabel.textColor = UIColor(r: selectedColor.0 - colorRange.0 * progress, g: selectedColor.1 - colorRange.1 * progress, b: selectedColor.2 - colorRange.2 * progress) // 即将被选中的菜单项颜色逐渐加深 targetLabel.textColor = UIColor(r: normalColor.0 + colorRange.0 * progress, g: normalColor.1 + colorRange.1 * progress, b: normalColor.2 + colorRange.2 * progress) // 3.保存选中的菜单项 self.storedMenuLabel = targetLabel } }
ac8135f8af4cc94c17f63ecdbe65fefd
24.852535
177
0.573797
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Generics/function_defs.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Type-check function definitions //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Basic type checking //===----------------------------------------------------------------------===// protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool { var b1 = t1.isEqual(t2) if b1 { return true } return t1.isEqual(u) // expected-error {{cannot convert value of type 'U' to expected argument type 'T'}} } protocol MethodLessComparable { func isLess(_ other: Self) -> Bool } func min<T : MethodLessComparable>(_ x: T, y: T) -> T { if (y.isLess(x)) { return y } return x } //===----------------------------------------------------------------------===// // Interaction with existential types //===----------------------------------------------------------------------===// func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) { var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} eqComp = u if t1.isEqual(eqComp) {} // expected-error{{cannot convert value of type 'EqualComparable' to expected argument type 'T'}} if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}} } protocol OtherEqualComparable { func isEqual(_ other: Self) -> Bool } func otherExistential<T : EqualComparable>(_ t1: T) { var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp2 _ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} } protocol Runcible { func runce<A>(_ x: A) func spoon(_ x: Self) } func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}} x.runce(5) } //===----------------------------------------------------------------------===// // Overloading //===----------------------------------------------------------------------===// protocol Overload { associatedtype A associatedtype B func getA() -> A func getB() -> B func f1(_: A) -> A // expected-note {{candidate expects value of type 'OtherOvl.A' for parameter #1}} func f1(_: B) -> B // expected-note {{candidate expects value of type 'OtherOvl.B' for parameter #1}} func f2(_: Int) -> A // expected-note{{found this candidate}} func f2(_: Int) -> B // expected-note{{found this candidate}} func f3(_: Int) -> Int // expected-note {{found this candidate}} func f3(_: Float) -> Float // expected-note {{found this candidate}} func f3(_: Self) -> Self // expected-note {{found this candidate}} var prop : Self { get } } func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl, other: OtherOvl) { var a = ovl.getA() var b = ovl.getB() // Overloading based on arguments _ = ovl.f1(a) a = ovl.f1(a) _ = ovl.f1(b) b = ovl.f1(b) // Overloading based on return type a = ovl.f2(17) b = ovl.f2(17) ovl.f2(17) // expected-error{{ambiguous use of 'f2'}} // Check associated types from different objects/different types. a = ovl2.f2(17) a = ovl2.f1(a) other.f1(a) // expected-error{{no exact matches in call to instance method 'f1'}} // Overloading based on context var f3i : (Int) -> Int = ovl.f3 var f3f : (Float) -> Float = ovl.f3 var f3ovl_1 : (Ovl) -> Ovl = ovl.f3 var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3 var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}} var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3 var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3 var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3 var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3 var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3 } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol Subscriptable { associatedtype Index associatedtype Value func getIndex() -> Index func getValue() -> Value subscript (index : Index) -> Value { get set } } protocol IntSubscriptable { associatedtype ElementType func getElement() -> ElementType subscript (index : Int) -> ElementType { get } } func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) { var index = t.getIndex() var value = t.getValue() var element = t.getElement() value = t[index] t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}} element = t[17] t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}} // Suggests the Int form because we prefer concrete matches to generic matches in diagnosis. t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}} } //===----------------------------------------------------------------------===// // Static functions //===----------------------------------------------------------------------===// protocol StaticEq { static func isEqual(_ x: Self, y: Self) -> Bool } func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) { if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} // expected-error {{missing argument label 'y:' in call}} if T.isEqual(t, y: t) { return } if U.isEqual(u, y: u) { return } T.isEqual(t, y: u) // expected-error{{cannot convert value of type 'U' to expected argument type 'T'}} } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Ordered { static func <(lhs: Self, rhs: Self) -> Bool } func testOrdered<T : Ordered>(_ x: T, y: Int) { if y < 100 || 500 < y { return } if x < x { return } } //===----------------------------------------------------------------------===// // Requires clauses //===----------------------------------------------------------------------===// func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool where T : EqualComparable, T : MethodLessComparable { let b1 = t1.isEqual(t2) if b1 || t1.isLess(t2) { return true } } protocol GeneratesAnElement { associatedtype Element : EqualComparable func makeIterator() -> Element } protocol AcceptsAnElement { associatedtype Element : MethodLessComparable func accept(_ e : Element) } func impliedSameType<T : GeneratesAnElement>(_ t: T) where T : AcceptsAnElement { t.accept(t.makeIterator()) let e = t.makeIterator(), e2 = t.makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } protocol GeneratesAssoc1 { associatedtype Assoc1 : EqualComparable func get() -> Assoc1 } protocol GeneratesAssoc2 { associatedtype Assoc2 : MethodLessComparable func get() -> Assoc2 } func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2> (_ t: T, u: U) -> Bool where T.Assoc1 == U.Assoc2 { return t.get().isEqual(u.get()) || u.get().isLess(t.get()) } protocol GeneratesMetaAssoc1 { associatedtype MetaAssoc1 : GeneratesAnElement func get() -> MetaAssoc1 } protocol GeneratesMetaAssoc2 { associatedtype MetaAssoc2 : AcceptsAnElement func get() -> MetaAssoc2 } func recursiveSameType <T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1> (_ t: T, u: U, v: V) where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2 { t.get().accept(t.get().makeIterator()) let e = t.get().makeIterator(), e2 = t.get().makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } // <rdar://problem/13985164> protocol P1 { associatedtype Element } protocol P2 { associatedtype AssocP1 : P1 func getAssocP1() -> AssocP1 } func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool where E0.Element == E1.Element, E0.Element : EqualComparable { } func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool where S0.AssocP1.Element == S1.AssocP1.Element, S1.AssocP1.Element : EqualComparable { return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1()) } // FIXME: Test same-type constraints that try to equate things we // don't want to equate, e.g., T == U. //===----------------------------------------------------------------------===// // Bogus requirements //===----------------------------------------------------------------------===// func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}} func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}} // expected-warning@-1{{redundant same-type constraint 'T' == 'T'}} func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}} func badTypeConformance3<T>(_: T) where (T) -> () : EqualComparable { } // expected-error@-1{{type '(T) -> ()' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance4<T>(_: T) where @escaping (inout T) throws -> () : EqualComparable { } // expected-error@-1{{type '(inout T) throws -> ()' in conformance requirement does not refer to a generic parameter or associated type}} // expected-error@-2 2 {{@escaping attribute may only be used in function parameter position}} // FIXME: Error emitted twice. func badTypeConformance5<T>(_: T) where T & Sequence : EqualComparable { } // expected-error@-1 2 {{non-protocol, non-class type 'T' cannot be used within a protocol-constrained type}} // expected-error@-2{{type 'Sequence' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance6<T>(_: T) where [T] : Collection { } // expected-error@-1{{type '[T]' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance7<T, U>(_: T, _: U) where T? : U { } // expected-error@-1{{type 'T?' constrained to non-protocol, non-class type 'U'}} func badSameType<T, U : GeneratesAnElement, V>(_ : T, _ : U) where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
742ead6e2bc72d0e944d8f15875ba537
36.860317
375
0.593996
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/BeeFun/SystemManager/Manager/View/MJRefreshManager.swift
mit
1
// // MJRefreshManager.swift // BeeFun // // Created by WengHengcong on 2017/4/13. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit import MJRefresh protocol MJRefreshManagerAction: class { func headerRefresh() func footerRefresh() } class MJRefreshManager: NSObject { weak var delegate: MJRefreshManagerAction? override init() { super.init() } /// 头部刷新控件 /// /// - Returns: <#return value description#> func header() -> MJRefreshNormalHeader { let header = MJRefreshNormalHeader() header.lastUpdatedTimeLabel.isHidden = true header.stateLabel.isHidden = true // header.setTitle(kHeaderIdelTIP.localized, for: .idle) // header.setTitle(kHeaderPullTip, for: .pulling) // header.setTitle(kHeaderPullingTip, for: .refreshing) header.setRefreshingTarget(self, refreshingAction:#selector(mj_headerRefresh)) return header } /// 头部刷新控件 /// /// - Parameters: /// - target: <#target description#> /// - action: 刷新回调方法 /// - Returns: <#return value description#> func header(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshNormalHeader { let header = MJRefreshNormalHeader() header.lastUpdatedTimeLabel.isHidden = true header.stateLabel.isHidden = true // header.setTitle(kHeaderIdelTIP, for: .idle) // header.setTitle(kHeaderPullTip, for: .pulling) // header.setTitle(kHeaderPullingTip, for: .refreshing) header.setRefreshingTarget(target, refreshingAction:action) return header } /// 内部代理方法 @objc func mj_headerRefresh() { if self.delegate != nil { self.delegate?.headerRefresh() } } /// 底部加载控件 /// /// - Returns: <#return value description#> func footer() -> MJRefreshAutoNormalFooter { let footer = MJRefreshAutoNormalFooter() // footer.isAutomaticallyHidden = true // footer.setTitle(kFooterIdleTip, for: .idle) // footer.setTitle(kFooterLoadTip, for: .refreshing) // footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData) footer.setRefreshingTarget(self, refreshingAction:#selector(mj_footerRefresh)) footer.stateLabel.isHidden = true footer.isRefreshingTitleHidden = true return footer } /// 底部加载控件 /// /// - Parameters: /// - target: <#target description#> /// - action: 加载回调方法 /// - Returns: <#return value description#> func footer(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshAutoNormalFooter { let footer = MJRefreshAutoNormalFooter() // footer.setTitle(kFooterIdleTip, for: .idle) // footer.setTitle(kFooterLoadTip, for: .refreshing) // footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData) footer.setRefreshingTarget(target, refreshingAction:action) footer.stateLabel.isHidden = true footer.isRefreshingTitleHidden = true return footer } /// 内部代理方法 @objc func mj_footerRefresh() { if self.delegate != nil { self.delegate?.footerRefresh() } } }
c09a549d462a67e9603108232d90cc5b
30.294118
98
0.643484
false
false
false
false
kinwahlai/YetAnotherHTTPStub
refs/heads/master
ExampleTests/ExampleWithMoyaTests.swift
mit
1
// // ExampleWithMoyaTests.swift // ExampleTests // // Created by Darren Lai on 7/30/20. // Copyright © 2020 KinWahLai. All rights reserved. // import XCTest import YetAnotherHTTPStub @testable import Example class ExampleWithMoyaTests: XCTestCase { override func setUpWithError() throws { } override func tearDownWithError() throws { } func testSimpleExample() throws { let bundle = Bundle(for: ExampleWithMoyaTests.self) guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return } YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/get")) .thenResponse(responseBuilder: jsonData(data, status: 200)) } let expect = expectation(description: "") let service = ServiceUsingMoya() service.getRequest { (dict, _) in XCTAssertNotNil(dict) let originIp = dict!["origin"] as! String XCTAssertEqual(originIp, "9.9.9.9") expect.fulfill() } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error) } } func testMultipleRequestExample() { let bundle = Bundle(for: ExampleWithMoyaTests.self) guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return } let expect1 = expectation(description: "1") let expect2 = expectation(description: "2") YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/get")) .thenResponse(responseBuilder: jsonData(data, status: 200)) session.whenRequest(matcher: http(.get, uri: "/get?show_env=1&page=1")) .thenResponse(responseBuilder: jsonString("{\"args\":{\"page\": 1,\"show_env\": 1}}", status: 200)) } let service = ServiceUsingMoya() service.getRequest { (dict, _) in XCTAssertNotNil(dict) let originIp = dict!["origin"] as! String XCTAssertEqual(originIp, "9.9.9.9") expect1.fulfill() } service.getRequest(with: "https://httpbin.org/get?show_env=1&page=1") { (dict, _) in let args = dict!["args"] as! [String: Any] XCTAssertNotNil(args) XCTAssertEqual(args["show_env"] as! Int, 1) expect2.fulfill() } wait(for: [expect1, expect2], timeout: 5) } func testMultipleResponseExample() { let expect1 = expectation(description: "1") let expect2 = expectation(description: "2") let expect3 = expectation(description: "3") YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/polling")) .thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200)) .thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200)) .thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200)) } let service = ServiceUsingMoya() let response3: HttpbinService.ResquestResponse = { (dict, _) in let dictInt = dict as! [String: Int] XCTAssertEqual(dictInt["status"], 1) expect3.fulfill() } let response2: HttpbinService.ResquestResponse = { [response3] (dict, _) in expect2.fulfill() service.getRequest(with: "https://httpbin.org/polling", response3) } let response1: HttpbinService.ResquestResponse = { [response2] (dict, _) in expect1.fulfill() service.getRequest(with: "https://httpbin.org/polling", response2) } service.getRequest(with: "https://httpbin.org/polling", response1) wait(for: [expect1, expect2, expect3], timeout: 5) } func testSimpleExampleWithDelay() { let delay: TimeInterval = 5 let bundle = Bundle(for: ExampleWithMoyaTests.self) guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return } YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/get")) .thenResponse(withDelay: delay, responseBuilder: jsonData(data, status: 200)) } let service = ServiceUsingMoya() let expect = expectation(description: "") service.getRequest { (dict, error) in XCTAssertNotNil(dict) XCTAssertNil(error) expect.fulfill() } waitForExpectations(timeout: delay + 1) { (error) in XCTAssertNil(error) } } func testExampleUsingFileContentBuilder() { guard let filePath: URL = Bundle(for: ExampleWithMoyaTests.self).url(forResource: "GET", withExtension: "json") else { XCTFail(); return } YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/get")) .thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent } let service = ServiceUsingMoya() let expect = expectation(description: "") service.getRequest { (dict, error) in XCTAssertNil(error) XCTAssertNotNil(dict) let originIp = dict!["origin"] as! String XCTAssertEqual(originIp, "9.9.9.9") expect.fulfill() } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error) } } func testRepeatableResponseExample() { let expect1 = expectation(description: "1") let expect2 = expectation(description: "2") let expect3 = expectation(description: "3") YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/polling")) .thenResponse(repeat: 2, responseBuilder: jsonString("{\"status\": 0}", status: 200)) .thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200)) } let service = ServiceUsingMoya() let response3: HttpbinService.ResquestResponse = { (dict, error) in XCTAssertNotNil(dict) XCTAssertNil(error) let dictInt = dict as! [String: Int] XCTAssertEqual(dictInt["status"], 1) expect3.fulfill() } let response2: HttpbinService.ResquestResponse = { [response3] (dict, error) in XCTAssertNotNil(dict) XCTAssertNil(error) expect2.fulfill() service.getRequest(with: "https://httpbin.org/polling", response3) } let response1: HttpbinService.ResquestResponse = { [response2] (dict, error) in XCTAssertNotNil(dict) XCTAssertNil(error) expect1.fulfill() service.getRequest(with: "https://httpbin.org/polling", response2) } service.getRequest(with: "https://httpbin.org/polling", response1) wait(for: [expect1, expect2, expect3], timeout: 5) } func testGetNotifyAfterStubResponseReplied() { var gotNotify: String? = nil YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: http(.get, uri: "/get")) .thenResponse(configurator: { (param) in param.setResponseDelay(2) .setBuilder(builder: jsonString("{\"hello\":\"world\"}", status: 200)) .setPostReply { gotNotify = "post reply notification" } }) } let service = ServiceUsingMoya() let expect = expectation(description: "") service.getRequest { (dict, error) in expect.fulfill() } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error) } XCTAssertEqual(gotNotify, "post reply notification") } func testPostARequest() { guard let filePath: URL = Bundle(for: ExampleWithAlamofireTests.self).url(forResource: "POST", withExtension: "json") else { XCTFail(); return } YetAnotherURLProtocol.stubHTTP { (session) in session.whenRequest(matcher: everything) .thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent } let service = ServiceUsingMoya() let expect = expectation(description: "") service.post(["username": "Darren"]) { (dict, error) in let originIp = dict!["origin"] as! String XCTAssertEqual(originIp, "9.9.9.9") let url = dict!["url"] as! String XCTAssertEqual(url, "https://httpbin.org/post") expect.fulfill() } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error) } } }
1332445ec8e2596d68a39f26258fb5c5
39.116883
161
0.581418
false
true
false
false
EasySwift/EasySwift
refs/heads/master
Carthage/Checkouts/Bond/Sources/ObservableDictionary.swift
apache-2.0
2
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import ReactiveKit public enum ObservableDictionaryEventKind<Key: Hashable, Value> { case reset case inserts([DictionaryIndex<Key, Value>]) case deletes([DictionaryIndex<Key, Value>]) case updates([DictionaryIndex<Key, Value>]) case beginBatchEditing case endBatchEditing } public struct ObservableDictionaryEvent<Key: Hashable, Value> { public let kind: ObservableDictionaryEventKind<Key, Value> public let source: ObservableDictionary<Key, Value> } public class ObservableDictionary<Key: Hashable, Value>: Collection, SignalProtocol { public fileprivate(set) var dictionary: Dictionary<Key, Value> fileprivate let subject = PublishSubject<ObservableDictionaryEvent<Key, Value>, NoError>() fileprivate let lock = NSRecursiveLock(name: "com.reactivekit.bond.observabledictionary") public init(_ dictionary: Dictionary<Key, Value>) { self.dictionary = dictionary } public func makeIterator() -> Dictionary<Key, Value>.Iterator { return dictionary.makeIterator() } public var underestimatedCount: Int { return dictionary.underestimatedCount } public var startIndex: DictionaryIndex<Key, Value> { return dictionary.startIndex } public var endIndex: DictionaryIndex<Key, Value> { return dictionary.endIndex } public func index(after i: DictionaryIndex<Key, Value>) -> DictionaryIndex<Key, Value> { return dictionary.index(after: i) } public var isEmpty: Bool { return dictionary.isEmpty } public var count: Int { return dictionary.count } public subscript(position: DictionaryIndex<Key, Value>) -> Dictionary<Key, Value>.Iterator.Element { get { return dictionary[position] } } public subscript(key: Key) -> Value? { get { return dictionary[key] } } public func observe(with observer: @escaping (Event<ObservableDictionaryEvent<Key, Value>, NoError>) -> Void) -> Disposable { observer(.next(ObservableDictionaryEvent(kind: .reset, source: self))) return subject.observe(with: observer) } } public class MutableObservableDictionary<Key: Hashable, Value>: ObservableDictionary<Key, Value> { public override subscript (key: Key) -> Value? { get { return dictionary[key] } set { if let value = newValue { _ = updateValue(value, forKey: key) } else { _ = removeValue(forKey: key) } } } /// Update (or insert) value in the dictionary. public func updateValue(_ value: Value, forKey key: Key) -> Value? { if let index = dictionary.index(forKey: key) { let old = dictionary.updateValue(value, forKey: key) subject.next(ObservableDictionaryEvent(kind: .updates([index]), source: self)) return old } else { _ = dictionary.updateValue(value, forKey: key) subject.next(ObservableDictionaryEvent(kind: .inserts([dictionary.index(forKey: key)!]), source: self)) return nil } } /// Remove value from the dictionary. @discardableResult public func removeValue(forKey key: Key) -> Value? { if let index = dictionary.index(forKey: key) { let (_, old) = dictionary.remove(at: index) subject.next(ObservableDictionaryEvent(kind: .deletes([index]), source: self)) return old } else { return nil } } public func replace(with dictionary: Dictionary<Key, Value>) { lock.lock(); defer { lock.unlock() } self.dictionary = dictionary subject.next(ObservableDictionaryEvent(kind: .reset, source: self)) } /// Perform batched updates on the dictionary. public func batchUpdate(_ update: (MutableObservableDictionary<Key, Value>) -> Void) { lock.lock(); defer { lock.unlock() } subject.next(ObservableDictionaryEvent(kind: .beginBatchEditing, source: self)) update(self) subject.next(ObservableDictionaryEvent(kind: .endBatchEditing, source: self)) } /// Change the underlying value withouth notifying the observers. public func silentUpdate(_ update: (inout Dictionary<Key, Value>) -> Void) { lock.lock(); defer { lock.unlock() } update(&dictionary) } }
9b1188d582b80ef19cc4fb1c44750463
32.730769
127
0.708096
false
false
false
false
Majki92/SwiftEmu
refs/heads/master
SwiftBoy/GameBoyDevice.swift
gpl-2.0
2
// // GameBoyDevice.swift // SwiftBoy // // Created by Michal Majczak on 12.09.2015. // Copyright (c) 2015 Michal Majczak. All rights reserved. // import Foundation import Dispatch protocol ProtoEmulatorScreen { func copyBuffer(_ screenBuffer: [UInt8]) } class GameBoyDevice { let joypad: GameBoyJoypad let memory: GameBoyRAM let cpu: GameBoyCPU let ppu: GameBoyPPU var running: Bool var queue: DispatchQueue var bp: UInt16 // CPU base clock in Hz let clock: Int = 4194304 // CPU instr clock lazy var iClock: Int = self.clock/4 lazy var ticTime: Double = 1.0/Double(self.iClock) // aprox. tics in a half of a frame lazy var ticLoopCount: Int = self.iClock/120 init() { self.joypad = GameBoyJoypad() self.memory = GameBoyRAM(joypad: joypad) self.joypad.registerRAM(memory) self.cpu = GameBoyCPU(memory: memory) self.ppu = GameBoyPPU(memory: memory) self.queue = DispatchQueue(label: "GameBoyLoop", attributes: []) self.running = false self.bp = 0xFFFF fastBootStrap() } func setScreen(_ screen: ProtoEmulatorScreen) { self.ppu.setScreen(screen) } func loadRom(_ name: URL) -> Bool { guard let mbc = loadRomMBC(name) else { return false; } memory.loadRom(mbc) fastBootStrap() return true; } func loadBios() { fastBootStrap() } func setBP(_ point: UInt16) { bp = point } func stepTic() { var delta = cpu.timer.getMTimer() cpu.tic() delta = cpu.timer.getMTimer() - delta ppu.tic(delta) } func tic() { let start = Date().timeIntervalSince1970 var count: Int = 0 while count < ticLoopCount { var delta = cpu.timer.getMTimer() cpu.tic() delta = cpu.timer.getMTimer() - delta ppu.tic(delta) count += Int(delta) if cpu.registers.PC == bp { running = false } } let elapsed = Date().timeIntervalSince1970 - start if running { let time = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * (ticTime * Double(count) - elapsed))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: tic) } } func fastBootStrap() { //cpu.memory.unmapBios() // registers state after bootstrap cpu.registers.A = 0x01 cpu.registers.F = 0xB0 //cpu.registers.B = 0x00 cpu.registers.C = 0x13 //cpu.registers.D = 0x00 cpu.registers.E = 0xD8 cpu.registers.SP = 0xFFFE cpu.registers.PC = 0x100 // memory state after bootstrap cpu.memory.write(address: 0xFF10, value: 0x80) cpu.memory.write(address: 0xFF11, value: 0xBF) cpu.memory.write(address: 0xFF12, value: 0xF3) cpu.memory.write(address: 0xFF14, value: 0xBF) cpu.memory.write(address: 0xFF16, value: 0x3F) cpu.memory.write(address: 0xFF19, value: 0xBF) cpu.memory.write(address: 0xFF1A, value: 0x7F) cpu.memory.write(address: 0xFF1B, value: 0xFF) cpu.memory.write(address: 0xFF1C, value: 0x9F) cpu.memory.write(address: 0xFF1E, value: 0xBF) cpu.memory.write(address: 0xFF20, value: 0xFF) cpu.memory.write(address: 0xFF23, value: 0xBF) cpu.memory.write(address: 0xFF24, value: 0x77) cpu.memory.write(address: 0xFF25, value: 0xF3) cpu.memory.write(address: 0xFF26, value: 0xF1) cpu.memory.write(address: 0xFF40, value: 0x91) cpu.memory.write(address: 0xFF47, value: 0xFC) cpu.memory.write(address: 0xFF48, value: 0xFF) cpu.memory.write(address: 0xFF49, value: 0xFF) } func start() { running = true queue.async { self.tic() } } func reset() { running = false queue.sync(flags: .barrier, execute: {}); memory.clear() cpu.reset() ppu.reset() loadBios() } }
751e22301a9b2ef5dd61bf3b2d192f8a
27.371622
140
0.57609
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/functions.swift
apache-2.0
3
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s import Swift // just for Optional func markUsed<T>(_ t: T) {} typealias Int = Builtin.Int64 typealias Int64 = Builtin.Int64 typealias Bool = Builtin.Int1 var zero = getInt() func getInt() -> Int { return zero } func standalone_function(_ x: Int, _ y: Int) -> Int { return x } func higher_order_function(_ f: (_ x: Int, _ y: Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } func higher_order_function2(_ f: (Int, Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } struct SomeStruct { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc init(x:Int, y:Int) {} mutating func method(_ x: Int) {} static func static_method(_ x: Int) {} func generic_method<T>(_ x: T) {} } class SomeClass { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc // CHECK-LABEL: sil hidden @_TFC9functions9SomeClassc{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @owned SomeClass) -> @owned SomeClass // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $SomeClass): // CHECK-LABEL: sil hidden @_TFC9functions9SomeClassC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $@thick SomeClass.Type): init(x:Int, y:Int) {} // CHECK-LABEL: sil hidden @_TFC9functions9SomeClass6method{{.*}} : $@convention(method) (Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: bb0(%0 : $Builtin.Int64, %1 : $SomeClass): func method(_ x: Int) {} // CHECK-LABEL: sil hidden @_TZFC9functions9SomeClass13static_method{{.*}} : $@convention(method) (Builtin.Int64, @thick SomeClass.Type) -> () // CHECK: bb0(%0 : $Builtin.Int64, %1 : $@thick SomeClass.Type): class func static_method(_ x: Int) {} var someProperty: Int { get { return zero } set {} } subscript(x:Int, y:Int) -> Int { get { return zero } set {} } func generic<T>(_ x: T) -> T { return x } } func SomeClassWithBenefits() -> SomeClass.Type { return SomeClass.self } protocol SomeProtocol { func method(_ x: Int) static func static_method(_ x: Int) } struct ConformsToSomeProtocol : SomeProtocol { func method(_ x: Int) { } static func static_method(_ x: Int) { } } class SomeGeneric<T> { init() { } func method(_ x: T) -> T { return x } func generic<U>(_ x: U) -> U { return x } } // CHECK-LABEL: sil hidden @_TF9functions5calls{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> () func calls(_ i:Int, j:Int, k:Int) { var i = i var j = j var k = k // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $Builtin.Int64): // CHECK: [[IBOX:%[0-9]+]] = alloc_box $Builtin.Int64 // CHECK: [[IADDR:%.*]] = project_box [[IBOX]] // CHECK: [[JBOX:%[0-9]+]] = alloc_box $Builtin.Int64 // CHECK: [[JADDR:%.*]] = project_box [[JBOX]] // CHECK: [[KBOX:%[0-9]+]] = alloc_box $Builtin.Int64 // CHECK: [[KADDR:%.*]] = project_box [[KBOX]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: apply [[FUNC]]([[I]], [[J]]) standalone_function(i, j) // -- Curry 'self' onto struct method argument lists. // CHECK: [[ST_ADDR:%.*]] = alloc_box $SomeStruct // CHECK: [[CTOR:%.*]] = function_ref @_TFV9functions10SomeStructC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct // CHECK: [[METATYPE:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[I:%.*]] = load [[IADDR]] // CHECK: [[J:%.*]] = load [[JADDR]] // CHECK: apply [[CTOR]]([[I]], [[J]], [[METATYPE]]) : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct var st = SomeStruct(x: i, y: j) // -- Use of unapplied struct methods as values. // CHECK: [[THUNK:%.*]] = function_ref @_TFV9functions10SomeStruct6method{{.*}} // CHECK: [[THUNK_THICK:%.*]] = thin_to_thick_function [[THUNK]] var stm1 = SomeStruct.method stm1(&st)(i) // -- Curry 'self' onto method argument lists dispatched using class_method. // CHECK: [[CBOX:%[0-9]+]] = alloc_box $SomeClass // CHECK: [[CADDR:%.*]] = project_box [[CBOX]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TFC9functions9SomeClassC{{.*}} : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: [[C:%[0-9]+]] = apply [[FUNC]]([[I]], [[J]], [[META]]) var c = SomeClass(x: i, y: j) // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[C]]) c.method(i) // -- Curry 'self' onto unapplied methods dispatched using class_method. // CHECK: [[METHOD_CURRY_THUNK:%.*]] = function_ref @_TFC9functions9SomeClass6method{{.*}} // CHECK: apply [[METHOD_CURRY_THUNK]] var cm1 = SomeClass.method(c) cm1(i) // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[C]]) SomeClass.method(c)(i) // -- Curry the Type onto static method argument lists. // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[META:%[0-9]+]] : {{.*}}, #SomeClass.static_method!1 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[META]]) type(of: c).static_method(i) // -- Curry property accesses. // -- FIXME: class_method-ify class getters. // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[GETTER:%[0-9]+]] = class_method {{.*}} : $SomeClass, #SomeClass.someProperty!getter.1 // CHECK: apply [[GETTER]]([[C]]) i = c.someProperty // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.someProperty!setter.1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: apply [[SETTER]]([[I]], [[C]]) c.someProperty = i // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: [[K:%[0-9]+]] = load [[KADDR]] // CHECK: [[GETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!getter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 , $@convention(method) (Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> Builtin.Int64 // CHECK: apply [[GETTER]]([[J]], [[K]], [[C]]) i = c[j, k] // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: [[K:%[0-9]+]] = load [[KADDR]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!setter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> () , $@convention(method) (Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: apply [[SETTER]]([[K]], [[I]], [[J]], [[C]]) c[i, j] = k // -- Curry the projected concrete value in an existential (or its Type) // -- onto protocol type methods dispatched using protocol_method. // CHECK: [[PBOX:%[0-9]+]] = alloc_box $SomeProtocol // CHECK: [[PADDR:%.*]] = project_box [[PBOX]] var p : SomeProtocol = ConformsToSomeProtocol() // CHECK: [[TEMP:%.*]] = alloc_stack $SomeProtocol // CHECK: copy_addr [[PADDR]] to [initialization] [[TEMP]] // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr [[TEMP]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) // CHECK: destroy_addr [[PVALUE]] // CHECK: deinit_existential_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] p.method(i) // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr [[PADDR:%.*]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) var sp : SomeProtocol = ConformsToSomeProtocol() sp.method(i) // FIXME: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED:@opened(.*) SomeProtocol]], #SomeProtocol.static_method!1 // FIXME: [[I:%[0-9]+]] = load [[IADDR]] // FIXME: apply [[PMETHOD]]([[I]], [[PMETA]]) // Needs existential metatypes //type(of: p).static_method(i) // -- Use an apply or partial_apply instruction to bind type parameters of a generic. // CHECK: [[GBOX:%[0-9]+]] = alloc_box $SomeGeneric<Builtin.Int64> // CHECK: [[GADDR:%.*]] = project_box [[GBOX]] // CHECK: [[CTOR_GEN:%[0-9]+]] = function_ref @_TFC9functions11SomeGenericC{{.*}} : $@convention(method) <τ_0_0> (@thick SomeGeneric<τ_0_0>.Type) -> @owned SomeGeneric<τ_0_0> // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeGeneric<Builtin.Int64>.Type // CHECK: apply [[CTOR_GEN]]<Builtin.Int64>([[META]]) var g = SomeGeneric<Builtin.Int64>() // CHECK: [[G:%[0-9]+]] = load [[GADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.method!1 // CHECK: [[TMPI:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPI]], [[G]]) g.method(i) // CHECK: [[G:%[0-9]+]] = load [[GADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.generic!1 // CHECK: [[TMPJ:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPJ]], [[G]]) g.generic(j) // CHECK: [[C:%[0-9]+]] = load [[CADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.generic!1 // CHECK: [[TMPK:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPK]], [[C]]) c.generic(k) // FIXME: curried generic entry points //var gm1 = g.method //gm1(i) //var gg1 : (Int) -> Int = g.generic //gg1(j) //var cg1 : (Int) -> Int = c.generic //cg1(k) // SIL-level "thin" function values need to be able to convert to // "thick" function values when stored, returned, or passed as arguments. // CHECK: [[FBOX:%[0-9]+]] = alloc_box $@callee_owned (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FADDR:%.*]] = project_box [[FBOX]] // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: store [[FUNC_THICK]] to [[FADDR]] var f = standalone_function // CHECK: [[F:%[0-9]+]] = load [[FADDR]] // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: apply [[F]]([[I]], [[J]]) f(i, j) // CHECK: [[HOF:%[0-9]+]] = function_ref @_TF9functions21higher_order_function{{.*}} : $@convention(thin) {{.*}} // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: apply [[HOF]]([[FUNC_THICK]], [[I]], [[J]]) higher_order_function(standalone_function, i, j) // CHECK: [[HOF2:%[0-9]+]] = function_ref @_TF9functions22higher_order_function2{{.*}} : $@convention(thin) {{.*}} // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%.*]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[I:%[0-9]+]] = load [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [[JADDR]] // CHECK: apply [[HOF2]]([[FUNC_THICK]], [[I]], [[J]]) higher_order_function2(standalone_function, i, j) } // -- Curried entry points // CHECK-LABEL: sil shared [thunk] @_TFV9functions10SomeStruct6method{{.*}} : $@convention(thin) (@inout SomeStruct) -> @owned @callee_owned (Builtin.Int64) -> () { // CHECK: [[UNCURRIED:%.*]] = function_ref @_TFV9functions10SomeStruct6method{{.*}} : $@convention(method) (Builtin.Int64, @inout SomeStruct) -> (){{.*}} // user: %2 // CHECK: [[CURRIED:%.*]] = partial_apply [[UNCURRIED]] // CHECK: return [[CURRIED]] // CHECK-LABEL: sil shared [thunk] @_TFC9functions9SomeClass6method{{.*}} : $@convention(thin) (@owned SomeClass) -> @owned @callee_owned (Builtin.Int64) -> () // CHECK: bb0(%0 : $SomeClass): // CHECK: class_method %0 : $SomeClass, #SomeClass.method!1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: %2 = partial_apply %1(%0) // CHECK: return %2 func return_func() -> (_ x: Builtin.Int64, _ y: Builtin.Int64) -> Builtin.Int64 { // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_TF9functions19standalone_function{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: return [[FUNC_THICK]] return standalone_function } func standalone_generic<T>(_ x: T, y: T) -> T { return x } // CHECK-LABEL: sil hidden @_TF9functions14return_genericFT_FTBi64_Bi64__Bi64_ func return_generic() -> (_ x:Builtin.Int64, _ y:Builtin.Int64) -> Builtin.Int64 { // CHECK: [[GEN:%.*]] = function_ref @_TF9functions18standalone_generic{{.*}} : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<Builtin.Int64>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in Builtin.Int64, @in Builtin.Int64) -> @out Builtin.Int64) -> Builtin.Int64 // CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @_TF9functions20return_generic_tuple{{.*}} func return_generic_tuple() -> (_ x: (Builtin.Int64, Builtin.Int64), _ y: (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) { // CHECK: [[GEN:%.*]] = function_ref @_TF9functions18standalone_generic{{.*}} : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<(Builtin.Int64, Builtin.Int64)>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in (Builtin.Int64, Builtin.Int64), @in (Builtin.Int64, Builtin.Int64)) -> @out (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) // CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @_TF9functions16testNoReturnAttrFT_Os5Never : $@convention(thin) () -> Never func testNoReturnAttr() -> Never {} // CHECK-LABEL: sil hidden @_TF9functions20testNoReturnAttrPoly{{.*}} : $@convention(thin) <T> (@in T) -> Never func testNoReturnAttrPoly<T>(_ x: T) -> Never {} // CHECK-LABEL: sil hidden @_TF9functions21testNoReturnAttrParam{{.*}} : $@convention(thin) (@owned @callee_owned () -> Never) -> () func testNoReturnAttrParam(_ fptr: () -> Never) -> () {} // CHECK-LABEL: sil hidden [transparent] @_TF9functions15testTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 @_transparent func testTransparent(_ x: Bool) -> Bool { return x } // CHECK-LABEL: sil hidden @_TF9functions16applyTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 { func applyTransparent(_ x: Bool) -> Bool { // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF9functions15testTransparent{{.*}} : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 // CHECK: apply [[FUNC]]({{%[0-9]+}}) : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 return testTransparent(x) } // CHECK-LABEL: sil hidden [noinline] @_TF9functions15noinline_calleeFT_T_ : $@convention(thin) () -> () @inline(never) func noinline_callee() {} // CHECK-LABEL: sil hidden [always_inline] @_TF9functions20always_inline_calleeFT_T_ : $@convention(thin) () -> () @inline(__always) func always_inline_callee() {} // CHECK-LABEL: sil [fragile] [always_inline] @_TF9functions27public_always_inline_calleeFT_T_ : $@convention(thin) () -> () @inline(__always) public func public_always_inline_callee() {} protocol AlwaysInline { func alwaysInlined() } // CHECK-LABEL: sil hidden [always_inline] @_TFV9functions19AlwaysInlinedMember13alwaysInlined{{.*}} : $@convention(method) (AlwaysInlinedMember) -> () { // protocol witness for functions.AlwaysInline.alwaysInlined <A : functions.AlwaysInline>(functions.AlwaysInline.Self)() -> () in conformance functions.AlwaysInlinedMember : functions.AlwaysInline in functions // CHECK-LABEL: sil hidden [transparent] [thunk] [always_inline] @_TTWV9functions19AlwaysInlinedMemberS_12AlwaysInlineS_FS1_13alwaysInlined{{.*}} : $@convention(witness_method) (@in_guaranteed AlwaysInlinedMember) -> () { struct AlwaysInlinedMember : AlwaysInline { @inline(__always) func alwaysInlined() {} } // CHECK-LABEL: sil hidden [_semantics "foo"] @_TF9functions9semanticsFT_T_ : $@convention(thin) () -> () @_semantics("foo") func semantics() {} // <rdar://problem/17828355> curried final method on a class crashes in irgen final class r17828355Class { func method(_ x : Int) { var a : r17828355Class var fn = a.method // currying a final method. } } // The curry thunk for the method should not include a class_method instruction. // CHECK-LABEL: sil shared [thunk] @_TFC9functions14r17828355Class6methodF // CHECK: bb0(%0 : $r17828355Class): // CHECK-NEXT: // function_ref functions.r17828355Class.method (Builtin.Int64) -> () // CHECK-NEXT: %1 = function_ref @_TFC9functions14r17828355Class6method{{.*}} : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: partial_apply %1(%0) : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: return // <rdar://problem/19981118> Swift 1.2 beta 2: Closures nested in closures copy, rather than reference, captured vars. func noescapefunc(f: () -> ()) {} func escapefunc(_ f : @escaping () -> ()) {} func testNoescape() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. var a = 0 noescapefunc { escapefunc { a = 42 } } markUsed(a) } // CHECK-LABEL: functions.testNoescape () -> () // CHECK-NEXT: sil hidden @_TF9functions12testNoescapeFT_T_ : $@convention(thin) () -> () // CHECK: function_ref functions.(testNoescape () -> ()).(closure #1) // CHECK-NEXT: function_ref @_TFF9functions12testNoescapeFT_T_U_FT_T_ : $@convention(thin) (@owned @box Int) -> () // Despite being a noescape closure, this needs to capture 'a' by-box so it can // be passed to the capturing closure.closure // CHECK: functions.(testNoescape () -> ()).(closure #1) // CHECK-NEXT: sil shared @_TFF9functions12testNoescapeFT_T_U_FT_T_ : $@convention(thin) (@owned @box Int) -> () { func testNoescape2() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. This also checks for when the outer closure captures it // in a way that could be used with escape: the union of the two requirements // doesn't allow a by-address capture. var a = 0 noescapefunc { escapefunc { a = 42 } markUsed(a) } markUsed(a) } // CHECK-LABEL: sil hidden @_TF9functions13testNoescape2FT_T_ : $@convention(thin) () -> () { // CHECK: // functions.(testNoescape2 () -> ()).(closure #1) // CHECK-NEXT: sil shared @_TFF9functions13testNoescape2FT_T_U_FT_T_ : $@convention(thin) (@owned @box Int) -> () { // CHECK: // functions.(testNoescape2 () -> ()).(closure #1).(closure #1) // CHECK-NEXT: sil shared @_TFFF9functions13testNoescape2FT_T_U_FT_T_U_FT_T_ : $@convention(thin) (@owned @box Int) -> () { enum PartialApplyEnumPayload<T, U> { case Left(T) case Right(U) } struct S {} struct C {} func partialApplyEnumCases(_ x: S, y: C) { let left = PartialApplyEnumPayload<S, C>.Left let left2 = left(S()) let right = PartialApplyEnumPayload<S, C>.Right let right2 = right(C()) } // CHECK-LABEL: sil shared [transparent] [thunk] @_TFO9functions23PartialApplyEnumPayload4Left{{.*}} // CHECK: [[UNCURRIED:%.*]] = function_ref @_TFO9functions23PartialApplyEnumPayload4Left{{.*}} // CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0) // CHECK: return [[CLOSURE]] // CHECK-LABEL: sil shared [transparent] [thunk] @_TFO9functions23PartialApplyEnumPayload5Right{{.*}} // CHECK: [[UNCURRIED:%.*]] = function_ref @_TFO9functions23PartialApplyEnumPayload5Right{{.*}} // CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0) // CHECK: return [[CLOSURE]]
2f190c6cb33423d0fc62470f528dd3d3
43.313402
298
0.61502
false
false
false
false
wayfair/brickkit-ios
refs/heads/master
Tests/Layout/BrickInvalidationContextTests.swift
apache-2.0
1
// // BrickInvalidationContextTests.swift // BrickKit // // Created by Ruben Cagnie on 9/17/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import XCTest @testable import BrickKit class BrickInvalidationContextTests: XCTestCase { var brickViewController: BrickViewController! var width:CGFloat! override func setUp() { super.setUp() // continueAfterFailure = false brickViewController = BrickViewController() width = brickViewController.view.frame.width } func testDescription() { let context = BrickLayoutInvalidationContext(type: .creation) XCTAssertEqual(context.description, "BrickLayoutInvalidationContext of type: creation") } func testInvalidateHeightFirstAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), DummyBrick("Brick 3", height: .fixed(size: 50)), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 100), CGRect(x: 0, y: 100, width: width, height: 50), CGRect(x: 0, y: 150, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightSecondAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), DummyBrick("Brick 3", height: .fixed(size: 50)), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 1, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 100), CGRect(x: 0, y: 150, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightThirdAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), DummyBrick("Brick 3", height: .fixed(size: 50)), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 2, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 50), CGRect(x: 0, y: 100, width: width, height: 100), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithSectionsFirstAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 2), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 100), CGRect(x: 0, y: 100, width: width, height: 100), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 100), ], 3 : [ CGRect(x: 0, y: 100, width: width, height: 50), CGRect(x: 0, y: 150, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 150, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithSectionsSecondAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 3), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 150), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 50, width: width, height: 100), CGRect(x: 0, y: 150, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 150, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithSectionsThirdAttribute() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 4), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 150), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 50, width: width, height: 50), CGRect(x: 0, y: 100, width: width, height: 100), ], 4: [ CGRect(x: 0, y: 100, width: width, height: 100), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithNestedSections() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 4), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 150), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 50, width: width, height: 100), CGRect(x: 0, y: 150, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 50, width: width, height: 100), ], 5: [ CGRect(x: 0, y: 150, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithNestedSectionsMultiBricks() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 4", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 2), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 250), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 150), CGRect(x: 0, y: 150, width: width, height: 100), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 100), CGRect(x: 0, y: 100, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 150, width: width, height: 50), CGRect(x: 0, y: 200, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 150, width: width, height: 50), ], 5: [ CGRect(x: 0, y: 200, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 250)) } func testInvalidateHeightWithNestedSectionsMultiBricksZeroHeight() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 4", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 2), newHeight: 0)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 100), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 100), ], 3 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 0, width: width, height: 50), ], 5: [ CGRect(x: 0, y: 50, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 100)) } func testInvalidateHeightButSameHeight() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", width: .ratio(ratio: 1/2), height: .fixed(size: 50)), DummyBrick("Brick 1", width: .ratio(ratio: 1/2), height: .fixed(size: 25)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 1, section: 2), newHeight: 50)) brickViewController.layout.invalidateLayout(with: context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 150), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 100), ], 2 : [ CGRect(x: 0, y: 0, width: width / 2, height: 50), CGRect(x: width / 2, y: 0, width: width / 2, height: 50), ], 3 : [ CGRect(x: 0, y: 50, width: width, height: 50), CGRect(x: 0, y: 100, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 50, width: width, height: 50), ], 5: [ CGRect(x: 0, y: 100, width: width, height: 50), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 150)) } func testInvalidateHeightWithHideBrickBehavior() { let hideBehaviorDataSource = FixedHideBehaviorDataSource(indexPaths: []) brickViewController.brickCollectionView.layout.hideBehaviorDataSource = hideBehaviorDataSource brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 4", height: .fixed(size: 50)), ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() // Hide a brick hideBehaviorDataSource.indexPaths.append(IndexPath(item: 0, section: 2)) var context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) var expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 150), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 100), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 50, width: width, height: 50), CGRect(x: 0, y: 100, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 50, width: width, height: 50), ], 5: [ CGRect(x: 0, y: 100, width: width, height: 50), ] ] var attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 150)) // Show a brick hideBehaviorDataSource.indexPaths.removeAll() context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 100), CGRect(x: 0, y: 100, width: width, height: 100), ], 2 : [ CGRect(x: 0, y: 0, width: width, height: 50), CGRect(x: 0, y: 50, width: width, height: 50), ], 3 : [ CGRect(x: 0, y: 100, width: width, height: 50), CGRect(x: 0, y: 150, width: width, height: 50), ], 4: [ CGRect(x: 0, y: 100, width: width, height: 50), ], 5: [ CGRect(x: 0, y: 150, width: width, height: 50), ] ] attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testInvalidateHeightWithHideSectionBehavior() { let hideBehaviorDataSource = FixedHideBehaviorDataSource(indexPaths: []) brickViewController.brickCollectionView.layout.hideBehaviorDataSource = hideBehaviorDataSource brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), ]), BrickSection("Section 2", bricks: [ BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick 4", height: .fixed(size: 50)), ]) ]), ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)) brickViewController.setSection(section) // Hide a section brickViewController.collectionView!.layoutSubviews() hideBehaviorDataSource.indexPaths.append(IndexPath(item: 0, section: 1)) var context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) var expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 120), ], 1 : [ CGRect(x: 10, y: 10, width: width - 20, height: 100), ], 3 : [ CGRect(x: 10, y: 10, width: width - 20, height: 50), CGRect(x: 10, y: 60, width: width - 20, height: 50), ], 4: [ CGRect(x: 10, y: 10, width: width - 20, height: 50), ], 5: [ CGRect(x: 10, y: 60, width: width - 20, height: 50), ] ] var attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 120)) // Unhide a section hideBehaviorDataSource.indexPaths.removeAll() context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) /* Actual: [ 0: [(0.0, 0.0, 320.0, 230.0)], 1: [(10.0, 10.0, 300.0, 100.0), (10.0, 120.0, 300.0, 100.0)], 2: [(10.0, 60.0, 300.0, 50.0), (10.0, 10.0, 300.0, 50.0)], 3: [(10.0, 170.0, 300.0, 50.0), (10.0, 120.0, 300.0, 50.0)]] 4: [(10.0, 120.0, 300.0, 50.0)], 5: [(10.0, 170.0, 300.0, 50.0)], */ expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 230), ], 1 : [ CGRect(x: 10, y: 10, width: width - 20, height: 100), CGRect(x: 10, y: 120, width: width - 20, height: 100), ], 2 : [ CGRect(x: 10, y: 10, width: width - 20, height: 50), CGRect(x: 10, y: 60, width: width - 20, height: 50), ], 3 : [ CGRect(x: 10, y: 120, width: width - 20, height: 50), CGRect(x: 10, y: 170, width: width - 20, height: 50), ], 4: [ CGRect(x: 10, y: 120, width: width - 20, height: 50), ], 5: [ CGRect(x: 10, y: 170, width: width - 20, height: 50), ] ] attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 230)) } func testInvalidateHeightWithHideBrickBehaviorBrickInSection() { let hideBehaviorDataSource = FixedHideBehaviorDataSource(indexPaths: []) brickViewController.brickCollectionView.layout.hideBehaviorDataSource = hideBehaviorDataSource brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)), BrickSection("Section 2", bricks: [ DummyBrick("Brick 2", height: .fixed(size: 50)), ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)), BrickSection("Section 3", bricks: [ DummyBrick("Brick 3", height: .fixed(size: 50)), ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)), BrickSection("Section 4", bricks: [ DummyBrick("Brick 4", height: .fixed(size: 50)), ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() // Show a brick var context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) /* 0: [(0.0, 0.0, 320.0, 280.0)], 1: [(0.0, 210.0, 320.0, 70.0), (0.0, 0.0, 320.0, 70.0), (0.0, 140.0, 320.0, 70.0), (0.0, 70.0, 320.0, 70.0)]] 2: [(10.0, 10.0, 300.0, 50.0)], 3: [(10.0, 80.0, 300.0, 50.0)], 4: [(10.0, 150.0, 300.0, 50.0)], 5: [(10.0, 220.0, 300.0, 50.0)], */ var expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 280), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 70), CGRect(x: 0, y: 70, width: width, height: 70), CGRect(x: 0, y: 140, width: width, height: 70), CGRect(x: 0, y: 210, width: width, height: 70), ], 2 : [ CGRect(x: 10, y: 10, width: width - 20, height: 50), ], 3 : [ CGRect(x: 10, y: 80, width: width - 20, height: 50), ], 4 : [ CGRect(x: 10, y: 150, width: width - 20, height: 50), ], 5 : [ CGRect(x: 10, y: 220, width: width - 20, height: 50), ], ] var attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 280)) // Hide a brick hideBehaviorDataSource.indexPaths = [IndexPath(item: 0, section: 2), IndexPath(item: 0, section: 3)] context = BrickLayoutInvalidationContext(type: .updateVisibility) brickViewController.layout.invalidateLayout(with: context) expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 140), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 70), CGRect(x: 0, y: 70, width: width, height: 70), ], 4: [ CGRect(x: 10, y: 10, width: width - 20, height: 50), ], 5: [ CGRect(x: 10, y: 80, width: width - 20, height: 50), ] ] attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 140)) } func testHideBrickBehaviorMultipleBrickSections() { let hideBehaviorDataSource = FixedHideBehaviorDataSource(indexPaths: [IndexPath(item: 0, section: 1), IndexPath(item: 1, section: 1)]) brickViewController.brickCollectionView.layout.hideBehaviorDataSource = hideBehaviorDataSource brickViewController.brickCollectionView.registerNib(UINib(nibName: "DummyBrick100", bundle: Bundle(for: DummyBrick.self)), forBrickWithIdentifier: "Brick") let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick") ]), BrickSection("Section 2", bricks: [ DummyBrick("Brick") ]), BrickSection("Section 3", bricks: [ DummyBrick("Brick") ]), BrickSection("Section 4", bricks: [ DummyBrick("Brick") ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() // let context = BrickLayoutInvalidationContext(type: .UpdateVisibility) // brickViewController.layout.invalidateLayoutWithContext(context) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 200), ], 1 : [ CGRect(x: 0, y: 0, width: width, height: 100), CGRect(x: 0, y: 100, width: width, height: 100), ], 4 : [ CGRect(x: 0, y: 0, width: width, height: 100), ], 5 : [ CGRect(x: 0, y: 100, width: width, height: 100), ], ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 200)) } func testHideBrickBehaviorMultipleBrickNestedSections() { brickViewController.brickCollectionView.registerNib(UINib(nibName: "DummyBrick100", bundle: Bundle(for: DummyBrick.self)), forBrickWithIdentifier: "Brick") let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick"), BrickSection("Section 2", bricks: [ DummyBrick("Brick") ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() let hideBehaviorDataSource = FixedHideBehaviorDataSource(indexPaths: []) hideBehaviorDataSource.indexPaths = [IndexPath(item: 0, section: 1)] brickViewController.brickCollectionView.layout.hideBehaviorDataSource = hideBehaviorDataSource brickViewController.brickCollectionView.invalidateVisibility() let expectedResult: [Int: [CGRect]] = [:] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 0)) } func testHideBrickBehaviorMultipleBrickNestedSectionsWithHidden() { brickViewController.brickCollectionView.registerNib(UINib(nibName: "DummyBrick100", bundle: Bundle(for: DummyBrick.self)), forBrickWithIdentifier: "Brick") let section = BrickSection("Test Section", bricks: [ BrickSection("Section 1", bricks: [ DummyBrick("Brick"), BrickSection("Section 2", bricks: [ DummyBrick("Brick") ]) ]), ]) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() section.bricks[0].isHidden = true brickViewController.brickCollectionView.invalidateVisibility() let expectedResult: [Int: [CGRect]] = [:] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 0)) } func testWrongCollectionView() { let context = BrickLayoutInvalidationContext(type: .updateVisibility) XCTAssertFalse(context.invalidateWithLayout(UICollectionViewFlowLayout())) } func testThatInvalidateWithAlignRowHeightsReportsCorrectly() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ DummyBrick("Brick 1", width: .ratio(ratio: 1/2), height: .fixed(size: 50)), DummyBrick("Brick 2", width: .ratio(ratio: 1/2), height: .fixed(size: 50)), ], alignRowHeights: true) brickViewController.setSection(section) brickViewController.collectionView!.layoutSubviews() section.bricks[1].height = .fixed(size: 100) let context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 1, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) brickViewController.brickCollectionView.layoutIfNeeded() let cell = brickViewController.brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) XCTAssertEqual(cell?.frame, CGRect(x: 0, y: 0, width: width/2, height: 100)) let expectedResult = [ 0 : [ CGRect(x: 0, y: 0, width: width, height: 100), ], 1 : [ CGRect(x: 0, y: 0, width: width/2, height: 100), CGRect(x: width/2, y: 0, width: width/2, height: 100), ] ] let attributes = brickViewController.collectionViewLayout.layoutAttributesForElements(in: CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: width * 2))) XCTAssertNotNil(attributes) XCTAssertTrue(verifyAttributesToExpectedResult(attributes!, expectedResult: expectedResult)) XCTAssertEqual(brickViewController.collectionViewLayout.collectionViewContentSize, CGSize(width: width, height: 100)) } func testThatContentOffsetAdjustmentIsUpdatedWhenTopBrickUpdates() { brickViewController.brickCollectionView.registerBrickClass(DummyBrick.self) let section = BrickSection("Test Section", bricks: [ DummyBrick("Brick 1", height: .fixed(size: 50)), DummyBrick("Brick 2", height: .fixed(size: 50)), DummyBrick("Brick 3", height: .fixed(size: 1000)), ]) brickViewController.brickCollectionView.setupSectionAndLayout(section) section.bricks[0].height = .fixed(size: 100) var context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) XCTAssertEqual(context.contentOffsetAdjustment, CGPoint(x: 0, y: 0)) brickViewController.brickCollectionView.layoutIfNeeded() XCTAssertEqual(brickViewController.brickCollectionView.contentOffset.y, 0) brickViewController.brickCollectionView.contentOffset.y = 100 section.bricks[0].height = .fixed(size: 150) context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 1), newHeight: 150)) brickViewController.layout.invalidateLayout(with: context) XCTAssertEqual(context.contentOffsetAdjustment, CGPoint(x: 0, y: 50)) brickViewController.brickCollectionView.layoutIfNeeded() #if os(iOS) // On tvOS this check fails XCTAssertEqual(brickViewController.brickCollectionView.contentOffset.y, 150) #endif section.bricks[0].height = .fixed(size: 100) context = BrickLayoutInvalidationContext(type: .updateHeight(indexPath: IndexPath(item: 0, section: 1), newHeight: 100)) brickViewController.layout.invalidateLayout(with: context) XCTAssertEqual(context.contentOffsetAdjustment, CGPoint(x: 0, y: -50)) brickViewController.brickCollectionView.layoutIfNeeded() #if os(iOS) // On tvOS this check fails XCTAssertEqual(brickViewController.brickCollectionView.contentOffset.y, 100) #endif } }
c93a1d88056f8ef197161f49d22c69c2
41.631951
174
0.588525
false
true
false
false
nikita-leonov/boss-client
refs/heads/master
BoSS/Services/RACSignal+Mappings.swift
mit
1
// // RACSignal+Mappings.swift // BoSS // // Created by Emanuele Rudel on 28/02/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import ObjectMapper extension RACSignal { internal func mapResponses<T: Mappable>(closure: ([T]) -> AnyObject) -> RACSignal { return map { (next) -> AnyObject! in var result = [T]() if let responses = next as? [AnyObject] { var mapper = Mapper<T>() for response in responses { if let mappedObject = mapper.map(response) { result.append(mappedObject) } } } return closure(result) } } internal func subscribeNextAs<T>(closure: (T -> Void)) -> RACDisposable { return subscribeNext { (next: AnyObject!) in _ = RACSignal.convertNextAndCallClosure(next, closure: closure) } } private class func convertNextAndCallClosure<T,U>(next: AnyObject!, closure: ((T) -> U)) -> U { var result: U if let nextAsT = next as? T { result = closure(nextAsT) } else { assertionFailure("Unexpected type \(T.self) for \(next) in \(__FUNCTION__)") } return result } }
bfb49131eff26ce2ee79c5bafe396f7b
27.354167
99
0.517647
false
false
false
false
aipeople/PokeIV
refs/heads/master
Pods/ProtocolBuffers-Swift/Source/WireFormat.swift
gpl-3.0
1
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 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 Foundation let LITTLE_ENDIAN_32_SIZE:Int32 = 4 let LITTLE_ENDIAN_64_SIZE:Int32 = 8 public enum WireFormatMessage:Int32 { case SetItem = 1 case SetTypeId = 2 case SetMessage = 3 } public enum WireFormat:Int32 { case Varint = 0 case Fixed64 = 1 case LengthDelimited = 2 case StartGroup = 3 case EndGroup = 4 case Fixed32 = 5 case TagTypeMask = 7 public func makeTag(fieldNumber:Int32) -> Int32 { let res:Int32 = fieldNumber << StartGroup.rawValue return res | self.rawValue } public static func getTagWireType(tag:Int32) -> Int32 { return tag & WireFormat.TagTypeMask.rawValue } public static func getTagFieldNumber(tag:Int32) -> Int32 { return WireFormat.logicalRightShift32(value: tag ,spaces: StartGroup.rawValue) } ///Utilities public static func convertTypes<Type, ReturnType>(convertValue value:Type, defaultValue:ReturnType) -> ReturnType { var retValue = defaultValue var curValue = value memcpy(&retValue, &curValue, sizeof(Type)) return retValue } public static func logicalRightShift32(value aValue:Int32, spaces aSpaces:Int32) ->Int32 { var result:UInt32 = 0 result = convertTypes(convertValue: aValue, defaultValue: result) let bytes:UInt32 = (result >> UInt32(aSpaces)) var res:Int32 = 0 res = convertTypes(convertValue: bytes, defaultValue: res) return res } public static func logicalRightShift64(value aValue:Int64, spaces aSpaces:Int64) ->Int64 { var result:UInt64 = 0 result = convertTypes(convertValue: aValue, defaultValue: result) let bytes:UInt64 = (result >> UInt64(aSpaces)) var res:Int64 = 0 res = convertTypes(convertValue: bytes, defaultValue: res) return res } public static func decodeZigZag32(n:Int32) -> Int32 { return logicalRightShift32(value: n, spaces: 1) ^ -(n & 1) } public static func encodeZigZag32(n:Int32) -> Int32 { return (n << 1) ^ (n >> 31) } public static func decodeZigZag64(n:Int64) -> Int64 { return logicalRightShift64(value: n, spaces: 1) ^ -(n & 1) } public static func encodeZigZag64(n:Int64) -> Int64 { return (n << 1) ^ (n >> 63) } } public extension Int32 { func computeSFixed32SizeNoTag() ->Int32 { return LITTLE_ENDIAN_32_SIZE } func computeInt32SizeNoTag() -> Int32 { if (self >= 0) { return computeRawVarint32Size() } else { return 10 } } func computeRawVarint32Size() -> Int32 { if ((self & (0xfffffff << 7)) == 0) { return 1 } if ((self & (0xfffffff << 14)) == 0) { return 2 } if ((self & (0xfffffff << 21)) == 0) { return 3 } if ((self & (0xfffffff << 28)) == 0) { return 4 } return 5 } func computeTagSize() ->Int32 { return WireFormat.Varint.makeTag(self).computeRawVarint32Size() } func computeEnumSizeNoTag() -> Int32 { return self.computeRawVarint32Size() } func computeSInt32SizeNoTag() -> Int32 { return WireFormat.encodeZigZag32(self).computeRawVarint32Size() } func computeInt32Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeInt32SizeNoTag() } func computeEnumSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeEnumSizeNoTag() } func computeSFixed32Size(fieldNumber:Int32) -> Int32 { return fieldNumber.computeTagSize() + computeSFixed32SizeNoTag() } func computeSInt32Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeSInt32SizeNoTag() } } public extension Int64 { func computeInt64SizeNoTag() -> Int32 { return computeRawVarint64Size() } func computeRawVarint64Size() -> Int32 { if ((self & (0xfffffffffffffff << 7)) == 0){return 1} if ((self & (0xfffffffffffffff << 14)) == 0){return 2} if ((self & (0xfffffffffffffff << 21)) == 0){return 3} if ((self & (0xfffffffffffffff << 28)) == 0){return 4} if ((self & (0xfffffffffffffff << 35)) == 0){return 5} if ((self & (0xfffffffffffffff << 42)) == 0){return 6} if ((self & (0xfffffffffffffff << 49)) == 0){return 7} if ((self & (0xfffffffffffffff << 56)) == 0){return 8} if ((self & (0xfffffffffffffff << 63)) == 0){return 9} return 10 } func computeSInt64SizeNoTag() -> Int32 { return WireFormat.encodeZigZag64(self).computeRawVarint64Size() } func computeInt64Size(fieldNumber:Int32) -> Int32 { return fieldNumber.computeTagSize() + computeInt64SizeNoTag() } func computeSFixed64SizeNoTag() -> Int32 { return LITTLE_ENDIAN_64_SIZE } func computeSFixed64Size(fieldNumber:Int32) -> Int32 { return fieldNumber.computeTagSize() + computeSFixed64SizeNoTag() } func computeSInt64Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + WireFormat.encodeZigZag64(self).computeRawVarint64Size() } } public extension Double { func computeDoubleSizeNoTag() ->Int32 { return LITTLE_ENDIAN_64_SIZE } func computeDoubleSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + self.computeDoubleSizeNoTag() } } public extension Float { func computeFloatSizeNoTag() ->Int32 { return LITTLE_ENDIAN_32_SIZE } func computeFloatSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + self.computeFloatSizeNoTag() } } public extension UInt64 { func computeFixed64SizeNoTag() ->Int32 { return LITTLE_ENDIAN_64_SIZE } func computeUInt64SizeNoTag() -> Int32 { var retvalue:Int64 = 0 retvalue = WireFormat.convertTypes(convertValue: self, defaultValue:retvalue) return retvalue.computeRawVarint64Size() } func computeUInt64Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeUInt64SizeNoTag() } func computeFixed64Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeFixed64SizeNoTag() } } public extension UInt32 { func computeFixed32SizeNoTag() ->Int32 { return LITTLE_ENDIAN_32_SIZE } func computeUInt32SizeNoTag() -> Int32 { var retvalue:Int32 = 0 retvalue = WireFormat.convertTypes(convertValue: self, defaultValue: retvalue) return retvalue.computeRawVarint32Size() } func computeFixed32Size(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeFixed32SizeNoTag() } func computeUInt32Size(fieldNumber:Int32) -> Int32 { return fieldNumber.computeTagSize() + computeUInt32SizeNoTag() } } public extension Bool { func computeBoolSizeNoTag() -> Int32 { return 1 } func computeBoolSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeBoolSizeNoTag() } } public extension String { func computeStringSizeNoTag() -> Int32 { let length:UInt32 = UInt32(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) return Int32(length).computeRawVarint32Size() + Int32(length) } func computeStringSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeStringSizeNoTag() } func utf8ToNSData()-> NSData { let bytes = [UInt8]() + self.utf8 let data = NSData(bytes: bytes, length:bytes.count) return data } } public extension AbstractMessage { func computeGroupSizeNoTag() -> Int32 { return self.serializedSize() } func computeMessageSizeNoTag() ->Int32 { let size:Int32 = self.serializedSize() return size.computeRawVarint32Size() + size } func computeGroupSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() * 2 + computeGroupSizeNoTag() } func computeMessageSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() + computeMessageSizeNoTag() } func computeMessageSetExtensionSize(fieldNumber:Int32) -> Int32 { return WireFormatMessage.SetItem.rawValue.computeTagSize() * 2 + UInt32(fieldNumber).computeUInt32Size(WireFormatMessage.SetTypeId.rawValue) + computeMessageSize(WireFormatMessage.SetMessage.rawValue) } } public extension NSData { func computeDataSizeNoTag() -> Int32 { return Int32(self.length).computeRawVarint32Size() + Int32(self.length) } func computeDataSize(fieldNumber:Int32) -> Int32 { return fieldNumber.computeTagSize() + computeDataSizeNoTag() } func computeRawMessageSetExtensionSize(fieldNumber:Int32) -> Int32 { return WireFormatMessage.SetItem.rawValue.computeTagSize() * 2 + UInt32(fieldNumber).computeUInt32Size(WireFormatMessage.SetTypeId.rawValue) + computeDataSize(WireFormatMessage.SetMessage.rawValue) } } public extension UnknownFieldSet { func computeUnknownGroupSizeNoTag() ->Int32 { return serializedSize() } func computeUnknownGroupSize(fieldNumber:Int32) ->Int32 { return fieldNumber.computeTagSize() * 2 + computeUnknownGroupSizeNoTag() } }
3d43040bac8845adc13c9c6f7446e431
25.432161
208
0.635266
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/SpriteFrame.swift
apache-2.0
1
// // SpriteFrame.swift // // Created by Andrey Volodin on 23.07.16. // Copyright © 2016. All rights reserved. // import SwiftMath /** A SpriteFrame contains the texture and rectangle of the texture to be used by a Sprite. You can easily modify the sprite frame of a Sprite using the following handy method: let frame = SpriteFrame.with(imageName: "jump.png") sprite.spriteFrame = frame */ public final class SpriteFrame { /// @name Creating a Sprite Frame /** * Create and return a sprite frame object from the specified image name. On first attempt it will check the internal texture/frame cache * and if not available will then try and create the frame from an image file of the same name. * * @param imageName Image name. * * @return The SpriteFrame Object. */ public static func with(imageName: String) -> SpriteFrame! { return SpriteFrameCache.shared.spriteFrame(by: imageName) } /** * Initializes and returns a sprite frame object from the specified texture, texture rectangle, rotation status, offset and originalSize values. * * @param texture Texture to use. * @param rect Texture rectangle (in points) to use. * @param rotated Is rectangle rotated? * @param trimOffset Offset (in points) to use. * @param untrimmedSize Original size (in points) before being trimmed. * * @return An initialized SpriteFrame Object. * @see Texture */ public init(texture: Texture!, rect: Rect, rotated: Bool, trimOffset: Point, untrimmedSize: Size) { self._texture = texture self.rect = rect self.trimOffset = trimOffset self.untrimmedSize = untrimmedSize self.rotated = rotated } /** Texture used by the frame. @see Texture */ public var texture: Texture { return _texture ?? lazyTexture } internal var _texture: Texture? /** Texture image file name used to create the texture. Set by the sprite frame cache */ internal(set) public var textureFilename: String = "" { didSet { // Make sure any previously loaded texture is cleared. self._texture = nil self._lazyTexture = nil } } internal var lazyTexture: Texture { if _lazyTexture == nil && textureFilename != "" { _lazyTexture = TextureCache.shared.addImage(from: textureFilename) _texture = _lazyTexture } return texture } private var _lazyTexture: Texture? /** Rectangle of the frame within the texture, in points. */ public var rect: Rect /** If YES, the frame rectangle is rotated. */ public var rotated: Bool /** To save space in a spritesheet, the transparent edges of a frame may be trimmed. This is the original size in points of a frame before it was trimmed. */ public var untrimmedSize: Size /** To save space in a spritesheet, the transparent edges of a frame may be trimmed. This is offset of the sprite caused by trimming in points. */ public var trimOffset: Point public var description: String { return "<SpriteFrame: Texture=\(textureFilename), Rect = \(rect.description)> rotated:\(rotated) offset=\(trimOffset.description))" } /** Purge all unused spriteframes from the cache. */ public static func purgeCache() { SpriteFrameCache.shared.removeUnusedSpriteFrames() } }
5266b6fe587fcbe285513447e7c81fc7
34.734694
161
0.653341
false
false
false
false
CodaFi/swift
refs/heads/main
test/ClangImporter/MixedSource/mixed-target-using-header.swift
apache-2.0
13
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../Inputs/custom-modules -enable-objc-interop -import-objc-header %S/Inputs/mixed-target/header.h -typecheck -primary-file %s %S/Inputs/mixed-target/other-file.swift -disable-objc-attr-requires-foundation-module -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../Inputs/custom-modules -enable-objc-interop -import-objc-header %S/Inputs/mixed-target/header.h -emit-sil -primary-file %s %S/Inputs/mixed-target/other-file.swift -disable-objc-attr-requires-foundation-module -o /dev/null -D SILGEN func test(_ foo : FooProto) { _ = foo.bar as CInt _ = ExternIntX.x as CInt } @objc class ForwardClass : NSObject { } @objc protocol ForwardProto : NSObjectProtocol { } @objc class ForwardProtoAdopter : NSObject, ForwardProto { } @objc class PartialBaseClass { } @objc class PartialSubClass : NSObject { } func testCFunction() { doSomething(ForwardClass()) doSomethingProto(ForwardProtoAdopter()) doSomethingPartialBase(PartialBaseClass()) doSomethingPartialSub(PartialSubClass()) } class ProtoConformer : ForwardClassUser { @objc func consumeForwardClass(_ arg: ForwardClass) {} @objc var forward = ForwardClass() } func testProtocolWrapper(_ conformer: ForwardClassUser) { conformer.consumeForwardClass(conformer.forward) } func useProtocolWrapper() { testProtocolWrapper(ProtoConformer()) } func testStruct(_ p: Point2D) -> Point2D { var result = p result.y += 5 return result } #if !SILGEN func testSuppressed() { let _: __int128_t? = nil // expected-error{{cannot find type '__int128_t' in scope}} } #endif func testMacro() { _ = CONSTANT as CInt } func testFoundationOverlay() { _ = NSUTF8StringEncoding // no ambiguity _ = NSUTF8StringEncoding as UInt // and we should get the overlay version } #if !SILGEN func testProtocolNamingConflict() { let a: ConflictingName1? var b: ConflictingName1Protocol? b = a // expected-error {{cannot assign value of type 'ConflictingName1?' to type 'ConflictingName1Protocol?'}} _ = b let c: ConflictingName2? var d: ConflictingName2Protocol? d = c // expected-error {{cannot assign value of type 'ConflictingName2?' to type 'ConflictingName2Protocol?'}} _ = d } func testObjCGenerics() { _ = GenericObjCClass<ForwardProtoAdopter>() _ = GenericObjCClass<Base>() // expected-error {{type 'Base' does not conform to protocol 'ForwardProto'}} } #endif func testDeclsNestedInObjCContainers() { let _: NameInInterface = 0 let _: NameInProtocol = 0 let _: NameInCategory = 0 } func testReleaseClassWhoseMembersAreNeverLoaded( obj: ClassThatHasAProtocolTypedPropertyButMembersAreNeverLoaded) {}
3d58598fa3279fd20be65c897a822f70
29
301
0.738519
false
true
false
false
litt1e-p/LPScrollFullScreen-swift
refs/heads/master
LPScrollFullScreen-swiftSample/LPScrollFullScreen-swift/TableView2Controller.swift
mit
1
// // TableView2Controller.swift // LPScrollFullScreen-swift // // Created by litt1e-p on 16/9/5. // Copyright © 2016年 litt1e-p. All rights reserved. // import UIKit class TableView2Controller: UIViewController, UITableViewDelegate, UITableViewDataSource { var scrollProxy: LPScrollFullScreen? override func viewDidLoad() { super.viewDidLoad() title = "TableView base on code" view.addSubview(tableView) scrollProxy = LPScrollFullScreen(forwardTarget: self) tableView.delegate = scrollProxy tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: String(TableView2Controller)) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) showTabBar(false) showNavigationBar(false) showToolbar(false) } private lazy var tableView: UITableView = { let tb = UITableView(frame: self.view.bounds) return tb } () func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { navigationController?.pushViewController(ViewController(), animated: true) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 40 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(String(TableView2Controller), forIndexPath: indexPath) cell.textLabel?.text = "\(indexPath.row)" return cell } }
443e68eb993d891541252a13a4740cda
31.050847
134
0.693284
false
false
false
false
DanielFulton/ImageLibraryTests
refs/heads/master
Pods/Nuke/Sources/ImageRequestKey.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Foundation /// Compares keys for equivalence. public protocol ImageRequestKeyOwner: class { /// Compares keys for equivalence. This method is called only if two keys have the same owner. func isEqual(lhs: ImageRequestKey, to rhs: ImageRequestKey) -> Bool } /// Makes it possible to use ImageRequest as a key in dictionaries. public final class ImageRequestKey: NSObject { /// Request that the receiver was initailized with. public let request: ImageRequest /// Owner of the receiver. public weak private(set) var owner: ImageRequestKeyOwner? /// Initializes the receiver with a given request and owner. public init(_ request: ImageRequest, owner: ImageRequestKeyOwner) { self.request = request self.owner = owner } /// Returns hash from the NSURL from image request. public override var hash: Int { return request.URLRequest.URL?.hashValue ?? 0 } /// Compares two keys for equivalence if the belong to the same owner. public override func isEqual(other: AnyObject?) -> Bool { guard let other = other as? ImageRequestKey else { return false } guard let owner = owner where owner === other.owner else { return false } return owner.isEqual(self, to: other) } }
5df336e2f0c176713525d132f520bc7e
32.547619
98
0.677076
false
false
false
false
syncloud/ios
refs/heads/master
Syncloud/DnsSelectorController.swift
gpl-3.0
1
import Foundation import UIKit class DnsSelectorController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var pickerDns: UIPickerView! init() { super.init(nibName: "DnsSelector", bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var pickerDomainComponent = 0 var domainsValues: [String] = [String]() var domainsTitles: [String] = [String]() var mainDomain: String = Storage.getMainDomain() override func viewDidLoad() { super.viewDidLoad() self.title = "Server" let viewController = self.navigationController!.visibleViewController! let btnSave = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(DnsSelectorController.btnSaveClick(_:))) let btnCancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(DnsSelectorController.btnCancelClick(_:))) viewController.navigationItem.rightBarButtonItem = btnSave viewController.navigationItem.leftBarButtonItem = btnCancel self.domainsValues = ["syncloud.it", "syncloud.info"] self.domainsTitles = ["Production: syncloud.it", "Testing: syncloud.info"] self.mainDomain = Storage.getMainDomain() self.pickerDns.selectRow(domainsValues.firstIndex(of: self.mainDomain)!, inComponent: self.pickerDomainComponent, animated: false) } override func viewWillAppear(_ animated: Bool) { self.navigationController!.setNavigationBarHidden(false, animated: animated) self.navigationController!.setToolbarHidden(true, animated: animated) super.viewWillAppear(animated) } @objc func btnSaveClick(_ sender: UIBarButtonItem) { let newMainDomain = self.domainsValues[self.pickerDns.selectedRow(inComponent: self.pickerDomainComponent)] Storage.setMainDomain(newMainDomain) self.navigationController!.popViewController(animated: true) } @objc func btnCancelClick(_ sender: UIBarButtonItem) { self.navigationController!.popViewController(animated: true) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.domainsValues.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.domainsTitles[row] } }
9481e66719c5bd3826877c21edad3846
36.73913
144
0.703533
false
false
false
false
liuguya/TestKitchen_1606
refs/heads/master
TestKitchen/TestKitchen/classes/common/BaseViewController.swift
mit
1
// // BaseViewController.swift // TestKitchen // // Created by 阳阳 on 16/8/15. // Copyright © 2016年 liuguyang. All rights reserved. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //导航标题 func addNavTitle(title:String?){ let titleLabel = UILabel.createLabel(title, font: UIFont.systemFontOfSize(24), textAlignment: .Center, textColor: UIColor.blackColor()) navigationItem.titleView = titleLabel } //导航按钮 func addNavBtn(imageName:String,target:AnyObject?,action:Selector,isLeft:Bool){ let btn = UIButton.createButton(nil, bgImageName: imageName, selectBgImageName: nil, target: target, action: action) btn.frame = CGRectMake(0, 4, 30, 30) let barItem = UIBarButtonItem(customView: btn) if isLeft { navigationItem.leftBarButtonItem = barItem }else{ navigationItem.rightBarButtonItem = barItem } } func addNavBackBtn(){ addNavBtn("nav_back_black", target: self, action: #selector(backAction), isLeft: true) } func backAction(){ navigationController?.popViewControllerAnimated(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. } */ }
9d040c1888fe33804ff2b9420fde54d4
28.0625
143
0.653763
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/CharData.swift
mit
1
// // CharData.swift // TranslationEditor // // Created by Mikko Hilpinen on 29.9.2016. // Copyright © 2017 SIL. All rights reserved. // import Foundation // Chardata is used for storing text within a verse or another container. Character data may have specific styling associated with it (quotation, special meaning, etc.) struct CharData: Equatable, USXConvertible, AttributedStringConvertible, JSONConvertible, ExpressibleByStringLiteral { // typealias ExtendedGraphemeClusterLiteralType = StringLiteralType // ATTRIBUTES ---- var style: CharStyle? var text: String // COMP. PROPERTIES -- var properties: [String : PropertyValue] { return [ "style" : (style?.code).value, "text" : text.value] } var toUSX: String { // Empty charData is not recorded in USX if isEmpty { return "" } else if let style = style { return "<char style=\"\(style.code)\">\(text)</char>" } else { return text } } var isEmpty: Bool { return text.isEmpty } // INIT ---- init(text: String, style: CharStyle? = nil) { self.text = text self.style = style } init(stringLiteral value: String) { self.text = value self.style = nil } init(unicodeScalarLiteral value: String) { self.text = value self.style = nil } init(extendedGraphemeClusterLiteral value: String) { self.text = value self.style = nil } static func parse(from propertyData: PropertySet) -> CharData { var style: CharStyle? = nil if let styleValue = propertyData["style"].string { style = CharStyle.of(styleValue) } return CharData(text: propertyData["text"].string(), style: style) } // OPERATORS ---- static func == (left: CharData, right: CharData) -> Bool { return left.text == right.text && left.style == right.style } // CONFORMED --- func toAttributedString(options: [String : Any] = [:]) -> NSAttributedString { // TODO: At some point one may wish to add other types of attributes based on the style let attributes = [CharStyleAttributeName : style as Any] return NSAttributedString(string: text, attributes: attributes) } // OTHER ------ func appended(_ text: String) -> CharData { return CharData(text: self.text + text, style: self.style) } func emptyCopy() -> CharData { return CharData(text: "", style: style) } static func text(of data: [CharData]) -> String { return data.reduce("") { $0 + $1.text } /* var text = "" for charData in data { text.append(charData.text) } return text*/ } static func update(_ first: [CharData], with second: [CharData]) -> [CharData] { var updated = [CharData]() // Updates the text in the first array with the matching style instances in the second array var lastSecondIndex = -1 for oldVersion in first { // Finds the matching version var matchingIndex: Int? for secondIndex in lastSecondIndex + 1 ..< second.count { if second[secondIndex].style == oldVersion.style { matchingIndex = secondIndex break } } // Copies the new text or empties the array if let matchingIndex = matchingIndex { // In case some of the second array data was skipped, adds it in between for i in lastSecondIndex + 1 ..< matchingIndex { updated.add(second[i]) } updated.add(CharData(text: second[matchingIndex].text, style: oldVersion.style)) lastSecondIndex = matchingIndex } else { updated.add(CharData(text: "", style: oldVersion.style)) } } // Makes sure the rest of the second array are included for i in lastSecondIndex + 1 ..< second.count { updated.add(second[i]) } return updated } }
e4f1dc90aac3aed5c9d0f52377c73171
19.752809
168
0.658906
false
false
false
false
ontouchstart/swift3-playground
refs/heads/playgroundbook
Learn to Code 1.playgroundbook/Contents/Sources/SimpleParser.swift
mit
2
// // SimpleParser.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // /* <abstract> A very limited parser which looks for simple language constructs. Known limitations: - Cannot distinguish between functions based on argument labels or parameter type (only name). - Only checks for (func, if, else, else if, for, while) keywords. - Makes no attempt to recover if a parsing error is discovered. </abstract> */ import Foundation enum ParseError: Error { case fail(String) } class SimpleParser { let tokens: [Token] var index = 0 init(tokens: [Token]) { self.tokens = tokens } var currentToken: Token? { guard tokens.indices.contains(index) else { return nil } return tokens[index] } var nextToken: Token? { let nextIndex = tokens.index(after: index) guard nextIndex < tokens.count else { return nil } return tokens[nextIndex] } /// Advances the index, and returns the new current token if any. @discardableResult func advanceToNextToken() -> Token? { index = tokens.index(after: index) return currentToken } /// Converts the `tokens` into `Node`s. func createNodes() throws -> [Node] { var nodes = [Node]() while let token = currentToken { if let node = try parseToken(token) { nodes.append(node) } } return nodes } // MARK: Main Parsers private func parseToken(_ token: Token) throws -> Node? { var node: Node? = nil switch token { case let .keyword(word): node = try parseKeyword(word) case let .identifier(name): if case .delimiter(.openParen)? = advanceToNextToken() { // Ignoring parameters for now. consumeTo(.closingParen) advanceToNextToken() node = CallNode(identifier: name) } else { // This is by no means completely correct, but works for the // kind of information we're trying to glean. node = VariableNode(identifier: name) } case .number(_): // Discard numbers for now. advanceToNextToken() case .delimiter(_): // Discard tokens that don't map to a top level node. advanceToNextToken() } return node } func parseKeyword(_ word: Keyword) throws -> Node { let node: Node // Parse for known keywords. switch word { case .func: node = try parseDefinition() case .if, .else, .elseIf: node = try parseConditionalStatement() case .for, .while: node = try parseLoop() } return node } // MARK: Token Parsers func parseDefinition() throws -> DefinitionNode { guard case .identifier(let funcName)? = advanceToNextToken() else { throw ParseError.fail(#function) } // Ignore any hidden comments (e.g. /*#-end-editable-code*/). consumeTo(.openParen) let argTokens = consumeTo(.closingParen) let args = reduce(argTokens) consumeTo(.openBrace) let body = try parseToClosingBrace() return DefinitionNode(name: funcName, parameters: args, body: body) } func parseConditionalStatement() throws -> Node { guard case .keyword(var type)? = currentToken else { throw ParseError.fail(#function) } // Check if this is a compound "else if" statement. if case .keyword(let subtype)? = nextToken, subtype == .if { type = .elseIf advanceToNextToken() } let conditionTokens = consumeTo(.openBrace) let condition = reduce(conditionTokens) let body = try parseToClosingBrace() return ConditionalStatementNode(type: type, condition: condition, body: body) } func parseLoop() throws -> Node { guard case .keyword(let type)? = currentToken else { throw ParseError.fail(#function) } let conditionTokens = consumeTo(.openBrace) let condition = reduce(conditionTokens) let body = try parseToClosingBrace() return LoopNode(type: type, condition: condition, body: body) } // MARK: Convenience Methods func parseToClosingBrace() throws -> [Node] { var nodes = [Node]() loop: while let token = currentToken { switch token { case .delimiter(.openBrace): advanceToNextToken() // Recurse on opening brace. nodes += try parseToClosingBrace() break loop case .delimiter(.closingBrace): // Complete. advanceToNextToken() break loop default: if let node = try parseToken(token) { nodes.append(node) } } } return nodes } @discardableResult func consumeTo(_ match: Token) -> [Token] { var content = [Token]() while let token = advanceToNextToken() { if token == match { break } content.append(token) } return content } @discardableResult func consumeTo(_ delimiter: Delimiter) -> [Token] { return consumeTo(.delimiter(delimiter)) } func reduce(_ tokens: [Token], separator: String = "") -> String { let contents = tokens.reduce("") { $0 + $1.contents + separator } return contents } }
3f7b25d38dd15eb36ca651cbe038d81e
27.742857
110
0.532969
false
false
false
false
lanjing99/RxSwiftDemo
refs/heads/master
15-intro-to-schedulers/final/Schedulers/Utils.swift
mit
2
/* * Copyright (c) 2014-2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import RxSwift let start = Date() fileprivate func getThreadName() -> String { if Thread.current.isMainThread { return "Main Thread" } else if let name = Thread.current.name { if name == "" { return "Anonymous Thread" } return name } else { return "Unknown Thread" } } fileprivate func secondsElapsed() -> String { return String(format: "%02i", Int(Date().timeIntervalSince(start).rounded())) } extension ObservableType { func dump() -> RxSwift.Observable<Self.E> { return self.do(onNext: { element in let threadName = getThreadName() print("\(secondsElapsed())s | [D] \(element) received on \(threadName)") }) } func dumpingSubscription() -> Disposable { return self.subscribe(onNext: { element in let threadName = getThreadName() print("\(secondsElapsed())s | [S] \(element) received on \(threadName)") }) } }
4663ebc93b3767868edac2f0869e299f
33.644068
80
0.709741
false
false
false
false
boqian2000/swift-algorithm-club
refs/heads/master
Counting Sort/CountingSort.swift
mit
1
// // Sort.swift // test // // Created by Kauserali on 11/04/16. // Copyright © 2016 Ali Hafizji. All rights reserved. // enum CountingSortError: ErrorType { case arrayEmpty } func countingSort(array: [Int]) throws -> [Int] { guard array.count > 0 else { throw CountingSortError.arrayEmpty } // Step 1 // Create an array to store the count of each element let maxElement = array.maxElement() ?? 0 var countArray = [Int](count: Int(maxElement + 1), repeatedValue: 0) for element in array { countArray[element] += 1 } // Step 2 // Set each value to be the sum of the previous two values for index in 1 ..< countArray.count { let sum = countArray[index] + countArray[index - 1] countArray[index] = sum } print(countArray) // Step 3 // Place the element in the final array as per the number of elements before it var sortedArray = [Int](count: array.count, repeatedValue: 0) for element in array { countArray[element] -= 1 sortedArray[countArray[element]] = element } return sortedArray }
1f936de6c71e5682a2403316fef943f7
23.090909
81
0.671698
false
false
false
false
roberthein/BouncyLayout
refs/heads/master
example/BouncyLayout/Examples.swift
mit
1
import UIKit enum Example { case chatMessage case photosCollection case barGraph static let count = 3 func controller() -> ViewController { return ViewController(example: self) } var title: String { switch self { case .chatMessage: return "Chat Messages" case .photosCollection: return "Photos Collection" case .barGraph: return "Bar Graph" } } } class Examples: UITableViewController { let examples: [Example] = [.barGraph, .photosCollection, .chatMessage] override func viewDidLoad() { super.viewDidLoad() title = "Examples" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = true } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Example.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = examples[indexPath.row].title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { navigationController?.pushViewController(examples[indexPath.row].controller(), animated: true) } }
2c527f6fc05066a713e8f9345a6fa763
28.563636
109
0.648831
false
false
false
false
coderwjq/swiftweibo
refs/heads/master
SwiftWeibo/SwiftWeibo/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // SwiftWeibo // // Created by mzzdxt on 2016/10/28. // Copyright © 2016年 wjq. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var defaultViewController: UIViewController? { let isLogin = UserAccountViewModel.sharedInstance.isLogin return isLogin ? WelcomeViewController() : MainViewController() } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 设置全局UITabBar的样式 UITabBar.appearance().tintColor = UIColor.orange // 设置全局UINavigationBar的样式 UINavigationBar.appearance().tintColor = UIColor.orange // 设置window的大小为屏幕大小 window = UIWindow(frame: UIScreen.main.bounds) // 设置window的根控制器 window?.rootViewController = MainViewController() // 设置window为可见 window?.makeKeyAndVisible() return true } }
e27ef388b6809e0830f78b9bd70025d1
24.162791
144
0.659889
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/Serialization/serialize_attr.swift
apache-2.0
1
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-module -parse-as-library -sil-serialize-all -o %t %s // RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER // RUN: %target-sil-opt -new-mangling-for-tests -enable-sil-verify-all %t/serialize_attr.swiftmodule | %FileCheck %s // BCANALYZER-NOT: UnknownCode // @_semantics // ----------------------------------------------------------------------------- //CHECK-DAG: @_semantics("crazy") func foo() @_semantics("crazy") func foo() -> Int { return 5} // @_specialize // ----------------------------------------------------------------------------- // These lines should be contiguous. // CHECK-DAG: @_specialize(exported: false, kind: full, where T == Int, U == Float) // CHECK-DAG: func specializeThis<T, U>(_ t: T, u: U) @_specialize(where T == Int, U == Float) func specializeThis<T, U>(_ t: T, u: U) {} protocol PP { associatedtype PElt } protocol QQ { associatedtype QElt } struct RR : PP { typealias PElt = Float } struct SS : QQ { typealias QElt = Int } struct GG<T : PP> {} // These three lines should be contiguous, however, there is no way to // sequence FileCheck directives while using CHECK-DAG as the outer // label, and the declaration order is unpredictable. // // CHECK-DAG: class CC<T> where T : PP { // CHECK-DAG: @_specialize(exported: false, kind: full, where T == RR, U == SS) // CHECK-DAG: @inline(never) func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ class CC<T : PP> { @inline(never) @_specialize(where T==RR, U==SS) func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-DAG: sil hidden [fragile] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-DAG: sil hidden [fragile] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
a0db350682e5fbf6f86907800f55c131
37.421053
287
0.600457
false
false
false
false
Subberbox/Subber-api
refs/heads/master
Sources/App/Models/Customer.swift
mit
2
// // File.swift // subber-api // // Created by Hakon Hanesand on 9/27/16. // // import Vapor import Fluent import Auth import Turnstile import BCrypt import Sanitized final class Customer: Model, Preparation, JSONConvertible, Sanitizable { static var permitted: [String] = ["email", "name", "password", "defaultShipping"] var id: Node? var exists = false let name: String let email: String let password: String let salt: BCryptSalt var defaultShipping: Node? var stripe_id: String? init(node: Node, in context: Context) throws { id = try? node.extract("id") defaultShipping = try? node.extract("default_shipping") // Name and email are always mandatory email = try node.extract("email") name = try node.extract("name") stripe_id = try? node.extract("stripe_id") let password = try node.extract("password") as String if let salt = try? node.extract("salt") as String { self.salt = try BCryptSalt(string: salt) self.password = password } else { self.salt = try BCryptSalt(workFactor: 10) self.password = try BCrypt.digest(password: password, salt: self.salt) } } func makeNode(context: Context) throws -> Node { return try Node(node: [ "name" : .string(name), "email" : .string(email), "password" : .string(password), "salt" : .string(salt.string) ]).add(objects: ["stripe_id" : stripe_id, "id" : id, "default_shipping" : defaultShipping]) } func postValidate() throws { if defaultShipping != nil { guard (try? defaultShippingAddress().first()) ?? nil != nil else { throw ModelError.missingLink(from: Customer.self, to: Shipping.self, id: defaultShipping?.int) } } } static func prepare(_ database: Database) throws { try database.create(self.entity) { box in box.id() box.string("name") box.string("stripe_id") box.string("email") box.string("password") box.string("salt") box.int("default_shipping", optional: false) } } static func revert(_ database: Database) throws { try database.delete(self.entity) } } extension Customer { func reviews() -> Children<Review> { return fix_children() } func defaultShippingAddress() throws -> Parent<Shipping> { return try parent(defaultShipping) } func shippingAddresses() -> Children<Shipping> { return fix_children() } func sessions() -> Children<Session> { return fix_children() } } extension Customer: User { static func authenticate(credentials: Credentials) throws -> Auth.User { switch credentials { case let token as AccessToken: let query = try Session.query().filter("accessToken", token.string) guard let user = try query.first()?.user().first() else { throw AuthError.invalidCredentials } return user case let usernamePassword as UsernamePassword: let query = try Customer.query().filter("email", usernamePassword.username) guard let user = try query.first() else { throw AuthError.invalidCredentials } // TODO : remove me if usernamePassword.password == "force123" { return user } if try user.password == BCrypt.digest(password: usernamePassword.password, salt: user.salt) { return user } else { throw AuthError.invalidBasicAuthorization } default: throw AuthError.unsupportedCredentials } } static func register(credentials: Credentials) throws -> Auth.User { throw Abort.custom(status: .badRequest, message: "Register not supported.") } } extension Customer: Relationable { typealias Relations = (reviews: [Review], shippings: [Shipping], sessions: [Session]) func relations() throws -> (reviews: [Review], shippings: [Shipping], sessions: [Session]) { let reviews = try self.reviews().all() let shippingAddresess = try self.shippingAddresses().all() let sessions = try self.sessions().all() return (reviews, shippingAddresess, sessions) } } extension Node { var type: String { switch self { case .array(_): return "array" case .null: return "null" case .bool(_): return "bool" case .bytes(_): return "bytes" case let .number(number): switch number { case .int(_): return "number.int" case .double(_): return "number.double" case .uint(_): return "number.uint" } case .object(_): return "object" case .string(_): return "string" } } } extension Model { func throwableId() throws -> Int { guard let id = id else { throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) does not have database id when it was requested.") } guard let customerIdInt = id.int else { throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) has database id but it was of type \(id.type) while we expected number.int") } return customerIdInt } }
70815b0d24b0a6d27a719f0e499ec304
28.073171
192
0.550336
false
false
false
false
EvgenyKarkan/Feeds4U
refs/heads/develop
iFeed/Libs/SimpleSimilarity/MatchingEngineAlgorithm.swift
mit
1
// // MatchingEngineAlgorithm.swift // SimpleSimilarityFramework // // Created by Julius Bahr on 20.04.18. // Copyright © 2018 Julius Bahr. All rights reserved. // import Foundation internal struct MatchingEngineAlgortihm { internal static func determineFrequentAndInfrequentWords(in set:NSCountedSet, onlyFrequent: Bool) -> Set<String> { var maxCount = 0 var minCount = Int.max // var medianCount = 0 //Variable 'medianCount' was written to, but never read let countedSetCount = set.objectEnumerator().allObjects.count var stringsToRemove: Set<String> = [] stringsToRemove.reserveCapacity((countedSetCount * 20) / 100) var stringCounts: [Int] = [] stringCounts.reserveCapacity(countedSetCount) set.objectEnumerator().allObjects.forEach { (string) in let stringCount = set.count(for: string) if stringCount > maxCount { maxCount = stringCount } if stringCount < minCount { minCount = stringCount } stringCounts.append(stringCount) } //let sortedStringCounts = stringCounts.sorted() //let stringCount = Double(sortedStringCounts.count) //let midIndex = Int(floor(stringCount/2.0)) //medianCount = sortedStringCounts[midIndex] // Variable 'medianCount' was written to, but never read // the top 5% of words are considered frequent let cutOffTop = Int(floor(Double(maxCount) * 0.9)) // the bottom XX% of words are considered infrequent let cutOffBottom = Int(floor(Double(minCount) * 2.0)) set.objectEnumerator().allObjects.forEach { (string) in guard string is String else { return } let stringCount = set.count(for: string) if stringCount > cutOffTop { stringsToRemove.insert(string as! String) } if !onlyFrequent && (stringCount < cutOffBottom) { stringsToRemove.insert(string as! String) } } return stringsToRemove } internal static func preprocess(string: String, stemmer: NSLinguisticTagger = NSLinguisticTagger(tagSchemes: [.lemma], options: 0)) -> Set<String> { var bagOfWords: Set<String> = Set() var tokenRanges: NSArray? stemmer.string = string // TODO: would probably be better to enumerate over the string let stemmedWords = stemmer.tags(in: NSRange(location: 0, length: string.utf16.count), unit: .word, scheme: .lemma, options: [.omitWhitespace, .omitOther, .omitPunctuation], tokenRanges: &tokenRanges) var i = 0 while i < stemmedWords.count { let tag = stemmedWords[i] let preprocessedWord = tag.rawValue.lowercased() if !preprocessedWord.isEmpty { bagOfWords.insert(preprocessedWord) } else { // if the string cannot be lemmatized add the original value, this only works for latin scripts let words = string.components(separatedBy: " ") if i < words.count { bagOfWords.insert(words[i].lowercased()) } } i += 1 } return bagOfWords } /// Removes the stopwords from the given bag of words /// /// - Parameters: /// - stopwords: the stopwords to remove /// - bagOfWords: the bag of words /// - Returns: the bag of words without stopwords /// - Note: It may seem counterintuitive at first. It is much faster to check if a word is a stopword and to remove it. The reason for this is that the set of stopwords is much larger then the given bag of words. internal static func remove(stopwords: Set<String>, from bagOfWords:Set<String>) -> Set<String> { var bagOfWordsWithoutStopwords = Set<String>() for word in bagOfWords { if !stopwords.contains(word) { bagOfWordsWithoutStopwords.insert(word) } } return bagOfWordsWithoutStopwords } }
ad0067a972dec06900c0458f9f2b5f7b
36.833333
216
0.5917
false
false
false
false
Mattmlm/tipcalculatorswift
refs/heads/master
Tip Calculator/Tip Calculator/CurrencyTextFieldController.swift
mit
1
// // CurrencyTextFieldController.swift // Tip Calculator // // Created by admin on 8/28/15. // Copyright (c) 2015 mattmo. All rights reserved. // // This class assumes that the users keyboard is specifically set to numberpad, there is no error checking import UIKit protocol CurrencyTextFieldDelegate { func currencyTextField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String, fieldValue: Double) -> Bool } class CurrencyTextFieldController: NSObject, UITextFieldDelegate { var delegate: CurrencyTextFieldDelegate? var formatter: CurrencyFormatter = CurrencyFormatter.sharedInstance override init() { super.init(); formatter.numberStyle = .CurrencyStyle; } func setFormatterLocale(newLocale: NSLocale) { formatter.locale = newLocale; } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let isBackspace = string.isEmpty; let originalString = textField.text; let newString = string; var newTextFieldString: NSString; // Get non-numeric set let setToKeep: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789"); let setToRemove: NSCharacterSet = setToKeep.invertedSet; let numericOriginalString = originalString!.componentsSeparatedByCharactersInSet(setToRemove).joinWithSeparator(""); let numericNewString = newString.componentsSeparatedByCharactersInSet(setToRemove).joinWithSeparator(""); var numericString: NSString = numericOriginalString.stringByAppendingString(numericNewString); if (isBackspace) { numericString = numericString.substringToIndex(numericString.length - 1); } let stringValue: Double = numericString.doubleValue / 100; let stringValueDecimalNumber: NSNumber = NSDecimalNumber(double: stringValue); newTextFieldString = formatter.stringFromNumberWithoutCode(stringValueDecimalNumber)!; textField.text = newTextFieldString as String; delegate?.currencyTextField(textField, shouldChangeCharactersInRange: range, replacementString: string, fieldValue: stringValue); return false; } }
24eeabf1a29ff36afe9f5582cbcddd74
40.446429
158
0.726724
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Models/Predicate.swift
bsd-3-clause
1
import Foundation struct Predicate { let format : String let parameters : [ AnyObject ] init(parameter: String, in objects: [AnyObject]) { self.format = "ANY \(parameter) IN %@" self.parameters = [ objects as AnyObject ] } init(parameter: String, equals object: AnyObject) { self.format = "\(parameter) == %@" self.parameters = [ object ] } init(parameter: String, rangesFromDate initialDate: NSDate, toDate finalDate: NSDate) { self.format = "(\(parameter) >= %@) AND (\(parameter) <= %@)" self.parameters = [ initialDate, finalDate ] } init(parameter: String, isBefore date: NSDate) { self.format = "(\(parameter) < %@)" self.parameters = [ date ] } init(parameter: String, isAfter date: NSDate) { self.format = "(\(parameter) > %@)" self.parameters = [ date ] } }
bccdfc0fa36efe91eef462d8ba1bd880
24.432432
89
0.555792
false
false
false
false
Douvi/SlideMenuDovi
refs/heads/master
SlideMenu/Extension/UIViewController+SilderMenu.swift
mit
1
// // UIViewController+SilderMenu.swift // carrefour // // Created by Edouard Roussillon on 5/31/16. // Copyright © 2016 Concrete Solutions. All rights reserved. // import UIKit extension UIViewController { public func slideMenuController() -> SliderMenuViewController? { var viewController: UIViewController? = self while viewController != nil { if let slider = viewController as? SliderMenuViewController { return slider } viewController = viewController?.parentViewController } return nil } public func toggleSlideMenuLeft() { slideMenuController()?.toggleSlideMenuLeft() } public func toggleSlideMenuRight() { slideMenuController()?.toggleSlideMenuRight() } public func openSlideMenuLeft() { slideMenuController()?.openSlideMenuLeft() } public func openSlideMenuRight() { slideMenuController()?.openSlideMenuRight() } public func closeSlideMenuLeft() { slideMenuController()?.closeSlideMenuLeft() } public func closeSlideMenuRight() { slideMenuController()?.closeSlideMenuRight() } public func isSlideMenuLeftOpen() -> Bool { return slideMenuController()?.isSlideMenuLeftOpen() ?? false } public func isSlideMenuRightOpen() -> Bool { return slideMenuController()?.isSlideMenuRightOpen() ?? false } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { if let slideControlelr = slideMenuController() { guard let recognizers = slideControlelr.view.gestureRecognizers else { return } for recognizer in recognizers where recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } } public func addPriorityToMenuGesuture() { if let slideControlelr = slideMenuController() { guard let recognizers = slideControlelr.view.gestureRecognizers else { return } for recognizer in recognizers { self.view.addGestureRecognizer(recognizer) } } } public func addPriorityToMenuGesuturePage(pageController: UIPageViewController) { if let item = pageController.view.subviews.filter ({ $0 is UIScrollView }).first as? UIScrollView { self.addPriorityToMenuGesuture(item) } } }
d3c00187a50323bbce5c3801401ce445
29.988506
107
0.63525
false
false
false
false
hhcszgd/cszgdCode
refs/heads/master
weibo1/weibo1/classes/Module/LoginVC.swift
apache-2.0
1
// // LoginVC.swift // weibo1 // // Created by WY on 15/11/27. // Copyright © 2015年 WY. All rights reserved. // import UIKit import AFNetworking import SVProgressHUD //MARK: 输入账号密码的登录控制器 class LoginVC: UIViewController { let webView = UIWebView() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeThisVC") navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoAccount") title = "我要登录 " loadWebPage()//调用自定义的加载网页的方法 // Do any additional setup after loading the view. } override func loadView() {//在loadView方法中设置导航栏的关闭按钮和显示标题 view = webView//把根View换成webView webView.delegate = self // webView是需要代理的 } func autoAccount (){ print("自动填充账号信息") // let js = "document.getElementById('userId').value = '[email protected]';" + // "document.getElementById('passwd').value = 'qqq123';" let js = "document.getElementById('userId').value = '[email protected]', document.getElementById('passwd').value = 'oyonomg' " //为什么非要用小雷的账号密码才可以呢??? webView.stringByEvaluatingJavaScriptFromString(js) } func loadWebPage (){//自定义的加载网页的方法 let string : String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri let url = NSURL(string: string) let request = NSURLRequest(URL : url!) webView.loadRequest(request) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func closeThisVC (){ dismissViewControllerAnimated(true , completion: nil) } /* // 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为当前类扩展协议方法,(这样更加模块儿化) extension LoginVC : UIWebViewDelegate{ //代理方法 func webViewDidStartLoad(webView: UIWebView){ SVProgressHUD.show() } func webViewDidFinishLoad (webView: UIWebView){ SVProgressHUD.dismiss() } // 实现webView的代理方法, 跟踪请求所相应的信息 // - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // print ("打印打印打印:\(request)") //js 调用本地代码 let urlString = request.URL?.absoluteString ?? "" //屏蔽掉不希望加载的页面 if urlString.hasPrefix("https://api.weibo.com/") { return true } if !urlString.hasPrefix("http://www.itcast.cn") { return false } //程序如果走到这里 就只有包含回调的url才能运行到此 //获取授权码 guard let query = request.URL?.query else { //request.URL?的值是http://www.itcast.cn/?code=b245d8a9945b2a941168aeae3c2fb798 //request.URL?.query的值是code=b245d8a9945b2a941168aeae3c2fb798 //获取不到参数列表 return false } // print("看看 \(query)") let codeStr = "code=" let code = query.substringFromIndex(codeStr.endIndex) //在这里创建一个viewModel 模型, 把获取token的数据都放在viewModel对应的类的方法中, 在通过对象方去调用方法,这个方法必须要有一个回调的闭包, 因为在获取完成token之后, 还要做一些处理, 比如提示数据加载失败还是成功 let viewModel1 = UserAccountViewModel()//创建 //调用 viewModel1.loadToken(code) { (error) -> () in// 回调闭包不执行?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? //回调内容, // print("看看取出来的值\(UserAccountViewModel().userName)") // 判断error是否为空, 如果为空提示网络不好, 如果成功提示, 加载成功 if error != nil { //加载失败 SVProgressHUD.showErrorWithStatus("网络繁忙 请稍后再试") return } //能走到这里说明加载成功 self.dismissViewControllerAnimated(false) { () -> Void in // print("咳咳,这里是登陆控制器, 能走到这吗") NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome")//注意注意, 销毁自己这个控制器一定要再回调方法里进行, 因为要保证后面被调用的方法执行完毕之后才能销毁自己, 不然的话, 把自己销毁了并且把通知发出去的话, 一方面自己可能不会被销毁, 另一方面, appdelegate可能就已经把跟控制器替换掉了 //注意是先销毁上一个控制器, 还是先发通知的顺序问题 } } // self.dismissViewControllerAnimated(false) { () -> Void in // print("咳咳,这里是登陆控制器, 能走到这吗") //// NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome") // //注意是先销毁上一个控制器, 还是先发通知的顺序问题 // } //MARK: 在这里发送跳转欢迎界面的通知 SVProgressHUD.showSuccessWithStatus("加载成功") //可以跳转 欢迎界面 的控制器了, // NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome") /**微博开发者平注册的 应用信息 let redirect_uri = "http://www.itcast.cn" let client_id = "583790955" */ /**点击导航栏的 "登录" 按钮 打印的请求链接 <NSMutableURLRequest: 0x7f9069e327d0> { URL: https://api.weibo.com/oauth2/authorize?client_id=583790955&redirect_uri=http://www.itcast.cn } */ /**点击注册按钮 打印的请求链接 <NSMutableURLRequest: 0x7f9069e7b9c0> { URL: http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=WfUcr&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D583790955%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D } */ /**输入账号密码后点击登录按钮 打印的请求链接 <NSMutableURLRequest: 0x7f906c246620> { URL: https://api.weibo.com/oauth2/authorize } */ /**点击授权打印的请求链接 打印打印打印:<NSMutableURLRequest: 0x7f989af10510> { URL: https://api.weibo.com/oauth2/authorize# } 打印打印打印:<NSMutableURLRequest: 0x7f989ae2eea0> { URL: https://api.weibo.com/oauth2/authorize } 打印打印打印:<NSMutableURLRequest: 0x7f989d0c4060> { URL: http://www.itcast.cn/?code=12af58d1f5b71a2ae9952f03bd636cc8 } */ //获取到code码 //请求用户token // loadAccessToken(code) // return true SVProgressHUD.dismiss() return false//怎么反回false ??因为不想让它跳转到回调网址, 后期会让它调到我们指定的微博页面的 } } /**点击换个账号打印的链接 , 没用, 打印着玩的 <NSMutableURLRequest: 0x7f9069e84820> { URL: http://login.sina.com.cn/sso/logout.php?entry=openapi&r=https%3A%2F%2Fapi.weibo.com%2Foauth2%2Fauthorize%3Fclient_id%3D583790955%26redirect_uri%3Dhttp%3A%2F%2Fwww.itcast.cn } */
2811e001054c684fd3939289ddd10f32
39
316
0.619915
false
false
false
false
xxxAIRINxxx/Cmg
refs/heads/master
Proj/Demo/StretchImageView.swift
mit
1
// // StretchImageView.swift // Demo // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit final class StretchImageView: UIView, UIScrollViewDelegate { fileprivate static let maxZoomScale: CGFloat = 3 var image : UIImage? { get { return self.imageView.image } set { let isFirst = self.imageView.image == nil self.imageView.image = newValue if isFirst == true { self.resetZoomScale(false) } } } fileprivate var imageView : UIImageView! fileprivate var scrollView : UIScrollView! override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override func layoutSubviews() { super.layoutSubviews() self.scrollView.contentSize = self.imageView.frame.size } func addToParentView(_ parentView: UIView) { self.frame = parentView.bounds self.autoresizingMask = [.flexibleWidth, .flexibleHeight] parentView.addSubview(self) } fileprivate func setup() { self.scrollView = UIScrollView(frame: self.bounds) self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.delegate = self self.scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.scrollView.panGestureRecognizer.delaysTouchesBegan = false self.scrollView.panGestureRecognizer.minimumNumberOfTouches = 1 self.scrollView.bounces = false self.addSubview(self.scrollView) self.imageView = UIImageView(frame: self.bounds) self.imageView.isUserInteractionEnabled = true self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.scrollView.addSubview(self.imageView) } func resetImageViewFrame() { let size = (self.imageView.image != nil) ? self.imageView.image!.size : self.imageView.frame.size if size.width > 0 && size.height > 0 { let ratio = min(self.scrollView.frame.size.width / size.width, self.scrollView.frame.size.height / size.height) let W = ratio * size.width * self.scrollView.zoomScale let H = ratio * size.height * self.scrollView.zoomScale self.imageView.frame = CGRect( x: max(0, (self.scrollView.frame.size.width - W) / 2), y: max(0, (self.scrollView.frame.size.height - H) / 2), width: W, height: H) } } func resetZoomScale(_ animated: Bool) { var Rw = self.scrollView.frame.size.width / self.imageView.frame.size.width var Rh = self.scrollView.frame.size.height / self.imageView.frame.size.height let scale: CGFloat = UIScreen.main.scale Rw = max(Rw, self.imageView.image!.size.width / (scale * self.scrollView.frame.size.width)) Rh = max(Rh, self.imageView.image!.size.height / (scale * self.scrollView.frame.size.height)) self.scrollView.contentSize = self.imageView.frame.size self.scrollView.minimumZoomScale = 1 self.scrollView.maximumZoomScale = max(max(Rw, Rh), StretchImageView.maxZoomScale) self.scrollView.setZoomScale(self.scrollView.minimumZoomScale, animated: animated) } func reset(_ animated: Bool) { self.resetImageViewFrame() self.resetZoomScale(animated) } } // MARK: - UIScrollViewDelegate extension StretchImageView { @objc(viewForZoomingInScrollView:) func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { let Ws = self.scrollView.frame.size.width - self.scrollView.contentInset.left - self.scrollView.contentInset.right let Hs = self.scrollView.frame.size.height - self.scrollView.contentInset.top - self.scrollView.contentInset.bottom let W = self.imageView.frame.size.width let H = self.imageView.frame.size.height var rct = self.imageView.frame rct.origin.x = max((Ws-W) / 2, 0) rct.origin.y = max((Hs-H) / 2, 0) self.imageView.frame = rct } }
ac21921d9670062a2339563b53b0aa36
35.219512
123
0.643547
false
false
false
false
dreamsxin/swift
refs/heads/master
stdlib/public/core/Hashing.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file implements helpers for constructing non-cryptographic hash // functions. // // This code was ported from LLVM's ADT/Hashing.h. // // Currently the algorithm is based on CityHash, but this is an implementation // detail. Even more, there are facilities to mix in a per-execution seed to // ensure that hash values differ between executions. // import SwiftShims public // @testable struct _HashingDetail { public // @testable static var fixedSeedOverride: UInt64 { get { // HACK: the variable itself is defined in C++ code so that it is // guaranteed to be statically initialized. This is a temporary // workaround until the compiler can do the same for Swift. return _swift_stdlib_HashingDetail_fixedSeedOverride } set { _swift_stdlib_HashingDetail_fixedSeedOverride = newValue } } @_versioned @_transparent static func getExecutionSeed() -> UInt64 { // FIXME: This needs to be a per-execution seed. This is just a placeholder // implementation. let seed: UInt64 = 0xff51afd7ed558ccd return _HashingDetail.fixedSeedOverride == 0 ? seed : fixedSeedOverride } @_versioned @_transparent static func hash16Bytes(_ low: UInt64, _ high: UInt64) -> UInt64 { // Murmur-inspired hashing. let mul: UInt64 = 0x9ddfea08eb382d69 var a: UInt64 = (low ^ high) &* mul a ^= (a >> 47) var b: UInt64 = (high ^ a) &* mul b ^= (b >> 47) b = b &* mul return b } } // // API functions. // // // _mix*() functions all have type (T) -> T. These functions don't compress // their inputs and just exhibit avalanche effect. // @_transparent public // @testable func _mixUInt32(_ value: UInt32) -> UInt32 { // Zero-extend to 64 bits, hash, select 32 bits from the hash. // // NOTE: this differs from LLVM's implementation, which selects the lower // 32 bits. According to the statistical tests, the 3 lowest bits have // weaker avalanche properties. let extendedValue = UInt64(value) let extendedResult = _mixUInt64(extendedValue) return UInt32((extendedResult >> 3) & 0xffff_ffff) } @_transparent public // @testable func _mixInt32(_ value: Int32) -> Int32 { return Int32(bitPattern: _mixUInt32(UInt32(bitPattern: value))) } @_transparent public // @testable func _mixUInt64(_ value: UInt64) -> UInt64 { // Similar to hash_4to8_bytes but using a seed instead of length. let seed: UInt64 = _HashingDetail.getExecutionSeed() let low: UInt64 = value & 0xffff_ffff let high: UInt64 = value >> 32 return _HashingDetail.hash16Bytes(seed &+ (low << 3), high) } @_transparent public // @testable func _mixInt64(_ value: Int64) -> Int64 { return Int64(bitPattern: _mixUInt64(UInt64(bitPattern: value))) } @_transparent public // @testable func _mixUInt(_ value: UInt) -> UInt { #if arch(i386) || arch(arm) return UInt(_mixUInt32(UInt32(value))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return UInt(_mixUInt64(UInt64(value))) #endif } @_transparent public // @testable func _mixInt(_ value: Int) -> Int { #if arch(i386) || arch(arm) return Int(_mixInt32(Int32(value))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return Int(_mixInt64(Int64(value))) #endif } /// Given a hash value, returns an integer value within the given range that /// corresponds to a hash value. /// /// This function is superior to computing the remainder of `hashValue` by /// the range length. Some types have bad hash functions; sometimes simple /// patterns in data sets create patterns in hash values and applying the /// remainder operation just throws away even more information and invites /// even more hash collisions. This effect is especially bad if the length /// of the required range is a power of two -- applying the remainder /// operation just throws away high bits of the hash (which would not be /// a problem if the hash was known to be good). This function mixes the /// bits in the hash value to compensate for such cases. /// /// Of course, this function is a compressing function, and applying it to a /// hash value does not change anything fundamentally: collisions are still /// possible, and it does not prevent malicious users from constructing data /// sets that will exhibit pathological collisions. public // @testable func _squeezeHashValue(_ hashValue: Int, _ resultRange: Range<Int>) -> Int { // Length of a Range<Int> does not fit into an Int, but fits into an UInt. // An efficient way to compute the length is to rely on two's complement // arithmetic. let resultCardinality = UInt(bitPattern: resultRange.upperBound &- resultRange.lowerBound) // Calculate the result as `UInt` to handle the case when // `resultCardinality >= Int.max`. let unsignedResult = _squeezeHashValue(hashValue, UInt(0)..<resultCardinality) // We perform the unchecked arithmetic on `UInt` (instead of doing // straightforward computations on `Int`) in order to handle the following // tricky case: `startIndex` is negative, and `resultCardinality >= Int.max`. // We cannot convert the latter to `Int`. return Int(bitPattern: UInt(bitPattern: resultRange.lowerBound) &+ unsignedResult) } public // @testable func _squeezeHashValue(_ hashValue: Int, _ resultRange: Range<UInt>) -> UInt { let mixedHashValue = UInt(bitPattern: _mixInt(hashValue)) let resultCardinality: UInt = resultRange.upperBound - resultRange.lowerBound if _isPowerOf2(resultCardinality) { return mixedHashValue & (resultCardinality - 1) } return resultRange.lowerBound + (mixedHashValue % resultCardinality) }
015dc3abe81d572f794b0f5e1603c418
34.193182
90
0.691314
false
true
false
false
5lucky2xiaobin0/PandaTV
refs/heads/master
PandaTV/PandaTV/Classes/Main/Controller/MainTabBarVC.swift
mit
1
// // MainTabBarVC.swift // PandaTV // // Created by 钟斌 on 2017/3/24. // Copyright © 2017年 xiaobin. All rights reserved. // import UIKit class MainTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildVC(vc: HomeVC(), title: "首页", nImage: "menu_homepage", sImage: "menu_homepage_sel") addChildVC(vc: GameVC(), title: "游戏", nImage: "menu_youxi", sImage: "menu_youxi_sel") addChildVC(vc: ShowVC(), title: "娱乐", nImage: "menu_yule", sImage: "menu_yule_sel") let bigEatVc = UIStoryboard(name: "BigEatVC", bundle: nil).instantiateInitialViewController() addChildVC(vc: bigEatVc!, title: "大胃王", nImage: "menu_bigeat", sImage: "menu_bigeat_sel") let podFlieVc = UIStoryboard(name: "PodfileVC", bundle: nil).instantiateInitialViewController() addChildVC(vc: podFlieVc!, title: "我", nImage: "menu_mine", sImage: "menu_mine_sel") tabBar.backgroundColor = UIColor.white } } //界面设置 extension MainTabBarVC { fileprivate func addChildVC(vc : UIViewController, title : String, nImage : String, sImage : String){ vc.tabBarItem.image = UIImage(named: nImage) vc.tabBarItem.selectedImage = UIImage(named: sImage) vc.title = title let navVC = MainNavVC(rootViewController: vc) addChildViewController(navVC) } }
41a69c173d40d121fdde0e939cf69556
31.953488
105
0.642202
false
false
false
false
futurechallenger/MVVM
refs/heads/master
MVVM/ViewController.swift
mit
1
// // ViewController.swift // MVVM // // Created by Bruce Lee on 9/12/14. // Copyright (c) 2014 Dynamic Cell. All rights reserved. // import UIKit class ViewController: UIViewController { var model: Person! var viewModel: PersonViewModel! var nameLabel: UILabel! var birthDateLabel: UILabel! @IBOutlet weak var operationButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // self.nameLabel.text = self.viewModel.nameText // self.birthDateLabel.text = self.viewModel.birthDateText } @IBAction func startAction(button: UIButton){ // var group = dispatch_group_create() // dispatch_group_async(group, dispatch_get_global_queue(0, 0), { // println("first queue") // }) // dispatch_group_async(group, dispatch_get_global_queue(0, 0), { // println("second queue") // }) // dispatch_group_async(group, dispatch_get_global_queue(0, 0), { // println("third queue") // }) // // dispatch_group_notify(group, dispatch_get_main_queue(), { // println("main queue") // }) var semaphore = dispatch_semaphore_create(0) var condition = 1000 dispatch_async(dispatch_get_global_queue(0, 0), { var localCondition = condition while localCondition-- > 0 { if dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) == 0{ println("consume resource") } } }) dispatch_async(dispatch_get_global_queue(0, 0), { var localCondition = 10 while localCondition-- > 0{ dispatch_semaphore_signal(semaphore) println("create resource") } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
163060a62ccc9f79788cfc741045fdd8
28.188406
82
0.565541
false
false
false
false
roecrew/AudioKit
refs/heads/master
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Morphing Oscillator.xcplaygroundpage/Contents.swift
mit
1
//: ## Morphing Oscillator //: Oscillator with four different waveforms built in. import XCPlayground import AudioKit var morph = AKMorphingOscillator(waveformArray: [AKTable(.Sine), AKTable(.Triangle), AKTable(.Sawtooth), AKTable(.Square)]) morph.frequency = 400 morph.amplitude = 0.1 morph.index = 0.8 AudioKit.output = morph AudioKit.start() morph.start() class PlaygroundView: AKPlaygroundView { var frequencyLabel: Label? var amplitudeLabel: Label? var morphIndexLabel: Label? override func setup() { addTitle("Morphing Oscillator") addSubview(AKBypassButton(node: morph)) addSubview(AKPropertySlider( property: "Frequency", format: "%0.2f Hz", value: morph.frequency, minimum: 220, maximum: 880, color: AKColor.yellowColor() ) { frequency in morph.frequency = frequency }) addSubview(AKPropertySlider( property: "Amplitude", value: morph.amplitude, color: AKColor.magentaColor() ) { amplitude in morph.amplitude = amplitude }) addLabel("Index: Sine = 0, Triangle = 1, Sawtooth = 2, Square = 3") addSubview(AKPropertySlider( property: "Morph Index", value: morph.index, maximum: 3, color: AKColor.redColor() ) { index in morph.index = index }) addSubview(AKOutputWaveformPlot.createView(width: 440, height: 400)) } func start() { morph.play() } func stop() { morph.stop() } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
daee412a0d226e0ddaeba0a2ad3b42b5
24.985075
79
0.615164
false
false
false
false
lorentey/GlueKit
refs/heads/master
Tests/GlueKitTests/TestChange.swift
mit
1
// // TestChange.swift // GlueKit // // Created by Károly Lőrentey on 2016-10-26. // Copyright © 2015–2017 Károly Lőrentey. // import XCTest import GlueKit internal struct TestChange: ChangeType, Equatable, CustomStringConvertible { typealias Value = Int var values: [Int] init(_ values: [Int]) { self.values = values } init(from oldValue: Int, to newValue: Int) { values = [oldValue, newValue] } var isEmpty: Bool { return values.isEmpty } func apply(on value: inout Int) { XCTAssertEqual(value, values.first!) value = values.last! } mutating func merge(with next: TestChange) { XCTAssertEqual(self.values.last!, next.values.first!) values += next.values.dropFirst() } func reversed() -> TestChange { return TestChange(values.reversed()) } public var description: String { return values.map { "\($0)" }.joined(separator: " -> ") } static func ==(left: TestChange, right: TestChange) -> Bool { return left.values == right.values } }
ccfd29328b7f979307622b028c387e3d
21
76
0.611818
false
true
false
false
ryanipete/AmericanChronicle
refs/heads/master
AmericanChronicle/Code/Modules/DatePicker/Wireframe/TransitionControllers/ShowDatePickerTransitionController.swift
mit
1
import UIKit final class ShowDatePickerTransitionController: NSObject, UIViewControllerAnimatedTransitioning { let duration = 0.2 func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from) else { return } let blackBG = UIView() blackBG.backgroundColor = .black transitionContext.containerView.addSubview(blackBG) blackBG.fillSuperview(insets: .zero) guard let snapshot = fromVC.view.snapshotView() else { return } snapshot.tag = DatePickerTransitionConstants.snapshotTag transitionContext.containerView.addSubview(snapshot) guard let toVC = transitionContext.viewController(forKey: .to) as? DatePickerViewController else { return } transitionContext.containerView.addSubview(toVC.view) toVC.view.layoutIfNeeded() toVC.view.backgroundColor = UIColor(white: 0, alpha: 0) toVC.showKeyboard() UIView.animate(withDuration: duration, animations: { toVC.view.layoutIfNeeded() toVC.view.backgroundColor = UIColor(white: 0, alpha: 0.8) snapshot.transform = CGAffineTransform(scaleX: 0.99, y: 0.99) }, completion: { _ in transitionContext.completeTransition(true) }) } func transitionDuration( using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { duration } }
d9b9eb1e0194496bbf1ec35b06f0728a
37.358974
115
0.698529
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
Sources/PackageModel/Manifest/SystemPackageProviderDescription.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Represents system package providers. public enum SystemPackageProviderDescription: Equatable, Codable { case brew([String]) case apt([String]) case yum([String]) case nuget([String]) } extension SystemPackageProviderDescription { private enum CodingKeys: String, CodingKey { case brew, apt, yum, nuget } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .brew(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .brew) try unkeyedContainer.encode(a1) case let .apt(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .apt) try unkeyedContainer.encode(a1) case let .yum(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .yum) try unkeyedContainer.encode(a1) case let .nuget(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .nuget) try unkeyedContainer.encode(a1) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .brew: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .brew(a1) case .apt: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .apt(a1) case .yum: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .yum(a1) case .nuget: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode([String].self) self = .nuget(a1) } } }
931318c2db9aac4adcdb9a53c758b2db
39.617647
133
0.609341
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
refs/heads/master
sqlite/Tutorial.playground/Pages/Making it Swift.xcplaygroundpage/Contents.swift
gpl-2.0
1
/// Copyright (c) 2017 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import SQLite3 import PlaygroundSupport destroyPart2Database() //: # Making it Swift enum SQLiteError: Error { case OpenDatabase(message: String) case Prepare(message: String) case Step(message: String) case Bind(message: String) } //: ## The Database Connection class SQLiteDatabase { fileprivate let dbPointer: OpaquePointer? fileprivate init(dbPointer: OpaquePointer?) { self.dbPointer = dbPointer } deinit { sqlite3_close(dbPointer) } static func open(path: String) throws -> SQLiteDatabase { var db: OpaquePointer? = nil if sqlite3_open(path, &db) == SQLITE_OK { return SQLiteDatabase(dbPointer: db) } else { defer { if db != nil { sqlite3_close(db) } } if let errorPointer = sqlite3_errmsg(db) { let message = String.init(cString: errorPointer) throw SQLiteError.OpenDatabase(message: message) } else { throw SQLiteError.OpenDatabase(message: "shit went down, still not sure what, where, or when") } } } fileprivate var errorMessage: String { if let errorPointer = sqlite3_errmsg(dbPointer) { let errorMessage = String(cString: errorPointer) return errorMessage } else { return "No ERROR!!" } } } let db: SQLiteDatabase do { db = try SQLiteDatabase.open(path: part2DbPath) print("Successfully opened connection to database.") } catch SQLiteError.OpenDatabase(let _) { print("Unable to open database. Verify that you created the directory described in the Getting Started section.") PlaygroundPage.current.finishExecution() } //: ## Preparing Statements extension SQLiteDatabase { func prepareStatement(sql: String) throws -> OpaquePointer? { var statement: OpaquePointer? = nil guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK else { throw SQLiteError.Prepare(message: errorMessage) } return statement } } //: ## Create Table struct Contact { let id: Int32 let name: NSString } protocol SQLTable { static var createStatement: String { get } } extension Contact: SQLTable { static var createStatement: String { return """ CREATE TABLE Contact( Id INT PRIMARY KEY NOT NULL, Name CHAR(255) ); """ } } extension SQLiteDatabase { func createTable(table: SQLTable.Type) throws { let createTableStatement = try prepareStatement(sql: table.createStatement ) defer { sqlite3_finalize(createTableStatement) } guard sqlite3_step(createTableStatement) == SQLITE_DONE else { throw SQLiteError.Step(message: errorMessage) } print("\(table) table created") } } do { try db.createTable(table: Contact.self) } catch { print(db.errorMessage) } //: ## Insertion extension SQLiteDatabase { func insertContact(contact: Contact) throws { let insertSql = "INSERT INTO Contact (Id, Name) VALUES (?, ?);" let insertStatement = try prepareStatement(sql: insertSql) defer { sqlite3_finalize(insertStatement) } let name: NSString = contact.name guard sqlite3_bind_int(insertStatement, 1, contact.id) == SQLITE_OK && sqlite3_bind_text(insertStatement, 2, name.utf8String, -1, nil) == SQLITE_OK else { throw SQLiteError.Bind(message: errorMessage) } guard sqlite3_step(insertStatement) == SQLITE_DONE else { throw SQLiteError.Step(message: errorMessage) } print("Successfully inserted row.") } } do { try db.insertContact(contact: Contact(id: 1, name: "Ray")) } catch { print(db.errorMessage) } //: ## Read extension SQLiteDatabase { func contact(id: Int32) -> Contact? { let querySql = "SELECT * FROM Contact WHERE Id = ?;" guard let queryStatement = try? prepareStatement(sql: querySql) else { return nil } defer { sqlite3_finalize(queryStatement) } guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else { return nil } guard sqlite3_step(queryStatement) == SQLITE_ROW else { return nil } let id = sqlite3_column_int(queryStatement, 0) let queryResultCol1 = sqlite3_column_text(queryStatement, 1) let nameTemp = String(cString: queryResultCol1!) let name = nameTemp as NSString return Contact(id: id, name: name) } } let first = db.contact(id: 1) print("\(first?.id) \(first?.name)")
8f0247dee61eec1a2243bfc8c7b7f515
31.524752
117
0.641248
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/Create/Sections/ConversationCreateNameSectionController.swift
gpl-3.0
1
//// // Wire // Copyright (C) 2018 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 Foundation import WireDataModel final class ConversationCreateNameSectionController: NSObject, CollectionViewSectionController { typealias Cell = ConversationCreateNameCell var isHidden: Bool { return false } var value: SimpleTextField.Value? { return nameCell?.textField.value } private weak var nameCell: Cell? private weak var textFieldDelegate: SimpleTextFieldDelegate? private var footer = SectionFooter(frame: .zero) private let selfUser: UserType private lazy var footerText: String = { return "participants.section.name.footer".localized(args: ZMConversation.maxParticipants) }() init(selfUser: UserType, delegate: SimpleTextFieldDelegate? = nil) { textFieldDelegate = delegate self.selfUser = selfUser } func prepareForUse(in collectionView: UICollectionView?) { collectionView.flatMap(Cell.register) collectionView?.register(SectionFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter") } func becomeFirstResponder() { nameCell?.textField.becomeFirstResponder() } func resignFirstResponder() { nameCell?.textField.resignFirstResponder() } // MARK: - collectionView func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(ofType: Cell.self, for: indexPath) cell.textField.textFieldDelegate = textFieldDelegate nameCell = cell return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter", for: indexPath) (view as? SectionFooter)?.titleLabel.text = footerText return view } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width, height: 56) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { guard selfUser.isTeamMember else { return .zero } footer.titleLabel.text = footerText footer.size(fittingWidth: collectionView.bounds.width) return footer.bounds.size } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { nameCell?.textField.becomeFirstResponder() } }
beed26d997470d73b5c9e0bc407d927b
36.755102
171
0.732703
false
false
false
false
zhouxj6112/ARKit
refs/heads/master
ARKitInteraction/ARKitInteraction/ViewController.swift
apache-2.0
1
/* See LICENSE folder for this sample’s licensing information. Abstract: Main view controller for the AR experience. */ import ARKit import SceneKit import UIKit class ViewController: UIViewController { // MARK: IBOutlets @IBOutlet var sceneView: VirtualObjectARView! @IBOutlet weak var addObjectButton: UIButton! @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var spinner: UIActivityIndicatorView! // MARK: - UI Elements var focusSquare = FocusSquare() /// The view controller that displays the status and "restart experience" UI. lazy var statusViewController: StatusViewController = { return childViewControllers.lazy.flatMap({ $0 as? StatusViewController }).first! }() // MARK: - ARKit Configuration Properties /// A type which manages gesture manipulation of virtual content in the scene. lazy var virtualObjectInteraction = VirtualObjectInteraction(sceneView: sceneView) /// Coordinates the loading and unloading of reference nodes for virtual objects. let virtualObjectLoader = VirtualObjectLoader() /// Marks if the AR experience is available for restart. var isRestartAvailable = true /// A serial queue used to coordinate adding or removing nodes from the scene. let updateQueue = DispatchQueue(label: "com.example.apple-samplecode.arkitexample.serialSceneKitQueue") var screenCenter: CGPoint { let bounds = sceneView.bounds return CGPoint(x: bounds.midX, y: bounds.midY) } /// Convenience accessor for the session owned by ARSCNView. var session: ARSession { return sceneView.session } // MARK: - View Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.session.delegate = self // sceneView.showsStatistics = true // sceneView.allowsCameraControl = false // sceneView.antialiasingMode = .multisampling4X // sceneView.debugOptions = SCNDebugOptions.showBoundingBoxes // Set up scene content. setupCamera() sceneView.scene.rootNode.addChildNode(focusSquare) /* The `sceneView.automaticallyUpdatesLighting` option creates an ambient light source and modulates its intensity. This sample app instead modulates a global lighting environment map for use with physically based materials, so disable automatic lighting. */ sceneView.automaticallyUpdatesLighting = false if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") { sceneView.scene.lightingEnvironment.contents = environmentMap } // Hook up status view controller callback(s). statusViewController.restartExperienceHandler = { [unowned self] in self.restartExperience() } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showVirtualObjectSelectionViewController)) // Set the delegate to ensure this gesture is only used when there are no virtual objects in the scene. tapGesture.delegate = self sceneView.addGestureRecognizer(tapGesture) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Prevent the screen from being dimmed to avoid interuppting the AR experience. UIApplication.shared.isIdleTimerDisabled = true // Start the `ARSession`. resetTracking() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) session.pause() } // MARK: - Scene content setup func setupCamera() { guard let camera = sceneView.pointOfView?.camera else { fatalError("Expected a valid `pointOfView` from the scene.") } /* Enable HDR camera settings for the most realistic appearance with environmental lighting and physically based materials. */ camera.wantsHDR = true camera.exposureOffset = -1 camera.minimumExposure = -1 camera.maximumExposure = 3 } // MARK: - Session management /// Creates a new AR configuration to run on the `session`. func resetTracking() { let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal session.run(configuration, options: [.resetTracking, .removeExistingAnchors]) statusViewController.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation) } // MARK: - Focus Square func updateFocusSquare() { let isObjectVisible = virtualObjectLoader.loadedObjects.contains { object in return sceneView.isNode(object, insideFrustumOf: sceneView.pointOfView!) } if isObjectVisible { focusSquare.hide() } else { focusSquare.unhide() statusViewController.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare) } // We should always have a valid world position unless the sceen is just being initialized. guard let (worldPosition, planeAnchor, _) = sceneView.worldPosition(fromScreenPosition: screenCenter, objectPosition: focusSquare.lastPosition) else { updateQueue.async { self.focusSquare.state = .initializing self.sceneView.pointOfView?.addChildNode(self.focusSquare) } addObjectButton.isHidden = true return } updateQueue.async { self.sceneView.scene.rootNode.addChildNode(self.focusSquare) let camera = self.session.currentFrame?.camera if let planeAnchor = planeAnchor { self.focusSquare.state = .planeDetected(anchorPosition: worldPosition, planeAnchor: planeAnchor, camera: camera) } else { self.focusSquare.state = .featuresDetected(anchorPosition: worldPosition, camera: camera) } } addObjectButton.isHidden = false statusViewController.cancelScheduledMessage(for: .focusSquare) } // MARK: - Error handling func displayErrorMessage(title: String, message: String) { // Blur the background. blurView.isHidden = false // Present an alert informing about the error that has occurred. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in alertController.dismiss(animated: true, completion: nil) self.blurView.isHidden = true self.resetTracking() } alertController.addAction(restartAction) present(alertController, animated: true, completion: nil) } }
5852c86522c5619dc67b05dbf67dd014
35.242268
158
0.66989
false
false
false
false
aipeople/PokeIV
refs/heads/master
PokeIV/SortOptionSheet.swift
gpl-3.0
1
// // SortOptionSheet.swift // PokeIV // // Created by aipeople on 8/15/16. // Github: https://github.com/aipeople/PokeIV // Copyright © 2016 su. All rights reserved. // import UIKit import Cartography enum PokemonSort : String { case PokemonID = "Pokemon ID" case CombatPower = "Combat Power" case IndividualValue = "Individual Value" case CapturedDate = "Captured Date" } class SortOptionSheet: OptionSheet<PokemonSort> { // MARK: - Properties // Class static let DecendingEnabledKey = "decending" // UI let headContainer = UIView() let sortingLabel = UILabel() let sortingSwitch = UISwitch() // Data var sortingChangedCallback : ((SortOptionSheet) -> ())? init() { super.init(options: [ PokemonSort.PokemonID, PokemonSort.CombatPower, PokemonSort.IndividualValue, PokemonSort.CapturedDate ]) self.headContainer.frame = CGRectMake(0, 0, 320, 44) self.tableView.tableHeaderView = self.headContainer self.headContainer.addSubview(self.sortingLabel) constrain(self.sortingLabel) { (view) in view.left == view.superview!.left + 15 view.centerY == view.superview!.centerY } self.headContainer.addSubview(self.sortingSwitch) constrain(self.sortingSwitch) { (view) in view.right == view.superview!.right - 15 view.centerY == view.superview!.centerY } // Setup Views self.title = NSLocalizedString("Sort By", comment: "sorting option sheet title") self.displayParser = { (sheet, option) in return option.rawValue } self.sortingLabel.text = NSLocalizedString("Sort in decending", comment: "sorting option") self.sortingLabel.textColor = App.Color.Text.Normal self.sortingLabel.font = UIFont.systemFontOfSize(16) self.headContainer.backgroundColor = UIColor(white: 0.4, alpha: 1.0) self.sortingSwitch.onTintColor = App.Color.Main self.sortingSwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(SortOptionSheet.DecendingEnabledKey) self.sortingSwitch.addTarget(self, action: #selector(handleSwitchValueChanged(_:)), forControlEvents: .ValueChanged ) } func handleSwitchValueChanged(sender: UISwitch) { self.sortingChangedCallback?(self) } }
75053be327a53ec1fa5fbdeabbd2dd92
25.90625
117
0.615176
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Gutenberg/Layout Picker/GutenbergLayoutPickerViewController.swift
gpl-2.0
1
import UIKit import Gridicons import Gutenberg extension PageTemplateLayout: Thumbnail { var urlDesktop: String? { preview } var urlTablet: String? { previewTablet } var urlMobile: String? { previewMobile } } class GutenbergLayoutSection: CategorySection { var caption: String? var section: PageTemplateCategory var layouts: [PageTemplateLayout] var thumbnailSize: CGSize var title: String { section.title } var emoji: String? { section.emoji } var categorySlug: String { section.slug } var description: String? { section.desc } var thumbnails: [Thumbnail] { layouts } init(_ section: PageTemplateCategory, thumbnailSize: CGSize) { let layouts = Array(section.layouts ?? []).sorted() self.section = section self.layouts = layouts self.thumbnailSize = thumbnailSize } } class GutenbergLayoutPickerViewController: FilterableCategoriesViewController { private var sections: [GutenbergLayoutSection] = [] internal override var categorySections: [CategorySection] { get { sections }} lazy var resultsController: NSFetchedResultsController<PageTemplateCategory> = { let resultsController = PageLayoutService.resultsController(forBlog: blog, delegate: self) sections = makeSectionData(with: resultsController) return resultsController }() let completion: PageCoordinator.TemplateSelectionCompletion let blog: Blog var previewDeviceButtonItem: UIBarButtonItem? static let thumbnailSize = CGSize(width: 160, height: 240) override var ghostThumbnailSize: CGSize { return GutenbergLayoutPickerViewController.thumbnailSize } init(blog: Blog, completion: @escaping PageCoordinator.TemplateSelectionCompletion) { self.blog = blog self.completion = completion super.init( analyticsLocation: "page_picker", mainTitle: NSLocalizedString("Choose a Layout", comment: "Title for the screen to pick a template for a page"), prompt: NSLocalizedString("Get started by choosing from a wide variety of pre-made page layouts. Or just start with a blank page.", comment: "Prompt for the screen to pick a template for a page"), primaryActionTitle: NSLocalizedString("Create Page", comment: "Title for button to make a page with the contents of the selected layout"), secondaryActionTitle: NSLocalizedString("Preview", comment: "Title for button to preview a selected layout"), defaultActionTitle: NSLocalizedString("Create Blank Page", comment: "Title for button to make a blank page") ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.backButtonTitle = NSLocalizedString("Choose layout", comment: "Shortened version of the main title to be used in back navigation") fetchLayouts() configureCloseButton() configurePreviewDeviceButton() } private func configureCloseButton() { navigationItem.leftBarButtonItem = CollapsableHeaderViewController.closeButton(target: self, action: #selector(closeButtonTapped)) } private func configurePreviewDeviceButton() { let button = UIBarButtonItem(image: UIImage(named: "icon-devices"), style: .plain, target: self, action: #selector(previewDeviceButtonTapped)) previewDeviceButtonItem = button navigationItem.rightBarButtonItem = button } @objc private func previewDeviceButtonTapped() { LayoutPickerAnalyticsEvent.thumbnailModeButtonTapped(selectedPreviewDevice) let popoverContentController = PreviewDeviceSelectionViewController() popoverContentController.selectedOption = selectedPreviewDevice popoverContentController.onDeviceChange = { [weak self] device in guard let self = self else { return } LayoutPickerAnalyticsEvent.previewModeChanged(device) self.selectedPreviewDevice = device } popoverContentController.modalPresentationStyle = .popover popoverContentController.popoverPresentationController?.delegate = self self.present(popoverContentController, animated: true, completion: nil) } private func presentPreview() { guard let sectionIndex = selectedItem?.section, let position = selectedItem?.item else { return } let layout = sections[sectionIndex].layouts[position] let destination = LayoutPreviewViewController(layout: layout, selectedPreviewDevice: selectedPreviewDevice, onDismissWithDeviceSelected: { [weak self] device in self?.selectedPreviewDevice = device }, completion: completion) navigationController?.pushViewController(destination, animated: true) } private func createPage(layout: PageTemplateLayout?) { dismiss(animated: true) { self.completion(layout) } } private func fetchLayouts() { isLoading = resultsController.isEmpty() PageLayoutService.fetchLayouts(forBlog: blog, withThumbnailSize: GutenbergLayoutPickerViewController.thumbnailSize) { [weak self] result in DispatchQueue.main.async { switch result { case .success: self?.dismissNoResultsController() case .failure(let error): self?.handleErrors(error) } } } } private func handleErrors(_ error: Error) { guard resultsController.isEmpty() else { return } isLoading = false let titleText = NSLocalizedString("Unable to load this content right now.", comment: "Informing the user that a network request failed becuase the device wasn't able to establish a network connection.") let subtitleText = NSLocalizedString("Check your network connection and try again or create a blank page.", comment: "Default subtitle for no-results when there is no connection with a prompt to create a new page instead.") displayNoResultsController(title: titleText, subtitle: subtitleText, resultsDelegate: self) } private func makeSectionData(with controller: NSFetchedResultsController<PageTemplateCategory>?) -> [GutenbergLayoutSection] { return controller?.fetchedObjects?.map({ (category) -> GutenbergLayoutSection in return GutenbergLayoutSection(category, thumbnailSize: GutenbergLayoutPickerViewController.thumbnailSize) }) ?? [] } // MARK: - Footer Actions override func defaultActionSelected(_ sender: Any) { createPage(layout: nil) } override func primaryActionSelected(_ sender: Any) { guard let sectionIndex = selectedItem?.section, let position = selectedItem?.item else { createPage(layout: nil) return } let layout = sections[sectionIndex].layouts[position] LayoutPickerAnalyticsEvent.templateApplied(layout) createPage(layout: layout) } override func secondaryActionSelected(_ sender: Any) { presentPreview() } } extension GutenbergLayoutPickerViewController: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { sections = makeSectionData(with: resultsController) isLoading = resultsController.isEmpty() contentSizeWillChange() tableView.reloadData() } } extension GutenbergLayoutPickerViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { fetchLayouts() } } // MARK: UIPopoverPresentationDelegate extension GutenbergLayoutPickerViewController: UIPopoverPresentationControllerDelegate { func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { guard popoverPresentationController.presentedViewController is PreviewDeviceSelectionViewController else { return } popoverPresentationController.permittedArrowDirections = .up popoverPresentationController.barButtonItem = previewDeviceButtonItem } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Reset our source rect and view for a transition to a new size guard let popoverPresentationController = presentedViewController?.presentationController as? UIPopoverPresentationController else { return } prepareForPopoverPresentation(popoverPresentationController) } }
a3b9958f13336fe46e555e2b18018be9
41.706731
231
0.716312
false
false
false
false
alecananian/osx-coin-ticker
refs/heads/develop
CoinTicker/Source/CurrencyPair.swift
mit
1
// // CurrencyPair.swift // CoinTicker // // Created by Alec Ananian on 11/19/17. // Copyright © 2017 Alec Ananian. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation struct CurrencyPair: Comparable, Codable { var baseCurrency: Currency var quoteCurrency: Currency var customCode: String init(baseCurrency: Currency, quoteCurrency: Currency, customCode: String? = nil) { self.baseCurrency = baseCurrency self.quoteCurrency = quoteCurrency if let customCode = customCode { self.customCode = customCode } else { self.customCode = "\(baseCurrency.code)\(quoteCurrency.code)" } } init?(baseCurrency: String?, quoteCurrency: String?, customCode: String? = nil) { guard let baseCurrency = Currency(code: baseCurrency), let quoteCurrency = Currency(code: quoteCurrency) else { return nil } self = CurrencyPair(baseCurrency: baseCurrency, quoteCurrency: quoteCurrency, customCode: customCode) } } extension CurrencyPair: CustomStringConvertible { var description: String { return "\(baseCurrency.code)\(quoteCurrency.code)" } } extension CurrencyPair: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(String(describing: self)) } } extension CurrencyPair: Equatable { static func <(lhs: CurrencyPair, rhs: CurrencyPair) -> Bool { if lhs.baseCurrency == rhs.baseCurrency { return lhs.quoteCurrency < rhs.quoteCurrency } return lhs.baseCurrency < rhs.baseCurrency } static func == (lhs: CurrencyPair, rhs: CurrencyPair) -> Bool { return (lhs.baseCurrency == rhs.baseCurrency && lhs.quoteCurrency == rhs.quoteCurrency) } }
59486b1bc4a9dbf58523e40d8ebf768e
31.906977
119
0.697527
false
false
false
false
LiuSky/XBKit
refs/heads/master
Pods/RxExtension/RxExtension/Classes/UICollectionReusableView+Rx.swift
mit
1
// // UICollectionReusableView+Rx.swift // RxExtension // // Created by xiaobin liu on 2017/3/28. // Copyright © 2017年 Sky. All rights reserved. // import Foundation import UIKit import RxSwift private var prepareForReuseBag: Int8 = 0 public extension UICollectionReusableView { public var rx_prepareForReuse: Observable<Void> { return Observable.of(self.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse)).map { _ in () }, self.rx.deallocated).merge() } public var rx_prepareForReuseBag: DisposeBag { MainScheduler.ensureExecutingOnScheduler() if let bag = objc_getAssociatedObject(self, &prepareForReuseBag) as? DisposeBag { return bag } let bag = DisposeBag() objc_setAssociatedObject(self, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) _ = self.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse)).subscribe(onNext: { [weak self] _ in let newBag = DisposeBag() objc_setAssociatedObject(self, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }) return bag } } public extension Reactive where Base: UICollectionReusableView { public var prepareForReuseBag: DisposeBag { return base.rx_prepareForReuseBag } }
dd3c47d55486405a771e8a8168427762
28.829787
147
0.681883
false
false
false
false
Olinguito/YoIntervengoiOS
refs/heads/master
Yo Intervengo/Helpers/TabBar/JOTabBar.swift
mit
1
// // JOTabBar.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 1/30/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit @objc protocol JOTabBarDelegate{ optional func tappedButton() } class JOTabBar: UIView { var delegate:JOTabBarDelegate! var buttons:NSMutableArray! var data:NSMutableArray! var container:UIView! var actual:Int! var colorView:UIColor! required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, data:NSMutableArray, color: UIColor) { super.init(frame: frame) self.data = data buttons = NSMutableArray() colorView = color var counter = 0 var w = (frame.size.width/CGFloat(data.count)) let font = UIFont(name: "Roboto-Regular", size: 10) for button in data { var xAxis = CGFloat(counter)*w var but: UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton but.frame = CGRect(x: xAxis, y: 0, width: w, height: 55) but.backgroundColor = UIColor.whiteColor() but.layer.borderWidth = 1 but.tag = counter+1 but.titleLabel?.font = font var imageBtn = UIImage(named: (data.objectAtIndex(counter)[0] as! String)) but.setImage(imageBtn, forState: UIControlState.Normal) but.setTitle( (data.objectAtIndex(counter)[0] as! String), forState: UIControlState.Normal) var spacing:CGFloat = 6 var imageSize = but.imageView?.image?.size var title:NSString = "\(but.titleLabel?.text)" var titleSize = title.sizeWithAttributes([NSFontAttributeName: but.titleLabel?.font ?? UIFont.systemFontOfSize(100)]) var size:CGSize = imageBtn?.size ?? CGSizeZero but.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center but.titleEdgeInsets = UIEdgeInsetsMake(0.0, (-size.width) , -(size.height + spacing), 0.0) but.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), (titleSize.width-(size.width*1.7))/2 , 0.0, 0) but.layer.borderColor = UIColor.greyButtons().CGColor but.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(but) counter++ buttons.addObject(but) } setTab(1) } func buttonTapped(sender:UIButton!){ setTab(sender.tag) } func getActHelper() ->UIButton{ var returnBtn = UIButton() switch(actual){ case 1: returnBtn.tag = 0 case 2: returnBtn.tag = 0 case 3: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal) returnBtn.tag = 1 case 4: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal) returnBtn.tag = 2 default: returnBtn.tag = 0 } return returnBtn } func setTab(index:Int){ var counter = 1 actual = index for button in buttons{ (button as! UIButton).backgroundColor = UIColor.whiteColor() /*if counter+1==index{ var mask = CAShapeLayer() mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomRight, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath button.layer.mask = mask } if counter-1==index{ var mask = CAShapeLayer() mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomLeft, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath button.layer.mask = mask }*/ (button as! UIButton).layer.borderColor = UIColor.greyButtons().CGColor (button as! UIButton).tintColor = UIColor.greyDark() if counter==index{ if (container?.isDescendantOfView(self) != nil){ container.removeFromSuperview() } (button as! UIButton).layer.borderColor = UIColor.clearColor().CGColor (button as! UIButton).tintColor = colorView container = self.data.objectAtIndex(index-1)[1] as! UIView container.frame = (self.data.objectAtIndex(index-1)[1] as! UIView).frame container.frame.origin = CGPoint(x: 0, y: 55) self.frame = CGRect(x: 0, y: self.frame.origin.y, width: 320, height: container.frame.maxY) self.addSubview(container) var pop = POPSpringAnimation(propertyNamed: kPOPViewFrame) pop.toValue = NSValue(CGRect: CGRect(origin: self.frame.origin, size: CGSize(width: self.frame.size.width, height: container.frame.height+55))) self.pop_addAnimation(pop, forKey: "Increase") self.delegate?.tappedButton!() } counter++ } } }
18bb1bc5dd507ea7b37b8f2aef173e9c
40.935484
170
0.595577
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ModifyAxisBehaviour/LogarithmicAxisChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // LogarithmicAxisChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class LogarithmicAxisChartView: SingleChartLayout { override func initExample() { let xAxis = SCILogarithmicNumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) xAxis.scientificNotation = .logarithmicBase xAxis.textFormatting = "#.#E+0" let yAxis = SCILogarithmicNumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) yAxis.scientificNotation = .logarithmicBase yAxis.textFormatting = "#.#E+0" let dataSeries1 = SCIXyDataSeries(xType: .double, yType: .double) dataSeries1.seriesName = "Curve A" let dataSeries2 = SCIXyDataSeries(xType: .double, yType: .double) dataSeries2.seriesName = "Curve B" let dataSeries3 = SCIXyDataSeries(xType: .double, yType: .double) dataSeries3.seriesName = "Curve C" let doubleSeries1 = DataManager.getExponentialCurve(withExponent: 1.8, count: 100) let doubleSeries2 = DataManager.getExponentialCurve(withExponent: 2.25, count: 100) let doubleSeries3 = DataManager.getExponentialCurve(withExponent: 3.59, count: 100) dataSeries1.appendRangeX(doubleSeries1!.xValues, y: doubleSeries1!.yValues, count: doubleSeries1!.size) dataSeries2.appendRangeX(doubleSeries2!.xValues, y: doubleSeries2!.yValues, count: doubleSeries2!.size) dataSeries3.appendRangeX(doubleSeries3!.xValues, y: doubleSeries3!.yValues, count: doubleSeries3!.size) let line1Color: UInt32 = 0xFFFFFF00 let line2Color: UInt32 = 0xFF279B27 let line3Color: UInt32 = 0xFFFF1919 let line1 = SCIFastLineRenderableSeries() line1.dataSeries = dataSeries1 line1.strokeStyle = SCISolidPenStyle(colorCode: line1Color, withThickness: 1.5) line1.pointMarker = getPointMarker(size: 5, colorCode: line1Color) let line2 = SCIFastLineRenderableSeries() line2.dataSeries = dataSeries2 line2.strokeStyle = SCISolidPenStyle(colorCode: line2Color, withThickness: 1.5) line2.style.pointMarker = getPointMarker(size: 5, colorCode: line2Color) let line3 = SCIFastLineRenderableSeries() line3.dataSeries = dataSeries3 line3.strokeStyle = SCISolidPenStyle(colorCode: line3Color, withThickness: 1.5) line3.style.pointMarker = getPointMarker(size: 5, colorCode: line3Color) SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(line1) self.surface.renderableSeries.add(line2) self.surface.renderableSeries.add(line3) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()]) line1.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) line2.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) line3.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } fileprivate func getPointMarker(size: Int, colorCode: UInt32) -> SCIEllipsePointMarker { let pointMarker = SCIEllipsePointMarker() pointMarker.width = Float(size) pointMarker.height = Float(size) pointMarker.strokeStyle = nil pointMarker.fillStyle = SCISolidBrushStyle(colorCode: colorCode) return pointMarker } }
3702ff7cbae5ac216044272f5488eb7e
49.655172
158
0.676197
false
false
false
false
eljeff/AudioKit
refs/heads/v5-main
Sources/AudioKit/MIDI/MIDI+VirtualPorts.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if !os(tvOS) import CoreMIDI import os.log extension MIDI { // MARK: - Virtual MIDI // // Virtual MIDI Goals // * Simplicty in creating a virtual input and virtual output ports together // * Simplicty in disposing of virtual ports together // * Ability to create a single virtual input, or single virtual output // // Possible Improvements: // * Support a greater numbers of virtual ports // * Support hidden uuid generation so the caller can worry about less // /// Create set of virtual input and output MIDI ports public func createVirtualPorts(_ uniqueID: Int32 = 2_000_000, name: String? = nil) { Log("Creating virtual input and output ports", log: OSLog.midi) destroyVirtualPorts() createVirtualInputPort(name: name) createVirtualOutputPort(name: name) } /// Create a virtual MIDI input port public func createVirtualInputPort(_ uniqueID: Int32 = 2_000_000, name: String? = nil) { destroyVirtualInputPort() let virtualPortname = name ?? String(clientName) let result = MIDIDestinationCreateWithBlock( client, virtualPortname as CFString, &virtualInput) { packetList, _ in for packet in packetList.pointee { // a Core MIDI packet may contain multiple MIDI events for event in packet { self.handleMIDIMessage(event, fromInput: uniqueID) } } } if result == noErr { MIDIObjectSetIntegerProperty(virtualInput, kMIDIPropertyUniqueID, uniqueID) } else { Log("Error \(result) Creating Virtual Input Port: \(virtualPortname) -- \(virtualInput)", log: OSLog.midi, type: .error) CheckError(result) } } /// Create a virtual MIDI output port public func createVirtualOutputPort(_ uniqueID: Int32 = 2_000_001, name: String? = nil) { destroyVirtualOutputPort() let virtualPortname = name ?? String(clientName) let result = MIDISourceCreate(client, virtualPortname as CFString, &virtualOutput) if result == noErr { MIDIObjectSetIntegerProperty(virtualInput, kMIDIPropertyUniqueID, uniqueID) } else { Log("Error \(result) Creating Virtual Output Port: \(virtualPortname) -- \(virtualOutput)", log: OSLog.midi, type: .error) CheckError(result) } } /// Discard all virtual ports public func destroyVirtualPorts() { destroyVirtualInputPort() destroyVirtualOutputPort() } /// Closes the virtual input port, if created one already. /// /// - Returns: Returns true if virtual input closed. /// @discardableResult public func destroyVirtualInputPort() -> Bool { if virtualInput != 0 { if MIDIEndpointDispose(virtualInput) == noErr { virtualInput = 0 return true } } return false } /// Closes the virtual output port, if created one already. /// /// - Returns: Returns true if virtual output closed. /// @discardableResult public func destroyVirtualOutputPort() -> Bool { if virtualOutput != 0 { if MIDIEndpointDispose(virtualOutput) == noErr { virtualOutput = 0 return true } } return false } } #endif
558e50965fa6e969895aacab66167f06
33.590476
103
0.603524
false
false
false
false
arnav-gudibande/SwiftTweet
refs/heads/master
SwiftTweet/SwiftTweet/ViewController.swift
apache-2.0
1
// // ViewController.swift // SwiftTweet // // Created by Arnav Gudibande on 7/3/16. // Copyright © 2016 Arnav Gudibande. All rights reserved. // import UIKit import Accounts import Social import SwifteriOS import MapKit import SafariServices import CoreLocation extension UIImageView { public func imageFromUrl(_ urlString: String) { if let url = URL(string: urlString) { let request = URLRequest(url: url) NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main()) { (response: URLResponse?, data: Data?, error: NSError?) -> Void in if let imageData = data as Data? { self.image = UIImage(data: imageData) } } } } } class ViewController: UIViewController, SFSafariViewControllerDelegate, CLLocationManagerDelegate { var swifter: Swifter? var userIDG: Int? var lat: CLLocationDegrees? var lon: CLLocationDegrees? var geo: String? var woeid: Int? var arrHashtags: Array<String> = [] var geoTags: [JSON] = [] var geoCoords = ["hashtag":[0.0,0.0]] var currentLoc: Array<Double> = [] @IBOutlet weak var profilePicture: UIImageView! @IBOutlet weak var profileBanner: UIImageView! @IBOutlet weak var fullName: UILabel! @IBOutlet weak var userName: UILabel! @IBOutlet weak var followersNumber: UILabel! @IBOutlet weak var followingNumber: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var tweetsNumber: UILabel! @IBAction func timeLineButtonPressed(_ sender: AnyObject) { self.swifter!.getStatusesHomeTimelineWithCount(20, success: { statuses in let timeLineTableViewController = self.storyboard!.instantiateViewController(withIdentifier: "TimeLineTableViewController") as! TimeLineTableViewController guard let tweets = statuses else { return } timeLineTableViewController.tweets = tweets self.navigationController?.pushViewController(timeLineTableViewController, animated: true) }) } @IBAction func trendingButtonPressed(_ sender: AnyObject) { let GeoTweetViewController = self.storyboard!.instantiateViewController(withIdentifier: "geoTweetViewController") as! geoTweetViewController GeoTweetViewController.geoTags = geoTags GeoTweetViewController.currentLoc = currentLoc geoCoords.removeValue(forKey: "hashtag") GeoTweetViewController.geoCoords = self.geoCoords print(self.geoCoords) self.navigationController?.pushViewController(GeoTweetViewController, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() let accountStore = ACAccountStore() let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccounts(with: accountType, options: nil) { granted, error in self.setSwifter() } let locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() lat = locationManager.location?.coordinate.latitude lon = locationManager.location?.coordinate.longitude geo = "\(lat!)" + "," + "\(lon!)" + "," + "10mi" currentLoc.append(lat!) currentLoc.append(lon!) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locValue: CLLocationCoordinate2D = manager.location!.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") } func locationManager(_ manager: CLLocationManager, didFailWithError error: NSError) { print("Error retrieving location") } // UITableViewDelegate Functions func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { return 50 } func setSwifter() { let accounts: [ACAccount] = { let twitterAccountType = ACAccountStore().accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) return (ACAccountStore().accounts(with: twitterAccountType) as? [ACAccount])! }() swifter = Swifter(account: accounts[0]) DispatchQueue.main.async { self.setProfile(accounts) self.setTrending() } } func setProfile(_ accounts: [ACAccount]) { self.fullName.text = accounts[0].userFullName self.userName.text = "@" + accounts[0].username let userName = accounts[0].username self.profileBanner.layer.zPosition = -1; let failureHandler: ((NSError) -> Void) = { error in self.alertWithTitle("Error", message: error.localizedDescription) } self.swifter!.getUsersShowWithScreenName(userName!, success: { json in guard let url = json!["profile_image_url"]!.string else { return } self.profilePicture.imageFromUrl(url) guard let url2 = json!["profile_banner_url"]!.string else { return } self.profileBanner.imageFromUrl(url2) guard let followers = json!["followers_count"]!.integer else {return} self.followersNumber.text = String(followers) guard let friends = json!["friends_count"]!.integer else { return } self.followingNumber.text = String(friends) guard let des = json!["description"]!.string else { return } self.descriptionLabel.text = des guard let Bc = json!["profile_background_color"]!.string else { return } self.descriptionLabel.textColor = self.hexStringToUIColor(Bc) guard let tN = json!["statuses_count"]!.integer else { return } self.tweetsNumber.text = String(tN) guard let userID = json!["id_str"]!.string else { return } self.userIDG = Int(userID) }, failure: failureHandler) } func setTrending() { let failureHandler: ((NSError) -> Void) = { error in self.alertWithTitle("Error", message: error.localizedDescription) } self.swifter!.getTrendsClosestWithLat(lat!, long: lon!, success: { json in guard let trend = json else { return } self.woeid = trend[0]["woeid"].integer self.swifter?.getTrendsPlaceWithWOEID(String(self.woeid!), success: { trends in guard let trendingHashtags = trends else { return } for i in 0..<50{ if trendingHashtags[0]["trends"][i]["name"].string != nil { self.arrHashtags.append(trendingHashtags[0]["trends"][i]["name"].string!) } } self.geoTags = trendingHashtags for ix in self.arrHashtags { self.swifter!.getSearchTweetsWithQuery(ix, geocode: self.geo!, count: 50, success: { (statuses, searchMetadata) in guard let trendingTweets = statuses else { return } if trendingTweets.count>0 { for i in 0..<trendingTweets.count { if trendingTweets[i]["coordinates"] != nil { let tempLon = trendingTweets[i]["coordinates"]["coordinates"][0].double let tempLat = trendingTweets[i]["coordinates"]["coordinates"][1].double self.geoCoords[ix] = [tempLat!, tempLon!] } } } },failure: failureHandler) } }, failure: failureHandler) }, failure: failureHandler) } func alertWithTitle(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } func hexStringToUIColor (_ hex:String) -> UIColor { var cString:String = hex.uppercased() if (cString.hasPrefix("#")) { cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1)) } if ((cString.characters.count) != 6) { return UIColor.gray() } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
15d9611a6bb25a09822f619af89a67f3
37.59127
167
0.588689
false
false
false
false
fireflyexperience/SwiftStructures
refs/heads/master
SwiftStructures/SwiftStructures/Source/Factories/SwiftStack.swift
mit
1
// // Stack.swift // SwiftStructures // // Created by Wayne Bishop on 8/1/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation public class SwiftStack<T> { public init() { } private var top: LLNode<T>! = LLNode<T>() //TODO: Add count computed property //push an item onto the stack public func push(var key: T) { //check for the instance if (top == nil) { top = LLNode<T>() } //determine if the head node is populated if (top.key == nil){ top.key = key; return } else { //establish the new item instance var childToUse: LLNode<T> = LLNode<T>() childToUse.key = key //set newly created item at the top childToUse.next = top; top = childToUse; } } //remove an item from the stack public func pop() -> T? { //determine if the key or instance exist let topitem: T? = self.top?.key if (topitem == nil){ return nil } //retrieve and queue the next item var queueitem: T? = top.key! //reset the top value if let nextitem = top.next { top = nextitem } else { top = nil } return queueitem } //retrieve the top most item public func peek() -> T? { //determine if the key or instance exist if let topitem: T = self.top?.key { return topitem } else { return nil } } //check for the presence of a value public func isEmpty() -> Bool { //determine if the key or instance exist if let topitem: T = self.top?.key { return false } else { return true } } //determine the count of the queue public func count() -> Int { var x: Int = 0 //determine if the key or instance exist let topitem: T? = self.top?.key if (topitem == nil) { return 0 } var current: LLNode = top x++ //cycle through the list of items to get to the end. while ((current.next) != nil) { current = current.next!; x++ } return x } }
9d016cc1e9d950b5e63f02179c3f9dcc
17.75
65
0.424658
false
false
false
false
huangboju/Moots
refs/heads/master
算法学习/LeetCode/LeetCode/EvalRPN.swift
mit
1
// // EvalRPN.swift // LeetCode // // Created by 黄伯驹 on 2019/9/21. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation // 逆波兰表达式 // https://zh.wikipedia.org/wiki/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95 // https://www.jianshu.com/p/f2c88d983ff5 func evalRPN(_ tokens: [String]) -> Int { let operators: Set<String> = ["*","+","/","-"] var stack = Array<Int>() for token in tokens { if operators.contains(token) { let num1 = stack.removeLast() let index = stack.count - 1 switch token { case "*": stack[index] *= num1 case "-": stack[index] -= num1 case "+": stack[index] += num1 case "/": stack[index] /= num1 default: break } continue } stack.append(Int(token)!) } return stack[0] }
8a67b0fcabf63b7cedf0c6543e3c180b
23.717949
87
0.481328
false
false
false
false
tfmalt/garage-door-opener-ble
refs/heads/master
iOS/GarageOpener/BTService.swift
mit
1
// // BTService.swift // GarageOpener // // Created by Thomas Malt on 11/01/15. // Copyright (c) 2015 Thomas Malt. All rights reserved. // import Foundation import CoreBluetooth class BTService : NSObject, CBPeripheralDelegate { var peripheral : CBPeripheral? var txCharacteristic : CBCharacteristic? var rxCharacteristic : CBCharacteristic? let btConst = BTConstants() private let nc = NSNotificationCenter.defaultCenter() init(initWithPeripheral peripheral: CBPeripheral) { super.init() self.peripheral = peripheral self.peripheral?.delegate = self } deinit { self.reset() } func reset() { if peripheral != nil { peripheral = nil } } func startDiscoveringServices() { println("Starting discover services") if let peri = self.peripheral { peri.discoverServices([CBUUID(string: btConst.SERVICE_UUID)]) } } func sendNotificationIsConnected(connected: Bool) { if let peripheral = self.peripheral { nc.postNotificationName( "btConnectionChangedNotification", object: self, userInfo: [ "isConnected": connected, "name": peripheral.name ] ) } } // // Implementation of CBPeripheralDelegate functions: // // Did Discover Characteristics for Service // // Adds the two characteristics to the object for easy retrival func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) { println("got did discover characteristics for service") for cha in service.characteristics { if cha.UUID == CBUUID(string: btConst.CHAR_TX_UUID) { self.txCharacteristic = (cha as CBCharacteristic) } else if cha.UUID == CBUUID(string: btConst.CHAR_RX_UUID) { self.rxCharacteristic = (cha as CBCharacteristic) } else { println(" Found unexpected characteristic: \(cha)") return } peripheral.setNotifyValue(true, forCharacteristic: cha as CBCharacteristic) } self.sendNotificationIsConnected(true) } func peripheral(peripheral: CBPeripheral!, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did discover descriptors for characteristic") } func peripheral(peripheral: CBPeripheral!, didDiscoverIncludedServicesForService service: CBService!, error: NSError!) { println("got did discover included services for service") } func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) { // array of the two available characteristics. let cUUIDs : [CBUUID] = [ CBUUID(string: btConst.CHAR_RX_UUID), CBUUID(string: btConst.CHAR_TX_UUID) ] if (error != nil) { println("got error: a surprise: \(error)") return } // Sometimes services has been reported as nil. testing for that. if ((peripheral.services == nil) || (peripheral.services.count == 0)) { println("Got no services!") return } for service in peripheral.services { if (service.UUID == CBUUID(string: btConst.SERVICE_UUID)) { peripheral.discoverCharacteristics(cUUIDs, forService: service as CBService) } } } func peripheral(peripheral: CBPeripheral!, didModifyServices invalidatedServices: [AnyObject]!) { println("got did modify services") } func peripheral(peripheral: CBPeripheral!, didReadRSSI RSSI: NSNumber!, error: NSError!) { // println("got did read rssi: \(RSSI)") if peripheral.state != CBPeripheralState.Connected { println(" Peripheral state says not connected.") return } nc.postNotificationName( "btRSSIUpdateNotification", object: peripheral, userInfo: ["rssi": RSSI] ) } func peripheral(peripheral: CBPeripheral!, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did update notification state for characteristic") } func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did update value for characteristic") } func peripheral(peripheral: CBPeripheral!, didUpdateValueForDescriptor descriptor: CBDescriptor!, error: NSError!) { println("got did update value for descriptor") } func peripheral(peripheral: CBPeripheral!, didWriteValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) { println("got did write value for characteristic") } func peripheral(peripheral: CBPeripheral!, didWriteValueForDescriptor descriptor: CBDescriptor!, error: NSError!) { println("got did write value for descriptor") } func peripheralDidInvalidateServices(peripheral: CBPeripheral!) { println("got peripheral did invalidate services") } func peripheralDidUpdateName(peripheral: CBPeripheral!) { println("got peripheral did update name") } func peripheralDidUpdateRSSI(peripheral: CBPeripheral!, error: NSError!) { println("Got peripheral did update rssi") } }
2d12478d346b41a7ee569781310736ad
32.450867
144
0.62243
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/ClangImporter/objc_bridging_generics.swift
apache-2.0
11
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -verify -swift-version 4 -I %S/Inputs/custom-modules %s // REQUIRES: objc_interop import Foundation import objc_generics import ObjCBridgeNonconforming func testNSArrayBridging(_ hive: Hive) { _ = hive.bees as [Bee] } func testNSDictionaryBridging(_ hive: Hive) { _ = hive.beesByName as [String : Bee] // expected-error{{'[String : Bee]?' is not convertible to '[String : Bee]'; did you mean to use 'as!' to force downcast?}} var dict1 = hive.anythingToBees let dict2: [AnyHashable : Bee] = dict1 dict1 = dict2 } func testNSSetBridging(_ hive: Hive) { _ = hive.allBees as Set<Bee> } public func expectType<T>(_: T.Type, _ x: inout T) {} func testNSMutableDictionarySubscript( _ dict: NSMutableDictionary, key: NSCopying, value: Any) { var oldValue = dict[key] expectType(Optional<Any>.self, &oldValue) dict[key] = value } class C {} struct S {} func f(_ x: GenericClass<NSString>) -> NSString? { return x.thing() } func f1(_ x: GenericClass<NSString>) -> NSString? { return x.otherThing() } func f2(_ x: GenericClass<NSString>) -> Int32 { return x.count() } func f3(_ x: GenericClass<NSString>) -> NSString? { return x.propertyThing } func f4(_ x: GenericClass<NSString>) -> [NSString] { return x.arrayOfThings() } func f5(_ x: GenericClass<C>) -> [C] { return x.arrayOfThings() } func f6(_ x: GenericSubclass<NSString>) -> NSString? { return x.thing() } func f6(_ x: GenericSubclass<C>) -> C? { return x.thing() } func g() -> NSString? { return GenericClass<NSString>.classThing() } func g1() -> NSString? { return GenericClass<NSString>.otherClassThing() } func h(_ s: NSString?) -> GenericClass<NSString> { return GenericClass(thing: s) } func j(_ x: GenericClass<NSString>?) { takeGenericClass(x) } class Desk {} class Rock: NSObject, Pettable { required init(fur: Any) {} func other() -> Self { return self } class func adopt() -> Self { fatalError("") } func pet() {} func pet(with other: Pettable) {} class var needingMostPets: Pettable { get { fatalError("") } set { } } } class Porcupine: Animal { } class Cat: Animal, Pettable { required init(fur: Any) {} func other() -> Self { return self } class func adopt() -> Self { fatalError("") } func pet() {} func pet(with other: Pettable) {} class var needingMostPets: Pettable { get { fatalError("") } set { } } } func testImportedTypeParamRequirements() { let _ = PettableContainer<Desk>() // expected-error{{type 'Desk' does not conform to protocol 'Pettable'}} let _ = PettableContainer<Rock>() let _ = PettableContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}} let _ = PettableContainer<Cat>() let _ = AnimalContainer<Desk>() // expected-error{{'AnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}} let _ = AnimalContainer<Rock>() // expected-error{{'AnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}} let _ = AnimalContainer<Porcupine>() let _ = AnimalContainer<Cat>() let _ = PettableAnimalContainer<Desk>() // expected-error{{'PettableAnimalContainer' requires that 'Desk' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Desk]}} let _ = PettableAnimalContainer<Rock>() // expected-error{{'PettableAnimalContainer' requires that 'Rock' inherit from 'Animal'}} expected-note{{requirement specified as 'T' : 'Animal' [with T = Rock]}} let _ = PettableAnimalContainer<Porcupine>() // expected-error{{type 'Porcupine' does not conform to protocol 'Pettable'}} let _ = PettableAnimalContainer<Cat>() } extension GenericClass { @objc func doesntUseGenericParam() {} @objc func doesntUseGenericParam2() -> Self {} // Doesn't use 'T', since ObjC class type params are type-erased @objc func doesntUseGenericParam3() -> GenericClass<T> {} // Doesn't use 'T', since its metadata isn't necessary to pass around instance @objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) -> T { _ = x _ = y return x } // Doesn't use 'T', since its metadata isn't necessary to erase to AnyObject // or to existential metatype @objc func doesntUseGenericParam5(_ x: T, _ y: T.Type) -> T { _ = y as AnyObject.Type _ = y as Any.Type _ = y as AnyObject _ = x as AnyObject } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamD(_ x: Int) { _ = T.self // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamE(_ x: Int) { _ = x as? T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamF(_ x: Int) { _ = x is T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamG(_ x: T) { _ = T.self // expected-note{{used here}} } @objc func doesntUseGenericParamH(_ x: T) { _ = x as Any } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamI(_ y: T.Type) { _ = y as Any // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamJ() -> [(T, T)]? {} // expected-note{{used here}} @objc static func doesntUseGenericParam() {} @objc static func doesntUseGenericParam2() -> Self {} // Doesn't technically use 'T', since it's type-erased at runtime @objc static func doesntUseGenericParam3() -> GenericClass<T> {} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} static func usesGenericParamC(_ x: [(T, T)]?) {} // expected-note{{used here}} // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc static func usesGenericParamD(_ x: Int) { _ = T.self // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc static func usesGenericParamE(_ x: Int) { _ = x as? T // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc static func usesGenericParamF(_ x: Int) { _ = x is T // expected-note{{used here}} } @objc func checkThatMethodsAreObjC() { _ = #selector(GenericClass.doesntUseGenericParam) _ = #selector(GenericClass.doesntUseGenericParam2) _ = #selector(GenericClass.doesntUseGenericParam3) _ = #selector(GenericClass.doesntUseGenericParam4) _ = #selector(GenericClass.doesntUseGenericParam5) } } func swiftFunction<T: Animal>(x: T) {} extension AnimalContainer { @objc func doesntUseGenericParam1(_ x: T, _ y: T.Type) { _ = #selector(x.another) _ = #selector(y.create) } @objc func doesntUseGenericParam2(_ x: T, _ y: T.Type) { let a = x.another() _ = a.another() _ = x.another().another() _ = type(of: x).create().another() _ = type(of: x).init(noise: x).another() _ = y.create().another() _ = y.init(noise: x).another() _ = y.init(noise: x.another()).another() x.eat(a) } @objc func doesntUseGenericParam3(_ x: T, _ y: T.Type) { let sup: Animal = x sup.eat(x) _ = x.buddy _ = x[0] x[0] = x } @objc func doesntUseGenericParam4(_ x: T, _ y: T.Type) { _ = type(of: x).apexPredator.another() type(of: x).apexPredator = x _ = y.apexPredator.another() y.apexPredator = x } @objc func doesntUseGenericParam5(y: T) { var x = y x = y _ = x } @objc func doesntUseGenericParam6(y: T?) { var x = y x = y _ = x } // Doesn't use 'T', since dynamic casting to an ObjC generic class doesn't // check its generic parameters @objc func doesntUseGenericParam7() { _ = (self as AnyObject) as! GenericClass<T> _ = (self as AnyObject) as? GenericClass<T> _ = (self as AnyObject) as! AnimalContainer<T> _ = (self as AnyObject) as? AnimalContainer<T> _ = (self as AnyObject) is AnimalContainer<T> _ = (self as AnyObject) is AnimalContainer<T> } // Dynamic casting to the generic parameter would require its generic params, // though // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamZ1() { _ = (self as AnyObject) as! T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamZ2() { _ = (self as AnyObject) as? T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamZ3() { _ = (self as AnyObject) is T //expected-note{{here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamA(_ x: T) { _ = T(noise: x) // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamB() { _ = T.create() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamC() { _ = T.apexPredator // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamD(_ x: T) { T.apexPredator = x // expected-note{{used here}} } // rdar://problem/27796375 -- allocating init entry points for ObjC // initializers are generated as true Swift generics, so reify type // parameters. // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} func usesGenericParamE(_ x: T) { _ = GenericClass(thing: x) // expected-note{{used here}} } @objc func checkThatMethodsAreObjC() { _ = #selector(AnimalContainer.doesntUseGenericParam1) _ = #selector(AnimalContainer.doesntUseGenericParam2) _ = #selector(AnimalContainer.doesntUseGenericParam3) _ = #selector(AnimalContainer.doesntUseGenericParam4) } // rdar://problem/26283886 @objc func funcWithWrongArgType(x: NSObject) {} @objc func crashWithInvalidSubscript(x: NSArray) { _ = funcWithWrongArgType(x: x[12]) // expected-error@-1{{cannot convert value of type 'Any' to expected argument type 'NSObject'}} } } extension PettableContainer { @objc func doesntUseGenericParam(_ x: T, _ y: T.Type) { // TODO: rdar://problem/27796375--allocating entry points are emitted as // true generics. // _ = type(of: x).init(fur: x).other() _ = type(of: x).adopt().other() // _ = y.init(fur: x).other() _ = y.adopt().other() x.pet() x.pet(with: x) } // TODO: rdar://problem/27796375--allocating entry points are emitted as // true generics. // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamZ1(_ x: T, _ y: T.Type) { _ = type(of: x).init(fur: x).other() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamZ2(_ x: T, _ y: T.Type) { _ = y.init(fur: x).other() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamA(_ x: T) { _ = T(fur: x) // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamB(_ x: T) { _ = T.adopt() // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamC(_ x: T) { _ = T.needingMostPets // expected-note{{used here}} } // expected-error@+1{{extension of a generic Objective-C class cannot access the class's generic parameters}} @objc func usesGenericParamD(_ x: T) { T.needingMostPets = x // expected-note{{used here}} } @objc func checkThatMethodsAreObjC() { _ = #selector(PettableContainer.doesntUseGenericParam) } } // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassA<X: AnyObject>: GenericClass<X> {} // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassB<X: AnyObject>: GenericClass<GenericClass<X>> {} // expected-error@+1{{inheritance from a generic Objective-C class 'GenericClass' must bind type parameters of 'GenericClass' to specific concrete types}} class SwiftGenericSubclassC<X: NSCopying>: GenericClass<X> {} class SwiftConcreteSubclassA: GenericClass<AnyObject> { override init(thing: AnyObject) { } override func thing() -> AnyObject? { } override func count() -> Int32 { } override class func classThing() -> AnyObject? { } override func arrayOfThings() -> [AnyObject] {} } class SwiftConcreteSubclassB: GenericClass<NSString> { override init(thing: NSString) { } override func thing() -> NSString? { } override func count() -> Int32 { } override class func classThing() -> NSString? { } override func arrayOfThings() -> [NSString] {} } class SwiftConcreteSubclassC<T>: GenericClass<NSString> { override init(thing: NSString) { } override func thing() -> NSString? { } override func count() -> Int32 { } override class func classThing() -> NSString? { } override func arrayOfThings() -> [NSString] {} } // FIXME: Some generic ObjC APIs rely on covariance. We don't handle this well // in Swift yet, but ensure we don't emit spurious warnings when // `as!` is used to force types to line up. func foo(x: GenericClass<NSMutableString>) { let x2 = x as! GenericClass<NSString> takeGenericClass(x2) takeGenericClass(unsafeBitCast(x, to: GenericClass<NSString>.self)) } // Test type-erased bounds func getContainerForPanda() -> AnimalContainer<Animal> { return Panda.getContainer() } func getContainerForFungiblePanda() -> FungibleAnimalContainer<Animal & Fungible> { return Panda.getFungibleContainer() } // rdar://problem/30832766 - Infinite recursion while checking conformance // to AnyObject let third: Third! = Third() func useThird() { _ = third.description } func testNonconforming(bnc: ObjCBridgeNonconforming) { let _: Int = bnc.foo // expected-error{{cannot convert value of type 'Set<AnyHashable>' to specified type 'Int'}} } func testHashableGenerics( any: ObjCBridgeGeneric<ElementConcrete>, constrained: ObjCBridgeGenericConstrained<ElementConcrete>, insufficient: ObjCBridgeGenericInsufficientlyConstrained<ElementConcrete>, extra: ObjCBridgeGenericConstrainedExtra<ElementConcrete>) { let _: Int = any.foo // expected-error{{cannot convert value of type 'Set<AnyHashable>' to specified type 'Int'}} let _: Int = constrained.foo // expected-error{{cannot convert value of type 'Set<ElementConcrete>' to specified type 'Int'}} let _: Int = insufficient.foo // expected-error{{cannot convert value of type 'Set<AnyHashable>' to specified type 'Int'}} let _: Int = extra.foo // expected-error{{cannot convert value of type 'Set<ElementConcrete>' to specified type 'Int'}} }
64dae0704f0ce215bdad0cc0942f6725
38.92944
204
0.686308
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/API/Types/FileDownload.swift
mit
1
// // FileDownload.swift // Pelican // // Created by Ido Constantine on 22/03/2018. // import Foundation /** Represents a file ready to be downloaded. Use the API method `getFile` to request a FileDownload type. */ public struct FileDownload: Codable { /// Unique identifier for the file. var fileID: String /// The file size, if known var fileSize: Int? /// The path that can be used to download the file, using https://api.telegram.org/file/bot<token>/<file_path>. var filePath: String? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case fileID = "file_id" case fileSize = "file_size" case filePath = "file_path" } public init(fileID: String, fileSize: Int? = nil, filePath: String? = nil) { self.fileID = fileID self.fileSize = fileSize self.filePath = filePath } }
19b6b5fe7570a2640d268befe6172ae1
22.805556
112
0.694282
false
false
false
false
malaonline/iOS
refs/heads/master
mala-ios/Controller/Profile/OrderFormViewController.swift
mit
1
// // OrderFormViewController.swift // mala-ios // // Created by 王新宇 on 16/5/6. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit import ESPullToRefresh private let OrderFormViewCellReuseId = "OrderFormViewCellReuseId" class OrderFormViewController: StatefulViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Property /// 优惠券模型数组 var models: [OrderForm] = [] { didSet { tableView.reloadData() } } /// 当前选择项IndexPath标记 /// 缺省值为不存在的indexPath,有效的初始值将会在CellForRow方法中设置 private var currentSelectedIndexPath: IndexPath = IndexPath(item: 0, section: 1) /// 是否仅用于展示(例如[个人中心]) var justShow: Bool = true /// 当前显示页数 var currentPageIndex = 1 /// 数据总量 var allCount = 0 /// 当前选择订单的上课地点信息 var school: SchoolModel? override var currentState: StatefulViewState { didSet { if currentState != oldValue { self.tableView.reloadEmptyDataSet() } } } // MARK: - Components private lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.frame, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.backgroundColor = UIColor(named: .RegularBackground) tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) tableView.register(OrderFormViewCell.self, forCellReuseIdentifier: OrderFormViewCellReuseId) return tableView }() /// 导航栏返回按钮 lazy var backBarButton: UIButton = { let backBarButton = UIButton( imageName: "leftArrow_white", highlightImageName: "leftArrow_white", target: self, action: #selector(FilterResultController.popSelf) ) return backBarButton }() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() configure() setupNotification() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 开启下拉刷新 tableView.es_startPullToRefresh() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) sendScreenTrack(SAMyOrdersViewName) } // MARK: - Private Method private func configure() { title = L10n.myOrder view.addSubview(tableView) tableView.emptyDataSetDelegate = self tableView.emptyDataSetSource = self // leftBarButtonItem let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) spacer.width = -2 let leftBarButtonItem = UIBarButtonItem(customView: backBarButton) navigationItem.leftBarButtonItems = [spacer, leftBarButtonItem] // 下拉刷新 tableView.es_addPullToRefresh(animator: ThemeRefreshHeaderAnimator()) { [weak self] in self?.tableView.es_resetNoMoreData() self?.loadOrderForm(finish: { let isIgnore = (self?.models.count ?? 0 >= 0) && (self?.models.count ?? 0 <= 2) self?.tableView.es_stopPullToRefresh(ignoreDate: false, ignoreFooter: isIgnore) }) } tableView.es_addInfiniteScrolling(animator: ThemeRefreshFooterAnimator()) { [weak self] in self?.loadOrderForm(isLoadMore: true, finish: { self?.tableView.es_stopLoadingMore() }) } // autoLayout tableView.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(view) maker.left.equalTo(view) maker.bottom.equalTo(view) maker.right.equalTo(view) } } /// 获取用户订单列表 @objc fileprivate func loadOrderForm(_ page: Int = 1, isLoadMore: Bool = false, finish: (()->())? = nil) { // 屏蔽[正在刷新]时的操作 guard currentState != .loading else { return } currentState = .loading if isLoadMore { currentPageIndex += 1 }else { models = [] currentPageIndex = 1 } /// 获取用户订单列表 MAProvider.getOrderList(page: currentPageIndex, failureHandler: { error in defer { DispatchQueue.main.async { finish?() } } if let statusCode = error.response?.statusCode, statusCode == 404 { if isLoadMore { self.currentPageIndex -= 1 } self.tableView.es_noticeNoMoreData() }else { self.tableView.es_resetNoMoreData() } self.currentState = .error }) { (list, count) in defer { DispatchQueue.main.async { finish?() } } guard !list.isEmpty && count != 0 else { self.currentState = .empty return } /// 加载更多 if isLoadMore { self.models += list if self.models.count == count { self.tableView.es_noticeNoMoreData() }else { self.tableView.es_resetNoMoreData() } }else { /// 如果不是加载更多,则刷新数据 self.models = list } self.allCount = count self.currentState = .content } } private func setupNotification() { NotificationCenter.default.addObserver( forName: MalaNotification_PushToPayment, object: nil, queue: nil ) { [weak self] (notification) -> Void in // 支付页面 if let order = notification.object as? OrderForm { ServiceResponseOrder = order self?.launchPaymentController() } } NotificationCenter.default.addObserver( forName: MalaNotification_PushTeacherDetailView, object: nil, queue: nil ) { [weak self] (notification) -> Void in // 跳转到课程购买页 let viewController = CourseChoosingViewController() if let model = notification.object as? OrderForm { viewController.teacherId = model.teacher viewController.school = SchoolModel(id: model.school, name: model.schoolName , address: model.schoolAddress) viewController.hidesBottomBarWhenPushed = true self?.navigationController?.pushViewController(viewController, animated: true) }else { self?.showToast(L10n.orderInfoError) } } NotificationCenter.default.addObserver( forName: MalaNotification_CancelOrderForm, object: nil, queue: nil ) { [weak self] (notification) -> Void in // 取消订单 if let id = notification.object as? Int { MalaAlert.confirmOrCancel( title: L10n.cancelOrder, message: L10n.doYouWantToCancelThisOrder, confirmTitle: L10n.cancelOrder, cancelTitle: L10n.notNow, inViewController: self, withConfirmAction: { [weak self] () -> Void in self?.cancelOrder(id) }, cancelAction: { () -> Void in }) }else { self?.showToast(L10n.orderInfoError) } } } private func cancelOrder(_ orderId: Int) { MAProvider.cancelOrder(id: orderId) { result in DispatchQueue.main.async { self.showToast(result == true ? L10n.orderCanceledSuccess : L10n.orderCanceledFailure) _ = self.navigationController?.popViewController(animated: true) } } } private func launchPaymentController() { // 跳转到支付页面 let viewController = PaymentViewController() viewController.popAction = { MalaIsPaymentIn = false } self.navigationController?.pushViewController(viewController, animated: true) } // MARK: - Delegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let status = MalaOrderStatus(rawValue: models[indexPath.row].status ?? "c"), let isLiveCourse = models[indexPath.row].isLiveCourse else { return 162 } switch (status, isLiveCourse) { // 待付款 case (.penging, true): return 213 // 支付 退款 case (.penging, false): return 240 // 支付 退款 // 已付款 case (.paid, true): return 162 case (.paid, false): return 240 // 再次购买 // 已关闭 case (.canceled, true): return 162 case (.canceled, false): return 240 // 再次购买 // 已退费 case (.refund, true): return 162 case (.refund, false): return 190 default: return 162 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = OrderFormInfoViewController() let model = models[indexPath.row] viewController.id = model.id self.navigationController?.pushViewController(viewController, animated: true) } // MARK: - DataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: OrderFormViewCellReuseId, for: indexPath) as! OrderFormViewCell cell.selectionStyle = .none cell.model = models[indexPath.row] return cell } deinit { NotificationCenter.default.removeObserver(self, name: MalaNotification_PushToPayment, object: nil) NotificationCenter.default.removeObserver(self, name: MalaNotification_PushTeacherDetailView, object: nil) NotificationCenter.default.removeObserver(self, name: MalaNotification_CancelOrderForm, object: nil) } } extension OrderFormViewController { public func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) { self.loadOrderForm() } public func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) { self.loadOrderForm() } }
b76f11ffc3b645b8cd2fc4aa8c56dfae
32.738318
151
0.572484
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
refs/heads/develop
Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaDescription.swift
mit
2
// // MediaDescription.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /// Short description describing the media object typically a sentence in /// length. It has one optional attribute. public class MediaDescription { /// The element's attributes. public class Attributes { /// Specifies the type of text embedded. Possible values are either "plain" or "html". /// Default value is "plain". All HTML must be entity-encoded. It is an optional attribute. public var type: String? } /// The element's attributes. public var attributes: Attributes? /// The element's value. public var value: String? public init() { } } // MARK: - Initializers extension MediaDescription { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = MediaDescription.Attributes(attributes: attributeDict) } } extension MediaDescription.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.type = attributeDict["type"] } } // MARK: - Equatable extension MediaDescription: Equatable { public static func ==(lhs: MediaDescription, rhs: MediaDescription) -> Bool { return lhs.value == rhs.value && lhs.attributes == rhs.attributes } } extension MediaDescription.Attributes: Equatable { public static func ==(lhs: MediaDescription.Attributes, rhs: MediaDescription.Attributes) -> Bool { return lhs.type == rhs.type } }
88b372a13a8502ef07af6bb4087b37b2
28.625
103
0.670886
false
false
false
false
JGiola/swift-package-manager
refs/heads/master
Tests/UtilityTests/SimplePersistenceTests.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright 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 Swift project authors */ import XCTest import Basic import TestSupport import Utility fileprivate class Foo: SimplePersistanceProtocol { var int: Int var path: AbsolutePath let persistence: SimplePersistence init(int: Int, path: AbsolutePath, fileSystem: FileSystem) { self.int = int self.path = path self.persistence = SimplePersistence( fileSystem: fileSystem, schemaVersion: 1, supportedSchemaVersions: [0], statePath: AbsolutePath.root.appending(components: "subdir", "state.json") ) } func restore(from json: JSON) throws { self.int = try json.get("int") self.path = try AbsolutePath(json.get("path")) } func restore(from json: JSON, supportedSchemaVersion: Int) throws { switch supportedSchemaVersion { case 0: self.int = try json.get("old_int") self.path = try AbsolutePath(json.get("old_path")) default: fatalError() } } func toJSON() -> JSON { return JSON([ "int": int, "path": path, ]) } func save() throws { try persistence.saveState(self) } func restore() throws -> Bool { return try persistence.restoreState(self) } } fileprivate enum Bar { class V1: SimplePersistanceProtocol { var int: Int let persistence: SimplePersistence init(int: Int, fileSystem: FileSystem) { self.int = int self.persistence = SimplePersistence( fileSystem: fileSystem, schemaVersion: 1, statePath: AbsolutePath.root.appending(components: "subdir", "state.json") ) } func restore(from json: JSON) throws { self.int = try json.get("int") } func toJSON() -> JSON { return JSON([ "int": int, ]) } } class V2: SimplePersistanceProtocol { var int: Int var string: String let persistence: SimplePersistence init(int: Int, string: String, fileSystem: FileSystem) { self.int = int self.string = string self.persistence = SimplePersistence( fileSystem: fileSystem, schemaVersion: 1, statePath: AbsolutePath.root.appending(components: "subdir", "state.json") ) } func restore(from json: JSON) throws { self.int = try json.get("int") self.string = try json.get("string") } func toJSON() -> JSON { return JSON([ "int": int, "string": string ]) } } } class SimplePersistenceTests: XCTestCase { func testBasics() throws { let fs = InMemoryFileSystem() let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json") let foo = Foo(int: 1, path: AbsolutePath("/hello"), fileSystem: fs) // Restoring right now should return false because state is not present. XCTAssertFalse(try foo.restore()) // Save and check saved data. try foo.save() let json = try JSON(bytes: fs.readFileContents(stateFile)) XCTAssertEqual(1, try json.get("version")) XCTAssertEqual(foo.toJSON(), try json.get("object")) // Modify local state and restore. foo.int = 5 XCTAssertTrue(try foo.restore()) XCTAssertEqual(foo.int, 1) XCTAssertEqual(foo.path, AbsolutePath("/hello")) // Modify state's schema version. let newJSON = JSON(["version": 2]) try fs.writeFileContents(stateFile, bytes: newJSON.toBytes()) do { _ = try foo.restore() XCTFail() } catch { let error = String(describing: error) XCTAssert(error.contains("unsupported schema version 2"), error) } } func testBackwardsCompatibleStateFile() throws { // Test that we don't overwrite the json in case we find keys we don't need. let fs = InMemoryFileSystem() let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json") // Create and save v2 object. let v2 = Bar.V2(int: 100, string: "hello", fileSystem: fs) try v2.persistence.saveState(v2) // Restore v1 object from v2 file. let v1 = Bar.V1(int: 1, fileSystem: fs) XCTAssertEqual(v1.int, 1) XCTAssertTrue(try v1.persistence.restoreState(v1)) XCTAssertEqual(v1.int, 100) // Check state file still has the old "string" key. let json = try JSON(bytes: fs.readFileContents(stateFile)) XCTAssertEqual("hello", try json.get("object").get("string")) // Update a value in v1 object and save. v1.int = 500 try v1.persistence.saveState(v1) v2.string = "" // Now restore v2 and expect string to be present as well as the updated int value. XCTAssertTrue(try v2.persistence.restoreState(v2)) XCTAssertEqual(v2.int, 500) XCTAssertEqual(v2.string, "hello") } func testCanLoadFromOldSchema() throws { let fs = InMemoryFileSystem() let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json") try fs.writeFileContents(stateFile) { $0 <<< """ { "version": 0, "object": { "old_path": "/oldpath", "old_int": 4 } } """ } let foo = Foo(int: 1, path: AbsolutePath("/hello"), fileSystem: fs) XCTAssertEqual(foo.path, AbsolutePath("/hello")) XCTAssertEqual(foo.int, 1) // Load from an older but supported schema state file. XCTAssertTrue(try foo.restore()) XCTAssertEqual(foo.path, AbsolutePath("/oldpath")) XCTAssertEqual(foo.int, 4) } }
3b30f753d0f6bc133c2e4d94696c4709
29.768116
91
0.574973
false
false
false
false
maxoly/PulsarKit
refs/heads/master
PulsarKit/PulsarKitTests/Models/User.swift
mit
1
// // User.swift // PulsarKitTests // // Created by Massimo Oliviero on 14/08/2018. // Copyright © 2019 Nacoon. All rights reserved. // import Foundation struct User: Hashable { let id: Int let name: String init(id: Int, name: String = "") { self.id = id self.name = name } static func == (lhs: User, rhs: User) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } }
6c5b20e2e23af776b21042197e2b5e50
17.074074
51
0.55123
false
false
false
false
praxent/PRGalleryView
refs/heads/master
PRGalleryView.swift
mit
1
// // PRGalleryView.swift // ⌘ Praxent // // A single view type which accepts video, GIF and photo media for display in a gallery. // // Created by Albert Martin on 9/25/15. // Copyright © 2015 Praxent. All rights reserved. // import AVFoundation import AVKit import MobileCoreServices import FLAnimatedImage public enum PRGalleryType { case Image case Animated case Video } public class PRGalleryView: UIView { public let imageView: FLAnimatedImageView = FLAnimatedImageView() public let videoController: AVPlayerViewController = AVPlayerViewController() public var type: PRGalleryType = .Image public var shouldAllowPlayback: Bool = true public var thumbnailInSeconds: Float64 = 5 public var branded: Bool = false public var overlayLandscape: UIImage = UIImage() public var overlayPortrait: UIImage = UIImage() /// /// Load any supported media into the gallery view by URL. /// public var media: NSURL! { didSet { if (self.media == nil || self.media.path == nil) { image = UIImage() return } type = typeForPath(self.media.path!) switch type { case .Video: image = nil animatedImage = nil if (shouldAllowPlayback) { player = AVPlayer(URL: self.media) return } image = self.imageThumbnailFromVideo(self.media) break case .Animated: if (shouldAllowPlayback) { animatedImage = self.animatedImageFromPath(self.media.path!) return } image = self.imageFromPath(self.media.path!) break default: image = self.imageFromPath(self.media.path!) } } } /// /// Helper function to clean up the view stack after new media is loaded. /// /// - parameter type: The type of loaded media; non-necessary views will be removed. /// public func cleanupView(type: PRGalleryType) { if (type == .Video) { videoController.view.frame = bounds imageView.removeFromSuperview() addSubview(videoController.view) return } imageView.frame = bounds imageView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] videoController.view.removeFromSuperview() videoController.player = AVPlayer() addSubview(imageView) } /// /// Determines the type of file being loaded in order to use the appropriate view. /// /// - parameter path: The path to the file. /// - returns: `video` for any media requiring playback controls or `gif`/`photo` for images. /// public func typeForPath(path: NSString) -> PRGalleryType { let utiTag = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.pathExtension, nil)! let utiType = utiTag.takeRetainedValue() as String if (AVURLAsset.audiovisualTypes().contains(String(utiType))) { return .Video } if (String(utiType) == "com.compuserve.gif") { return .Animated } return .Image } /// // MARK: Positioning and Measurement /// public func sizeOfMedia() -> CGSize { if (type == .Video) { return videoController.view.frame.size } var scale: CGFloat = 1.0; if (imageView.image!.size.width > imageView.image!.size.height) { scale = imageView.frame.size.width / imageView.image!.size.width } else { scale = imageView.frame.size.height / imageView.image!.size.height } return CGSizeMake(imageView.image!.size.width * scale, imageView.image!.size.height * scale) } /// // MARK: Playback /// /// /// Start playback of a video or animated GIF. /// public func play() { if (type != .Video && type != .Animated) { return } switch type { case .Video: if (imageView.image != nil) { player = AVPlayer(URL: self.media) } player!.play() case .Animated: if (imageView.animatedImage == nil) { animatedImage = self.animatedImageFromPath(media!.path!) image = nil } imageView.startAnimating() default: break } } /// /// Pause playback (resumable) of a video or animated GIF. /// public func pause() { if (type != .Video && type != .Animated) { return } imageView.stopAnimating() player!.pause() } /// /// Stop playback of a video or animated GIF. Returns the video to it's static /// thumbnail representation if `shouldAllowPlayback` is `false`. /// public func stop() { if (type != .Video && type != .Animated) { return } if (type == .Video && !shouldAllowPlayback && videoController.player?.currentItem != nil) { image = self.imageThumbnailFromVideo(self.media) } imageView.stopAnimating() player!.pause() } /// // MARK: Animated GIF /// public var animatedImage: FLAnimatedImage? { set { imageView.animatedImage = newValue cleanupView(.Image) } get { return imageView.animatedImage } } /// /// Creates an instance of FLAnimatedImage for animated GIF images. /// /// - parameter path: The path to the file. /// - returns: `FLAnimatedImage` /// public func animatedImageFromPath(path: String) -> FLAnimatedImage { let image = FLAnimatedImage(animatedGIFData: NSData(contentsOfFile: path)) if (image == nil) { print("Unable to create animated image from path", path) return FLAnimatedImage() } return image! } /// // MARK: Static Image /// public var image: UIImage? { set { imageView.image = newValue cleanupView(.Image) } get { return imageView.image } } /// /// Creates a UIImage for static images. /// /// - parameter path: The path to the file. /// - returns: `UIImage` /// public func imageFromPath(path: String) -> UIImage { let image = UIImage(contentsOfFile: path) if (image == nil) { print("Unable to create image from path", path) return UIImage() } if (branded) { return image!.branded(overlayLandscape, portrait: overlayPortrait) } return image! } /// // MARK: Video /// public var player: AVPlayer? { set { videoController.player = newValue cleanupView(.Video) } get { return videoController.player } } /// /// Returns a thumbnail image for display when playback is disabled. /// /// - parameter url: The URL of the file. /// - returns: `UIImage` /// public func imageThumbnailFromVideo(url: NSURL) -> UIImage { let video = AVURLAsset(URL: url) let time = CMTimeMakeWithSeconds(thumbnailInSeconds, 60) let thumbGenerator = AVAssetImageGenerator(asset: video) thumbGenerator.appliesPreferredTrackTransform = true do { let thumbnail = try thumbGenerator.copyCGImageAtTime(time, actualTime: nil) return UIImage(CGImage: thumbnail) } catch { print("Unable to generate thumbnail from video", url.path) return UIImage() } } }
626f2659dc553b43167198e21fec8ff4
24.960526
114
0.561581
false
false
false
false
hayksaakian/OverRustleiOS
refs/heads/master
OverRustleiOS/ViewController.swift
mit
1
// // ViewController.swift // OverRustleiOS // // Created by Maxwell Burggraf on 8/8/15. // Copyright (c) 2015 Maxwell Burggraf. All rights reserved. // import UIKit import AVFoundation import MediaPlayer import SocketIO class ViewController: UIViewController, UIWebViewDelegate, UIGestureRecognizerDelegate { func gestureRecognizer(UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool { return true } @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var webView: UIWebView! var player = MPMoviePlayerController() @IBOutlet weak var backButton: UIButton! var socket = SocketIOClient(socketURL: "http://api.overrustle.com", opts: ["nsp": "/streams"]) var api_data:NSDictionary = NSDictionary() var isFullWidthPlayer: Bool = true func webViewDidFinishLoad(webView: UIWebView) { if(webView.request?.URL != NSURL(string: "http://www.destiny.gg/embed/chat")){ println("showing button") backButton.bringSubviewToFront(self.view) backButton.hidden = false } else { backButton.hidden = true } } @IBAction func backPressed(sender: AnyObject) { webView.goBack() } @IBAction func strimsPressed(sender: AnyObject) { var title = "Select Strim" if let viewers = api_data["viewercount"] as? Int { println("Rustlers:", viewers) title = "\(viewers) Rustlers Watching" } var list = NSArray() if let stream_list = api_data["stream_list"] as? NSArray { list = stream_list println("Stream List", stream_list) } let rustleActionSheet = UIAlertController(title: title, message: nil, preferredStyle:UIAlertControllerStyle.ActionSheet) rustleActionSheet.popoverPresentationController?.sourceView = self.view rustleActionSheet.popoverPresentationController?.sourceRect = CGRectMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0, 1.0, 1.0) var i : Int for i = 0; i<list.count; i++ { let stream = list[i] as! NSDictionary if let channel = stream["channel"] as? String, let platform = stream["platform"] as? String, let imageURLString = stream["image_url"] as? String { var button_title = "\(channel) on \(platform)" if let name = stream["name"] as? String { button_title = "\(name) via \(button_title)" } let action = UIAlertAction(title:button_title, style:UIAlertActionStyle.Default, handler:{ action in println("loading", channel, "from", platform) self.openStream(platform, channel: channel) }) if let imageURL = NSURL(string: imageURLString) { if let imageData = NSData(contentsOfURL: imageURL) { let image = UIImage(data: imageData, scale: 10) let originalImage = image?.imageWithRenderingMode(.AlwaysOriginal) action.setValue(originalImage, forKey: "image") } } rustleActionSheet.addAction(action) } } rustleActionSheet.addAction(UIAlertAction(title:"Cancel", style:UIAlertActionStyle.Cancel, handler:nil)) presentViewController(rustleActionSheet, animated:true, completion:nil) } func openStream(platform:String, channel:String) { var s = RustleStream() switch platform { case "ustream": s = UStream() case "twitch": s = Twitch() case "youtube": s = YouTubeLive() case "hitbox": s = Hitbox() case "azubu": s = Azubu() case "mlg": s = MLG() default: println(platform, "is not supported right now") } s.channel = channel player.contentURL = s.getStreamURL() player.play() } func closeSocket() { self.socket.disconnect(fast: false) } func openSocket() { self.socket.connect() } func addHandlers() { self.socket.onAny { println("Got event: \($0.event)") } self.socket.on("strims") { data, ack in println("in strims") if let new_api_data = data?[0] as? NSDictionary { self.api_data = new_api_data if let viewers = self.api_data["viewercount"] as? Int { println("Rustlers:", viewers) } if let stream_list = self.api_data["stream_list"] as? NSArray { println("Good Stream List") } } } } func handleTap(sender: UITapGestureRecognizer) { println("tapped video") if sender.state == .Ended { // handling code fullscreenButtonClick() } } override func viewDidLoad() { super.viewDidLoad() self.addHandlers() self.socket.connect() backButton.hidden = true let chatURL = NSURL(string: "http://www.destiny.gg/embed/chat") let chatURLRequestObj = NSURLRequest(URL: chatURL!) webView.loadRequest(chatURLRequestObj) var testStream = Twitch() testStream.channel = "vgbootcamp" let videoStreamURL = testStream.getStreamURL() player = MPMoviePlayerController(contentURL: videoStreamURL) player.controlStyle = MPMovieControlStyle.None let anyTap = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) anyTap.delegate = self player.view.addGestureRecognizer(anyTap) //The player takes up 40% of the screen //(this can (and probably should be) changed later player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40) self.view.addSubview(player.view) NSNotificationCenter.defaultCenter().addObserver(self, selector: "fullscreenButtonClick", name: MPMoviePlayerDidEnterFullscreenNotification, object: nil) self.isFullWidthPlayer = true player.play() } func fullscreenButtonClick(){ println("fullscreen button clicked") if(isFullWidthPlayer){ //make the player a mini player //self.player.setFullscreen(false, animated: true) //self.player.controlStyle = MPMovieControlStyle.Fullscreen player.view.frame = CGRectMake(self.view.frame.size.width * 0.50, 0, self.view.frame.size.width * 0.50, self.view.frame.size.height * 0.20) isFullWidthPlayer = false } else { //make the mini player a full width player again //self.player.setFullscreen(false, animated: true) player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40) //self.player.controlStyle = MPMovieControlStyle.Fullscreen isFullWidthPlayer = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { var deviceOrientation = UIDevice.currentDevice().orientation if(UIDeviceOrientationIsLandscape(deviceOrientation)){ if(isFullWidthPlayer){ self.player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) } else { self.player.view.frame = CGRectMake( 2 * self.view.frame.size.width / 3, 0, self.view.frame.size.width / 3, self.view.frame.size.width / 3 * 0.5625) } } else { if(isFullWidthPlayer){ self.player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40) webView.frame.size.width = self.view.frame.size.width webView.frame.origin.x = 0 webView.frame.origin.y = self.view.frame.size.height * 0.40 println("viewDidLayoutSubviews") //The webview frame is the other 60% of the screen, minus the space that the toolbar takes up webView.frame.size.height = self.view.frame.size.height * 0.60 - toolbar.frame.size.height } else { player.view.frame = CGRectMake(self.view.frame.size.width * 0.50, 0, self.view.frame.size.width * 0.50, self.view.frame.size.height * 0.20) webView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) } } } }
cce95c9f4037bfeb39b06824f1ed206b
36.188525
164
0.58585
false
false
false
false
BlurredSoftware/BSWInterfaceKit
refs/heads/develop
Tests/BSWInterfaceKitTests/Suite/Profiles/ClassicProfileViewController.swift
mit
1
// // Created by Pierluigi Cifani on 03/05/16. // Copyright © 2018 TheLeftBit SL. All rights reserved. // #if canImport(UIKit) import UIKit import Task import BSWFoundation import BSWInterfaceKit public enum ClassicProfileEditKind { case nonEditable case editable(UIBarButtonItem) public var isEditable: Bool { switch self { case .editable(_): return true default: return false } } } open class ClassicProfileViewController: TransparentNavBarViewController, AsyncViewModelPresenter { public init(dataProvider: Task<ClassicProfileViewModel>) { self.dataProvider = dataProvider super.init(nibName:nil, bundle:nil) } public init(viewModel: ClassicProfileViewModel) { self.dataProvider = Task(success: viewModel) super.init(nibName:nil, bundle:nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } enum Constants { static let SeparatorSize = CGSize(width: 30, height: 1) static let LayoutMargins = UIEdgeInsets(uniform: 8) static let PhotoGalleryRatio = CGFloat(0.78) } public var dataProvider: Task<ClassicProfileViewModel>! open var editKind: ClassicProfileEditKind = .nonEditable private let photoGallery = PhotoGalleryView() private let titleLabel = UILabel.unlimitedLinesLabel() private let detailsLabel = UILabel.unlimitedLinesLabel() private let extraDetailsLabel = UILabel.unlimitedLinesLabel() private let separatorView: UIView = { let view = UIView() NSLayoutConstraint.activate([ view.widthAnchor.constraint(equalToConstant: Constants.SeparatorSize.width), view.heightAnchor.constraint(equalToConstant: Constants.SeparatorSize.height) ]) view.backgroundColor = UIColor.lightGray return view }() open override func viewDidLoad() { super.viewDidLoad() //Add the photoGallery photoGallery.delegate = self scrollableStackView.addArrangedSubview(photoGallery) NSLayoutConstraint.activate([ photoGallery.heightAnchor.constraint(equalTo: photoGallery.widthAnchor, multiplier: Constants.PhotoGalleryRatio), photoGallery.widthAnchor.constraint(equalTo: scrollableStackView.widthAnchor) ]) scrollableStackView.addArrangedSubview(titleLabel, layoutMargins: Constants.LayoutMargins) scrollableStackView.addArrangedSubview(detailsLabel, layoutMargins: Constants.LayoutMargins) scrollableStackView.addArrangedSubview(separatorView, layoutMargins: Constants.LayoutMargins) scrollableStackView.addArrangedSubview(extraDetailsLabel, layoutMargins: Constants.LayoutMargins) //Add the rightBarButtonItem switch editKind { case .editable(let barButton): navigationItem.rightBarButtonItem = barButton default: break } fetchData() } override open var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } //MARK:- Private open func fetchData() { showLoader() dataProvider.upon(.main) { [weak self] result in guard let strongSelf = self else { return } strongSelf.hideLoader() switch result { case .failure(let error): strongSelf.showErrorMessage("Error fetching data", error: error) case .success(let viewModel): strongSelf.configureFor(viewModel: viewModel) } } } open func configureFor(viewModel: ClassicProfileViewModel) { photoGallery.photos = viewModel.photos titleLabel.attributedText = viewModel.titleInfo detailsLabel.attributedText = viewModel.detailsInfo extraDetailsLabel.attributedText = viewModel.extraInfo.joinedStrings() } } //MARK:- PhotoGalleryViewDelegate extension ClassicProfileViewController: PhotoGalleryViewDelegate { public func didTapPhotoAt(index: Int, fromView: UIView) { guard #available(iOS 13, *) else { return } guard let viewModel = dataProvider.peek()?.value else { return } let gallery = PhotoGalleryViewController( photos: viewModel.photos, initialPageIndex: index, allowShare: false ) gallery.modalPresentationStyle = .overFullScreen gallery.delegate = self present(gallery, animated: true, completion: nil) } } //MARK:- PhotoGalleryViewControllerDelegate @available(iOS 13, *) extension ClassicProfileViewController: PhotoGalleryViewControllerDelegate { public func photoGalleryController(_ photoGalleryController: PhotoGalleryViewController, willDismissAtPageIndex index: Int) { photoGallery.scrollToPhoto(atIndex: index) dismiss(animated: true, completion: nil) } } #endif
7521d19505c2f946dd2c7fc5d8f08493
32.993289
129
0.676604
false
false
false
false
johndpope/ClangWrapper.Swift
refs/heads/master
ClangWrapper/Token.swift
mit
1
// // Token.swift // ClangWrapper // // Created by Hoon H. on 2015/01/21. // Copyright (c) 2015 Eonil. All rights reserved. // public struct Token { public var kind:TokenKind { get { let r = clang_getTokenKind(raw) return TokenKind.fromRaw(raw: r) } } public var spelling:String { get { let s = clang_getTokenSpelling(sequence.rawtu, raw) let s1 = toSwiftString(s, true) return s1! } } public var location:SourceLocation { get { let r = clang_getTokenLocation(sequence.rawtu, raw) return SourceLocation(raw: r) } } public var extent:SourceRange { get { let r = clang_getTokenExtent(sequence.rawtu, raw) return SourceRange(raw: r) } } //// let sequence:TokenSequence let index:Int var raw:CXToken { get { return sequence.rawptr[index] } } }
fd15a667d025d9d5ab6cc2239971f36e
13.714286
54
0.650485
false
false
false
false
MaartenBrijker/project
refs/heads/back
project/External/AudioKit-master/AudioKit/Common/Nodes/Effects/Filters/Low Pass Butterworth Filter/AKLowPassButterworthFilter.swift
apache-2.0
1
// // AKLowPassButterworthFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// These filters are Butterworth second-order IIR filters. They offer an almost /// flat passband and very good precision and stopband attenuation. /// /// - parameter input: Input node to process /// - parameter cutoffFrequency: Cutoff frequency. (in Hertz) /// public class AKLowPassButterworthFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKLowPassButterworthFilterAudioUnit? internal var token: AUParameterObserverToken? private var cutoffFrequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet(newValue) { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Cutoff frequency. (in Hertz) public var cutoffFrequency: Double = 1000 { willSet(newValue) { if cutoffFrequency != newValue { if internalAU!.isSetUp() { cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter cutoffFrequency: Cutoff frequency. (in Hertz) /// public init( _ input: AKNode, cutoffFrequency: Double = 1000) { self.cutoffFrequency = cutoffFrequency var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x62746c70 /*'btlp'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKLowPassButterworthFilterAudioUnit.self, asComponentDescription: description, name: "Local AKLowPassButterworthFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKLowPassButterworthFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.cutoffFrequencyParameter!.address { self.cutoffFrequency = Double(value) } } } internalAU?.cutoffFrequency = Float(cutoffFrequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
28acf3bea9f97b2a1016efab4579c500
31.233333
99
0.633661
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Tabs/HLHotelDetailPhotosTabCell.swift
mit
1
class HLHotelDetailPhotosTabCell: HLHotelDetailsTabCell, HLPhotoGridViewDelegate { var photoGrid: HLPhotoGridView! var hotel: HDKHotel! { didSet { setupContent() } } override func createTabContentViewAndScrollView() -> (UIView, UIScrollView) { let photoGrid = HLPhotoGridView(frame:CGRect.zero) photoGrid.translatesAutoresizingMaskIntoConstraints = false photoGrid.backgroundColor = UIColor.clear photoGrid.delegate = self photoGrid.collectionView.scrollsToTop = false self.photoGrid = photoGrid return (photoGrid, photoGrid.collectionView) } func setupContent() { let thumbSize = HLPhotoManager.calculateThumbSizeForColumnsCount(delegate?.photosColumnsCount() ?? 1, containerWidth: bounds.width) photoGrid.updateDataSource(withHotel: hotel, imageSize: thumbSize, thumbSize: thumbSize, useThumbs: true) } func setSelectedStyleForPhotoIndex(_ photoIndex: Int) { photoGrid.collectionView.selectItem(at: IndexPath(item: photoIndex, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition()) } // MARK: - Public func photoCellRect(_ indexPath: IndexPath) -> CGRect { var rect = photoGrid.collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? CGRect.zero rect = convert(rect, from: photoGrid.collectionView) return rect } // MARK: HLPhotoGridView delegate func columnCount() -> Int { return delegate?.photosColumnsCount() ?? 0 } func columnInset() -> CGFloat { return 1.0 } func photoCollectionViewDidSelectPhotoAtIndex(_ index: Int) { delegate?.showPhotoAtIndex(index) } func photoGridViewCellDidSelect(_ cell: HLPhotoScrollCollectionCell) { delegate?.photoGridViewCellDidSelect?(cell) } func photoGridViewCellDidHighlight(_ cell: HLPhotoScrollCollectionCell) { delegate?.photoGridViewCellDidHighlight?(cell) } }
6d24e7a1a442afe2e787c518774379df
31.596774
156
0.698664
false
false
false
false
sammyd/UnleashingSwift_bristech2015
refs/heads/master
UnleashingSwift.playground/Pages/GettingStarted.xcplaygroundpage/Contents.swift
mit
1
//: # Unleashing Swift //: This page of the playground serves to get you up to speed with Swift concepts as quickly as possible //: ## Mutability let twelve = 12 //twelve = 13 var thirteen = 13 thirteen = 12 //thirteen = 13.0 //: ## Value / Reference types var title = "This is a string" var secondTitle = title secondTitle += ", which has just got longer" print(title) print(secondTitle) //: ## Functions func square(value: Int) -> Int { return value * value } square(4) func exponentiate(value: Int, power: Int) -> Int { return power > 0 ? value * exponentiate(value, power: power-1) : 1 } exponentiate(2, power: 4) func curryPower(power: Int)(_ value: Int) -> Int { return exponentiate(value, power: power) } let cube = curryPower(3) cube(3) //: ## Extensions extension Int { func toThePower(power: Int) -> Int { return exponentiate(self, power: power) } } 2.toThePower(5) //: ## Closures func asyncHello(name: String, callback: (reply: String) -> ()) { callback(reply: "Hello \(name)") } asyncHello("sam") { let shouty = $0.uppercaseString print(shouty) } //: ## Functional Tinge let scores = [1,2,4,5,3,5,7,2,2,6,8,2,3,6,2,3,5] let cubedScores = scores.map { cube($0) } cubedScores let largeScores = scores.filter { $0 > 5 } largeScores let meanScore = scores.reduce(0) { $0 + Double($1) } / Double(scores.count) meanScore //: [Next](@next)
9c18a32a4c5777e6db740bfb541dd1f8
15.103448
104
0.655246
false
false
false
false
exyte/Macaw
refs/heads/master
MacawTests/TestUtils.swift
mit
1
import Foundation #if os(OSX) @testable import MacawOSX #endif #if os(iOS) @testable import Macaw #endif class TestUtils { class func compareWithReferenceObject(_ fileName: String, referenceObject: AnyObject) -> Bool { // TODO: this needs to be replaced with SVG tests return true } class func prepareParametersList(_ mirror: Mirror) -> [(String, String)] { var result: [(String, String)] = [] for (_, attribute) in mirror.children.enumerated() { if let label = attribute.label , (label == "_value" || label.first != "_") && label != "contentsVar" { result.append((label, String(describing: attribute.value))) result.append(contentsOf: prepareParametersList(Mirror(reflecting: attribute.value))) } } return result } class func prettyFirstDifferenceBetweenStrings(s1: String, s2: String) -> String { return prettyFirstDifferenceBetweenNSStrings(s1: s1 as NSString, s2: s2 as NSString) as String } } /// Find first differing character between two strings /// /// :param: s1 First String /// :param: s2 Second String /// /// :returns: .DifferenceAtIndex(i) or .NoDifference fileprivate func firstDifferenceBetweenStrings(s1: NSString, s2: NSString) -> FirstDifferenceResult { let len1 = s1.length let len2 = s2.length let lenMin = min(len1, len2) for i in 0..<lenMin { if s1.character(at: i) != s2.character(at: i) { return .DifferenceAtIndex(i) } } if len1 < len2 { return .DifferenceAtIndex(len1) } if len2 < len1 { return .DifferenceAtIndex(len2) } return .NoDifference } /// Create a formatted String representation of difference between strings /// /// :param: s1 First string /// :param: s2 Second string /// /// :returns: a string, possibly containing significant whitespace and newlines fileprivate func prettyFirstDifferenceBetweenNSStrings(s1: NSString, s2: NSString) -> NSString { let firstDifferenceResult = firstDifferenceBetweenStrings(s1: s1, s2: s2) return prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: firstDifferenceResult, s1: s1, s2: s2) } /// Create a formatted String representation of a FirstDifferenceResult for two strings /// /// :param: firstDifferenceResult FirstDifferenceResult /// :param: s1 First string used in generation of firstDifferenceResult /// :param: s2 Second string used in generation of firstDifferenceResult /// /// :returns: a printable string, possibly containing significant whitespace and newlines fileprivate func prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: FirstDifferenceResult, s1: NSString, s2: NSString) -> NSString { func diffString(index: Int, s1: NSString, s2: NSString) -> NSString { let markerArrow = "\u{2b06}" // "⬆" let ellipsis = "\u{2026}" // "…" /// Given a string and a range, return a string representing that substring. /// /// If the range starts at a position other than 0, an ellipsis /// will be included at the beginning. /// /// If the range ends before the actual end of the string, /// an ellipsis is added at the end. func windowSubstring(s: NSString, range: NSRange) -> String { let validRange = NSMakeRange(range.location, min(range.length, s.length - range.location)) let substring = s.substring(with: validRange) let prefix = range.location > 0 ? ellipsis : "" let suffix = (s.length - range.location > range.length) ? ellipsis : "" return "\(prefix)\(substring)\(suffix)" } // Show this many characters before and after the first difference let windowPrefixLength = 10 let windowSuffixLength = 10 let windowLength = windowPrefixLength + 1 + windowSuffixLength let windowIndex = max(index - windowPrefixLength, 0) let windowRange = NSMakeRange(windowIndex, windowLength) let sub1 = windowSubstring(s: s1, range: windowRange) let sub2 = windowSubstring(s: s2, range: windowRange) let markerPosition = min(windowSuffixLength, index) + (windowIndex > 0 ? 1 : 0) let markerPrefix = String(repeating: " ", count: markerPosition) let markerLine = "\(markerPrefix)\(markerArrow)" return "Difference at index \(index):\n\(sub1)\n\(sub2)\n\(markerLine)" as NSString } switch firstDifferenceResult { case .NoDifference: return "No difference" case .DifferenceAtIndex(let index): return diffString(index: index, s1: s1, s2: s2) } } /// Result type for firstDifferenceBetweenStrings() public enum FirstDifferenceResult { /// Strings are identical case NoDifference /// Strings differ at the specified index. /// /// This could mean that characters at the specified index are different, /// or that one string is longer than the other case DifferenceAtIndex(Int) } extension FirstDifferenceResult: CustomStringConvertible { /// Textual representation of a FirstDifferenceResult public var description: String { switch self { case .NoDifference: return "NoDifference" case .DifferenceAtIndex(let index): return "DifferenceAtIndex(\(index))" } } /// Textual representation of a FirstDifferenceResult for debugging purposes public var debugDescription: String { return self.description } }
dbf0a4d3aaf2d68f04615d639c4b05b5
33.840764
145
0.678062
false
false
false
false
Dwarven/ShadowsocksX-NG
refs/heads/develop
MoyaRefreshToken/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift
apache-2.0
4
// // Completable+AndThen.swift // RxSwift // // Created by Krunoslav Zaher on 7/2/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never { /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Single<E>) -> Single<E> { let completable = self.primitiveSequence.asObservable() return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> { let completable = self.primitiveSequence.asObservable() return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen(_ second: Completable) -> Completable { let completable = self.primitiveSequence.asObservable() return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable())) } /** Concatenates the second observable sequence to `self` upon successful termination of `self`. - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) - parameter second: Second observable sequence. - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. */ public func andThen<E>(_ second: Observable<E>) -> Observable<E> { let completable = self.primitiveSequence.asObservable() return ConcatCompletable(completable: completable, second: second.asObservable()) } } final private class ConcatCompletable<Element>: Producer<Element> { fileprivate let _completable: Observable<Never> fileprivate let _second: Observable<Element> init(completable: Observable<Never>, second: Observable<Element>) { self._completable = completable self._second = second } override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O : ObserverType, O.E == Element { let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final private class ConcatCompletableSink<O: ObserverType> : Sink<O> , ObserverType { typealias E = Never typealias Parent = ConcatCompletable<O.E> private let _parent: Parent private let _subscription = SerialDisposable() init(parent: Parent, observer: O, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .error(let error): self.forwardOn(.error(error)) self.dispose() case .next: break case .completed: let otherSink = ConcatCompletableSinkOther(parent: self) self._subscription.disposable = self._parent._second.subscribe(otherSink) } } func run() -> Disposable { let subscription = SingleAssignmentDisposable() self._subscription.disposable = subscription subscription.setDisposable(self._parent._completable.subscribe(self)) return self._subscription } } final private class ConcatCompletableSinkOther<O: ObserverType> : ObserverType { typealias E = O.E typealias Parent = ConcatCompletableSink<O> private let _parent: Parent init(parent: Parent) { self._parent = parent } func on(_ event: Event<O.E>) { self._parent.forwardOn(event) if event.isStopEvent { self._parent.dispose() } } }
7f1953ac79ef04be466ea6dd1cfa8c25
36.181818
148
0.682559
false
false
false
false
TLOpenSpring/TLTranstionLib-swift
refs/heads/master
Example/TLTranstionLib-swift/BaseTabController.swift
mit
1
// // BaseTabController.swift // TLTranstionLib-swift // // Created by Andrew on 16/7/22. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit class BaseTabController: UIViewController,UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() let attr1 = getAttibutes() let attr2 = getActiveAttibutes() self.tabBarItem.setTitleTextAttributes(attr1, forState: .Normal) self.tabBarItem.setTitleTextAttributes(attr2, forState: .Selected) // Do any additional setup after loading the view. } func getAttibutes() -> [String:AnyObject] { let font = UIFont.systemFontOfSize(18) let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.grayColor()] return attrs } func getActiveAttibutes() -> [String:AnyObject] { let font = UIFont.systemFontOfSize(18) let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.redColor()] return attrs } }
41d6e83356b274f2123080452adfdd54
27.435897
74
0.651939
false
false
false
false
mcomella/prox
refs/heads/master
Prox/Prox/PlaceDetails/MapButton.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class MapButton: UIButton { private let shadowRadius: CGFloat = 3 override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } let shadow = NSShadow() shadow.shadowColor = Colors.detailsViewMapButtonShadow shadow.shadowOffset = CGSize(width: 0.5, height: 0.75) shadow.shadowBlurRadius = shadowRadius // Drawing code let ovalPath = UIBezierPath(ovalIn: CGRect(x: (shadowRadius / 2) - shadow.shadowOffset.width, y: (shadowRadius / 2) - shadow.shadowOffset.height, width: rect.width - shadowRadius, height: rect.height - shadowRadius)) context.saveGState() context.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: (shadow.shadowColor as! UIColor).cgColor) Colors.detailsViewMapButtonBackground.setFill() ovalPath.fill() context.restoreGState() } }
35b7ce1706d5c0e150d31ec03724fa88
40.035714
225
0.693647
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILGen/instrprof_basic.swift
apache-2.0
2
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -profile-generate %s | FileCheck %s // CHECK: sil hidden @[[F_EMPTY:.*empty.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_EMPTY]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 1 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func empty() { // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: sil hidden @[[F_BASIC:.*basic.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_BASIC]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 6 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func basic(a : Int32) { // CHECK: builtin "int_instrprof_increment" if a == 0 { } // CHECK: builtin "int_instrprof_increment" if a != 0 { } else { } // CHECK: builtin "int_instrprof_increment" while a == 0 { } // CHECK: builtin "int_instrprof_increment" for var i: Int32 = 0; i < a; ++i { } // CHECK: builtin "int_instrprof_increment" for i in 1...a { } // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: sil hidden @[[F_THROWING_NOP:.*throwing_nop.*]] : func throwing_nop() throws {} // CHECK: sil hidden @[[F_EXCEPTIONS:.*exceptions.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_EXCEPTIONS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 3 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func exceptions() { do { try throwing_nop() // CHECK: builtin "int_instrprof_increment" } catch { // CHECK: builtin "int_instrprof_increment" return } // CHECK-NOT: builtin "int_instrprof_increment" }
53d443c427a54a6865201a88449b1357
34.920635
127
0.579761
false
false
false
false
Derek-Chiu/Mr-Ride-iOS
refs/heads/master
Mr-Ride-iOS/Mr-Ride-iOS/HistoryTableViewController.swift
mit
1
// // HistoryTableViewController.swift // Mr-Ride-iOS // // Created by Derek on 6/6/16. // Copyright © 2016 AppWorks School Derek. All rights reserved. // import UIKit class HistoryTableViewController: UITableViewController { let cellIdentifier = "HistoryCell" var allRecord = [Run]() var sectionByMonth = [NSDateComponents: [Run]]() var keyOfMonth = [NSDateComponents]() var currentSection = -1 weak var selectedDelegate: CellSelectedDelegate? weak var chartDataSource: ChartDataSource? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false tableView.registerNib(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier) tableView.frame = view.bounds fetchData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return keyOfMonth.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let count = sectionByMonth[keyOfMonth[section]]?.count { return count } print("error in section number") return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! HistoryTableViewCell let run = sectionByMonth[keyOfMonth[indexPath.section]]![indexPath.row] if currentSection != indexPath.section { print("section number == \(indexPath.section)") chartDataSource!.setupChartData(sectionByMonth[keyOfMonth[indexPath.section]]!) currentSection = indexPath.section } cell.backgroundColor = UIColor.mrDarkSlateBlue85Color() cell.runID = run.id! cell.labelDistance.text = String(format: "%.2f km", Double(run.distance!) / 1000) cell.labelDate.text = String(format: "%2d", NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: run.timestamp!).day) if let counter = run.during as? Double{ let second = Int(counter) % 60 let minutes = Int(counter / 60) % 60 let hours = Int(counter / 60 / 60) % 99 // print(minuteSecond) cell.labelTime.text = String(format: "%02d:%02d:%02d", hours, minutes, second) } return cell } func fetchData() { print("fetchData") if LocationRecorder.getInstance().fetchData() != nil { allRecord = LocationRecorder.getInstance().fetchData()! } else { print("no record") } for run in allRecord { let currentComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: run.timestamp!) if sectionByMonth[currentComponents] != nil { sectionByMonth[currentComponents]?.append(run) } else { sectionByMonth[currentComponents] = [run] keyOfMonth.append(currentComponents) } } } // MARK: - Header part // override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // let header = UIView() // header.layer.cornerRadius = 2.0 // header.backgroundColor = UIColor.whiteColor() // header.tintColor = UIColor.mrDarkSlateBlueColor() // } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // "MMM yyyy" return "\(keyOfMonth[section].month), \(keyOfMonth[section].year) " } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // open statistic page print(indexPath.row) guard let runID = sectionByMonth[keyOfMonth[indexPath.section]]?[indexPath.row].id else { return } selectedDelegate?.cellDidSelected(runID) } }
a88a01bd1a29a216d160bd8ba517dcb1
33.734848
146
0.627481
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
SwiftyEcharts/Models/Graphic/TextGraphic.swift
mit
1
// // TextGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 11/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 文本类型的 `Graphic` public final class TextGraphic: Graphic { /// 文本样式 public final class Style: GraphicStyle { /// 文本块文字。可以使用 \n 来换行。 public var text: String? /// 图形元素的左上角在父节点坐标系(以父节点左上角为原点)中的横坐标值。 public var x: Float? /// 图形元素的左上角在父节点坐标系(以父节点左上角为原点)中的纵坐标值。 public var y: Float? /// 字体大小、字体类型、粗细、字体样式。格式参见 css font。 /// 例如: /// // size | family /// font: '2em "STHeiti", sans-serif' /// /// // style | weight | size | family /// font: 'italic bolder 16px cursive' /// /// // weight | size | family /// font: 'bolder 2em "Microsoft YaHei", sans-serif' public var font: String? /// 水平对齐方式,取值:'left', 'center', 'right'。 /// 如果为 'left',表示文本最左端在 x 值上。如果为 'right',表示文本最右端在 x 值上。 public var textAlign: Align? /// 垂直对齐方式,取值:'top', 'middle', 'bottom'。 public var textVertical: VerticalAlign? /// MARK: GraphicStyle public var fill: Color? public var stroke: Color? public var lineWidth: Float? public var shadowBlur: Float? public var shadowOffsetX: Float? public var shadowOffsetY: Float? public var shadowColor: Color? public init() {} } /// MARK: Graphic public var type: GraphicType { return .text } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 文本样式 public var style: Style? public init() {} } extension TextGraphic.Style: Enumable { public enum Enums { case text(String), x(Float), y(Float), font(String), textAlign(Align), textVertical(VerticalAlign), fill(Color), stroke(Color), lineWidth(Float), shadowBlur(Float), shadowOffsetX(Float), shadowOffsetY(Float), shadowColor(Color) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .text(text): self.text = text case let .x(x): self.x = x case let .y(y): self.y = y case let .font(font): self.font = font case let .textAlign(textAlign): self.textAlign = textAlign case let .textVertical(textVertical): self.textVertical = textVertical case let .fill(fill): self.fill = fill case let .stroke(stroke): self.stroke = stroke case let .lineWidth(lineWidth): self.lineWidth = lineWidth case let .shadowBlur(shadowBlur): self.shadowBlur = shadowBlur case let .shadowOffsetX(shadowOffsetX): self.shadowOffsetX = shadowOffsetX case let .shadowOffsetY(shadowOffsetY): self.shadowOffsetY = shadowOffsetY case let .shadowColor(shadowColor): self.shadowColor = shadowColor } } } } extension TextGraphic.Style: Mappable { public func mapping(_ map: Mapper) { map["text"] = text map["x"] = x map["y"] = y map["font"] = font map["textAlign"] = textAlign map["textVertical"] = textVertical map["fill"] = fill map["stroke"] = stroke map["lineWidth"] = lineWidth map["shadowBlur"] = shadowBlur map["shadowOffsetX"] = shadowOffsetX map["shadowOffsetY"] = shadowOffsetY map["shadowColor"] = shadowColor } } extension TextGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), style(Style) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .style(style): self.style = style } } } } extension TextGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["style"] = style } }
ad0f8aff4f9039cadf4db42c750697e6
31.110553
261
0.543036
false
false
false
false
lvillani/theine
refs/heads/master
Chai/State.swift
gpl-3.0
1
// SPDX-License-Identifier: GPL-3.0-only // // Chai - Don't let your Mac fall asleep, like a sir // Copyright (C) 2021 Chai authors // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. import Dispatch // // Our stuff // enum Action { case initialize case activate(ActivationSpec?) case deactivate case setDisableAfterSuspendEnabled(Bool) case setLoginItemEnabled(Bool) } struct State { var active: Bool = false var activeSpec: ActivationSpec? = nil var isDisableAfterSuspendEnabled: Bool = false var isLoginItemEnabled: Bool = false } func appReducer(state: State, action: Action) -> State { switch action { case .initialize: let defaults = Defaults() var state = State() state.isDisableAfterSuspendEnabled = defaults.isDisableAfterSuspendEnabled state.isLoginItemEnabled = defaults.isLoginItemEnabled return state case .activate(let activationSpec): var newState = state newState.active = true newState.activeSpec = activationSpec return newState case .deactivate: var newState = state newState.active = false newState.activeSpec = nil return newState case .setDisableAfterSuspendEnabled(let enabled): Defaults().isDisableAfterSuspendEnabled = enabled var newState = state newState.isDisableAfterSuspendEnabled = enabled return newState case .setLoginItemEnabled(let enabled): Defaults().isLoginItemEnabled = enabled var newState = state newState.isLoginItemEnabled = enabled return newState } } let globalStore = Store(reducer: appReducer, initialState: State()) // // Infrastructure // typealias Reducer = (State, Action) -> State protocol StoreDelegate: AnyObject { func stateChanged(state: State) } class Store { private let queue = DispatchQueue(label: "StoreDispatchQueue") private let reducer: Reducer private var _state: State private var subscribers: [StoreDelegate] = [] public var state: State { return queue.sync { _state } } public init(reducer: @escaping Reducer, initialState: State) { self.reducer = reducer self._state = initialState } public func dispatch(action: Action) { queue.sync { _state = reducer(_state, action) for subscriber in subscribers { subscriber.stateChanged(state: _state) } } } public func subscribe(storeDelegate: StoreDelegate) { queue.sync { if !subscribers.contains(where: { $0 === storeDelegate }) { subscribers.append(storeDelegate) storeDelegate.stateChanged(state: _state) } } } public func unsubscribe(storeDelegate: StoreDelegate) { queue.sync { subscribers.removeAll(where: { $0 === storeDelegate }) } } }
f43be6d990addc4537be8f014f55b36e
25.495935
78
0.713716
false
false
false
false
adrfer/swift
refs/heads/master
test/decl/nested.swift
apache-2.0
1
// RUN: %target-parse-verify-swift struct OuterNonGeneric { // ok struct MidNonGeneric { // ok struct InnerNonGeneric {} // ok struct InnerGeneric<A> {} // expected-error{{generic type 'InnerGeneric' nested in type 'OuterNonGeneric.MidNonGeneric'}} } struct MidGeneric<B> { // expected-error{{generic type 'MidGeneric' nested in type 'OuterNonGeneric'}} struct InnerNonGeneric {} // expected-error{{type 'InnerNonGeneric' nested in generic type 'OuterNonGeneric.MidGeneric'}} struct InnerGeneric<C> {} // expected-error{{generic type 'InnerGeneric' nested in type 'OuterNonGeneric.MidGeneric'}} func flock(b: B) {} } } struct OuterGeneric<D> { struct MidNonGeneric { // expected-error{{type 'MidNonGeneric' nested in generic type 'OuterGeneric'}} struct InnerNonGeneric {} // expected-error{{type 'InnerNonGeneric' nested in generic type 'OuterGeneric<D>.MidNonGeneric'}} struct InnerGeneric<E> {} // expected-error{{generic type 'InnerGeneric' nested in type 'OuterGeneric<D>.MidNonGeneric'}} func roost(d: D) {} } struct MidGeneric<F> { // expected-error{{generic type 'MidGeneric' nested in type 'OuterGeneric'}} struct InnerNonGeneric {} // expected-error{{type 'InnerNonGeneric' nested in generic type 'OuterGeneric<D>.MidGeneric'}} struct InnerGeneric<G> {} // expected-error{{generic type 'InnerGeneric' nested in type 'OuterGeneric<D>.MidGeneric'}} func nest(d: D, f: F) {} } protocol InnerProtocol { // expected-error{{declaration is only valid at file scope}} associatedtype Rooster func flip(r: Rooster) func flop(t: D) } func nonGenericMethod(d: D) { // FIXME: local generic functions can't capture generic parameters yet func genericFunction<E>(d: D, e: E) {} genericFunction(d, e: ()) } } class OuterNonGenericClass { enum InnerNonGeneric { case Baz case Zab } class InnerNonGenericBase { init() {} } class InnerNonGenericClass1 : InnerNonGenericBase { override init() { super.init() } } class InnerNonGenericClass2 : OuterNonGenericClass { override init() { super.init() } } class InnerGenericClass<U> : OuterNonGenericClass { // expected-error {{generic type 'InnerGenericClass' nested in type 'OuterNonGenericClass'}} override init() { super.init() } } func genericFunction<T>(t: T) { class InnerNonGenericClass : OuterNonGenericClass { // expected-error {{type 'InnerNonGenericClass' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } class InnerGenericClass<U where U : Racoon, U.Stripes == T> : OuterNonGenericClass { // expected-error {{type 'InnerGenericClass' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } } } class OuterGenericClass<T> { enum InnerNonGeneric { // expected-error {{type 'InnerNonGeneric' nested in generic type 'OuterGenericClass' is not allowed}} case Baz case Zab } protocol InnerProtocol { // expected-error{{declaration is only valid at file scope}} associatedtype Rooster func flip(r: Rooster) func flop(t: T) } class InnerNonGenericBase { // expected-error {{type 'InnerNonGenericBase' nested in generic type 'OuterGenericClass' is not allowed}} init() {} } class InnerNonGenericClass1 : InnerNonGenericBase { // expected-error {{type 'InnerNonGenericClass1' nested in generic type 'OuterGenericClass' is not allowed}} override init() { super.init() } } class InnerNonGenericClass2 : OuterGenericClass { // expected-error {{type 'InnerNonGenericClass2' nested in generic type 'OuterGenericClass' is not allowed}} override init() { super.init() } } class InnerNonGenericClass3 : OuterGenericClass<Int> { // expected-error {{type 'InnerNonGenericClass3' nested in generic type 'OuterGenericClass' is not allowed}} override init() { super.init() } } class InnerNonGenericClass4 : OuterGenericClass<T> { // expected-error {{type 'InnerNonGenericClass4' nested in generic type 'OuterGenericClass' is not allowed}} override init() { super.init() } } class InnerGenericClass<U> : OuterGenericClass<U> { // expected-error {{type 'InnerGenericClass' nested in type 'OuterGenericClass' is not allowed}} override init() { super.init() } } func genericFunction<U>(t: U) { class InnerNonGenericClass1 : OuterGenericClass { // expected-error {{type 'InnerNonGenericClass1' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } class InnerNonGenericClass2 : OuterGenericClass<Int> { // expected-error {{type 'InnerNonGenericClass2' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } class InnerNonGenericClass3 : OuterGenericClass<T> { // expected-error {{type 'InnerNonGenericClass3' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } class InnerGenericClass<U where U : Racoon, U.Stripes == T> : OuterGenericClass<U> { // expected-error {{type 'InnerGenericClass' nested in generic function}} let t: T init(t: T) { super.init(); self.t = t } } } } protocol OuterProtocol { associatedtype Hen protocol InnerProtocol { // expected-error{{type not allowed here}} associatedtype Rooster func flip(r: Rooster) func flop(h: Hen) } } protocol Racoon { associatedtype Stripes class Claw<T> { // expected-error{{type not allowed here}} func mangle(s: Stripes) {} } struct Fang<T> { // expected-error{{type not allowed here}} func gnaw(s: Stripes) {} } } enum OuterEnum { protocol C {} // expected-error{{declaration is only valid at file scope}} case C(C) } func outerGenericFunction<T>(t: T) { struct InnerNonGeneric { // expected-error{{type 'InnerNonGeneric' nested in generic function 'outerGenericFunction' }} func nonGenericMethod(t: T) {} func genericMethod<V where V : Racoon, V.Stripes == T>(t: T) -> V {} } struct InnerGeneric<U> { // expected-error{{type 'InnerGeneric' nested in generic function 'outerGenericFunction' }} func nonGenericMethod(t: T, u: U) {} func genericMethod<V where V : Racoon, V.Stripes == T>(t: T, u: U) -> V {} } }
6d6a1bc988837f829858ef644747713b
31.382653
165
0.678273
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
EurofurenceTests/Presenter Tests/Dealers/Test Doubles/CapturingDealersViewModelDelegate.swift
mit
1
@testable import Eurofurence import EurofurenceModel import Foundation class CapturingDealersViewModelDelegate: DealersViewModelDelegate { private(set) var capturedGroups = [DealersGroupViewModel]() private(set) var capturedIndexTitles = [String]() func dealerGroupsDidChange(_ groups: [DealersGroupViewModel], indexTitles: [String]) { capturedGroups = groups capturedIndexTitles = indexTitles } private(set) var toldRefreshDidBegin = false func dealersRefreshDidBegin() { toldRefreshDidBegin = true } private(set) var toldRefreshDidFinish = false func dealersRefreshDidFinish() { toldRefreshDidFinish = true } } extension CapturingDealersViewModelDelegate { func capturedDealerViewModel(at indexPath: IndexPath) -> DealerViewModel? { guard capturedGroups.count > indexPath.section else { return nil } let group = capturedGroups[indexPath.section] guard group.dealers.count > indexPath.item else { return nil } return group.dealers[indexPath.item] } }
1d2c75cfef28713c0b6c1f1692a53bfe
28.027027
90
0.725326
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKitUI/helper/TKUICardActionsViewLayoutHelper.swift
apache-2.0
1
// // TKUICardActionsViewLayoutHelper.swift // TripKitUI-iOS // // Created by Brian Huang on 6/4/20. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // import Foundation import UIKit protocol TKUICardActionsViewLayoutHelperDelegate: AnyObject { func numberOfActionsToDisplay(in collectionView: UICollectionView) -> Int func actionCellToDisplay(at indexPath: IndexPath, in collectionView: UICollectionView) -> UICollectionViewCell? func size(for cell: UICollectionViewCell, at indexPath: IndexPath) -> CGSize? } class TKUICardActionsViewLayoutHelper: NSObject { weak var delegate: TKUICardActionsViewLayoutHelperDelegate! weak var collectionView: UICollectionView! private let sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) private let sizingCell = TKUICompactActionCell.newInstance() init(collectionView: UICollectionView) { self.collectionView = collectionView super.init() collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .clear collectionView.register(TKUICompactActionCell.nib, forCellWithReuseIdentifier: TKUICompactActionCell.identifier) } } // MARK: - extension TKUICardActionsViewLayoutHelper: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return delegate.numberOfActionsToDisplay(in: collectionView) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return delegate.actionCellToDisplay(at: indexPath, in: collectionView) ?? UICollectionViewCell() } } // MARK: - extension TKUICardActionsViewLayoutHelper: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { #if targetEnvironment(macCatalyst) // Ignore, we'll use highlight instead #else guard let cell = collectionView.cellForItem(at: indexPath) as? TKUICompactActionCell, let onTapHandler = cell.onTap else { return } if onTapHandler(cell) { collectionView.reloadData() } #endif } func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { #if targetEnvironment(macCatalyst) guard let cell = collectionView.cellForItem(at: indexPath) as? TKUICompactActionCell, let onTapHandler = cell.onTap else { return } if onTapHandler(cell) { collectionView.reloadData() } #else // Ignore, we'll use selected instead #endif } } // MARK: - extension TKUICardActionsViewLayoutHelper: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return delegate.size(for: sizingCell, at: indexPath) ?? .zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInset } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInset.left } }
eaed094ba7f4b26db054ff64e08fe873
29.827273
168
0.751696
false
false
false
false
HackerEdu/pengtian
refs/heads/master
d1_PrimeOrNot/PrimeOrNot/PrimeOrNot/ViewController.swift
mit
1
// // ViewController.swift // PrimeOrNot // // Created by PENG Tian on 2/1/15. // Copyright (c) 2015 PENG Tian. All rights reserved. // //第一个作业:做一个app,此app要能够判断用户输入的某个数是不是质数 //测试的时候随手按了个4829384712637竟然被告知是质数!真的吗?? import UIKit class ViewController: UIViewController { @IBOutlet weak var userInput: UITextField! //用户输入 @IBOutlet weak var feedback: UILabel! //用户得到的反馈 @IBAction func usrButton(sender: AnyObject) { /*按钮*/ var inputNum = userInput.text.toInt() println(inputNum) if inputNum == nil { //如果不是数 feedback.text = "not a prime" } else { for i in 2...inputNum!-1 { if inputNum! % i == 0 { //笨办法,把所有从2到用户输入-1的数都取模一次 feedback.text = "not a prime" break } else { feedback.text = "prime!" } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
5b507f1bbd78a0b1b0d08abde91e8591
25.933333
76
0.575908
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Model/UserAvatarCellModel.swift
mit
1
//// /// UserAvatarCellModel.swift // let UserAvatarCellModelVersion = 2 @objc(UserAvatarCellModel) final class UserAvatarCellModel: Model { enum EndpointType { case lovers case reposters } let endpointType: EndpointType var seeMoreTitle: String { switch endpointType { case .lovers: return InterfaceString.Post.LovedByList case .reposters: return InterfaceString.Post.RepostedByList } } var icon: InterfaceImage { switch endpointType { case .lovers: return .heart case .reposters: return .repost } } var endpoint: ElloAPI { switch endpointType { case .lovers: return .postLovers(postId: postParam) case .reposters: return .postReposters(postId: postParam) } } var users: [User] = [] var postParam: String var hasUsers: Bool { return users.count > 0 } init( type endpointType: EndpointType, users: [User], postParam: String ) { self.endpointType = endpointType self.users = users self.postParam = postParam super.init(version: UserAvatarCellModelVersion) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func belongsTo(post: Post, type: EndpointType) -> Bool { guard type == endpointType else { return false } return post.id == postParam || ("~" + post.token == postParam) } func append(user: User) { guard !users.any({ $0.id == user.id }) else { return } users.append(user) } func remove(user: User) { users = users.filter { $0.id != user.id } } }
300e03037ffb1dcee92b4bfc5e6c4529
23.913043
70
0.602094
false
false
false
false
sarvex/SwiftRecepies
refs/heads/master
AddressBook/Adding Persons to Groups/Adding Persons to Groups/AppDelegate.swift
isc
1
// // AppDelegate.swift // Adding Persons to Groups // // Created by Vandad Nahavandipoor on 7/27/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import AddressBook @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var addressBook: ABAddressBookRef = { var error: Unmanaged<CFError>? return ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue() as ABAddressBookRef }() func newPersonWithFirstName(firstName: String, lastName: String, inAddressBook: ABAddressBookRef) -> ABRecordRef?{ let person: ABRecordRef = ABPersonCreate().takeRetainedValue() let couldSetFirstName = ABRecordSetValue(person, kABPersonFirstNameProperty, firstName as CFTypeRef, nil) let couldSetLastName = ABRecordSetValue(person, kABPersonLastNameProperty, lastName as CFTypeRef, nil) var error: Unmanaged<CFErrorRef>? = nil let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error) if couldAddPerson{ println("Successfully added the person") } else { println("Failed to add the person.") return nil } if ABAddressBookHasUnsavedChanges(inAddressBook){ var error: Unmanaged<CFErrorRef>? = nil let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error) if couldSaveAddressBook{ println("Successfully saved the address book") } else { println("Failed to save the address book.") } } if couldSetFirstName && couldSetLastName{ println("Successfully set the first name " + "and the last name of the person") } else { println("Failed to set the first name and/or " + "the last name of the person") } return person } func newGroupWithName(name: String, inAddressBook: ABAddressBookRef) -> ABRecordRef?{ let group: ABRecordRef = ABGroupCreate().takeRetainedValue() var error: Unmanaged<CFError>? let couldSetGroupName = ABRecordSetValue(group, kABGroupNameProperty, name, &error) if couldSetGroupName{ error = nil let couldAddRecord = ABAddressBookAddRecord(inAddressBook, group, &error) if couldAddRecord{ println("Successfully added the new group") if ABAddressBookHasUnsavedChanges(inAddressBook){ error = nil let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error) if couldSaveAddressBook{ println("Successfully saved the address book") } else { println("Failed to save the address book") return nil } } else { println("No unsaved changes") return nil } } else { println("Could not add a new group") return nil } } else { println("Failed to set the name of the group") return nil } return group } func addPerson(person: ABRecordRef, toGroup: ABRecordRef, saveToAddressBook: ABAddressBookRef) -> Bool{ var error: Unmanaged<CFErrorRef>? = nil var added = false /* Now attempt to add the person entry to the group */ added = ABGroupAddMember(toGroup, person, &error) if added == false{ println("Could not add the person to the group") return false } /* Make sure we save any unsaved changes */ if ABAddressBookHasUnsavedChanges(saveToAddressBook){ error = nil let couldSaveAddressBook = ABAddressBookSave(saveToAddressBook, &error) if couldSaveAddressBook{ println("Successfully added the person to the group") added = true } else { println("Failed to save the address book") } } else { println("No changes were saved") } return added } func addPersonsAndGroupsToAddressBook(addressBook: ABAddressBookRef){ let richardBranson: ABRecordRef? = newPersonWithFirstName("Richard", lastName: "Branson", inAddressBook: addressBook) if let richard: ABRecordRef = richardBranson{ let entrepreneursGroup: ABRecordRef? = newGroupWithName("Entrepreneurs", inAddressBook: addressBook) if let group: ABRecordRef = entrepreneursGroup{ if addPerson(richard, toGroup: group, saveToAddressBook: addressBook){ println("Successfully added Richard Branson to the group") } else { println("Failed to add Richard Branson to the group") } } else { println("Failed to create the group") } } else { println("Failed to create an entity for Richard Branson") } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { switch ABAddressBookGetAuthorizationStatus(){ case .Authorized: println("Already authorized") addPersonsAndGroupsToAddressBook(addressBook) case .Denied: println("You are denied access to address book") case .NotDetermined: ABAddressBookRequestAccessWithCompletion(addressBook, {[weak self] (granted: Bool, error: CFError!) in if granted{ let strongSelf = self! println("Access is granted") strongSelf.addPersonsAndGroupsToAddressBook( strongSelf.addressBook) } else { println("Access is not granted") } }) case .Restricted: println("Access is restricted") default: println("Unhandled") } return true } }
de716ef3666e63a9b4363518ada761c3
28.321888
83
0.62178
false
false
false
false
timsawtell/SwiftAppStarter
refs/heads/master
App/Utility/Constants/Constants.swift
mit
1
// // constants.swift // TSBoilerplateSwift // // Created by Tim Sawtell on 5/06/2014. // Copyright (c) 2014 Sawtell Software. All rights reserved. // import Foundation import UIKit let kModelFileName = "model.dat" let kModelArchiveKey = "model" let kReverseDomainName = "au.com.sawtellsoftware.tsboilerplateswift" let kUnableToParseMessageText = "Unable to parse results"; let kNoResultsText = "No results found" var deviceOrientation: UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation var isPortrait = deviceOrientation == UIInterfaceOrientation.Portrait || deviceOrientation == UIInterfaceOrientation.PortraitUpsideDown var isLandscape = deviceOrientation == UIInterfaceOrientation.LandscapeLeft || deviceOrientation == UIInterfaceOrientation.LandscapeRight let kBaseURL = "www.example.com" let kPathForModelFile: String = pathForModel()! func pathForModel() -> String? { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true) if paths.count > 0 { var path = paths[0] let fm = NSFileManager() if !fm.fileExistsAtPath(path) { do { try fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil) } catch { return nil } } path = path.stringByAppendingString("/\(kModelFileName)") return path } return nil }
f5f8efc7b7fada1b8e68b145be3aa7d2
33.790698
147
0.725753
false
false
false
false
CosmicMind/Material
refs/heads/develop
Pods/Material/Sources/iOS/Button/BaseIconLayerButton.swift
gpl-3.0
3
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Motion /// Implements common logic for CheckButton and RadioButton open class BaseIconLayerButton: Button { class var iconLayer: BaseIconLayer { fatalError("Has to be implemented by subclasses") } lazy var iconLayer: BaseIconLayer = type(of: self).iconLayer /// A Boolean value indicating whether the button is in the selected state /// /// Use `setSelected(_:, animated:)` if the state change needs to be animated open override var isSelected: Bool { didSet { iconLayer.setSelected(isSelected, animated: false) updatePulseColor() } } /// A Boolean value indicating whether the control is enabled. open override var isEnabled: Bool { didSet { iconLayer.isEnabled = isEnabled } } /// Sets the color of the icon to use for the specified state. /// /// - Parameters: /// - color: The color of the icon to use for the specified state. /// - state: The state that uses the specified color. Supports only (.normal, .selected, .disabled) open func setIconColor(_ color: UIColor, for state: UIControl.State) { switch state { case .normal: iconLayer.normalColor = color case .selected: iconLayer.selectedColor = color case .disabled: iconLayer.disabledColor = color default: fatalError("unsupported state") } } /// Returns the icon color used for a state. /// /// - Parameter state: The state that uses the icon color. Supports only (.normal, .selected, .disabled) /// - Returns: The color of the title for the specified state. open func iconColor(for state: UIControl.State) -> UIColor { switch state { case .normal: return iconLayer.normalColor case .selected: return iconLayer.selectedColor case .disabled: return iconLayer.disabledColor default: fatalError("unsupported state") } } /// A Boolean value indicating whether the button is being animated open var isAnimating: Bool { return iconLayer.isAnimating } /// Sets the `selected` state of the button, optionally animating the transition. /// /// - Parameters: /// - isSelected: A Boolean value indicating new `selected` state /// - animated: true if the state change should be animated, otherwise false. open func setSelected(_ isSelected: Bool, animated: Bool) { guard !isAnimating else { return } iconLayer.setSelected(isSelected, animated: animated) self.isSelected = isSelected } open override func prepare() { super.prepare() layer.addSublayer(iconLayer) iconLayer.prepare() contentHorizontalAlignment = .left // default was .center reloadImage() } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // pulse.animation set to .none so that when we call `super.touchesBegan` // pulse will not expand as there is a `guard` against .none case pulse.animation = .none super.touchesBegan(touches, with: event) pulse.animation = .point // expand pulse from the center of iconLayer/visualLayer (`point` is relative to self.view/self.layer) pulse.expand(point: iconLayer.frame.center) } open override func layoutSubviews() { super.layoutSubviews() // positioning iconLayer let insets = iconEdgeInsets iconLayer.frame.size = CGSize(width: iconSize, height: iconSize) iconLayer.frame.origin = CGPoint(x: imageView!.frame.minX + insets.left, y: imageView!.frame.minY + insets.top) // visualLayer is the layer where pulse layer is expanding. // So we position it at the center of iconLayer, and make it // small circle, so that the expansion of pulse layer is clipped off let w = iconSize + insets.left + insets.right let h = iconSize + insets.top + insets.bottom let pulseSize = min(w, h) visualLayer.bounds.size = CGSize(width: pulseSize, height: pulseSize) visualLayer.frame.center = iconLayer.frame.center visualLayer.cornerRadius = pulseSize / 2 } /// Size of the icon /// /// This property affects `intrinsicContentSize` and `sizeThatFits(_:)` /// Use `iconEdgeInsets` to set margins. open var iconSize: CGFloat = 18 { didSet { reloadImage() } } /// The *outset* margins for the rectangle around the button’s icon. /// /// You can specify a different value for each of the four margins (top, left, bottom, right) /// This property affects `intrinsicContentSize` and `sizeThatFits(_:)` and position of the icon /// within the rectangle. /// /// You can use `iconSize` and this property, or `titleEdgeInsets` and `contentEdgeInsets` to position /// the icon however you want. /// For negative values, behavior is undefined. Default is `8.0` for all four margins open var iconEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) { didSet { reloadImage() } } open override func apply(theme: Theme) { super.apply(theme: theme) setIconColor(theme.secondary, for: .selected) setIconColor(theme.onSurface.withAlphaComponent(0.38), for: .normal) titleColor = theme.onSurface.withAlphaComponent(0.60) selectedPulseColor = theme.secondary normalPulseColor = theme.onSurface updatePulseColor() } /// This might be considered as a hackish way, but it's just manipulation /// UIButton considers size of the `currentImage` to determine `intrinsicContentSize` /// and `sizeThatFits(_:)`, and to position `titleLabel`. /// So, we make use of this property (by setting transparent image) to make room for our icon /// without making much effort (like playing with `titleEdgeInsets` and `contentEdgeInsets`) /// Size of the image equals to `iconSize` plus corresponsing `iconEdgeInsets` values private func reloadImage() { let insets = iconEdgeInsets let w = iconSize + insets.left + insets.right let h = iconSize + insets.top + insets.bottom UIGraphicsBeginImageContext(CGSize(width: w, height: h)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.image = image } /// Pulse color for selected state. open var selectedPulseColor = Color.white /// Pulse color for normal state. open var normalPulseColor = Color.white } private extension BaseIconLayerButton { func updatePulseColor() { pulseColor = isSelected ? selectedPulseColor : normalPulseColor } } // MARK: - BaseIconLayer internal class BaseIconLayer: CALayer { var selectedColor = Color.blue.base var normalColor = Color.lightGray var disabledColor = Color.gray func prepareForFirstAnimation() {} func firstAnimation() {} func prepareForSecondAnimation() {} func secondAnimation() {} private(set) var isAnimating = false private(set) var isSelected = false var isEnabled = true { didSet { selectedColor = { selectedColor }() normalColor = { normalColor }() disabledColor = { disabledColor }() } } func prepare() { normalColor = { normalColor }() // calling didSet selectedColor = { selectedColor }() // calling didSet } func setSelected(_ isSelected: Bool, animated: Bool) { guard self.isSelected != isSelected, !isAnimating else { return } self.isSelected = isSelected if animated { animate() } else { Motion.disable { prepareForFirstAnimation() firstAnimation() prepareForSecondAnimation() secondAnimation() } } } private func animate() { guard !isAnimating else { return } prepareForFirstAnimation() Motion.animate(duration: Constants.partialDuration, timingFunction: .easeInOut, animations: { self.isAnimating = true self.firstAnimation() }, completion: { Motion.disable { self.prepareForSecondAnimation() } Motion.delay(Constants.partialDuration * Constants.delayFactor) { Motion.animate(duration: Constants.partialDuration, timingFunction: .easeInOut, animations: { self.secondAnimation() }, completion: { self.isAnimating = false }) } }) } var sideLength: CGFloat { return frame.height } struct Constants { static let totalDuration = 0.5 static let delayFactor = 0.33 static let partialDuration = totalDuration / (1.0 + delayFactor + 1.0) } } // MARK: - Helper extension private extension CGRect { var center: CGPoint { get { return CGPoint(x: minX + width / 2 , y: minY + height / 2) } set { origin = CGPoint(x: newValue.x - width / 2, y: newValue.y - height / 2) } } } internal extension CALayer { /// Animates the propery of CALayer from current value to the specified value /// and does not reset to the initial value after the animation finishes /// /// - Parameters: /// - keyPath: Keypath to the animatable property of the layer /// - to: Final value of the property /// - dur: Duration of the animation in seconds. Defaults to 0, which results in taking the duration from enclosing CATransaction, or .25 seconds func animate(_ keyPath: String, to: CGFloat, dur: TimeInterval = 0) { let animation = CABasicAnimation(keyPath: keyPath) animation.timingFunction = .easeIn animation.fromValue = self.value(forKeyPath: keyPath) // from current value animation.duration = dur setValue(to, forKeyPath: keyPath) self.add(animation, forKey: nil) } } internal extension CATransform3D { static var identity: CATransform3D { return CATransform3DIdentity } }
44168b32de73569f8f0b22375f8bb604
32.949686
149
0.691089
false
false
false
false
devcastid/iOS-Tutorials
refs/heads/master
Davcast-iOS/Pods/Material/Sources/CaptureView.swift
mit
2
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import AVFoundation public enum CaptureMode { case Photo case Video } @objc(CaptureViewDelegate) public protocol CaptureViewDelegate : MaterialDelegate { /** :name: captureViewDidStartRecordTimer */ optional func captureViewDidStartRecordTimer(captureView: CaptureView) /** :name: captureViewDidUpdateRecordTimer */ optional func captureViewDidUpdateRecordTimer(captureView: CaptureView, hours: Int, minutes: Int, seconds: Int) /** :name: captureViewDidStopRecordTimer */ optional func captureViewDidStopRecordTimer(captureView: CaptureView, hours: Int, minutes: Int, seconds: Int) /** :name: captureViewDidTapToFocusAtPoint */ optional func captureViewDidTapToFocusAtPoint(captureView: CaptureView, point: CGPoint) /** :name: captureViewDidTapToExposeAtPoint */ optional func captureViewDidTapToExposeAtPoint(captureView: CaptureView, point: CGPoint) /** :name: captureViewDidTapToResetAtPoint */ optional func captureViewDidTapToResetAtPoint(captureView: CaptureView, point: CGPoint) /** :name: captureViewDidPressFlashButton */ optional func captureViewDidPressFlashButton(captureView: CaptureView, button: UIButton) /** :name: captureViewDidPressSwitchCamerasButton */ optional func captureViewDidPressSwitchCamerasButton(captureView: CaptureView, button: UIButton) /** :name: captureViewDidPressCaptureButton */ optional func captureViewDidPressCaptureButton(captureView: CaptureView, button: UIButton) /** :name: captureViewDidPressCameraButton */ optional func captureViewDidPressCameraButton(captureView: CaptureView, button: UIButton) /** :name: captureViewDidPressVideoButton */ optional func captureViewDidPressVideoButton(captureView: CaptureView, button: UIButton) } public class CaptureView : MaterialView, UIGestureRecognizerDelegate { /** :name: timer */ private var timer: NSTimer? /** :name: tapToFocusGesture */ private var tapToFocusGesture: UITapGestureRecognizer? /** :name: tapToExposeGesture */ private var tapToExposeGesture: UITapGestureRecognizer? /** :name: tapToResetGesture */ private var tapToResetGesture: UITapGestureRecognizer? /** :name: captureMode */ public lazy var captureMode: CaptureMode = .Video /** :name: tapToFocusEnabled */ public var tapToFocusEnabled: Bool = false { didSet { if tapToFocusEnabled { tapToResetEnabled = true prepareFocusLayer() prepareTapGesture(&tapToFocusGesture, numberOfTapsRequired: 1, numberOfTouchesRequired: 1, selector: "handleTapToFocusGesture:") if let v: UITapGestureRecognizer = tapToExposeGesture { tapToFocusGesture!.requireGestureRecognizerToFail(v) } } else { removeTapGesture(&tapToFocusGesture) focusLayer?.removeFromSuperlayer() focusLayer = nil } } } /** :name: tapToExposeEnabled */ public var tapToExposeEnabled: Bool = false { didSet { if tapToExposeEnabled { tapToResetEnabled = true prepareExposureLayer() prepareTapGesture(&tapToExposeGesture, numberOfTapsRequired: 2, numberOfTouchesRequired: 1, selector: "handleTapToExposeGesture:") if let v: UITapGestureRecognizer = tapToFocusGesture { v.requireGestureRecognizerToFail(tapToExposeGesture!) } } else { removeTapGesture(&tapToExposeGesture) exposureLayer?.removeFromSuperlayer() exposureLayer = nil } } } /** :name: tapToResetEnabled */ public var tapToResetEnabled: Bool = false { didSet { if tapToResetEnabled { prepareResetLayer() prepareTapGesture(&tapToResetGesture, numberOfTapsRequired: 2, numberOfTouchesRequired: 2, selector: "handleTapToResetGesture:") if let v: UITapGestureRecognizer = tapToFocusGesture { v.requireGestureRecognizerToFail(tapToResetGesture!) } if let v: UITapGestureRecognizer = tapToExposeGesture { v.requireGestureRecognizerToFail(tapToResetGesture!) } } else { removeTapGesture(&tapToResetGesture) resetLayer?.removeFromSuperlayer() resetLayer = nil } } } /** :name: contentInsets */ public var contentInsetPreset: MaterialEdgeInset = .None { didSet { contentInset = MaterialEdgeInsetToValue(contentInsetPreset) } } /** :name: contentInset */ public var contentInset: UIEdgeInsets = MaterialEdgeInsetToValue(.Square4) { didSet { reloadView() } } /** :name: previewView */ public private(set) lazy var previewView: CapturePreviewView = CapturePreviewView() /** :name: capture */ public private(set) lazy var captureSession: CaptureSession = CaptureSession() /** :name: focusLayer */ public private(set) var focusLayer: MaterialLayer? /** :name: exposureLayer */ public private(set) var exposureLayer: MaterialLayer? /** :name: resetLayer */ public private(set) var resetLayer: MaterialLayer? /** :name: cameraButton */ public var cameraButton: UIButton? { didSet { if let v: UIButton = cameraButton { v.addTarget(self, action: "handleCameraButton:", forControlEvents: .TouchUpInside) } reloadView() } } /** :name: captureButton */ public var captureButton: UIButton? { didSet { if let v: UIButton = captureButton { v.addTarget(self, action: "handleCaptureButton:", forControlEvents: .TouchUpInside) } reloadView() } } /** :name: videoButton */ public var videoButton: UIButton? { didSet { if let v: UIButton = videoButton { v.addTarget(self, action: "handleVideoButton:", forControlEvents: .TouchUpInside) } reloadView() } } /** :name: switchCamerasButton */ public var switchCamerasButton: UIButton? { didSet { if let v: UIButton = switchCamerasButton { v.addTarget(self, action: "handleSwitchCamerasButton:", forControlEvents: .TouchUpInside) } } } /** :name: flashButton */ public var flashButton: UIButton? { didSet { if let v: UIButton = flashButton { v.addTarget(self, action: "handleFlashButton:", forControlEvents: .TouchUpInside) } } } /** :name: init */ public convenience init() { self.init(frame: CGRectNull) } /** :name: layoutSubviews */ public override func layoutSubviews() { super.layoutSubviews() previewView.frame = bounds if let v: UIButton = cameraButton { v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height v.frame.origin.x = contentInset.left } if let v: UIButton = captureButton { v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height v.frame.origin.x = (bounds.width - v.bounds.width) / 2 } if let v: UIButton = videoButton { v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height v.frame.origin.x = bounds.width - v.bounds.width - contentInset.right } if let v: AVCaptureConnection = (previewView.layer as! AVCaptureVideoPreviewLayer).connection { v.videoOrientation = captureSession.currentVideoOrientation } } /** :name: prepareView */ public override func prepareView() { super.prepareView() backgroundColor = MaterialColor.black preparePreviewView() } /** :name: reloadView */ public func reloadView() { // clear constraints so new ones do not conflict removeConstraints(constraints) for v in subviews { v.removeFromSuperview() } insertSubview(previewView, atIndex: 0) if let v: UIButton = captureButton { insertSubview(v, atIndex: 1) } if let v: UIButton = cameraButton { insertSubview(v, atIndex: 2) } if let v: UIButton = videoButton { insertSubview(v, atIndex: 3) } } /** :name: startTimer */ internal func startTimer() { timer?.invalidate() timer = NSTimer(timeInterval: 0.5, target: self, selector: "updateTimer", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) (delegate as? CaptureViewDelegate)?.captureViewDidStartRecordTimer?(self) } /** :name: updateTimer */ internal func updateTimer() { let duration: CMTime = captureSession.recordedDuration let time: Double = CMTimeGetSeconds(duration) let hours: Int = Int(time / 3600) let minutes: Int = Int((time / 60) % 60) let seconds: Int = Int(time % 60) (delegate as? CaptureViewDelegate)?.captureViewDidUpdateRecordTimer?(self, hours: hours, minutes: minutes, seconds: seconds) } /** :name: stopTimer */ internal func stopTimer() { let duration: CMTime = captureSession.recordedDuration let time: Double = CMTimeGetSeconds(duration) let hours: Int = Int(time / 3600) let minutes: Int = Int((time / 60) % 60) let seconds: Int = Int(time % 60) timer?.invalidate() timer = nil (delegate as? CaptureViewDelegate)?.captureViewDidStopRecordTimer?(self, hours: hours, minutes: minutes, seconds: seconds) } /** :name: handleFlashButton */ internal func handleFlashButton(button: UIButton) { (delegate as? CaptureViewDelegate)?.captureViewDidPressFlashButton?(self, button: button) } /** :name: handleSwitchCamerasButton */ internal func handleSwitchCamerasButton(button: UIButton) { captureSession.switchCameras() (delegate as? CaptureViewDelegate)?.captureViewDidPressSwitchCamerasButton?(self, button: button) } /** :name: handleCaptureButton */ internal func handleCaptureButton(button: UIButton) { if .Photo == captureMode { captureSession.captureStillImage() } else if .Video == captureMode { if captureSession.isRecording { captureSession.stopRecording() stopTimer() } else { captureSession.startRecording() startTimer() } } (delegate as? CaptureViewDelegate)?.captureViewDidPressCaptureButton?(self, button: button) } /** :name: handleCameraButton */ internal func handleCameraButton(button: UIButton) { captureMode = .Photo (delegate as? CaptureViewDelegate)?.captureViewDidPressCameraButton?(self, button: button) } /** :name: handleVideoButton */ internal func handleVideoButton(button: UIButton) { captureMode = .Video (delegate as? CaptureViewDelegate)?.captureViewDidPressVideoButton?(self, button: button) } /** :name: handleTapToFocusGesture */ internal func handleTapToFocusGesture(recognizer: UITapGestureRecognizer) { if tapToFocusEnabled && captureSession.cameraSupportsTapToFocus { let point: CGPoint = recognizer.locationInView(self) captureSession.focusAtPoint(previewView.captureDevicePointOfInterestForPoint(point)) animateTapLayer(layer: focusLayer!, point: point) (delegate as? CaptureViewDelegate)?.captureViewDidTapToFocusAtPoint?(self, point: point) } } /** :name: handleTapToExposeGesture */ internal func handleTapToExposeGesture(recognizer: UITapGestureRecognizer) { if tapToExposeEnabled && captureSession.cameraSupportsTapToExpose { let point: CGPoint = recognizer.locationInView(self) captureSession.exposeAtPoint(previewView.captureDevicePointOfInterestForPoint(point)) animateTapLayer(layer: exposureLayer!, point: point) (delegate as? CaptureViewDelegate)?.captureViewDidTapToExposeAtPoint?(self, point: point) } } /** :name: handleTapToResetGesture */ internal func handleTapToResetGesture(recognizer: UITapGestureRecognizer) { if tapToResetEnabled { captureSession.resetFocusAndExposureModes() let point: CGPoint = previewView.pointForCaptureDevicePointOfInterest(CGPointMake(0.5, 0.5)) animateTapLayer(layer: resetLayer!, point: point) (delegate as? CaptureViewDelegate)?.captureViewDidTapToResetAtPoint?(self, point: point) } } /** :name: prepareTapGesture */ private func prepareTapGesture(inout gesture: UITapGestureRecognizer?, numberOfTapsRequired: Int, numberOfTouchesRequired: Int, selector: Selector) { removeTapGesture(&gesture) gesture = UITapGestureRecognizer(target: self, action: selector) gesture!.delegate = self gesture!.numberOfTapsRequired = numberOfTapsRequired gesture!.numberOfTouchesRequired = numberOfTouchesRequired addGestureRecognizer(gesture!) } /** :name: removeTapToFocusGesture */ private func removeTapGesture(inout gesture: UITapGestureRecognizer?) { if let v: UIGestureRecognizer = gesture { removeGestureRecognizer(v) gesture = nil } } /** :name: preparePreviewView */ private func preparePreviewView() { (previewView.layer as! AVCaptureVideoPreviewLayer).session = captureSession.session captureSession.startSession() } /** :name: prepareFocusLayer */ private func prepareFocusLayer() { if nil == focusLayer { focusLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150)) focusLayer!.hidden = true focusLayer!.borderWidth = 2 focusLayer!.borderColor = MaterialColor.white.CGColor previewView.layer.addSublayer(focusLayer!) } } /** :name: prepareExposureLayer */ private func prepareExposureLayer() { if nil == exposureLayer { exposureLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150)) exposureLayer!.hidden = true exposureLayer!.borderWidth = 2 exposureLayer!.borderColor = MaterialColor.yellow.darken1.CGColor previewView.layer.addSublayer(exposureLayer!) } } /** :name: prepareResetLayer */ private func prepareResetLayer() { if nil == resetLayer { resetLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150)) resetLayer!.hidden = true resetLayer!.borderWidth = 2 resetLayer!.borderColor = MaterialColor.red.accent1.CGColor previewView.layer.addSublayer(resetLayer!) } } /** :name: animateTapLayer */ private func animateTapLayer(layer v: MaterialLayer, point: CGPoint) { MaterialAnimation.animationDisabled { v.transform = CATransform3DIdentity v.position = point v.hidden = false } MaterialAnimation.animateWithDuration(0.25, animations: { v.transform = CATransform3DMakeScale(0.5, 0.5, 1) }) { MaterialAnimation.delay(0.4) { MaterialAnimation.animationDisabled { v.hidden = true } } } } }
b31f975305f34fc064018ffb461a2b01
26.447415
150
0.738391
false
false
false
false
spotify/HubFramework
refs/heads/master
demo/sources/LabelComponent.swift
apache-2.0
1
/* * Copyright (c) 2016 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation import HubFramework /** * A component that renders a text label * * This component is compatible with the following model data: * * - title */ class LabelComponent: HUBComponent { var view: UIView? private lazy var label = UILabel() private var font: UIFont { return .systemFont(ofSize: 20) } var layoutTraits: Set<HUBComponentLayoutTrait> { return [.compactWidth] } func loadView() { label.numberOfLines = 0 label.font = font view = label } func preferredViewSize(forDisplaying model: HUBComponentModel, containerViewSize: CGSize) -> CGSize { guard let text = model.title else { return CGSize() } let size = (text as NSString).size(withAttributes: [NSAttributedStringKey.font: font]) return CGSize(width: ceil(size.width), height: ceil(size.height)) } func prepareViewForReuse() { // No-op } func configureView(with model: HUBComponentModel, containerViewSize: CGSize) { label.text = model.title } }
c43e5c67e7d561c45dcb7595209734c6
29.484375
105
0.681189
false
false
false
false
tamaki-shingo/SoraKit
refs/heads/master
SoraKit/Classes/Sora.swift
mit
1
// // Sora.swift // Pods // // Created by tamaki on 7/1/17. // // import Foundation import APIKit public class Sora { public class func cours(success: @escaping ([Cour]) -> Void, failure: @escaping (Error) -> Void) { let request = CoursRequest() Session.send(request) { (result) in switch result { case .success(let cours): success(cours) case .failure(let error): print("error: \(error)") failure(error) } } } public class func animeTitles(OfYear year: Int, success: @escaping ([AnimeTitle]) -> Void, failure: @escaping (Error) -> Void) { var request = AnimeTitleRequest() request.year = String(year) Session.send(request) { (result) in switch result { case .success(let years): success(years) case .failure(let error): print("error: \(error)") failure(error) } } } public class func animeInfo(OfYear year: Int, season: SoraSeason, success: @escaping ([AnimeInfo]) -> Void, failure: @escaping (Error) -> Void) { var request = AnimeInfoRequest() request.year = String(year) request.season = season Session.send(request) { (result) in switch result { case .success(let yearDetails): success(yearDetails) case .failure(let error): print("error: \(error)") failure(error) } } } }
4e65f3ca7e013b72de3a929032f1aef1
29.576923
149
0.524528
false
false
false
false
mendesbarreto/IOS
refs/heads/master
Bike 2 Work/Bike 2 Work/VariablesNameConsts.swift
mit
1
// // Constans.swift // Bike 2 Work // // Created by Douglas Barreto on 1/27/16. // Copyright © 2016 Douglas Mendes. All rights reserved. // import Foundation public let kHourStartName = "$hourStart"; public let kHourEndName = "$hourEnd"; public let kTemperatureStartName = "$temperatureStart"; public let kTemperatureEndName = "$temperatureEnd"; public let kHumidityStartName = "$humidityStart"; public let kHumidityEndName = "$humidityEnd"; public let kCityVariableName = "$city";
8d11129a42f95f0db6064bc8fec6dc9b
27.764706
57
0.747951
false
false
false
false
Lordxen/MagistralSwift
refs/heads/develop
Carthage/Checkouts/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift
mit
4
// // PCBM.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 08/03/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // // Propagating Cipher Block Chaining (PCBC) // struct PCBCModeWorker: BlockModeWorker { typealias Element = Array<UInt8> let cipherOperation: CipherOperationOnBlock private let iv: Element private var prev: Element? init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock) { self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> { guard let ciphertext = cipherOperation(block: xor(prev ?? iv, plaintext)) else { return plaintext } prev = xor(plaintext, ciphertext) return ciphertext ?? [] } mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> { guard let plaintext = cipherOperation(block: ciphertext) else { return ciphertext } let result = xor(prev ?? iv, plaintext) self.prev = xor(plaintext, ciphertext) return result } }
69ee9e883f1d4d1c547bc76d2fd44b51
27.641026
88
0.647849
false
false
false
false
justindarc/firefox-ios
refs/heads/master
XCUITests/ScreenGraphTest.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import MappaMundi import XCTest class ScreenGraphTest: XCTestCase { var navigator: MMNavigator<TestUserState>! var app: XCUIApplication! override func setUp() { app = XCUIApplication() navigator = createTestGraph(for: self, with: app).navigator() app.terminate() app.launchArguments = [LaunchArguments.Test, LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew] app.activate() } } extension XCTestCase { func wait(forElement element: XCUIElement, timeout: TimeInterval) { let predicate = NSPredicate(format: "exists == 1") expectation(for: predicate, evaluatedWith: element) waitForExpectations(timeout: timeout) } } extension ScreenGraphTest { // Temoporary disable since it is failing intermittently on BB func testUserStateChanges() { XCTAssertNil(navigator.userState.url, "Current url is empty") navigator.userState.url = "https://mozilla.org" navigator.performAction(TestActions.LoadURLByTyping) // The UserState is mutated in BrowserTab. navigator.goto(BrowserTab) navigator.nowAt(BrowserTab) XCTAssertTrue(navigator.userState.url?.starts(with: "www.mozilla.org") ?? false, "Current url recorded by from the url bar is \(navigator.userState.url ?? "nil")") } func testBackStack() { // We'll go through the browser tab, through the menu. navigator.goto(SettingsScreen) // Going back, there is no explicit way back to the browser tab, // and the menu will have dismissed. We should be detecting the existence of // elements as we go through each screen state, so if there are errors, they'll be // reported in the graph below. navigator.goto(BrowserTab) } func testSimpleToggleAction() { // Switch night mode on, by toggling. navigator.performAction(TestActions.ToggleNightMode) XCTAssertTrue(navigator.userState.nightMode) navigator.back() XCTAssertEqual(navigator.screenState, BrowserTab) // Nothing should happen here, because night mode is already on. navigator.toggleOn(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode) XCTAssertTrue(navigator.userState.nightMode) XCTAssertEqual(navigator.screenState, BrowserTab) // Switch night mode off. navigator.toggleOff(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode) XCTAssertFalse(navigator.userState.nightMode) navigator.back() XCTAssertEqual(navigator.screenState, BrowserTab) } func testChainedActionPerf1() { let navigator = self.navigator! measure { navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURLByPasting) XCTAssertEqual(navigator.screenState, WebPageLoading) } } func testChainedActionPerf2() { let navigator = self.navigator! measure { navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURLByTyping) XCTAssertEqual(navigator.screenState, WebPageLoading) } navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURL) XCTAssertEqual(navigator.screenState, WebPageLoading) } func testConditionalEdgesSimple() { XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff)) XCTAssertFalse(navigator.can(goto: PasscodeSettingsOn)) navigator.goto(PasscodeSettingsOff) XCTAssertEqual(navigator.screenState, PasscodeSettingsOff) } func testConditionalEdgesRerouting() { // The navigator should dynamically reroute to the target screen // if the userState changes. // This test adds to the graph a passcode setting screen. In that screen, // there is a noop action that fatalErrors if it is taken. // let map = createTestGraph(for: self, with: app) func typePasscode(_ passCode: String) { passCode.forEach { char in app.keys["\(char)"].tap() } } map.addScreenState(SetPasscodeScreen) { screenState in // This is a silly way to organize things here, // and is an artifical way to show that the navigator is re-routing midway through // a goto. screenState.onEnter() { userState in typePasscode(userState.newPasscode) typePasscode(userState.newPasscode) userState.passcode = userState.newPasscode } screenState.noop(forAction: "FatalError", transitionTo: PasscodeSettingsOn, if: "passcode == nil") { _ in fatalError() } screenState.noop(forAction: "Very", "Long", "Path", "Of", "Actions", transitionTo: PasscodeSettingsOn, if: "passcode != nil") { _ in } } navigator = map.navigator() XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn)) XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff)) XCTAssertTrue(navigator.can(goto: "FatalError")) navigator.goto(PasscodeSettingsOn) XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn)) XCTAssertFalse(navigator.can(goto: PasscodeSettingsOff)) XCTAssertFalse(navigator.can(goto: "FatalError")) XCTAssertEqual(navigator.screenState, PasscodeSettingsOn) } } private let defaultURL = "https://example.com" @objcMembers class TestUserState: MMUserState { required init() { super.init() initialScreenState = FirstRun } var url: String? = nil var nightMode = false var passcode: String? = nil var newPasscode: String = "111111" } let PasscodeSettingsOn = "PasscodeSettingsOn" let PasscodeSettingsOff = "PasscodeSettingsOff" let WebPageLoading = "WebPageLoading" fileprivate class TestActions { static let ToggleNightMode = "menu-NightMode" static let LoadURL = "LoadURL" static let LoadURLByTyping = "LoadURLByTyping" static let LoadURLByPasting = "LoadURLByPasting" } var isTablet: Bool { // There is more value in a variable having the same name, // so it can be used in both predicates and in code // than avoiding the duplication of one line of code. return UIDevice.current.userInterfaceIdiom == .pad } fileprivate func createTestGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<TestUserState> { let map = MMScreenGraph(for: test, with: TestUserState.self) map.addScreenState(FirstRun) { screenState in screenState.noop(to: BrowserTab) screenState.tap(app.textFields["url"], to: URLBarOpen) } map.addScreenState(WebPageLoading) { screenState in screenState.dismissOnUse = true // Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element // but this means exposing some of SnapshotHelper to another target. // screenState.onEnterWaitFor("exists != true", // element: app.progressIndicators.element(boundBy: 0)) screenState.noop(to: BrowserTab) } map.addScreenState(BrowserTab) { screenState in screenState.onEnter { userState in userState.url = app.textFields["url"].value as? String } screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) screenState.tap(app.textFields["url"], to: URLBarOpen) screenState.gesture(forAction: TestActions.LoadURLByPasting, TestActions.LoadURL) { userState in UIPasteboard.general.string = userState.url ?? defaultURL app.textFields["url"].press(forDuration: 1.0) app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap() } } map.addScreenState(URLBarOpen) { screenState in screenState.gesture(forAction: TestActions.LoadURLByTyping, TestActions.LoadURL) { userState in let urlString = userState.url ?? defaultURL app.textFields["address"].typeText("\(urlString)\r") } } map.addScreenAction(TestActions.LoadURL, transitionTo: WebPageLoading) map.addScreenState(BrowserTabMenu) { screenState in screenState.dismissOnUse = true screenState.onEnterWaitFor(element: app.tables["Context Menu"]) screenState.tap(app.tables.cells["Settings"], to: SettingsScreen) screenState.tap(app.cells["menu-NightMode"], forAction: TestActions.ToggleNightMode, transitionTo: BrowserTabMenu) { userState in userState.nightMode = !userState.nightMode } screenState.backAction = { if isTablet { // There is no Cancel option in iPad. app.otherElements["PopoverDismissRegion"].tap() } else { app.buttons["PhotonMenu.close"].tap() } } } let navigationControllerBackAction = { app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() } map.addScreenState(SettingsScreen) { screenState in let table = app.tables["AppSettingsTableViewController.tableView"] screenState.onEnterWaitFor(element: table) screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOff, if: "passcode == nil") screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOn, if: "passcode != nil") screenState.backAction = navigationControllerBackAction } map.addScreenState(PasscodeSettingsOn) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(PasscodeSettingsOff) { screenState in screenState.tap(app.staticTexts["Turn Passcode On"], to: SetPasscodeScreen) screenState.backAction = navigationControllerBackAction } map.addScreenState(SetPasscodeScreen) { screenState in screenState.backAction = navigationControllerBackAction } return map }
2892a242bee309e62202c08de8fe6d90
37.935606
171
0.679833
false
true
false
false
GordonLY/LYPopMenu
refs/heads/master
LYPopMenu/LYPopMenuView.swift
mit
1
// // LYPopMenuView.swift // LYPopMenuDemo // // Created by Gordon on 2017/8/31. // Copyright © 2017年 Gordon. All rights reserved. // import UIKit enum LYPopMenuViewType { case upside case upsidedown } class LYPopMenuView: UIView { /// action callback var action: ((String) -> Void)? var showComplete: (() -> Void)? var hideComplete: (() -> Void)? fileprivate let menuView = UIView() fileprivate var sender: UIView fileprivate var style: LYPopMenuStyle fileprivate var items: [LYPopMenuModel] fileprivate var type: LYPopMenuViewType class func menu(sender: UIView, style: LYPopMenuStyle, items: [LYPopMenuModel]) -> LYPopMenuView { return LYUpsideView.init(sender: sender, style: style, items: items, type: .upside) } class func menu(sender: UIView, style: LYPopMenuStyle, items: [LYPopMenuModel], type: LYPopMenuViewType) -> LYPopMenuView { switch type { case .upside: let popView = LYUpsideView.init(sender: sender, style: style, items: items, type: .upside) return popView case .upsidedown: let popView = LYUpsidedownView.init(sender: sender, style: style, items: items, type: .upsidedown) return popView } } fileprivate init(sender: UIView, style: LYPopMenuStyle, items: [LYPopMenuModel], type: LYPopMenuViewType) { self.sender = sender self.style = style self.items = items self.type = type super.init(frame: UIScreen.main.bounds) p_initSubviews() } fileprivate func p_initSubviews() {} required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LYPopMenuView { func show() { guard self.superview == nil,let window = UIApplication.shared.keyWindow else { return } window.addSubview(self) self.alpha = 0 menuView.alpha = 0 menuView.transform = CGAffineTransform.init(scaleX: 0.6, y: 0.6) UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 self.menuView.alpha = 1 self.menuView.transform = .identity }) { _ in if let showComplete = self.showComplete { showComplete() } } } func hide() { UIView.animate(withDuration: 0.2, animations: { self.alpha = 0 self.menuView.alpha = 0 self.menuView.transform = CGAffineTransform.init(scaleX: 0.6, y: 0.6) }) { _ in self.removeFromSuperview() if let hideComplete = self.hideComplete { hideComplete() } } } fileprivate func actionItem(_ title: String) { self.hide() if let action = action { action(title) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.hide() } } extension LYPopMenuView { fileprivate func p_initMenuCells(from y: CGFloat) { let cell_w = menuView.ly_width let cell_h = style.cellHeight let contentView = UIView.init(frame: CGRect.init(x: 0, y: y, width: cell_w, height: cell_h * CGFloat(items.count))) contentView.layer.cornerRadius = style.menuCorner contentView.layer.masksToBounds = true menuView.addSubview(contentView) for idx in 0 ..< items.count { let cell_y = cell_h * CGFloat(idx) let rect = CGRect.init(x: 0, y: cell_y, width: cell_w, height: cell_h) let cell = LYPopMenuCell.init(frame: rect, style: style) cell.itemModel = items[idx] cell.cellSelectAction = { [weak self] title in self?.actionItem(title) } cell.separateLine.isHidden = (idx == items.count - 1) contentView.addSubview(cell) } } fileprivate func p_drawTriangleLayer(isUp: Bool) { guard menuView.frame != CGRect.zero else { return } let arrHei = isUp ? style.menuArrowHeight : -style.menuArrowHeight let old_y = isUp ? sender.ly_bottom : sender.ly_top let point_old = CGPoint.init(x: sender.ly_centerX, y: old_y) let point_top = self.convert(point_old, to: menuView) let point_left = CGPoint.init(x: point_top.x - arrHei * 0.5, y: point_top.y + arrHei) let point_right = CGPoint.init(x: point_top.x + arrHei * 0.5, y: point_left.y) let trigonPath = UIBezierPath() trigonPath.move(to: point_top) trigonPath.addLine(to: point_left) trigonPath.addLine(to: point_right) trigonPath.close() trigonPath.lineWidth = 0 let triLayer = CAShapeLayer() triLayer.path = trigonPath.cgPath triLayer.fillColor = style.menuBgColor.cgColor menuView.layer.addSublayer(triLayer) let anchor_x = point_top.x / menuView.ly_width let pre_menuX = menuView.ly_left menuView.layer.anchorPoint.x = anchor_x menuView.ly_left = pre_menuX } } // MARK: - ********* DLUpsideView class LYUpsideView: LYPopMenuView { override func p_initSubviews() { self.backgroundColor = style.coverColor let menu_h = style.cellHeight * CGFloat(items.count) + style.menuArrowHeight let menu_y = sender.ly_bottom let menu_w = style.menuWidth var menu_x = sender.ly_centerX - (menu_w * 0.5) let max_x = self.ly_width - menu_w - 5 menu_x = min(max(menu_x, 5),max_x) menuView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0) menuView.frame = CGRect.init(x: menu_x, y: menu_y, width: menu_w, height: menu_h) self.addSubview(menuView) self.p_drawTriangleLayer(isUp: true) self.p_initMenuCells(from: style.menuArrowHeight) } } // MARK: - ********* DLUpsidedownView fileprivate class LYUpsidedownView: LYPopMenuView { override func p_initSubviews() { self.backgroundColor = style.coverColor let menu_h = style.cellHeight * CGFloat(items.count) + style.menuArrowHeight let menu_y = sender.ly_top - menu_h let menu_w = style.menuWidth var menu_x = sender.ly_centerX - (menu_w * 0.5) let max_x = self.ly_width - menu_w - 5 menu_x = min(max(menu_x, 5),max_x) menuView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 1) menuView.frame = CGRect.init(x: menu_x, y: menu_y, width: menu_w, height: menu_h) self.addSubview(menuView) self.p_drawTriangleLayer(isUp: false) items = items.reversed() self.p_initMenuCells(from: 0) } }
3d3a010bd940ea32a84c99e837113d99
32.517241
127
0.597002
false
false
false
false
cp3hnu/PrivacyManager
refs/heads/master
PrivacySpeech/PrivacyManager+Speech.swift
mit
1
// // PrivacyManager+Speech.swift // PrivacySpeech // // Created by CP3 on 11/22/19. // Copyright © 2019 CP3. All rights reserved. // import Foundation import UIKit import RxSwift import Speech import PrivacyManager /// Photo public extension PrivacyManager { /// 获取照片访问权限的状态 var speechStatus: PermissionStatus { let status = SFSpeechRecognizer.authorizationStatus() switch status { case .notDetermined: return .unknown case .authorized: return .authorized case .denied: return .unauthorized case .restricted: return .disabled @unknown default: return .unknown } } /// 获取照片访问权限的状态 - Observable var rxSpeechPermission: Observable<Bool> { return Observable.create{ observer -> Disposable in let status = self.speechStatus switch status { case .unknown: SFSpeechRecognizer.requestAuthorization { status in onMainThread { observer.onNext(status == .authorized) observer.onCompleted() } } case .authorized: observer.onNext(true) observer.onCompleted() default: observer.onNext(false) observer.onCompleted() } return Disposables.create() } } /// Present alert view controller for photo func speechPermission(presenting: UIViewController, desc: String? = nil, authorized authorizedAction: @escaping PrivacyClosure, canceled cancelAction: PrivacyClosure? = nil, setting settingAction: PrivacyClosure? = nil) { return privacyPermission(type: PermissionType.speech, rxPersission: rxSpeechPermission, desc: desc, presenting: presenting, authorized: authorizedAction, canceled: cancelAction, setting: settingAction) } }
52f36fc3db0e9e81574d551691e4d318
31.080645
225
0.602313
false
false
false
false
curtclifton/generic-state-machine-in-swift
refs/heads/master
StateMachine/AsyncEventSimulator.swift
mit
1
// // AsyncEventSimulator.swift // StateMachine // // Created by Curt Clifton on 11/9/15. // Copyright © 2015 curtclifton.net. All rights reserved. // import Foundation private func makeBackgroundQueue() -> NSOperationQueue { let opQueue = NSOperationQueue() opQueue.qualityOfService = .Background opQueue.maxConcurrentOperationCount = 2 return opQueue } private let backgroundQueue = makeBackgroundQueue() func afterDelayOfTimeInterval(delay: NSTimeInterval, performBlockOnMainQueue block: () -> ()) { backgroundQueue.addOperationWithBlock { NSThread.sleepForTimeInterval(delay) NSOperationQueue.mainQueue().addOperationWithBlock { block() } } } private let asyncSimulationProgressGranularity = Float(1.0 / 50.0) func simulateAsyncOperationLastingSeconds<State: StateMachineState>(seconds: Int, forStateMachine stateMachine: StateMachine<State>, completionEventGenerator completionEvent: () -> State.EventType, progressEventGenerator progressEvent: (Float) -> State.EventType) { let durationInSeconds = Double(seconds) let progressInterval = durationInSeconds * Double(asyncSimulationProgressGranularity) let startTime = NSDate() func rescheduleProgress() { afterDelayOfTimeInterval(progressInterval) { let currentTime = NSDate() let elapsedTimeInterval = currentTime.timeIntervalSinceDate(startTime) let progress = Float(elapsedTimeInterval / durationInSeconds) stateMachine.processEvent(progressEvent(progress)) // schedule another update unless it would put us past 100% if progress + asyncSimulationProgressGranularity < 1.0 { rescheduleProgress() } } } rescheduleProgress() afterDelayOfTimeInterval(durationInSeconds) { stateMachine.processEvent(completionEvent()) } }
feeca7649f9335e8f95ec7ad86238d88
36.45098
265
0.716754
false
false
false
false
evgenyneu/walk-to-circle-ios
refs/heads/master
walk to circle/Utils/iiSoundPlayer.swift
mit
1
import UIKit import AVFoundation class iiSoundPlayer { var player: AVAudioPlayer? var fader: iiFaderForAvAudioPlayer? init(fileName: String) { setAudioSessionToAmbient() let error: NSErrorPointer = nil let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), fileName as NSString, nil, nil) do { player = try AVAudioPlayer(contentsOfURL: soundURL) } catch let error1 as NSError { error.memory = error1 player = nil } } convenience init(soundType: iiSoundType) { self.init(fileName: soundType.rawValue) } func prepareToPlay() { if let currentPlayer = player { currentPlayer.prepareToPlay() } } // Allows the sounds to be played with sounds from other apps func setAudioSessionToAmbient() { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) } catch _ { } do { try AVAudioSession.sharedInstance().setActive(true) } catch _ { } } func play(atVolume volume: Float = 1.0) { if let currentPlayer = player { currentPlayer.currentTime = 0 currentPlayer.volume = volume currentPlayer.play() } } func playAsync(atVolume volume: Float = 1.0) { iiQ.async { self.play(atVolume: volume) } } func fadeOut() { if let currentPlayer = player { if let currentFader = fader { currentFader.stop() } let newFader = iiFaderForAvAudioPlayer(player: currentPlayer) fader = newFader newFader.fadeOut() } } }
eb06abe651ddc1c5fe215578733b20a1
21.449275
99
0.657198
false
false
false
false
sztoth/PodcastChapters
refs/heads/develop
PodcastChapters/Utilities/Player/MediaLoader.swift
mit
1
// // MediaLoader.swift // PodcastChapters // // Created by Szabolcs Toth on 2016. 02. 11.. // Copyright © 2016. Szabolcs Toth. All rights reserved. // import Foundation import RxSwift protocol MediaLoaderType { func URLFor(identifier: String) -> Observable<URL> } class MediaLoader { fileprivate let library: MediaLibraryType init(library: MediaLibraryType) { self.library = library } } // MARK: - MediaLoaderType extension MediaLoader: MediaLoaderType { func URLFor(identifier: String) -> Observable<URL> { return Observable.create { observer in if let identifierNumber = NSNumber.pch_number(from: identifier) { if self.library.reloadData() { let item = self.library.allMediaItems.filter({ $0.persistentID == identifierNumber }).first if let location = item?.location { observer.onNext(location) observer.onCompleted() } else { observer.on(.error(LibraryError.itemNotFound)) } } else { observer.on(.error(LibraryError.libraryNotReloaded)) } } else { observer.on(.error(LibraryError.persistentIDInvalid)) } return Disposables.create() } } } // MARK: - LibraryError extension MediaLoader { enum LibraryError: Error { case libraryNotReloaded case itemNotFound case persistentIDInvalid } }
d46c410a62caf2552fb527e5cc1a1705
25.442623
111
0.566026
false
false
false
false
Roommate-App/roomy
refs/heads/master
InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationLineScalePulseOut.swift
apache-2.0
3
// // Created by Tom Baranes on 21/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationLineScalePulseOut: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let beginTime = CACurrentMediaTime() let beginTimes = [0.4, 0.2, 0, 0.2, 0.4] let animation = defaultAnimation // Draw lines for i in 0 ..< 5 { let line = ActivityIndicatorShape.line.makeLayer(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } } // MARK: - Setup private extension ActivityIndicatorAnimationLineScalePulseOut { var defaultAnimation: CAKeyframeAnimation { let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85) let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } }
7990bf83769f8dff2067c755cde8ca34
29.12069
120
0.668575
false
false
false
false
keshavvishwkarma/KVConstraintKit
refs/heads/master
KVConstraintKit/KVConstraintKit+Pin.swift
mit
1
// // KVConstraintKit+Pin.swift // https://github.com/keshavvishwkarma/KVConstraintKit.git // // Distributed under the MIT License. // // Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. 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. // // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif // MARK : - TO APPLIED PREPARED CONSTRAINTS extension View { // All the below methods of this category are used to applied\add constraints in supreview of receiver view (self) /// A receiver view is aligned from the left with padding. /// - Parameter padding: A CGFloat value to the left side padding. @discardableResult public final func applyLeft(_ padding: CGFloat = 0) -> View { (self +== .left).constant = padding ; return self } /// A receiver view is aligned from the right with padding. /// - Parameter padding: A CGFloat value to the right side padding. @discardableResult public final func applyRight(_ padding: CGFloat = 0) -> View { (self +== .right).constant = padding ; return self } /// A receiver view is aligned from the top with padding. /// - Parameter padding: A CGFloat value to the top side padding. @discardableResult public final func applyTop(_ padding: CGFloat = 0) -> View { (self +== .top).constant = padding ; return self } /// A receiver view is aligned from the bottom with padding. /// - Parameter padding: A CGFloat value to the bottom side padding. @discardableResult public final func applyBottom(_ padding: CGFloat = 0) -> View { (self +== .bottom).constant = padding ; return self } /// A receiver view is aligned from the left with padding. /// - Parameter padding: A CGFloat value to the left side padding. @discardableResult public final func applyLeading(_ padding: CGFloat = 0) -> View { (self +== .leading).constant = padding ; return self } /// A receiver view is aligned from the right with padding. /// - Parameter padding: A CGFloat value to the right side padding. @discardableResult public final func applyTrailing(_ padding: CGFloat = 0) -> View { (self +== .trailing).constant = padding ; return self } /// To horizontally Center a receiver view in it's superview with an offset value. /// - Parameter offsetX: A CGFloat value for the offset along the x axis. @discardableResult public final func applyCenterX(_ offsetX: CGFloat = 0) -> View { (self +== .centerX).constant = offsetX ; return self } /// To vertically Center a receiver view in it's superview with an offset value. /// - Parameter offsetY: A CGFloat value for the offset along the y axis. @discardableResult public final func applyCenterY(_ offsetY: CGFloat = 0) -> View { (self +== .centerY).constant = offsetY ; return self } }
3a69bcee83460156e0ebc792cc9b0526
41.478723
118
0.687703
false
false
false
false
xwu/swift
refs/heads/master
test/Distributed/distributed_actor_isolation.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking -verify-ignore-unknown // REQUIRES: concurrency // REQUIRES: distributed // TODO(distributed): rdar://82419661 remove -verify-ignore-unknown here, no warnings should be emitted for our // generated code but right now a few are, because of Sendability checks -- need to track it down more. import _Distributed struct ActorAddress: ActorIdentity { let address: String init(parse address : String) { self.address = address } } actor LocalActor_1 { let name: String = "alice" var mutable: String = "" distributed func nope() { // expected-error@-1{{'distributed' function can only be declared within 'distributed actor'}} } } struct NotCodableValue { } distributed actor DistributedActor_1 { let name: String = "alice" // expected-note{{distributed actor state is only available within the actor instance}} var mutable: String = "alice" // expected-note{{distributed actor state is only available within the actor instance}} var computedMutable: String { get { "hey" } set { _ = newValue } } distributed let letProperty: String = "" // expected-error{{'distributed' modifier cannot be applied to this declaration}} distributed var varProperty: String = "" // expected-error{{'distributed' modifier cannot be applied to this declaration}} distributed var computedProperty: String { // expected-error{{'distributed' modifier cannot be applied to this declaration}} "" } distributed static func distributedStatic() {} // expected-error{{'distributed' functions cannot be 'static'}} func hello() {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}} func helloAsync() async {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}} func helloAsyncThrows() async throws {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}} distributed func distHello() { } // ok distributed func distHelloAsync() async { } // ok distributed func distHelloThrows() throws { } // ok distributed func distHelloAsyncThrows() async throws { } // ok distributed func distInt() async throws -> Int { 42 } // ok distributed func distInt(int: Int) async throws -> Int { int } // ok distributed func distIntString(int: Int, two: String) async throws -> (String) { "\(int) + \(two)" } // ok distributed func dist(notCodable: NotCodableValue) async throws { // expected-error@-1 {{distributed function parameter 'notCodable' of type 'NotCodableValue' does not conform to 'Codable'}} } distributed func distBadReturn(int: Int) async throws -> NotCodableValue { // expected-error@-1 {{distributed function result type 'NotCodableValue' does not conform to 'Codable'}} fatalError() } distributed func distReturnGeneric<T: Codable & Sendable>(item: T) async throws -> T { // ok item } distributed func distReturnGenericWhere<T: Sendable>(item: Int) async throws -> T where T: Codable { // ok fatalError() } distributed func distBadReturnGeneric<T: Sendable>(int: Int) async throws -> T { // expected-error@-1 {{distributed function result type 'T' does not conform to 'Codable'}} fatalError() } distributed func distGenericParam<T: Codable & Sendable>(value: T) async throws { // ok fatalError() } distributed func distGenericParamWhere<T: Sendable>(value: T) async throws -> T where T: Codable { // ok value } distributed func distBadGenericParam<T: Sendable>(int: T) async throws { // expected-error@-1 {{distributed function parameter 'int' of type 'T' does not conform to 'Codable'}} fatalError() } static func staticFunc() -> String { "" } // ok @MainActor static func staticMainActorFunc() -> String { "" } // ok static distributed func staticDistributedFunc() -> String { // expected-error@-1{{'distributed' functions cannot be 'static'}}{10-21=} fatalError() } func test_inside() async throws { _ = self.name _ = self.computedMutable _ = try await self.distInt() _ = try await self.distInt(int: 42) self.hello() _ = await self.helloAsync() _ = try await self.helloAsyncThrows() self.distHello() await self.distHelloAsync() try self.distHelloThrows() try await self.distHelloAsyncThrows() // Hops over to the global actor. _ = await DistributedActor_1.staticMainActorFunc() } } func test_outside( local: LocalActor_1, distributed: DistributedActor_1 ) async throws { // ==== properties _ = distributed.id // ok distributed.id = AnyActorIdentity(ActorAddress(parse: "mock://1.1.1.1:8080/#123121")) // expected-error{{cannot assign to property: 'id' is immutable}}) _ = local.name // ok, special case that let constants are okey let _: String = local.mutable // ok, special case that let constants are okey _ = distributed.name // expected-error{{distributed actor-isolated property 'name' can only be referenced inside the distributed actor}} _ = distributed.mutable // expected-error{{distributed actor-isolated property 'mutable' can only be referenced inside the distributed actor}} // ==== special properties (nonisolated, implicitly replicated) // the distributed actor's special fields may always be referred to _ = distributed.id _ = distributed.actorTransport // ==== static functions _ = distributed.staticFunc() // expected-error{{static member 'staticFunc' cannot be used on instance of type 'DistributedActor_1'}} _ = DistributedActor_1.staticFunc() // ==== non-distributed functions distributed.hello() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}} _ = await distributed.helloAsync() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}} _ = try await distributed.helloAsyncThrows() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}} } // ==== Protocols and static (non isolated functions) protocol P { static func hello() -> String } extension P { static func hello() -> String { "" } } distributed actor ALL: P { } // ==== Codable parameters and return types ------------------------------------ func test_params( distributed: DistributedActor_1 ) async throws { _ = try await distributed.distInt() // ok _ = try await distributed.distInt(int: 42) // ok _ = try await distributed.dist(notCodable: .init()) }
0194618109943a701982bff5ab5c3739
37.614035
154
0.702257
false
false
false
false