repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Trivial - 不需要看的题目/165_Compare Version Numbers.swift
1
2717
// 165_Compare Version Numbers // https://leetcode.com/problems/compare-version-numbers/ // // Created by Honghao Zhang on 10/20/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Compare two version numbers version1 and version2. //If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. // //You may assume that the version strings are non-empty and contain only digits and the . character. // //The . character does not represent a decimal point and is used to separate number sequences. // //For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. // //You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. // // // //Example 1: // //Input: version1 = "0.1", version2 = "1.1" //Output: -1 //Example 2: // //Input: version1 = "1.0.1", version2 = "1" //Output: 1 //Example 3: // //Input: version1 = "7.5.2.4", version2 = "7.5.3" //Output: -1 //Example 4: // //Input: version1 = "1.01", version2 = "1.001" //Output: 0 //Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” //Example 5: // //Input: version1 = "1.0", version2 = "1.0.0" //Output: 0 //Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" // // //Note: // //Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. //Version strings do not start or end with dots, and they will not be two consecutive dots. // import Foundation class Num165 { // MARK: - Compare each components // get version components, then compare each component // if there's no such component, defaults to 0 func compareVersion(_ version1: String, _ version2: String) -> Int { let version1Components = version1.split(separator: ".").compactMap { Int($0) } let version2Components = version2.split(separator: ".").compactMap { Int($0) } var i = 0 while i < version1Components.count || i < version2Components.count { let c1 = (i < version1Components.count) ? version1Components[i] : 0 // component1 let c2 = (i < version2Components.count) ? version2Components[i] : 0 // component2 if c1 > c2 { return 1 } else if c1 < c2 { return -1 } else { i += 1 } } return 0 } }
mit
96e3d2b6322c98e207491dc748d929ca
34.605263
256
0.664819
3.641992
false
false
false
false
daehn/Counted-Set
CountedSetTests/CountedSetTests.swift
1
10215
// // The MIT License (MIT) // Copyright 2016 Silvan Dähn // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import XCTest @testable import CountedSet class CountedSetTests: XCTestCase { var sut: CountedSet<String>! override func setUp() { super.setUp() sut = CountedSet<String>() } func testThatItAddsElementsToTheSetAndSetsTheCorrectCount() { // when sut.insert("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 1) } func testThatItIncreasesTheCountWhenAddingAnElementMultipleTimes() { // when sut.insert("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 1) // when sut.insert("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 2) // when sut.insert("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 3) } func testThatItReturnsZeroAsElementCountForElementsNotInTheSet() { XCTAssertEqual(sut.count(for: "Hello"), 0) } func testThatItDecreasesTheCountWhenAddingAnElementMultipleTimes() { // given sut = CountedSet(arrayLiteral: "Hello", "Hello") XCTAssertEqual(sut.count(for: "Hello"), 2) // when sut.remove("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 1) // when sut.remove("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 0) } func testThatItDoesNotDecreaseTheCountIfAlreadyZero() { // given sut = CountedSet(arrayLiteral: "Hello") XCTAssertEqual(sut.count(for: "Hello"), 1) // when sut.remove("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 0) // when sut.remove("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 0) } func testThatItMultipleElementsCanbeAddedWithoutAffectingEachOther() { // given sut = CountedSet(arrayLiteral: "Hello", "World", "Hello") XCTAssertEqual(sut.count(for: "Hello"), 2) XCTAssertEqual(sut.count(for: "World"), 1) // when sut.remove("Hello") // then XCTAssertEqual(sut.count(for: "Hello"), 1) XCTAssertEqual(sut.count(for: "World"), 1) // when sut.insert("World") // then XCTAssertEqual(sut.count(for: "Hello"), 1) XCTAssertEqual(sut.count(for: "World"), 2) } func testThatItReturnsNilIfThereIsTheElementToRemoveIsNotInTheSet() { // when let element = "Test" sut.insert(element) // then XCTAssertEqual(element, sut.remove(element)) XCTAssertNil(sut.remove(element)) } func testThatItReturnsTheElementWithTheMostOccurences() { // given sut = CountedSet(arrayLiteral: "Hello", "World", "Hello") // when let mostOccuring = sut.mostFrequent() // then XCTAssertEqual(mostOccuring?.element, "Hello") XCTAssertEqual(mostOccuring?.count, 2) } func testThatItReturnsTheElementWithTheMostOccurencesWhenThereIsOnlyOneElement() { // given sut = CountedSet(arrayLiteral: "Hello") let mostOccuring = sut.mostFrequent() XCTAssertEqual(mostOccuring?.element, "Hello") XCTAssertEqual(mostOccuring?.count, 1) } func testThatItReturnsNilIfThereIsNoMostOccuringElement() { // when let mostOccuring = sut.mostFrequent() // then XCTAssertNil(mostOccuring) } func testThatToEqualCountedSetsAreReportedEqual() { // when sut = CountedSet(arrayLiteral: "Hello", "World", "Hello") let other = CountedSet(arrayLiteral: "Hello", "Hello", "World") // then XCTAssertEqual(sut, other) } func testThatToNotEqualCountedSetsAreNotReportedEqual() { // when sut = CountedSet(arrayLiteral: "Hello", "World", "Hello", "World") let other = CountedSet(arrayLiteral: "Hello", "Hello", "World") // then XCTAssertNotEqual(sut, other) } func testThatToReturnsTheCorrectElementWhenSubscipted() { // when sut = CountedSet(arrayLiteral: "Hello", "Tiny", "World", "Hello", "Tiny", "Tiny") guard let worldIndex = sut.index(of: "World") else { return XCTFail() } guard let tinyIndex = sut.index(of: "Tiny") else { return XCTFail() } guard let helloIndex = sut.index(of: "Hello") else { return XCTFail() } // then XCTAssertEqual("World", sut[worldIndex]) XCTAssertEqual("Tiny", sut[tinyIndex]) XCTAssertEqual("Hello", sut[helloIndex]) } func testThatItCreatesACorrectGenerator() { // given sut = CountedSet(arrayLiteral: "Hello", "World", "Hello") var generator = sut.makeIterator() var generatedElements = [String]() // when while let element = generator.next() { generatedElements.append(element) } // then let expected = Set<String>(arrayLiteral: "Hello", "World") XCTAssertEqual(Set(generatedElements), expected) } func testThatItReturnsTheCountWhenSubsciptedWithElement() { // given sut = CountedSet(arrayLiteral: "Foo", "Bar", "Baz", "Foo", "Foo", "Bar") // then XCTAssertEqual(sut["Foo"], 3) XCTAssertEqual(sut["Bar"], 2) XCTAssertEqual(sut["Baz"], 1) } func testThatItDoesNotAddTheCountsForElementsWithTheSameHash() { // given let first = HashHelper(hashValue: 1, name: "first") let second = HashHelper(hashValue: 2, name: "second") var sut = CountedSet(arrayLiteral: first, second) // then XCTAssertEqual(sut.count(for: first), 1) XCTAssertEqual(sut.count(for: second), 1) // when let third = HashHelper(hashValue: 1, name: "third") sut.insert(third) // then XCTAssertEqual(sut.count(for: first), 1) XCTAssertEqual(sut.count(for: second), 1) XCTAssertEqual(sut.count(for: third), 1) } func testThatItDoesAddTheCountsForElementsWithTheSameIdentity() { // given let first = HashHelper(hashValue: 1, name: "first") var sut = CountedSet(arrayLiteral: first) // then XCTAssertEqual(sut.count(for: first), 1) // when let second = HashHelper(hashValue: 1, name: "first") sut.insert(second) // then XCTAssertEqual(sut.count(for: first), 2) XCTAssertEqual(sut.count(for: second), 2) } func testThatItReturnsZeroIfTheElementIsNotInTheSetWhenSubscipted() { // given sut = ["Foo", "Bar"] // then XCTAssertEqual(sut["Baz"], 0) } func testThatItAddsANonExistentElementWhenSettingCount() { // given sut = ["Foo", "Bar"] // when sut.setCount(2, for: "Baz") // then XCTAssert(sut.contains("Baz")) XCTAssertEqual(sut.count(for: "Baz"), 2) } func testThatItSetsTheNewCountWhenSettingCountForContainedElement() { // given sut = ["Foo", "Bar"] // when XCTAssert(sut.setCount(3, for: "Foo")) // then XCTAssertEqual(sut.count(for: "Foo"), 3) } func testThatItReturnsFalseWhenSettingExistingCount() { // given sut = ["Foo", "Bar", "Foo"] // then XCTAssertFalse(sut.setCount(2, for: "Foo")) } func testThatItReturnsTrueWhenSettingCountForElementWithDifferentExistingCount() { // given sut = ["Foo", "Bar"] // then XCTAssert(sut.setCount(2, for: "Foo")) } func testThatItRemovesElementFrombackingStoreWhenSettingCountForContainedElementToZero() { // given sut = ["Foo", "Bar"] // when XCTAssert(sut.setCount(0, for: "Foo")) // then XCTAssertFalse(sut.contains("Foo")) XCTAssertEqual(sut.count(for: "Foo"), 0) } func testThePerformanceOfAdding_10000_ElementsToTheCountedSet() { var sut = CountedSet<Int>() let range = 0..<100 measure { range.forEach { _ in range.forEach { // when sut.insert($0) } } } // then XCTAssertEqual(sut.count, 100) range.forEach { XCTAssertEqual(sut.count(for: $0), 1000) } } func testThatItReturnsAValidDescription() { // given sut = CountedSet(arrayLiteral: "Foo", "Bar", "Foo") let expected = "<CountedSet>:\n\t- Foo: 2\n\t- Bar: 1\n" // then XCTAssertEqual(sut.description, expected) } func testThatItReturnsDistinctHashValues() { // given let sut1 = CountedSet(arrayLiteral: "Foo", "Bar", "Foo") let sut2 = CountedSet(arrayLiteral: "Foo", "Foo", "Bar") let sut3 = CountedSet(arrayLiteral: "Foo", "Bar") // then XCTAssertEqual(sut1.hashValue, sut2.hashValue) XCTAssertNotEqual(sut2.hashValue, sut3.hashValue) } }
mit
d104d6e648d0016a87cc226983b47c52
29.76506
94
0.603877
4.458315
false
true
false
false
manumax/TinyRobotWars
TinyRobotWars/Core/Lexer.swift
1
4532
// // Created by Manuele Mion on 17/05/15. // Copyright (c) 2015 manumax. All rights reserved. // import Foundation enum Token { case register(String) case number(Int) case op(Operator) case relOp(RelationalOperator) case to case `if` case goto case gosub case endsub case label(String) case comment(String) } extension Token: Equatable { static func ==(lhs: Token, rhs: Token) -> Bool { switch (lhs, rhs) { case let (.register(l), .register(r)): return l == r case let (.number(l), .number(r)): return l == r case let (.op(l), .op(r)): return l.rawValue == r.rawValue case let (.relOp(l), .relOp(r)): return l.rawValue == r.rawValue case (.to, .to): return true case (.`if`, .`if`): return true case (.goto, .goto): return true case (.gosub, .gosub): return true case (.endsub, .endsub): return true case let (.label(l), .label(r)): return l == r case let (.comment(l), .comment(r)): return l == r default: return false } } } enum Operator: String { case plus = "+" case minus = "-" case times = "*" case divide = "/" } enum RelationalOperator: String { case equal = "=" case notEqual = "#" case greaterThan = ">" case lessThan = "<" } let registers = ["AIM", "SHOT", "RADAR", "DAMAGE", "SPEEDX", "SPEEDY", "RANDOM", "INDEX"] let singleCharToTokenMap: [Character: Token] = [ "+": .op(.plus), "-": .op(.minus), "*": .op(.times), "/": .op(.divide), "=": .relOp(.equal), "#": .relOp(.notEqual), ">": .relOp(.greaterThan), "<": .relOp(.lessThan), ] extension Character { var value: Int32 { return Int32(String(self).unicodeScalars.first!.value) } var isSpace: Bool { return isspace(self.value) != 0 } var isAlphanumeric: Bool { return isalnum(self.value) != 0 } var isEOL: Bool { return self.value == Int32("\n") } } class Lexer: IteratorProtocol { typealias Element = Token let input: String var index: String.Index var currentChar: Character? { return self.index < self.input.endIndex ? input[index] : nil } init(withString input: String) { self.input = input self.index = input.startIndex } func nextChar() { index = input.index(after: index) } func skipSpaces() { while let char = self.currentChar, char.isSpace { nextChar() } } func readComment() -> String { var str = "" while let char = currentChar, !char.isEOL { str.append(char) self.nextChar() } return str } func readIdentifierOrNumber() -> String { var str = "" while let char = currentChar, char.isAlphanumeric { str.append(char) self.nextChar() } return str } func next() -> Token? { self.skipSpaces() guard let char = self.currentChar else { return nil; } if char == ";" { nextChar() let str = self.readComment() return .comment(str) } if let token = singleCharToTokenMap[char] { nextChar() return token } if char.isAlphanumeric { let str = self.readIdentifierOrNumber() // Number if let number = Int(str) { return .number(number) } // Identifier switch str { case "TO": return .to case "IF": return .if case "GOTO": return .goto case "GOSUB": return .gosub case "ENDSUB": return .endsub case "A"..."Z" where str.count == 1: fallthrough case _ where registers.contains(str): return .register(str) default: return .label(str) } } return nil } func lex() -> [Token] { var tokens = [Token]() while let token = self.next() { tokens.append(token) } return tokens } }
mit
3a874914088e34168f506d616b9a1b0e
22.481865
89
0.481686
4.259398
false
false
false
false
JoshTheGeek/threadword
threadword/main.swift
1
2608
// // main.swift // threadword // // Created by Joshua Oldenburg on 6/18/14. // Copyright (c) 2014 Joshua Oldenburg. All rights reserved. // import Foundation let parser = GBCommandLineParser() parser.registerOption("prefix", shortcut: 112 /* p */, requirement: GBValueRequired) //parser.registerOption("file", shortcut: 102 /* f */, requirement: GBValueRequired) parser.registerOption("all", shortcut: 61 /* a */, requirement: GBValueNone) var options = Dictionary<String, AnyObject>() var lines = Array<String>() func _parseOption(flags: GBParseFlags, argument: String?, value: AnyObject?, stop: CMutablePointer<ObjCBool>?) { switch flags { case GBParseFlagOption: options[argument!] = value case GBParseFlagArgument: if let strValue: String = value? as? NSString { if (countElements(strValue) > 0) { lines += strValue } } case GBParseFlagMissingValue: println("Error: option \(argument) requires a value") exit(2) case GBParseFlagUnknownOption: println("Error: uknown option \(argument)") exit(2) default: println("Error: this should never happen - unknown GBParseFlags \(flags)") exit(1) } } parser.parseOptionsUsingDefaultArgumentsWithBlock(_parseOption) if lines.count <= 1 { println("Error: you must give a puzzle to solve!") exit(2) } println("Solving puzzle:") for line in lines { println(" \(line)") } let puzzle = JOThreadWordsPuzzle(level: lines) let allWords = puzzle.solve() var solution: String[] let prefix: String? = options["prefix"]? as? String let showAllWords: Bool = (options["all"] != nil) let filePath: String? = options["file"]? as? String var fileWords: String[] /*if filePath != nil { let fileData: String? = NSString.stringWithContentsOfFile(filePath) as? String if fileData == nil { println("The specified file did not exist!") exit(3) } else { fileWords = fileData!.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } }*/ if showAllWords { // --all solution = allWords } else if prefix != nil || filePath != nil { // --prefix and/or --file solution = allWords.filter() { word -> Bool in if prefix != nil && !word.bridgeToObjectiveC().hasPrefix(prefix) { return false } // Never runs, is disabled if fileWords != nil && !JOUtil.isFound(JOUtil.binarySearchArray(fileWords, forObject:word)) { return false } return true } } else { solution = allWords.filter() { JOUtil.isWord($0) } } println("All words, by location: \(solution.description)") println("All words, alphabetically: \(sort(solution) { $0 < $1 })") println("\(solution.count) solutions found")
mit
b6e5a444e46612dcc2e1261d03bcbf9f
27.347826
112
0.706672
3.582418
false
false
false
false
arslanbilal/cryptology-project
Cryptology Project/Cryptology Project/Classes/Controllers/User/PasswordEditController/PasswordEditViewController.swift
1
5591
// // PasswordEditViewController.swift // Cryptology Project // // Created by Bilal Arslan on 08/04/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import UIKit class PasswordEditViewController: UIViewController, UITextFieldDelegate { let passwordTextField = UITextField.newAutoLayoutView() let password2TextField = UITextField.newAutoLayoutView() let submitButton = UIButton.newAutoLayoutView() // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.title = "Change Password" self.loadViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Load Views func loadViews() { let loginElementsView = UIView.newAutoLayoutView() loginElementsView.backgroundColor = UIColor.loginViewBackgroundColor() loginElementsView.layer.cornerRadius = 10.0 self.view.addSubview(loginElementsView) loginElementsView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(30.0, 15.5, 0, 15.5), excludingEdge: .Bottom) loginElementsView.autoSetDimension(.Height, toSize: 190) let passwordView = UIView.newAutoLayoutView() passwordView.backgroundColor = UIColor.whiteColor() passwordView.layer.cornerRadius = 5.0 loginElementsView.addSubview(passwordView) passwordView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10.0, 10.0, 0, 10.0), excludingEdge: .Bottom) passwordView.autoSetDimension(.Height, toSize: 50) passwordTextField.delegate = self passwordTextField.textAlignment = .Center passwordTextField.secureTextEntry = true passwordTextField.placeholder = "password" passwordView.addSubview(passwordTextField) passwordTextField.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(2.0, 5.0, 2.0, 5.0)) let password2View = UIView.newAutoLayoutView() password2View.backgroundColor = UIColor.whiteColor() password2View.layer.cornerRadius = 5.0 loginElementsView.addSubview(password2View) password2View.autoPinEdgeToSuperviewEdge(.Left, withInset: 10.0) password2View.autoPinEdgeToSuperviewEdge(.Right, withInset: 10.0) password2View.autoPinEdge(.Top, toEdge: .Bottom, ofView: passwordView, withOffset: 10.0) password2View.autoSetDimension(.Height, toSize: 50) password2TextField.delegate = self password2TextField.textAlignment = .Center password2TextField.secureTextEntry = true password2TextField.placeholder = "retype password" password2View.addSubview(password2TextField) password2TextField.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(2.0, 5.0, 2.0, 5.0)) submitButton.backgroundColor = UIColor.incomingMessageColor() submitButton.titleLabel?.textColor = UIColor.whiteColor() submitButton.setTitle("Change Password", forState: .Normal) submitButton.addTarget(self, action: #selector(PasswordEditViewController.didTapSubmitButton(_:)), forControlEvents: .TouchUpInside) submitButton.layer.cornerRadius = 5.0 loginElementsView.addSubview(submitButton) submitButton.autoPinEdge(.Top, toEdge: .Bottom, ofView: password2View, withOffset: 10.0) submitButton.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0.0, 10.0, 10.0, 10.0), excludingEdge: .Top) //submitButton.autoSetDimension(.Height, toSize: 50) } // MARK: - Button Action func didTapSubmitButton(sender: UIButton) { let password1 = passwordTextField.text! let password2 = password2TextField.text! if password1 != "" && password2 != "" { if password1 == password2 { if password1.length > 7 { ActiveUser.sharedInstance.user.changePassword(password1) passwordTextField.text = "" passwordTextField.resignFirstResponder() password2TextField.text = "" password2TextField.resignFirstResponder() showAlertView("Password Changed!", message: "", style: .Alert) } else { showAlertView("Cannot Change", message: "Enter more than 8 chracter.", style: .Alert) } } else { showAlertView("Match Error", message: "Passwords you enter does not match.", style: .Alert) } } else { showAlertView("Error!", message: "Fill the password fields.", style: .Alert) } } // MARK: - UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return false } // MARK: - AlertViewInitialise func showAlertView(title: String, message: String, style: UIAlertControllerStyle) { let alertController = UIAlertController.init(title: title, message: message, preferredStyle: style) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
bf8fd251eb96d23e9f37c6011a89c5a8
40.716418
140
0.656708
5.551142
false
false
false
false
ShengQiangLiu/arcgis-runtime-samples-ios
OfflineGeocodingSample/swift/OfflineGeocoding/RecentViewController.swift
4
2458
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit class RecentViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var items:[String]! var completion:((String) -> Void)! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "RecentCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell! if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) } cell.textLabel!.text = self.items[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.completion(self.items[indexPath.row]) } @IBAction func cancel(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
6b39b9918d35dcfc83cb01b82214a91b
31.342105
113
0.691619
5.343478
false
false
false
false
limaoxuan/MXSpringAnimation
MXSpringAnimation/MXSpringAnimation/ViewController.swift
1
4040
// // ViewController.swift // MXSpringAnimation // // Created by 李茂轩 on 15/2/15. // Copyright (c) 2015年 lee. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var nameArray : [String]! @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self nameArray = ["content","sort","mask"] tableView.reloadData() tableView.separatorStyle = UITableViewCellSeparatorStyle.None // 动画延时 let diff = 0.05 // 获取tableview的高 let tableHeight = self.tableView.bounds.size.height let cells : [UITableViewCell] = tableView.visibleCells() as [UITableViewCell] // 便利单元格,将之隐藏 for cell in cells { cell.transform = CGAffineTransformMakeTranslation(0, tableHeight) } for i in 0...cells.count-1{ let cell : UITableViewCell = cells[i] as UITableViewCell let delay = diff * Double(i) UIView.animateWithDuration(1, delay: delay, options: UIViewAnimationOptions.allZeros, animations: { () -> Void in cell.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nameArray.count } // func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = "\(indexPath.row+1)--" + nameArray[indexPath.row] // cell.lin return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print(indexPath.row) var toViewController : UIViewController! if indexPath.row == 0 { toViewController = getMainStoryboardInstance("ContentViewController") // self.navigationController?.pushViewController(toViewController, animated: true) } else if indexPath.row == 1 { toViewController = getMainStoryboardInstance("AudioViewController") } self.navigationController?.pushViewController(toViewController, animated: true) // self.performSegueWithIdentifier("toChatSegue", sender: self) // performSegueWithIdentifier("", sender: self) } // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // // if segue.identifier == "setting" { // // transitionType( TransitionType.MaskLayerZoomIn) // // // // } // // // // // } // @IBAction func maskLayerAnimation(sender: AnyObject) { // // let viewController = ViewController() // self.navigationController?.navigationBarHidden = true // // self.navigationController?.pushViewController(viewController, animated: true) // // // } }
apache-2.0
4a401dee044502d51bbae567def6c137
25.818792
125
0.535786
6.027149
false
false
false
false
Zewo/Reflection
Sources/Reflection/Any+Extensions.swift
2
1540
// // Any+Extensions.swift // Reflection // // Created by Bradley Hilton on 10/17/16. // // protocol AnyExtensions {} extension AnyExtensions { static func construct(constructor: (Property.Description) throws -> Any) throws -> Any { return try Reflection.constructGenericType(self, constructor: constructor) } static func isValueTypeOrSubtype(_ value: Any) -> Bool { return value is Self } static func value(from storage: UnsafeRawPointer) -> Any { return storage.assumingMemoryBound(to: self).pointee } static func write(_ value: Any, to storage: UnsafeMutableRawPointer) throws { guard let this = value as? Self else { throw ReflectionError.valueIsNotType(value: value, type: self) } storage.assumingMemoryBound(to: self).initialize(to: this) } } func extensions(of type: Any.Type) -> AnyExtensions.Type { struct Extensions : AnyExtensions {} var extensions: AnyExtensions.Type = Extensions.self withUnsafePointer(to: &extensions) { pointer in UnsafeMutableRawPointer(mutating: pointer).assumingMemoryBound(to: Any.Type.self).pointee = type } return extensions } func extensions(of value: Any) -> AnyExtensions { struct Extensions : AnyExtensions {} var extensions: AnyExtensions = Extensions() withUnsafePointer(to: &extensions) { pointer in UnsafeMutableRawPointer(mutating: pointer).assumingMemoryBound(to: Any.self).pointee = value } return extensions }
mit
66ed71ec0b895d45a0070fff70c7102e
29.8
104
0.685714
4.680851
false
false
false
false
wireapp/wire-ios
WireCommonComponents/AVAsset+VideoConvert.swift
1
6225
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import AVFoundation import WireUtilities private let zmLog = ZMSLog(tag: "UI") // MARK: - audio convert extension AVAsset { public static func convertAudioToUploadFormat( _ inPath: String, outPath: String, completion: ((_ success: Bool) -> Void )? = .none) { let fileURL = URL(fileURLWithPath: inPath) let alteredAsset = AVAsset(url: fileURL) let session = AVAssetExportSession(asset: alteredAsset, presetName: AVAssetExportPresetAppleM4A) guard let exportSession = session else { zmLog.error("Failed to create export session with asset \(alteredAsset)") completion?(false) return } let encodedEffectAudioURL = URL(fileURLWithPath: outPath) exportSession.outputURL = encodedEffectAudioURL as URL exportSession.outputFileType = AVFileType.m4a exportSession.exportAsynchronously { [unowned exportSession] in switch exportSession.status { case .failed: zmLog.error("Cannot transcode \(inPath) to \(outPath): \(String(describing: exportSession.error))") DispatchQueue.main.async { completion?(false) } default: DispatchQueue.main.async { completion?(true) } } } } } // MARK: - video convert public typealias ConvertVideoCompletion = (URL?, AVURLAsset?, Error?) -> Void extension AVURLAsset { public static let defaultVideoQuality: String = AVAssetExportPresetHighestQuality /// Convert a Video file URL to a upload format /// /// - Parameters: /// - url: video file URL /// - quality: video quality, default is AVAssetExportPresetHighestQuality /// - deleteSourceFile: set to false for testing only /// - completion: ConvertVideoCompletion closure. URL: exported file's URL. AVURLAsset: assert of converted video. Error: error of conversion public static func convertVideoToUploadFormat(at url: URL, quality: String = AVURLAsset.defaultVideoQuality, deleteSourceFile: Bool = true, fileLengthLimit: Int64? = nil, completion: @escaping ConvertVideoCompletion ) { let filename = url.deletingPathExtension().lastPathComponent + ".mp4" let asset: AVURLAsset = AVURLAsset(url: url, options: nil) guard let track = AVAsset(url: url as URL).tracks(withMediaType: AVMediaType.video).first else { return } let size = track.naturalSize let cappedQuality: String if size.width > 1920 || size.height > 1920 { cappedQuality = AVAssetExportPreset1920x1080 } else { cappedQuality = quality } asset.convert(filename: filename, quality: cappedQuality, fileLengthLimit: fileLengthLimit) { URL, asset, error in completion(URL, asset, error) if deleteSourceFile { do { try FileManager.default.removeItem(at: url) } catch let deleteError { zmLog.error("Cannot delete file: \(url) (\(deleteError))") } } } } public func convert(filename: String, quality: String = defaultVideoQuality, fileLengthLimit: Int64? = nil, completion: @escaping ConvertVideoCompletion) { let outputURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename) if FileManager.default.fileExists(atPath: outputURL.path) { do { try FileManager.default.removeItem(at: outputURL) } catch let deleteError { zmLog.error("Cannot delete old leftover at \(outputURL): \(deleteError)") } } guard let exportSession = AVAssetExportSession(asset: self, presetName: quality) else { return } if let fileLengthLimit = fileLengthLimit { exportSession.fileLengthLimit = fileLengthLimit } exportSession.exportVideo(exportURL: outputURL) { _, error in DispatchQueue.main.async(execute: { completion(outputURL, self, error) }) } } } extension AVAssetExportSession { public func exportVideo(exportURL: URL, completion: @escaping (URL?, Error?) -> Void) { if FileManager.default.fileExists(atPath: exportURL.path) { do { try FileManager.default.removeItem(at: exportURL) } catch let error { zmLog.error("Cannot delete old leftover at \(exportURL): \(error)") } } outputURL = exportURL shouldOptimizeForNetworkUse = true outputFileType = .mp4 metadata = [] metadataItemFilter = AVMetadataItemFilter.forSharing() weak var session: AVAssetExportSession? = self exportAsynchronously { if let session = session, let error = session.error { zmLog.error("Export session error: status=\(session.status.rawValue) error=\(error) output=\(exportURL)") } completion(exportURL, session?.error) } } }
gpl-3.0
074885139476d4f8f31ede80b4d7d1dc
40.778523
147
0.601767
5.375648
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/NSLayoutConstraint/NSLayoutConstraint/VFLViewController.swift
1
2581
// // VFLViewController.swift // NSLayoutConstraint // // Created by pantosoft on 2018/7/16. // Copyright © 2018年 jianghongbing. All rights reserved. // import UIKit class VFLViewController: UIViewController, CreateView{ private var myLayoutConstraints: [NSLayoutConstraint] = [] private var redView: UIView! private var greenView: UIView! private var blueView: UIView! private var orangeView: UIView! override func viewDidLoad() { super.viewDidLoad() redView = createView(with: .red, superView: view) greenView = createView(with: .green, superView: view) blueView = createView(with: .blue, superView: view) orangeView = createView(with: .orange, superView: view) } override func updateViewConstraints() { super.updateViewConstraints() if myLayoutConstraints.count > 0 { NSLayoutConstraint.deactivate(myLayoutConstraints) } let views = ["redView": redView!, "greenView": greenView!, "blueView": blueView!, "orangeView": orangeView!] let topMargin = self.view.layoutMargins.top + 20 let bottomMargin = self.view.layoutMargins.bottom + 20 let leftMargin = self.view.layoutMargins.left let rightMargin = self.view.layoutMargins.right let metrics = ["horizonalMargin": 10, "verticalMargin": 20, "topMargin": topMargin, "bottomMargin": bottomMargin, "leftMargin": leftMargin, "rightMargin": rightMargin] var horizonalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[redView(==greenView)]-(horizonalMargin)-[greenView]-(rightMargin)-|", options: [.alignAllTop, .alignAllBottom, .directionLeadingToTrailing], metrics: metrics, views: views) horizonalConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-(leftMargin)-[blueView(==orangeView)]-(horizonalMargin)-[orangeView]-(rightMargin)-|", options: [.alignAllTop, .alignAllBottom, .directionLeadingToTrailing], metrics: metrics, views: views) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[redView(==blueView)]-(verticalMargin)-[blueView]-(bottomMargin)-|", options: [.alignAllLeading, .alignAllCenterX], metrics: metrics, views: views) myLayoutConstraints = horizonalConstraints + verticalConstraints NSLayoutConstraint.activate(myLayoutConstraints) } override func viewLayoutMarginsDidChange() { super.viewLayoutMarginsDidChange() view.setNeedsUpdateConstraints() } }
mit
ed8f83a669f261b0a5ae458ee4ef2a08
49.54902
275
0.706362
5.218623
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/UserProfile/Views/CopyableLabel.swift
1
2545
// // Wire // Copyright (C) 2017 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 UIKit /// This class is a drop-in replacement for UILabel which can be copied. final class CopyableLabel: UILabel { private let dimmedAlpha: CGFloat = 0.4 private let dimmAnimationDuration: TimeInterval = 0.33 override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = true addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressed))) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var canBecomeFirstResponder: Bool { return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return action == #selector(copy(_:)) } override func copy(_ sender: Any?) { UIPasteboard.general.string = text } @objc private func longPressed(_ recognizer: UILongPressGestureRecognizer) { guard recognizer.state == .began, let view = recognizer.view, let superview = view.superview, view == self, becomeFirstResponder() else { return } NotificationCenter.default.addObserver(self, selector: #selector(menuDidHide), name: UIMenuController.didHideMenuNotification, object: nil) UIMenuController.shared.showMenu(from: superview, rect: view.frame) fade(dimmed: true) } @objc private func menuDidHide(_ note: Notification) { NotificationCenter.default.removeObserver(self, name: UIMenuController.didHideMenuNotification, object: nil) fade(dimmed: false) } private func fade(dimmed: Bool) { UIView.animate(withDuration: dimmAnimationDuration) { self.alpha = dimmed ? self.dimmedAlpha : 1 } } }
gpl-3.0
4e7fc749a7908b6146b3b3d17f49ea96
33.391892
147
0.690373
4.748134
false
false
false
false
danielsaidi/KeyboardKit
Sources/KeyboardKit/Haptics/HapticFeedback.swift
1
2490
// // HapticFeedback.swift // KeyboardKit // // Created by Daniel Saidi on 2019-04-26. // Copyright © 2021 Daniel Saidi. All rights reserved. // import UIKit /** This enum provides a streamlined way of working with haptic feedback. You can call `prepare()` and `trigger()` on these hapic feedbacks to prepare and trigger the desired feedback. */ public enum HapticFeedback: CaseIterable { case error, success, warning, lightImpact, mediumImpact, heavyImpact, selectionChanged, none } // MARK: - Public Functions public extension HapticFeedback { func prepare() { HapticFeedback.prepare(self) } static func prepare(_ feedback: HapticFeedback) { switch feedback { case .error, .success, .warning: notificationGenerator.prepare() case .lightImpact: lightImpactGenerator.prepare() case .mediumImpact: mediumImpactGenerator.prepare() case .heavyImpact: heavyImpactGenerator.prepare() case .selectionChanged: selectionGenerator.prepare() case .none: return } } func trigger() { HapticFeedback.trigger(self) } static func trigger(_ feedback: HapticFeedback) { switch feedback { case .error: triggerNotification(.error) case .success: triggerNotification(.success) case .warning: triggerNotification(.warning) case .lightImpact: lightImpactGenerator.impactOccurred() case .mediumImpact: mediumImpactGenerator.impactOccurred() case .heavyImpact: heavyImpactGenerator.impactOccurred() case .selectionChanged: selectionGenerator.selectionChanged() case .none: return } } } // MARK: - Private Trigger Functions private extension HapticFeedback { static func triggerNotification(_ notification: UINotificationFeedbackGenerator.FeedbackType) { notificationGenerator.notificationOccurred(notification) } } // MARK: - Private Generators private extension HapticFeedback { private static var notificationGenerator = UINotificationFeedbackGenerator() private static var lightImpactGenerator = UIImpactFeedbackGenerator(style: .light) private static var mediumImpactGenerator = UIImpactFeedbackGenerator(style: .medium) private static var heavyImpactGenerator = UIImpactFeedbackGenerator(style: .heavy) private static var selectionGenerator = UISelectionFeedbackGenerator() }
mit
8c30e07ed70fc85af51dd8a238a4ace8
26.655556
99
0.701487
5.329764
false
false
false
false
cornerstonecollege/401
401_2016_2/c_examples/Maps/Maps/ViewController.swift
1
1078
// // ViewController.swift // Maps // // Created by younseolocal on 2016-11-07. // Copyright © 2016 younseolocal. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Check if app is authorized and ask for permission if it is not. if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { self.locationManager.requestWhenInUseAuthorization() } // Check again because we do not know if the user gabe us authorization. if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { self.locationManager.startUpdatingLocation() self.locationManager.startUpdatingHeading() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
db3c167df9d9c006f3c748e742076703
24.642857
80
0.657382
5.523077
false
false
false
false
loudnate/LoopKit
LoopKitUI/Views/LevelMaskView.swift
1
2623
// // LevelMaskView.swift // Loop // // Created by Nate Racklyeft on 8/28/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit // Displays a variable-height level indicator, masked by an image. // Inspired by https://github.com/carekit-apple/CareKit/blob/master/CareKit/CareCard/OCKHeartView.h public class LevelMaskView: UIView { var firstDataUpdate = true var value: Double = 1.0 { didSet { animateFill(duration: firstDataUpdate ? 0 : 1.25) firstDataUpdate = false } } private var clampedValue: Double { return value.clamped(to: 0...1.0) } @IBInspectable var maskImage: UIImage? { didSet { fillView?.removeFromSuperview() mask?.removeFromSuperview() maskImageView?.removeFromSuperview() guard let maskImage = maskImage else { fillView = nil mask = nil maskImageView = nil return } mask = UIView() maskImageView = UIImageView(image: maskImage) maskImageView!.contentMode = .center mask!.addSubview(maskImageView!) clipsToBounds = true fillView = UIView() fillView!.backgroundColor = tintColor addSubview(fillView!) } } private var fillView: UIView? private var maskImageView: UIView? override public func layoutSubviews() { super.layoutSubviews() guard let maskImage = maskImage else { return } let maskImageSize = maskImage.size mask?.frame = CGRect(origin: .zero, size: maskImageSize) mask?.center = CGPoint(x: bounds.midX, y: bounds.midY) maskImageView?.frame = mask?.bounds ?? bounds if (fillView?.layer.animationKeys()?.count ?? 0) == 0 { updateFillViewFrame() } } override public func tintColorDidChange() { super.tintColorDidChange() fillView?.backgroundColor = tintColor } private func animateFill(duration: TimeInterval) { UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: { self.updateFillViewFrame() }, completion: nil) } private func updateFillViewFrame() { guard let maskViewFrame = mask?.frame else { return } var fillViewFrame = maskViewFrame fillViewFrame.origin.y = maskViewFrame.maxY fillViewFrame.size.height = -CGFloat(clampedValue) * maskViewFrame.height fillView?.frame = fillViewFrame } }
mit
05549b9ee07d3cdd3716bd825e70ba3c
26.6
103
0.61251
4.984791
false
false
false
false
BareFeetWare/BFWControls
BFWControls/Modules/Alert/View/AlertView.swift
1
5957
// // AlertView.swift // BFWControls // // Created by Tom Brodhurst-Hill on 23/02/2016. // Copyright © 2016 BareFeetWare. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit @IBDesignable open class AlertView: NibView { // MARK: - Structs fileprivate struct ButtonTitle { static let cancel = "Cancel" static let ok = "OK" } fileprivate struct Minimum { static let height: CGFloat = 50.0 } // MARK: - IBOutlets @IBOutlet open weak var titleLabel: UILabel? @IBOutlet open weak var messageLabel: UILabel? @IBOutlet open weak var button0: UIButton? @IBOutlet open weak var button1: UIButton? @IBOutlet open weak var button2: UIButton? @IBOutlet open weak var button3: UIButton? @IBOutlet open weak var button4: UIButton? @IBOutlet open weak var button5: UIButton? @IBOutlet open weak var button6: UIButton? @IBOutlet open weak var button7: UIButton? @IBOutlet open var horizontalButtonsLayoutConstraints: [NSLayoutConstraint]? @IBOutlet open var verticalButtonsLayoutConstraints: [NSLayoutConstraint]? // MARK: - Variables @IBInspectable open var title: String? { get { return titleLabel?.text } set { titleLabel?.text = newValue } } @IBInspectable open var message: String? { get { return messageLabel?.text } set { messageLabel?.text = newValue } } @IBInspectable open var hasCancel: Bool = true { didSet { setNeedsUpdateView() } } @IBInspectable open var button0Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button1Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button2Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button3Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button4Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button5Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button6Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var button7Title: String? { didSet { setNeedsUpdateView() } } @IBInspectable open var maxHorizontalButtonTitleCharacterCount: Int = 9 { didSet { setNeedsUpdateView() } } // MARK: - Functions open func buttonTitle(at index: Int) -> String? { let button = buttons[index] return button.currentTitle } open func index(of button: UIButton) -> Int? { return buttons.firstIndex(of: button) } open func button(forTitle title: String) -> UIButton? { return actions.first { $0.title == title }?.button } // MARK: - Private variables and functions typealias Action = (button: UIButton?, title: String?) fileprivate var displayedButton0Title: String { return button0Title ?? (hasCancel ? ButtonTitle.cancel : ButtonTitle.ok) } fileprivate var bottomActions: [Action] { return [ (button0, displayedButton0Title), (button1, button1Title) ] } fileprivate var topActions: [Action] { return [ (button2, button2Title), (button3, button3Title), (button4, button4Title), (button5, button5Title), (button6, button6Title), (button7, button7Title) ] } fileprivate var actions: [Action] { return bottomActions + topActions } fileprivate var buttons: [UIButton] { return actions.compactMap { $0.button } } fileprivate var isHorizontalLayout: Bool { let hasTopTitles = topActions.compactMap { $0.title }.count > 0 let hasShortBottomTitles = bottomActions.compactMap { action in action.title }.filter { title in title.count <= maxHorizontalButtonTitleCharacterCount }.count == 2 return hasShortBottomTitles && !hasTopTitles } fileprivate func hideUnused() { for action in actions { action.button?.isHidden = action.title == nil || isPlaceholderString(action.title) } messageLabel?.activateOnlyConstraintsWithFirstVisible(in: buttons.reversed()) if let stackView = button0?.superview as? UIStackView { stackView.axis = isHorizontalLayout ? .horizontal : .vertical } else if let horizontalButtonsLayoutConstraints = horizontalButtonsLayoutConstraints, let verticalButtonsLayoutConstraints = verticalButtonsLayoutConstraints { if isHorizontalLayout { NSLayoutConstraint.activate(horizontalButtonsLayoutConstraints) NSLayoutConstraint.deactivate(verticalButtonsLayoutConstraints) } else { NSLayoutConstraint.activate(verticalButtonsLayoutConstraints) NSLayoutConstraint.deactivate(horizontalButtonsLayoutConstraints) } } } // MARK: - UIView // Override NibView which copies size from xib. Forces calculation using contents. open override var intrinsicContentSize : CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: Minimum.height) } open override func layoutSubviews() { hideUnused() super.layoutSubviews() } // MARK: - NibView open override var placeholderViews: [UIView] { return [titleLabel, messageLabel].compactMap { $0 } } open override func updateView() { super.updateView() for action in actions { action.button?.setTitle(action.title, for: .normal) } } }
mit
5f444d78939b91020856d8d0d17b76b6
31.194595
94
0.625252
5.103685
false
false
false
false
BananosTeam/CreativeLab
Assistant/Trello/Models/List.swift
1
861
// // List.swift // Assistant // // Created by Dmitrii Celpan on 5/14/16. // Copyright © 2016 Bananos. All rights reserved. // import Foundation final class List { var id: String? var name: String? var closed: Bool? var idBoard: String? var subscribed: Bool? } final class ListParser { func listsFromDictionaties(dictionaries: [NSDictionary]) -> [List] { return dictionaries.map() { listFromDictionary($0) } } func listFromDictionary(dictionary: NSDictionary) -> List { let list = List() list.id = dictionary["id"] as? String list.name = dictionary["name"] as? String list.closed = dictionary["closed"] as? Bool list.idBoard = dictionary["idBoard"] as? String list.subscribed = dictionary["subscribed"] as? Bool return list } }
mit
4679dde6bb70fc5eac920d7ef37ae084
22.243243
72
0.616279
4.018692
false
false
false
false
amco/couchbase-lite-ios
Swift/MutableFragment.swift
1
6664
// // MutableFragment.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// MutableFragmentProtocol provides read and write access to the data value /// wrapped by a fragment object. protocol MutableFragmentProtocol: FragmentProtocol { var value: Any? { get set } var string: String? { get set } var number: NSNumber? { get set } var int: Int { get set } var int64: Int64 { get set } var float: Float { get set } var double: Double { get set } var boolean: Bool { get set } var date: Date? { get set } var blob: Blob? { get set } var array: MutableArrayObject? { get set } var dictionary: MutableDictionaryObject? { get set } } /// MutableArrayFragment protocol provides subscript access to Fragment objects /// by index. protocol MutableArrayFragment { subscript(index: Int) -> MutableFragment { get } } /// MutableDictionaryFragment protocol provides subscript access to /// CBLMutableFragment objects by key. protocol MutableDictionaryFragment { subscript(key: String) -> MutableFragment { get } } /// MutableFragment provides read and write access to data value. MutableFragment also provides /// subscript access by either key or index to the nested values which are wrapped by /// MutableFragment objects. public final class MutableFragment: Fragment, MutableDictionaryFragment, MutableArrayFragment { /// Gets the value from or sets the value to the fragment object. public override var value: Any? { get { return DataConverter.convertGETValue(fragmentImpl.value) } set { fragmentImpl.value = (DataConverter.convertSETValue(newValue) as! NSObject) } } /// Gets the value as string or sets the string value to the fragment object. public override var string: String? { get { return fragmentImpl.string } set { fragmentImpl.string = newValue } } /// Gets the value as number or sets the number value to the fragment object. public override var number: NSNumber? { get { return fragmentImpl.number } set { fragmentImpl.number = newValue } } /// Gets the value as integer or sets the integer value to the fragment object. public override var int: Int { get { return fragmentImpl.integerValue } set { fragmentImpl.integerValue = newValue } } /// Gets the value as integer or sets the integer value to the fragment object. public override var int64: Int64 { get { return fragmentImpl.longLongValue } set { fragmentImpl.longLongValue = newValue } } /// Gets the value as float or sets the float value to the fragment object. public override var float: Float { get { return fragmentImpl.floatValue } set { fragmentImpl.floatValue = newValue } } /// Gets the value as double or sets the double value to the fragment object. public override var double: Double { get { return fragmentImpl.doubleValue } set { fragmentImpl.doubleValue = newValue } } /// Gets the value as boolean or sets the boolean value to the fragment object. public override var boolean: Bool { get { return fragmentImpl.booleanValue } set { fragmentImpl.booleanValue = newValue } } /// Gets the value as blob or sets the blob value to the fragment object. public override var date: Date? { get { return fragmentImpl.date } set { fragmentImpl.date = newValue } } /// Gets the value as blob or sets the blob value to the fragment object. public override var blob: Blob? { get { return fragmentImpl.blob } set { fragmentImpl.blob = newValue } } /// Get the value as an MutableArrayObject object, a mapping object of an array value. /// Returns nil if the value is nil, or the value is not an array. public override var array: MutableArrayObject? { get { return DataConverter.convertGETValue(fragmentImpl.array) as? MutableArrayObject } set { fragmentImpl.array = (DataConverter.convertSETValue(newValue) as! CBLMutableArray) } } /// Get a property's value as a MutableDictionaryObject object, a mapping object of /// a dictionary value. Returns nil if the value is nil, or the value is not a dictionary. public override var dictionary: MutableDictionaryObject? { get { return DataConverter.convertGETValue(fragmentImpl.dictionary) as? MutableDictionaryObject } set { fragmentImpl.dictionary = (DataConverter.convertSETValue(newValue) as! CBLMutableDictionary) } } // MARK: Subscripts /// Subscript access to a MutableFragment object by index. /// /// - Parameter index: The index. public override subscript(index: Int) -> MutableFragment { return MutableFragment(fragmentImpl[UInt(index)]) } /// Subscript access to a MutableFragment object by key. /// /// - Parameter key: The key. public override subscript(key: String) -> MutableFragment { return MutableFragment(fragmentImpl[key]) } // MARK: Internal init(_ impl: CBLMutableFragment?) { super.init(impl ?? MutableFragment.kNonexistent) } // MARK: Private private var fragmentImpl: CBLMutableFragment { return _impl as! CBLMutableFragment } static let kNonexistent = CBLMutableFragment() }
apache-2.0
324e178b65741f68e6e4fc0618c85c1b
26.53719
104
0.620198
5.071537
false
false
false
false
lionheart/LionheartTableViewCells
Example/Tests/Tests.swift
1
1190
// https://github.com/Quick/Quick import Quick import Nimble import LionheartTableViewCells class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
apache-2.0
07c890bd909d3a726f687226e67c83a5
22.68
63
0.370777
5.506977
false
false
false
false
THREDOpenSource/SYNUtils
SYNUtils/SYNUtils/Extensions/NSTimer+Utils.swift
2
5617
// // NSTimer+Utils.swift // SYNUtils // // Created by John Hurliman on 6/23/15. // Copyright (c) 2015 Syntertainment. All rights reserved. // import Foundation public enum BackoffStrategy { case Exponential case Fibonacci } extension NSTimer { public typealias TimerCallback = NSTimer! -> Void /// Schedule a function to run once after the specified delay. /// /// :param: delay Number of seconds to wait before running the function /// :param: handler Function to run /// :returns: The newly created timer associated with this execution public class func schedule(delay afterDelay: NSTimeInterval, handler: TimerCallback) -> NSTimer { let fireDate = afterDelay + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes) return timer } /// Schedule a function to run continuously with the specified interval. /// /// :param: repeatInterval Number of seconds to wait before running the /// function the first time, and in between each successive run /// :param: handler Function to return /// :returns: The newly created timer associated with this execution public class func schedule(repeatInterval interval: NSTimeInterval, handler: TimerCallback) -> NSTimer { let fireDate = interval + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes) return timer } } extension NSTimer { public typealias SuccessCallback = Bool -> Void public typealias AsyncCallback = SuccessCallback -> Void /// Run the given callback immediately. If the callback calls its completion /// handler with a false value, the callback will be scheduled to run again /// in the future using the given delay and backoff strategy settings. This /// process will repeat each time the completion handler is called, until it /// is called with a true value. /// /// NSTimer.tryWithBackoff(.Fibonacci, 0.5, 30.0) { /// (done: Bool -> Void) in /// // Do work, then call done with success/failure /// done(true) /// } /// /// :param: strategy Backoff strategy. Exponential and Fibonacci backoff are /// currently supported. Both strategies incorporate up to 10% random /// jitter as well /// :param: firstDelay Starting delay, after the callback has failed once /// :param: maxDelay Upper limit on the delay between callbacks /// :param: callback Callback to run immediately and again after each /// failure public class func tryWithBackoff( strategy: BackoffStrategy, firstDelay: NSTimeInterval, maxDelay: NSTimeInterval, callback: AsyncCallback) { // Run the callback immediately callback { (success: Bool) in if success { return } // Create the timer let timerInfo = BackoffTimerInfo(strategy: strategy, delay: firstDelay, nextDelay: firstDelay, maxDelay: maxDelay, callback: callback) NSTimer.scheduledTimerWithTimeInterval(firstDelay, target: timerInfo, selector: "timerDidFire:", userInfo: timerInfo, repeats: false) } } private class BackoffTimerInfo: NSObject { let strategy: BackoffStrategy let delay: NSTimeInterval let nextDelay: NSTimeInterval let maxDelay: NSTimeInterval let callback: AsyncCallback init(strategy: BackoffStrategy, delay: NSTimeInterval, nextDelay: NSTimeInterval, maxDelay: NSTimeInterval, callback: AsyncCallback) { self.strategy = strategy self.delay = delay self.nextDelay = nextDelay self.maxDelay = maxDelay self.callback = callback } @objc func timerDidFire(timer: NSTimer!) { let this = self let timerInfo = timer.userInfo as! BackoffTimerInfo timerInfo.callback { (success: Bool) in if success { return } var delay: NSTimeInterval var nextDelay: NSTimeInterval switch (timerInfo.strategy) { case .Exponential: delay = timerInfo.delay * 2.0 nextDelay = delay break; case .Fibonacci: delay = timerInfo.nextDelay nextDelay = timerInfo.nextDelay + timerInfo.delay break; } let userInfo = BackoffTimerInfo(strategy: timerInfo.strategy, delay: delay, nextDelay: nextDelay, maxDelay: timerInfo.maxDelay, callback: timerInfo.callback) // Add up to 10% random jitter and cap at max delay delay = min(timerInfo.maxDelay, delay + NSTimer.jitter(delay, percent: 0.1)) NSTimer.scheduledTimerWithTimeInterval(delay, target: this, selector: "timerDidFire:", userInfo: userInfo, repeats: false) } } } class func jitter(x: Double, percent: Double) -> Double { return Double.random(0.0, x) * percent } }
mit
aa8cb822479b6b8baee63dee8b66e6ae
39.410072
142
0.617767
5.48
false
false
false
false
alibaba/coobjc
Examples/coSwiftDemo/coSwiftDemoTests/coSwiftSequenceTests.swift
1
3015
// // coSwiftSequenceTests.swift // coSwiftDemoTests // // Copyright © 2018 Alibaba Group Holding Limited All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import coswift import Quick import Nimble class SequenceSpec: QuickSpec { override func spec() { describe("Generator tests") { it("test sequence on same queue") { var step = 0; let gen = co_sequence(Int.self) { var i = 0; while true { try yield { i } step = i; i += 1; } } let co = co_launch { for i in 0..<10 { let val = try gen.next() expect(val).to(equal(i)) } gen.cancel() } waitUntil { done in co_launch { co.join() gen.join() expect(step).to(equal(9)) done() } } } it("yield value chain") { var step = 0; let sq1 = co_sequence(Int.self) { var i = 0; while true { try yield { i } step = i; i+=1; } } let sq2 = co_sequence(Int.self) { while true { try yield { try sq1.next() } } } let co = co_launch { for i in 0..<10 { let val = try sq2.next() expect(val).to(equal(i)) } sq1.cancel() sq2.cancel() } waitUntil { done in co_launch { co.join() expect(step).to(equal(9)) done() } } } } } }
apache-2.0
487b43122f5cf83713d741b7325975b9
28.262136
77
0.359987
5.612663
false
false
false
false
Matzo/Kamishibai
Kamishibai/Classes/KamishibaiFocusView.swift
1
6076
// // KamishibaiFocusView.swift // Hello // // Created by Keisuke Matsuo on 2017/08/12. // // import UIKit public class KamishibaiFocusView: UIView { // MARK: Properties public var focus: FocusType? public var animationDuration: TimeInterval = 0.5 var maskLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.fillRule = kCAFillRuleEvenOdd layer.fillColor = UIColor.black.cgColor return layer }() // MARK: Initializing override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSubviews() { super.layoutSubviews() maskLayer.frame = self.bounds } func setup() { backgroundColor = UIColor.black.withAlphaComponent(0.55) layer.mask = maskLayer isUserInteractionEnabled = false } // MARK: Public Methods public func appear(focus: FocusType, completion: (() -> Void)? = nil) { CATransaction.begin() CATransaction.setCompletionBlock(completion) layer.add(alphaAnimation(animationDuration, from: 0.0, to: 1.0), forKey: nil) maskLayer.add(appearAnimation(animationDuration, focus: focus), forKey: nil) self.focus = focus CATransaction.commit() } public func move(to focus: FocusType, completion: (() -> Void)? = nil) { CATransaction.begin() CATransaction.setCompletionBlock(completion) maskLayer.add(moveAnimation(animationDuration, focus: focus), forKey: nil) self.focus = focus CATransaction.commit() } public func disappear(completion: (() -> Void)? = nil) { CATransaction.begin() CATransaction.setCompletionBlock(completion) layer.add(alphaAnimation(animationDuration, to: 0.0), forKey: nil) self.focus = nil CATransaction.commit() } // MARK: Private Methods // MARK: CAAnimation func maskPath(_ path: UIBezierPath) -> UIBezierPath { let screenRect = UIScreen.main.bounds return [path].reduce(UIBezierPath(rect: screenRect)) { $0.append($1) return $0 } } func appearAnimation(_ duration: TimeInterval, focus: FocusType) -> CAAnimation { let beginPath = maskPath(focus.initialPath != nil ? focus.initialPath! : focus.path) let endPath = maskPath(focus.path) return pathAnimation(duration, beginPath: beginPath, endPath: endPath) } func disappearAnimation(_ duration: TimeInterval) -> CAAnimation { return alphaAnimation(duration, from: 1.0, to: 0.0) } func moveAnimation(_ duration: TimeInterval, focus: FocusType) -> CAAnimation { let endPath = maskPath(focus.path) return pathAnimation(duration, beginPath: nil, endPath: endPath) } func alphaAnimation(_ duration: TimeInterval, from: CGFloat? = nil, to: CGFloat) -> CAAnimation { let animation = CABasicAnimation(keyPath: "opacity") animation.duration = duration animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.66, 0, 0.33, 1) if let from = from { animation.fromValue = from } animation.toValue = to animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards return animation } func pathAnimation(_ duration: TimeInterval, beginPath: UIBezierPath?, endPath: UIBezierPath) -> CAAnimation { let animation = CABasicAnimation(keyPath: "path") animation.duration = duration animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.66, 0, 0.33, 1) if let path = beginPath { animation.fromValue = path.cgPath } animation.toValue = endPath.cgPath animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards return animation } } public protocol FocusType { var frame: CGRect { get } var initialPath: UIBezierPath? { get } var path: UIBezierPath { get } } public struct Focus { public struct Rect: FocusType { public var frame: CGRect public var initialFrame: CGRect? public var initialPath: UIBezierPath? { if let initialFrame = initialFrame { return UIBezierPath(rect: initialFrame) } return nil } public var path: UIBezierPath { return UIBezierPath(rect: frame) } public init(frame: CGRect, initialFrame: CGRect? = nil) { self.frame = frame self.initialFrame = initialFrame } } public struct RoundRect: FocusType { public var frame: CGRect public var initialFrame: CGRect? public var cornerRadius: CGFloat public var initialPath: UIBezierPath? { if let initialFrame = initialFrame { return UIBezierPath(roundedRect: initialFrame, cornerRadius: cornerRadius) } return nil } public var path: UIBezierPath { return UIBezierPath(roundedRect: frame, cornerRadius: cornerRadius) } public init(frame: CGRect, initialFrame: CGRect? = nil, cornerRadius: CGFloat) { self.frame = frame self.initialFrame = initialFrame self.cornerRadius = cornerRadius } } public struct Oval: FocusType { public var frame: CGRect public var initialFrame: CGRect? public var initialPath: UIBezierPath? { if let initialFrame = initialFrame { return UIBezierPath(ovalIn: initialFrame) } return nil } public var path: UIBezierPath { return UIBezierPath(ovalIn: frame) } public init(frame: CGRect, initialFrame: CGRect? = nil) { self.frame = frame self.initialFrame = initialFrame } } }
mit
839291781da2842fd009c7549ceae5f1
31.148148
114
0.625082
5.110177
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRides/BaseDeeplink.swift
1
6199
// // BaseDeeplink.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** * A Deeplinking object for authenticating a user via the native Uber app */ @objc(UBSDKBaseDeeplink) public class BaseDeeplink: NSObject, Deeplinking { /// The scheme for the auth deeplink public var scheme: String /// The domain for the auth deeplink public var domain: String /// The path for the auth deeplink public var path: String /// The array of query items the deeplink will include public var queryItems: [URLQueryItem]? public let deeplinkURL: URL private var waitingOnSystemPromptResponse = false private var checkingSystemPromptResponse = false private var promptTimer: Timer? private var completionWrapper: ((NSError?) -> ()) = { _ in } @objc public init?(scheme: String, domain: String, path: String, queryItems: [URLQueryItem]?) { self.scheme = scheme self.domain = domain self.path = path self.queryItems = queryItems var requestURLComponents = URLComponents() requestURLComponents.scheme = scheme requestURLComponents.host = domain requestURLComponents.path = path requestURLComponents.queryItems = queryItems guard let deeplinkURL = requestURLComponents.url else { return nil } self.deeplinkURL = deeplinkURL super.init() } /** Executes the base deeplink, accounting for the possiblity of an alert appearing on iOS 9+ - parameter completion: The completion block to execute once the deeplink has executed. Passes in True if the url was successfully opened, false otherwise. */ @objc public func execute(completion: ((NSError?) -> ())? = nil) { let usingIOS9 = ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 9, minorVersion: 0, patchVersion: 0)) if usingIOS9 { executeOnIOS9(completion) } else { executeOnBelowIOS9(completion) } } //Mark: Internal Interface func executeOnIOS9(_ completion: ((NSError?) -> ())?) { NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveHandler), name: Notification.Name.UIApplicationWillResignActive, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveHandler), name: Notification.Name.UIApplicationDidBecomeActive, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackgroundHandler), name: Notification.Name.UIApplicationDidEnterBackground, object: nil) completionWrapper = { handled in NotificationCenter.default.removeObserver(self) self.promptTimer?.invalidate() self.promptTimer = nil self.checkingSystemPromptResponse = false self.waitingOnSystemPromptResponse = false completion?(handled) } var error: NSError? if UIApplication.shared.canOpenURL(deeplinkURL) { let openedURL = UIApplication.shared.openURL(deeplinkURL) if !openedURL { error = DeeplinkErrorFactory.errorForType(.unableToFollow) } } else { error = DeeplinkErrorFactory.errorForType(.unableToOpen) } if error != nil { completionWrapper(error) } } func executeOnBelowIOS9(_ completion: ((NSError?) -> ())?) { completionWrapper = { handled in completion?(handled) } var error: NSError? if UIApplication.shared.canOpenURL(deeplinkURL) { let openedURL = UIApplication.shared.openURL(deeplinkURL) if !openedURL { error = DeeplinkErrorFactory.errorForType(.unableToFollow) } } else { error = DeeplinkErrorFactory.errorForType(.unableToOpen) } completionWrapper(error) } //Mark: App Lifecycle Notifications @objc private func appWillResignActiveHandler(_ notification: Notification) { if !waitingOnSystemPromptResponse { waitingOnSystemPromptResponse = true } else if checkingSystemPromptResponse { completionWrapper(nil) } } @objc private func appDidBecomeActiveHandler(_ notification: Notification) { if waitingOnSystemPromptResponse { checkingSystemPromptResponse = true promptTimer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(deeplinkHelper), userInfo: nil, repeats: false) } } @objc private func appDidEnterBackgroundHandler(_ notification: Notification) { completionWrapper(nil) } @objc private func deeplinkHelper() { let error = DeeplinkErrorFactory.errorForType(.deeplinkNotFollowed) completionWrapper(error) } }
mit
77f2fe4b2937988d271a511d79dc4cf1
37.02454
173
0.667312
5.380208
false
false
false
false
noprom/Cocktail-Pro
smartmixer/smartmixer/UserCenter/UserHome.swift
1
16512
// // UserHome.swift // smartmixer // // Created by 姚俊光 on 14/9/29. // Copyright (c) 2014年 smarthito. All rights reserved. // import UIKit import CoreData class UserHome: UIViewController,UIScrollViewDelegate,UITableViewDelegate,HistoryCellDelegate,NSFetchedResultsControllerDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ //用户信息的View @IBOutlet var userInfoLayer:UIView! //用户背景图片 @IBOutlet var userInfoBg:UIImageView! //用户信息距顶部的控制 @IBOutlet var userInfoframe: UIView! //信息的滚动 @IBOutlet var scollViewMap:UIScrollView! //概览信息 @IBOutlet var sumInfo:UILabel! //用户名字 @IBOutlet var userName:UILabel! //用户头像 @IBOutlet var userImage:UIImageView! //点击还原的我按钮 @IBOutlet var myButton:UIButton! //没有数据时的提示 @IBOutlet var nodataTip:UILabel! //历史信息的table @IBOutlet var historyTableView:UITableView! var clickGesture:UITapGestureRecognizer! class func UserHomeRoot()->UIViewController{ let userCenterController = UIStoryboard(name:"UserCenter"+deviceDefine,bundle:nil).instantiateInitialViewController() as! UserHome return userCenterController } override func viewDidLoad() { super.viewDidLoad() let fileManager = NSFileManager.defaultManager() if(fileManager.isReadableFileAtPath(applicationDocumentsPath+"/mybg.png")){ userInfoBg.image = UIImage(contentsOfFile: applicationDocumentsPath+"/mybg.png") } userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png") userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")! self.userInfoframe.userInteractionEnabled = true clickGesture = UITapGestureRecognizer() clickGesture.addTarget(self, action: Selector("changeHomebg:")) clickGesture?.delegate = self self.userInfoframe.addGestureRecognizer(clickGesture!) scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50)) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.tabBarController?.tabBar.hidden = true self.hidesBottomBarWhenPushed = true self.navigationController?.setNavigationBarHidden(true, animated: true) let UserCook = NSUserDefaults.standardUserDefaults().integerForKey("UserCook") let UserFavor = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor") let UserHave = NSUserDefaults.standardUserDefaults().integerForKey("UserHave") let UserContainer = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer") sumInfo.text = "\(UserFavor)个收藏,\(UserCook)次制作,\(UserHave)种材料,\(UserContainer)种器具" userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png") userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")! scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50)) rootController.showOrhideToolbar(true) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } //@MARK:修改主页的背景选取照片 var imagePicker:UIImagePickerController! var popview:UIPopoverController! //修改主页的背景图片 func changeHomebg(sender:UITapGestureRecognizer){ if(scollViewMap.contentOffset.y>10){ UIView.animateWithDuration(0.3, animations: { self.userInfoframe.frame = CGRect(x: self.userInfoframe.frame.origin.x, y: 0, width: self.userInfoframe.frame.width, height: self.userInfoframe.frame.height) self.userInfoLayer.alpha = 1 self.myButton.hidden = true self.setalpha = false self.view.layoutIfNeeded() }) self.scollViewMap.contentOffset.y = 0 }else{ imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical imagePicker.tabBarItem.title="请选择背景图片" if(deviceDefine==""){ self.presentViewController(imagePicker, animated: true, completion: nil) }else{ popview = UIPopoverController(contentViewController: imagePicker) popview.presentPopoverFromRect(CGRect(x: 512, y: 50, width: 10, height: 10), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } } } //写入Document中 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info["UIImagePickerControllerOriginalImage"] as! UIImage userInfoBg.image = image let imageData = UIImagePNGRepresentation(image) imageData!.writeToFile(applicationDocumentsPath+"/mybg.png", atomically: false) self.dismissViewControllerAnimated(true, completion: nil) if(osVersion<8 && deviceDefine != ""){ popview.dismissPopoverAnimated(true) } } //@MARK:点击商城 @IBAction func OnStoreClick(sender:UIButton){ let baike:WebView = WebView.WebViewInit() baike.myWebTitle = "商城" baike.WebUrl="http://www.smarthito.com" rootController.showOrhideToolbar(false) baike.showToolbar = true self.navigationController?.pushViewController(baike, animated: true) } //@MARK:点击设置 var aboutview:UIViewController! @IBAction func OnSettingClick(sender:UIButton){ if(deviceDefine==""){ aboutview = AboutViewPhone.AboutViewPhoneInit() }else{ aboutview = AboutViewPad.AboutViewPadInit() } self.navigationController?.pushViewController(aboutview, animated: true) rootController.showOrhideToolbar(false) } //#MARK:这里是处理滚动的处理向下向上滚动影藏控制栏 var lastPos:CGFloat = 0 //滚动开始记录开始偏移 func scrollViewWillBeginDragging(scrollView: UIScrollView) { lastPos = scrollView.contentOffset.y } var setalpha:Bool=false func scrollViewDidScroll(scrollView: UIScrollView) { let off = scrollView.contentOffset.y if(off<=240 && off>0){//在区间0~240需要渐变处理 userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -off, width: userInfoframe.frame.width, height: userInfoframe.frame.height) userInfoLayer.alpha = 1-off/240 myButton.hidden = true setalpha = false }else if(off>240 && setalpha==false){//大于240区域 userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -240, width: userInfoframe.frame.width, height: userInfoframe.frame.height) userInfoLayer.alpha = 0 myButton.hidden = false setalpha = true }else if(off<0){ userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: 0, width: userInfoframe.frame.width, height: userInfoframe.frame.height) self.userInfoLayer.alpha = 1 self.myButton.hidden = true self.setalpha = false } /**/ if((off-lastPos)>50 && off>50){//向下了 lastPos = off rootController.showOrhideToolbar(false) }else if((lastPos-off)>70){ lastPos = off rootController.showOrhideToolbar(true) } } var numberOfObjects:Int=0 //@MARK:这里是处理显示数据的 //告知窗口现在有多少个item需要添加 func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections! let item = sectionInfo[section] numberOfObjects = item.numberOfObjects if(numberOfObjects==0){ nodataTip.hidden = false }else{ nodataTip.hidden = true } historyTableView.contentSize = CGSize(width: 0, height: CGFloat(numberOfObjects*50)) return item.numberOfObjects } //处理单个View的添加 func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History var indentifier = "his-cook" if(item.type==1){ indentifier="his-addfaver" }else if(item.type==2){ indentifier="his-addhave" }else if(item.type==3){ indentifier="his-addhave" } let cell :HistoryCell = tableView.dequeueReusableCellWithIdentifier(indentifier) as! HistoryCell if(deviceDefine==""){ cell.scroll.contentSize = CGSize(width: 380, height: 50) }else{ //cell.scroll.contentSize = CGSize(width: 1104, height: 50) } cell.name.text = item.name cell.thumb.image = UIImage(named: item.thumb) cell.time.text = formatDateString(item.addtime) cell.delegate = self return cell } var lastDayString:String!=nil func formatDateString(date:NSDate)->String{ let formatter = NSDateFormatter() formatter.dateFormat="yyyy.MM.dd" let newstring = formatter.stringFromDate(date) if(newstring != lastDayString){ lastDayString = newstring return lastDayString }else{ return "." } } //要删除某个 func historyCell(sender:HistoryCell){ skipUpdate = true let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)! let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History managedObjectContext.deleteObject(item) do { try managedObjectContext.save() }catch{ abort() } // if !managedObjectContext.save(&error) { // abort() // } self.historyTableView?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top) } //选中某个需要显示 func historyCell(sender:HistoryCell,show ShowCell:Bool){ self.navigationController?.setNavigationBarHidden(false, animated: false) rootController.showOrhideToolbar(false) let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)! let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History if(item.type==0||item.type==1){ let recipe=DataDAO.getOneRecipe(item.refid.integerValue) if(deviceDefine==""){ let recipeDetail = RecipeDetailPhone.RecipesDetailPhoneInit() recipeDetail.CurrentData = recipe self.navigationController?.pushViewController(recipeDetail, animated: true) }else{ let recipeDetail = RecipeDetailPad.RecipeDetailPadInit() recipeDetail.CurrentData = recipe self.navigationController?.pushViewController(recipeDetail, animated: true) } }else if(item.type==2){ let materials = IngredientDetail.IngredientDetailInit() materials.ingridient=DataDAO.getOneIngridient(item.refid.integerValue) self.navigationController?.pushViewController(materials, animated: true) }else if(item.type==3){ let container = ContainerDetail.ContainerDetailInit() container.CurrentContainer = DataDAO.getOneContainer(item.refid.integerValue) self.navigationController?.pushViewController(container, animated: true) } } //@MARK:历史数据的添加处理 class func addHistory(type:Int,id refId:Int,thumb imageThumb:String,name showName:String){ let history = NSEntityDescription.insertNewObjectForEntityForName("History", inManagedObjectContext: managedObjectContext) as! History history.type = type history.refid = refId history.thumb = imageThumb history.name = showName history.addtime = NSDate() if(type==0){ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")+1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook") do { try managedObjectContext.save() }catch{ abort() } // var error: NSError? = nil // if !managedObjectContext.save(&error) { // abort() // } }else if(type==1){ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")+1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor") }else if(type==2){//添加了材料的拥有 let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")+1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave") DataDAO.updateRecipeCoverd(refId, SetHave: true) }else{ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")+1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer") } } //历史数据的删除 class func removeHistory(type:Int,id refId:Int){ if(type==0){ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")-1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook") }else if(type==1){ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")-1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor") }else if(type==2){ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")-1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave") DataDAO.updateRecipeCoverd(refId, SetHave: false) }else{ let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")-1 NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer") } } //@MARK:数据的读取 var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName("History", inManagedObjectContext: managedObjectContext) fetchRequest.fetchBatchSize = 30 fetchRequest.sortDescriptors = [NSSortDescriptor(key: "addtime", ascending: false)] let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) _fetchedResultsController = aFetchedResultsController _fetchedResultsController?.delegate = self do { try self.fetchedResultsController.performFetch() }catch{ abort() } // var error: NSError? = nil // if !_fetchedResultsController!.performFetch(&error) { // abort() // } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil var skipUpdate:Bool=false func controllerDidChangeContent(controller: NSFetchedResultsController) { if(skipUpdate){ skipUpdate=false }else{ _fetchedResultsController = nil historyTableView.reloadData() lastDayString=nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
dc5b83882e5be4455553cd857af09640
40.426357
220
0.658496
5.158301
false
false
false
false
rosslebeau/AdventOfCode
Day8/day8playground.playground/Contents.swift
1
2413
import Foundation func replaceWith(string: String, matchRegex: NSRegularExpression, replacement: String) -> String { let cleanString = NSMutableString(string: string) matchRegex.replaceMatchesInString(cleanString, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, cleanString.length), withTemplate:replacement); return cleanString as String } func trimEnds(string: String) -> String { let trimEnds = Range<String.CharacterView.Index>(start: string.characters.startIndex.successor(), end:string.characters.endIndex.predecessor()) return string[trimEnds] } func part1(lines: [String]) throws -> Int { let hexMatch = "[0-9a-f]" let escapeDecodeRegex = try NSRegularExpression(pattern: "\\\\\\\\|\\\\\\\"|\\\\x" + hexMatch + hexMatch, options:NSRegularExpressionOptions(rawValue: 0)) // Trim the quotes off either end of the string, then replace any escape patterns with a placeholder character let unescapedLines = lines .map({line in trimEnds(line)}) .map({line in replaceWith(line, matchRegex: escapeDecodeRegex, replacement: ".")}) return lines.map({line in line.characters.count}).reduce(0, combine:+) - unescapedLines.map({line in line.characters.count}).reduce(0, combine:+) } func part2(lines: [String]) throws -> Int { let escapeEncodeRegex = try NSRegularExpression(pattern: "(\\\\|\\\")", options:NSRegularExpressionOptions(rawValue: 0)) let escapedLines = lines .map({line in replaceWith(line, matchRegex: escapeEncodeRegex, replacement: "\\\\$1")}) .map({line in "\"" + line + "\""}) return escapedLines.map({line in line.characters.count}).reduce(0, combine:+) - lines.map({line in line.characters.count}).reduce(0, combine:+) } enum AdventError: ErrorType { case InputPathFailed } do { guard let filePath = NSBundle.mainBundle().pathForResource("input", ofType: nil) else { throw AdventError.InputPathFailed } let fileContent = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) let lines = fileContent.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).filter{!$0.isEmpty} as [String] try print("Part 1: \(part1(lines))") try print("Part 2: \(part2(lines))") } catch let caught as NSError { print("error: " + caught.description) }
mit
ccd47e9b04f18cc01926d1fc6309881d
39.216667
161
0.689598
4.308929
false
false
false
false
pierrewehbe/MyVoice
MyVoice/AudioObject.swift
1
1015
// // AudioFile.swift // MyVoice // // Created by Pierre on 12/28/16. // Copyright © 2016 Pierre. All rights reserved. // import Foundation class AudioObject { var name : String var duration : String var dateOfCreation : String var directory : String var flags : [TimeInterval] init(){ self.name = "NONAME" self.duration = "00:00:00" self.dateOfCreation = "Never Created" self.directory = "DOESN'T EXIST" self.flags = [] } init(n: String, d: String , dof: String, dir: String , f : [TimeInterval]){ self.name = n self.duration = d self.dateOfCreation = dof self.directory = dir self.flags = f } func printInfo(){ print(name) print(duration) print(dateOfCreation) print(directory) print(flags) } }
mit
8bf679452c5b57a75360ecd68d5e00ed
21.043478
79
0.491124
4.155738
false
false
false
false
blstream/mEatUp
mEatUp/mEatUp/Room.swift
1
1112
// // Room.swift // mEatUp // // Created by Paweł Knuth on 11.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import Foundation import CloudKit class Room: CloudKitObject, Equatable { static let entityName = "Room" var title: String? var accessType: AccessType? var restaurant: Restaurant? var maxCount: Int? var date: NSDate? var owner: User? var didEnd: Bool? = false var recordID: CKRecordID? var eventOccured: Bool { guard let date = date else { return true } return date.isLessThanDate(NSDate()) } init(title: String, accessType: AccessType, restaurant: Restaurant, maxCount: Int, date: NSDate, owner: User) { self.title = title self.accessType = accessType self.restaurant = restaurant self.maxCount = maxCount self.date = date self.owner = owner } init() { owner = User() restaurant = Restaurant() } } func == (lhs: Room, rhs: Room) -> Bool { return lhs.recordID == rhs.recordID }
apache-2.0
bc97ce5f30cb26add005d173d67c04b7
20.346154
115
0.594595
4.236641
false
false
false
false
MattLewin/Interview-Prep
Cracking the Coding Interview.playground/Pages/Stacks and Queues.xcplaygroundpage/Contents.swift
1
23896
//: [Previous](@previous) [Next](@next) //: # Stacks and Queues import Darwin // for arc4random() import Foundation /*: --- ## 3.1 Three in One ### Describe how you could use a single array to implement three stacks * Callout(Plan): Use an array and a set of three indexes into that array. Each of those indexes will be a top of one of the stacks. Each element of a given stack will be offset from the next element in the stack by 3, thus allowing us three co-existing stacks. - Note: Looking at the two solutions provided in the book, it seems that the author meant to imply that the array being used for the three stacks is of fixed size. I did not infer that, so I implemented something dynamic. The gist is the same, except that we would need to check for exceeding the predetermined bounds rather than resizing the array. */ struct TripleStack: CustomStringConvertible { // Could be made generic, but I'm using `Int`s for simplicity private var tops = [-3, -2, -1] private var s = Array<Int>() public enum Errors: Error { case Empty(stackNo: Int) } public func isEmpty(stackNo: Int) -> Bool { return tops[stackNo] < 0 } public mutating func push(item: Int, to stackNo: Int) { tops[stackNo] += 3 growArray() s[tops[stackNo]] = item } public func peek(stackNo: Int) throws -> Int { guard !isEmpty(stackNo: stackNo) else { throw Errors.Empty(stackNo: stackNo) } return s[tops[stackNo]] } public mutating func pop(stackNo: Int) throws -> Int { guard !isEmpty(stackNo: stackNo) else { throw Errors.Empty(stackNo: stackNo) } let item = s[tops[stackNo]] tops[stackNo] -= 3 return item } public var description: String { var output = String() for stackNo in 1...3 { let stackIndex = stackNo - 1 output += "Stack \(stackNo): " var index = tops[stackIndex] while index >= 0 { output += String(format: "%d, ", s[index]) index -= 3 } output += "\n" } return output } private mutating func growArray() { let maxTopIndex = max(tops[0], tops[1], tops[2]) + 1 // Return if we have enough capacity guard s.capacity <= maxTopIndex else { return } // Otherwise, grow the array let newSize = maxTopIndex * 2 let padding = Array(repeating: Int.min, count: newSize) s.append(contentsOf: padding) } } // Populate the three stacks var triStack = TripleStack() for i in 1..<5 { triStack.push(item: i, to: 0) triStack.push(item: i + 10, to: 1) triStack.push(item: i * 10 + i, to: 2) } triStack.push(item: 999, to: 1) print(triStack.description) try triStack.peek(stackNo: 1) try triStack.pop(stackNo: 1) do { try triStack.pop(stackNo: 0) try triStack.pop(stackNo: 0) try triStack.pop(stackNo: 0) try triStack.pop(stackNo: 0) try triStack.pop(stackNo: 0) } catch TripleStack.Errors.Empty(let stackNo) { print("Attempt to pop empty stack \(stackNo)") } /*: --- ## 3.2 Stack Min ### How would you design a stack that, in addition to `push` and `pop`, has a function, `min`, that returns the minimum element? `Push`, `pop`, and `min` should all operate in `O(1)` time. * Callout(Plan): A. Include minimum value in stack as part of the element data structure B. Keep a separate stack for minimums (A) is good if the stack is not huge. If it *is* huge, we burn an extra `sizeof(item)` for each stack element, when the minimum value may change infrequently (B) is good if the stack is huge, because we only grow the 'min stack' when we push a new minimum Let's do (B) - Callout(Implementation Details): - `peek()` should return top value per usual - `push()` should push onto minimum stack if new value is <= top of minimum stack. (Pushing equal so we can pop equal values and still maintain the prior minimum.) - `pop()` should pop the minimum stack if existing top.value == minimum */ struct StackWithMin<T: Comparable>: CustomStringConvertible { private var stack = Stack<T>() private var minStack = Stack<T>() public mutating func peek() throws -> T { return try stack.peek() } public func isEmpty() -> Bool { return stack.isEmpty() } public mutating func push(_ item: T) { if stack.isEmpty() { stack.push(item) minStack.push(item) } else { let min = try! minStack.peek() if item <= min { minStack.push(item) } stack.push(item) } } public mutating func pop() throws -> T { do { let item = try stack.pop() let min = try minStack.peek() if item <= min { _ = try! minStack.pop() } return item } catch { throw error } } public func min() throws -> T { return try minStack.peek() } public var description: String { var output = " Stack: " + stack.description + "\n" output += "Minimum Stack: " + minStack.description + "\n" return output } } var stackWithMin = StackWithMin<Int>() let rangeTop = 5 for i in 1..<rangeTop { stackWithMin.push(rangeTop - i + 10) stackWithMin.push(rangeTop - i) stackWithMin.push((rangeTop - i) * 10 + i) } stackWithMin.push(999) print("\n3.2 Stack with min(): Test 1:") print(stackWithMin.description) print("\n3.2 Stack with min(): Test 2:") print("stackWithMin.min() == 1: \(try! stackWithMin.min() == 1)") print("\n3.3 Stack with min(): Test 3:") try print("stackWithMin.pop() == 999: \(stackWithMin.pop() == 999)") print("\n3.3 Stack with min(): Test 4:") for _ in 0..<3 { try! stackWithMin.pop() } try print("stackWithMin.min() == 2: \(stackWithMin.min() == 2)") print("\n3.3 Stack with min(): Current Stack State:") print(stackWithMin.description) /*: --- ## 3.3 Stack of Plates ### Imagine a literal stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure, `SetofStacks` that mimics this. `SetOfStacks` should be composed of several stacks and should create a new stack once the previous one exceeds capacity. `SetOfStacks.push()` and `SetOfStacks.pop()` should behave identically to a single stack. (That is, `pop()` should return the same values as if there were just a single stack.) * Callout(Follow Up): Implement a function `popAt(int index)` that performs a pop operation on a specific substack. - Callout(Plan): - Data structure needs one or more stacks => array, list, or stack of substacks. - The stack of substacks is out, because `popAt` will be unreasonably difficult to implement with a stack of substacks. - A linked list allows us to harvest empty stack nodes versus keeping around unused array elements. Each empty stack in an array, though, will consume almost no memory. Thus, we are going with an array. - Initializer needs a threshold parameter - Data structure must contain a count of elements in each stack => a substack structure * Callout(Implementation Details): - `Substack`: element count, stack - `SetOfStacks`: array of substacks, threshold, current stack num - `pop()` : when last element of current substack is popped, decrement current stack num. Don't go below 0 - `push()` : if current substack's element count equals threshold, append empty stack to array - `popAt()`: simply index the stack array */ struct SetOfStacks<T> { class Substack<T> { var count = 0 var stack = Stack<T>() func description(indentation: Int = 0) -> String { let indent = String(repeating: " ", count: indentation) var output = indent + "[\n" output += indent + " count: \(count)\n" output += indent + " stack: \(stack.description)\n" output += indent + "]\n" return output } } var allStacks = [Substack<T>()] let threshold: Int var currentStack = 0 public init(threshold: Int) { self.threshold = threshold } public func isEmpty() -> Bool { return allStacks[0].stack.isEmpty() } public func peek() throws -> T { guard !allStacks[0].stack.isEmpty() else { throw Stack<T>.Errors.Empty } return try! allStacks[currentStack].stack.peek() } public mutating func push(_ item: T) { if allStacks[currentStack].count == threshold { addStack() } let substack = allStacks[currentStack] substack.stack.push(item) substack.count += 1 } public mutating func pop() throws -> T { guard !allStacks[0].stack.isEmpty() else { throw Stack<T>.Errors.Empty } let substack = allStacks[currentStack] let item = try! substack.stack.pop() substack.count -= 1 if substack.count == 0 && currentStack != 0 { currentStack -= 1 } return item } public mutating func popAt(substack: Int) throws -> T { guard substack <= currentStack, !allStacks[substack].stack.isEmpty() else { throw Stack<T>.Errors.Empty } let substack = allStacks[substack] let item = try! substack.stack.pop() substack.count -= 1 return item } private mutating func addStack() { currentStack += 1 if allStacks.count <= currentStack { allStacks.append(Substack<T>()) } } public var description: String { var output = "[\n" output += " threshold:\(threshold)\n" output += " currentStack:\(currentStack)\n" output += " allStacks:\n" for i in 0...currentStack { output += allStacks[i].description(indentation: 1) } output += "]\n" return output } } print("---------- 3.3 Stack of Plates ----------") var plates = SetOfStacks<Int>(threshold: 5) for i in 0..<5 { plates.push(i) plates.push(i + 10) plates.push(i * 10 + i) } plates.push(999) print("plates:") print(plates.description) print("plates.peek() = \(try! plates.peek())") print("plates.isEmpty() = \(plates.isEmpty())") print("plates.pop() = \(try! plates.pop())") print("plates.popAt(substack: 1) = \(try! plates.popAt(substack: 1))") print("plates.pop() = \(try! plates.pop())") print("plates:") print(plates.description) print("popping plates until empty") var output = "[" repeat { output += "\(try! plates.pop()) " } while !plates.isEmpty() output += "]" print(output) print("plates:") print(plates.description) print("plates.isEmpty() = \(plates.isEmpty())") do { print("plates.pop() (should fail) = \(try plates.pop())") } catch { print("plates.pop() failed. error: \(error)") } /*: --- ## 3.4 Queue via Stacks ### Implement `MyQueue`, which implements a queue using two stacks. * Callout(Plan): The FIFO nature of a queue can be implemented by having "tail" and "head" stacks. When `enqueu`ing, we push the new element onto the "tail" stack. This means the first-in element will always be at the bottom of that stack. When `dequeu`ing, we `pop()` the top element of the "head" stack. If that stack is empty, we "move" the "tail" stack to the "head" stack. "Move" in this context means `pop`ping each element from the "tail" stack and `push`ing it onto the "head" stack. This will leave the "head" stack with the elements `pop`able in FIFO order. */ struct MyQueue<T> { var headStack = Stack<T>() // dequeue ops var tailStack = Stack<T>() // enqueue ops public enum Errors: Error { case Empty // dequeue() called on empty queue } public mutating func enqueue(_ item: T) { tailStack.push(item) } public mutating func dequeue() throws -> T { if headStack.isEmpty() { guard !tailStack.isEmpty() else { throw Errors.Empty } moveTailToHead() } return try! headStack.pop() } public func isEmpty() -> Bool { return headStack.isEmpty() && tailStack.isEmpty() } fileprivate mutating func moveTailToHead() { repeat { headStack.push(try! tailStack.pop()) } while !tailStack.isEmpty() } } print("\n\n---------- 3.4 Queue via Stacks ----------\n") var myQ = MyQueue<Int>() for i in (0..<3).reversed() { myQ.enqueue(i) } print("o queue with three elements: " + String(describing: myQ)) print("o myQ.dequeue() == 2: \(try! myQ.dequeue() == 2)") print("o queue with head element removed: " + String(describing: myQ)) for i in (0..<5).reversed() { myQ.enqueue(i * 10 + i / 2) } print("o queue with five new elements (notice 'tailStack'): " + String(describing: myQ)) _ = try! myQ.dequeue() _ = try! myQ.dequeue() print("o queue with first two elements dequeued: " + String(describing: myQ)) print("o myQ.dequeue() == 42: \(try! myQ.dequeue() == 42)") print("o queue with next element dequeued: " + String(describing: myQ)) /*: --- ## 3.5 Sort Stack ### Write a program to sort a stack such that the smallest items are on top. You can use a temporary stack, but no other data structure (i.e., an array). The stack should support `push`, `pop`, `peek`, and `isEmpty`. * Callout(Plan): When pushing a new value, we need to ensure the new value is placed beneath any lesser values and above any greater values. => popping elements and pushing them onto a temporary stack until we reach a value greater than or equal to our new item. In addition, to make things more efficient, we only need to "consolidate" the two stacks when we want to `pop` or `peek`. - Callout(Implementation Details for `push`): 1. While the sorted stack is not empty, compare new item to `top` of sorted stack 2. if `item` > than `top`, pop sorted and push to minimums stack, and then continue the loop 3. if `item` == `top`, push it onto the sorted stack 4. if `item` < `top`, while minimums stack is not empty, compare to `top` of minimums stack 1. if `item` >= `top`, push onto sorted stack and exit 2. if `item` < `top`, pop minimums stack and push that onto the sorted stack, and then return to (4) 3. if minimums stack empty, push `item` onto sorted and exit 5. if sorted stack is empty, push `item` onto sorted stack */ struct SortedStack<T: Comparable> { var sortedStack = Stack<T>() var minsStack = Stack<T>() public enum Errors: Error { case Empty // Attempted to peek or pop an empty stack } public func isEmpty() -> Bool { return sortedStack.isEmpty() && minsStack.isEmpty() } fileprivate mutating func consolidateStacks() { while !minsStack.isEmpty() { sortedStack.push(try! minsStack.pop()) } } public mutating func peek() throws -> T { consolidateStacks() guard !sortedStack.isEmpty() else { throw Errors.Empty } return try! sortedStack.peek() } public mutating func pop() throws -> T { consolidateStacks() guard !sortedStack.isEmpty() else { throw Errors.Empty } return try! sortedStack.pop() } public mutating func push(_ item: T) { while !sortedStack.isEmpty() { let sortedTop = try! sortedStack.peek() switch item { case _ where item > sortedTop: minsStack.push(try! sortedStack.pop()) case _ where item == sortedTop: sortedStack.push(item) return case _ where item < sortedTop: // check minsStack while !minsStack.isEmpty() { let minsTop = try! minsStack.peek() switch item { case _ where item >= minsTop: sortedStack.push(item) return case _ where item < minsTop: sortedStack.push(try! minsStack.pop()) default: break // we can never get here } } sortedStack.push(item) return default: break // we can never get here } } sortedStack.push(item) } } print("\n\n---------- 3.5 Sorted Stack ----------\n") var ss = SortedStack<Character>() print("Testing SortedStack using the characters in the string, \"STACK\"") print("SortedStack: \(String(describing: ss))") for char in "STACK" { ss.push(char) print("pushed \(char). SortedStack: \(String(describing: ss))") } print("Peeking at sorted stack: \(try! ss.peek())") print("SortedStack: \(String(describing: ss))") ss = SortedStack<Character>() print("\nTesting SortedStack using the characters in the string, \"ABDCE\"") print("SortedStack: \(String(describing: ss))") for char in "ABDCE" { ss.push(char) print("pushed \(char). SortedStack: \(String(describing: ss))") } print("Peeking at sorted stack: \(try! ss.peek())") print("SortedStack: \(String(describing: ss))") /*: --- ## 3.5 (redux) ### I misread the problem. The challenge was to sort an (unsorted) stack using at most one other stack. I've already looked at the answer, so I don't know what I would have come up with. Here's what the book provides. * Callout(Plan): We will build a stack sorted from highest to lowest, and then reverse it by putting it back into the original stack 1. Pop the top of the unsorted stack, `s1`, and store that value in a temporary variable 2. Find the correct place in the sorted stack, `s2`, to store this value. The correct place is above the first element less than it. 3. Finding the correct place, requires us to pop `s2` until it's either empty, or we find a value less than the element we are pushing. We push all these popped values onto `s1` temporarily. 4. Push our temp value onto `s2` 5. Repeat until `s1` is empty 6. Reverse `s2` by popping each element and pushing it into `s1` - Callout(Complexity): `O(N^2)` time and `O(N)` space */ func sort<T:Comparable>(_ s1: inout Stack<T>) { var s2 = Stack<T>() while !s1.isEmpty() { // Insert each element in s1 in sorted order into s2. let tmp = try! s1.pop() while !s2.isEmpty() && (try! s2.peek() > tmp) { s1.push(try! s2.pop()) } s2.push(tmp) } // Copy the elements from s2 back to s1 while !s2.isEmpty() { s1.push(try! s2.pop()) } } print("\n\n---------- 3.5 (redux) Sort a Stack ----------\n") var stackToSort = Stack<Character>() print("testing sort(:) with the characters in the string, \"STACK\"") for char in "STACK" { stackToSort.push(char) } print("unsorted stackToSort: \(String(describing: stackToSort))") sort(&stackToSort) print(" sorted stackToSort: \(String(describing: stackToSort))") print("") stackToSort = Stack<Character>() print("testing sort(:) with the characters in the string, \"ABDCE\"") for char in "ABDCE" { stackToSort.push(char) } print("unsorted stackToSort: \(String(describing: stackToSort))") sort(&stackToSort) print(" sorted stackToSort: \(String(describing: stackToSort))") /*: --- ## 3.6 Animal Shelter ### A shelter operates on a FIFO basis, taking in dogs and cats. A human can request the oldest pet, oldest dog, or oldest cat. Implement `dequeueCat`, `dequeueDog`, `dequeueAny`, and `enqueue`. You can use the built-in `LinkedList`. (But, this not being Java, we don't have such a thing.) * Callout(Initial Thoughts): - two linked lists, one for dogs, one for cats - enclosing data structure keeps a counter of animals taken in - each animal has a "priority" that is the counter when it was brought in - keep head and tail pointers for enqueue and dequeue - `dequeueCat` removes and returns head of that queue, dog the same - `dequeueAny` removes and returns the one with the smallest priority value */ struct Animal: CustomStringConvertible { enum Species { case Cat case Dog } let name: String let species: Species var description: String { return "\(name):\(species)" } init(species: Species) { switch species { case .Cat: name = "Felix-\(Int(arc4random()))" case .Dog: name = "Phydeaux-\(Int(arc4random()))" } self.species = species } } struct AnimalShelter: CustomStringConvertible { class ListNode: CustomStringConvertible { let animal: Animal let priority: Int var next: ListNode? init(animal: Animal, priority: Int) { self.animal = animal self.priority = priority } var description: String { let thisAnimal = "\(animal)(\(priority))" guard next != nil else { return thisAnimal } return "\(thisAnimal) " + next!.description } } public enum Errors: Error { case NoAnimals } var intakeCount = 0 var dogs: ListNode? var cats: ListNode? var dogsTail: ListNode? var catsTail: ListNode? public mutating func enqueue(_ stray: Animal) { let newNode = ListNode(animal: stray, priority: intakeCount) intakeCount += 1 switch stray.species { case .Cat: guard catsTail != nil else { catsTail = newNode cats = catsTail return } catsTail!.next = newNode catsTail = newNode case .Dog: guard dogsTail != nil else { dogsTail = newNode dogs = dogsTail return } dogsTail!.next = newNode dogsTail = newNode } } public mutating func dequeueAny() throws -> Animal { guard cats != nil, dogs != nil else { throw Errors.NoAnimals } if cats == nil { return try! dequeueDog() } else if dogs == nil { return try! dequeueCat() } if cats!.priority < dogs!.priority { return try! dequeueCat() } else { return try! dequeueDog() } } public mutating func dequeueCat() throws -> Animal { guard let catNode = cats else { throw Errors.NoAnimals } cats = catNode.next return catNode.animal } public mutating func dequeueDog() throws -> Animal { guard let dogNode = dogs else { throw Errors.NoAnimals } dogs = dogNode.next return dogNode.animal } var description: String { let dogsDesc = "Dogs: [ \(String(describing: dogs)) ]" let catsDesc = "Cats: [ \(String(describing: cats)) ]" return "\(dogsDesc), \(catsDesc)" } } print("\n\n---------- 3.6 Animal Shelter ----------\n") var shelter = AnimalShelter() for _ in 0..<5 { switch Int(arc4random_uniform(2)) { case 0: shelter.enqueue(Animal(species: .Dog)) shelter.enqueue(Animal(species: .Cat)) case 1: shelter.enqueue(Animal(species: .Cat)) shelter.enqueue(Animal(species: .Dog)) default: break // will never get here } } print("Shelter Population: \(String(describing: shelter))") print("dequeueAny(): \(try! shelter.dequeueAny())") print("dequeueCat(): \(try! shelter.dequeueCat())") print("dequeueDog(): \(try! shelter.dequeueDog())") //: --- //: [Previous](@previous) [Next](@next)
unlicense
af87d8dee8850a73a546fac6bd1ee3f0
31.914601
568
0.60847
4.111493
false
false
false
false
modesty/wearableD
WearableD/SimpleOAuth2/OAuth2FlowViewController.swift
2
5659
// // OAuth2FlowViewController.swift // WearableD // // Created by Zhang, Modesty on 1/28/15. // Based on https://github.com/crousselle/SwiftOAuth2/blob/master/Classes/CRAuthenticationViewController.swift // Copyright (c) 2015 Intuit. All rights reserved. // import Foundation import UIKit class OAuth2FlowViewController: UIViewController, UIWebViewDelegate { var webView: UIWebView? var spinnerView: UIActivityIndicatorView? var successCallback : ((code:String)-> Void)? var failureCallback : ((error:NSError) -> Void)? var isRetrievingAuthCode : Bool? = false required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(successCallback:((code:String)-> Void), failureCallback:((error:NSError) -> Void)) { self.successCallback = successCallback self.failureCallback = failureCallback super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() self.title = "Login" self.webView = UIWebView(frame: self.view.bounds); self.spinnerView = UIActivityIndicatorView(frame: self.view.bounds) if let bindCheck = self.webView { self.webView!.backgroundColor = UIColor.clearColor() self.webView!.scalesPageToFit = true self.webView!.delegate = self self.view.addSubview(self.webView!) self.spinnerView!.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge self.spinnerView!.hidesWhenStopped = true self.spinnerView!.color = UIColor.darkTextColor() self.spinnerView!.center = self.view.center; self.spinnerView!.startAnimating() self.view.addSubview(self.spinnerView!) } self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancelAction")) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let urlRequest : NSURLRequest = NSURLRequest(URL: NSURL(string: OAuth2Utils.authUri())!) self.webView!.loadRequest(urlRequest) } func cancelAction() { // self.dismissViewControllerAnimated(true, completion: { self.failureCallback!(error: NSError(domain: "Authentication cancelled", code: 409, userInfo: nil)) // }) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url : NSString = request.URL!.absoluteString! self.isRetrievingAuthCode = url.hasPrefix(OAuth2Credentials.redirectURL) if (self.isRetrievingAuthCode!) { if (url.rangeOfString("error").location != NSNotFound) { let error:NSError = NSError(domain:"SimpleOAuth2", code:0, userInfo: nil) self.failureCallback!(error:error) } else { let optionnalState:String? = self.extractParameterFromUrl("state", url: url) if let state = optionnalState { if (state == OAuth2Credentials.state) { let optionnalCode:String? = self.extractParameterFromUrl("code", url: url) if let code = optionnalCode { self.successCallback!(code:code) } else { self.failureCallback!(error: NSError(domain: "Authentication failed: missing authorization code", code: 409, userInfo: nil)) } } else { self.failureCallback!(error: NSError(domain: "Authentication failed: not recognized state", code: 409, userInfo: nil)) } } else { self.failureCallback!(error: NSError(domain: "Authentication failed: missing state", code: 409, userInfo: nil)) } return false } } return true } func webViewDidFinishLoad(webView: UIWebView) { self.spinnerView!.stopAnimating() } func webView(webView: UIWebView!, didFaiLoadWithError error: NSError!) { if (!self.isRetrievingAuthCode!) { self.failureCallback!(error: error) } } func extractParameterFromUrl(parameterName:NSString, url:NSString) -> String? { if(url.rangeOfString("?").location == NSNotFound) { return nil } if let urlString: String = url.componentsSeparatedByString("?")[1] as? String { var dict = Dictionary <String, String>() for param in urlString.componentsSeparatedByString("&") { var array = Array <AnyObject>() array = param.componentsSeparatedByString("=") let name:String = array[0] as! String let value:String = array[1] as! String dict[name] = value } if let result = dict[parameterName as String] { return result } } return nil } }
apache-2.0
88c819d01d690b6494976e30c4fc760a
35.986928
163
0.584025
5.348771
false
false
false
false
bnickel/bite-swift
Bite/And.swift
1
1227
// // And.swift // Bite // // Created by Brian Nickel on 6/16/14. // Copyright (c) 2014 Brian Nickel. All rights reserved. // public struct AndGenerator<T:GeneratorType, U:GeneratorType where T.Element == U.Element> : GeneratorType { var firstIsFinished = false var firstSource:T var secondSource:U init(_ firstSource:T, _ secondSource:U) { self.firstSource = firstSource self.secondSource = secondSource } public mutating func next() -> T.Element? { if !firstIsFinished { if let element = firstSource.next() { return element } firstIsFinished = true } return secondSource.next() } } public struct AndSequence<T:SequenceType, U:SequenceType where T.Generator.Element == U.Generator.Element> : SequenceType { var firstSource:T var secondSource:U init(_ firstSource:T, _ secondSource:U) { self.firstSource = firstSource self.secondSource = secondSource } public func generate() -> AndGenerator<T.Generator, U.Generator> { return AndGenerator<T.Generator, U.Generator>(firstSource.generate(), secondSource.generate()) } }
mit
26ce34f58b87832b748c22bfc2f24153
26.886364
123
0.629992
4.429603
false
false
false
false
WIND-FIRE-WHEEL/WFWCUSTOMIM
IMDemo/IMDemo/IM/XWController/IMViewController.swift
1
12774
// // IMViewController.swift // IMDemo // // Created by 徐往 on 2017/7/25. // Copyright © 2017年 徐往. All rights reserved. // import Foundation enum EventType:NSInteger { case updateData case updateKeyboard case updateMessage } class IMController :XWBaseController , UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate { /* FIXME:Getter And Setter */ var keyboardHeight:CGFloat = 0.0 var alwaysChangeMessageHeight:CGFloat = 0.0 var animationDuration:Double = 0.0 var eventTp:EventType = EventType(rawValue: 0)!{ didSet { switch eventTp { case .updateData: if self.keyboardHeight == 0.0 { self.imTableView.contentOffset = CGPoint(x:0,y:0) self.inputV.frame = CGRect(x:0, y:IM.screenSize.height - self.inputV.xw_height, width:IM.screenSize.width, height:self.inputV.xw_height) self.imTableView.frame = CGRect(x:0, y:IM.screenNavHeight, width:IM.screenSize.width, height:IM.screenSize.height - IM.screenNavHeight - self.inputV.xw_height) } else { self.inputV.frame = CGRect(x:0, y:IM.screenSize.height - self.inputV.xw_height - self.keyboardHeight, width:IM.screenSize.width, height:self.inputV.xw_height) let inputLocaltion:(Bool, CGFloat) = self.isScroll(inputY: self.inputV.xw_y) if inputLocaltion.0 { // 如果超过 self.imTableView.contentOffset = CGPoint(x:0,y: -inputLocaltion.1) } } case .updateMessage: UIView.animate(withDuration: 0.1, animations: { self.inputV.frame = CGRect(x:0,y:IM.screenSize.height - self.keyboardHeight - 14 - self.alwaysChangeMessageHeight,width:IM.screenSize.width,height:self.alwaysChangeMessageHeight + 14) }, completion: { (isFinish) in let inputLocaltion:(Bool, CGFloat) = self.isScroll(inputY: self.inputV.frame.origin.y) UIView.animate(withDuration: 0.1, animations: { if inputLocaltion.0 { self.imTableView.contentOffset = CGPoint(x:0,y: -inputLocaltion.1) } }) }) print("") case .updateKeyboard: if self.keyboardHeight == 0.0 { self.imTableView.contentOffset = CGPoint(x:0,y:0) self.inputV.frame = CGRect(x:0, y:IM.screenSize.height - self.inputV.xw_height, width:IM.screenSize.width, height:self.inputV.xw_height) self.imTableView.frame = CGRect(x:0, y:IM.screenNavHeight, width:IM.screenSize.width, height:IM.screenSize.height - IM.screenNavHeight - self.inputV.xw_height) } else { UIView.animate(withDuration: self.animationDuration, animations: { self.inputV.frame = CGRect(x:0, y:IM.screenSize.height - self.inputV.xw_height - self.keyboardHeight, width:IM.screenSize.width, height:self.inputV.xw_height) let inputLocaltion:(Bool, CGFloat) = self.isScroll(inputY: self.inputV.xw_y) if inputLocaltion.0 { // 如果超过 self.imTableView.contentOffset = CGPoint(x:0,y: -inputLocaltion.1) } }) } print("") default: print("") } } } var inputV:IMInputView! lazy var imDataArray:NSMutableArray = { let arr = NSMutableArray() return arr }() static let IMCellID = "IMCell" lazy var imTableView: UITableView = { let frame = CGRect(x:0,y:IM.screenNavHeight,width:IM.screenSize.width,height:IM.screenSize.height - IM.defaultKeyboardHeight - IM.screenNavHeight) let tableView = UITableView.init(frame: frame, style: .grouped) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.showsHorizontalScrollIndicator = true tableView.backgroundColor = UIColor.init(red: 230, green: 230, blue: 230, alpha: 1.0) tableView.register(IMCell.classForCoder(), forCellReuseIdentifier: IMCellID) return tableView }() /* FIXME: tableViewDelegate */ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let model:IMModel = self.imDataArray[indexPath.row] as? IMModel { if let height = model.messageSize?.height, height > 40 { return height + 20 } else { return 60 } } return 60 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let imCell:IMCell = tableView.dequeueReusableCell(withIdentifier: IMController.IMCellID) as! IMCell imCell.configWithModel(model: self.imDataArray[indexPath.row] as! IMModel) return imCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.imDataArray.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.inputV.endEditing(true) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.inputV.messageInput.resignFirstResponder() } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.title = "聊天室" layoutTableView() observeKeyboard() layoutInputView() } func layoutTableView(){ self.view.addSubview(self.imTableView) DispatchQueue.global().async { self.configData() DispatchQueue.main.async { self.imTableView.reloadData() self.imTableView.scrollToRow(at: NSIndexPath.init(row: self.imDataArray.count - 1, section: 0) as IndexPath, at: .bottom, animated: true) self.eventTp = .updateData } } } func layoutInputView(){ self.inputV = IMInputView.init(frame: CGRect(x:0,y:IM.screenSize.height - IM.defaultKeyboardHeight, width:IM.screenSize.width,height:IM.defaultKeyboardHeight )) self.inputV.backgroundColor = UIColor.lightGray self.view.addSubview(self.inputV) // MARK: 根据输入的文字动态改变输入框的高度 self.inputV.xw_getMessageHeight = { messageHeight in unowned let weakSelf = self weakSelf.alwaysChangeMessageHeight = messageHeight weakSelf.eventTp = .updateMessage // let result:(Bool, CGFloat) = weakSelf.isScroll(inputY: weakSelf.inputV.frame.origin.y) // // UIView.animate(withDuration: 0.1, animations: { // if result.0 { // weakSelf.imTableView.frame = CGRect(x:0,y:IM.screenNavHeight - result.1 - weakSelf.keyboardHeight, width:IM.screenSize.width,height:IM.screenSize.height - weakSelf.inputV.xw_height - IM.screenNavHeight) // // } // // weakSelf.inputV.frame = CGRect(x:0,y:IM.screenSize.height - weakSelf.keyboardHeight - 14 - messageHeight,width:IM.screenSize.width,height:messageHeight + 14) // // }) } // MARK: 发送消息 self.inputV.xw_sendMessage = { message in let model = IMModel() model.messageContent = message as NSString model.headerIcon = "gerentouxiang.jpg" model.sendType = 1 self.imDataArray.add(model) self.imTableView.reloadData() self.imTableView.scrollToRow(at: NSIndexPath.init(row: self.imDataArray.count - 1, section: 0) as IndexPath, at: .bottom, animated: true) self.eventTp = .updateData // let chatMsgBuilder = ChatMsg.Builder() // chatMsgBuilder.setMid("1") // chatMsgBuilder.setMsg(message) // chatMsgBuilder.setTid("0") // let chatMsgdata = try! chatMsgBuilder.build().data() // XWIMGCDSocketManager.share().sendMsg(chatMsgdata) } } func configData() { let data = NSMutableDictionary(dictionary:["headerIcon":"gerentouxiang.jpg","messageContent":"asfdsdf"]) for item in 0...2 { let model = IMModel() model.headerIcon = data["headerIcon"] as? String model.messageContent = (data["messageContent"] as? NSString)! if item % 2 == 0 { model.sendType = 0 } self.imDataArray.add(model) } } /* FIXME: 键盘监听 */ func observeKeyboard(){ NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyBoardWillHide(_ notification: Notification){ let duration:Double = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double self.animationDuration = duration // UIView.animate(withDuration: duration) { // self.imTableView.frame = CGRect(x:0, y:IM.screenNavHeight , width:IM.screenSize.width,height:IM.screenSize.height - IM.screenNavHeight - self.inputV.xw_height) // self.inputV.frame = CGRect(x:0,y:IM.screenSize.height - self.inputV.xw_height,width:IM.screenSize.width,height:self.inputV.xw_height) // } self.keyboardHeight = 0.0 self.eventTp = .updateKeyboard } func keyBoardWillShow(_ notification: Notification){ let rectValue:CGRect = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect let duration:Double = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double let offset = rectValue.size.height self.keyboardHeight = offset self.animationDuration = duration if offset > 0 { // self.imTableView.scrollToRow(at: NSIndexPath.init(row: self.imDataArray.count - 1, section: 0) as IndexPath, at: .bottom, animated: true) self.eventTp = .updateKeyboard // // let result:(Bool, CGFloat) = self.isScroll(inputY: IM.screenSize.height - offset - self.inputV.xw_height) // // UIView.animate(withDuration: duration, animations: { // if result.0 { // self.imTableView.frame = CGRect(x:0, y:IM.screenNavHeight - result.1, width:IM.screenSize.width,height:IM.screenSize.height - IM.screenNavHeight - self.inputV.xw_height) // // } // self.inputV.frame = CGRect(x:0,y:IM.screenSize.height - offset - self.inputV.xw_height,width:IM.screenSize.width,height:self.inputV.xw_height) // // // }) } } /* FIXME: ScrollviewDelegate */ func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { self.isEditing = false } /* FIXME: 判断当前最后一条的cell的高度是否在键盘的下面 */ func isScroll(inputY: CGFloat) -> (Bool, CGFloat) { let cell:IMCell = self.imTableView.cellForRow(at: NSIndexPath.init(row: self.imDataArray.count - 1, section: 0) as IndexPath) as! IMCell let cellInSuperFrame = cell.convert(cell.bounds, to: self.view) as CGRect if cellInSuperFrame.origin.y + cellInSuperFrame.size.height > inputY{ let moreHeight = cellInSuperFrame.origin.y + cellInSuperFrame.size.height - inputY return (true, moreHeight) } return (false, 0) } }
mit
3f237bef62e71ea3913ee73cd1003269
38.908517
224
0.589993
4.694249
false
false
false
false
artsy/eigen
ios/Artsy/View_Controllers/Core/UIViewController+BlurredStatusView.swift
1
4310
import UIKit import ObjectiveC private var statusViewAssociatedKey: Int = 0 enum BlurredStatusOverlayViewCloseButtonState { case hide case show(target: NSObject, selector: Selector) } // As of iOS7+, it is the responsibility of the view controller to maintain its preferred status bar style. // This style may change while the blurred overlay is present, but it's up to the view controller to do that. extension UIViewController { var blurredStatusOverlayView: UIView? { set { objc_setAssociatedObject(self, &statusViewAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, &statusViewAssociatedKey) as? UIView } } func ar_presentBlurredOverlayWithTitle(_ title: String, subtitle: String, buttonState: BlurredStatusOverlayViewCloseButtonState = .hide) { if blurredStatusOverlayView != nil { return } // This is processing heavy, move the blurring / setup to a background queue ar_dispatch_async { UIGraphicsBeginImageContext(self.view.bounds.size) self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false) let viewImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let blurredImage: UIImage? = viewImage?.blurredImage(withRadius: 12, iterations: 2, tintColor: UIColor.black) ar_dispatch_main_queue { // Create an imageview of the blurred view, for the view's background let imageView = UIImageView(frame: self.view.bounds) self.blurredStatusOverlayView = imageView imageView.image = blurredImage self.view.addSubview(imageView) if let view = self.view { imageView.align(toView: view) } // We want it tinted black, but applying a black tint doesn't really // do too much in the blur image, so apply a transparent black overlay let darkOverlay = UIView(frame: imageView.bounds) darkOverlay.backgroundColor = UIColor(white: 0, alpha: 0.75) imageView.addSubview(darkOverlay) darkOverlay.align(toView: imageView) // Optional X button in the top trailing edge if case .show(let target, let selector) = buttonState { let dimension = 40 let closeButton = ARMenuButton() closeButton.setBorderColor(.white, for: UIControl.State(), animated: false) closeButton.setBackgroundColor(.clear, for: UIControl.State(), animated: false) let cross = UIImage(named:"serif_modal_close")?.withRenderingMode(.alwaysTemplate) closeButton.setImage(cross, for: UIControl.State()) closeButton.alpha = 0.5 closeButton.tintColor = .white closeButton.addTarget(target, action: selector, for: .touchUpInside) imageView.addSubview(closeButton) closeButton.alignTrailingEdge(withView: imageView, predicate: "-20") closeButton.alignTopEdge(withView: imageView, predicate: "20") closeButton.constrainWidth("\(dimension)", height: "\(dimension)") } let textStack = ORStackView() textStack.addSerifPageTitle(title, subtitle: subtitle) textStack.subviews .compactMap { $0 as? UILabel } .forEach { label in label.textColor = .white label.backgroundColor = .clear } // Vertically center the text stack imageView.addSubview(textStack) textStack.constrainWidth(toView: imageView, predicate: "-40") textStack.alignCenter(withView: imageView) } } } func ar_removeBlurredOverlayWithTitle() { guard let blurredStatusOverlayView = blurredStatusOverlayView else { return } blurredStatusOverlayView.removeFromSuperview() self.blurredStatusOverlayView = nil } }
mit
3ede0e77f69846d595359155aa2f40e3
42.979592
142
0.614153
5.641361
false
false
false
false
jejefcgb/ProjetS9-iOS
Projet S9/Conference.swift
1
1432
// // Conference.swift // Projet S9 // // Created by Jérémie Foucault on 30/11/2014. // Copyright (c) 2014 Jérémie Foucault. All rights reserved. // import Foundation private let _ConferenceSharedInstance = Conference() /** Data entity that represents a conference. Subclasses NSObject to enable Obj-C instantiation. */ class Conference : NSObject, Equatable { var id: Int?, address: String?, title: String?, start_day: String?, end_day: String?, major: Int?, created_at: Int?, updated_at: Int?, tracks: [Track]? class var sharedInstance: Conference { return _ConferenceSharedInstance } // Used by Foundation collections, such as NSSet. override func isEqual(object: AnyObject!) -> Bool { return self == object as Conference } func setData(id:Int, address:String, title:String, start_day:String, end_day:String, major:Int, created_at:Int, updated_at:Int, tracks:[Track]) { self.id = id self.address = address self.title = title self.start_day = start_day self.end_day = end_day self.major = major self.created_at = created_at self.updated_at = updated_at self.tracks = tracks } } // Required for Equatable protocol conformance func == (lhs: Conference, rhs: Conference) -> Bool { return lhs.id == rhs.id }
apache-2.0
085a61d508b3b7561050216d53b1e7bc
23.637931
149
0.621849
3.966667
false
false
false
false
YMXian/Deliria
Deliria/Deliria/JSON/Transforms/DateFormatterTransform.swift
1
1831
// // DateFormatterTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-03-09. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // 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 open class DateFormatterTransform: TransformType { public typealias Object = Date public typealias JSON = String let dateFormatter: DateFormatter public init(dateFormatter: DateFormatter) { self.dateFormatter = dateFormatter } public func transformFromJSON(_ value: Any?) -> Date? { if let dateString = value as? String { return dateFormatter.date(from: dateString) } return nil } public func transformToJSON(_ value: Date?) -> String? { if let date = value { return dateFormatter.string(from: date) } return nil } }
mit
669c8e6cb5668f1246c3251535e5225f
32.907407
81
0.739487
4.170843
false
false
false
false
a20251313/googleads-mobile-ios-examples
Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift
2
3901
// Copyright (c) 2015 Google. All rights reserved. import UIKit import GoogleMobileAds class ViewController: UIViewController, GADInterstitialDelegate, UIAlertViewDelegate { enum GameState: NSInteger{ case NotStarted case Playing case Paused case Ended } /// The interstitial ad. var interstitial: GADInterstitial? /// The countdown timer. var timer: NSTimer? /// The game counter. var counter = 3 /// The state of the game. var gameState = GameState.NotStarted /// The date that the timer was paused. var pauseDate: NSDate? /// The last fire date before a pause. var previousFireDate: NSDate? @IBOutlet var gameText: UILabel! @IBOutlet var playAgainButton: UIButton! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. startNewGame() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) pauseGame() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) resumeGame() } // MARK: Game logic private func startNewGame() { gameState = .Playing counter = 3 playAgainButton.hidden = true loadInterstitial() gameText.text = String(counter) timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector:"decrementCounter:", userInfo: nil, repeats: true) } private func pauseGame() { if (gameState != .Playing) { return } gameState = .Paused // Record the relevant pause times. pauseDate = NSDate() previousFireDate = timer!.fireDate // Prevent the timer from firing while app is in background. timer!.fireDate = NSDate.distantFuture() as! NSDate } private func resumeGame() { if (gameState != .Paused) { return } gameState = .Playing // Calculate amount of time the app was paused. var pauseTime = pauseDate!.timeIntervalSinceNow * -1 // Set the timer to start firing again. timer!.fireDate = previousFireDate!.dateByAddingTimeInterval(pauseTime) } func decrementCounter(timer: NSTimer) { counter-- if (counter > 0) { gameText.text = String(counter) } else { endGame() } } private func endGame() { gameState = .Ended gameText.text = "Game over!" playAgainButton.hidden = false timer!.invalidate() timer = nil } // MARK: Interstitial button actions @IBAction func playAgain(sender: AnyObject) { if (interstitial!.isReady) { interstitial!.presentFromRootViewController(self) } else { UIAlertView(title: "Interstitial not ready", message: "The interstitial didn't finish loading or failed to load", delegate: self, cancelButtonTitle: "Drat").show() } } private func loadInterstitial() { interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910") interstitial!.delegate = self // Request test ads on devices you specify. Your test device ID is printed to the console when // an ad request is made. GADInterstitial automatically returns test ads when running on a // simulator. interstitial!.loadRequest(GADRequest()) } // MARK: UIAlertViewDelegate implementation func alertView(alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { startNewGame() } // MARK: GADInterstitialDelegate implementation func interstitialDidFailToReceiveAdWithError ( interstitial: GADInterstitial, error: GADRequestError) { println("interstitialDidFailToReceiveAdWithError: %@" + error.localizedDescription) } func interstitialDidDismissScreen (interstitial: GADInterstitial) { println("interstitialDidDismissScreen") startNewGame() } }
apache-2.0
cf3bf772bf04327d60fa1c793d1a28b1
23.853503
98
0.691361
4.894605
false
false
false
false
linchaosheng/CSSwiftWB
SwiftCSWB/SwiftCSWB/Class/Home/V/WBHomePicCollection.swift
1
2242
// // WBHomePicCollection.swift // SwiftCSWB // // Created by LCS on 16/7/4. // Copyright © 2016年 Apple. All rights reserved. // import UIKit class WBHomePicCollection: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate { let reuseID = "picCell" var status : WBStatus? { didSet{ reloadData() } } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) dataSource = self delegate = self backgroundColor = UIColor.whiteColor() scrollEnabled = false registerNib(UINib(nibName: "WBHomePicCell", bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: reuseID) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class func picCollectionView(collectionViewLayout: UICollectionViewLayout) -> WBHomePicCollection{ let collectionView : WBHomePicCollection = WBHomePicCollection(frame: CGRectZero, collectionViewLayout: collectionViewLayout) return collectionView } } extension WBHomePicCollection { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return status?.pic_urls?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell : WBHomePicCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseID, forIndexPath: indexPath) as! WBHomePicCell let picStr = status?.pic_urls![indexPath.item]["thumbnail_pic"] as? String cell.picUrl = picStr return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let bmiddle_pic = status?.bmiddle_pic // 发送通知给HomeViewController NSNotificationCenter.defaultCenter().postNotificationName(CSShowPhotoBrowserController, object: self, userInfo: ["bmiddle_pic" : bmiddle_pic!, "index" : indexPath.item]) } }
apache-2.0
d61f2502bcb903e8f11b2eb0c34df378
32.283582
177
0.68865
5.65736
false
false
false
false
cannawen/dota-helper
dota-helper/MapViewController.swift
1
2716
// // MapViewController.swift // dota-helper // // Created by Canna Wen on 2016-11-26. // Copyright © 2016 Canna Wen. All rights reserved. // import UIKit class MapViewController: UIViewController { @IBOutlet weak var mapImageView: UIImageView! @IBOutlet var singleTapGestureRecognizer: UITapGestureRecognizer! @IBOutlet var doubleTapGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var togglePauseButton: UIButton! @IBOutlet weak var resetButton: UIButton! let gameState = GameState() override func viewDidLoad() { super.viewDidLoad() singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer) gameState.resetGame(renderer: self) } @IBAction func mapTapped(_ sender: UITapGestureRecognizer) { gameState.addWard(type: .observer, location: sender.location(in: mapImageView)) } @IBAction func mapDoubleTapped(_ sender: UITapGestureRecognizer) { gameState.addWard(type: .sentry, location: sender.location(in: mapImageView)) } @IBAction func pauseToggleTapped() { gameState.togglePauseState() } @IBAction func resetButtonTapped() { gameState.resetGame(renderer: self) } } extension MapViewController: GameRenderer { func render(gameState: GameState) { mapImageView.render(gameState: gameState) togglePauseButton.renderPauseButton(gameState: gameState) resetButton.renderResetButton() } } private extension UIImageView { func render(gameState: GameState) { subviews.forEach { $0.removeFromSuperview() } let wardViews = gameState.wards.map { WardView.new(ward: $0, currentTime: gameState.currentTime) } wardViews.forEach { addSubview($0) } } } private extension UIButton { func renderPauseButton(gameState: GameState) { titleLabel?.numberOfLines = 0 setTitle(gameState.pauseButtonTitle(), for: .normal) backgroundColor = gameState.pauseButtonColor() } func renderResetButton() { titleLabel?.numberOfLines = 0 setTitle("RESET".addEndlines(), for: .normal) } } private extension GameState { func pauseButtonTitle() -> String { if paused == true { return "RESUME".addEndlines() } else { return "PAUSE".addEndlines() } } func pauseButtonColor() -> UIColor { if paused == true { return .green } else { return .red } } } private extension String { func addEndlines() -> String { let stringArray = self.characters.map { String($0) } return stringArray.joined(separator: "\n") } }
apache-2.0
e534a4c8f6d316f3b91b269058c71292
27.578947
106
0.657459
4.79682
false
false
false
false
ZamzamInc/SwiftyPress
Sources/SwiftyPress/Repositories/Post/Models/ExtendedPost.swift
1
1014
// // ExtendedPost.swift // SwiftyPress // // Created by Basem Emara on 2019-05-11. // Copyright © 2019 Zamzam Inc. All rights reserved. // import ZamzamCore // Type used for decoding the server payload public struct ExtendedPost: Equatable { public let post: Post public let author: Author? public let media: Media? public let terms: [Term] } // MARK: - Conversions extension ExtendedPost: Codable { private enum CodingKeys: String, CodingKey { case post case author case media case terms } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.post = try container.decode(Post.self, forKey: .post) self.author = try container.decode(Author.self, forKey: .author) self.media = try container.decode(Media.self, forKey: .media) self.terms = try container.decode(FailableCodableArray<Term>.self, forKey: .terms).elements } }
mit
39d7222df228bcf9eae99652435dae2f
25.657895
99
0.662389
4.117886
false
false
false
false
salmojunior/TMDb
TMDb/Pods/SwiftMessages/SwiftMessages/MessageView.swift
2
14162
// // MessageView.swift // SwiftMessages // // Created by Timothy Moose on 7/30/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit /* */ open class MessageView: BaseView, Identifiable, AccessibleMessage { /* MARK: - Button tap handler */ /// An optional button tap handler. The `button` is automatically /// configured to call this tap handler on `.TouchUpInside`. open var buttonTapHandler: ((_ button: UIButton) -> Void)? func buttonTapped(_ button: UIButton) { buttonTapHandler?(button) } /* MARK: - Touch handling */ open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // Only accept touches within the background view. Anything outside of the // background view's bounds should be transparent and does not need to receive // touches. This helps with tap dismissal when using `DimMode.gray` and `DimMode.color`. return backgroundView == self ? super.point(inside: point, with: event) : backgroundView.point(inside: point, with: event) } /* MARK: - IB outlets */ /// An optional title label. @IBOutlet open var titleLabel: UILabel? /// An optional body text label. @IBOutlet open var bodyLabel: UILabel? /// An optional icon image view. @IBOutlet open var iconImageView: UIImageView? /// An optional icon label (e.g. for emoji character, icon font, etc.). @IBOutlet open var iconLabel: UILabel? /// An optional button. This buttons' `.TouchUpInside` event will automatically /// invoke the optional `buttonTapHandler`, but its fine to add other target /// action handlers can be added. @IBOutlet open var button: UIButton? { didSet { if let old = oldValue { old.removeTarget(self, action: #selector(MessageView.buttonTapped(_:)), for: .touchUpInside) } if let button = button { button.addTarget(self, action: #selector(MessageView.buttonTapped(_:)), for: .touchUpInside) } } } /* MARK: - Identifiable */ open var id: String { get { return customId ?? "MessageView:title=\(String(describing: titleLabel?.text)), body=\(String(describing: bodyLabel?.text))" } set { customId = newValue } } private var customId: String? /* MARK: - AccessibleMessage */ /** An optional prefix for the `accessibilityMessage` that can be used to futher clarify the message for VoiceOver. For example, the view's background color or icon might convey that a message is a warning, in which case one may specify the value "warning". */ private var accessibilityPrefix: String? open var accessibilityMessage: String? { let components = [accessibilityPrefix, titleLabel?.text, bodyLabel?.text].flatMap { $0 } guard components.count > 0 else { return nil } return components.joined(separator: ", ") } public var accessibilityElement: NSObject? { return backgroundView } open var additonalAccessibilityElements: [NSObject]? { var elements: [NSObject] = [] func getAccessibleSubviews(view: UIView) { for subview in view.subviews { if subview.isAccessibilityElement { elements.append(subview) } else { // Only doing this for non-accessible `subviews`, which avoids // including button labels, etc. getAccessibleSubviews(view: subview) } } } getAccessibleSubviews(view: self.backgroundView) return elements } } /* MARK: - Creating message views This extension provides several convenience functions for instantiating `MessageView` from the included nib files in a type-safe way. These nib files can be found in the Resources folder and can be drag-and-dropped into a project and modified. You may still use these APIs if you've copied the nib files because SwiftMessages looks for them in the main bundle first. See `SwiftMessages` for additional nib loading options. */ extension MessageView { /** Specifies one of the nib files included in the Resources folders. */ public enum Layout: String { /** The standard message view that stretches across the full width of the container view. */ case MessageView = "MessageView" /** A floating card-style view with rounded corners. */ case CardView = "CardView" /** Like `CardView` with one end attached to the super view. */ case TabView = "TabView" /** A 20pt tall view that can be used to overlay the status bar. Note that this layout will automatically grow taller if displayed directly under the status bar (see the `ContentInsetting` protocol). */ case StatusLine = "StatusLine" /** A standard message view like `MessageView`, but without stack views for iOS 8. */ case MessageViewIOS8 = "MessageViewIOS8" } /** Loads the nib file associated with the given `Layout` and returns the first view found in the nib file with the matching type `T: MessageView`. - Parameter layout: The `Layout` option to use. - Parameter filesOwner: An optional files owner. - Returns: An instance of generic view type `T: MessageView`. */ public static func viewFromNib<T: MessageView>(layout: Layout, filesOwner: AnyObject = NSNull.init()) -> T { return try! SwiftMessages.viewFromNib(named: layout.rawValue) } /** Loads the nib file associated with the given `Layout` from the given bundle and returns the first view found in the nib file with the matching type `T: MessageView`. - Parameter layout: The `Layout` option to use. - Parameter bundle: The name of the bundle containing the nib file. - Parameter filesOwner: An optional files owner. - Returns: An instance of generic view type `T: MessageView`. */ public static func viewFromNib<T: MessageView>(layout: Layout, bundle: Bundle, filesOwner: AnyObject = NSNull.init()) -> T { return try! SwiftMessages.viewFromNib(named: layout.rawValue, bundle: bundle, filesOwner: filesOwner) } } /* MARK: - Layout adjustments This extention provides a few convenience functions for adjusting the layout. */ extension MessageView { @available(iOS 9, *) /** Constrains the image view to a specified size. By default, the size of the image view is determined by its `intrinsicContentSize`. - Parameter size: The size to be translated into Auto Layout constraints. - Parameter contentMode: The optional content mode to apply. */ public func configureIcon(withSize size: CGSize, contentMode: UIViewContentMode? = nil) { var views: [UIView] = [] if let iconImageView = iconImageView { views.append(iconImageView) } if let iconLabel = iconLabel { views.append(iconLabel) } views.forEach { let constraints = [$0.heightAnchor.constraint(equalToConstant: size.height), $0.widthAnchor.constraint(equalToConstant: size.width)] $0.addConstraints(constraints) if let contentMode = contentMode { $0.contentMode = contentMode } } } } /* MARK: - Theming This extention provides a few convenience functions for setting styles, colors and icons. You are encouraged to write your own such functions if these don't exactly meet your needs. */ extension MessageView { /** A convenience function for setting some pre-defined colors and icons. - Parameter theme: The theme type to use. - Parameter iconStyle: The icon style to use. Defaults to `.Default`. */ public func configureTheme(_ theme: Theme, iconStyle: IconStyle = .default) { let iconImage = iconStyle.image(theme: theme) switch theme { case .info: let backgroundColor = UIColor(red: 225.0/255.0, green: 225.0/255.0, blue: 225.0/255.0, alpha: 1.0) let foregroundColor = UIColor.darkText configureTheme(backgroundColor: backgroundColor, foregroundColor: foregroundColor, iconImage: iconImage) case .success: let backgroundColor = UIColor(red: 97.0/255.0, green: 161.0/255.0, blue: 23.0/255.0, alpha: 1.0) let foregroundColor = UIColor.white configureTheme(backgroundColor: backgroundColor, foregroundColor: foregroundColor, iconImage: iconImage) case .warning: let backgroundColor = UIColor(red: 238.0/255.0, green: 189.0/255.0, blue: 34.0/255.0, alpha: 1.0) let foregroundColor = UIColor.white configureTheme(backgroundColor: backgroundColor, foregroundColor: foregroundColor, iconImage: iconImage) case .error: let backgroundColor = UIColor(red: 249.0/255.0, green: 66.0/255.0, blue: 47.0/255.0, alpha: 1.0) let foregroundColor = UIColor.white configureTheme(backgroundColor: backgroundColor, foregroundColor: foregroundColor, iconImage: iconImage) } } /** A convenience function for setting a foreground and background color. Note that images will only display the foreground color if they're configured with UIImageRenderingMode.AlwaysTemplate. - Parameter backgroundColor: The background color to use. - Parameter foregroundColor: The foreground color to use. */ public func configureTheme(backgroundColor: UIColor, foregroundColor: UIColor, iconImage: UIImage? = nil, iconText: String? = nil) { iconImageView?.image = iconImage iconLabel?.text = iconText iconImageView?.tintColor = foregroundColor let backgroundView = self.backgroundView ?? self backgroundView.backgroundColor = backgroundColor iconLabel?.textColor = foregroundColor titleLabel?.textColor = foregroundColor bodyLabel?.textColor = foregroundColor button?.backgroundColor = foregroundColor button?.tintColor = backgroundColor button?.contentEdgeInsets = UIEdgeInsetsMake(7.0, 7.0, 7.0, 7.0) button?.layer.cornerRadius = 5.0 iconImageView?.isHidden = iconImageView?.image == nil iconLabel?.isHidden = iconLabel?.text == nil } } /* MARK: - Configuring the content This extension provides a few convenience functions for configuring the message content. You are encouraged to write your own such functions if these don't exactly meet your needs. SwiftMessages does not try to be clever by adjusting the layout based on what content you configure. All message elements are optional and it is up to you to hide or remove elements you don't need. The easiest way to remove unwanted elements is to drag-and-drop one of the included nib files into your project as a starting point and make changes. */ extension MessageView { /** Sets the message body text. - Parameter body: The message body text to use. */ public func configureContent(body: String) { bodyLabel?.text = body } /** Sets the message title and body text. - Parameter title: The message title to use. - Parameter body: The message body text to use. */ public func configureContent(title: String, body: String) { configureContent(body: body) titleLabel?.text = title } /** Sets the message title, body text and icon image. Also hides the `iconLabel`. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconImage: The icon image to use. */ public func configureContent(title: String, body: String, iconImage: UIImage) { configureContent(title: title, body: body) iconImageView?.image = iconImage iconImageView?.isHidden = false iconLabel?.text = nil iconLabel?.isHidden = true } /** Sets the message title, body text and icon text (e.g. an emoji). Also hides the `iconImageView`. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconText: The icon text to use (e.g. an emoji). */ public func configureContent(title: String, body: String, iconText: String) { configureContent(title: title, body: body) iconLabel?.text = iconText iconLabel?.isHidden = false iconImageView?.isHidden = true iconImageView?.image = nil } /** Sets all configurable elements. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconImage: The icon image to use. - Parameter iconText: The icon text to use (e.g. an emoji). - Parameter buttonImage: The button image to use. - Parameter buttonTitle: The button title to use. - Parameter buttonTapHandler: The button tap handler block to use. */ public func configureContent(title: String?, body: String?, iconImage: UIImage?, iconText: String?, buttonImage: UIImage?, buttonTitle: String?, buttonTapHandler: ((_ button: UIButton) -> Void)?) { titleLabel?.text = title bodyLabel?.text = body iconImageView?.image = iconImage iconLabel?.text = iconText button?.setImage(buttonImage, for: UIControlState()) button?.setTitle(buttonTitle, for: UIControlState()) self.buttonTapHandler = buttonTapHandler iconImageView?.isHidden = iconImageView?.image == nil iconLabel?.isHidden = iconLabel?.text == nil } }
mit
9e1f6db362111de4f59581bd0de39212
35.591731
201
0.647059
4.96007
false
true
false
false
EZ-NET/ESOcean
ESOceanTests/UUID/UUIDTest.swift
1
2302
// // UUIDTest.swift // ESSwim // // Created by 熊谷 友宏 on H26/12/25. // // import XCTest import Ocean class UUIDTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUUIDGenerate() { let uuid1 = Ocean.UUID() let uuid1String = String(uuid1) print("Auto Generated UUID : \(uuid1String)") XCTAssertTrue(uuid1String.characters.count == 36) let uuid2String = "D7EE438F-1713-4B6A-8784-827727BA090B" let uuid2 = Ocean.UUID(string: uuid2String)! let uuid2_1 = Ocean.UUID(string: uuid2String)! XCTAssertEqual(String(uuid2), uuid2String) let uuid3String = "???E438F-1713-4B6A-8784-827727BA090B" let uuid3 = Ocean.UUID(string: uuid3String) XCTAssertTrue(uuid3 == nil) let uuid4:Ocean.UUID = "3472941B-812E-4136-8389-3DE6C9FC494F" XCTAssertTrue(String(uuid4) == "3472941B-812E-4136-8389-3DE6C9FC494F") // 文字列リテラルからの変換は、間違った値の場合は即落ち // let uuid5:Swim.UUID = "???2941B-812E-4136-8389-3DE6C9FC494F" let uuid6:Ocean.UUID = nil XCTAssertTrue(uuid6.isNull) XCTAssertEqual(uuid6, Ocean.UUID.Null) let uuid7 = uuid4 let uuid8:Ocean.UUID = "DA5900E0-25A4-4C84-9ADC-C82A66D92E4A" XCTAssertEqual(uuid7, uuid4) XCTAssertEqual(uuid2, uuid2_1) XCTAssertEqual(uuid4, uuid7) XCTAssertTrue(uuid2 > uuid4) XCTAssertTrue(uuid2 > uuid6) XCTAssertTrue(uuid4 > uuid6) XCTAssertTrue(uuid4 < uuid8) XCTAssertTrue(uuid2 < uuid8) XCTAssertTrue(uuid2 >= uuid2_1) XCTAssertTrue(uuid4 >= uuid7) XCTAssertTrue(uuid2 <= uuid2_1) XCTAssertTrue(uuid4 <= uuid7) XCTAssertTrue(uuid2 >= uuid4) XCTAssertTrue(uuid2 >= uuid6) XCTAssertTrue(uuid4 >= uuid6) XCTAssertTrue(uuid4 <= uuid8) XCTAssertTrue(uuid2 <= uuid8) XCTAssertFalse(uuid1.isNull) XCTAssertFalse(uuid2.isNull) XCTAssertFalse(uuid2_1.isNull) XCTAssertFalse(uuid4.isNull) XCTAssertTrue(uuid6.isNull) XCTAssertFalse(uuid7.isNull) XCTAssertFalse(uuid8.isNull) } }
mit
7019f3da3c0918b9ccfabcda509f2e71
23.637363
111
0.70339
2.946124
false
true
false
false
OneBestWay/EasyCode
Swift/TestMonkey/Pods/SwiftMonkeyPaws/SwiftMonkeyPaws/MonkeyPaws.swift
1
13305
// // MonkeyPaws.swift // Fleek // // Created by Dag Agren on 12/04/16. // Copyright © 2016 Zalando SE. All rights reserved. // import UIKit private let maxGesturesShown: Int = 15 private let crossRadius: CGFloat = 7 private let circleRadius: CGFloat = 7 /** A class that visualises input events as an overlay over your regular UI. To use, simply instantiate it and keep a reference to it around so that it does not get deinited. You will want to have some way to only instantiate it for test usage, though, such as adding a command-line flag to enable it. Example usage: ``` var paws: MonkeyPaws? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if CommandLine.arguments.contains("--MonkeyPaws") { paws = MonkeyPaws(view: window!) } return true } ``` */ public class MonkeyPaws: NSObject, CALayerDelegate { private var gestures: [(hash: Int?, gesture: Gesture)] = [] private weak var view: UIView? let layer = CALayer() fileprivate static var tappingTracks: [WeakReference<MonkeyPaws>] = [] /** Create a MonkeyPaws object that will visualise input events. - parameter view: The view to put the visualisation layer in. Usually, you will want to pass your main `UIWindow` here. - parameter tapUIApplication: By default, MonkeyPaws will swizzle some methods in UIApplication to intercept events so that it can visualise them. If you do not want this, pass `false` here and provide it with events manually. */ public init(view: UIView, tapUIApplication: Bool = true) { super.init() self.view = view layer.delegate = self layer.isOpaque = false layer.frame = view.layer.bounds layer.contentsScale = UIScreen.main.scale layer.rasterizationScale = UIScreen.main.scale view.layer.addSublayer(layer) if tapUIApplication { tapUIApplicationSendEvent() } } /** If you have disabled UIApplication event tapping, use this method to pass in `UIEvent` objects to visualise. */ public func append(event: UIEvent) { guard event.type == .touches else { return } guard let touches = event.allTouches else { return } for touch in touches { append(touch: touch) } bumpAndDisplayLayer() } func append(touch: UITouch) { guard let view = view else { return } let touchHash = touch.hash let point = touch.location(in: view) let index = gestures.index(where: { (gestureHash, _) -> Bool in return gestureHash == touchHash }) if let index = index { let gesture = gestures[index].gesture if touch.phase == .ended { gestures[index].gesture.end(at: point) gestures[index].hash = nil } else if touch.phase == .cancelled { gestures[index].gesture.cancel(at: point) gestures[index].hash = nil } else { gesture.extend(to: point) } } else { if gestures.count > maxGesturesShown { gestures.removeFirst() } gestures.append((hash: touchHash, gesture: Gesture(from: point, inLayer: layer))) for i in 0 ..< gestures.count { gestures[i].gesture.number = gestures.count - i } } } private static let swizzleMethods: Bool = { let originalSelector = #selector(UIApplication.sendEvent(_:)) let swizzledSelector = #selector(UIApplication.monkey_sendEvent(_:)) let originalMethod = class_getInstanceMethod(UIApplication.self, originalSelector) let swizzledMethod = class_getInstanceMethod(UIApplication.self, swizzledSelector) let didAddMethod = class_addMethod(UIApplication.self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) if didAddMethod { class_replaceMethod(UIApplication.self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) } else { method_exchangeImplementations(originalMethod, swizzledMethod) } return true }() private func tapUIApplicationSendEvent() { _ = MonkeyPaws.swizzleMethods MonkeyPaws.tappingTracks.append(WeakReference(self)) } private func bumpAndDisplayLayer() { guard let superlayer = layer.superlayer else { return } guard let layers = superlayer.sublayers else { return } guard let index = layers.index(of: layer) else { return } if index != layers.count - 1 { layer.removeFromSuperlayer() superlayer.addSublayer(layer) } layer.frame = superlayer.bounds layer.setNeedsDisplay() layer.displayIfNeeded() } } private class Gesture { var points: [CGPoint] var containerLayer = CALayer() var startLayer = CAShapeLayer() var numberLayer = CATextLayer() var pathLayer: CAShapeLayer? var endLayer: CAShapeLayer? private static var counter: Int = 0 init(from: CGPoint, inLayer: CALayer) { self.points = [from] let counter = Gesture.counter Gesture.counter += 1 let angle = 45 * (CGFloat(fmod(Float(counter) * 0.279, 1)) * 2 - 1) let mirrored = counter % 2 == 0 let colour = UIColor(hue: CGFloat(fmod(Float(counter) * 0.391, 1)), saturation: 1, brightness: 0.5, alpha: 1) startLayer.path = monkeyHandPath(angle: angle, scale: 1, mirrored: mirrored).cgPath startLayer.strokeColor = colour.cgColor startLayer.fillColor = nil startLayer.position = from containerLayer.addSublayer(startLayer) numberLayer.string = "1" numberLayer.bounds = CGRect(x:0, y: 0, width: 32, height: 13) numberLayer.fontSize = 10 numberLayer.alignmentMode = kCAAlignmentCenter numberLayer.foregroundColor = colour.cgColor numberLayer.position = from numberLayer.contentsScale = UIScreen.main.scale containerLayer.addSublayer(numberLayer) inLayer.addSublayer(containerLayer) } deinit { containerLayer.removeFromSuperlayer() } var number: Int = 0 { didSet { numberLayer.string = String(number) let fraction = Float(number - 1) / Float(maxGesturesShown) let alpha = sqrt(1 - fraction) containerLayer.opacity = alpha } } func extend(to: CGPoint) { guard let startPath = startLayer.path, let startPoint = points.first else { assertionFailure("No start marker layer exists") return } points.append(to) let pathLayer = self.pathLayer ?? { () -> CAShapeLayer in let newLayer = CAShapeLayer() newLayer.strokeColor = startLayer.strokeColor newLayer.fillColor = nil let maskPath = CGMutablePath() maskPath.addRect(CGRect(x: -10000, y: -10000, width: 20000, height: 20000)) maskPath.addPath(startPath) let maskLayer = CAShapeLayer() maskLayer.path = maskPath maskLayer.fillRule = kCAFillRuleEvenOdd maskLayer.position = startLayer.position newLayer.mask = maskLayer self.pathLayer = newLayer containerLayer.addSublayer(newLayer) return newLayer }() let path = CGMutablePath() path.move(to: startPoint) for point in points.dropFirst() { path.addLine(to: point) } pathLayer.path = path } func end(at: CGPoint) { guard endLayer == nil else { assertionFailure("Attempted to end or cancel a gesture twice!") return } extend(to: at) let layer = CAShapeLayer() layer.strokeColor = startLayer.strokeColor layer.fillColor = nil layer.position = at let path = circlePath() layer.path = path.cgPath containerLayer.addSublayer(layer) endLayer = layer } func cancel(at: CGPoint) { guard endLayer == nil else { assertionFailure("Attempted to end or cancel a gesture twice!") return } extend(to: at) let layer = CAShapeLayer() layer.strokeColor = startLayer.strokeColor layer.fillColor = nil layer.position = at let path = crossPath() layer.path = path.cgPath containerLayer.addSublayer(layer) endLayer = layer } } private func monkeyHandPath(angle: CGFloat, scale: CGFloat, mirrored: Bool) -> UIBezierPath { let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: -5.91, y: 8.76)) bezierPath.addCurve(to: CGPoint(x: -10.82, y: 2.15), controlPoint1: CGPoint(x: -9.18, y: 7.11), controlPoint2: CGPoint(x: -8.09, y: 4.9)) bezierPath.addCurve(to: CGPoint(x: -16.83, y: -1.16), controlPoint1: CGPoint(x: -13.56, y: -0.6), controlPoint2: CGPoint(x: -14.65, y: 0.5)) bezierPath.addCurve(to: CGPoint(x: -14.65, y: -6.11), controlPoint1: CGPoint(x: -19.02, y: -2.81), controlPoint2: CGPoint(x: -19.57, y: -6.66)) bezierPath.addCurve(to: CGPoint(x: -8.09, y: -2.81), controlPoint1: CGPoint(x: -9.73, y: -5.56), controlPoint2: CGPoint(x: -8.64, y: -0.05)) bezierPath.addCurve(to: CGPoint(x: -11.37, y: -13.82), controlPoint1: CGPoint(x: -7.54, y: -5.56), controlPoint2: CGPoint(x: -7, y: -8.32)) bezierPath.addCurve(to: CGPoint(x: -7.54, y: -17.13), controlPoint1: CGPoint(x: -15.74, y: -19.33), controlPoint2: CGPoint(x: -9.73, y: -20.98)) bezierPath.addCurve(to: CGPoint(x: -4.27, y: -8.87), controlPoint1: CGPoint(x: -5.36, y: -13.27), controlPoint2: CGPoint(x: -6.45, y: -7.76)) bezierPath.addCurve(to: CGPoint(x: -4.27, y: -18.23), controlPoint1: CGPoint(x: -2.08, y: -9.97), controlPoint2: CGPoint(x: -3.72, y: -12.72)) bezierPath.addCurve(to: CGPoint(x: 0.65, y: -18.23), controlPoint1: CGPoint(x: -4.81, y: -23.74), controlPoint2: CGPoint(x: 0.65, y: -25.39)) bezierPath.addCurve(to: CGPoint(x: 1.2, y: -8.32), controlPoint1: CGPoint(x: 0.65, y: -11.07), controlPoint2: CGPoint(x: -0.74, y: -9.29)) bezierPath.addCurve(to: CGPoint(x: 3.93, y: -18.78), controlPoint1: CGPoint(x: 2.29, y: -7.76), controlPoint2: CGPoint(x: 3.93, y: -9.3)) bezierPath.addCurve(to: CGPoint(x: 8.3, y: -16.03), controlPoint1: CGPoint(x: 3.93, y: -23.19), controlPoint2: CGPoint(x: 9.96, y: -21.86)) bezierPath.addCurve(to: CGPoint(x: 5.57, y: -6.11), controlPoint1: CGPoint(x: 7.76, y: -14.1), controlPoint2: CGPoint(x: 3.93, y: -6.66)) bezierPath.addCurve(to: CGPoint(x: 9.4, y: -10.52), controlPoint1: CGPoint(x: 7.21, y: -5.56), controlPoint2: CGPoint(x: 9.16, y: -10.09)) bezierPath.addCurve(to: CGPoint(x: 12.13, y: -6.66), controlPoint1: CGPoint(x: 12.13, y: -15.48), controlPoint2: CGPoint(x: 15.41, y: -9.42)) bezierPath.addCurve(to: CGPoint(x: 8.3, y: -1.16), controlPoint1: CGPoint(x: 8.85, y: -3.91), controlPoint2: CGPoint(x: 8.85, y: -3.91)) bezierPath.addCurve(to: CGPoint(x: 8.3, y: 7.11), controlPoint1: CGPoint(x: 7.76, y: 1.6), controlPoint2: CGPoint(x: 9.4, y: 4.35)) bezierPath.addCurve(to: CGPoint(x: -5.91, y: 8.76), controlPoint1: CGPoint(x: 7.21, y: 9.86), controlPoint2: CGPoint(x: -2.63, y: 10.41)) bezierPath.close() bezierPath.apply(CGAffineTransform(translationX: 0.5, y: 0)) bezierPath.apply(CGAffineTransform(scaleX: scale, y: scale)) if mirrored { bezierPath.apply(CGAffineTransform(scaleX: -1, y: 1)) } bezierPath.apply(CGAffineTransform(rotationAngle: angle / 180 * CGFloat.pi)) return bezierPath } private func circlePath() -> UIBezierPath { return UIBezierPath(ovalIn: CGRect(centre: CGPoint.zero, size: CGSize(width: circleRadius * 2, height: circleRadius * 2))) } private func crossPath() -> UIBezierPath { let rect = CGRect(centre: CGPoint.zero, size: CGSize(width: crossRadius * 2, height: crossRadius * 2)) let cross = UIBezierPath() cross.move(to: CGPoint(x: rect.minX, y: rect.minY)) cross.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) cross.move(to: CGPoint(x: rect.minX, y: rect.maxY)) cross.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) return cross } private struct WeakReference<T: AnyObject> { weak var value: T? init(_ value: T) { self.value = value } } extension UIApplication { func monkey_sendEvent(_ event: UIEvent) { for weakTrack in MonkeyPaws.tappingTracks { if let track = weakTrack.value { track.append(event: event) } } self.monkey_sendEvent(event) } } extension CGRect { public init(centre: CGPoint, size: CGSize) { self.origin = CGPoint(x: centre.x - size.width / 2, y: centre.y - size.height / 2) self.size = size } }
mit
5742c2a95b2cc91f484f8886a65f077b
34.763441
162
0.621993
4.002407
false
false
false
false
Melon-IT/animation-kit-swift
MelonAnimationKit/MelonAnimationKit/MBaseIconLayer.swift
1
4811
// // MBaseIconLayer.swift // MelonAnimationKit // // Created by Tomasz Popis on 29/02/16. // Copyright © 2016 Melon. All rights reserved. // import UIKit public enum MIconHorizontalAligment: Int { case left case center case right public init() { self = .center } } public enum MIconVerticalAligment: Int { case top case center case bottom public init() { self = .center } } public protocol MIconDrawingDelegate { func draw(in _context: CGContext, frame: CGRect) } open class MBaseIconLayer: CALayer { open var drawingDelegate: MIconDrawingDelegate? open var factor: CGFloat open var offset: UIOffset open var aligment:(horizontal: MIconHorizontalAligment,vertical: MIconVerticalAligment) open var color: UIColor public init(width: CGFloat, factor: CGFloat, offset: UIOffset, aligment:(MIconHorizontalAligment, MIconVerticalAligment), color: UIColor, drawingDelegate: MIconDrawingDelegate? = nil) { self.factor = factor self.offset = offset self.aligment = aligment self.color = color self.drawingDelegate = drawingDelegate super.init() self.frame = CGRect(x: 0, y: 0, width: width, height: width * self.factor) self.contentsScale = UIScreen.main.scale } public override init() { self.factor = 1 self.offset = UIOffset.zero self.aligment = (MIconHorizontalAligment(),MIconVerticalAligment()) self.color = UIColor.clear super.init() self.frame = CGRect(x: 0, y: 0, width: 0, height: 0) self.contentsScale = UIScreen.main.scale } public convenience init(width: CGFloat, color: UIColor = UIColor.clear, factor: CGFloat = 1) { self.init(width: width, factor: factor, offset: UIOffset.zero, aligment:(MIconHorizontalAligment(),MIconVerticalAligment()), color: color) } public override init(layer: Any) { if let iconLayer = layer as? MBaseIconLayer { self.factor = iconLayer.factor self.offset = iconLayer.offset self.aligment = iconLayer.aligment self.color = iconLayer.color super.init(layer: layer) self.frame = iconLayer.frame } else { self.factor = 1 self.offset = UIOffset.zero self.aligment = (MIconHorizontalAligment(),MIconVerticalAligment()) self.color = UIColor.clear super.init(layer: layer) self.frame = (layer as? CALayer)?.frame ?? CGRect.zero } } open override func encode(with coder: NSCoder) { coder.encode(self.offset, forKey: "offset") coder.encode(self.factor, forKey: "factor") coder.encode(self.aligment.horizontal, forKey: "horizontal-aligmnet") coder.encode(self.aligment.vertical, forKey: "verticla-aligment") coder.encode(self.color, forKey: "color") super.encode(with: coder) } public required init?(coder aDecoder: NSCoder) { self.offset = aDecoder.decodeUIOffset(forKey: "offset") self.factor = CGFloat(aDecoder.decodeFloat(forKey: "factor")) let horizontal = aDecoder.decodeObject(forKey: "horizontal-aligmnet") as! MIconHorizontalAligment let vertical = aDecoder.decodeObject(forKey: "verticla-aligment") as! MIconVerticalAligment self.aligment = (horizontal, vertical) self.color = aDecoder.decodeObject(forKey: "color") as! UIColor super.init(coder: aDecoder) } open override func draw(in ctx: CGContext) { self.drawingDelegate?.draw(in: ctx, frame: self.frame) } open func align() { if let superFrame = self.superlayer?.frame { switch self.aligment.horizontal { case MIconHorizontalAligment.left: self.frame.origin.x = 0 break case MIconHorizontalAligment.center: self.frame.origin.x = superFrame.width/2 - frame.width/2 break case MIconHorizontalAligment.right: self.frame.origin.x = superFrame.width - frame.width break } switch self.aligment.vertical { case MIconVerticalAligment.top: break case MIconVerticalAligment.center: self.frame.origin.y = superFrame.height/2 - frame.height/2 break case MIconVerticalAligment.bottom: self.frame.origin.y = superFrame.height - frame.height break } self.frame.origin.x += self.offset.horizontal self.frame.origin.y += self.offset.vertical } } }
mit
67caa6cd26ca44f3088afc8780dded6d
26.175141
101
0.616216
4.542021
false
false
false
false
DenHeadless/Transporter
Tests/TransporterTests/StateTests.swift
1
884
// // StateTests.swift // Transporter // // Created by Denys Telezhkin on 06.07.14. // Copyright (c) 2014 Denys Telezhkin. All rights reserved. // import XCTest import Transporter class StateTests: XCTestCase { func testNumberEqualStates() { let state = State(6) let state2 = State(5+1) XCTAssert(state.value == state2.value) } func testNumberDifferentState() { let state = State(4) let state2 = State(3) XCTAssertFalse(state.value == state2.value) } func testDifferentStrings() { let state = State("Foo") let state2 = State("Bar") XCTAssertFalse(state.value == state2.value) } func testIdenticalStrings() { let state = State("omg") let state2 = State("omg") XCTAssert(state.value == state2.value) } }
mit
9b5eddeb3f96189d3462f969d0397aee
20.560976
60
0.579186
4.03653
false
true
false
false
timelessg/TLStoryCamera
TLStoryCameraFramework/TLStoryCameraFramework/Class/Views/TLStoryCameraButton.swift
1
9212
// // TLStoryCameraButton.swift // TLStoryCamera // // Created by GarryGuo on 2017/5/10. // Copyright © 2017年 GarryGuo. All rights reserved. // import UIKit let MaxDragOffset:CGFloat = 300; protocol TLStoryCameraButtonDelegate : NSObjectProtocol { func cameraStart(hoopButton:TLStoryCameraButton) -> Void func cameraComplete(hoopButton:TLStoryCameraButton, type:TLStoryType) -> Void func cameraDrag(hoopButton:TLStoryCameraButton,offsetY:CGFloat) -> Void } class TLStoryCameraButton: UIControl { public weak var delegete : TLStoryCameraButtonDelegate? public var centerPoint:CGPoint { return CGPoint.init(x: self.width / 2.0, y: self.width / 2.0) } fileprivate let zoomInSize = CGSize.init(width: 120, height: 120) fileprivate let zoomOutSize = CGSize.init(width: 80, height: 80) fileprivate lazy var blureCircleView:UIVisualEffectView = { $0.isUserInteractionEnabled = false $0.layer.cornerRadius = 40 $0.layer.masksToBounds = true return $0 }(UIVisualEffectView.init(effect: UIBlurEffect.init(style: .light))) fileprivate lazy var insideCircleView:UIView = { $0.backgroundColor = UIColor.white $0.isUserInteractionEnabled = false $0.layer.cornerRadius = 27.5 return $0 }(UIView.init()) fileprivate lazy var ringMaskLayer:CAShapeLayer = { var proLayer = CAShapeLayer() proLayer.lineWidth = 3 proLayer.strokeColor = UIColor.init(colorHex: 0x0056ff).cgColor proLayer.fillColor = UIColor.clear.cgColor proLayer.lineJoin = kCALineJoinRound proLayer.lineCap = kCALineCapRound return proLayer }() fileprivate lazy var gradientLayer:CAGradientLayer = { var gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.colors = [UIColor.red.cgColor, UIColor.orange.cgColor] gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5) return gradientLayer }() fileprivate var insideCircleViewTransform:CGAffineTransform? fileprivate var blureCircleViewTransform:CGAffineTransform? fileprivate var timer:CADisplayLink? fileprivate var percent:CGFloat = 0 fileprivate var totalPercent = CGFloat(Double.pi * 2.0) / CGFloat(TLStoryConfiguration.maxRecordingTime) fileprivate var progress:CGFloat = 0 override init(frame:CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear blureCircleView.bounds = CGRect.init(x: 0, y: 0, width: zoomOutSize.width, height: zoomOutSize.height) blureCircleView.center = centerPoint self.addSubview(blureCircleView) insideCircleView.frame = CGRect.init(x: 0, y: 0, width: 55, height: 55) insideCircleView.clipsToBounds = true insideCircleView.center = centerPoint self.addSubview(insideCircleView) self.layer.addSublayer(gradientLayer) gradientLayer.mask = ringMaskLayer self.addTarget(self, action: #selector(startAction), for: .touchDown) self.addTarget(self, action: #selector(complete), for: [.touchUpOutside,.touchUpInside,.touchCancel]) self.addTarget(self, action: #selector(draggedAction), for: .touchDragInside) self.addTarget(self, action: #selector(draggedAction), for: .touchDragOutside) } public func show() { self.isHidden = false UIView.animate(withDuration: 0.25, animations: { self.centerY -= 50 self.alpha = 1 }) } @objc fileprivate func complete() { self.stopTimer() self.delegete?.cameraComplete(hoopButton: self, type: self.progress < CGFloat(TLStoryConfiguration.minRecordingTime) ? .photo : .video) percent = 0 progress = 0 self.setNeedsDisplay() } public func reset() { blureCircleView.layer.removeAnimation(forKey: "blureCircleScale") insideCircleView.layer.removeAnimation(forKey: "insideCircleAnim") self.bounds = CGRect.init(x: 0, y: 0, width: self.zoomOutSize.width, height: self.zoomOutSize.height) self.center = CGPoint.init(x: self.superview!.width / 2, y: self.superview!.bounds.height - 53 - 40) self.blureCircleView.center = centerPoint if let t = self.blureCircleViewTransform { self.blureCircleView.transform = t } if let t = self.insideCircleViewTransform { self.insideCircleView.transform = t } self.insideCircleView.alpha = 1 self.insideCircleView.center = self.centerPoint UIView.animate(withDuration: 0.25, animations: { self.centerY += 50 self.alpha = 0 }) { (x) in self.isHidden = true } } @objc fileprivate func startAction(sender:UIButton) { self.delegete?.cameraStart(hoopButton: self) self.bounds = CGRect.init(x: 0, y: 0, width: zoomInSize.width, height: zoomInSize.height) self.center = CGPoint.init(x: superview!.width / 2, y: superview!.bounds.height - 30 - 60) self.insideCircleView.center = centerPoint self.gradientLayer.bounds = self.bounds; self.gradientLayer.position = self.centerPoint insideCircleViewTransform = insideCircleView.transform blureCircleViewTransform = blureCircleView.transform self.touchBeginAnim() self.startTimer() } fileprivate func startTimer() { timer?.invalidate() timer = CADisplayLink.init(target: self, selector: #selector(countDownd)) timer?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) } fileprivate func stopTimer() { timer?.isPaused = true timer?.invalidate() timer = nil } @objc fileprivate func draggedAction(sender:UIButton, event:UIEvent) { let touch = (event.allTouches! as NSSet).anyObject() as! UITouch let point = touch.location(in: self) let offsetY = point.y < 0 ? -point.y : 0; if offsetY < MaxDragOffset && offsetY > 0 { delegete?.cameraDrag(hoopButton: self, offsetY: offsetY) } } @objc fileprivate func countDownd() { progress += 1 percent = totalPercent * progress if progress > CGFloat(TLStoryConfiguration.maxRecordingTime) { self.cancelTracking(with: nil) } self.setNeedsDisplay() } fileprivate func touchBeginAnim() { blureCircleView.center = centerPoint let insideCircleScaleAnim = CABasicAnimation.init(keyPath: "transform.scale") insideCircleScaleAnim.fromValue = 1 insideCircleScaleAnim.toValue = 0.8 let insideCircleAlphaAnim = CABasicAnimation.init(keyPath: "opacity") insideCircleAlphaAnim.fromValue = 1 insideCircleAlphaAnim.toValue = 0.6 let insideCircleGroupAnim = CAAnimationGroup.init() insideCircleGroupAnim.animations = [insideCircleAlphaAnim,insideCircleScaleAnim] insideCircleGroupAnim.duration = 0.35 insideCircleGroupAnim.isRemovedOnCompletion = false insideCircleGroupAnim.fillMode = kCAFillModeBoth insideCircleGroupAnim.delegate = self insideCircleView.layer.add(insideCircleGroupAnim, forKey: "insideCircleAnim") let anim = CABasicAnimation.init(keyPath: "transform.scale") anim.fromValue = 1 anim.toValue = 1.5 anim.fillMode = kCAFillModeBoth anim.isRemovedOnCompletion = false anim.duration = 0.35 anim.delegate = self blureCircleView.layer.add(anim, forKey: "blureCircleScale") } internal override func draw(_ rect: CGRect) { let path = UIBezierPath.init(arcCenter: CGPoint.init(x: self.width / 2.0, y: self.height / 2.0), radius: 58, startAngle: 1.5 * CGFloat(Double.pi), endAngle: 1.5 * CGFloat(Double.pi) + percent, clockwise: true) self.ringMaskLayer.path = path.cgPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TLStoryCameraButton: CAAnimationDelegate { internal func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let a = insideCircleView.layer.animation(forKey: "insideCircleAnim"), a.isEqual(anim) { if flag { insideCircleView.alpha = 0.6 insideCircleView.transform = insideCircleView.transform.scaledBy(x: 0.8, y: 0.8) } insideCircleView.layer.removeAnimation(forKey: "insideCircleAnim") } if let a = blureCircleView.layer.animation(forKey: "blureCircleScale"), a.isEqual(anim) { if flag { blureCircleView.transform = blureCircleView.transform.scaledBy(x: 1.5, y: 1.5) } blureCircleView.layer.removeAnimation(forKey: "blureCircleScale") } } }
mit
e8c48db7b9f7874a6cd07d54e9765b8f
36.897119
218
0.651428
4.756715
false
false
false
false
con-beo-vang/Spendy
Spendy/Views/Settings/ThemeCell.swift
1
1297
// // ThemeCell.swift // Spendy // // Created by Dave Vo on 9/27/15. // Copyright © 2015 Cheetah. All rights reserved. // import UIKit import SevenSwitch @objc protocol ThemeCellDelegate { optional func themeCell(timeCell: ThemeCell, didChangeValue value: Bool) } class ThemeCell: UITableViewCell { @IBOutlet weak var switchView: UIView! var onSwitch: SevenSwitch! var delegate: ThemeCellDelegate! override func awakeFromNib() { super.awakeFromNib() onSwitch = SevenSwitch(frame: CGRect(x: 0, y: 0, width: 70, height: 30)) onSwitch.thumbTintColor = UIColor.whiteColor() onSwitch.activeColor = UIColor.clearColor() onSwitch.inactiveColor = UIColor.clearColor() onSwitch.onTintColor = Color.strongColor onSwitch.borderColor = UIColor(netHex: 0xDCDCDC) onSwitch.shadowColor = UIColor(netHex: 0x646464) onSwitch.offLabel.text = "Green" onSwitch.onLabel.text = "Gold" onSwitch.onLabel.textColor = UIColor.whiteColor() switchView.addSubview(onSwitch) onSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: UIControlEvents.ValueChanged) } func switchValueChanged() { if delegate != nil { delegate?.themeCell?(self, didChangeValue: onSwitch.on) } } }
mit
49e9fbec0881ca53860089b73dd4321a
24.411765
106
0.70216
4.24918
false
false
false
false
apple/swift-syntax
Sources/SwiftSyntax/SyntaxTreeViewMode.swift
1
1679
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Specifies how missing and unexpected nodes should be handled when traversing /// a syntax tree. public enum SyntaxTreeViewMode { /// Visit the tree in a way that reproduces the original source code. /// Missing nodes will not be visited, unexpected nodes will be visited. /// This mode is useful for source code transformations like a formatter. case sourceAccurate /// Views the syntax tree with fixes applied, that is missing nodes will be /// visited but unexpected nodes will be skipped. /// This views the tree in a way that's closer to being syntactical correct /// and should be used for structural analysis of the syntax tree. case fixedUp /// Both missing and unexpected nodes will be traversed. case all /// Returns whether this traversal node should visit `node` or ignore it. @_spi(RawSyntax) public func shouldTraverse(node: RawSyntax) -> Bool { switch self { case .sourceAccurate: if let tokenView = node.tokenView { return tokenView.presence == .present } return true case .fixedUp: return node.kind != .unexpectedNodes case .all: return true } } }
apache-2.0
e3d8aa77ac8d2e1562da0cabf2deb6d9
36.311111
80
0.645622
4.909357
false
false
false
false
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Home/Controller/RecommendViewController.swift
1
3311
// // RecommendViewController.swift // MSDouYuZB // // Created by jiayuan on 2017/8/2. // Copyright © 2017年 mrsong. All rights reserved. // import UIKit private let kPrettyItemH: CGFloat = kItemW * 4/3 private let kScrollCycleVH: CGFloat = kScreenW * 3/8 private let kCateVH: CGFloat = 90 private let kPrettyCellID = "kPrettyCellID" class RecommendViewController: BaseTVCateViewController, UICollectionViewDelegateFlowLayout { // MARK: - 属性 private lazy var presenter = RecommendPresenter() private lazy var scrollCycleV: ScrollCycleView = { let scrollCycleV = ScrollCycleView.getView() scrollCycleV.frame = CGRect(x: 0, y: -kScrollCycleVH-kCateVH, width: kScreenW, height: kScrollCycleVH) return scrollCycleV }() private lazy var cateV: RecommendCateView = { let cateV = RecommendCateView.getView() cateV.frame = CGRect(x: 0, y: -kCateVH, width: kScreenW, height: kCateVH) return cateV }() // MARK: - Private Methods override func loadData() { dataSource = presenter // 请求直播数据 showLoading() presenter.requestTVData { [weak self] in self?.hideLoading() // 展示各个分类的直播数据 self?.collectionV.reloadData() // 展示推荐的分类数据 // 移除热门和颜值分类 var cateArr = self?.presenter.tvCateArr cateArr?.removeFirst() cateArr?.removeFirst() // 追加更多分类 let cate = TVCate() cate.tag_name = "更多" cateArr?.append(cate) self?.cateV.cateArr = cateArr } // 请求循环轮播数据 presenter.requestScrollCycleData {[weak self] in self?.scrollCycleV.itemArr = self?.presenter.scrollCycleItemArr } } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell cell.tvRoom = presenter.tvCateArr[indexPath.section].roomArr[indexPath.row] return cell } return super.collectionView(collectionView, cellForItemAt: indexPath) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } // MARK: - UI override func setupUI() { super.setupUI() collectionV.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionV.addSubview(scrollCycleV) collectionV.addSubview(cateV) collectionV.contentInset = UIEdgeInsets(top: kScrollCycleVH + kCateVH, left: 0, bottom: 0, right: 0) } }
mit
bfab32add046c844d5a1d09a0699a4b8
31.673469
160
0.639288
4.873668
false
false
false
false
tanhuiya/ThPullRefresh
ThPullRefreshDemo/ExampleController_two.swift
1
1708
// // ExampleController_two.swift // PullRefreshDemo // // Created by ci123 on 16/1/19. // Copyright © 2016年 tanhui. All rights reserved. // import UIKit class ExampleController_two: UIViewController { let tableView : UITableView = UITableView() lazy var dataArr : NSMutableArray = { return NSMutableArray() }() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.barTintColor = UIColor.orangeColor() self.navigationController?.navigationBar.barStyle = .BlackTranslucent } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(tableView) tableView.frame = self.view.bounds self.tableView.addBounceHeadRefresh(self,bgColor:UIColor.orangeColor(),loadingColor:UIColor.lightGrayColor(), action: "loadNewData") self.tableView.addFootRefresh(self, action: "loadMoreData") } func loadNewData(){ dataArr.removeAllObjects() for (var i = 0 ;i<5;i++){ let str = "最新5个cell,第\(i+1)个" dataArr.addObject(str) } //延时模拟刷新 DeLayTime(2.0, closure: { () -> () in self.tableView.reloadData() self.tableView.tableHeadStopRefreshing() }) } func loadMoreData(){ for (var i = 0 ;i<5;i++){ let str = "上拉刷新5个cell,第\(i+1)个" dataArr.addObject(str) } //延时模拟刷新 DeLayTime(2.0, closure: { () -> () in self.tableView.reloadData() self.tableView.tableFootStopRefreshing() }) } }
mit
b59bf31c8e5a82a1b5450c99cd4b1cbb
29.611111
140
0.606171
4.260309
false
false
false
false
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/CoreDataStore.swift
1
2734
// // CoreDataStore.swift // SpareTimeAlarmApp // // Created by Pham Nguyen Nhat Trung on 8/6/15. // Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved. // import CoreData class CoreDataStore: NSObject { let storeName = "CoreData" let storeFilename = "CoreData.sqlite" lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "me.iascchen.MyTTT" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource(self.storeName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.storeFilename) var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions) } catch var error as NSError { coordinator = nil // Report any error we got. // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error.userInfo)") abort() } catch { fatalError() } return coordinator }() }
mit
1696c87436eeb63c7288cefd90e62cfb
50.584906
290
0.704828
5.602459
false
false
false
false
lyimin/iOS-Animation-Demo
iOS-Animation学习笔记/iOS-Animation学习笔记/扩大背景转场动画/PingFirstController.swift
1
3882
// // PingFirstController.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 16/1/14. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit class PingFirstController : UIViewController, PingFirstContentViewDelegate, UINavigationControllerDelegate, PingIconViewController { /// 数据 let items = [ PingItemModel(image: UIImage(named: "icon-twitter"), color: UIColor(red: 0.255, green: 0.557, blue: 0.910, alpha: 1), name: "Twitter", summary: "Twitter is an online social networking service that enables users to send and read short 140-character messages called \"tweets\"."), PingItemModel(image: UIImage(named: "icon-facebook"), color: UIColor(red: 0.239, green: 0.353, blue: 0.588, alpha: 1), name: "Facebook", summary: "Facebook (formerly thefacebook) is an online social networking service headquartered in Menlo Park, California. Its name comes from a colloquialism for the directory given to students at some American universities."), PingItemModel(image: UIImage(named: "icon-youtube"), color: UIColor(red: 0.729, green: 0.188, blue: 0.180, alpha: 1), name: "Youtube", summary: "YouTube is a video-sharing website headquartered in San Bruno, California. The service was created by three former PayPal employees in February 2005 and has been owned by Google since late 2006. The site allows users to upload, view, and share videos.") ] // 记录当前点中的图标和背景色 fileprivate weak var selectIcon : UIImageView! fileprivate weak var selectColor : UIView! //MARK: - Lify cycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.delegate = self self.navigationController?.isNavigationBarHidden = true; } override func viewDidLoad() { super.viewDidLoad() let contentView : PingFirstContentView = PingFirstContentView.contentView() contentView.delegate = self contentView.frame = self.view.bounds self.view.addSubview(contentView) } //MARK: - UINavigation Delegate func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .push { return PingTransition(operation: .push) } else if operation == .pop { return PingTransition(operation: .pop) } return nil } //MARK: - PingIconViewController Delegate func pingIconColorViewForTransition(_ transition: PingTransition) -> UIView! { if let color = selectColor { return color } else { return nil } } func pingIconImageViewForTransition(_ transition: PingTransition) -> UIImageView! { if let icon = selectIcon { return icon } else { return nil } } //MARK: - Event or Action func twitterItemViewClick(_ color: UIView!, icon: UIImageView!) { self.selectColor = color self.selectIcon = icon self.navigationController?.pushViewController(PingSecondController(model: items.first! ), animated: true) } func facebookItemViewClick(_ color: UIView!, icon: UIImageView!) { self.selectColor = color self.selectIcon = icon self.navigationController?.pushViewController(PingSecondController(model: items[1]), animated: true) } func youtubeItemViewClick(_ color: UIView!, icon: UIImageView!) { self.selectColor = color self.selectIcon = icon self.navigationController?.pushViewController(PingSecondController(model: items.last!), animated: true) } }
mit
5b0b42a3179a5d5a00739267c8ff7b19
42.579545
406
0.680574
4.823899
false
false
false
false
LuckyResistor/FontToBytes
FontToBytes/InputImage.swift
1
2753
// // Lucky Resistor's Font to Byte // --------------------------------------------------------------------------- // (c)2015 by Lucky Resistor. See LICENSE for details. // // 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 2 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, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // import Cocoa /// A protocol which wraps the input image for the converter /// protocol InputImage { /// The width of the image in pixels. /// var width: Int { get } /// The height of the image in pixels. /// var height: Int { get } /// Check if a given pixel is set in the image. /// func isPixelSet(x x: Int, y: Int) -> Bool } /// A input image which is based on a NSImage. /// class InputImageFromNSImage: InputImage { /// The internal image representation. /// private var bitmapImage: NSBitmapImageRep? = nil; /// Create a new instance from the given image. /// /// - Parameter image: The image to use. /// init(image: NSImage) throws { if image.TIFFRepresentation == nil { throw ConverterError(summary: "The current image can not be converted into the required format.", details: "Please use a RGB or RGBA image in PNG format for the best results."); } bitmapImage = NSBitmapImageRep(data: image.TIFFRepresentation!)!; } // Implement the protocol var width: Int { get { return bitmapImage!.pixelsWide } } var height: Int { get { return bitmapImage!.pixelsHigh } } func isPixelSet(x x: Int, y: Int) -> Bool { if x < 0 || x > self.width || y < 0 || y > self.height { return false } if let color = bitmapImage!.colorAtX(x, y: y) { if color.alphaComponent < 1.0 { return false } if color.redComponent > 0.2 || color.blueComponent > 0.2 || color.greenComponent > 0.2 { return false } else { return true } } else { return false } } }
gpl-2.0
e12e9ce4bb48157b60b1a85f4e673cf4
27.091837
109
0.582637
4.588333
false
false
false
false
skyPeat/DoYuLiveStreaming
DoYuLiveStreaming/DoYuLiveStreaming/Classes/Tools/SP_NetWorkingTool.swift
1
984
// // SP_NetWorkingTool.swift // DoYuLiveStreaming // // Created by tianfeng pan on 17/3/23. // Copyright © 2017年 tianfeng pan. All rights reserved. // import UIKit import Alamofire enum requestType { case get case post } class SP_NetWorkingTool { class func request(type : requestType,urlString : String,parameters : [String : Any]? = nil,finishedCallBack : @escaping (_ result : Any) -> ()){ // 0、获取请求类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 1、发送网络请求 Alamofire.request(urlString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in // 3.获取结果 guard let result = response.result.value else { print(response.result.error!) return } // 4.将结果回调出去 finishedCallBack(result) } } }
mit
a5ca53b9a025a338391a2736c8c6ce67
29.032258
150
0.60043
4.193694
false
false
false
false
flash286/swift-ios-psyhologist
Psyhologist/DiagnosedHappinessViewController.swift
1
1675
// // DiagnosedHappinessViewController.swift // Psyhologist // // Created by Брызгалов Николай on 01.03.15. // Copyright (c) 2015 Bryzgalov Nikolay. All rights reserved. // import UIKit class DiagnosedHappinessViewController: HappinessViewController, UIPopoverPresentationControllerDelegate { override var happines: Int { didSet { diagnosticHistory += [happines] } } private let defaults = NSUserDefaults.standardUserDefaults() var diagnosticHistory: [Int] { set { defaults.setObject(newValue, forKey: History.DefaultsKey) } get { return defaults.objectForKey(History.DefaultsKey) as? [Int] ?? [] } } private struct History { static let SegueIdentifier = "Show Diagnostic History" static let DefaultsKey = "DiagnosedHappinessViewController.History" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case History.SegueIdentifier: if let tvc = segue.destinationViewController as? TextViewController { if let ppc = tvc.popoverPresentationController { ppc.delegate = self } tvc.text = "\(diagnosticHistory)" } default: break } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } }
apache-2.0
0ff16c9dcb968acd83cb9b9db5733212
29.722222
127
0.617842
5.701031
false
false
false
false
ldt25290/MyInstaMap
ThirdParty/AlamofireImage/Source/UIImage+AlamofireImage.swift
3
12454
// // UIImage+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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) || os(watchOS) import CoreGraphics import Foundation import UIKit // MARK: Initialization private let lock = NSLock() extension UIImage { /// Initializes and returns the image object with the specified data in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:)` method. /// /// - parameter data: The data object containing the image data. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data) -> UIImage? { lock.lock() let image = UIImage(data: data) lock.unlock() return image } /// Initializes and returns the image object with the specified data and scale in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:scale:)` method. /// /// - parameter data: The data object containing the image data. /// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 /// results in an image whose size matches the pixel-based dimensions of the image. Applying a /// different scale factor changes the size of the image as reported by the size property. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? { lock.lock() let image = UIImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKey { static var inflated = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool { return inflated } else { return false } } set { objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. /// /// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it /// allows a bitmap representation to be constructed in the background rather than on the main thread. public func af_inflate() { guard !af_inflated else { return } af_inflated = true _ = cgImage?.dataProvider?.data } } // MARK: - Alpha extension UIImage { /// Returns whether the image contains an alpha component. public var af_containsAlphaComponent: Bool { let alphaInfo = cgImage?.alphaInfo return ( alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast ) } /// Returns whether the image is opaque. public var af_isOpaque: Bool { return !af_containsAlphaComponent } } // MARK: - Scaling extension UIImage { /// Returns a new version of the image scaled to the specified size. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageScaled(to size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: .zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// The resulting image contains an alpha component used to pad the width or height with the necessary transparent /// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. /// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` /// method in conjunction with a `.Center` content mode to achieve the same visual result. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFit size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFill size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// /// - returns: A new image object. public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// Returns a new version of the image rounded into a circle. /// /// - returns: A new image object. public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } } #endif #if os(iOS) || os(tvOS) import CoreImage // MARK: - Core Image Filters @available(iOS 9.0, *) extension UIImage { /// Returns a new version of the image using a CoreImage filter with the specified name and parameters. /// /// - parameter name: The name of the CoreImage filter to use on the new image. /// - parameter parameters: The parameters to apply to the CoreImage filter. /// /// - returns: A new image object, or `nil` if the filter failed for any reason. public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? { var image: CoreImage.CIImage? = ciImage if image == nil, let CGImage = self.cgImage { image = CoreImage.CIImage(cgImage: CGImage) } guard let coreImage = image else { return nil } let context = CIContext(options: [kCIContextPriorityRequestLow: true]) var parameters: [String: Any] = parameters ?? [:] parameters[kCIInputImageKey] = coreImage guard let filter = CIFilter(name: name, withInputParameters: parameters) else { return nil } guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent) return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation) } } #endif
mit
33deefcabcbf75879a57904ee8d0fd12
38.536508
122
0.660591
4.799229
false
false
false
false
applico/iOS-Categories
Swift/UIImage+Additions.swift
2
2227
// // UIImage+Additions.swift // iOSCategories // // Created by Applico on 6/2/15. // Copyright (c) 2015 Applico Inc. All rights reserved. // import Foundation import UIKit extension UIImage { func imageByScalingProportionallToSize(targetSize: CGSize) -> UIImage { var sourceImage = self var newImage = UIImage() var scaleFactor:CGFloat = 0 var scaledWidth = sourceImage.size.width var scaledHeight = sourceImage.size.height var thumbnailOrigin = CGPointZero if CGSizeEqualToSize(sourceImage.size, targetSize) == false { if targetSize.width/sourceImage.size.width > targetSize.height/sourceImage.size.height { scaleFactor = targetSize.width/sourceImage.size.width } else { scaleFactor = targetSize.height/sourceImage.size.height } scaledWidth = sourceImage.size.width * scaleFactor scaledHeight = sourceImage.size.height * scaleFactor thumbnailOrigin.x = targetSize.width - scaledWidth } //draw thumbnail UIGraphicsBeginImageContext(targetSize) var thumbnailRect = CGRectZero thumbnailRect.origin = thumbnailOrigin thumbnailRect.size.width = scaledWidth thumbnailRect.size.height = scaledHeight sourceImage.drawInRect(thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func imageByApplyingAlpha(alpha:CGFloat) -> UIImage{ UIGraphicsBeginImageContextWithOptions(size, false, 0.0) var ctx = UIGraphicsGetCurrentContext() var area = CGRectMake(0, 0, size.width, size.height) CGContextScaleCTM(ctx, 1, -1) CGContextTranslateCTM(ctx, 0, -size.height) CGContextSetBlendMode(ctx, kCGBlendModeMultiply) CGContextSetAlpha(ctx, alpha) CGContextDrawImage(ctx, area, CGImage) var newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
mit
e2bac1ff88e5e49c68adce4110417e6e
23.472527
96
0.636731
5.695652
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Entity Test Doubles/FakeEvent.swift
1
6158
import EurofurenceModel import Foundation import TestUtilities public final class FakeEvent: Event { public enum FavouritedState { case unset case favourited case unfavourited } public var identifier: EventIdentifier public var title: String public var subtitle: String public var abstract: String public var room: Room public var track: Track public var hosts: String public var day: Day public var startDate: Date public var endDate: Date public var eventDescription: String public var posterGraphicPNGData: Data? public var bannerGraphicPNGData: Data? public var isSponsorOnly: Bool public var isSuperSponsorOnly: Bool public var isArtShow: Bool public var isKageEvent: Bool public var isDealersDen: Bool public var isMainStage: Bool public var isPhotoshoot: Bool public var isAcceptingFeedback: Bool public var isFavourite: Bool public var isFaceMaskRequired: Bool public init( identifier: EventIdentifier, title: String, subtitle: String, abstract: String, room: Room, track: Track, hosts: String, day: Day, startDate: Date, endDate: Date, eventDescription: String, posterGraphicPNGData: Data?, bannerGraphicPNGData: Data?, isSponsorOnly: Bool, isSuperSponsorOnly: Bool, isArtShow: Bool, isKageEvent: Bool, isDealersDen: Bool, isMainStage: Bool, isPhotoshoot: Bool, isAcceptingFeedback: Bool, isFavourite: Bool, isFaceMaskRequired: Bool ) { self.identifier = identifier self.title = title self.subtitle = subtitle self.abstract = abstract self.room = room self.track = track self.hosts = hosts self.day = day self.startDate = startDate self.endDate = endDate self.eventDescription = eventDescription self.posterGraphicPNGData = posterGraphicPNGData self.bannerGraphicPNGData = bannerGraphicPNGData self.isSponsorOnly = isSponsorOnly self.isSuperSponsorOnly = isSuperSponsorOnly self.isArtShow = isArtShow self.isKageEvent = isKageEvent self.isDealersDen = isDealersDen self.isMainStage = isMainStage self.isPhotoshoot = isPhotoshoot self.isAcceptingFeedback = isAcceptingFeedback self.isFavourite = isFavourite self.isFaceMaskRequired = isFaceMaskRequired favouritedState = .unset } private var observers: [EventObserver] = [] public func add(_ observer: EventObserver) { observers.append(observer) notifyObserverOfCurrentFavouriteStateAsPerEventContract(observer) } public func remove(_ observer: EventObserver) { observers.removeAll(where: { $0 === observer }) } public private(set) var favouritedState: FavouritedState public func favourite() { isFavourite = true favouritedState = .favourited observers.forEach({ $0.eventDidBecomeFavourite(self) }) } public func unfavourite() { isFavourite = false favouritedState = .unfavourited observers.forEach({ $0.eventDidBecomeUnfavourite(self) }) } public var feedbackToReturn: FakeEventFeedback? public private(set) var lastGeneratedFeedback: FakeEventFeedback? public func prepareFeedback() -> EventFeedback { let feedback = feedbackToReturn ?? FakeEventFeedback() lastGeneratedFeedback = feedback return feedback } public let shareableURL = URL.random public var contentURL: URL { return shareableURL } private func notifyObserverOfCurrentFavouriteStateAsPerEventContract(_ observer: EventObserver) { if favouritedState == .favourited { observer.eventDidBecomeFavourite(self) } else { observer.eventDidBecomeUnfavourite(self) } } } public class FakeEventFeedback: EventFeedback { public enum State { case unset case submitted } public private(set) var state: State = .unset public var feedback: String public var starRating: Int public init(rating: Int = 0) { feedback = "" self.starRating = rating } private var delegate: EventFeedbackDelegate? public func submit(_ delegate: EventFeedbackDelegate) { state = .submitted self.delegate = delegate } public func simulateSuccess() { delegate?.eventFeedbackSubmissionDidFinish(self) } public func simulateFailure() { delegate?.eventFeedbackSubmissionDidFail(self) } } extension FakeEvent: RandomValueProviding { public static var random: FakeEvent { let startDate = Date.random return FakeEvent( identifier: .random, title: .random, subtitle: .random, abstract: .random, room: .random, track: .random, hosts: .random, day: .random, startDate: startDate, endDate: startDate.addingTimeInterval(.random), eventDescription: .random, posterGraphicPNGData: .random, bannerGraphicPNGData: .random, isSponsorOnly: .random, isSuperSponsorOnly: .random, isArtShow: .random, isKageEvent: .random, isDealersDen: .random, isMainStage: .random, isPhotoshoot: .random, isAcceptingFeedback: .random, isFavourite: .random, isFaceMaskRequired: .random ) } public static var randomStandardEvent: FakeEvent { let event = FakeEvent.random event.isSponsorOnly = false event.isSuperSponsorOnly = false event.isArtShow = false event.isKageEvent = false event.isMainStage = false event.isPhotoshoot = false event.isDealersDen = false return event } }
mit
364c5c2b833f70147b58ca8239bb939d
27.910798
101
0.634622
5.317789
false
false
false
false
apple/swift
test/SILGen/constrained_extensions.swift
2
12980
// RUN: %target-swift-emit-silgen -module-name constrained_extensions -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-sil -module-name constrained_extensions -O -primary-file %s > /dev/null // RUN: %target-swift-emit-ir -module-name constrained_extensions -primary-file %s > /dev/null extension Array where Element == Int { // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int> public init(x: ()) { self.init() } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE16instancePropertySivg : $@convention(method) (@guaranteed Array<Int>) -> Int // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE16instancePropertySivs : $@convention(method) (Int, @inout Array<Int>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$sSa22constrained_extensionsSiRszlE16instancePropertySivM : $@yield_once @convention(method) (@inout Array<Int>) -> @yields @inout Int public var instanceProperty: Element { get { return self[0] } set { self[0] = newValue } } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE14instanceMethodSiyF : $@convention(method) (@guaranteed Array<Int>) -> Int public func instanceMethod() -> Element { return instanceProperty } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE14instanceMethod1eS2i_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int public func instanceMethod(e: Element) -> Element { return e } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE14staticPropertySivgZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static var staticProperty: Element { return Array(x: ()).instanceProperty } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE12staticMethodSiyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static func staticMethod() -> Element { return staticProperty } // CHECK-LABEL: sil non_abi [serialized] [ossa] @$sSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int public static func staticMethod(e: Element? = (nil)) -> Element { return e! } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlEySiyt_tcig : $@convention(method) (@guaranteed Array<Int>) -> Int public subscript(i: ()) -> Element { return self[0] } // CHECK-LABEL: sil [ossa] @$sSa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Element) { x += 1 } increment(x: &instanceProperty) } } extension Dictionary where Key == Int { // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE1xSDySiq_Gyt_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> { public init(x: ()) { self.init() } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$sSD22constrained_extensionsSiRszrlE16instancePropertyq_vM : $@yield_once @convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> @yields @inout Value public var instanceProperty: Value { get { return self[0]! } set { self[0] = newValue } } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod() -> Value { return instanceProperty } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE14instanceMethod1vq_q__tF : $@convention(method) <Key, Value where Key == Int> (@in_guaranteed Value, @guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod(v: Value) -> Value { return v } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE12staticMethodSiyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static func staticMethod() -> Key { return staticProperty } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE14staticPropertySivgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static var staticProperty: Key { return 0 } // CHECK-LABEL: sil non_abi [serialized] [ossa] @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int> // CHECK-LABEL: sil non_abi [serialized] [ossa] @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value> // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in_guaranteed Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value public static func staticMethod(k: Key? = (nil), v: Value? = (nil)) -> Value { return v! } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsStaticMethod() -> Value { return staticMethod() } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsConstructor() -> Value { return Dictionary(x: ()).instanceMethod() } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlEyq_yt_tcig : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public subscript(i: ()) -> Value { return self[0]! } // CHECK-LABEL: sil [ossa] @$sSD22constrained_extensionsSiRszrlE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Value) { } increment(x: &instanceProperty) } } public class GenericClass<X, Y> {} extension GenericClass where Y == () { // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5valuexvM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout X public var value: X { get { while true {} } set {} } // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvs : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout () public var empty: Y { get { return () } set {} } // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tciM : $@yield_once @convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @yields @inout X public subscript(_: Y) -> X { get { while true {} } set {} } // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxcig : $@convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s22constrained_extensions12GenericClassCAAytRs_rlEyyxciM : $@yield_once @convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> @yields @inout () public subscript(_: X) -> Y { get { while true {} } set {} } } protocol VeryConstrained {} struct AnythingGoes<T> { // CHECK-LABEL: sil hidden [transparent] [ossa] @$s22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <T> () -> @out Optional<T> var meaningOfLife: T? = nil } extension AnythingGoes where T : VeryConstrained { // CHECK-LABEL: sil hidden [ossa] @$s22constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlE13fromExtensionACyxGyt_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> { // CHECK: [[RESULT:%.*]] = struct_element_addr {{%.*}} : $*AnythingGoes<T>, #AnythingGoes.meaningOfLife // CHECK: [[INIT:%.*]] = function_ref @$s22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: return init(fromExtension: ()) {} } extension Array where Element == Int { struct Nested { // CHECK-LABEL: sil hidden [transparent] [ossa] @$sSa22constrained_extensionsSiRszlE6NestedV1eSiSgvpfi : $@convention(thin) () -> Optional<Int> var e: Element? = nil // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tFfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> () mutating func hasDefault(e: Element? = (nil)) { self.e = e } } } extension Array where Element == AnyObject { class NestedClass { // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsyXlRszlE11NestedClassCfd : $@convention(method) (@guaranteed Array<AnyObject>.NestedClass) -> @owned Builtin.NativeObject // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsyXlRszlE11NestedClassCfD : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> () deinit { } // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$sSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_GycfC : $@convention(method) (@thick Array<AnyObject>.NestedClass.Type) -> @owned Array<AnyObject>.NestedClass // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_Gycfc : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> @owned Array<AnyObject>.NestedClass } class DerivedClass : NestedClass { // CHECK-LABEL: sil hidden [transparent] [ossa] @$sSa22constrained_extensionsyXlRszlE12DerivedClassC1eyXlSgvpfi : $@convention(thin) () -> @owned Optional<AnyObject> // CHECK-LABEL: sil hidden [ossa] @$sSa22constrained_extensionsyXlRszlE12DerivedClassCfE : $@convention(method) (@guaranteed Array<AnyObject>.DerivedClass) -> () var e: Element? = nil } enum NestedEnum { case hay case grain func makeHay() -> NestedEnum { return .hay } } } func referenceNestedTypes() { _ = Array<AnyObject>.NestedClass() _ = Array<AnyObject>.DerivedClass() } struct S<T> { struct X {} } // CHECK-LABEL: sil hidden [ossa] @$s22constrained_extensions1SVAASiRszlEyAC1XVySi_GSicir : $@yield_once @convention(method) (Int, S<Int>) -> @yields S<Int>.X extension S<Int> { subscript(index:Int) -> X { _read { fatalError() } } }
apache-2.0
fb8f0734e9d13ca79d49b9ca32f7bad9
52.623967
248
0.698906
3.829988
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/ProfileImageView.swift
2
2623
// // ProfileImageView.swift // edX // // Created by Michael Katz on 9/17/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit @IBDesignable class ProfileImageView: UIImageView { var borderWidth: CGFloat = 1.0 var borderColor: UIColor? private func setup() { var borderStyle = OEXStyles.sharedStyles().profileImageViewBorder(borderWidth) if borderColor != nil { borderStyle = BorderStyle(cornerRadius: borderStyle.cornerRadius, width: borderStyle.width, color: borderColor) } applyBorderStyle(borderStyle) backgroundColor = OEXStyles.sharedStyles().profileImageBorderColor() } convenience init() { self.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init (frame: CGRect) { super.init(frame: frame) let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "profilePhotoPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) setup() } override func layoutSubviews() { super.layoutSubviews() setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "profilePhotoPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } func blurimate() -> Removable { let blur = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: blur) let vib = UIVibrancyEffect(forBlurEffect: blur) let vibView = UIVisualEffectView(effect: vib) let spinner = SpinnerView(size: .Medium, color: .White) vibView.contentView.addSubview(spinner) spinner.snp_makeConstraints {make in make.center.equalTo(spinner.superview!) } spinner.startAnimating() insertSubview(blurView, atIndex: 0) blurView.contentView.addSubview(vibView) vibView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(vibView.superview!) } blurView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self) } return BlockRemovable() { UIView.animateWithDuration(0.4, animations: { spinner.stopAnimating() }) { _ in blurView.removeFromSuperview() } } } }
apache-2.0
1972ebce82f884bb73954eb13ea8dfc6
29.858824
128
0.624095
5.133072
false
false
false
false
peiei/PJPhototLibrary
JPhotoLibrary/Class/AlbumCollectionView.swift
1
10932
// // AlbumCollectionView.swift // JPhotoLibrary // // Created by AidenLance on 2017/2/6. // Copyright © 2017年 AidenLance. All rights reserved. // import Foundation import UIKit import Photos let bottomViewHeight:CGFloat = 44 class AlbumCollectionViewController : UIViewController { var assetCollectionArray: PHFetchResult<PHAsset>! let collectionCellID = "collectionCellID" var albumCollectionView: AlbumCollectionView! var bottomBar: BottomBarView? let assetManager: AssetManager = AssetManager() var lastPreheatRect = CGRect.zero override func viewDidLoad() { super.viewDidLoad() SelectImageCenter.shareManager.initData(collectionCout: (assetCollectionArray.count)) let rightBarItem = UIBarButtonItem.init(title: "取消", style: .plain, target: self, action: #selector(dismissNavVC)) self.navigationItem.rightBarButtonItem = rightBarItem albumCollectionView = AlbumCollectionView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: self.view.bounds.width, height: self.view.bounds.height - bottomViewHeight))) albumCollectionView?.register(AlbumCollectionViewCell.self, forCellWithReuseIdentifier: collectionCellID) albumCollectionView?.delegate = self albumCollectionView?.dataSource = self bottomBar = BottomBarView.init(frame: CGRect.init(origin: CGPoint.init(x: 0, y: self.view.bounds.height - bottomViewHeight), size: CGSize.init(width: ConstantValue.screenWidth, height: bottomViewHeight))) self.view.addSubview(albumCollectionView!) self.view.addSubview(bottomBar!) NotificationCenter.default.addObserver(self, selector: #selector(reloadCellSelectStatusAction(notify:)), name: .UpdateAlbumThumbnailCellData, object: nil) } func dismissNavVC() { self.navigationController?.dismiss(animated: true, completion: nil) } func reloadCellSelectStatusAction (notify: NSNotification) { albumCollectionView?.reloadItems(at: [NSIndexPath.init(row: notify.object as! Int, section: 0) as IndexPath]) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard assetCollectionArray.count > 0 else { return } albumCollectionView?.scrollToItem(at: NSIndexPath.init(row: (assetCollectionArray?.count)! - 1, section: 0) as IndexPath, at: .bottom, animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateCachingAsset() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) assetManager.stopCachingImage() } deinit { SelectImageCenter.shareManager.cleanData() NotificationCenter.default.removeObserver(self, name: .UpdateAlbumThumbnailCellData, object: nil) NotificationCenter.default.removeObserver(self, name: .UpdateSelectNum, object: nil) } } class BottomBarView : UIView { var sendBt: UIButton! var sendNum: UILabel! let sendBtHeight: CGFloat = 30 let sendBtWidth: CGFloat = 40 override init(frame: CGRect) { sendBt = UIButton.init(frame: CGRect.init(x: frame.width - sendBtWidth - 10, y: 7, width: sendBtWidth, height: sendBtHeight)) sendBt.setTitle("发送", for: .normal) super.init(frame: frame) sendBt.setTitleColor(UIColor.btTitleSelectColor, for: .normal) sendBt.setTitleColor(UIColor.btTitleDisableColor, for: .disabled) sendBt.addTarget(self, action: #selector(sendAction(sender:)), for: .touchUpInside) sendBt.isEnabled = false sendNum = UILabel.init(frame: CGRect.init(x: frame.width - sendBtWidth - 10 - 3 - 60, y: 8, width: 60, height: sendBtHeight - 5)) sendNum.textAlignment = .right sendNum.textColor = UIColor.btTitleSelectColor sendNum.font = UIFont.systemFont(ofSize: 14) NotificationCenter.default.addObserver(self, selector: #selector(updateSendNumAction(notify:)), name: .UpdateSelectNum, object: nil) self.backgroundColor = .white self.addSubview(sendBt) self.addSubview(sendNum) } @objc fileprivate func updateSendNumAction(notify: NSNotification) { if notify.object as! Int == 0 { self.sendBt.isEnabled = false } else { self.sendBt.isEnabled = true } self.sendNum.text = String.init(format: "%@", notify.object as! Int == 0 ? "" : "(" + (notify.object as! Int).description + ")") } func sendAction(sender: UIButton) { PJPhotoAlbum.default.selectItems = SelectImageCenter.shareManager.selectArray ShareNavigationController.shareNav.nav.dismiss(animated: true, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } let preheatCount = 2*4 extension AlbumCollectionViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let albumBrowser = BrowserCollectionVC.init() albumBrowser.assetCollectionArray = assetCollectionArray albumBrowser.selectItemIndex = indexPath.row self.navigationController?.pushViewController(albumBrowser, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { updateCachingAsset() } func updateCachingAsset () { let visibleRect = CGRect.init(origin: albumCollectionView.contentOffset, size: albumCollectionView.bounds.size) let visibleItems = getItems(for: visibleRect) let prheatRect = visibleRect.insetBy(dx: 0, dy: -0.5 * visibleRect.height) let preheatItems = getItems(for: prheatRect) let lastPreheat = getItems(for: lastPreheatRect) let visibleSet = Set(visibleItems!) let preheatSet = Set(preheatItems!) let lastPreheatSet = Set(lastPreheat!) let new = Array(preheatSet.subtracting(lastPreheatSet)) let old = Array(lastPreheatSet.subtracting(visibleSet).subtracting(lastPreheatSet.subtracting(preheatSet))) guard new.min() != lastPreheatSet.min() else { return } let newAsset = new.flatMap { temp in assetCollectionArray[temp] } let oldAsset = old.flatMap { temp in assetCollectionArray[temp] } assetManager.stopCachingThumbnail(for: oldAsset) assetManager.startLoadThumbnail(for: newAsset) lastPreheatRect = prheatRect } func getItems(for rect: CGRect) -> [Int]?{ let layoutAttributes = albumCollectionView.collectionViewLayout.layoutAttributesForElements(in: rect) return layoutAttributes?.map { $0.indexPath.row } } } extension AlbumCollectionViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assetCollectionArray?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellID, for: indexPath) let albumThumbnailCell = cell as! AlbumCollectionViewCell albumThumbnailCell.cellImageAsset = assetCollectionArray?[indexPath.row] albumThumbnailCell.cellIndex = indexPath.row albumThumbnailCell.selectBt.isSelected = SelectImageCenter.shareManager.collectionArray[indexPath.row] assetManager.getImage(for: (assetCollectionArray?[indexPath.row])!) { image in if image != nil { albumThumbnailCell.contentImage = image } } return cell } } class AlbumCollectionView : UICollectionView { convenience init(frame: CGRect) { let layout = UICollectionViewFlowLayout.init() layout.itemSize = thumbnailSize layout.estimatedItemSize = thumbnailSize layout.scrollDirection = .vertical layout.minimumLineSpacing = 2 layout.minimumInteritemSpacing = 0 self.init(frame: frame, collectionViewLayout: layout) self.backgroundColor = UIColor.white } } class AlbumCollectionViewCell : UICollectionViewCell { let contentImageView: UIImageView let selectBt: UIButton var cellIndex: Int? var cellImageAsset: PHAsset? var contentImage: UIImage? { set { self.contentImageView.image = newValue } get { return self.contentImageView.image } } override init(frame: CGRect) { contentImageView = UIImageView.init() contentImageView.contentMode = .scaleAspectFill contentImageView.clipsToBounds = true contentImageView.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = NSLayoutConstraint.init(item: contentImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: thumbnailSize.width) let heightConstraint = NSLayoutConstraint.init(item: contentImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: thumbnailSize.height) contentImageView.addConstraints([widthConstraint, heightConstraint]) selectBt = UIButton.init(frame: CGRect.init(origin: CGPoint.init(x: frame.width - 2 - 23, y: 2), size: CGSize.init(width: 23, height: 23))) selectBt.setImage(UIImage.init(named: "unSelect"), for: .normal) selectBt.setImage(UIImage.init(named: "select"), for: .selected) super.init(frame: frame) self.contentView.addSubview(contentImageView) self.contentView.backgroundColor = UIColor.white self.contentView.addSubview(selectBt) selectBt.addTarget(self, action: #selector(cellSelectAction(sender:)), for: .touchUpInside) } func cellSelectAction(sender: UIButton) { if sender.isSelected { sender.isSelected = false guard cellIndex != nil, cellImageAsset != nil else { fatalError("cellIndex or cellImageAsset is nil") } SelectImageCenter.shareManager.removeSelectImage(index: cellIndex!, imageAsset: cellImageAsset!) } else { sender.isSelected = true SelectImageCenter.shareManager.addSelectImage(index: cellIndex!, imageAsset: cellImageAsset!) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
985ec80bfcb7635fa94d06f6b397f3e4
36.920139
212
0.679791
5.12723
false
false
false
false
avaidyam/Parrot
MochaUI/LayerButton.swift
1
8729
import Cocoa import QuartzCore /* TODO: Track NSButton.Type values and fix LayerButton.State. */ /* TODO: Animate title<->alternateTitle changes. */ /* TODO: Respect {alternate}attributedTitle and isSpringLoaded. */ /* TODO: Track momentary, State.mixed, and NSImageScaling/Position. */ /* TODO: Support non-Template images (basically remove the mask layer). */ /* TODO: Support focus rings. */ /* TODO: Add scale transformation on selection. */ public class LayerButton: NSButton, CALayerDelegate { // pressed, pulsed, deeplyPressed, inactive, active, disabled, drag, rollover /* public struct State: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let none = State(rawValue: 0 << 0) public static let hover = State(rawValue: 1 << 0) public static let highlighted = State(rawValue: 0 << 1) public static let selected = State(rawValue: 1 << 1) public static let disabled = State(rawValue: 1 << 1) // ??? public static let main = State(rawValue: 0 << 2) public static let key = State(rawValue: 1 << 2) public static let aqua = State(rawValue: 0 << 3) public static let graphite = State(rawValue: 1 << 3) public static let vibrant = State(rawValue: 1 << 4) public static let highContrast = State(rawValue: 1 << 5) } */ public struct Properties { private static var activeShadow: NSShadow = { let s = NSShadow() // default shadowColor = black + 0.33 alpha s.shadowOffset = NSSize(width: 0, height: 5) s.shadowBlurRadius = 10 return s }() public var cornerRadius: CGFloat public var borderWidth: CGFloat public var borderColor: NSColor public var shadow: NSShadow? public var bezelColor: NSColor public var rimOpacity: Float public var iconColor: NSColor public var textColor: NSColor public var duration: TimeInterval public init(cornerRadius: CGFloat = 0.0, borderWidth: CGFloat = 0.0, borderColor: NSColor = .clear, shadow: NSShadow? = nil, bezelColor: NSColor = .clear, rimOpacity: Float = 0.0, iconColor: NSColor = .clear, textColor: NSColor = .clear, duration: TimeInterval = 0.0) { self.cornerRadius = cornerRadius self.borderWidth = borderWidth self.borderColor = borderColor self.shadow = shadow self.bezelColor = bezelColor self.rimOpacity = rimOpacity self.iconColor = iconColor self.textColor = textColor self.duration = duration } public static let inactive = Properties(cornerRadius: 4.0, bezelColor: .white, rimOpacity: 0.25, iconColor: .darkGray, textColor: .darkGray, duration: 0.5) public static let active = Properties(cornerRadius: 4.0, bezelColor: .darkGray, rimOpacity: 0.25, iconColor: .white, textColor: .white, duration: 0.1) } private var containerLayer = CALayer() private var titleLayer = CATextLayer() private var iconLayer = CALayer() private var rimLayer = CALayer() public private(set) var isHovered = false { didSet { self.needsDisplay = true } } public var activeOnHighlight = true { didSet { self.needsDisplay = true } } public var inactiveProperties: Properties = .inactive { didSet { self.needsDisplay = true } } public var activeProperties: Properties = .active { didSet { self.needsDisplay = true } } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } public override init(frame: NSRect) { super.init(frame: frame) setup() } private func setup() { self.wantsLayer = true self.layerContentsRedrawPolicy = .onSetNeedsDisplay self.layer?.masksToBounds = false self.containerLayer.masksToBounds = false self.titleLayer.masksToBounds = false self.iconLayer.masksToBounds = true self.rimLayer.masksToBounds = false self.iconLayer.mask = CALayer() self.iconLayer.mask?.contentsGravity = kCAGravityResizeAspect self.titleLayer.alignmentMode = kCAAlignmentCenter self.rimLayer.borderColor = .black self.rimLayer.borderWidth = 0.5 self.layer?.addSublayer(self.containerLayer) self.containerLayer.addSublayer(self.iconLayer) self.containerLayer.addSublayer(self.titleLayer) self.layer?.addSublayer(self.rimLayer) let trackingArea = NSTrackingArea(rect: bounds, options: [.activeAlways, .inVisibleRect, .mouseEnteredAndExited], owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } override open func layout() { super.layout() self.subviews.forEach { $0.removeFromSuperview() } // remove NSButtonCell's views let imageRect = (self.cell?.value(forKey: "_imageView") as? NSView)?.frame ?? .zero var titleRect = (self.cell?.value(forKey: "_titleTextField") as? NSView)?.frame ?? .zero titleRect.origin.y += 1 // CATextLayer baseline is +1.5px compared to NSTextLayer. let props = (self.isHighlighted) ? self.activeProperties : self.inactiveProperties let initState = self.containerLayer.frame == .zero // we just initialized if !initState { NSAnimationContext.beginGrouping() NSAnimationContext.current.allowsImplicitAnimation = true NSAnimationContext.current.duration = props.duration } self.containerLayer.frame = self.layer?.bounds ?? .zero self.iconLayer.frame = imageRect self.iconLayer.mask?.frame = self.iconLayer.bounds self.titleLayer.frame = titleRect self.rimLayer.frame = self.layer?.bounds.insetBy(dx: -0.5, dy: -0.5) ?? .zero if !initState { NSAnimationContext.endGrouping() } } public override var allowsVibrancy: Bool { return false } public override var wantsUpdateLayer: Bool { return true } public override func updateLayer() { self.containerLayer.contents = nil // somehow this gets set by NSButtonCell? let props = (self.isHighlighted) ? self.activeProperties : self.inactiveProperties NSAnimationContext.beginGrouping() NSAnimationContext.current.allowsImplicitAnimation = true NSAnimationContext.current.duration = props.duration self.titleLayer.font = self.font self.titleLayer.fontSize = self.font?.pointSize ?? 0.0 self.titleLayer.string = self.isHighlighted && self.alternateTitle != "" ? self.alternateTitle : self.title self.iconLayer.mask?.contents = self.isHighlighted && self.alternateImage != nil ? self.alternateImage : self.image self.layer?.cornerRadius = props.cornerRadius self.layer?.borderWidth = props.borderWidth self.layer?.borderColor = props.borderColor.cgColor self.layer?.backgroundColor = props.bezelColor.cgColor self.rimLayer.opacity = props.rimOpacity self.rimLayer.cornerRadius = props.cornerRadius self.shadow = props.shadow self.iconLayer.backgroundColor = props.iconColor.cgColor self.titleLayer.foregroundColor = props.textColor.cgColor NSAnimationContext.endGrouping() } public override func mouseEntered(with event: NSEvent) { self.isHovered = true } public override func mouseExited(with event: NSEvent) { self.isHovered = false } public override var focusRingMaskBounds: NSRect { return self.bounds } public override func drawFocusRingMask() { let props = (self.isHighlighted) ? self.activeProperties : self.inactiveProperties let path = NSBezierPath(roundedRect: self.bounds, xRadius: props.cornerRadius, yRadius: props.cornerRadius) path.fill() } public override func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties() guard let scale = self.window?.backingScaleFactor else { return } self.layer?.contentsScale = scale self.containerLayer.contentsScale = scale self.titleLayer.contentsScale = scale self.iconLayer.contentsScale = scale } }
mpl-2.0
4fc3934b5c6931a2a393459eb7362ea5
40.76555
149
0.63627
4.945609
false
false
false
false
darrarski/DRRxObservableArray
DRRxObservableArrayTests/ObservableArraySpec.swift
1
11441
import Quick import Nimble import RxSwift import RxTest class ObservableArraySpec: QuickSpec { override func spec() { describe("ObservableArray of Strings") { var sut: ObservableArray<String>! context("when initialized with array") { beforeEach { sut = ObservableArray(["a", "b", "c"]) } afterEach { sut = nil } it("should have correct elements") { expect(sut.elements).to(equal(["a", "b", "c"])) } it("should have correct count") { expect(sut.count).to(equal(3)) } context("when element appended") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut.append("d") } afterEach { observer = nil } it("should have correct elements") { expect(sut.elements).to(equal(["a", "b", "c", "d"])) } it("should have correct count") { expect(sut.count).to(equal(4)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.inserted(indices: [3], elements: ["d"])) ] expect(observer.events).to(equal(expected)) } } context("when element prepended") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut.prepend("d") } afterEach { observer = nil } it("should have correct elements") { expect(sut.elements).to(equal(["d", "a", "b", "c"])) } it("should have correct count") { expect(sut.count).to(equal(4)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.inserted(indices: [0], elements: ["d"])) ] expect(observer.events).to(equal(expected)) } } context("when elements appended") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut.append(contentsOf: ["d", "e"]) } afterEach { observer = nil } it("should have correct elements") { expect(sut.elements).to(equal(["a", "b", "c", "d", "e"])) } it("should have correct count") { expect(sut.count).to(equal(5)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.inserted(indices: [3, 4], elements: ["d", "e"])) ] expect(observer.events).to(equal(expected)) } } context("when element inserted at index") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut.insert("d", at: 1) } afterEach { observer = nil } it("should have correct elements") { expect(sut.elements).to(equal(["a", "d", "b", "c"])) } it("should have correct count") { expect(sut.count).to(equal(4)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.inserted(indices: [1], elements: ["d"])) ] expect(observer.events).to(equal(expected)) } } context("when first element removed") { var removedElement: String! var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) removedElement = sut.removeFirst() } afterEach { removedElement = nil observer = nil } it("should remove correct element") { expect(removedElement).to(equal("a")) } it("should have correct elements") { expect(sut.elements).to(equal(["b", "c"])) } it("should have correct count") { expect(sut.count).to(equal(2)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.deleted(indices: [0], elements: ["a"])) ] expect(observer.events).to(equal(expected)) } } context("when last element removed") { var removedElement: String! var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) removedElement = sut.removeLast() } afterEach { removedElement = nil observer = nil } it("should remove correct element") { expect(removedElement).to(equal("c")) } it("should have correct elements") { expect(sut.elements).to(equal(["a", "b"])) } it("should have correct count") { expect(sut.count).to(equal(2)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.deleted(indices: [2], elements: ["c"])) ] expect(observer.events).to(equal(expected)) } } context("when element removed at index") { var removedElement: String! var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) removedElement = sut.remove(at: 1) } afterEach { removedElement = nil observer = nil } it("should remove correct element") { expect(removedElement).to(equal("b")) } it("should have correct elements") { expect(sut.elements).to(equal(["a", "c"])) } it("should have correct count") { expect(sut.count).to(equal(2)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.deleted(indices: [1], elements: ["b"])) ] expect(observer.events).to(equal(expected)) } } context("when all elements removed") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut.removeAll() } afterEach { observer = nil } it("should have no elements") { expect(sut.elements).to(equal([])) } it("should have correct count") { expect(sut.count).to(equal(0)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.deleted(indices: [0, 1, 2], elements: ["a", "b", "c"])) ] expect(observer.events).to(equal(expected)) } } context("when get-subscripted") { var element: String! beforeEach { element = sut[1] } it("should return correct element") { expect(element).to(equal("b")) } } context("when element replaced using subscript") { var observer: TestableObserver<ObservableArrayChangeEvent<String>>! beforeEach { observer = self.createObserver(forSut: sut) sut[1] = "d" } it("should have correct elements") { expect(sut.elements).to(equal(["a", "d", "c"])) } it("should have correct count") { expect(sut.count).to(equal(3)) } it("should notify observers") { let expected = [ next(0, ObservableArrayChangeEvent<String>.updated(indices: [1], oldElements: ["b"], newElements: ["d"])) ] expect(observer.events).to(equal(expected)) } } } } } private func createObserver(forSut sut: ObservableArray<String>) -> TestableObserver<ObservableArrayChangeEvent<String>> { let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(ObservableArrayChangeEvent<String>.self) let _ = sut.events.subscribe(observer) scheduler.start() return observer } }
mit
0dcf4844c4805a484f4a1d52d5b87bac
34.977987
133
0.403024
6.349057
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/E_191_NumberOf1Bits.swift
1
2802
// // E_191_NumberOf1Bits.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/9. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/number-of-1-bits import Foundation // MARK: - 题目名称: 191. Number of 1 Bits /* MARK: - 所属类别: 标签: Bit Manipulation 相关题目: (E) Reverse Bits (E) Power of Two (M) Counting Bits (E) Binary Watch (E) Hamming Distance */ /* MARK: - 题目英文: Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. */ /* MARK: - 题目翻译: 编写一个函数,它接收一个无符号整数并返回它二进制形式中 '1'的个数(也称为Hamming weight)。 例如,整数 ‘11’ 的32位二进制表示形式为 00000000000000000000000000001011 ,所以函数应当返回3。 */ /* MARK: - 解题思路: 考虑位运算 设输入的数为n,把n与1做二进制的与&(AND)运算,即可判断它的最低位是否为1。 如果是的话,把计数变量加一。然后把n向右移动一位,重复上述操作。 当n变为0时,终止算法,输出结果。 */ /* MARK: - 复杂度分析: 时间复杂度:O(n) 空间复杂度:O(1) */ // MARK: - 代码: private class Solution { // 取模 整除 func hammingWeight(_ n: UInt32) -> Int { // 传进来n为let类型 不能改变,所以搞个num变量 var num = n // 计数器 var count = 0 while num > 0 { // 把num与1做二进制的与(AND)运算,即可判断它的最低位是否为1 if num & 1 == 1 { count += 1 } // 右移一位 相当于 / 2 public func >>=(lhs: inout UInt32, rhs: UInt32) num >>= 1 } return count; } // 取模 整除 func hammingWeight2(_ n: UInt32) -> Int { // 传进来n为let类型 不能改变,所以搞个num变量 var num = n // 计数器 var count = 0 while num > 0 { count += 1 // x & (x - 1) 它会把整数x的二进制的最后一个1去掉。 num &= (num - 1) } return count; } } // MARK: - 测试代码: func numberOf1Bits() { print(Solution().hammingWeight(0)) print(Solution().hammingWeight(1)) print(Solution().hammingWeight(2)) print(Solution().hammingWeight(8)) print(Solution().hammingWeight(11)) print(Solution().hammingWeight(7)) }
mit
fccaa0b23181aaa269a1c20e9eb3b0fa
16.65873
130
0.554607
3.098886
false
false
false
false
CharlesVu/Smart-iPad
Persistance/Persistance/RealmModels/TFL/RealmTFLMode.swift
1
749
// // TFLMode.swift // Persistance // // Created by Charles Vu on 06/06/2019. // Copyright © 2019 Charles Vu. All rights reserved. // import Foundation import RealmSwift @objcMembers public class RealmTFLMode: Object { public dynamic var name: String! = "" public dynamic var lines: List<RealmTFLLine> = List() override public static func primaryKey() -> String? { return "name" } convenience init(name: String, lines: List<RealmTFLLine>) { self.init() self.name = name self.lines = lines } convenience init(mode: TFLMode) { self.init() self.name = mode.name lines.append(objectsIn: mode.lines.map { RealmTFLLine(line: $0) }) } }
mit
f325906d0fdc897b26e0d6e36777b326
22.375
74
0.612299
3.875648
false
false
false
false
github410117/XHNetworkingTool
XHMoyaNetworkTool/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift
14
3877
// // RxTableViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif let tableViewDataSourceNotSet = TableViewDataSourceNotSet() final class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { rxAbstractMethod(message: dataSourceNotSet) } } /// For more information take a look at `DelegateProxyType`. public class RxTableViewDataSourceProxy : DelegateProxy , UITableViewDataSource , DelegateProxyType { /// Typed parent object. public weak fileprivate(set) var tableView: UITableView? fileprivate weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet /// Initializes `RxTableViewDataSourceProxy` /// /// - parameter parentObject: Parent object for delegate proxy. public required init(parentObject: AnyObject) { self.tableView = castOrFatalError(parentObject) super.init(parentObject: parentObject) } // MARK: delegate /// Required delegate method implementation. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) } /// Required delegate method implementation. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAt: indexPath) } // MARK: proxy /// For more information take a look at `DelegateProxyType`. public override class func createProxyForObject(_ object: AnyObject) -> AnyObject { let tableView: UITableView = castOrFatalError(object) return tableView.createRxDataSourceProxy() } /// For more information take a look at `DelegateProxyType`. public override class func delegateAssociatedObjectTag() -> UnsafeRawPointer { return dataSourceAssociatedTag } /// For more information take a look at `DelegateProxyType`. public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { let tableView: UITableView = castOrFatalError(object) tableView.dataSource = castOptionalOrFatalError(delegate) } /// For more information take a look at `DelegateProxyType`. public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? { let tableView: UITableView = castOrFatalError(object) return tableView.dataSource } /// For more information take a look at `DelegateProxyType`. public override func setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UITableViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? tableViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) refreshTableViewDataSource() } // https://github.com/ReactiveX/RxSwift/issues/907 private func refreshTableViewDataSource() { if self.tableView?.dataSource === self { if _requiredMethodsDataSource != nil && _requiredMethodsDataSource !== tableViewDataSourceNotSet { self.tableView?.dataSource = self } else { self.tableView?.dataSource = nil } } } } #endif
mit
382c41945c3f8e607b943a50dacede25
34.888889
125
0.714138
5.944785
false
false
false
false
sergdort/CleanArchitectureRxSwift
RealmPlatform/Utility/Extensions/Realm+Ext.swift
1
1619
import Foundation import Realm import RealmSwift import RxSwift extension Object { static func build<O: Object>(_ builder: (O) -> () ) -> O { let object = O() builder(object) return object } } extension RealmSwift.SortDescriptor { init(sortDescriptor: NSSortDescriptor) { self.init(keyPath: sortDescriptor.key ?? "", ascending: sortDescriptor.ascending) } } extension Realm: ReactiveCompatible {} extension Reactive where Base == Realm { func save<R: RealmRepresentable>(entity: R, update: Bool = true) -> Observable<Void> where R.RealmType: Object { return Observable.create { observer in do { try self.base.write { self.base.add(entity.asRealm(), update: update ? .all : .error) } observer.onNext(()) observer.onCompleted() } catch { observer.onError(error) } return Disposables.create() } } func delete<R: RealmRepresentable>(entity: R) -> Observable<Void> where R.RealmType: Object { return Observable.create { observer in do { guard let object = self.base.object(ofType: R.RealmType.self, forPrimaryKey: entity.uid) else { fatalError() } try self.base.write { self.base.delete(object) } observer.onNext(()) observer.onCompleted() } catch { observer.onError(error) } return Disposables.create() } } }
mit
09adcbd040a2416fa6f3b6c67ca34698
29.54717
126
0.55281
4.847305
false
false
false
false
chashmeetsingh/Youtube-iOS
YouTube Demo/ApiService.swift
1
1724
// // ApiService.swift // YouTube Demo // // Created by Chashmeet Singh on 11/01/17. // Copyright © 2017 Chashmeet Singh. All rights reserved. // import UIKit class ApiService: NSObject { static let sharedInstance = ApiService() let baseUrl = "https://s3-us-west-2.amazonaws.com/youtubeassets" func fetchVideos(completion: @escaping ([Video]) -> Void) { fetchVideosForUrl(url: "\(baseUrl)/home_num_likes.json", completion: completion) } func fetchTrendingFeed(completion: @escaping ([Video]) -> Void) { fetchVideosForUrl(url: "\(baseUrl)/trending.json", completion: completion) } func fetchSubscriptionFeed(completion: @escaping ([Video]) -> Void) { fetchVideosForUrl(url: "\(baseUrl)/subscriptions.json", completion: completion) } func fetchVideosForUrl(url: String, completion: @escaping ([Video]) -> Void) { let url = URL(string: url) URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in if let error = error { print(error) return } do { if let data = data, let jsonDictionaries = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String : AnyObject]] { DispatchQueue.main.async { completion(jsonDictionaries.map({return Video(dictionary: $0)})) } } } catch let jsonError { print(jsonError) } }).resume() } }
mit
fb899747bf15060aee4de8e347d01082
30.327273
145
0.54614
4.839888
false
false
false
false
maxgoedjen/M3U8
M3U8/PlaylistItem.swift
1
1689
// // PlaylistItem.swift // M3U8 // // Created by Max Goedjen on 8/12/15. // Copyright © 2015 Max Goedjen. All rights reserved. // import Foundation public struct PlaylistItem: Item { public let uri: String public let iframe: Bool public let bandwidth: Int public let programID: String? public let width: Int? public let height: Int? public let codecs: [String] public let audioCodec: String? public let averageBandwidth: Int? public let level: Double? public let profile: String? public let video: String? public let audio: String? public let subtitles: String? public let closedCaptions: String? public init(uri: String, iframe: Bool, bandwidth: Int, programID: String? = nil, width: Int? = nil, height: Int? = nil, codecs: [String] = [], audioCodec: String? = nil, averageBandwidth: Int? = nil, level: Double? = nil, profile: String? = nil, video: String? = nil, audio: String? = nil, subtitles: String? = nil, closedCaptions: String? = nil) { self.uri = uri self.iframe = iframe self.bandwidth = bandwidth self.programID = programID self.width = width self.height = height self.codecs = codecs self.audioCodec = audioCodec self.averageBandwidth = averageBandwidth self.level = level self.profile = profile self.video = video self.audio = audio self.subtitles = subtitles self.closedCaptions = closedCaptions } public init?(string: String) { return nil } } extension PlaylistItem { public var description: String { return "" } }
mit
a62b0bdbb98df2dc8406296dba389370
27.627119
352
0.630924
4.127139
false
false
false
false
Ryanair/RYRCalendar
RYRCalendar/Classes/RYRCalendar.swift
1
13622
// // RYRCalendar.swift // RYRCalendar // // Created by Miquel, Aram on 01/06/2016. // Copyright © 2016 Ryanair. All rights reserved. // import UIKit public protocol RYRCalendarDelegate: class { func calendarDidSelectDate(calendar: RYRCalendar, selectedDate: NSDate) func calendarDidSelectMultipleDate(calendar: RYRCalendar, selectedStartDate startDate: NSDate, endDate: NSDate) func isDateAvailableToSelect(date: NSDate) -> Bool func calendarDidScrollToMonth(calendar: RYRCalendar, monthDate: NSDate) } extension RYRCalendarDelegate { func isDateAvailableToSelect(date: NSDate) -> Bool { return true } } public enum RYRCalendarSelectionType: Int { case None, Single, Multiple } public class RYRCalendar: UIView { // PUBLIC (API) public var style: RYRCalendarStyle = RYRCalendarStyle() { didSet { update() } } public weak var delegate: RYRCalendarDelegate? public var selectionType: RYRCalendarSelectionType = .None public var totalMonthsFromNow: Int = 1 // Date configuration public var baseDate: NSDate = NSDate() // PRIVATE private var singleSelectionIndexPath: NSIndexPath? private var multipleSelectionIndexPaths = [NSIndexPath]() private var headerView: RYRCalendarHeaderView! private var collectionView: UICollectionView! private var collectionViewLayout: UICollectionViewFlowLayout! private var cellSize: CGFloat { get { return CGFloat(Int(frame.size.width / 7)) } } // MARK: Initializers init() { super.init(frame: CGRectZero) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public func didMoveToSuperview() { self.collectionView.frame = superview!.frame } // MARK: Public public func update() { headerView.style = style.calendarHeaderStyle collectionView.reloadData() } // MARK: Private private func setup() { headerView = RYRCalendarHeaderView() headerView.style = style.calendarHeaderStyle addSubview(headerView) if #available(iOS 9.0, *) { collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.sectionHeadersPinToVisibleBounds = true } else { collectionViewLayout = RYRCalendarFlowLayout() } collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0); collectionView = UICollectionView(frame: frame, collectionViewLayout: collectionViewLayout) addSubview(collectionView) headerView.translatesAutoresizingMaskIntoConstraints = false collectionView.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: [], metrics: nil, views: ["collectionView": collectionView])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[headerView]-0-|", options: [], metrics: nil, views: ["headerView": headerView])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[headerView(30)][collectionView]-0-|", options: [], metrics: nil, views: ["collectionView": collectionView, "headerView": headerView])) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.clearColor() collectionView.registerClass(RYRDayCell.self, forCellWithReuseIdentifier: RYRDayCell.cellIndentifier) collectionView.registerClass(RYREmptyDayCell.self, forCellWithReuseIdentifier: RYREmptyDayCell.cellIndentifier) collectionView.registerClass(RYRMonthHeaderReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: RYRMonthHeaderReusableView.identifier) update() } internal func getBlankSpaces(fromDate: NSDate?) -> Int { if let firstDayOfMonth = fromDate?.setToFirstDayOfMonth() { let components = NSCalendar.currentCalendar().components([.Weekday], fromDate: firstDayOfMonth) let blankSpaces = components.weekday - 2 // this '2' is because components.Weekday starts on Saturday, and starts with 1 (not 0) return blankSpaces } return 0 } private func selectSingleIndexPath(indexPath: NSIndexPath) { if let previousSelectedIndexPath = singleSelectionIndexPath { unselectIndexPath(previousSelectedIndexPath) } if let date = dateFromIndexPath(indexPath) { if delegate?.isDateAvailableToSelect(date) ?? false { singleSelectionIndexPath = indexPath collectionView.reloadItemsAtIndexPaths([indexPath]) delegate?.calendarDidSelectDate(self, selectedDate: date) } } } private func selectMultipleIndexPath(indexPath: NSIndexPath) { guard let newDateSelection = dateFromIndexPath(indexPath) else { print("Error converting indexPath from selected date"); return } if let firstSelectedIndex = multipleSelectionIndexPaths.first, let firstDateSelection = dateFromIndexPath(firstSelectedIndex) { if multipleSelectionIndexPaths.count > 1 { // Contains two previously selected dates // We empty the selection, and select the newDate multipleSelectionIndexPaths = [] multipleSelectionIndexPaths.append(indexPath) if let date = dateFromIndexPath(indexPath) { delegate?.calendarDidSelectDate(self, selectedDate: date) } } else { // Contains one previously selected date let order = firstDateSelection.compare(newDateSelection) switch order { case .OrderedAscending: // If the firstDateSelection is before the newDateSelection, newDateSelection will become the second selected date multipleSelectionIndexPaths.append(indexPath) case .OrderedDescending: // If the firstDateSelection is after the newDateSelection, multipleSelectionIndexPaths will be emptied and then newDateSelection added multipleSelectionIndexPaths = [] multipleSelectionIndexPaths.append(indexPath) if let date = dateFromIndexPath(indexPath) { delegate?.calendarDidSelectDate(self, selectedDate: date) } case .OrderedSame: // If the firstDateSelection is same as newDateSelection, multipleSelectionIndexPaths will be emptied multipleSelectionIndexPaths.append(indexPath) } if multipleSelectionIndexPaths.count > 1 { if let startDate = dateFromIndexPath(multipleSelectionIndexPaths.first), endDate = dateFromIndexPath(multipleSelectionIndexPaths.last) { delegate?.calendarDidSelectMultipleDate(self, selectedStartDate: startDate, endDate: endDate) } } } } else { // Does not contain any date multipleSelectionIndexPaths.append(indexPath) if let date = dateFromIndexPath(indexPath) { delegate?.calendarDidSelectDate(self, selectedDate: date) } } collectionView.reloadItemsAtIndexPaths(collectionView.indexPathsForVisibleItems()) } private func unselectIndexPath(indexPath: NSIndexPath) { singleSelectionIndexPath = nil collectionView.reloadItemsAtIndexPaths([indexPath]) } private func dateFromIndexPath(indexPath: NSIndexPath?) -> NSDate? { guard let indexPath = indexPath else { return nil } let monthDate = baseDate.dateByAddingMonths(indexPath.section)?.setToFirstDayOfMonth() let blankSpaces = getBlankSpaces(monthDate) return monthDate?.dateByAddingDays(indexPath.row - blankSpaces) } } // MARK: CollectionView DataSource extension RYRCalendar: UICollectionViewDataSource { public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let dateForSection = baseDate.dateByAddingMonths(section) var numberOfItems = dateForSection?.numberOfDaysInCurrentMonth() ?? 0 numberOfItems += getBlankSpaces(dateForSection) ?? 0 return numberOfItems } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let dateForSection = baseDate.dateByAddingMonths(indexPath.section)?.setToFirstDayOfMonth() let blankSpaces = getBlankSpaces(dateForSection) if indexPath.row >= blankSpaces { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RYRDayCell.cellIndentifier, forIndexPath: indexPath) as! RYRDayCell cell.dayNumber = indexPath.row - blankSpaces + 1 if let rowDate = dateForSection?.dateByAddingDays(indexPath.row - blankSpaces) { if rowDate.isPastDay() { cell.style = style.cellStyleDisabled } else if indexPath == singleSelectionIndexPath { cell.style = style.cellStyleSelected } else if multipleSelectionIndexPaths.contains(indexPath) { if multipleSelectionIndexPaths.count > 1 && multipleSelectionIndexPaths.first == multipleSelectionIndexPaths.last { cell.style = style.cellStyleSelectedMultiple } else if multipleSelectionIndexPaths.first == indexPath { cell.style = style.cellStyleFirstSelected } else if multipleSelectionIndexPaths.last == indexPath { cell.style = style.cellStyleLastSelected } } else if rowDate.isBetweenDates(dateFromIndexPath(multipleSelectionIndexPaths.first), secondDate: dateFromIndexPath(multipleSelectionIndexPaths.last)) { cell.style = style.cellStyleMiddleSelected }else if rowDate.isToday() { cell.style = style.cellStyleToday } else if delegate?.isDateAvailableToSelect(rowDate) ?? true { cell.style = style.cellStyleEnabled } else { cell.style = style.cellStyleDisabled } } return cell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RYREmptyDayCell.cellIndentifier, forIndexPath: indexPath) as! RYREmptyDayCell return cell } } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return totalMonthsFromNow } } // MARK: CollectionView Delegate extension RYRCalendar: UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { switch selectionType { case .None: return case .Single: selectSingleIndexPath(indexPath) case .Multiple: selectMultipleIndexPath(indexPath) } } public func collectionView(collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, atIndexPath indexPath: NSIndexPath) { if let view = view as? RYRMonthHeaderReusableView { delegate?.calendarDidScrollToMonth(self, monthDate: view.date!) } } } // MARK: FlowLayout Delegate extension RYRCalendar: UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(cellSize, cellSize) } public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: RYRMonthHeaderReusableView.identifier, forIndexPath: indexPath) as! RYRMonthHeaderReusableView view.date = baseDate.setToFirstDayOfMonth()!.dateByAddingMonths(indexPath.section) view.style = style.monthHeaderStyle return view } return UICollectionReusableView() } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSizeMake(collectionView.frame.width, CGFloat(style.monthHeaderHeight)) } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let lateralSpacing = (frame.width - (cellSize * 7)) / 2 return UIEdgeInsets(top: 0, left: lateralSpacing, bottom: 0, right: lateralSpacing) } }
apache-2.0
ea14739a17f080bc3a485792a13cee7c
41.301242
210
0.698847
6.149436
false
false
false
false
adrfer/swift
test/Prototypes/GenericDispatch.swift
2
4597
//===--- GenericDispatch.swift - Demonstrate "partial specialization" -----===// // // 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 // //===----------------------------------------------------------------------===// // // Do stuff in Swift that we didn't think was possible. This file // will ensure that the capability doesn't regress and give us a // prototype to which we can refer when building the standard library. // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // CHECK: testing... print("testing...") //===----------------------------------------------------------------------===// //===--- Think of this code as being "in the library" ---------------------===// //===----------------------------------------------------------------------===// //===--- F "base" protocol (like ForwardIndexType) ------------------------===// protocol F { func successor() -> Self // This requirement allows generic distance() to find default // implementations. Only the author of F and the author of a // refinement of F having a non-default distance implementation need // to know about it. These refinements are expected to be rare // (which is why defaulted requirements are a win) func ~> (_: Self, _: (_Distance, (Self))) -> Int } // Operation tag for distance // // Operation tags allow us to use a single operator (~>) for // dispatching every generic function with a default implementation. // Only authors of specialized distance implementations need to touch // this tag. struct _Distance {} // This function cleans up the syntax of invocations func _distance<I>(other: I) -> (_Distance, (I)) { return (_Distance(), (other)) } // Default Implementation of distance for F's func ~> <I: F>(self_:I, _: (_Distance, (I))) -> Int { self_.successor() // Use an F-specific operation print("F") return 0 } //===--- Dispatching distance() function ----------------------------------===// // This generic function is for user consumption; it dispatches to the // appropriate implementation for T. func distance<T: F>(x: T, _ y: T) -> Int { return x~>_distance(y) } //===--- R refined protocol (like RandomAccessIndexType) ------------------===// protocol R : F { // Non-defaulted requirements of R go here, e.g. something to // measure the distance in O(1) static func sub(x: Self, y: Self) } // R has its own default implementation of distance, which is O(1). // Only the author of R needs to see this implementation. func ~> <I: R>(x: I, args: (_Distance, (I))) -> Int { let other = args.1 I.sub(other, y: x) print("R") return 1 } //===--- D refined protocol (like R, but with a custom distance) ----------===// // Users who want to provide a custom distance function will use this protocol protocol D : R { func distance(y: Self) -> Int } // Dispatch to D's distance() requirement // Only the author of D needs to see this implementation. func ~> <I: D>(x:I, args: (_Distance, (I))) -> Int { let other = args.1 return x.distance(other) } //===----------------------------------------------------------------------===// //===--- Think of this as being "user code" -------------------------------===// //===----------------------------------------------------------------------===// // This model of F automatically gets F's default implementation of distance struct SlowIndex : F { func successor() -> SlowIndex { return self } } // This model of R automatically gets R's default implementation of distance struct FastIndex : R { func successor() -> FastIndex { return self } static func sub(x: FastIndex, y: FastIndex) {} } struct X : D { // Customized distance implementation func distance(y: X) -> Int { print("X") return 3 } // Inherited requirements func successor() -> X { return self } static func sub(x: X, y: X) {} } // Here's a generic function that uses our dispatching distance func sort<T: F>(x: T) { // In here, we don't know whether T is an R or just a plain F, or // whether it has its own specialized implementation of distance(x, x) } // CHECK-NEXT: F sort(SlowIndex()) // CHECK-NEXT: R sort(FastIndex()) // CHECK-NEXT: X sort(X()) // CHECK-NEXT: done print("done.")
apache-2.0
240ab025f9be6e923f2369f5b9849b93
32.071942
80
0.581249
4.268338
false
false
false
false
JordanDoczy/Graph
Graph/CalculatorViewController.swift
1
3960
// // ViewController.swift // GraphingCalculator // // Created by Jordan Doczy on 11/3/15. // Copyright © 2015 Jordan Doczy. All rights reserved. // import UIKit class CalculatorViewController: UIViewController, GraphViewDataSource { @IBOutlet weak var display: UILabel! @IBOutlet weak var operationLabel: UILabel! fileprivate var isUserTyping = false fileprivate var model = CalculatorBrain() fileprivate var spacer:CGFloat = 10.0 override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var destination = segue.destination if let navController = destination as? UINavigationController { destination = navController.visibleViewController! } if let controller = destination as? GraphViewController { controller.title = model.description.components(separatedBy: ",").last controller.dataSource = self } } // (handles all digits and decimal point) @IBAction func appendDigit(_ sender: UIButton) { let digit = sender.currentTitle! if isUserTyping { if digit != "." || !display.text!.contains(".") { display.text = display.text! + digit } } else { display.text = digit isUserTyping = true } } @IBAction func appendVariable(_ sender: UIButton) { if let result = model.pushOperand(sender.currentTitle!) { displayValue = result } else { displayValue = nil } } // clears the model, displayValue, and history @IBAction func clear(_ sender: UIButton) { model.reset() displayValue = nil isUserTyping = false operationLabel.text = "" } // pushes a operation or operand onto the model @IBAction func enter() { isUserTyping = false if displayValue != nil { if let result = model.pushOperand(displayValue!) { displayValue = result } else { displayValue = nil } } } // handles ×,÷,+,−,√,sin,cos,pi @IBAction func operate(_ sender: UIButton) { if isUserTyping { enter() } if let operation = sender.currentTitle { displayValue = model.performOperation(operation) } else { displayValue = nil } } // sets a var on the model @IBAction func setVarialbe(_ sender: UIButton) { model.variableValues[CalculatorBrain.Variables.X] = displayValue isUserTyping = false displayValue = model.evaluate() } var displayValue: Double? { get { if display.text == nil { return nil } if let value = NumberFormatter().number(from: display.text!)?.doubleValue{ return value } return nil } set{ display.text = newValue == nil ? " " : "\(newValue!)" display.sizeToFit() operationLabelText = model.description + "=" } } var operationLabelText: String{ get { return operationLabel.text! } set{ operationLabel.text = newValue operationLabel.sizeToFit() } } func yForX(_ x:CGFloat) -> CGFloat? { var value:CGFloat? = nil let m = model.variableValues[CalculatorBrain.Variables.X] model.variableValues[CalculatorBrain.Variables.X] = Double(x) if let eval = model.evaluate(){ value = CGFloat(eval) } model.variableValues[CalculatorBrain.Variables.X] = m return value } }
apache-2.0
a40c85b13a5c69327a6e0cc4daf794f3
26.643357
86
0.562358
5.228836
false
false
false
false
stone-payments/onestap-sdk-ios
OnestapSDK/Core/API/ApiResponse.swift
1
4353
// // ApiResponse.swift // OnestapSDK // // Created by Munir Wanis on 17/08/17. // Copyright © 2017 Stone Payments. All rights reserved. // import Foundation // All API responses have those properties protocol Response { var success: Bool { get set } var operationReport: [ApiReport] { get set } } // Custom initialization to Response properties extension Response { mutating func initializeResponse(data: Data?) throws { guard let data = data, let jsonObject = try? JSONSerialization.jsonObject(with: data), let json = jsonObject as? JSON else { throw NSError.createParseError() } try self.initializeResponse(json: json) } mutating func initializeResponse(json: JSON) throws { self.operationReport = [] guard let success = json["success"] as? Bool else { self.success = false return } self.success = success guard let operationReportJSON = json["operationReport"] as? [JSON] else { return } let operationReport = try operationReportJSON.compactMap({ operationReport in return try ApiReport(json: operationReport) }) self.operationReport = operationReport } } // All entities that model the API responses can implement this so we can handle all responses in a generic way protocol InitializableWithData { init(data: Data?) throws } // Optionally, if you use JSON you can implement InitializableWithJson protocol protocol InitializableWithJson { init(json: JSON) throws } // Can be thrown when we can't even reach the API struct NetworkRequestError: Error { let error: Error? var localizedDescription: String { return error?.localizedDescription ?? "Network request error - no other information" } } // Can be thrown when we reach the API but the it returns a 5xx struct ApiGeneralError: Error { let data: Data? let httpUrlResponse: HTTPURLResponse } // Can be thrown when we reach the API but the it returns a 4xx struct ApiError: Error { var operationReport: [ApiReport] } // Can be thrown by InitializableWithData.init(data: Data?) implementations when parsing the data struct ApiParseError: Error { static let code = 999 let error: Error let httpUrlResponse: HTTPURLResponse let data: Data? var localizedDescription: String { return error.localizedDescription } } // This wraps a successful API response and it includes the generic data as well // The reason why we need this wrapper is that we want to pass to the client the status code and the raw response as well struct ApiResponse<T: InitializableWithData>: Response { var success: Bool = false var operationReport: [ApiReport] = [] let entity: T let httpUrlResponse: HTTPURLResponse let data: Data? init(data: Data?, httpUrlResponse: HTTPURLResponse) throws { do { self.entity = try T(data: data) self.httpUrlResponse = httpUrlResponse self.data = data try initializeResponse(data: data) } catch { throw ApiParseError(error: error, httpUrlResponse: httpUrlResponse, data: data) } } } // Some endpoints might return a 204 No Content // We can't have Void implement InitializableWithData so we've created a "Void" response struct VoidResponse: InitializableWithData { init(data: Data?) throws {} } extension Array: InitializableWithData { init(data: Data?) throws { guard let data = data, let jsonObject = try? JSONSerialization.jsonObject(with: data), let jsonArray = jsonObject as? [JSON] else { throw NSError.createParseError() } guard let element = Element.self as? InitializableWithJson.Type else { throw NSError.createParseError() } self = try jsonArray.map( { return try element.init(json: $0) as! Element } ) } } extension NSError { static func createParseError() -> NSError { return NSError(domain: "com.onestap.OnestapSDK", code: ApiParseError.code, userInfo: [NSLocalizedDescriptionKey: "A parsing error occured"]) } }
apache-2.0
2c506128ca39603d7be083ac9427cb56
29.222222
121
0.654412
4.857143
false
false
false
false
doronkatz/firefox-ios
XCUITests/PrivateBrowsingTest.swift
2
6772
/* 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 XCTest let url1 = "www.mozilla.org" let url2 = "people.mozilla.org" let url1Label = "Internet for people, not profit — Mozilla" let url2Label = "People of Mozilla" class PrivateBrowsingTest: BaseTestCase { var navigator: Navigator! var app: XCUIApplication! override func setUp() { super.setUp() app = XCUIApplication() navigator = createScreenGraph(app).navigator(self) } override func tearDown() { super.tearDown() } func testPrivateTabDoesNotTrackHistory() { navigator.openURL(urlString: url1) navigator.goto(BrowserTabMenu) // Go to History screen waitforExistence(app.toolbars.buttons["HistoryMenuToolbarItem"]) app.toolbars.buttons["HistoryMenuToolbarItem"].tap() navigator.nowAt(NewTabScreen) waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) // History without counting Recently Closed and Synced devices let history = app.tables["History List"].cells.count - 2 XCTAssertEqual(history, 1, "History entries in regular browsing do not match") // Go to Private browsing to open a website and check if it appears on History navigator.goto(PrivateTabTray) navigator.openURL(urlString: url2) navigator.nowAt(PrivateBrowserTab) waitForValueContains(app.textFields["url"], value: "people") navigator.goto(BrowserTabMenu) waitforExistence(app.toolbars.buttons["HistoryMenuToolbarItem"]) app.toolbars.buttons["HistoryMenuToolbarItem"].tap() waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) XCTAssertFalse(app.tables["History List"].staticTexts[url2Label].exists) let privateHistory = app.tables["History List"].cells.count - 2 XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match") } func testTabCountShowsOnlyNormalOrPrivateTabCount() { // Open two tabs in normal browsing and check the number of tabs open navigator.openNewURL(urlString: url1) navigator.goto(TabTray) navigator.goto(NewTabScreen) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url1Label]) let numTabs = app.collectionViews.cells.count XCTAssertEqual(numTabs, 2, "The number of regular tabs is not correct") // Open one tab in private browsing and check the total number of tabs navigator.goto(NewPrivateTabScreen) navigator.openURL(urlString: url2) navigator.nowAt(PrivateBrowserTab) waitForValueContains(app.textFields["url"], value: "people") navigator.goto(PrivateTabTray) waitforExistence(app.collectionViews.cells[url2Label]) let numPrivTabs = app.collectionViews.cells.count XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct") // Go back to regular mode and check the total number of tabs navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url1Label]) waitforNoExistence(app.collectionViews.cells[url2Label]) let numRegularTabs = app.collectionViews.cells.count XCTAssertEqual(numRegularTabs, 2, "The number of regular tabs is not correct") } func testClosePrivateTabsOptionClosesPrivateTabs() { // Check that Close Private Tabs when closing the Private Browsing Button is off by default navigator.goto(SettingsScreen) let appsettingstableviewcontrollerTableviewTable = app.tables["AppSettingsTableViewController.tableView"] appsettingstableviewcontrollerTableviewTable.staticTexts["Firefox needs to reopen for this change to take effect."].swipeUp() let closePrivateTabsSwitch = appsettingstableviewcontrollerTableviewTable.switches["Close Private Tabs, When Leaving Private Browsing"] XCTAssertFalse(closePrivateTabsSwitch.isSelected) // Open a Private tab navigator.goto(PrivateTabTray) navigator.openURL(urlString: url1) navigator.nowAt(PrivateBrowserTab) navigator.goto(PrivateTabTray) // Go back to regular browser navigator.goto(TabTray) // Go back to private browsing and check that the tab has not been closed navigator.goto(PrivateTabTray) waitforExistence(app.collectionViews.cells[url1Label]) let numPrivTabs = app.collectionViews.cells.count XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed") // Now the enable the Close Private Tabs when closing the Private Browsing Button navigator.goto(SettingsScreen) closePrivateTabsSwitch.tap() // Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing navigator.goto(PrivateTabTray) navigator.goto(TabTray) navigator.goto(PrivateTabTray) waitforNoExistence(app.collectionViews.cells[url1Label]) let numPrivTabsAfterClosing = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed") XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") } func testPrivateBrowserPanelView() { // If no private tabs are open, there should be a initial screen with label Private Browsing navigator.goto(PrivateTabTray) XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") let numPrivTabsFirstTime = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet") // If a private tab is open Private Browsing screen is not shown anymore navigator.goto(NewPrivateTabScreen) // Go to regular browsing navigator.goto(TabTray) // Go back to private brosing navigator.goto(PrivateTabTray) XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is shown") let numPrivTabsOpen = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsOpen, 1, "The number of tabs is not correct, there should be one private tab") } }
mpl-2.0
5163a995690dcf6c441723d94c3554dc
43.834437
175
0.713737
5.018532
false
false
false
false
whistlesun/SwiftWeather
Swift Weather Instant/TodayViewController.swift
35
6365
// // TodayViewController.swift // Swift Weather Instant // // Created by Marc Tarnutzer on 12.12.14. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import NotificationCenter import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class TodayViewController: UIViewController, NCWidgetProviding, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] println(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, json, error) in if(error != nil) { println("Error: \(error)") println(request) println(response) } else { println("Success: \(url)") println(request) var json = JSON(json!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let tempResult = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get forecast for index in 0...3 { println(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) if (index==0) { self.temp1.text = "\(temperature)°" } else if (index==1) { self.temp2.text = "\(temperature)°" } else if (index==2) { self.temp3.text = "\(temperature)°" } else if (index==3) { self.temp4.text = "\(temperature)°" } // Get forecast time var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==0) { self.time1.text = forecastTime } else if (index==1) { self.time2.text = forecastTime } else if (index==2) { self.time3.text = forecastTime } else if (index==3) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { println("Weather info is not available!") } } func updatePictures(index: Int, name: String) { if (index==0) { self.image1.image = UIImage(named: name) } if (index==1) { self.image2.image = UIImage(named: name) } if (index==2) { self.image3.image = UIImage(named: name) } if (index==3) { self.image4.image = UIImage(named: name) } } //CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location:CLLocation = locations[locations.count-1] as! CLLocation if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() println(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData locationManager.startUpdatingLocation() completionHandler(NCUpdateResult.NewData) } }
mit
85b18e75c2c88c88b6be3015499cc293
35.557471
123
0.542839
5.493092
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/File/KLPipe.swift
1
1353
/** * @file KLPipe.swift * @brief Define KLPipe class * @par Copyright * Copyright (C) 2017, 2018 Steel Wheels Project */ import CoconutData import KiwiEngine import JavaScriptCore import Foundation @objc public protocol KLPipeProtocol: JSExport { var reading: JSValue { get } var writing: JSValue { get } } @objc public class KLPipe: NSObject, KLPipeProtocol { private var mPipe: CNPipe private var mContext: KEContext private var mWriting: KLFile? private var mReading: KLFile? public init(context ctxt: KEContext){ mPipe = CNPipe() mContext = ctxt mWriting = nil mReading = nil } public var pipe: Pipe { get { return mPipe.pipe }} public var readerFile: CNFile { get { return mPipe.reader }} public var writerFile: CNFile { get { return mPipe.writer }} public var reading: JSValue { get { if let file = mReading { return JSValue(object: file, in: mContext) } else { let fileobj = KLFile(file: self.readerFile, context: mContext) mReading = fileobj return JSValue(object: fileobj, in: mContext) } } } public var writing: JSValue { get { if let file = mWriting { return JSValue(object: file, in: mContext) } else { let fileobj = KLFile(file: self.writerFile, context: mContext) mWriting = fileobj return JSValue(object: fileobj, in: mContext) } } } }
lgpl-2.1
d8e44aa7e8e7b8c85fd014d362a0ca23
20.822581
66
0.689579
3.324324
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Browser/Tab.swift
1
24980
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared import SwiftyJSON import XCGLogger fileprivate var debugTabCount = 0 func mostRecentTab(inTabs tabs: [Tab]) -> Tab? { var recent = tabs.first tabs.forEach { tab in if let time = tab.lastExecutedTime, time > (recent?.lastExecutedTime ?? 0) { recent = tab } } return recent } protocol TabContentScript { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol TabDelegate { func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String) @objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView) @objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) } @objc protocol URLChangeDelegate { func tab(_ tab: Tab, urlDidChangeTo url: URL) } struct TabState { var isPrivate: Bool = false var desktopSite: Bool = false var url: URL? var title: String? var favicon: Favicon? } class Tab: NSObject { fileprivate var _isPrivate: Bool = false internal fileprivate(set) var isPrivate: Bool { get { return _isPrivate } set { if _isPrivate != newValue { _isPrivate = newValue } } } var tabState: TabState { return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, url: url, title: displayTitle, favicon: displayFavicon) } // PageMetadata is derived from the page content itself, and as such lags behind the // rest of the tab. var pageMetadata: PageMetadata? var consecutiveCrashes: UInt = 0 var canonicalURL: URL? { if let string = pageMetadata?.siteURL, let siteURL = URL(string: string) { // If the canonical URL from the page metadata doesn't contain the // "#" fragment, check if the tab's URL has a fragment and if so, // append it to the canonical URL. if siteURL.fragment == nil, let fragment = self.url?.fragment, let siteURLWithFragment = URL(string: "\(string)#\(fragment)") { return siteURLWithFragment } return siteURL } return self.url } var userActivity: NSUserActivity? var webView: WKWebView? var tabDelegate: TabDelegate? weak var urlDidChangeDelegate: URLChangeDelegate? // TODO: generalize this. var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? fileprivate var lastRequest: URLRequest? var restoring: Bool = false var pendingScreenshot = false var url: URL? { didSet { if let _url = url, let internalUrl = InternalURL(_url), internalUrl.isAuthorized { url = URL(string: internalUrl.stripAuthorization) } } } var mimeType: String? var isEditing: Bool = false // When viewing a non-HTML content type in the webview (like a PDF document), this URL will // point to a tempfile containing the content so it can be shared to external applications. var temporaryDocument: TemporaryDocument? fileprivate var _noImageMode = false /// Returns true if this tab's URL is known, and it's longer than we want to store. var urlIsTooLong: Bool { guard let url = self.url else { return false } return url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX } // Use computed property so @available can be used to guard `noImageMode`. var noImageMode: Bool { get { return _noImageMode } set { if newValue == _noImageMode { return } _noImageMode = newValue contentBlocker?.noImageMode(enabled: _noImageMode) } } var contentBlocker: FirefoxTabContentBlocker? /// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs. var lastTitle: String? /// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to /// be managed by the web view's navigation delegate. var desktopSite: Bool = false var readerModeAvailableOrActive: Bool { if let readerMode = self.getContentScript(name: "ReaderMode") as? ReaderMode { return readerMode.state != .unavailable } return false } fileprivate(set) var screenshot: UIImage? var screenshotUUID: UUID? // If this tab has been opened from another, its parent will point to the tab from which it was opened weak var parent: Tab? fileprivate var contentScriptManager = TabContentScriptManager() private(set) var userScriptManager: UserScriptManager? fileprivate let configuration: WKWebViewConfiguration /// Any time a tab tries to make requests to display a Javascript Alert and we are not the active /// tab instance, queue it for later until we become foregrounded. fileprivate var alertQueue = [JSAlertInfo]() init(configuration: WKWebViewConfiguration, isPrivate: Bool = false) { self.configuration = configuration super.init() self.isPrivate = isPrivate debugTabCount += 1 } class func toRemoteTab(_ tab: Tab) -> RemoteTab? { if tab.isPrivate { return nil } if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) { let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed()) return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: Date.now(), icon: nil) } else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty { let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed()) if let displayURL = history.first { return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } } return nil } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { configuration.userContentController = WKUserContentController() configuration.allowsInlineMediaPlayback = true let webView = TabWebView(frame: .zero, configuration: configuration) webView.delegate = self webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.allowsLinkPreview = false // Night mode enables this by toggling WKWebView.isOpaque, otherwise this has no effect. webView.backgroundColor = .black // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate restore(webView) self.webView = webView self.webView?.addObserver(self, forKeyPath: KVOConstants.URL.rawValue, options: .new, context: nil) self.userScriptManager = UserScriptManager(tab: self) tabDelegate?.tab?(self, didCreateWebView: webView) } } func restore(_ webView: WKWebView) { // Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { restoring = true var urls = [String]() for url in sessionData.urls { urls.append(url.absoluteString) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = urls as AnyObject? jsonDict["currentPage"] = currentPage as AnyObject? guard let json = JSON(jsonDict).stringify()?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return } if let restoreURL = URL(string: "\(InternalURL.baseUrl)/\(SessionRestoreHandler.path)?history=\(json)") { let request = PrivilegedRequest(url: restoreURL) as URLRequest webView.load(request) lastRequest = request } } else if let request = lastRequest { webView.load(request) } else { print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")") } } deinit { debugTabCount -= 1 #if DEBUG guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } func checkTabCount(failures: Int) { // Need delay for pool to drain. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { if appDelegate.tabManager.tabs.count == debugTabCount { return } // If this assert has false positives, remove it and just log an error. assert(failures < 3, "Tab init/deinit imbalance, possible memory leak.") checkTabCount(failures: failures + 1) } } checkTabCount(failures: 0) #endif } func closeAndRemovePrivateBrowsingData() { webView?.removeObserver(self, forKeyPath: KVOConstants.URL.rawValue) if let webView = webView { tabDelegate?.tab?(self, willDeleteWebView: webView) } contentScriptManager.helpers.removeAll() if isPrivate { removeAllBrowsingData() } webView?.navigationDelegate = nil webView?.removeFromSuperview() webView = nil } func removeAllBrowsingData(completionHandler: @escaping () -> Void = {}) { let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases]) webView?.configuration.websiteDataStore.removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: completionHandler) } var loading: Bool { return webView?.isLoading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList } var historyList: [URL] { func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url } var tabs = self.backList?.map(listToUrl) ?? [URL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title, !title.isEmpty { return title } // When picking a display title. Tabs with sessionData are pending a restore so show their old title. // To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle. if let url = self.url, InternalURL(url)?.isAboutHomeURL ?? false, sessionData == nil, !restoring { return "" } guard let lastTitle = lastTitle, !lastTitle.isEmpty else { return self.url?.displayURL?.absoluteString ?? "" } return lastTitle } var displayFavicon: Favicon? { return favicons.max { $0.width! < $1.width! } } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { _ = webView?.goBack() } func goForward() { _ = webView?.goForward() } func goToBackForwardListItem(_ item: WKBackForwardListItem) { _ = webView?.go(to: item) } @discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? { if let webView = webView { // Convert about:reader?url=http://example.com URLs to local ReaderMode URLs if let url = request.url, let syncedReaderModeURL = url.decodeReaderModeURL, let localReaderModeURL = syncedReaderModeURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { let readerModeRequest = PrivilegedRequest(url: localReaderModeURL) as URLRequest lastRequest = readerModeRequest return webView.load(readerModeRequest) } lastRequest = request if let url = request.url, url.isFileURL, request.isPrivileged { return webView.loadFileURL(url, allowingReadAccessTo: url) } return webView.load(request) } return nil } func stop() { webView?.stopLoading() } func reload() { let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil if (userAgent ?? "") != webView?.customUserAgent, let currentItem = webView?.backForwardList.currentItem { webView?.customUserAgent = userAgent // Reload the initial URL to avoid UA specific redirection loadRequest(PrivilegedRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) as URLRequest) return } if let _ = webView?.reloadFromOrigin() { print("reloaded zombified tab from origin") return } if let webView = self.webView { print("restoring webView from scratch") restore(webView) } } func addContentScript(_ helper: TabContentScript, name: String) { contentScriptManager.addContentScript(helper, name: name, forTab: self) } func getContentScript(name: String) -> TabContentScript? { return contentScriptManager.getContentScript(name) } func hideContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = false if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = true if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(_ bar: SnackBar) { bars.append(bar) tabDelegate?.tab(self, didAddSnackbar: bar) } func removeSnackbar(_ bar: SnackBar) { if let index = bars.index(of: bar) { bars.remove(at: index) tabDelegate?.tab(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. bars.reversed().forEach { removeSnackbar($0) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. bars.reversed().filter({ !$0.shouldPersist(self) }).forEach({ removeSnackbar($0) }) } func expireSnackbars(withClass snackbarClass: String) { bars.reversed().filter({ $0.snackbarClassIdentifier == snackbarClass }).forEach({ removeSnackbar($0) }) } func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) { self.screenshot = screenshot if revUUID { self.screenshotUUID = UUID() } } func toggleDesktopSite() { desktopSite = !desktopSite reload() } func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) { alertQueue.append(alert) } func dequeueJavascriptAlertPrompt() -> JSAlertInfo? { guard !alertQueue.isEmpty else { return nil } return alertQueue.removeFirst() } func cancelQueuedAlerts() { alertQueue.forEach { alert in alert.cancel() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView, webView == self.webView, let path = keyPath, path == KVOConstants.URL.rawValue else { return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } guard let url = self.webView?.url else { return } if let helper = contentScriptManager.getContentScript(ContextMenuHelper.name()) as? ContextMenuHelper { helper.replaceWebViewLongPress() } self.urlDidChangeDelegate?.tab(self, urlDidChangeTo: url) } func isDescendentOf(_ ancestor: Tab) -> Bool { return sequence(first: parent) { $0?.parent }.contains { $0 == ancestor } } func setNightMode(_ enabled: Bool) { webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil) // For WKWebView background color to take effect, isOpaque must be false, which is counter-intuitive. Default is true. // The color is previously set to black in the webview init webView?.isOpaque = !enabled } func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) { guard let webView = self.webView else { return } if let path = Bundle.main.path(forResource: fileName, ofType: type), let source = try? String(contentsOfFile: path) { let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly) webView.configuration.userContentController.addUserScript(userScript) } } func observeURLChanges(delegate: URLChangeDelegate) { self.urlDidChangeDelegate = delegate } func removeURLChangeObserver(delegate: URLChangeDelegate) { if let existing = self.urlDidChangeDelegate, existing === delegate { self.urlDidChangeDelegate = nil } } } extension Tab: TabWebViewDelegate { fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) { tabDelegate?.tab(self, didSelectFindInPageForSelection: selection) } fileprivate func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String) { tabDelegate?.tab(self, didSelectSearchWithFirefoxForSelection: selection) } } extension Tab: ContentBlockerTab { func currentURL() -> URL? { return url } func currentWebView() -> WKWebView? { return webView } func imageContentBlockingEnabled() -> Bool { return noImageMode } } private class TabContentScriptManager: NSObject, WKScriptMessageHandler { fileprivate var helpers = [String: TabContentScript]() @objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addContentScript(_ helper: TabContentScript, name: String, forTab tab: Tab) { if let _ = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right TabHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { tab.webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName) } } func getContentScript(_ name: String) -> TabContentScript? { return helpers[name] } } private protocol TabWebViewDelegate: AnyObject { func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String) } class TabWebView: WKWebView, MenuHelperInterface { fileprivate weak var delegate: TabWebViewDelegate? // Updates the `background-color` of the webview to match // the theme if the webview is showing "about:blank" (nil). func applyTheme() { if url == nil { let backgroundColor = ThemeManager.instance.current.browser.background.hexString evaluateJavaScript("document.documentElement.style.backgroundColor = '\(backgroundColor)';") } } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage } @objc func menuHelperFindInPage() { evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection) } } @objc func menuHelperSearchWithFirefox() { evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" self.delegate?.tabWebViewSearchWithFirefox(self, didSelectSearchWithFirefoxForSelection: selection) } } internal override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // The find-in-page selection menu only appears if the webview is the first responder. becomeFirstResponder() return super.hitTest(point, with: event) } } /// // Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector // // This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never // instantiated. It only serves as a placeholder for the method. When the method is called, self is // actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know // that it is a UIView subclass to access its superview. // class TabWebViewMenuHelper: UIView { @objc func swizzledMenuHelperFindInPage() { if let tabWebView = superview?.superview as? TabWebView { tabWebView.evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection) } } } }
mpl-2.0
ab413944fe9a1c1b81ff17f2d75d4148
34.994236
201
0.635308
5.344459
false
false
false
false
CalebeEmerick/Checkout
Source/Checkout/Router.swift
1
1202
// // Router.swift // Checkout // // Created by Calebe Emerick on 30/11/16. // Copyright © 2016 CalebeEmerick. All rights reserved. // import UIKit struct Router { private static var storeControllerStack: ControllerStack<StoresController>? { guard let nc = Storyboard.main.instantiateViewController(withIdentifier: "StoresNavigationController") as? UINavigationController, let vc = nc.contentViewController as? StoresController else { return nil } return ControllerStack(navigation: nc, controller: vc) } static func enterApplication() { guard let window = Constants.appDelegate.window else { return } guard let snapshot = window.snapshotView(afterScreenUpdates: true) else { return } storeControllerStack?.navigation.view.addSubview(snapshot) window.rootViewController = storeControllerStack?.navigation UIView.transition(with: window, duration: 0.5, options: .transitionFlipFromLeft, animations: { snapshot.layer.opacity = 0 snapshot.removeFromSuperview() }, completion: nil) } }
mit
346a46e73ef1817fa5a021225988e72c
30.605263
136
0.651957
5.221739
false
false
false
false
danielcwj16/ConnectedAlarmApp
Pods/JTAppleCalendar/Sources/JTAppleCalendarLayout.swift
2
32402
// // JTAppleCalendarLayout.swift // // Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // 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. // /// Methods in this class are meant to be overridden and will be called by its collection view to gather layout information. class JTAppleCalendarLayout: UICollectionViewLayout, JTAppleCalendarLayoutProtocol { var allowsDateCellStretching = true var shouldClearCacheOnInvalidate = true var firstContentOffsetWasSet = false let errorDelta: CGFloat = 0.0000001 var lastSetCollectionViewSize: CGRect = .zero var cellSize: CGSize = CGSize.zero var itemSizeWasSet: Bool = false var scrollDirection: UICollectionViewScrollDirection = .horizontal var maxMissCount: Int = 0 var cellCache: [Int: [(Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)]] = [:] var headerCache: [Int: (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)] = [:] var decorationCache: [IndexPath:UICollectionViewLayoutAttributes] = [:] var sectionSize: [CGFloat] = [] var lastWrittenCellAttribute: (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)! var isPreparing = true var stride: CGFloat = 0 var minimumInteritemSpacing: CGFloat = 0 var minimumLineSpacing: CGFloat = 0 var sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) var headerSizes: [AnyHashable:CGFloat] = [:] var focusIndexPath: IndexPath? var isCalendarLayoutLoaded: Bool { return !cellCache.isEmpty } var layoutIsReadyToBePrepared: Bool { return !(!cellCache.isEmpty || collectionView!.frame.width == 0 || collectionView!.frame.height == 0 || delegate.calendarDataSource == nil) } var monthMap: [Int: Int] = [:] var numberOfRows: Int = 0 var strictBoundaryRulesShouldApply: Bool = false var thereAreHeaders: Bool { return !headerSizes.isEmpty } var thereAreDecorationViews = false weak var delegate: JTAppleCalendarDelegateProtocol! var currentHeader: (section: Int, size: CGSize)? // Tracks the current header size var currentCell: (section: Int, width: CGFloat, height: CGFloat)? // Tracks the current cell size var contentHeight: CGFloat = 0 // Content height of calendarView var contentWidth: CGFloat = 0 // Content wifth of calendarView var xCellOffset: CGFloat = 0 var yCellOffset: CGFloat = 0 var endSeparator: CGFloat = 0 var daysInSection: [Int: Int] = [:] // temporary caching var monthInfo: [Month] = [] var updatedLayoutCellSize: CGSize { // Default Item height and width var height: CGFloat = collectionView!.bounds.size.height / CGFloat(delegate.cachedConfiguration.numberOfRows) var width: CGFloat = collectionView!.bounds.size.width / CGFloat(maxNumberOfDaysInWeek) if itemSizeWasSet { // If delegate item size was set if scrollDirection == .horizontal { width = delegate.cellSize } else { height = delegate.cellSize } } return CGSize(width: width, height: height) } open override func register(_ nib: UINib?, forDecorationViewOfKind elementKind: String) { super.register(nib, forDecorationViewOfKind: elementKind) thereAreDecorationViews = true } open override func register(_ viewClass: AnyClass?, forDecorationViewOfKind elementKind: String) { super.register(viewClass, forDecorationViewOfKind: elementKind) thereAreDecorationViews = true } init(withDelegate delegate: JTAppleCalendarDelegateProtocol) { super.init() self.delegate = delegate } /// Tells the layout object to update the current layout. open override func prepare() { if !layoutIsReadyToBePrepared { return } setupDataFromDelegate() if scrollDirection == .vertical { configureVerticalLayout() } else { configureHorizontalLayout() } // Get rid of header data if dev didnt register headers. // They were used for calculation but are not needed to be displayed if !thereAreHeaders { headerCache.removeAll() } // Set the first content offset only once. This will prevent scrolling animation on viewDidload. if !firstContentOffsetWasSet { firstContentOffsetWasSet = true let firstContentOffset = delegate.firstContentOffset() collectionView!.setContentOffset(firstContentOffset, animated: false) } daysInSection.removeAll() // Clear chache lastSetCollectionViewSize = collectionView!.frame } func setupDataFromDelegate() { // get information from the delegate headerSizes = delegate.sizesForMonthSection() // update first. Other variables below depend on it strictBoundaryRulesShouldApply = thereAreHeaders || delegate.cachedConfiguration.hasStrictBoundaries numberOfRows = delegate.cachedConfiguration.numberOfRows monthMap = delegate.monthMap allowsDateCellStretching = delegate.allowsDateCellStretching monthInfo = delegate.monthInfo scrollDirection = delegate.scrollDirection maxMissCount = scrollDirection == .horizontal ? maxNumberOfRowsPerMonth : maxNumberOfDaysInWeek minimumInteritemSpacing = delegate.minimumInteritemSpacing minimumLineSpacing = delegate.minimumLineSpacing sectionInset = delegate.sectionInset cellSize = updatedLayoutCellSize } func indexPath(direction: SegmentDestination, of section:Int, item: Int) -> IndexPath? { var retval: IndexPath? switch direction { case .next: if let data = cellCache[section], !data.isEmpty, 0..<data.count ~= item + 1 { retval = IndexPath(item: item + 1, section: section) } else if let data = cellCache[section + 1], !data.isEmpty { retval = IndexPath(item: 0, section: section + 1) } case .previous: if let data = cellCache[section], !data.isEmpty, 0..<data.count ~= item - 1 { retval = IndexPath(item: item - 1, section: section) } else if let data = cellCache[section - 1], !data.isEmpty { retval = IndexPath(item: data.count - 1, section: section - 1) } default: break } return retval } func configureHorizontalLayout() { var section = 0 var totalDayCounter = 0 var headerGuide = 0 let fullSection = numberOfRows * maxNumberOfDaysInWeek var extra = 0 xCellOffset = sectionInset.left endSeparator = sectionInset.left + sectionInset.right for aMonth in monthInfo { for numberOfDaysInCurrentSection in aMonth.sections { // Generate and cache the headers if let aHeaderAttr = determineToApplySupplementaryAttribs(0, section: section) { headerCache[section] = aHeaderAttr if strictBoundaryRulesShouldApply { contentWidth += aHeaderAttr.4 yCellOffset = aHeaderAttr.5 } } // Generate and cache the cells for item in 0..<numberOfDaysInCurrentSection { if let attribute = determineToApplyAttribs(item, section: section) { if cellCache[section] == nil { cellCache[section] = [] } cellCache[section]!.append(attribute) lastWrittenCellAttribute = attribute xCellOffset += attribute.4 if strictBoundaryRulesShouldApply { headerGuide += 1 if numberOfDaysInCurrentSection - 1 == item || headerGuide % maxNumberOfDaysInWeek == 0 { // We are at the last item in the section // && if we have headers headerGuide = 0 xCellOffset = sectionInset.left yCellOffset += attribute.5 } } else { totalDayCounter += 1 extra += 1 if totalDayCounter % fullSection == 0 { // If you have a full section xCellOffset = sectionInset.left yCellOffset = 0 contentWidth += attribute.4 * 7 stride = contentWidth sectionSize.append(contentWidth) } else { if totalDayCounter >= delegate.totalDays { contentWidth += attribute.4 * 7 sectionSize.append(contentWidth) } if totalDayCounter % maxNumberOfDaysInWeek == 0 { xCellOffset = sectionInset.left yCellOffset += attribute.5 } } } } } // Save the content size for each section contentWidth += endSeparator if strictBoundaryRulesShouldApply { sectionSize.append(contentWidth) stride = sectionSize[section] } section += 1 } } contentHeight = self.collectionView!.bounds.size.height } func configureVerticalLayout() { var section = 0 var totalDayCounter = 0 var headerGuide = 0 xCellOffset = sectionInset.left yCellOffset = sectionInset.top endSeparator = sectionInset.top + sectionInset.bottom for aMonth in monthInfo { for numberOfDaysInCurrentSection in aMonth.sections { // Generate and cache the headers if strictBoundaryRulesShouldApply { if let aHeaderAttr = determineToApplySupplementaryAttribs(0, section: section) { headerCache[section] = aHeaderAttr yCellOffset += aHeaderAttr.5 contentHeight += aHeaderAttr.5 } } // Generate and cache the cells for item in 0..<numberOfDaysInCurrentSection { if let attribute = determineToApplyAttribs(item, section: section) { if cellCache[section] == nil { cellCache[section] = [] } cellCache[section]!.append(attribute) lastWrittenCellAttribute = attribute xCellOffset += attribute.4 if strictBoundaryRulesShouldApply { headerGuide += 1 if headerGuide % maxNumberOfDaysInWeek == 0 || numberOfDaysInCurrentSection - 1 == item { // We are at the last item in the // section && if we have headers headerGuide = 0 xCellOffset = sectionInset.left yCellOffset += attribute.5 contentHeight += attribute.5 } } else { totalDayCounter += 1 if totalDayCounter % maxNumberOfDaysInWeek == 0 { xCellOffset = sectionInset.left yCellOffset += attribute.5 contentHeight += attribute.5 } else if totalDayCounter == delegate.totalDays { contentHeight += attribute.5 } } } } // Save the content size for each section contentHeight += endSeparator yCellOffset += endSeparator sectionSize.append(contentHeight) section += 1 } } contentWidth = self.collectionView!.bounds.size.width } /// Returns the width and height of the collection view’s contents. /// The width and height of the collection view’s contents. open override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } /// Returns the layout attributes for all of the cells /// and views in the specified rectangle. override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let startSectionIndex = startIndexFrom(rectOrigin: rect.origin) // keep looping until there were no interception rects var attributes: [UICollectionViewLayoutAttributes] = [] var beganIntercepting = false var missCount = 0 outterLoop: for sectionIndex in startSectionIndex..<cellCache.count { if let validSection = cellCache[sectionIndex], !validSection.isEmpty { if thereAreDecorationViews { let attrib = layoutAttributesForDecorationView(ofKind: decorationViewID, at: IndexPath(item: 0, section: sectionIndex))! attributes.append(attrib) } // Add header view attributes if thereAreHeaders { let data = headerCache[sectionIndex]! if CGRect(x: data.2, y: data.3, width: data.4, height: data.5).intersects(rect) { let attrib = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: IndexPath(item: data.0, section: data.1)) attributes.append(attrib!) } } for val in validSection { if CGRect(x: val.2, y: val.3, width: val.4, height: val.5).intersects(rect) { missCount = 0 beganIntercepting = true let attrib = layoutAttributesForItem(at: IndexPath(item: val.0, section: val.1)) attributes.append(attrib!) } else { missCount += 1 // If there are at least 8 misses in a row // since intercepting began, then this // section has no more interceptions. // So break if missCount > maxMissCount && beganIntercepting { break outterLoop } } } } } return attributes } /// Returns the layout attributes for the item at the specified index /// path. A layout attributes object containing the information to apply /// to the item’s cell. override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { // If this index is already cached, then return it else, // apply a new layout attribut to it if let alreadyCachedCellAttrib = cellAttributeFor(indexPath.item, section: indexPath.section) { return alreadyCachedCellAttrib } return nil//deterimeToApplyAttribs(indexPath.item, section: indexPath.section) } func supplementaryAttributeFor(item: Int, section: Int, elementKind: String) -> UICollectionViewLayoutAttributes? { var retval: UICollectionViewLayoutAttributes? if let cachedData = headerCache[section] { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: IndexPath(item: item, section: section)) attributes.frame = CGRect(x: cachedData.2, y: cachedData.3, width: cachedData.4, height: cachedData.5) retval = attributes } return retval } func cellAttributeFor(_ item: Int, section: Int) -> UICollectionViewLayoutAttributes? { if let alreadyCachedCellAttrib = cellCache[section], item < alreadyCachedCellAttrib.count, item >= 0 { let cachedValue = alreadyCachedCellAttrib[item] let attrib = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: section)) attrib.frame = CGRect(x: cachedValue.2, y: cachedValue.3, width: cachedValue.4, height: cachedValue.5) if minimumInteritemSpacing > -1, minimumLineSpacing > -1 { var frame = attrib.frame.insetBy(dx: minimumInteritemSpacing, dy: minimumLineSpacing) if frame == .null { frame = attrib.frame.insetBy(dx: 0, dy: 0) } attrib.frame = frame } return attrib } return nil } func determineToApplyAttribs(_ item: Int, section: Int) -> (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)? { let monthIndex = monthMap[section]! let numberOfDays = numberOfDaysInSection(monthIndex) // return nil on invalid range if !(0...monthMap.count ~= section) || !(0...numberOfDays ~= item) { return nil } let size = sizeForitemAtIndexPath(item, section: section) let y = scrollDirection == .horizontal ? yCellOffset + sectionInset.top : yCellOffset return (item, section, xCellOffset + stride, y, size.width, size.height) } func determineToApplySupplementaryAttribs(_ item: Int, section: Int) -> (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)? { var retval: (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)? let headerHeight = cachedHeaderHeightForSection(section) switch scrollDirection { case .horizontal: let modifiedSize = sizeForitemAtIndexPath(item, section: section) let width = (modifiedSize.width * 7) retval = (item, section, contentWidth + sectionInset.left, sectionInset.top, width , headerHeight) case .vertical: // Use the calculaed header size and force the width // of the header to take up 7 columns // We cache the header here so we dont call the // delegate so much let modifiedSize = (width: collectionView!.frame.width, height: headerHeight) retval = (item, section, sectionInset.left, yCellOffset , modifiedSize.width - (sectionInset.left + sectionInset.right), modifiedSize.height) } if retval?.4 == 0, retval?.5 == 0 { return nil } return retval } open override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let alreadyCachedVal = decorationCache[indexPath] { return alreadyCachedVal } let retval = UICollectionViewLayoutAttributes(forDecorationViewOfKind: decorationViewID, with: indexPath) decorationCache[indexPath] = retval retval.frame = delegate.sizeOfDecorationView(indexPath: indexPath) retval.zIndex = -1 return retval } /// Returns the layout attributes for the specified supplementary view. open override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let alreadyCachedHeaderAttrib = supplementaryAttributeFor(item: indexPath.item, section: indexPath.section, elementKind: elementKind) { return alreadyCachedHeaderAttrib } return nil } func numberOfDaysInSection(_ index: Int) -> Int { if let days = daysInSection[index] { return days } let days = monthInfo[index].numberOfDaysInMonthGrid daysInSection[index] = days return days } func cachedHeaderHeightForSection(_ section: Int) -> CGFloat { var retval: CGFloat = 0 // We look for most specific to less specific // Section = specific dates // Months = generic months // Default = final resort if let height = headerSizes[section] { retval = height } else { let monthIndex = monthMap[section]! let monthName = monthInfo[monthIndex].name if let height = headerSizes[monthName] { retval = height } else if let height = headerSizes["default"] { retval = height } } return retval } func sizeForitemAtIndexPath(_ item: Int, section: Int) -> (width: CGFloat, height: CGFloat) { if let cachedCell = currentCell, cachedCell.section == section { if !strictBoundaryRulesShouldApply, scrollDirection == .horizontal, !cellCache.isEmpty { if let x = cellCache[0]?[0] { return (x.4, x.5) } else { return (0, 0) } } else { return (cachedCell.width, cachedCell.height) } } let width = cellSize.width - ((sectionInset.left / 7) + (sectionInset.right / 7)) var size: (width: CGFloat, height: CGFloat) = (width, cellSize.height) if itemSizeWasSet { if scrollDirection == .vertical { size.height = cellSize.height } else { size.width = cellSize.width let headerHeight = strictBoundaryRulesShouldApply ? cachedHeaderHeightForSection(section) : 0 let currentMonth = monthInfo[monthMap[section]!] let recalculatedNumOfRows = allowsDateCellStretching ? CGFloat(currentMonth.maxNumberOfRowsForFull(developerSetRows: numberOfRows)) : CGFloat(maxNumberOfRowsPerMonth) size.height = (collectionView!.frame.height - headerHeight - sectionInset.top - sectionInset.bottom) / recalculatedNumOfRows currentCell = (section: section, width: size.width, height: size.height) } } else { // Get header size if it already cached let headerHeight = strictBoundaryRulesShouldApply ? cachedHeaderHeightForSection(section) : 0 var height: CGFloat = 0 let currentMonth = monthInfo[monthMap[section]!] let numberOfRowsForSection: Int if allowsDateCellStretching { if strictBoundaryRulesShouldApply { numberOfRowsForSection = currentMonth.maxNumberOfRowsForFull(developerSetRows: numberOfRows) } else { numberOfRowsForSection = numberOfRows } } else { numberOfRowsForSection = maxNumberOfRowsPerMonth } height = (collectionView!.frame.height - headerHeight - sectionInset.top - sectionInset.bottom) / CGFloat(numberOfRowsForSection) size.height = height > 0 ? height : 0 currentCell = (section: section, width: size.width, height: size.height) } return size } func numberOfRowsForMonth(_ index: Int) -> Int { let monthIndex = monthMap[index]! return monthInfo[monthIndex].rows } func startIndexFrom(rectOrigin offset: CGPoint) -> Int { let key = scrollDirection == .horizontal ? offset.x : offset.y return startIndexBinarySearch(sectionSize, offset: key) } func sizeOfContentForSection(_ section: Int) -> CGFloat { switch scrollDirection { case .horizontal: return cellCache[section]![0].4 * CGFloat(maxNumberOfDaysInWeek) case .vertical: let headerSizeOfSection = !headerCache.isEmpty ? headerCache[section]!.5 : 0 return cellCache[section]![0].5 * CGFloat(numberOfRowsForMonth(section)) + headerSizeOfSection } } // func sectionFromRectOffset(_ offset: CGPoint) -> Int { // let theOffet = scrollDirection == .horizontal ? offset.x : offset.y // return sectionFromOffset(theOffet) // } func sectionFromOffset(_ theOffSet: CGFloat) -> Int { var val: Int = 0 for (index, sectionSizeValue) in sectionSize.enumerated() { if abs(theOffSet - sectionSizeValue) < errorDelta { continue } if theOffSet < sectionSizeValue { val = index break } } return val } func startIndexBinarySearch<T: Comparable>(_ val: [T], offset: T) -> Int { if val.count < 3 { return 0 } // If the range is less than 2 just break here. var midIndex: Int = 0 var startIndex = 0 var endIndex = val.count - 1 while startIndex < endIndex { midIndex = startIndex + (endIndex - startIndex) / 2 if midIndex + 1 >= val.count || offset >= val[midIndex] && offset < val[midIndex + 1] || val[midIndex] == offset { break } else if val[midIndex] < offset { startIndex = midIndex + 1 } else { endIndex = midIndex } } return midIndex } /// Returns an object initialized from data in a given unarchiver. /// self, initialized using the data in decoder. required public init?(coder aDecoder: NSCoder) { delegate = aDecoder.value(forKey: "delegate") as! JTAppleCalendarDelegateProtocol cellCache = aDecoder.value(forKey: "delegate") as! [Int : [(Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)]] headerCache = aDecoder.value(forKey: "delegate") as! [Int : (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)] headerSizes = aDecoder.value(forKey: "delegate") as! [AnyHashable:CGFloat] super.init(coder: aDecoder) } func setMinVisibleDate() { // jt101 for setting proposal let minIndices = minimumVisibleIndexPaths() switch (minIndices.headerIndex, minIndices.cellIndex) { case (.some(let path), nil): focusIndexPath = path case (nil, .some(let path)): focusIndexPath = path case (.some(let hPath), (.some(let cPath))): if hPath <= cPath { focusIndexPath = hPath } else { focusIndexPath = cPath } default: break } } // This function ignores decoration views //JT101 for setting proposal func minimumVisibleIndexPaths() -> (cellIndex: IndexPath?, headerIndex: IndexPath?) { let visibleItems: [UICollectionViewLayoutAttributes] = scrollDirection == .horizontal ? visibleElements(excludeHeaders: true) : visibleElements() var cells: [IndexPath] = [] var headers: [IndexPath] = [] for item in visibleItems { switch item.representedElementCategory { case .cell: cells.append(item.indexPath) case .supplementaryView: headers.append(item.indexPath) case .decorationView: break } } return (cells.min(), headers.min()) } func visibleElements(excludeHeaders: Bool? = false, from rect: CGRect? = nil) -> [UICollectionViewLayoutAttributes] { let aRect = rect ?? CGRect(x: collectionView!.contentOffset.x + 1, y: collectionView!.contentOffset.y + 1, width: collectionView!.frame.width - 2, height: collectionView!.frame.height - 2) guard let attributes = layoutAttributesForElements(in: aRect), !attributes.isEmpty else { return [] } if excludeHeaders == true { return attributes.filter { $0.representedElementKind != UICollectionElementKindSectionHeader } } return attributes } /// Returns the content offset to use after an animation /// layout update or change. /// - Parameter proposedContentOffset: The proposed point for the /// upper-left corner of the visible content /// - returns: The content offset that you want to use instead open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { var retval = proposedContentOffset if let focusIndexPath = focusIndexPath { if thereAreHeaders { let headerIndexPath = IndexPath(item: 0, section: focusIndexPath.section) if let headerAttr = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: headerIndexPath) { retval = scrollDirection == .horizontal ? CGPoint(x: headerAttr.frame.origin.x, y: 0) : CGPoint(x: 0, y: headerAttr.frame.origin.y) } } else { if let cellAttr = layoutAttributesForItem(at: focusIndexPath) { retval = scrollDirection == .horizontal ? CGPoint(x: cellAttr.frame.origin.x, y: 0) : CGPoint(x: 0, y: cellAttr.frame.origin.y) } } // Floating point issues. number could appear the same, but are not. // thereby causing UIScollView to think it has scrolled let retvalOffset: CGFloat let calendarOffset: CGFloat switch scrollDirection { case .horizontal: retvalOffset = retval.x calendarOffset = collectionView!.contentOffset.x case .vertical: retvalOffset = retval.y calendarOffset = collectionView!.contentOffset.y } if abs(retvalOffset - calendarOffset) < errorDelta { retval = collectionView!.contentOffset } } return retval } open override func invalidateLayout() { super.invalidateLayout() if shouldClearCacheOnInvalidate { clearCache() } shouldClearCacheOnInvalidate = true } func clearCache() { headerCache.removeAll() cellCache.removeAll() sectionSize.removeAll() decorationCache.removeAll() currentHeader = nil currentCell = nil lastWrittenCellAttribute = nil xCellOffset = 0 yCellOffset = 0 contentHeight = 0 contentWidth = 0 stride = 0 } }
mit
f0df7e4d13b3825ef567ad296ec3ba98
43.807746
196
0.583776
5.732791
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerDemo/MGImagePickerControllerDemo/UIDevice+Extension.swift
1
2167
// // UIDevice+Extension.swift // MGDS_Swift // // Created by i-Techsys.com on 2017/8/2. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit extension UIDevice { // 设备类型 public enum DeviceKind { case iPhone4 case iPhone5 case iPhone6 case iPhone6Plus case iPad case unknown } public var kind: DeviceKind { guard userInterfaceIdiom == .phone else { return .iPad } let result: DeviceKind switch UIScreen.main.nativeBounds.height { case 960: result = .iPhone4 case 1136: result = .iPhone5 case 1334: result = .iPhone6 case 2208: result = .iPhone6Plus default: result = .unknown } return result } public static func isPhone() -> Bool { return UIDevice().userInterfaceIdiom == .phone } public static func isPad() -> Bool { return UIDevice().userInterfaceIdiom == .pad } public static func isSimulator() -> Bool { return Simulator.isRunning } } // 判断平台是在模拟器还是真机 struct Platform { static let isSimulator: Bool = { var isSim = false #if targetEnvironment(simulator) isSim = true #endif return isSim }() } struct DeviceTools { static let isIphoneX: Bool = { var isIphoneSeries = false if UIDevice.isPhone(),#available(iOS 11,*) { if (UIApplication.shared.delegate!.window!!.safeAreaInsets.bottom > 0) { isIphoneSeries = true return isIphoneSeries } } return isIphoneSeries }() } public struct Simulator { public static var isRunning: Bool = { #if targetEnvironment(simulator) return true #else return false #endif // #if (arch(i386) || arch(x86_64)) && os(iOS) // return true // #else // return false // #endif }() }
mit
23d27d6dc89db44d34554d7f658f6ba4
21.1875
85
0.525352
4.722838
false
false
false
false
box/box-ios-sdk
Sources/Responses/WebhookItem.swift
1
1560
// // WebhookItem.swift // BoxSDK-iOS // // Created by Sujay Garlanka on 8/29/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Files, folders, or web links associated with a webhook. public enum WebhookItem: BoxModel { // MARK: - BoxModel public var rawData: [String: Any] { switch self { case let .folder(folder): return folder.rawData case let .file(file): return file.rawData } } /// Folder type case folder(Folder) /// File type case file(File) /// Initializer. /// /// - Parameter json: JSON dictionary. /// - Throws: Decoding error. public init(json: [String: Any]) throws { guard let type = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } switch type { case "file": let file = try File(json: json) self = .file(file) case "folder": let folder = try Folder(json: json) self = .folder(folder) default: throw BoxCodingError(message: .valueMismatch(key: "type", value: type, acceptedValues: ["file", "folder"])) } } } extension WebhookItem: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .folder(folder): return "folder \(String(describing: folder.name))" case let .file(file): return "file \(String(describing: file.name))" } } }
apache-2.0
21c89a5dbd2e3545c91bb5d631c10977
24.983333
119
0.568954
4.179625
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_fixed/00519-void.swift
65
657
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import Foundation var d { init(f, b : NSObject { } struct B<T where H.c: NSObject { deinit { print() -> (f: d where I) { e = { } } protocol e = e: C { } class A { return g<T : AnyObject, f: A { let c, AnyObject.c = D> String = B<(") } } typealias e = F>(self
apache-2.0
a7cd4b741240764891a94037a9caf98e
24.269231
79
0.686454
3.236453
false
false
false
false
tlax/looper
looper/View/Camera/Preview/VCameraPreviewPlayerTimerSlider.swift
1
5977
import UIKit class VCameraPreviewPlayerTimerSlider:UIView { private weak var controller:CCameraPreview! private weak var viewThumb:UIImageView! private weak var layoutTrackTop:NSLayoutConstraint! private weak var layoutTrackWidth:NSLayoutConstraint! private weak var layoutThumbLeft:NSLayoutConstraint! private weak var layoutInsideTrackWidth:NSLayoutConstraint! private var usableWidth:CGFloat private let timeSpan:TimeInterval private let thumbWidth_2:CGFloat private let kMinTime:TimeInterval = 1 private let kMaxTime:TimeInterval = 30 private let kTrackHeight:CGFloat = 2 private let kThumbWidth:CGFloat = 40 init(controller:CCameraPreview) { usableWidth = 0 timeSpan = kMaxTime - kMinTime thumbWidth_2 = kThumbWidth / 2.0 super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let track:UIView = UIView() track.isUserInteractionEnabled = false track.translatesAutoresizingMaskIntoConstraints = false track.clipsToBounds = true track.backgroundColor = UIColor(white:0.94, alpha:1) track.layer.cornerRadius = kTrackHeight / 2.0 let insideTrack:UIView = UIView() insideTrack.isUserInteractionEnabled = false insideTrack.clipsToBounds = true insideTrack.backgroundColor = UIColor.genericLight insideTrack.translatesAutoresizingMaskIntoConstraints = false let viewThumb:UIImageView = UIImageView() viewThumb.isUserInteractionEnabled = true viewThumb.translatesAutoresizingMaskIntoConstraints = false viewThumb.clipsToBounds = true viewThumb.contentMode = UIViewContentMode.center self.viewThumb = viewThumb track.addSubview(insideTrack) addSubview(track) addSubview(viewThumb) NSLayoutConstraint.equalsVertical( view:viewThumb, toView:self) NSLayoutConstraint.width( view:viewThumb, constant:kThumbWidth) layoutThumbLeft = NSLayoutConstraint.leftToLeft( view:viewThumb, toView:self) NSLayoutConstraint.equalsVertical( view:insideTrack, toView:track) NSLayoutConstraint.leftToLeft( view:insideTrack, toView:track) layoutInsideTrackWidth = NSLayoutConstraint.width( view:insideTrack) layoutTrackTop = NSLayoutConstraint.topToTop( view:track, toView:self) NSLayoutConstraint.height( view:track, constant:kTrackHeight) NSLayoutConstraint.leftToLeft( view:track, toView:self, constant:thumbWidth_2) layoutTrackWidth = NSLayoutConstraint.width( view:track) thumbNormal() } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY let remainHeight:CGFloat = height - kTrackHeight usableWidth = width - kThumbWidth let marginTop:CGFloat = remainHeight / 2.0 let addedTime:TimeInterval = controller.currentTime - kMinTime let percentage:CGFloat = CGFloat(addedTime / timeSpan) var percentageWidth:CGFloat = percentage * usableWidth if percentageWidth > usableWidth { percentageWidth = usableWidth } else if percentageWidth < 0 { percentageWidth = 0 } layoutTrackTop.constant = marginTop layoutTrackWidth.constant = usableWidth layoutThumbLeft.constant = percentageWidth layoutInsideTrackWidth.constant = percentageWidth DispatchQueue.main.async { [weak self] in self?.controller.viewPreview.viewPlayer.viewTimer.print() } super.layoutSubviews() } override func touchesBegan(_ touches:Set<UITouch>, with event:UIEvent?) { thumbSelected() guard let touch:UITouch = touches.first, let view:UIView = touch.view else { return } if view !== viewThumb { updateLocation(touch:touch) } } override func touchesMoved(_ touches:Set<UITouch>, with event:UIEvent?) { guard let touch:UITouch = touches.first else { return } updateLocation(touch:touch) } override func touchesCancelled(_ touches:Set<UITouch>, with event:UIEvent?) { thumbNormal() } override func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?) { thumbNormal() } //MARK: private private func updateLocation(touch:UITouch) { let touchLocation:CGPoint = touch.location(in:self) let touchX:CGFloat = touchLocation.x let usableX:CGFloat = touchX - thumbWidth_2 var xPercent:CGFloat = usableX / usableWidth if xPercent > 1 { xPercent = 1 } else if xPercent < 0 { xPercent = 0 } controller.currentTime = round((TimeInterval(xPercent) * timeSpan) + kMinTime) setNeedsLayout() } private func thumbSelected() { viewThumb.image = #imageLiteral(resourceName: "assetCameraSliderSelected") } private func thumbNormal() { viewThumb.image = #imageLiteral(resourceName: "assetCameraSlider") } }
mit
c15164425bdfc0430aa2409b7ed7797c
28.156098
86
0.605822
5.730585
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/User/CitysSelectViewController.swift
2
4272
// // CitysSelectViewController.swift // viossvc // // Created by 木柳 on 2016/11/25. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class CitySelectedCell: OEZTableViewCell { @IBOutlet weak var cityNameLabeL: UILabel! @IBOutlet weak var citySelectBtn: UIButton! } class CitysSelectViewController: BaseTableViewController { lazy var citys: NSMutableDictionary = { let path = NSBundle.mainBundle().pathForResource("city", ofType: "plist") let cityDic = NSMutableDictionary.init(contentsOfFile: path!) return cityDic! }() typealias selectCityBlock = (cityName: String) ->Void var keys: [AnyObject]? var selectIndex: NSIndexPath? var cityName: String? var selectCity = selectCityBlock?() override func viewDidLoad() { super.viewDidLoad() initData() initNav() initIndexView() } //MARK: --Data func initData() { keys = citys.allKeys.sort({ (obj1: AnyObject, obj2: AnyObject) -> Bool in let str1 = obj1 as? String let str2 = obj2 as? String return str1?.compare(str2!).rawValue < 0 }) for (section,key) in keys!.enumerate() { let values = citys.valueForKey(key as! String) as! NSMutableArray for (row,value) in values.enumerate() { if value as? String == cityName{ selectIndex = NSIndexPath.init(forRow: row, inSection: section) break } } if selectIndex != nil { break } } if selectIndex == nil { selectIndex = NSIndexPath.init(forRow: 0, inSection: 0) } } //MARK: --索引 func initIndexView() { tableView.sectionIndexColor = UIColor(RGBHex: 0x666666) } //MARK: --nav func initNav() { navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "确定", style: .Plain, target: self, action: #selector(rightItemTapped)) } func rightItemTapped() { let values = citys.valueForKey(keys![selectIndex!.section] as! String) as! NSMutableArray cityName = values[selectIndex!.row] as? String if selectCity != nil { selectCity!(cityName: cityName!) } navigationController?.popViewControllerAnimated(true) } //Mark: --table's delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return keys == nil ? 0 : keys!.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let values = citys.valueForKey(keys![section] as! String) as! NSMutableArray return values.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return keys![section] as? String } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let values = citys.valueForKey(keys![indexPath.section] as! String) as! NSMutableArray let cell: CitySelectedCell = tableView.dequeueReusableCellWithIdentifier("CitySelectedCell") as! CitySelectedCell cell.cityNameLabeL.text = values[indexPath.row] as? String cell.citySelectBtn.selected = (selectIndex != nil) && (selectIndex == indexPath) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let lastIndex:NSIndexPath = selectIndex == nil ? indexPath : selectIndex! selectIndex = indexPath tableView.reloadRowsAtIndexPaths([lastIndex,selectIndex!], withRowAnimation: .Automatic) } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return keys as? [String] } override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { let indexPath = NSIndexPath.init(forRow: 0, inSection: index) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) return index } }
apache-2.0
df9a6aeb071302112c4bd257b6317e15
36.017391
142
0.640122
4.978947
false
false
false
false
Michael-Vorontsov/ResultPromises
Example/iOS/iOS/ViewController.swift
1
6113
// // ViewController.swift // iOS // // Created by Mykhailo Vorontsov on 9/8/17. // Copyright © 2017 Mykhailo Vorontsov. All rights reserved. // import UIKit import ResultPromises final class ViewController: UITableViewController { enum ViewControllerError: Error { case imageConvertion case simulatedError } let session = URLSession.shared var reloadCount = 0 var users = [User]() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) reloadData() } @IBAction func pullToRefreshAction(_ sender: Any) { //! Launch reload function, with artificial delay 2.0 sconds, and artificial failure on every 5th load. reloadData(delay: 2.0, errorSimulationCounter: 5) //! Replace line above with line below to launch native-style reload procedure // oldReload() //! Replace first line of this fucntion with line below to run request without artificial errors and delays. // reloadData() } func resetUsers() { tableView.beginUpdates() if users.count > 0 { tableView.deleteSections([0], with: .fade) } users = [] tableView.endUpdates() } //* Reload data old manner func oldReload() { let request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/users")!) session.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() if let error = error { self.showError(message: error.localizedDescription) return } let httpResponse = response as! HTTPURLResponse guard (200...299).contains( httpResponse.statusCode) else { self.showError(message: "Code: \(httpResponse.statusCode)") return } guard let data = data else { self.showError(message: "Data is Empty!") return } let decoder = JSONDecoder() do { let users = try decoder.decode([User].self, from: data) self.users = users self.tableView.reloadData() } catch { self.showError(message: error.localizedDescription) } } }.resume() } // Reload data simples way func reloadData() { self.tableView.refreshControl?.beginRefreshing() resetUsers() URLRequest.requestFor(path: "https://jsonplaceholder.typicode.com/users") .then {(request) -> Promise<[User]> in return self.session.fetchRESTObject(from: request) } .onComplete { (_) in self.tableView.refreshControl?.endRefreshing() } .onSuccess { (users) in self.users = users self.tableView.reloadData() } .onError { (error) in self.showError(message: error.localizedDescription) } } //* Reload data, with delay, and failing with error func reloadData(delay: Double, errorSimulationCounter: Int) { self.tableView.refreshControl?.beginRefreshing() resetUsers() URLRequest.requestFor(path: "https://jsonplaceholder.typicode.com/users") .then {(request) -> Promise<[User]> in return self.session.fetchRESTObject(from: request) } // Add delay for better illustration .then{ (users) -> Promise<[User]> in let promise = Promise<[User]>() DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + delay) { promise.resolve(result: users) } return promise } // Add probability to fail .then{ (users) -> [User] in self.reloadCount += 1 if 0 == self.reloadCount % errorSimulationCounter { self.title = "Error simulation" throw ViewControllerError.simulatedError } self.title = "Pull \(5 - self.reloadCount % errorSimulationCounter) more time to get error" return users } .onComplete { (_) in self.tableView.refreshControl?.endRefreshing() } .onSuccess { (users) in self.users = users self.tableView.reloadData() } .onError { (error) in self.showError(message: error.localizedDescription) } } fileprivate func showError(message: String) { let alert = UIAlertController(title: "Network connection required!", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } //MARK: TableView override func numberOfSections(in tableView: UITableView) -> Int { return users.count > 0 ? 1 : 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let user = users[indexPath.row] cell.textLabel?.text = user.name cell.detailTextLabel?.text = user.email // Load user avatars let name = user.username cell.tag = name.hashValue URLRequest.requestFor(path: "https://robohash.org/\(name)") .then {(request) -> Promise<Data> in self.session.fetchData(from: request) } .then { (data) -> UIImage in guard let image = UIImage(data: data) else { throw ViewControllerError.imageConvertion } return image } // Add delay for better illustration .then{ (image) -> Promise<UIImage> in let promise = Promise<UIImage>() let rand = (Double(arc4random()) / Double(RAND_MAX)) + 0.5 DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + rand) { promise.resolve(result: image) } return promise } .onSuccess { (image) in // Cell can be reused with different user already if cell.tag == name.hashValue { cell.imageView?.image = image cell.setNeedsLayout() } } return cell } }
mit
150f41fcc075296939ac30e419c12594
30.34359
114
0.629581
4.487518
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/Backup/RecoveryPhrase/RecoveryPhraseView/RecoveryPhraseView.swift
1
2487
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit import RxCocoa import RxSwift final class RecoveryPhraseView: UIView { // MARK: - Public Properties var viewModel: RecoveryPhraseViewModel! { willSet { disposeBag = DisposeBag() } didSet { viewModel.words .bindAndCatch(to: rx.mnemonicContent) .disposed(by: disposeBag) clipboardButtonView.viewModel = viewModel.copyButtonViewModel } } // MARK: Private IBOutlets (UILabel) @IBOutlet private var firstLabel: UILabel! @IBOutlet private var secondLabel: UILabel! @IBOutlet private var thirdLabel: UILabel! @IBOutlet private var fourthLabel: UILabel! @IBOutlet private var fifthLabel: UILabel! @IBOutlet private var sixthLabel: UILabel! @IBOutlet private var seventhLabel: UILabel! @IBOutlet private var eigthLabel: UILabel! @IBOutlet private var ninthLabel: UILabel! @IBOutlet private var tenthLabel: UILabel! @IBOutlet private var eleventhLabel: UILabel! @IBOutlet private var twelfthLabel: UILabel! // MARK: - Private IBOutlets (Other) @IBOutlet private var numberedLabels: [UILabel]! @IBOutlet private var clipboardButtonView: ButtonView! // MARK: - Private Properties fileprivate var labels: [UILabel] { [ firstLabel, secondLabel, thirdLabel, fourthLabel, fifthLabel, sixthLabel, seventhLabel, eigthLabel, ninthLabel, tenthLabel, eleventhLabel, twelfthLabel ] } private var disposeBag = DisposeBag() // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { fromNib(in: .module) clipsToBounds = true numberedLabels.forEach { $0.textColor = .mutedText } layer.cornerRadius = 8.0 backgroundColor = .background } } extension Reactive where Base: RecoveryPhraseView { fileprivate var mnemonicContent: Binder<[LabelContent]> { Binder(base) { view, payload in payload.enumerated().forEach { value in view.labels[value.0].content = value.1 } } } }
lgpl-3.0
493ed9b1ac4045987505e5c2fbe87d47
25.446809
73
0.615849
4.884086
false
false
false
false
Daltron/BigBoard
Example/Tests/BigBoardTestsHelper.swift
1
1331
// // BigBoardTestsHelper.swift // BigBoard // // Created by Dalton Hinterscher on 5/17/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import ObjectMapper class BigBoardTestsHelper: NSObject { class func sampleDateRange() -> BigBoardHistoricalDateRange { return BigBoardHistoricalDateRange(startDate: sampleStartDate(), endDate: sampleEndDate()) } class func sampleStartDate() -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) var dateComponents = DateComponents() dateComponents.year = 2015 dateComponents.month = 6 dateComponents.day = 4 return calendar.date(from: dateComponents)! } class func sampleEndDate() -> Date { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) var dateComponents = DateComponents() dateComponents.year = 2015 dateComponents.month = 6 dateComponents.day = 11 return calendar.date(from: dateComponents)! } class func sampleStock() -> BigBoardStock { let sampleStock = BigBoardStock(map: Map(mappingType: .toJSON, JSON: [:])) sampleStock!.symbol = "GOOG" sampleStock!.name = "GOOGLE" return sampleStock! } }
mit
f2616fd0feb84347827ffba48020e0b4
27.297872
98
0.646617
5.037879
false
false
false
false
brentsimmons/Evergreen
Secrets/Sources/Secrets/CredentialsManager.swift
1
3776
// // CredentialsManager.swift // NetNewsWire // // Created by Maurice Parker on 5/5/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import Foundation public struct CredentialsManager { private static var keychainGroup: String? = { guard let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String else { return nil } let appIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as! String let appGroupSuffix = appGroup.suffix(appGroup.count - 6) return "\(appIdentifierPrefix)\(appGroupSuffix)" }() public static func storeCredentials(_ credentials: Credentials, server: String) throws { var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock, kSecAttrAccount as String: credentials.username, kSecAttrServer as String: server] if credentials.type != .basic { query[kSecAttrSecurityDomain as String] = credentials.type.rawValue } if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } let secretData = credentials.secret.data(using: String.Encoding.utf8)! query[kSecValueData as String] = secretData let status = SecItemAdd(query as CFDictionary, nil) switch status { case errSecSuccess: return case errSecDuplicateItem: break default: throw CredentialsError.unhandledError(status: status) } var deleteQuery = query deleteQuery.removeValue(forKey: kSecAttrAccessible as String) SecItemDelete(deleteQuery as CFDictionary) let addStatus = SecItemAdd(query as CFDictionary, nil) if addStatus != errSecSuccess { throw CredentialsError.unhandledError(status: status) } } public static func retrieveCredentials(type: CredentialsType, server: String, username: String) throws -> Credentials? { var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, kSecAttrAccount as String: username, kSecAttrServer as String: server, kSecMatchLimit as String: kSecMatchLimitOne, kSecReturnAttributes as String: true, kSecReturnData as String: true] if type != .basic { query[kSecAttrSecurityDomain as String] = type.rawValue } if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) guard status != errSecItemNotFound else { return nil } guard status == errSecSuccess else { throw CredentialsError.unhandledError(status: status) } guard let existingItem = item as? [String : Any], let secretData = existingItem[kSecValueData as String] as? Data, let secret = String(data: secretData, encoding: String.Encoding.utf8) else { return nil } return Credentials(type: type, username: username, secret: secret) } public static func removeCredentials(type: CredentialsType, server: String, username: String) throws { var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, kSecAttrAccount as String: username, kSecAttrServer as String: server, kSecMatchLimit as String: kSecMatchLimitOne, kSecReturnAttributes as String: true, kSecReturnData as String: true] if type != .basic { query[kSecAttrSecurityDomain as String] = type.rawValue } if let securityGroup = keychainGroup { query[kSecAttrAccessGroup as String] = securityGroup } let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw CredentialsError.unhandledError(status: status) } } }
mit
496a6578f27308a11cb1a29615a7c603
29.443548
121
0.726887
4.472749
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressTest/ViewRelated/Post/Views/PostCardStatusViewModelTests.swift
1
5570
@testable import WordPress import Nimble private typealias ButtonGroups = PostCardStatusViewModel.ButtonGroups class PostCardStatusViewModelTests: XCTestCase { private var contextManager: TestContextManager! private var context: NSManagedObjectContext! override func setUp() { super.setUp() contextManager = TestContextManager() context = contextManager.newDerivedContext() } override func tearDown() { context = nil contextManager = nil super.tearDown() } func testExpectedButtonGroupsForVariousPostAttributeCombinations() { // Arrange let expectations: [(String, Post, ButtonGroups)] = [ ( "Draft with remote", PostBuilder(context).drafted().withRemote().build(), ButtonGroups(primary: [.edit, .view, .more], secondary: [.publish, .duplicate, .trash]) ), ( "Draft that was not uploaded to the server", PostBuilder(context).drafted().with(remoteStatus: .failed).build(), ButtonGroups(primary: [.edit, .publish, .more], secondary: [.duplicate, .trash]) ), ( "Draft with remote and confirmed local changes", PostBuilder(context).drafted().withRemote().with(remoteStatus: .failed).confirmedAutoUpload().build(), ButtonGroups(primary: [.edit, .cancelAutoUpload, .more], secondary: [.publish, .duplicate, .trash]) ), ( "Draft with remote and canceled local changes", PostBuilder(context).drafted().withRemote().with(remoteStatus: .failed).confirmedAutoUpload().cancelledAutoUpload().build(), ButtonGroups(primary: [.edit, .publish, .more], secondary: [.duplicate, .trash]) ), ( "Local published draft with confirmed auto-upload", PostBuilder(context).published().with(remoteStatus: .failed).confirmedAutoUpload().build(), ButtonGroups(primary: [.edit, .cancelAutoUpload, .more], secondary: [.duplicate, .moveToDraft, .trash]) ), ( "Local published draft with canceled auto-upload", PostBuilder(context).published().with(remoteStatus: .failed).build(), ButtonGroups(primary: [.edit, .publish, .more], secondary: [.duplicate, .moveToDraft, .trash]) ), ( "Published post", PostBuilder(context).published().withRemote().build(), ButtonGroups(primary: [.edit, .view, .more], secondary: [.stats, .share, .duplicate, .moveToDraft, .trash]) ), ( "Published post with local confirmed changes", PostBuilder(context).published().withRemote().with(remoteStatus: .failed).confirmedAutoUpload().build(), ButtonGroups(primary: [.edit, .cancelAutoUpload, .more], secondary: [.stats, .share, .duplicate, .moveToDraft, .trash]) ), ( "Post with the max number of auto uploades retry reached", PostBuilder(context).with(remoteStatus: .failed) .with(autoUploadAttemptsCount: 3).confirmedAutoUpload().build(), ButtonGroups(primary: [.edit, .retry, .more], secondary: [.publish, .duplicate, .moveToDraft, .trash]) ), ] // Act and Assert expectations.forEach { scenario, post, expectedButtonGroups in let viewModel = PostCardStatusViewModel(post: post, isInternetReachable: false) guard viewModel.buttonGroups == expectedButtonGroups else { let reason = "The scenario \"\(scenario)\" failed. " + " Expected buttonGroups to be: \(expectedButtonGroups.prettifiedDescription)." + " Actual: \(viewModel.buttonGroups.prettifiedDescription)" XCTFail(reason) return } } } /// If the post fails to upload and there is internet connectivity, show "Upload failed" message /// func testReturnFailedMessageIfPostFailedAndThereIsConnectivity() { let post = PostBuilder(context).revision().with(remoteStatus: .failed).confirmedAutoUpload().build() let viewModel = PostCardStatusViewModel(post: post, isInternetReachable: true) expect(viewModel.status).to(equal(i18n("Upload failed"))) expect(viewModel.statusColor).to(equal(.error)) } /// If the post fails to upload and there is NO internet connectivity, show a message that we'll publish when the user is back online /// func testReturnWillUploadLaterMessageIfPostFailedAndThereIsConnectivity() { let post = PostBuilder(context).revision().with(remoteStatus: .failed).confirmedAutoUpload().build() let viewModel = PostCardStatusViewModel(post: post, isInternetReachable: false) expect(viewModel.status).to(equal(i18n("We'll publish the post when your device is back online."))) expect(viewModel.statusColor).to(equal(.warning)) } } private extension ButtonGroups { var prettifiedDescription: String { return "{ primary: \(primary.prettifiedDescription), secondary: \(secondary.prettifiedDescription) }" } } private extension Array where Element == PostCardStatusViewModel.Button { var prettifiedDescription: String { return "[" + map { String(describing: $0) }.joined(separator: ", ") + "]" } }
gpl-2.0
262b4e2ad5b907c2846fc0d920fe92b4
44.655738
140
0.620287
5.325048
false
true
false
false
bridger/NumberPad
DigitRecognizer/AppDelegate.swift
1
7855
// // AppDelegate.swift // NumberPad // // Created by Bridger Maxwell on 12/13/14. // Copyright (c) 2014 Bridger Maxwell. All rights reserved. // import UIKit import DigitRecognizerSDK let filePrefix = "SavedLibraries-" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { /* To add another digit: Change the storyboard to have another character in the segmented control. Make sure onlySaveNormalizedData. Then, run the app and input a bunch of samples for the new digit. Once you are done, copy the resulting file from the Documents directory. It is the new "training" file. Replace the existing train file. Now, temporarily set onlySaveNormalizedData to true. Launch the app and then send it to the background to re-save the training data as a normalized set. Replace the normalized.json file with the resulting file. */ let onlySaveNormalizedData = false var window: UIWindow? var library: DigitSampleLibrary = DigitSampleLibrary() var digitRecognizer: DigitRecognizer = DigitRecognizer() class func sharedAppDelegate() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { if let lastSave = newestSavedData() { let path = self.documentsDirectory().appendingPathComponent(lastSave)!.path loadData(path: path, legacyBatchID: "unknown") } else { loadData(path: Bundle.main.path(forResource: "bridger_all", ofType: "json")!, legacyBatchID: "bridger") loadData(path: Bundle.main.path(forResource: "ujipenchars2", ofType: "json")!, legacyBatchID: "ujipen2") } return true } func applicationWillResignActive(_ application: UIApplication) { saveData() #if (arch(i386) || arch(x86_64)) saveImagesAsBinary(library: library.samples, folder: self.documentsDirectory(), testPercentage: 0.1) #endif } func documentsDirectory() -> NSURL { let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String return NSURL(fileURLWithPath: path) } func saveData() { let dataToSave = self.library.jsonDataToSave() let saveNumber: Int if let lastSave = newestSavedData(), let lastNumber = Int(lastSave.substring(from: filePrefix.endIndex)) { saveNumber = lastNumber + 1 } else { saveNumber = 1 } let documentName = self.documentsDirectory().appendingPathComponent(filePrefix + String(saveNumber))! do { let jsonObject = try JSONSerialization.data(withJSONObject: dataToSave, options: []) try jsonObject.write(to: documentName) } catch let error as NSError { print("Couldn't save data \(error)") } } func loadData(path: String, legacyBatchID: String) { if let jsonLibrary = DigitSampleLibrary.jsonLibraryFromFile(path: path) { self.library.loadData(jsonData: jsonLibrary, legacyBatchID: legacyBatchID) } } func newestSavedData() -> String? { let contents: [String]? do { contents = try FileManager.default.contentsOfDirectory(atPath: self.documentsDirectory().path!) } catch _ { contents = nil } if let contents = contents { let filtered = contents.filter({ string in return string.hasPrefix(filePrefix) }).sorted(by: { (string1, string2) in return string1.localizedStandardCompare(string2) == ComparisonResult.orderedAscending }) return filtered.last } return nil } func saveImagesAsBinary(library: DigitSampleLibrary.PrototypeLibrary, folder: NSURL, testPercentage: CGFloat) { guard let trainImagesFile = OutputStream(toFileAtPath: folder.appendingPathComponent("digit-recognizer-images-train")!.path, append: false) else { fatalError("Couldn't open output file") } trainImagesFile.open() defer { trainImagesFile.close() } guard let trainLabelsFile = OutputStream(toFileAtPath: folder.appendingPathComponent("digit-recognizer-labels-train")!.path, append: false) else { fatalError("Couldn't open output file") } trainLabelsFile.open() defer { trainLabelsFile.close() } guard let testImagesFile = OutputStream(toFileAtPath: folder.appendingPathComponent("digit-recognizer-images-test")!.path, append: false) else { fatalError("Couldn't open output file") } testImagesFile.open() defer { testImagesFile.close() } guard let testLabelsFile = OutputStream(toFileAtPath: folder.appendingPathComponent("digit-recognizer-labels-test")!.path, append: false) else { fatalError("Couldn't open output file") } testLabelsFile.open() defer { testLabelsFile.close() } let imageSize = ImageSize(width: 28, height: 28) var bitmapData = Array<UInt8>(repeating: 0, count: Int(imageSize.width * imageSize.height)) bitmapData[0] = 0 // To silence the "never mutated" warning let bitmapPointer = UnsafeMutableRawPointer(mutating: bitmapData) var labelToWrite = Array<UInt8>(repeating: 0, count: 1) var trainWriteCount = 0 var testWriteCount = 0 writeloop: for (label, samples) in library { guard let byteLabel = self.digitRecognizer.labelStringToByte[label] else { print("Not writing images for unknown label: \(label)") continue } labelToWrite[0] = byteLabel for digit in samples { guard let normalizedStrokes = DigitRecognizer.normalizeDigit(inputDigit: digit.strokes) else { continue } let train_batch = CGFloat(arc4random_uniform(1000)) / 1000.0 > testPercentage if (train_batch) { let positiveAngles = 8 // this many on the positive and also the negative side var maxAngle = 0.22 / CGFloat(positiveAngles) if (label == "/" || label == "1") { maxAngle /= 2 } for angleBatch in -positiveAngles...positiveAngles { let angle = CGFloat(angleBatch) * maxAngle guard renderToContext(normalizedStrokes: normalizedStrokes, size: imageSize, angle: angle, data: bitmapPointer) != nil else { fatalError("Couldn't render image") } trainLabelsFile.write(labelToWrite, maxLength: 1) trainImagesFile.write(bitmapData, maxLength: bitmapData.count) trainWriteCount += 1 } } else { guard renderToContext(normalizedStrokes: normalizedStrokes, size: imageSize, data: bitmapPointer) != nil else { fatalError("Couldn't render image") } testLabelsFile.write(labelToWrite, maxLength: 1) testImagesFile.write(bitmapData, maxLength: bitmapData.count) testWriteCount += 1 } } } print("Wrote \(trainWriteCount) training and \(testWriteCount) testing binary images to \(folder.path!)") } }
apache-2.0
dbf75931f14062634c5bcc3e6ac0efeb
42.638889
527
0.618842
5.201987
false
true
false
false
vitkuzmenko/TableCollectionStructured
Source/Managers/CollectionStructuredController.swift
1
9302
// // structuredController.swift // Tablestructured // // Created by Vitaliy Kuzmenko on 06/10/16. // Copyright © 2016 Vitaliy Kuzmenko. All rights reserved. // import UIKit public enum CollectionViewReloadRule { case none, animated, noAnimation } open class CollectionStructuredController: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { open weak var collectionView: UICollectionView! { didSet { collectionView.dataSource = self collectionView.delegate = self configureCollectionView() } } open var structure: [StructuredSection] = [] private var previousStructure: [StructuredSection] = [] { didSet { structure.forEach { section in section.rows.forEach { object in if let invalidatableCell = object.value as? StructuredCellInvalidatable { invalidatableCell.invalidated() } } } } } open func indexPath<T: StructuredCell>(for object: T) -> IndexPath? { let obj = StructuredObject(value: object) return structure.indexPath(of: obj) } open func object(at indexPath: IndexPath) -> Any { return structure[indexPath.section][indexPath.row] } open func set(structure: [StructuredSection], rule: CollectionViewReloadRule = .noAnimation) { beginBuilding() self.structure = structure buildStructure(rule: rule) } open func beginBuilding() { previousStructure = structure structure = [] } open func newSection(identifier: String? = nil) -> StructuredSection { return StructuredSection(identifier: identifier) } open func append(section: StructuredSection) { section.isClosed = true if structure.contains(section) { fatalError("TableCollectionStructured: Table structure is contains section with \"\(section.identifier!)\" identifier") } if section.identifier == nil { section.identifier = String(format: "#Section%d", structure.count) } structure.append(section) } open func append(section: inout StructuredSection, new identifier: String? = nil) { append(section: section) section = StructuredSection(identifier: identifier) } open func configureCollectionView() { } open func buildStructure(rule: CollectionViewReloadRule = .noAnimation) { switch rule { case .none: break case .animated: self.performReload() case .noAnimation: self.reloadData() } } open func reloadData() { collectionView.reloadData() } open func performReload(completion: ((Bool) -> Void)? = nil) { let diff = StructuredDifference(from: previousStructure, to: structure) if !diff.reloadConstraint.isEmpty || collectionView.window == nil { return reloadData() } collectionView.performBatchUpdates({ for movement in diff.sectionsToMove { self.collectionView.moveSection(movement.from, toSection: movement.to) } self.collectionView.deleteSections(diff.sectionsToDelete) self.collectionView.insertSections(diff.sectionsToInsert) for movement in diff.rowsToMove { self.collectionView.moveItem(at: movement.from, to: movement.to) } self.collectionView.deleteItems(at: diff.rowsToDelete) self.collectionView.insertItems(at: diff.rowsToInsert) }, completion: { [weak self] f in self?.collectionView?.reloadData() completion?(f) }) } public func numberOfSections(in collectionView: UICollectionView) -> Int { return structure.count } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return structure[section].count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let model = object(at: indexPath) as? StructuredCell else { fatalError("Model should be StructuredCellModelProtocol") } return collectionView.dequeueReusableCell(withModel: model, for: indexPath) } open func collectionView(_ collectionView: UICollectionView, reuseIdentifierFor object: Any) -> String? { var identifier: String? if let object = object as? String { identifier = object } return identifier } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { return UICollectionReusableView() } open func collectionView(_ collectionView: UICollectionView, configure cell: UICollectionViewCell, for object: Any, at indexPath: IndexPath) { } open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let object = self.object(at: indexPath) as? StructuredCellWillDisplay { object.willDisplay?() } } @available(*, deprecated, message: "") open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, for object: Any, forItemAt indexPath: IndexPath) { } open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? StructuredCellDidEndDisplay { cell.didEndDisplay?() } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if let object = self.object(at: indexPath) as? StructuredCellDynamicSize { return object.size(for: collectionView) } else { return (collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? .zero } } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeFor object: Any, at: IndexPath) -> CGSize { return (collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? .zero } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let object = self.object(at: indexPath) as? StructuredCellSelectable, let cell = collectionView.cellForItem(at: indexPath) { _ = object.didSelect?(cell) } } open func collectionView(_ collectionView: UICollectionView, didSelectCell identifier: String, object: Any, at indexPath: IndexPath) { } open func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return false } open func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { } open func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath { return proposedIndexPath } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { } open func scrollViewDidZoom(_ scrollView: UIScrollView) { } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { } open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { } open func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { } open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nil } open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { } open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { } open func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return true } open func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { } open func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) { } }
apache-2.0
386614b9c296a0970960762bab7da2ea
33.448148
192
0.648317
6.004519
false
false
false
false
algolia/algoliasearch-client-swift
Tests/AlgoliaSearchClientTests/Doc/APIParameters/APIParameters+Personalization.swift
1
2157
// // APIParameters+Personalization.swift // // // Created by Vladislav Fitc on 07/07/2020. // import Foundation import AlgoliaSearchClient extension APIParameters { //MARK: - Personalization func personalization() { func enablePersonalization() { /* enablePersonalization = true|false */ func enable_personalization() { let query = Query("query") .set(\.enablePersonalization, to: true) index.search(query: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } func enable_personalization_with_user_token() { let query = Query("query") .set(\.enablePersonalization, to: true) .set(\.userToken, to: "123456") index.search(query: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } } func personalizationImpact() { /* personalizationImpact = personalization_impact */ func personalization_impact() { let query = Query("query") .set(\.personalizationImpact, to: 20) index.search(query: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } } func userToken() { /* userToken = 'YourCustomUserId' */ func set_user_token() { let query = Query("query") .set(\.userToken, to: "123456") index.search(query: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } func set_user_token_with_personalization() { let query = Query("query") .set(\.enablePersonalization, to: true) .set(\.userToken, to: "123456") index.search(query: query) { result in if case .success(let response) = result { print("Response: \(response)") } } } } } }
mit
f877a47862904afe5a5767f129d948ec
24.987952
53
0.525267
4.550633
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Library/MFMailComposeViewController.swift
1
973
import Foundation import Library import MessageUI import UIKit internal extension MFMailComposeViewController { static func support() -> MFMailComposeViewController { let mcvc = MFMailComposeViewController() mcvc.setSubject( Strings.support_email_subject() ) mcvc.setToRecipients([Strings.support_email_to()]) let app = Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "" let os = UIDevice.current.systemVersion let user = (AppEnvironment.current.currentUser?.id).flatMap(String.init) ?? "Logged out" let body = "\(Strings.support_email_body())\n\(user) | \(app) | \(os) | \(deviceModel())\n" mcvc.setMessageBody(body, isHTML: false) return mcvc } } private func deviceModel() -> String { var size: Int = 0 sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](repeating: 0, count: Int(size)) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String(cString: machine) }
apache-2.0
46d7db637afc608c892d8f3d75f8d605
28.484848
95
0.696814
4.088235
false
false
false
false
ejeinc/MetalScope
Sources/InterfaceOrientationUpdater.swift
1
2942
// // InterfaceOrientationUpdater.swift // MetalScope // // Created by Jun Tanaka on 2017/01/31. // Copyright © 2017 eje Inc. All rights reserved. // import SceneKit import UIKit internal final class InterfaceOrientationUpdater { let orientationNode: OrientationNode private var isTransitioning = false private var deviceOrientationDidChangeNotificationObserver: NSObjectProtocol? init(orientationNode: OrientationNode) { self.orientationNode = orientationNode } deinit { stopAutomaticInterfaceOrientationUpdates() } func updateInterfaceOrientation() { orientationNode.updateInterfaceOrientation() } func updateInterfaceOrientation(with transitionCoordinator: UIViewControllerTransitionCoordinator) { isTransitioning = true transitionCoordinator.animate(alongsideTransition: { context in SCNTransaction.lock() SCNTransaction.begin() SCNTransaction.animationDuration = context.transitionDuration SCNTransaction.animationTimingFunction = context.completionCurve.caMediaTimingFunction SCNTransaction.disableActions = !context.isAnimated self.updateInterfaceOrientation() SCNTransaction.commit() SCNTransaction.unlock() }, completion: { _ in self.isTransitioning = false }) } func startAutomaticInterfaceOrientationUpdates() { guard deviceOrientationDidChangeNotificationObserver == nil else { return } UIDevice.current.beginGeneratingDeviceOrientationNotifications() let observer = NotificationCenter.default.addObserver(forName: .UIDeviceOrientationDidChange, object: nil, queue: .main) { [weak self] _ in guard UIDevice.current.orientation.isValidInterfaceOrientation, self?.isTransitioning == false else { return } self?.updateInterfaceOrientation() } deviceOrientationDidChangeNotificationObserver = observer } func stopAutomaticInterfaceOrientationUpdates() { guard let observer = deviceOrientationDidChangeNotificationObserver else { return } UIDevice.current.endGeneratingDeviceOrientationNotifications() NotificationCenter.default.removeObserver(observer) deviceOrientationDidChangeNotificationObserver = nil } } private extension UIViewAnimationCurve { var caMediaTimingFunction: CAMediaTimingFunction { let name: String switch self { case .easeIn: name = kCAMediaTimingFunctionEaseIn case .easeOut: name = kCAMediaTimingFunctionEaseOut case .easeInOut: name = kCAMediaTimingFunctionEaseInEaseOut case .linear: name = kCAMediaTimingFunctionLinear } return CAMediaTimingFunction(name: name) } }
mit
ed135fb0a17dd25cb291901624400d9f
29.635417
147
0.690581
6.699317
false
false
false
false
joemcbride/outlander-osx
src/Outlander/PresetLoader.swift
1
4018
// // PresetLoader.swift // Outlander // // Created by Joseph McBride on 1/20/17. // Copyright © 2017 Joe McBride. All rights reserved. // import Foundation @objc class PresetLoader : NSObject { class func newInstance(context:GameContext, fileSystem:FileSystem) -> PresetLoader { return PresetLoader(context: context, fileSystem: fileSystem) } var context:GameContext var fileSystem:FileSystem init(context:GameContext, fileSystem:FileSystem) { self.context = context self.fileSystem = fileSystem } func load() { let configFile = self.context.pathProvider.profileFolder().stringByAppendingPathComponent("presets.cfg") if !self.fileSystem.fileExists(configFile) { setupDefaults() return } var data:String? do { data = try self.fileSystem.stringWithContentsOfFile(configFile, encoding: NSUTF8StringEncoding) } catch { return } if data == nil || data?.characters.count == 0 { return } self.context.presets.removeAll() let pattern = "^#preset \\{(.*?)\\} \\{(.*?)\\}(?:\\s\\{(.*?)\\})?$" let target = SwiftRegex(target: data!, pattern: pattern, options: [NSRegularExpressionOptions.AnchorsMatchLines, NSRegularExpressionOptions.CaseInsensitive]) let groups = target.allGroups() for group in groups { if group.count == 4 { let name = group[1] var color = group[2] var backgroundColor = "" var className = "" if group[3] != regexNoGroup { className = group[3] } var colors = color.componentsSeparatedByString(",") if(colors.count > 1) { color = colors[0] backgroundColor = colors[1] } let item = ColorPreset(name, color, className) item.backgroundColor = backgroundColor self.context.presets[item.name] = item } } if self.context.presets["exptracker"] == nil { self.add("exptracker", "#66FFFF") } } func save() { let configFile = self.context.pathProvider.profileFolder().stringByAppendingPathComponent("presets.cfg") var presets = "" let sorted = context.presets.sort { $0.0 < $1.0 } for (preset) in sorted { let name = preset.1.name let foreColor = preset.1.color let backgroundColor = preset.1.backgroundColor != nil ? preset.1.backgroundColor! : "" let className = preset.1.presetClass != nil ? preset.1.presetClass! : "" var color = foreColor if backgroundColor.characters.count > 0 { color = "\(color),\(backgroundColor)" } presets += "#preset {\(name)} {\(color)}" if className.characters.count > 0 { presets += " {\(className)}" } presets += "\n" } self.fileSystem.write(presets, toFile: configFile) } func setupDefaults() { self.add("automapper", "#66FFFF") self.add("chatter", "#66FFFF") self.add("creatures", "#FFFF00") self.add("roomdesc", "#cccccc") self.add("roomname", "#0000FF") self.add("scriptecho", "#66FFFF") self.add("scripterror", "#efefef", "#ff3300") self.add("scriptinfo", "#0066cc") self.add("scriptinput", "#acff2f") self.add("sendinput", "#acff2f") self.add("speech", "#66FFFF") self.add("thought", "#66FFFF") self.add("whisper", "#66FFFF") self.add("exptracker", "#66FFFF") } func add(name:String, _ color:String, _ backgroundColor:String? = nil) { let preset = ColorPreset(name, color, backgroundColor ?? "", "") self.context.presets[name] = preset } }
mit
6e287e45bc0d11a277508a1d8140b647
28.755556
165
0.549913
4.483259
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Binary Search/1150_Check If a Number Is Majority Element in a Sorted Array.swift
1
2884
// 1150_Check If a Number Is Majority Element in a Sorted Array // https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array/ // // Created by Honghao Zhang on 9/16/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element. // //A majority element is an element that appears more than N/2 times in an array of length N. // // // //Example 1: // //Input: nums = [2,4,5,5,5,5,5,6,6], target = 5 //Output: true //Explanation: //The value 5 appears 5 times and the length of the array is 9. //Thus, 5 is a majority element because 5 > 9/2 is true. //Example 2: // //Input: nums = [10,100,101,101], target = 101 //Output: false //Explanation: //The value 101 appears 2 times and the length of the array is 4. //Thus, 101 is not a majority element because 2 > 4/2 is false. // // //Note: // //1 <= nums.length <= 1000 //1 <= nums[i] <= 10^9 //1 <= target <= 10^9 // import Foundation class Num1150 { /// Use binary search to find the left and right index func isMajorityElement(_ nums: [Int], _ target: Int) -> Bool { let firstIndex = findFirstIndex(nums, target) let lastIndex = findLastIndex(nums, target) if firstIndex == -1 || lastIndex == -1 { return false } let count = lastIndex - firstIndex + 1 return count > nums.count / 2 } private func findFirstIndex(_ nums: [Int], _ target: Int) -> Int { if nums.count == 0 { return -1 } if nums.count == 1 { if nums[0] == target { return 0 } else { return -1 } } var start = 0 var end = nums.count - 1 while start + 1 < end { let mid = start + (end - start) / 2 if nums[mid] < target { start = mid } else if nums[mid] > target { end = mid } else { // to find the first index, move end end = mid } } if nums[start] == target { return start } else if nums[end] == target { return end } else { return -1 } } private func findLastIndex(_ nums: [Int], _ target: Int) -> Int { if nums.count == 0 { return -1 } if nums.count == 1 { if nums[0] == target { return 0 } else { return -1 } } var start = 0 var end = nums.count - 1 while start + 1 < end { let mid = start + (end - start) / 2 if nums[mid] < target { start = mid } else if nums[mid] > target { end = mid } else { // to find the last index, move start start = mid } } if nums[end] == target { return end } else if nums[start] == target { return start } else { return -1 } } }
mit
46ffe6074b00771518083eddbdec5a67
21.523438
132
0.554631
3.494545
false
false
false
false
tschob/AudioPlayerManager
AudioPlayerManager/Core/Private/AudioTracksQueue.swift
1
3027
// // AudioTracksQueue.swift // AudioPlayerManager // // Created by Hans Seiffert on 02.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit class AudioTracksQueue: NSObject { // MARK: - Private variables fileprivate(set) var currentTrack : AudioTrack? fileprivate var previousTrack : AudioTrack? { let previousIndex = self.currentItemQueueIndex - 1 if (previousIndex >= 0) { return self.queue[previousIndex] } return nil } fileprivate var queue = [AudioTrack]() fileprivate var currentItemQueueIndex = 0 fileprivate var history = [AudioTrack]() // MARK: - Set func replace(_ tracks: [AudioTrack]?, at startIndex: Int) { if let tracks = tracks { // Add the current track to the history if let currentTrack = self.currentTrack { self.history.append(currentTrack) } // Replace the tracks in the queue with the new ones self.queue = tracks self.currentItemQueueIndex = startIndex self.currentTrack?.cleanupAfterPlaying() self.currentTrack = tracks[startIndex] } else { self.queue.removeAll() self.currentTrack?.cleanupAfterPlaying() self.currentTrack = nil self.currentItemQueueIndex = 0 } } func prepend(_ tracks: [AudioTrack]) { // Insert the tracks at the beginning of the queue self.queue.insert(contentsOf: tracks, at: 0) // Adjust the current index to the new size self.currentItemQueueIndex += tracks.count } func append(_ tracks: [AudioTrack]) { self.queue.append(contentsOf: tracks) } // MARK: - Forward func canForward() -> Bool { return (self.queue.isEmpty == false && self.followingTrack() != nil) } func forward() -> Bool { if (self.canForward() == true), let currentTrack = self.currentTrack, let followingTrack = self.followingTrack() { // Add current track to the history currentTrack.cleanupAfterPlaying() // Replace the current track with the new one self.currentTrack = followingTrack // Adjust the current track index self.currentItemQueueIndex += 1 // Add the former track to the history self.history.append(currentTrack) return true } return false } fileprivate func followingTrack() -> AudioTrack? { let followingIndex = self.currentItemQueueIndex + 1 if (followingIndex < self.queue.count) { return self.queue[followingIndex] } return nil } // MARK: - Rewind func canRewind() -> Bool { return (self.previousTrack != nil) } func rewind() -> Bool { if (self.canRewind() == true), let currentTrack = self.currentTrack { currentTrack.cleanupAfterPlaying() // Replace the current track with the former one self.currentTrack = self.previousTrack // Adjust the current index self.currentItemQueueIndex -= 1 return true } return false } // MARK: - Get func count() -> Int { return self.queue.count } // History fileprivate func appendCurrentPlayingItemToQueue() { if let currentTrack = self.currentTrack { self.history.append(currentTrack) } } }
mit
09e6ead05a021417dc5905bc3804cda2
23.208
70
0.694977
3.74505
false
false
false
false
JTWang4778/LearningSwiftDemos
16-核心绘图/核心绘图/ViewController.swift
1
2711
// // ViewController.swift // 核心绘图 // // Created by 王锦涛 on 2017/7/5. // Copyright © 2017年 JTWang. All rights reserved. // import UIKit class ViewController: UIViewController { let dataArr = [ ["t":100, "x":10, "y":10], ["t":200, "x":34, "y":50], ["t":500, "x":40, "y":100], ["t":1000, "x":60, "y":20], ["t":2000, "x":100, "y":200], ["t":5000, "x":280, "y":10] ] let shapeLayer = CAShapeLayer() let gradientLayer = CAGradientLayer() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.automaticallyAdjustsScrollViewInsets = true // let lineView = LineView.init(frame: CGRect(x: 20, y: 300, width: 300, height: 300)) lineView.backgroundColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1) lineView.startAnimation(dataArr: self.dataArr) self.view.addSubview(lineView) let label = UILabel() label.text = "渐变文字" label.sizeToFit() label.center = CGPoint(x: 200, y: 200) self.view.addSubview(label) gradientLayer.frame = label.frame gradientLayer.colors = [UIColor.black.cgColor,UIColor.red.cgColor,UIColor.orange.cgColor,UIColor.yellow.cgColor] gradientLayer.startPoint = CGPoint(x: 0, y: 0.0) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0) self.view.layer.addSublayer(gradientLayer) gradientLayer.mask = label.layer label.frame = gradientLayer.bounds // 这一步很重要要 要重新设置frame // 利用CAShapeLayer 绘制指定圆角矩形 shapeLayer.lineWidth = 3 shapeLayer.strokeColor = UIColor.red.cgColor shapeLayer.fillColor = UIColor.white.cgColor let rect = CGRect(x: 20, y: 64, width: 100, height: 100) let radii = CGSize(width: 20, height: 20) let corners = UIRectCorner.init(rawValue: UIRectCorner.bottomLeft.rawValue + UIRectCorner.topRight.rawValue) let path = UIBezierPath.init(roundedRect: rect, byRoundingCorners: corners, cornerRadii: radii) shapeLayer.frame = rect self.view.layer.addSublayer(shapeLayer) shapeLayer.path = path.cgPath } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c51b931625293b73f617a7a59ddd125a
30.452381
120
0.571158
4.331148
false
false
false
false
chenzhe555/core-ios-swift
core-ios-swift/Framework_swift/subClass/MCLabel_s.swift
1
1785
// // MCLabel_s.swift // core-ios-swift // // Created by mc962 on 16/2/28. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit public class MCLabel_s: UILabel { //MARK: *************** .h(Protocal Enum ...) //MARK: *************** .h(Property Method ...) override public var text: String? { get{ return super.text; } set{ super.text = newValue; if(newValue != nil) { self.labelSize = MCViewTool_s.getLabelActualSize(newValue!, fontSize: self.font.pointSize, lines: self.limitNumbers, labelWidth: self.limitWidth, fontName: self.font.fontName); if(self.isChangeFrame) { self.frame = CGRectMake(self.x, self.y, self.labelSize.width, self.labelSize.height); } } else { self.frame = CGRectMake(self.x, self.y, 0, 0); } } } //限制的文本宽度(实现自定义类型的时候必须传入的值,默认为屏幕宽) public var limitWidth:CGFloat = UIScreen.mainScreen().bounds.size.width; //限制的文本行数(实现自定义类型的时候必须传入的值,默认为0) public var limitNumbers = 0; //是否自动改变Label的Frame(默认改变) public var isChangeFrame = true; //MARK: *************** .m(Category ...) private var labelSize:CGSize!; //MARK: *************** .m(Method ...) override init(frame: CGRect) { super.init(frame: frame); self.numberOfLines = 0; } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } }
mit
5479057eab7c0147d95168ed6cfe8d34
25.754098
192
0.522059
4
false
false
false
false
nuclearace/SwiftDiscord
Sources/SwiftDiscord/Gateway/DiscordGateway.swift
1
12377
// The MIT License (MIT) // Copyright (c) 2016 Erik Little // 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 /// Declares that a type will communicate with a Discord gateway. public protocol DiscordGatewayable : DiscordEngineHeartbeatable { // MARK: Properties /// Creates the handshake object that Discord expects. /// Override if you need to customize the handshake object. var handshakeObject: [String: Any] { get } /// Creates the resume object that Discord expects. /// Override if you need to customize the resume object. var resumeObject: [String: Any] { get } // MARK: Methods /// /// Handles a DiscordGatewayPayload. You shouldn't need to call this directly. /// /// Override this method if you need to customize payload handling. /// /// - parameter payload: The payload object /// func handleGatewayPayload(_ payload: DiscordGatewayPayload) // MARK: Methods /// /// Handles a dispatch payload. /// /// - parameter payload: The dispatch payload /// func handleDispatch(_ payload: DiscordGatewayPayload) /// /// Handles the hello event. /// /// - parameter payload: The dispatch payload /// func handleHello(_ payload: DiscordGatewayPayload) /// /// Handles the resumed event. /// /// - parameter payload: The payload for the event. /// func handleResumed(_ payload: DiscordGatewayPayload) /// /// Parses a raw message from the WebSocket. This is the entry point for all Discord events. /// You shouldn't call this directly. /// /// Override this method if you need to customize parsing. /// /// - parameter string: The raw payload string /// func parseGatewayMessage(_ string: String) /// /// Sends a payload to Discord. /// /// - parameter payload: The payload to send. /// func sendPayload(_ payload: DiscordGatewayPayload) /// /// Starts the handshake with the Discord server. You shouldn't need to call this directly. /// /// Override this method if you need to customize the handshake process. /// func startHandshake() } public extension DiscordGatewayable where Self: DiscordWebSocketable { /// Default Implementation. func sendPayload(_ payload: DiscordGatewayPayload) { guard let payloadString = payload.createPayloadString() else { error(message: "Could not create payload string for payload: \(payload)") return } DefaultDiscordLogger.Logger.debug("Sending ws: \(payloadString)", type: description) #if !os(Linux) websocket?.write(string: payloadString) #else try? websocket?.send(payloadString) #endif } } /// Holds a gateway payload, based on its type. public enum DiscordGatewayPayloadData : Encodable { /// Outgoing payloads only, payload is a custom encodable type case customEncodable(Encodable) /// Payload is a json object. case object([String: Any]) /// Payload is an integer. case integer(Int) /// The payload is a bool case bool(Bool) /// Payload is null. case null var value: Any { switch self { case let .customEncodable(encodable): return encodable case let .object(object): return object case let .integer(integer): return integer case let .bool(bool): return bool case .null: return NSNull() } } /// Encodable implementation. public func encode(to encoder: Encoder) throws { switch self { case let .customEncodable(encodable): try encodable.encode(to: encoder) case let .object(contents): try GenericEncodableDictionary(contents).encode(to: encoder) case let .integer(integer): var container = encoder.singleValueContainer() try container.encode(integer) case let .bool(bool): var container = encoder.singleValueContainer() try container.encode(bool) case .null: var container = encoder.singleValueContainer() try container.encodeNil() } } } extension DiscordGatewayPayloadData { static func dataFromDictionary(_ data: Any?) -> DiscordGatewayPayloadData { guard let data = data else { return .null } // TODO this is very ugly. See https://bugs.swift.org/browse/SR-5863 #if !os(Linux) switch data { case let object as [String: Any]: return .object(object) case let number as NSNumber where number === kCFBooleanTrue || number === kCFBooleanFalse: return .bool(number.boolValue) case let integer as Int: return .integer(integer) default: return .null } #else switch data { case let object as [String: Any]: return .object(object) case let bool as Bool: return .bool(bool) case let integer as Int: return .integer(integer) default: return .null } #endif } } /// Represents a gateway payload. This is lowest level of the Discord API. public struct DiscordGatewayPayload : Encodable { /// The payload code. public let code: DiscordGatewayCode /// The payload data. public let payload: DiscordGatewayPayloadData /// The sequence number of this dispatch. public let sequenceNumber: Int? /// The name of this dispatch. public let name: String? /// /// Creates a new DiscordGatewayPayload. /// /// - parameter code: The code of this payload /// - parameter payload: The data of this payload /// - parameter sequenceNumber: An optional sequence number for this dispatch /// - parameter name: The name of this dispatch /// public init(code: DiscordGatewayCode, payload: DiscordGatewayPayloadData, sequenceNumber: Int? = nil, name: String? = nil) { self.code = code self.payload = payload self.sequenceNumber = sequenceNumber self.name = name } private enum PayloadKeys : String, CodingKey { case code = "op" case payload = "d" case sequence = "s" case name = "t" } /// Encodable implementation. public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PayloadKeys.self) try container.encode(code.rawCode, forKey: .code) try container.encodeIfPresent(sequenceNumber, forKey: .sequence) try container.encodeIfPresent(name, forKey: .name) try payload.encode(to: container.superEncoder(forKey: .payload)) } func createPayloadString() -> String? { return JSON.encodeJSON(self) } } extension DiscordGatewayPayload { static func payloadFromString(_ string: String, fromGateway: Bool = true) -> DiscordGatewayPayload? { guard case let .object(dictionary)? = JSON.decodeJSON(string), let op = dictionary["op"] as? Int else { return nil } let code: DiscordGatewayCode let payload = DiscordGatewayPayloadData.dataFromDictionary(dictionary["d"]) if fromGateway, let gatewayCode = DiscordNormalGatewayCode(rawValue: op) { code = .gateway(gatewayCode) } else if let voiceCode = DiscordVoiceGatewayCode(rawValue: op) { code = .voice(voiceCode) } else { return nil } return DiscordGatewayPayload(code: code, payload: payload, sequenceNumber: dictionary["s"] as? Int, name: dictionary["t"] as? String) } } /// Top-level enum for gateway codes. public enum DiscordGatewayCode { /// Gateway code is a DiscordNormalGatewayCode. case gateway(DiscordNormalGatewayCode) /// Gateway code is a DiscordVoiceGatewayCode. case voice(DiscordVoiceGatewayCode) var rawCode: Int { switch self { case let .gateway(gatewayCode): return gatewayCode.rawValue case let .voice(voiceCode): return voiceCode.rawValue } } } /// Represents a regular gateway code public enum DiscordNormalGatewayCode : Int { /// Dispatch. case dispatch /// Heartbeat. case heartbeat /// Identify. case identify /// Status Update. case statusUpdate /// Voice Status Update. case voiceStatusUpdate /// Voice Server Ping. case voiceServerPing /// Resume. case resume /// Reconnect. case reconnect /// Request Guild Members. case requestGuildMembers /// Invalid Session. case invalidSession /// Hello. case hello /// HeartbeatAck case heartbeatAck } /// Represents a voice gateway code public enum DiscordVoiceGatewayCode : Int { /// Identify. Sent by the client. case identify = 0 /// Select Protocol. Sent by the client. case selectProtocol = 1 /// Ready. Sent by the server. case ready = 2 /// Heartbeat. Sent by the client. case heartbeat = 3 /// Session Description. Sent by the server. case sessionDescription = 4 /// Speaking. Sent by both client and server. case speaking = 5 /// Heartbeat ACK. Sent by the server. case heartbeatAck = 6 /// Resume. Sent by the client. case resume = 7 /// Hello. Sent by the server. case hello = 8 /// Resumed. Sent by the server. case resumed = 9 /// Client disconnect. Sent by the server. case clientDisconnect = 13 } /// Represents the reason a gateway was closed. public enum DiscordGatewayCloseReason : Int { /// We don't quite know why the gateway closed. case unknown = 0 /// The gateway closed because the network dropped. case noNetwork = 50 /// The gateway closed from a normal WebSocket close event. case normal = 1000 /// Something went wrong, but we aren't quite sure either. case unknownError = 4000 /// Discord got an opcode is doesn't recognize. case unknownOpcode = 4001 /// We sent a payload Discord doesn't know what to do with. case decodeError = 4002 /// We tried to send stuff before we were authenticated. case notAuthenticated = 4003 /// We failed to authenticate with Discord. case authenticationFailed = 4004 /// We tried to authenticate twice. case alreadyAuthenticated = 4005 /// We sent a bad sequence number when trying to resume. case invalidSequence = 4007 /// We sent messages too fast. case rateLimited = 4008 /// Our session timed out. case sessionTimeout = 4009 /// We sent an invalid shard when identifing. case invalidShard = 4010 /// We sent a protocol Discord doesn't recognize. case unknownProtocol = 4012 /// We got disconnected. case disconnected = 4014 /// The voice server crashed. case voiceServerCrash = 4015 /// We sent an encryption mode Discord doesn't know. case unknownEncryptionMode = 4016 // MARK: Initializers init?(error: Error?) { #if !os(Linux) guard let error = error else { return nil } self.init(rawValue: (error as NSError).code) #else self = .unknown #endif } }
mit
47edb808508ef6d63db1c7f4e74471af
29.114355
119
0.646279
4.867086
false
false
false
false
sihekuang/SKUIComponents
SKUIComponents/Classes/SKConnectionTableViewCell.swift
1
2859
// // ConnectionTableViewCell.swift // Pods // // Created by Daniel Lee on 12/29/16. // // import UIKit @IBDesignable open class SKConnectionTableViewCell: UITableViewCell { @IBInspectable open var circleArchWidth: CGFloat = 3 @IBInspectable open var circleRadius: CGFloat = 10 @IBInspectable open var circleColor: UIColor = UIColor.darkGray @IBInspectable open var circlePositionYRatio: CGFloat = 0.5 @IBInspectable open var circlePositionXPixel: CGFloat = 5 @IBInspectable open var isDrawingTopLine: Bool = true @IBInspectable open var isDrawingBottomLine: Bool = true @IBInspectable open var lineWidth: CGFloat = 2 @IBInspectable open var lineColor: UIColor = UIColor.lightGray open override func awakeFromNib() { super.awakeFromNib() // Initialization code } open override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } open override func draw(_ rect: CGRect) { let archWidth: CGFloat = circleArchWidth //1. make a rect where the circle goes let yPos: CGFloat = circlePositionYRatio * rect.height - circleRadius // 2 arch width on both sides of the circle, top and bottom let xPos: CGFloat = circlePositionXPixel let circleBounds = CGRect(x: xPos, y: yPos, width: circleRadius * 2, height: circleRadius * 2) //2. Draw circle _ = SKUIHelper.drawArchRing(startAngleRad: 0.0, endAngleRad: SKUIHelper.twoPi, color: circleColor, bounds: circleBounds, archWidth: archWidth) //3. draw a line between the mid point of the bottom of the rect/bottom of the circle and the bottom of cell lineColor.setStroke() let midXOfCircle = circleBounds.midX let topOfCircle = circleBounds.minY let bottomOfCircle = circleBounds.maxY if isDrawingTopLine{ let topLinePath = UIBezierPath() topLinePath.move(to: CGPoint(x: midXOfCircle, y: rect.minY)) //top-top topLinePath.addLine(to: CGPoint(x: midXOfCircle, y: topOfCircle)) //top-bottom topLinePath.close() topLinePath.lineWidth = lineWidth topLinePath.stroke() } if isDrawingBottomLine{ let bottomLinePath = UIBezierPath() bottomLinePath.move(to: CGPoint(x: midXOfCircle, y: rect.maxY)) //bottom-bottom bottomLinePath.addLine(to: CGPoint(x: midXOfCircle, y: bottomOfCircle)) //bottom-top bottomLinePath.close() bottomLinePath.lineWidth = lineWidth bottomLinePath.stroke() } } }
mit
1f4dd24b9d6eb611c0890e45dd64ac8e
30.766667
150
0.635187
4.963542
false
false
false
false
335g/Prelude
PreludeTests/CurryTests.swift
1
966
// Copyright (c) 2014 Rob Rix. All rights reserved. import Prelude import XCTest final class CurryTests: XCTestCase { // MARK: - Currying func testBinaryCurrying() { let f: Int -> Int -> Bool = curry(==) XCTAssertTrue(f(0)(0)) XCTAssertFalse(f(1)(0)) XCTAssertTrue(f(1)(1)) XCTAssertFalse(f(0)(1)) } func testTernaryCurrying() { let f: [Int] -> Int -> ((Int, Int) -> Int) -> Int = curry(reduce) XCTAssertEqual(f([1, 2, 3])(0)(+), 6) } // MARK: - Uncurrying func testBinaryUncurrying() { let f: Int -> Int -> Bool = curry(==) let g = uncurry(f) XCTAssertTrue(g(0, 0)) XCTAssertFalse(g(1, 0)) XCTAssertTrue(g(1, 1)) XCTAssertFalse(g(0, 1)) } func testTernaryUncurrying() { typealias ArgumentsTuple = ([Int], Int, (Int, Int) -> Int) let arguments: ArgumentsTuple = ([1, 2, 3], 0, +) let f: ArgumentsTuple -> Int = uncurry(curry(reduce)) XCTAssertEqual((reduce as ArgumentsTuple -> Int)(arguments), f(arguments)) } }
mit
b75016ff36a872e36f8c135ede8d1a1d
23.15
76
0.63354
3.009346
false
true
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/ViewController.swift
1
3655
// // ViewController.swift // MMGooglePlayNewsStand // // Created by mukesh mandora on 25/08/15. // Copyright (c) 2015 madapps. All rights reserved. // import UIKit class ViewController: UIViewController,MMPlayPageControllerDelegate { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate @IBOutlet weak var showDemoBut: UIButton! var navBar = UIView() var menuBut = UIButton() var searchBut = UIButton() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. initAddPlayViews() showDemoBut.tintColor=UIColor.whiteColor() showDemoBut.setImage(UIImage(named: "news")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) showDemoBut.backgroundColor=UIColor(hexString: "4caf50") showDemoBut.layer.cornerRadius=showDemoBut.frame.size.width/2 //NavBut navBar.frame=CGRectMake(0, 0, self.view.frame.width, 64) navBar.backgroundColor=UIColor.clearColor() menuBut.frame = CGRectMake(20, 27 , 20, 20) menuBut.tintColor=UIColor.whiteColor() menuBut.setImage(UIImage(named: "KeyboardClose")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) menuBut.addTarget(self, action: "handleCloseBtn", forControlEvents: .TouchUpInside) searchBut.frame = CGRectMake(self.view.frame.width-40, 27 , 20, 20) searchBut.setImage(UIImage(named: "KeyboardSearch")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) searchBut.tintColor=UIColor.whiteColor() navBar.addSubview(menuBut) navBar.addSubview(searchBut) view.addSubview(navBar) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func handleCloseBtn() { dismissViewControllerAnimated(true, completion: nil) } func initAddPlayViews() { // Attach the pages to the master let stb = UIStoryboard(name: "Main", bundle: nil) let page_zero = stb.instantiateViewControllerWithIdentifier("stand_one") as! MMSampleTableViewController let page_one = stb.instantiateViewControllerWithIdentifier("stand_one") as! MMSampleTableViewController let page_two = stb.instantiateViewControllerWithIdentifier("stand_one")as! MMSampleTableViewController let page_three = stb.instantiateViewControllerWithIdentifier("stand_one") as! MMSampleTableViewController appDelegate.walkthrough?.delegate = self appDelegate.walkthrough?.addViewControllerWithTitleandColor(page_zero, title: "Photos", color: UIColor(hexString: "9c27b0")) appDelegate.walkthrough?.addViewControllerWithTitleandColor(page_one, title: "Videos", color:UIColor(hexString: "009688")) appDelegate.walkthrough?.addViewControllerWithTitleandColor(page_two, title: "Feeds", color:UIColor(hexString: "ff9800")) appDelegate.walkthrough?.addViewControllerWithTitleandColor(page_three, title: "Notes", color: UIColor(hexString: "03a9f4")) //header Color page_zero.tag=1 page_one.tag=2 page_two.tag=3 page_three.tag=4 } func initPlayStand(){ self.presentViewController(appDelegate.walkthrough!, animated: true, completion: nil) } @IBAction func showDemoAction(sender: AnyObject) { initPlayStand() } }
mit
20b096909e8f54ded7bf2558894c9d3a
41.5
154
0.70342
4.945873
false
false
false
false