repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Mapping/MSAttribute+Convertible.swift
1
9992
// // MSAttribute+Convertible.swift // MoySkladSDK // // Created by Kostya on 27/12/2016. // Copyright © 2016 Andrey Parshakov. All rights reserved. // import Foundation extension MSAttribute : DictConvertable { public func dictionary(metaOnly: Bool = true) -> Dictionary<String, Any> { var dict = [String: Any]() dict["meta"] = meta.dictionary() guard !metaOnly else { return dict } dict["id"] = id dict["name"] = name if let type = value.type { dict["type"] = type } if case .file(let file) = value { if let instruction = file.instruction { dict["file"] = { switch instruction { case .delete: return NSNull() case .upload(let url): return ["filename": url.lastPathComponent, "content": try? Data(contentsOf: url).base64EncodedString()] } }() } } else { dict["value"] = { switch value { case .bool(let v): return v ?? NSNull() case .date(let v): return v?.toLongDate() ?? NSNull() case .double(let v): return v ?? NSNull() case .int(let v): return v ?? NSNull() case .link(let v): return v ?? NSNull() case .string(let v): return v ?? NSNull() case .text(let v): return v ?? NSNull() case .customentity(let custMeta, _, let custValue): return custMeta != nil ? ["meta":custMeta!.dictionary(), "name":custValue ?? ""] : NSNull() default: return nil } }() } return dict } public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSAttribute>? { guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } guard let name: String = dict.value("name"), name.count > 0 else { return MSEntity.meta(meta) } guard let type: String = dict.value("type"), type.count > 0 else { return MSEntity.meta(meta) } let id: String = dict.value("id") ?? "" if type.lowercased() == "string" { guard let value: String = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.string(value))) } else if type.lowercased() == "long" { guard let value: Int = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.int(value))) } else if type.lowercased() == "time" { guard let value = Date.fromMSDate(dict.value("value") ?? "") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.date(value))) } else if type.lowercased() == "double" { guard let value: Double = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.double(value))) } else if type.lowercased() == "file" { guard let value: String = dict.value("value") else { return MSEntity.meta(meta) } let url = URL(string: dict.msValue("download").value("href") ?? "") let mediaType: String? = dict.msValue("download").value("mediaType") return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value: MSAttributeValue.file(name: value, url: url, mediaType: mediaType, instruction: nil))) } else if type.lowercased() == "boolean" { guard let value: Bool = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.bool(value))) } else if type.lowercased() == "text" { guard let value: String = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.text(value))) } else if type.lowercased() == "link" { guard let value: String = dict.value("value") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.link(value))) } else if (type.lowercased() == "customentity") || (type.lowercased() == "employee") || (type.lowercased() == "contract") || (type.lowercased() == "project") || (type.lowercased() == "store") || (type.lowercased() == "product") || (type.lowercased() == "counterparty") || (type.lowercased() == "service") || (type.lowercased() == "bundle") || (type.lowercased() == "organization") { guard let value: [String: Any] = dict.value("value") else { return MSEntity.meta(meta) } guard let name: String = dict.value("name") else { return MSEntity.meta(meta) } guard let metaCustomentity = MSMeta.from(dict: value.msValue("meta"), parent: dict) else { return MSEntity.meta(meta) } guard let nameCustomentity: String = value.value("name") else { return MSEntity.meta(meta) } return MSEntity.entity(MSAttribute(meta: meta, id: id, name:name, value:.customentity(meta: metaCustomentity, name: name, value: nameCustomentity))) } else { return nil } } } extension MSAttributeDefinition { public static func from(dict: Dictionary<String, Any>) -> MSAttributeDefinition? { guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } guard let id: String = dict.value("id") else { return nil } guard let name: String = dict.value("name") else { return nil } guard let type: String = dict.value("type") else { return nil } guard let required: Bool = dict.value("required") else { return nil } let attributeValue: MSAttributeValue? = { switch type.lowercased() { case "text": return .text("") case "string": return MSAttributeValue.string("") case "double": return .double(nil) case "long": return .int(nil) case "time": return .date(nil) case "boolean": return .bool(false) case "link": return .link("") case "customentity": guard let customMeta = MSMeta.from(dict: dict.msValue("customEntityMeta"), parent: dict) else { return nil } return MSAttributeValue.customentity(meta: customMeta, name: name, value: "") case "employee": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .employee), name: name, value: "") case "contract": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .contract), name: name, value: "") case "project": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .project), name: name, value: "") case "store": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .store), name: name, value: "") case "product": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .product), name: name, value: "") case "counterparty": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .counterparty), name: name, value: "") case "productfolder": return MSAttributeValue.customentity(meta: MSMeta(name: name, href: "", type: .productfolder), name: name, value: "") case "file": return MSAttributeValue.file(name: "", url: nil, mediaType: nil, instruction: nil) default: return nil } }() guard let value = attributeValue else { return nil } return MSAttributeDefinition(meta: meta, id: id, name: name, value: value, required: required) } }
mit
itamaker/SunnyFPS
SunnyFPSTests/SunnyFPSTests.swift
1
977
// // SunnyFPSTests.swift // SunnyFPSTests // // Created by jiazhaoyang on 16/2/15. // Copyright © 2016年 gitpark. All rights reserved. // import XCTest @testable import SunnyFPS class SunnyFPSTests: 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 testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
apache-2.0
ahoppen/swift
test/Generics/Inputs/generic-nested-in-extension-on-objc-class.swift
27
83
import Foundation extension NSString { class _Inner1<T> where T: NSObject {} }
apache-2.0
lyft/SwiftLint
Tests/SwiftLintFrameworkTests/ExtendedNSStringTests.swift
1
1089
import Foundation import XCTest class ExtendedNSStringTests: XCTestCase { func testLineAndCharacterForByteOffset_forContentsContainingMultibyteCharacters() { let contents = "" + "import Foundation\n" + // 18 characters "class Test {\n" + // 13 characters "func test() {\n" + // 14 characters "// 日本語コメント : comment in Japanese\n" + // 33 characters "// do something\n" + // 16 characters "}\n" + "}" let string = NSString(string: contents) // A character placed on 80 offset indicates a white-space before 'do' at 5th line. if let lineAndCharacter = string.lineAndCharacter(forCharacterOffset: 80) { XCTAssertEqual(lineAndCharacter.line, 5) XCTAssertEqual(lineAndCharacter.character, 3) } else { XCTFail("NSString.lineAndCharacterForByteOffset should return non-nil tuple.") } } }
mit
jkereako/holidays
Tests/DateTests.swift
1
7021
// // DateTests.swift // Holidays // // Created by Jeff Kereakoglow on 10/1/15. // Copyright © 2015 Alexis Digital. All rights reserved. // import XCTest @testable import Holidays class DateTests: XCTestCase { var date: Date! override func setUp() { super.setUp() date = MockDate() } override func tearDown() { date = nil } func testBeginningOfDay() { let comps0 = NSDateComponents() comps0.year = 2015 comps0.month = 9 comps0.day = 30 let aDate = date.beginningOfDay( date:NSCalendar.currentCalendar().dateFromComponents(comps0)! ) let comps1 = components(date: aDate) XCTAssertTrue(comps1.year == 2015) XCTAssertTrue(comps1.month == 9) XCTAssertTrue(comps1.day == 30) XCTAssertTrue(comps1.hour == 0) XCTAssertTrue(comps1.minute == 0) XCTAssertTrue(comps1.second == 0) } func testEndOfDay() { let comps0 = NSDateComponents() comps0.year = 2015 comps0.month = 9 comps0.day = 30 let aDate = date.endOfDay( date:NSCalendar.currentCalendar().dateFromComponents(comps0)! ) let comps1 = components(date: aDate) XCTAssertTrue(comps1.year == 2015) XCTAssertTrue(comps1.month == 9) XCTAssertTrue(comps1.day == 30) XCTAssertTrue(comps1.hour == 23) XCTAssertTrue(comps1.minute == 59) XCTAssertTrue(comps1.second == 59) } func testNewYears() { let holiday = date.newYears XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 1) XCTAssertTrue(comps.day == 1) } func testMartinLutherKingJrDay() { let holiday = date.martinLutherKingJr XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 1) XCTAssertTrue(comps.day == 19) } func testValentines() { let holiday = date.valentines XCTAssertTrue(holiday.federalHoliday == false) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 2) XCTAssertTrue(comps.day == 14) } func testValentinesAdjustment() { let holiday = date.valentines XCTAssertTrue(holiday.federalHoliday == false) let adjustedHoliday = date.adjustForBusiness(holiday: holiday) XCTAssertTrue(adjustedHoliday.federalHoliday == false) let comps = components(date: adjustedHoliday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 2) XCTAssertTrue(comps.day == 13) } func testSaintPatricks() { let holiday = date.saintPatricks XCTAssertTrue(holiday.federalHoliday == false) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 3) XCTAssertTrue(comps.day == 17) } func testWashingtonsBirthdayDay() { let holiday = date.washingtonsBirthday XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 2) XCTAssertTrue(comps.day == 16) } func testMemorialDay() { let holiday = date.memorial XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 5) XCTAssertTrue(comps.day == 25) } func testIndependenceDay() { let holiday = date.independence XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 7) XCTAssertTrue(comps.day == 4) } // Independence Day in 2015 was on a Saturday, so it was moved to a Friday. func testIndependenceDayAdjustment() { let holiday = date.independence XCTAssertTrue(holiday.federalHoliday == true) let adjustedHoliday = date.adjustForBusiness(holiday: holiday) XCTAssertTrue(adjustedHoliday.federalHoliday == true) let comps = components(date: adjustedHoliday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 7) XCTAssertTrue(comps.day == 3) } func testLaborDay() { let holiday = date.labor XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 9) XCTAssertTrue(comps.day == 7) } func testColumbusDay() { let holiday = date.columbus XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 10) XCTAssertTrue(comps.day == 12) } // Columbus Day is always on a Monday, so we expect no change func testColumbusDayAdjustment() { let holiday = date.columbus XCTAssertTrue(holiday.federalHoliday == true) let adjustedHoliday = date.adjustForBusiness(holiday: holiday) XCTAssertTrue(adjustedHoliday.federalHoliday == true) let comps = components(date: adjustedHoliday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 10) XCTAssertTrue(comps.day == 12) } func testHalloween() { let holiday = date.halloween XCTAssertTrue(holiday.federalHoliday == false) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 10) XCTAssertTrue(comps.day == 31) } func testHalloweenAdjustment() { let holiday = date.halloween XCTAssertTrue(holiday.federalHoliday == false) let adjustedHoliday = date.adjustForBusiness(holiday: holiday) XCTAssertTrue(adjustedHoliday.federalHoliday == false) let comps = components(date: adjustedHoliday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 10) XCTAssertTrue(comps.day == 30) } func testVeteransDay() { let holiday = date.veterans XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 11) XCTAssertTrue(comps.day == 11) } func testThanksgivingDay() { let holiday = date.thanksgiving XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 11) XCTAssertTrue(comps.day == 26) } func testChristmas() { let holiday = date.christmas XCTAssertTrue(holiday.federalHoliday == true) let comps = components(date: holiday.date) XCTAssertTrue(comps.year == 2015) XCTAssertTrue(comps.month == 12) XCTAssertTrue(comps.day == 25) } private func components(date date: NSDate) -> NSDateComponents { return NSCalendar.currentCalendar().components( [.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date ) } }
mit
rowungiles/SwiftTech
SwiftTech/SwiftTech/Utilities/Search/CollectionTrie.swift
1
1370
// // CollectionTrie.swift // SwiftTech // // Created by Rowun Giles on 20/01/2016. // Copyright © 2016 Rowun Giles. All rights reserved. // import Foundation protocol CollectionTrie {} extension CollectionTrie { static internal func findRecursively<T: RangeReplaceableCollectionType, U: Equatable where T.Generator.Element == U>(findCollection: T, node: TrieNode<U>) -> TrieNode<U>? { var collection = findCollection guard !collection.isEmpty else { return node } let key = collection.removeFirst() if let childNode = node.children[key] { return findRecursively(collection, node: childNode) } return nil } static internal func addRecursively<T: RangeReplaceableCollectionType, U: Equatable where T.Generator.Element == U>(addCollection: T, addNode: TrieNode<U>) -> TrieNode<U> { var collection = addCollection var node = addNode guard !collection.isEmpty else { node.isFinal = true return node } let key = collection.removeFirst() let childNode = node.children[key] ?? TrieNode() node.children[key] = addRecursively(collection, addNode: childNode) return node } }
gpl-3.0
sspux/html2String
html2String+Extensions.swift
1
30507
// // html2String+Extensions.swift // // 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. // Mapping from XML/HTML character entity reference to character // From http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references private let characterEntities : [ String : Character ] = [ // XML predefined entities: "&quot;" : "\"", // U+0022 (34) HTML 2.0 HTMLspecial ISOnum quotation mark (APL quote) "&amp;" : "&", // U+0026 (38) HTML 2.0 HTMLspecial ISOnum ampersand "&apos;" : "'", // U+0027 (39) XHTML 1.0 HTMLspecial ISOnum apostrophe (apostrophe-quote); see below "&lt;" : "<", // U+003C (60) HTML 2.0 HTMLspecial ISOnum less-than sign "&gt;" : ">", // U+003E (62) HTML 2.0 HTMLspecial ISOnum greater-than sign "&nbsp;" : "\u{00a0}", // U+00A0 (160) HTML 3.2 HTMLlat1 ISOnum no-break space (non-breaking space)[d] "&iexcl;" : "¡", // U+00A1 (161) HTML 3.2 HTMLlat1 ISOnum inverted exclamation mark "&cent;" : "¢", // U+00A2 (162) HTML 3.2 HTMLlat1 ISOnum cent sign "&pound;" : "£", // U+00A3 (163) HTML 3.2 HTMLlat1 ISOnum pound sign "&curren;" : "¤", // U+00A4 (164) HTML 3.2 HTMLlat1 ISOnum currency sign "&yen;" : "¥", // U+00A5 (165) HTML 3.2 HTMLlat1 ISOnum yen sign (yuan sign) "&brvbar;" : "¦", // U+00A6 (166) HTML 3.2 HTMLlat1 ISOnum broken bar (broken vertical bar) "&sect;" : "§", // U+00A7 (167) HTML 3.2 HTMLlat1 ISOnum section sign "&uml;" : "¨", // U+00A8 (168) HTML 3.2 HTMLlat1 ISOdia diaeresis (spacing diaeresis); see Germanic umlaut "&copy;" : "©", // U+00A9 (169) HTML 3.2 HTMLlat1 ISOnum copyright symbol "&ordf;" : "ª", // U+00AA (170) HTML 3.2 HTMLlat1 ISOnum feminine ordinal indicator "&laquo;" : "«", // U+00AB (171) HTML 3.2 HTMLlat1 ISOnum left-pointing double angle quotation mark (left pointing guillemet) "&not;" : "¬", // U+00AC (172) HTML 3.2 HTMLlat1 ISOnum not sign "&shy;" : "\u{00ad}", // U+00AD (173) HTML 3.2 HTMLlat1 ISOnum soft hyphen (discretionary hyphen) "&reg;" : "®", // U+00AE (174) HTML 3.2 HTMLlat1 ISOnum registered sign (registered trademark symbol) "&macr;" : "¯", // U+00AF (175) HTML 3.2 HTMLlat1 ISOdia macron (spacing macron, overline, APL overbar) "&deg;" : "°", // U+00B0 (176) HTML 3.2 HTMLlat1 ISOnum degree symbol "&plusmn;" : "±", // U+00B1 (177) HTML 3.2 HTMLlat1 ISOnum plus-minus sign (plus-or-minus sign) "&sup2;" : "²", // U+00B2 (178) HTML 3.2 HTMLlat1 ISOnum superscript two (superscript digit two, squared) "&sup3;" : "³", // U+00B3 (179) HTML 3.2 HTMLlat1 ISOnum superscript three (superscript digit three, cubed) "&acute;" : "´", // U+00B4 (180) HTML 3.2 HTMLlat1 ISOdia acute accent (spacing acute) "&micro;" : "µ", // U+00B5 (181) HTML 3.2 HTMLlat1 ISOnum micro sign "&para;" : "¶", // U+00B6 (182) HTML 3.2 HTMLlat1 ISOnum pilcrow sign (paragraph sign) "&middot;" : "·", // U+00B7 (183) HTML 3.2 HTMLlat1 ISOnum middle dot (Georgian comma, Greek middle dot) "&cedil;" : "¸", // U+00B8 (184) HTML 3.2 HTMLlat1 ISOdia cedilla (spacing cedilla) "&sup1;" : "¹", // U+00B9 (185) HTML 3.2 HTMLlat1 ISOnum superscript one (superscript digit one) "&ordm;" : "º", // U+00BA (186) HTML 3.2 HTMLlat1 ISOnum masculine ordinal indicator "&raquo;" : "»", // U+00BB (187) HTML 3.2 HTMLlat1 ISOnum right-pointing double angle quotation mark (right pointing guillemet) "&frac14;" : "¼", // U+00BC (188) HTML 3.2 HTMLlat1 ISOnum vulgar fraction one quarter (fraction one quarter) "&frac12;" : "½", // U+00BD (189) HTML 3.2 HTMLlat1 ISOnum vulgar fraction one half (fraction one half) "&frac34;" : "¾", // U+00BE (190) HTML 3.2 HTMLlat1 ISOnum vulgar fraction three quarters (fraction three quarters) "&iquest;" : "¿", // U+00BF (191) HTML 3.2 HTMLlat1 ISOnum inverted question mark (turned question mark) "&Agrave;" : "À", // U+00C0 (192) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with grave accent (Latin capital letter A grave) "&Aacute;" : "Á", // U+00C1 (193) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with acute accent "&Acirc;" : "Â", // U+00C2 (194) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with circumflex "&Atilde;" : "Ã", // U+00C3 (195) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with tilde "&Auml;" : "Ä", // U+00C4 (196) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with diaeresis "&Aring;" : "Å", // U+00C5 (197) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter A with ring above (Latin capital letter A ring) "&AElig;" : "Æ", // U+00C6 (198) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter AE (Latin capital ligature AE) "&Ccedil;" : "Ç", // U+00C7 (199) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter C with cedilla "&Egrave;" : "È", // U+00C8 (200) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter E with grave accent "&Eacute;" : "É", // U+00C9 (201) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter E with acute accent "&Ecirc;" : "Ê", // U+00CA (202) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter E with circumflex "&Euml;" : "Ë", // U+00CB (203) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter E with diaeresis "&Igrave;" : "Ì", // U+00CC (204) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter I with grave accent "&Iacute;" : "Í", // U+00CD (205) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter I with acute accent "&Icirc;" : "Î", // U+00CE (206) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter I with circumflex "&Iuml;" : "Ï", // U+00CF (207) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter I with diaeresis "&ETH;" : "Ð", // U+00D0 (208) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter Eth "&Ntilde;" : "Ñ", // U+00D1 (209) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter N with tilde "&Ograve;" : "Ò", // U+00D2 (210) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with grave accent "&Oacute;" : "Ó", // U+00D3 (211) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with acute accent "&Ocirc;" : "Ô", // U+00D4 (212) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with circumflex "&Otilde;" : "Õ", // U+00D5 (213) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with tilde "&Ouml;" : "Ö", // U+00D6 (214) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with diaeresis "&times;" : "×", // U+00D7 (215) HTML 3.2 HTMLlat1 ISOnum multiplication sign "&Oslash;" : "Ø", // U+00D8 (216) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter O with stroke (Latin capital letter O slash) "&Ugrave;" : "Ù", // U+00D9 (217) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter U with grave accent "&Uacute;" : "Ú", // U+00DA (218) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter U with acute accent "&Ucirc;" : "Û", // U+00DB (219) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter U with circumflex "&Uuml;" : "Ü", // U+00DC (220) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter U with diaeresis "&Yacute;" : "Ý", // U+00DD (221) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter Y with acute accent "&THORN;" : "Þ", // U+00DE (222) HTML 2.0 HTMLlat1 ISOlat1 Latin capital letter THORN "&szlig;" : "ß", // U+00DF (223) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter sharp s (ess-zed); see German Eszett "&agrave;" : "à", // U+00E0 (224) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with grave accent "&aacute;" : "á", // U+00E1 (225) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with acute accent "&acirc;" : "â", // U+00E2 (226) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with circumflex "&atilde;" : "ã", // U+00E3 (227) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with tilde "&auml;" : "ä", // U+00E4 (228) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with diaeresis "&aring;" : "å", // U+00E5 (229) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter a with ring above "&aelig;" : "æ", // U+00E6 (230) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter ae (Latin small ligature ae) "&ccedil;" : "ç", // U+00E7 (231) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter c with cedilla "&egrave;" : "è", // U+00E8 (232) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter e with grave accent "&eacute;" : "é", // U+00E9 (233) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter e with acute accent "&ecirc;" : "ê", // U+00EA (234) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter e with circumflex "&euml;" : "ë", // U+00EB (235) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter e with diaeresis "&igrave;" : "ì", // U+00EC (236) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter i with grave accent "&iacute;" : "í", // U+00ED (237) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter i with acute accent "&icirc;" : "î", // U+00EE (238) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter i with circumflex "&iuml;" : "ï", // U+00EF (239) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter i with diaeresis "&eth;" : "ð", // U+00F0 (240) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter eth "&ntilde;" : "ñ", // U+00F1 (241) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter n with tilde "&ograve;" : "ò", // U+00F2 (242) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with grave accent "&oacute;" : "ó", // U+00F3 (243) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with acute accent "&ocirc;" : "ô", // U+00F4 (244) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with circumflex "&otilde;" : "õ", // U+00F5 (245) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with tilde "&ouml;" : "ö", // U+00F6 (246) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with diaeresis "&divide;" : "÷", // U+00F7 (247) HTML 3.2 HTMLlat1 ISOnum division sign (obelus) "&oslash;" : "ø", // U+00F8 (248) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter o with stroke (Latin small letter o slash) "&ugrave;" : "ù", // U+00F9 (249) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter u with grave accent "&uacute;" : "ú", // U+00FA (250) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter u with acute accent "&ucirc;" : "û", // U+00FB (251) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter u with circumflex "&uuml;" : "ü", // U+00FC (252) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter u with diaeresis "&yacute;" : "ý", // U+00FD (253) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter y with acute accent "&thorn;" : "þ", // U+00FE (254) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter thorn "&yuml;" : "ÿ", // U+00FF (255) HTML 2.0 HTMLlat1 ISOlat1 Latin small letter y with diaeresis "&OElig;" : "Œ", // U+0152 (338) HTML 4.0 HTMLspecial ISOlat2 Latin capital ligature oe[e] "&oelig;" : "œ", // U+0153 (339) HTML 4.0 HTMLspecial ISOlat2 Latin small ligature oe[e] "&Scaron;" : "Š", // U+0160 (352) HTML 4.0 HTMLspecial ISOlat2 Latin capital letter s with caron "&scaron;" : "š", // U+0161 (353) HTML 4.0 HTMLspecial ISOlat2 Latin small letter s with caron "&Yuml;" : "Ÿ", // U+0178 (376) HTML 4.0 HTMLspecial ISOlat2 Latin capital letter y with diaeresis "&fnof;" : "ƒ", // U+0192 (402) HTML 4.0 HTMLsymbol ISOtech Latin small letter f with hook (function, florin) "&circ;" : "ˆ", // U+02C6 (710) HTML 4.0 HTMLspecial ISOpub modifier letter circumflex accent "&tilde;" : "˜", // U+02DC (732) HTML 4.0 HTMLspecial ISOdia small tilde "&Alpha;" : "Α", // U+0391 (913) HTML 4.0 HTMLsymbol Greek capital letter Alpha "&Beta;" : "Β", // U+0392 (914) HTML 4.0 HTMLsymbol Greek capital letter Beta "&Gamma;" : "Γ", // U+0393 (915) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Gamma "&Delta;" : "Δ", // U+0394 (916) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Delta "&Epsilon;" : "Ε", // U+0395 (917) HTML 4.0 HTMLsymbol Greek capital letter Epsilon "&Zeta;" : "Ζ", // U+0396 (918) HTML 4.0 HTMLsymbol Greek capital letter Zeta "&Eta;" : "Η", // U+0397 (919) HTML 4.0 HTMLsymbol Greek capital letter Eta "&Theta;" : "Θ", // U+0398 (920) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Theta "&Iota;" : "Ι", // U+0399 (921) HTML 4.0 HTMLsymbol Greek capital letter Iota "&Kappa;" : "Κ", // U+039A (922) HTML 4.0 HTMLsymbol Greek capital letter Kappa "&Lambda;" : "Λ", // U+039B (923) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Lambda "&Mu;" : "Μ", // U+039C (924) HTML 4.0 HTMLsymbol Greek capital letter Mu "&Nu;" : "Ν", // U+039D (925) HTML 4.0 HTMLsymbol Greek capital letter Nu "&Xi;" : "Ξ", // U+039E (926) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Xi "&Omicron;" : "Ο", // U+039F (927) HTML 4.0 HTMLsymbol Greek capital letter Omicron "&Pi;" : "Π", // U+03A0 (928) HTML 4.0 HTMLsymbol Greek capital letter Pi "&Rho;" : "Ρ", // U+03A1 (929) HTML 4.0 HTMLsymbol Greek capital letter Rho "&Sigma;" : "Σ", // U+03A3 (931) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Sigma "&Tau;" : "Τ", // U+03A4 (932) HTML 4.0 HTMLsymbol Greek capital letter Tau "&Upsilon;" : "Υ", // U+03A5 (933) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Upsilon "&Phi;" : "Φ", // U+03A6 (934) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Phi "&Chi;" : "Χ", // U+03A7 (935) HTML 4.0 HTMLsymbol Greek capital letter Chi "&Psi;" : "Ψ", // U+03A8 (936) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Psi "&Omega;" : "Ω", // U+03A9 (937) HTML 4.0 HTMLsymbol ISOgrk3 Greek capital letter Omega "&alpha;" : "α", // U+03B1 (945) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter alpha "&beta;" : "β", // U+03B2 (946) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter beta "&gamma;" : "γ", // U+03B3 (947) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter gamma "&delta;" : "δ", // U+03B4 (948) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter delta "&epsilon;" : "ε", // U+03B5 (949) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter epsilon "&zeta;" : "ζ", // U+03B6 (950) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter zeta "&eta;" : "η", // U+03B7 (951) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter eta "&theta;" : "θ", // U+03B8 (952) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter theta "&iota;" : "ι", // U+03B9 (953) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter iota "&kappa;" : "κ", // U+03BA (954) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter kappa "&lambda;" : "λ", // U+03BB (955) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter lambda "&mu;" : "μ", // U+03BC (956) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter mu "&nu;" : "ν", // U+03BD (957) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter nu "&xi;" : "ξ", // U+03BE (958) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter xi "&omicron;" : "ο", // U+03BF (959) HTML 4.0 HTMLsymbol NEW Greek small letter omicron "&pi;" : "π", // U+03C0 (960) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter pi "&rho;" : "ρ", // U+03C1 (961) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter rho "&sigmaf;" : "ς", // U+03C2 (962) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter final sigma "&sigma;" : "σ", // U+03C3 (963) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter sigma "&tau;" : "τ", // U+03C4 (964) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter tau "&upsilon;" : "υ", // U+03C5 (965) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter upsilon "&phi;" : "φ", // U+03C6 (966) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter phi "&chi;" : "χ", // U+03C7 (967) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter chi "&psi;" : "ψ", // U+03C8 (968) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter psi "&omega;" : "ω", // U+03C9 (969) HTML 4.0 HTMLsymbol ISOgrk3 Greek small letter omega "&thetasym;": "ϑ", // U+03D1 (977) HTML 4.0 HTMLsymbol NEW Greek theta symbol "&upsih;" : "ϒ", // U+03D2 (978) HTML 4.0 HTMLsymbol NEW Greek Upsilon with hook symbol "&piv;" : "ϖ", // U+03D6 (982) HTML 4.0 HTMLsymbol ISOgrk3 Greek pi symbol "&ensp;" : "\u{2002}", //  U+2002 (8194) HTML 4.0 HTMLspecial ISOpub en space[d] "&emsp;" : "\u{2003}", //  U+2003 (8195) HTML 4.0 HTMLspecial ISOpub em space[d] "&thinsp;" : "\u{2009}", //  U+2009 (8201) HTML 4.0 HTMLspecial ISOpub thin space[d] "&zwnj;" : "\u{200C}", // U+200C (8204) HTML 4.0 HTMLspecial NEW RFC 2070 zero-width non-joiner "&zwj;" : "\u{200D}", // U+200D (8205) HTML 4.0 HTMLspecial NEW RFC 2070 zero-width joiner "&lrm;" : "\u{200E}", // U+200E (8206) HTML 4.0 HTMLspecial NEW RFC 2070 left-to-right mark "&rlm;" : "\u{200F}", // U+200F (8207) HTML 4.0 HTMLspecial NEW RFC 2070 right-to-left mark "&ndash;" : "–", // U+2013 (8211) HTML 4.0 HTMLspecial ISOpub en dash "&mdash;" : "—", // U+2014 (8212) HTML 4.0 HTMLspecial ISOpub em dash "&lsquo;" : "‘", // U+2018 (8216) HTML 4.0 HTMLspecial ISOnum left single quotation mark "&rsquo;" : "’", // U+2019 (8217) HTML 4.0 HTMLspecial ISOnum right single quotation mark "&sbquo;" : "‚", // U+201A (8218) HTML 4.0 HTMLspecial NEW single low-9 quotation mark "&ldquo;" : "“", // U+201C (8220) HTML 4.0 HTMLspecial ISOnum left double quotation mark "&rdquo;" : "”", // U+201D (8221) HTML 4.0 HTMLspecial ISOnum right double quotation mark "&bdquo;" : "„", // U+201E (8222) HTML 4.0 HTMLspecial NEW double low-9 quotation mark "&dagger;" : "†", // U+2020 (8224) HTML 4.0 HTMLspecial ISOpub dagger, obelisk "&Dagger;" : "‡", // U+2021 (8225) HTML 4.0 HTMLspecial ISOpub double dagger, double obelisk "&bull;" : "•", // U+2022 (8226) HTML 4.0 HTMLspecial ISOpub bullet (black small circle)[f] "&hellip;" : "…", // U+2026 (8230) HTML 4.0 HTMLsymbol ISOpub horizontal ellipsis (three dot leader) "&permil;" : "‰", // U+2030 (8240) HTML 4.0 HTMLspecial ISOtech per mille sign "&prime;" : "′", // U+2032 (8242) HTML 4.0 HTMLsymbol ISOtech prime (minutes, feet) "&Prime;" : "″", // U+2033 (8243) HTML 4.0 HTMLsymbol ISOtech double prime (seconds, inches) "&lsaquo;" : "‹", // U+2039 (8249) HTML 4.0 HTMLspecial ISO proposed single left-pointing angle quotation mark[g] "&rsaquo;" : "›", // U+203A (8250) HTML 4.0 HTMLspecial ISO proposed single right-pointing angle quotation mark[g] "&oline;" : "‾", // U+203E (8254) HTML 4.0 HTMLsymbol NEW overline (spacing overscore) "&frasl;" : "⁄", // U+2044 (8260) HTML 4.0 HTMLsymbol NEW fraction slash (solidus) "&euro;" : "€", // U+20AC (8364) HTML 4.0 HTMLspecial NEW euro sign "&image;" : "ℑ", // U+2111 (8465) HTML 4.0 HTMLsymbol ISOamso black-letter capital I (imaginary part) "&weierp;" : "℘", // U+2118 (8472) HTML 4.0 HTMLsymbol ISOamso script capital P (power set, Weierstrass p) "&real;" : "ℜ", // U+211C (8476) HTML 4.0 HTMLsymbol ISOamso black-letter capital R (real part symbol) "&trade;" : "™", // U+2122 (8482) HTML 4.0 HTMLsymbol ISOnum trademark symbol "&alefsym;" : "ℵ", // U+2135 (8501) HTML 4.0 HTMLsymbol NEW alef symbol (first transfinite cardinal)[h] "&larr;" : "←", // U+2190 (8592) HTML 4.0 HTMLsymbol ISOnum leftwards arrow "&uarr;" : "↑", // U+2191 (8593) HTML 4.0 HTMLsymbol ISOnum upwards arrow "&rarr;" : "→", // U+2192 (8594) HTML 4.0 HTMLsymbol ISOnum rightwards arrow "&darr;" : "↓", // U+2193 (8595) HTML 4.0 HTMLsymbol ISOnum downwards arrow "&harr;" : "↔", // U+2194 (8596) HTML 4.0 HTMLsymbol ISOamsa left right arrow "&crarr;" : "↵", // U+21B5 (8629) HTML 4.0 HTMLsymbol NEW downwards arrow with corner leftwards (carriage return) "&lArr;" : "⇐", // U+21D0 (8656) HTML 4.0 HTMLsymbol ISOtech leftwards double arrow[i] "&uArr;" : "⇑", // U+21D1 (8657) HTML 4.0 HTMLsymbol ISOamsa upwards double arrow "&rArr;" : "⇒", // U+21D2 (8658) HTML 4.0 HTMLsymbol ISOnum rightwards double arrow[j] "&dArr;" : "⇓", // U+21D3 (8659) HTML 4.0 HTMLsymbol ISOamsa downwards double arrow "&hArr;" : "⇔", // U+21D4 (8660) HTML 4.0 HTMLsymbol ISOamsa left right double arrow "&forall;" : "∀", // U+2200 (8704) HTML 4.0 HTMLsymbol ISOtech for all "&part;" : "∂", // U+2202 (8706) HTML 4.0 HTMLsymbol ISOtech partial differential "&exist;" : "∃", // U+2203 (8707) HTML 4.0 HTMLsymbol ISOtech there exists "&empty;" : "∅", // U+2205 (8709) HTML 4.0 HTMLsymbol ISOamso empty set (null set); see also U+8960, ⌀ "&nabla;" : "∇", // U+2207 (8711) HTML 4.0 HTMLsymbol ISOtech del or nabla (vector differential operator) "&isin;" : "∈", // U+2208 (8712) HTML 4.0 HTMLsymbol ISOtech element of "&notin;" : "∉", // U+2209 (8713) HTML 4.0 HTMLsymbol ISOtech not an element of "&ni;" : "∋", // U+220B (8715) HTML 4.0 HTMLsymbol ISOtech contains as member "&prod;" : "∏", // U+220F (8719) HTML 4.0 HTMLsymbol ISOamsb n-ary product (product sign)[k] "&sum;" : "∑", // U+2211 (8721) HTML 4.0 HTMLsymbol ISOamsb n-ary summation[l] "&minus;" : "−", // U+2212 (8722) HTML 4.0 HTMLsymbol ISOtech minus sign "&lowast;" : "∗", // U+2217 (8727) HTML 4.0 HTMLsymbol ISOtech asterisk operator "&radic;" : "√", // U+221A (8730) HTML 4.0 HTMLsymbol ISOtech square root (radical sign) "&prop;" : "∝", // U+221D (8733) HTML 4.0 HTMLsymbol ISOtech proportional to "&infin;" : "∞", // U+221E (8734) HTML 4.0 HTMLsymbol ISOtech infinity "&ang;" : "∠", // U+2220 (8736) HTML 4.0 HTMLsymbol ISOamso angle "&and;" : "∧", // U+2227 (8743) HTML 4.0 HTMLsymbol ISOtech logical and (wedge) "&or;" : "∨", // U+2228 (8744) HTML 4.0 HTMLsymbol ISOtech logical or (vee) "&cap;" : "∩", // U+2229 (8745) HTML 4.0 HTMLsymbol ISOtech intersection (cap) "&cup;" : "∪", // U+222A (8746) HTML 4.0 HTMLsymbol ISOtech union (cup) "&int;" : "∫", // U+222B (8747) HTML 4.0 HTMLsymbol ISOtech integral "&there4;" : "\u{2234}", // U+2234 (8756) HTML 4.0 HTMLsymbol ISOtech therefore sign "&sim;" : "∼", // U+223C (8764) HTML 4.0 HTMLsymbol ISOtech tilde operator (varies with, similar to)[m] "&cong;" : "≅", // U+2245 (8773) HTML 4.0 HTMLsymbol ISOtech congruent to "&asymp;" : "≈", // U+2248 (8776) HTML 4.0 HTMLsymbol ISOamsr almost equal to (asymptotic to) "&ne;" : "≠", // U+2260 (8800) HTML 4.0 HTMLsymbol ISOtech not equal to "&equiv;" : "≡", // U+2261 (8801) HTML 4.0 HTMLsymbol ISOtech identical to; sometimes used for 'equivalent to' "&le;" : "≤", // U+2264 (8804) HTML 4.0 HTMLsymbol ISOtech less-than or equal to "&ge;" : "≥", // U+2265 (8805) HTML 4.0 HTMLsymbol ISOtech greater-than or equal to "&sub;" : "⊂", // U+2282 (8834) HTML 4.0 HTMLsymbol ISOtech subset of "&sup;" : "⊃", // U+2283 (8835) HTML 4.0 HTMLsymbol ISOtech superset of[n] "&nsub;" : "⊄", // U+2284 (8836) HTML 4.0 HTMLsymbol ISOamsn not a subset of "&sube;" : "⊆", // U+2286 (8838) HTML 4.0 HTMLsymbol ISOtech subset of or equal to "&supe;" : "⊇", // U+2287 (8839) HTML 4.0 HTMLsymbol ISOtech superset of or equal to "&oplus;" : "⊕", // U+2295 (8853) HTML 4.0 HTMLsymbol ISOamsb circled plus (direct sum) "&otimes;" : "⊗", // U+2297 (8855) HTML 4.0 HTMLsymbol ISOamsb circled times (vector product) "&perp;" : "⊥", // U+22A5 (8869) HTML 4.0 HTMLsymbol ISOtech up tack (orthogonal to, perpendicular)[o] "&sdot;" : "⋅", // U+22C5 (8901) HTML 4.0 HTMLsymbol ISOamsb dot operator[p] "&lceil;" : "⌈", // U+2308 (8968) HTML 4.0 HTMLsymbol ISOamsc left ceiling (APL upstile) "&rceil;" : "⌉", // U+2309 (8969) HTML 4.0 HTMLsymbol ISOamsc right ceiling "&lfloor;" : "⌊", // U+230A (8970) HTML 4.0 HTMLsymbol ISOamsc left floor (APL downstile) "&rfloor;" : "⌋", // U+230B (8971) HTML 4.0 HTMLsymbol ISOamsc right floor "&lang;" : "〈", // U+2329 (9001) HTML 4.0 HTMLsymbol ISOtech left-pointing angle bracket (bra)[q] "&rang;" : "〉", // U+232A (9002) HTML 4.0 HTMLsymbol ISOtech right-pointing angle bracket (ket)[r] "&loz;" : "◊", // U+25CA (9674) HTML 4.0 HTMLsymbol ISOpub lozenge "&spades;" : "♠", // U+2660 (9824) HTML 4.0 HTMLsymbol ISOpub black spade suit[f] "&clubs;" : "♣", // U+2663 (9827) HTML 4.0 HTMLsymbol ISOpub black club suit (shamrock)[f] "&hearts;" : "♥", // U+2665 (9829) HTML 4.0 HTMLsymbol ISOpub black heart suit (valentine)[f] "&diams;" : "♦", // U+2666 (9830) HTML 4.0 HTMLsymbol ISOpub black diamond suit[f] ] extension String { /// Returns a new string made by replacing in the `String` /// all HTML character entity references with the corresponding /// character. var stringByDecodingHTMLEntities : String { // ===== Utility functions ===== // Convert the number in the string to the corresponding // Unicode character, e.g. // decodeNumeric("64", 10) --> "@" // decodeNumeric("20ac", 16) --> "€" func decodeNumeric(string : String, base : Int32) -> Character? { let code = UInt32(strtoul(string, nil, base)) return Character(UnicodeScalar(code)) } // Decode the HTML character entity to the corresponding // Unicode character, return `nil` for invalid input. // decode("&#64;") --> "@" // decode("&#x20ac;") --> "€" // decode("&lt;") --> "<" // decode("&foo;") --> nil func decode(entity : String) -> Character? { if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){ return decodeNumeric(entity.substringFromIndex(entity.startIndex.advancedBy(3)), base: 16) } else if entity.hasPrefix("&#") { return decodeNumeric(entity.substringFromIndex(entity.startIndex.advancedBy(2)), base: 10) } else { return characterEntities[entity] } } // ===== Method starts here ===== var result = "" var position = startIndex // Find the next '&' and copy the characters preceding it to `result`: while let ampRange = self.rangeOfString("&", range: position ..< endIndex) { result.appendContentsOf(self[position ..< ampRange.startIndex]) position = ampRange.startIndex // Find the next ';' and copy everything from '&' to ';' into `entity` if let semiRange = self.rangeOfString(";", range: position ..< endIndex) { let entity = self[position ..< semiRange.endIndex] position = semiRange.endIndex if let decoded = decode(entity) { // Replace by decoded character: result.append(decoded) } else { // Invalid entity, copy verbatim: result.appendContentsOf(entity) } } else { // No matching ';'. break } } // Copy remaining characters to `result`: result.appendContentsOf(self[position ..< endIndex]) return result } }
mit
duliodenis/jukebox
jukebox/jukebox/VideoLibrary.swift
1
1975
// // MusicLibrary.swift // jukebox // // Created by Dulio Denis on 3/21/15. // Copyright (c) 2015 Dulio Denis. All rights reserved. // import Foundation struct VideoLibrary { let library = [ [ "title": "Swift Programming", "description": "Watch great videos on the new Apple Swift Programming Language", "icon": "Swift_small", "largeIcon": "Swift_large", "backgroundColor": ["red": 255, "green": 204, "blue": 51, "alpha": 1.0], "videos": ["NSSpain 2014: Swift and C by Mike Ash", "Protocols in Swift With Core Data", "Swift, Swiftly"], "urls": ["https://vimeo.com/107707576", "https://vimeo.com/110260560", "https://vimeo.com/111035398"] ], [ "title": "Swift Functional Programming", "description": "Swift has the right language features to support writing functional programs", "icon": "Lambda_small", "largeIcon": "Lambda_large", "backgroundColor": ["red": 51, "green": 204, "blue": 102, "alpha": 1.0], "videos": ["Functional programming in Swift", "Chris Eidhof - Functional Programming in Swift", "Amit Biljani - Value Semantics in Swift"], "urls": ["https://vimeo.com/110841941", "https://vimeo.com/107419503", "https://vimeo.com/108920750"] ], [ "title": "iOS Design Patterns", "description": "In order to make the best Apps you need to know your iOS Design Patterns", "icon": "stencil_small", "largeIcon": "stencil_large", "backgroundColor": ["red": 255, "green": 102, "blue": 153, "alpha": 1.0], "videos": ["Saul Mora - Design Patterns for Mobile Apps", "David Shane: Using Design Patterns in iOS", "Asynchronous Design Patterns in Objective-C"], "urls": ["https://vimeo.com/74745264", "https://vimeo.com/41504128", "https://vimeo.com/72380570"] ], ] }
mit
McClementine/TextGameEngine
src/room.swift
1
783
public class Room { public var name: String public var message: String public var roomAccess: [Room] = [] public var commands: [Command]? public func printInfo() { print(message) print("You have access to the following room(s):") for rooms in roomAccess { print(rooms.name) } print("You can:") if commands?.count > 0 { for cmd in commands! { print(cmd.command) } } else { print("Do Nothing") } } public init(name: String, message: String, roomAccess: [Room], commands: [Command]) { self.name = name self.message = message self.roomAccess = roomAccess self.commands = commands } public init(name: String, message: String, roomAccess: [Room]) { self.name = name self.message = message self.roomAccess = roomAccess } }
mit
neilpa/Dumpster
Dumpster/DequeType.swift
1
406
// Copyright (c) 2015 Neil Pankey. All rights reserved. /// Protocol for a double-ended queue where values inserted and removed from the front or back. public protocol DequeType : QueueType, StackType { /// Returns the last value in `DequeType`, `nil` if empty. var last: Element? { get } /// Removes the last value in `DequeType` and returns it. mutating func removeLast() -> Element }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/26001-swift-astcontext-astcontext.swift
1
499
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class C: " struct a {:ta struct S{ func a } protoc{}enum B{ {: {}} protocol a {struct B<T where B :d
apache-2.0
mcudich/TemplateKit
Source/Template/NodeRegistry.swift
1
1568
public class NodeRegistry { public typealias ElementBuilder = ([String: Any], [Element]?) -> Element public static let shared = NodeRegistry() private lazy var elementBuilders = [String: ElementBuilder]() init() { registerDefaultProviders() } public func registerComponent<T: Properties>(_ type: ComponentCreation.Type, _ propertiesType: T.Type) { registerElementBuilder("\(type)") { properties, children in return component(type, propertiesType.init(properties)) } } public func registerElementBuilder(_ name: String, builder: @escaping ElementBuilder) { self.elementBuilders[name] = builder } func buildElement(with name: String, properties: [String: Any], children: [Element]?) -> Element { return elementBuilders[name]!(properties, children) } private func registerDefaultProviders() { registerElementBuilder("box") { properties, children in return box(DefaultProperties(properties), children) } registerElementBuilder("text") { properties, children in return text(TextProperties(properties)) } registerElementBuilder("textfield") { properties, children in return textfield(TextFieldProperties(properties)) } registerElementBuilder("image") { properties, children in return image(ImageProperties(properties)) } registerElementBuilder("button") { properties, children in return button(ButtonProperties(properties)) } registerElementBuilder("table") { properties, children in return table(TableProperties(properties)) } } }
mit
adrfer/swift
test/ClangModules/Darwin_test.swift
24
624
// RUN: %target-parse-verify-swift %clang-importer-sdk // REQUIRES: objc_interop import Darwin import MachO _ = nil as Fract? // expected-error{{use of undeclared type 'Fract'}} _ = nil as Darwin.Fract? // okay _ = 0 as OSErr _ = noErr as OSStatus // noErr is from the overlay _ = 0 as UniChar _ = ProcessSerialNumber() _ = 0 as Byte // expected-error {{use of undeclared type 'Byte'}} {{10-14=UInt8}} Darwin.fakeAPIUsingByteInDarwin() as Int // expected-error {{cannot convert value of type 'UInt8' to type 'Int' in coercion}} _ = FALSE // expected-error {{use of unresolved identifier 'FALSE'}} _ = DYLD_BOOL.FALSE
apache-2.0
kshala-ford/sdl_ios
SmartDeviceLink_Example/MenuManager.swift
2
7299
// // MenuManager.swift // SmartDeviceLink-Example-Swift // // Created by Nicole on 4/11/18. // Copyright © 2018 smartdevicelink. All rights reserved. // import Foundation import SmartDeviceLink import SmartDeviceLinkSwift class MenuManager: NSObject { /// Creates and returns the menu items /// /// - Parameter manager: The SDL Manager /// - Returns: An array of SDLAddCommand objects class func allMenuItems(with manager: SDLManager) -> [SDLMenuCell] { return [menuCellSpeakName(with: manager), menuCellGetVehicleSpeed(with: manager), menuCellShowPerformInteraction(with: manager), menuCellRecordInCarMicrophoneAudio(with: manager), menuCellDialNumber(with: manager), menuCellWithSubmenu(with: manager)] } /// Creates and returns the voice commands. The voice commands are menu items that are selected using the voice recognition system. /// /// - Parameter manager: The SDL Manager /// - Returns: An array of SDLVoiceCommand objects class func allVoiceMenuItems(with manager: SDLManager) -> [SDLVoiceCommand] { guard manager.systemCapabilityManager.vrCapability else { SDLLog.e("The head unit does not support voice recognition") return [] } return [voiceCommandStart(with: manager), voiceCommandStop(with: manager)] } } // MARK: - Root Menu private extension MenuManager { /// Menu item that speaks the app name when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellSpeakName(with manager: SDLManager) -> SDLMenuCell { return SDLMenuCell(title: ACSpeakAppNameMenuName, icon: SDLArtwork(image: UIImage(named: SpeakBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACSpeakAppNameMenuName], handler: { _ in manager.send(request: SDLSpeak(tts: ExampleAppNameTTS), responseHandler: { (_, response, error) in guard response?.resultCode == .success else { return } SDLLog.e("Error sending the Speak RPC: \(error?.localizedDescription ?? "no error message")") }) }) } /// Menu item that requests vehicle data when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellGetVehicleSpeed(with manager: SDLManager) -> SDLMenuCell { return SDLMenuCell(title: ACGetVehicleDataMenuName, icon: SDLArtwork(image: UIImage(named: CarBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACGetVehicleDataMenuName], handler: { _ in VehicleDataManager.getVehicleSpeed(with: manager) }) } /// Menu item that shows a custom menu (i.e. a Perform Interaction Choice Set) when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellShowPerformInteraction(with manager: SDLManager) -> SDLMenuCell { return SDLMenuCell(title: ACShowChoiceSetMenuName, icon: SDLArtwork(image: UIImage(named: MenuBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACShowChoiceSetMenuName], handler: { triggerSource in PerformInteractionManager.showPerformInteractionChoiceSet(with: manager, triggerSource: triggerSource) }) } /// Menu item that starts recording sounds via the in-car microphone when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellRecordInCarMicrophoneAudio(with manager: SDLManager) -> SDLMenuCell { if #available(iOS 10.0, *) { let audioManager = AudioManager(sdlManager: manager) return SDLMenuCell(title: ACRecordInCarMicrophoneAudioMenuName, icon: SDLArtwork(image: UIImage(named: MicrophoneBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACRecordInCarMicrophoneAudioMenuName], handler: { _ in audioManager.startRecording() }) } return SDLMenuCell(title: ACRecordInCarMicrophoneAudioMenuName, icon: SDLArtwork(image: UIImage(named: SpeakBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACRecordInCarMicrophoneAudioMenuName], handler: { _ in manager.send(AlertManager.alertWithMessageAndCloseButton("Speech recognition feature only available on iOS 10+")) }) } /// Menu item that dials a phone number when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellDialNumber(with manager: SDLManager) -> SDLMenuCell { return SDLMenuCell(title: ACDialPhoneNumberMenuName, icon: SDLArtwork(image: UIImage(named: PhoneBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [ACDialPhoneNumberMenuName], handler: { _ in guard RPCPermissionsManager.isDialNumberRPCAllowed(with: manager) else { manager.send(AlertManager.alertWithMessageAndCloseButton("This app does not have the required permissions to dial a number")) return } VehicleDataManager.checkPhoneCallCapability(manager: manager, phoneNumber:"555-555-5555") }) } /// Menu item that opens a submenu when selected /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLMenuCell object class func menuCellWithSubmenu(with manager: SDLManager) -> SDLMenuCell { var submenuItems = [SDLMenuCell]() for i in 0..<75 { let submenuTitle = "Submenu Item \(i)" submenuItems.append(SDLMenuCell(title: submenuTitle, icon: SDLArtwork(image: UIImage(named: MenuBWIconImageName)!, persistent: true, as: .PNG), voiceCommands: [submenuTitle, "Item \(i)", "\(i)"], handler: { (triggerSource) in let message = "\(submenuTitle) selected!" switch triggerSource { case .menu: manager.send(AlertManager.alertWithMessageAndCloseButton(message)) case .voiceRecognition: manager.send(SDLSpeak(tts: message)) default: break } })) } return SDLMenuCell(title: "Submenu", subCells: submenuItems) } } // MARK: - Menu Voice Commands private extension MenuManager { /// Voice command menu item that shows an alert when triggered via the VR system /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLVoiceCommand object class func voiceCommandStart(with manager: SDLManager) -> SDLVoiceCommand { return SDLVoiceCommand(voiceCommands: [VCStart], handler: { manager.send(AlertManager.alertWithMessageAndCloseButton("\(VCStart) voice command selected!")) }) } /// Voice command menu item that shows an alert when triggered via the VR system /// /// - Parameter manager: The SDL Manager /// - Returns: A SDLVoiceCommand object class func voiceCommandStop(with manager: SDLManager) -> SDLVoiceCommand { return SDLVoiceCommand(voiceCommands: [VCStop], handler: { manager.send(AlertManager.alertWithMessageAndCloseButton("\(VCStop) voice command selected!")) }) } }
bsd-3-clause
TBXark/TKRubberIndicator
Example/Tests/Tests.swift
1
769
import UIKit import XCTest import TKRubberPageControl class Tests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
frootloops/swift
stdlib/public/core/ThreadLocalStorage.swift
1
6370
//===--- ThreadLocalStorage.swift -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // For testing purposes, a thread-safe counter to guarantee that destructors get // called by pthread. #if INTERNAL_CHECKS_ENABLED public // @testable let _destroyTLSCounter = _stdlib_AtomicInt() #endif // Thread local storage for all of the Swift standard library // // @moveonly/@pointeronly: shouldn't be used as a value, only through its // pointer. Similarly, shouldn't be created, except by // _initializeThreadLocalStorage. // @_versioned // FIXME(sil-serialize-all) @_fixed_layout // FIXME(sil-serialize-all) internal struct _ThreadLocalStorage { // TODO: might be best to absract uBreakIterator handling and caching into // separate struct. That would also make it easier to maintain multiple ones // and other TLS entries side-by-side. // Save a pre-allocated UBreakIterator, as they are very expensive to set up. // Each thread can reuse their unique break iterator, being careful to reset // the text when it has changed (see below). Even with a naive always-reset // policy, grapheme breaking is 30x faster when using a pre-allocated // UBreakIterator than recreating one. // // private @_versioned // FIXME(sil-serialize-all) internal var uBreakIterator: OpaquePointer // TODO: Consider saving two, e.g. for character-by-character comparison // The below cache key tries to avoid resetting uBreakIterator's text when // operating on the same String as before. Avoiding the reset gives a 50% // speedup on grapheme breaking. // // As a invalidation check, save the base address from the last used // StringCore. We can skip resetting the uBreakIterator's text when operating // on a given StringCore when both of these associated references/pointers are // equal to the StringCore's. Note that the owner is weak, to force it to // compare unequal if a new StringCore happens to be created in the same // memory. // // TODO: unowned reference to string owner, base address, and _countAndFlags // private: Should only be called by _initializeThreadLocalStorage @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_uBreakIterator: OpaquePointer) { self.uBreakIterator = _uBreakIterator } // Get the current thread's TLS pointer. On first call for a given thread, // creates and initializes a new one. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) static internal func getPointer() -> UnsafeMutablePointer<_ThreadLocalStorage> { let tlsRawPtr = _stdlib_thread_getspecific(_tlsKey) if _fastPath(tlsRawPtr != nil) { return tlsRawPtr._unsafelyUnwrappedUnchecked.assumingMemoryBound( to: _ThreadLocalStorage.self) } return _initializeThreadLocalStorage() } // Retrieve our thread's local uBreakIterator and set it up for the given // StringCore. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) static internal func getUBreakIterator( for core: _StringCore ) -> OpaquePointer { _sanityCheck(core._owner != nil || core._baseAddress != nil, "invalid StringCore") let corePtr: UnsafeMutablePointer<UTF16.CodeUnit> = core.startUTF16 return getUBreakIterator( for: UnsafeBufferPointer(start: corePtr, count: core.count)) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) static internal func getUBreakIterator( for bufPtr: UnsafeBufferPointer<UTF16.CodeUnit> ) -> OpaquePointer { let tlsPtr = getPointer() let brkIter = tlsPtr[0].uBreakIterator var err = __swift_stdlib_U_ZERO_ERROR __swift_stdlib_ubrk_setText( brkIter, bufPtr.baseAddress!, Int32(bufPtr.count), &err) _precondition(err.isSuccess, "Unexpected ubrk_setUText failure") return brkIter } } // Destructor to register with pthreads. Responsible for deallocating any memory // owned. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("_stdlib_destroyTLS") internal func _destroyTLS(_ ptr: UnsafeMutableRawPointer?) { _sanityCheck(ptr != nil, "_destroyTLS was called, but with nil...") let tlsPtr = ptr!.assumingMemoryBound(to: _ThreadLocalStorage.self) __swift_stdlib_ubrk_close(tlsPtr[0].uBreakIterator) tlsPtr.deinitialize(count: 1) tlsPtr.deallocate() #if INTERNAL_CHECKS_ENABLED // Log the fact we've destroyed our storage _destroyTLSCounter.fetchAndAdd(1) #endif } // Lazily created global key for use with pthread TLS @_versioned // FIXME(sil-serialize-all) internal let _tlsKey: __swift_thread_key_t = { let sentinelValue = __swift_thread_key_t.max var key: __swift_thread_key_t = sentinelValue let success = _stdlib_thread_key_create(&key, _destroyTLS) _sanityCheck(success == 0, "somehow failed to create TLS key") _sanityCheck(key != sentinelValue, "Didn't make a new key") return key }() @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @inline(never) internal func _initializeThreadLocalStorage() -> UnsafeMutablePointer<_ThreadLocalStorage> { _sanityCheck(_stdlib_thread_getspecific(_tlsKey) == nil, "already initialized") // Create and initialize one. var err = __swift_stdlib_U_ZERO_ERROR let newUBreakIterator = __swift_stdlib_ubrk_open( /*type:*/ __swift_stdlib_UBRK_CHARACTER, /*locale:*/ nil, /*text:*/ nil, /*textLength:*/ 0, /*status:*/ &err) _precondition(err.isSuccess, "Unexpected ubrk_open failure") let tlsPtr: UnsafeMutablePointer<_ThreadLocalStorage> = UnsafeMutablePointer<_ThreadLocalStorage>.allocate( capacity: 1 ) tlsPtr.initialize( to: _ThreadLocalStorage(_uBreakIterator: newUBreakIterator) ) let success = _stdlib_thread_setspecific(_tlsKey, tlsPtr) _sanityCheck(success == 0, "setspecific failed") return tlsPtr }
apache-2.0
adrfer/swift
validation-test/compiler_crashers_fixed/25774-swift-iterabledeclcontext-getmembers.swift
13
447
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a{class d{let c{ func a{ func a<T where T:a{ } class a{ let a{ class a{ protocol a{ class a{ protocol A{class S{class d{{ }let d{class d{let:{let c{ { } class a{let:{ class B{ class a{ class B{ protocol g{ class a{ protocol a
apache-2.0
adamgraham/STween
STween/STweenTests/Tweening/Conformance/CALayer+TweeningTest.swift
1
6033
// // CALayer+TweeningTest.swift // STween // // Created by Adam Graham on 1/19/17. // Copyright © 2017 Adam Graham. All rights reserved. // import XCTest @testable import STween class CALayer_TweeningTest: XCTestCase { func testFrameTweenProperty() { let layer = UIView().layer let value = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0) let property = CALayer.TweenProperty.frame(value) property.animation(layer)(1.0) XCTAssertEqual(layer.frame, value) } func testBoundsTweenProperty() { let layer = UIView().layer let value = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0) let property = CALayer.TweenProperty.bounds(value) property.animation(layer)(1.0) XCTAssertEqual(layer.bounds, value) } func testPositionTweenProperty() { let layer = UIView().layer let value = CGPoint(x: 100.0, y: 100.0) let property = CALayer.TweenProperty.position(value) property.animation(layer)(1.0) XCTAssertEqual(layer.position, value) } func testZPositionTweenProperty() { let layer = UIView().layer let value = CGFloat(100.0) let property = CALayer.TweenProperty.zPosition(value) property.animation(layer)(1.0) XCTAssertEqual(layer.zPosition, value) } func testAnchorPointTweenProperty() { let layer = UIView().layer let value = CGPoint(x: 100.0, y: 100.0) let property = CALayer.TweenProperty.anchorPoint(value) property.animation(layer)(1.0) XCTAssertEqual(layer.anchorPoint, value) } func testAnchorPointZTweenProperty() { let layer = UIView().layer let value = CGFloat(100.0) let property = CALayer.TweenProperty.anchorPointZ(value) property.animation(layer)(1.0) XCTAssertEqual(layer.anchorPointZ, value) } func testTransformTweenProperty() { let layer = UIView().layer let value = CATransform3DMakeScale(0.5, 0.5, 0.5) let property = CALayer.TweenProperty.transform(value) property.animation(layer)(1.0) XCTAssertEqual(layer.transform, value) } func testSublayerTransformTweenProperty() { let layer = UIView().layer let value = CATransform3DMakeScale(0.5, 0.5, 0.5) let property = CALayer.TweenProperty.sublayerTransform(value) property.animation(layer)(1.0) XCTAssertEqual(layer.sublayerTransform, value) } func testContentsRectTweenProperty() { let layer = UIView().layer let value = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0) let property = CALayer.TweenProperty.contentsRect(value) property.animation(layer)(1.0) XCTAssertEqual(layer.contentsRect, value) } func testContentsCenterTweenProperty() { let layer = UIView().layer let value = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0) let property = CALayer.TweenProperty.contentsCenter(value) property.animation(layer)(1.0) XCTAssertEqual(layer.contentsCenter, value) } @available(iOS 4.0, *) func testContentsScaleTweenProperty() { let layer = UIView().layer let value = CGFloat(0.5) let property = CALayer.TweenProperty.contentsScale(value) property.animation(layer)(1.0) XCTAssertEqual(layer.contentsScale, value) } func testCornerRadiusTweenProperty() { let layer = UIView().layer let value = CGFloat(5.0) let property = CALayer.TweenProperty.cornerRadius(value) property.animation(layer)(1.0) XCTAssertEqual(layer.cornerRadius, value) } func testBorderWidthTweenProperty() { let layer = UIView().layer let value = CGFloat(1.0) let property = CALayer.TweenProperty.borderWidth(value) property.animation(layer)(1.0) XCTAssertEqual(layer.borderWidth, value) } func testBorderColorTweenProperty() { let layer = UIView().layer layer.borderColor = nil let value = UIColor.red let property = CALayer.TweenProperty.borderColor(value) property.animation(layer)(1.0) XCTAssertEqual(layer.borderColor, value.cgColor) } func testBackgroundColorTweenProperty() { let layer = UIView().layer layer.backgroundColor = nil let value = UIColor.green let property = CALayer.TweenProperty.backgroundColor(value) property.animation(layer)(1.0) XCTAssertEqual(layer.backgroundColor, value.cgColor) } func testOpacityTweenProperty() { let layer = UIView().layer let value = Float(0.5) let property = CALayer.TweenProperty.opacity(value) property.animation(layer)(1.0) XCTAssertEqual(layer.opacity, value) } func testShadowColorTweenProperty() { let layer = UIView().layer layer.shadowColor = nil let value = UIColor.blue let property = CALayer.TweenProperty.shadowColor(value) property.animation(layer)(1.0) XCTAssertEqual(layer.shadowColor, value.cgColor) } func testShadowOpacityTweenProperty() { let layer = UIView().layer let value = Float(0.5) let property = CALayer.TweenProperty.shadowOpacity(value) property.animation(layer)(1.0) XCTAssertEqual(layer.shadowOpacity, value) } func testShadowOffsetTweenProperty() { let layer = UIView().layer let value = CGSize(width: 3.0, height: 3.0) let property = CALayer.TweenProperty.shadowOffset(value) property.animation(layer)(1.0) XCTAssertEqual(layer.shadowOffset, value) } func testShadowRadiusTweenProperty() { let layer = UIView().layer let value = CGFloat(5.0) let property = CALayer.TweenProperty.shadowRadius(value) property.animation(layer)(1.0) XCTAssertEqual(layer.shadowRadius, value) } }
mit
SereivoanYong/Charts
Source/Charts/Data/Implementations/Standard/ScatterDataSet.swift
1
2243
// // ScatterDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class ScatterDataSet: LineScatterCandleRadarDataSet, IScatterChartDataSet { public enum Shape { case square case circle case triangle case cross case x case chevronUp case chevronDown } /// The size the scatter shape will have open var scatterShapeSize: CGFloat = 10.0 /// The radius of the hole in the shape (applies to Square, Circle and Triangle) /// **default**: 0.0 open var scatterShapeHoleRadius: CGFloat = 0.0 /// Color for the hole in the shape. Setting to `nil` will behave as transparent. /// **default**: nil open var scatterShapeHoleColor: UIColor? /// Sets the ScatterShape this DataSet should be drawn with. /// This will search for an available IShapeRenderer and set this renderer for the DataSet open func setScatterShape(_ shape: Shape) { shapeRenderer = ScatterDataSet.renderer(for: shape) } /// The IShapeRenderer responsible for rendering this DataSet. /// This can also be used to set a custom IShapeRenderer aside from the default ones. /// **default**: `SquareShapeRenderer` open var shapeRenderer: IShapeRenderer? = SquareShapeRenderer() open class func renderer(for shape: Shape) -> IShapeRenderer { switch shape { case .square: return SquareShapeRenderer() case .circle: return CircleShapeRenderer() case .triangle: return TriangleShapeRenderer() case .cross: return CrossShapeRenderer() case .x: return XShapeRenderer() case .chevronUp: return ChevronUpShapeRenderer() case .chevronDown: return ChevronDownShapeRenderer() } } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! ScatterDataSet copy.scatterShapeSize = scatterShapeSize copy.scatterShapeHoleRadius = scatterShapeHoleRadius copy.scatterShapeHoleColor = scatterShapeHoleColor copy.shapeRenderer = shapeRenderer return copy } }
apache-2.0
pixyzehn/EsaKit
Sources/EsaKit/Models/Watcher.swift
1
1359
// // Watcher.swift // EsaKit // // Created by pixyzehn on 2016/11/26. // Copyright © 2016 pixyzehn. All rights reserved. // import Foundation public struct Watcher: AutoEquatable, AutoHashable { public let user: MinimumUser public let createdAt: Date enum Key: String { case user case createdAt = "created_at" } } extension Watcher: Decodable { public static func decode(json: Any) throws -> Watcher { guard let dictionary = json as? [String: Any] else { throw DecodeError.invalidFormat(json: json) } guard let userJSON = dictionary[Key.user.rawValue] else { throw DecodeError.missingValue(key: Key.user.rawValue, actualValue: dictionary[Key.user.rawValue]) } let user: MinimumUser do { user = try MinimumUser.decode(json: userJSON) } catch { throw DecodeError.custom(error.localizedDescription) } guard let createdAtString = dictionary[Key.createdAt.rawValue] as? String, let createdAt = DateFormatter.iso8601.date(from: createdAtString) else { throw DecodeError.missingValue(key: Key.createdAt.rawValue, actualValue: dictionary[Key.createdAt.rawValue]) } return Watcher( user: user, createdAt: createdAt ) } }
mit
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/DesignPatterns/DesignPatterns/CMS/Employee.swift
1
408
// // Employee.swift // DesignPatterns // // Created by 朱双泉 on 2018/4/23. // Copyright © 2018 Castie!. All rights reserved. // import Foundation class Employee { var name: String? var num: Int? var level: Int? var salary: Float? static var startNumber: Int = 1000 func two_stage_init() {} func promote() {} func calcSalary() {} func disInfor() {} }
mit
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageUnderstandingV1/Models/KeywordsOptions.swift
1
1850
/** * Copyright IBM Corporation 2018 * * 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 /** An option indicating whether or not important keywords from the analyzed content should be returned. */ public struct KeywordsOptions: Encodable { /// Maximum number of keywords to return. public var limit: Int? /// Set this to true to return sentiment information for detected keywords. public var sentiment: Bool? /// Set this to true to analyze emotion for detected keywords. public var emotion: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case limit = "limit" case sentiment = "sentiment" case emotion = "emotion" } /** Initialize a `KeywordsOptions` with member variables. - parameter limit: Maximum number of keywords to return. - parameter sentiment: Set this to true to return sentiment information for detected keywords. - parameter emotion: Set this to true to analyze emotion for detected keywords. - returns: An initialized `KeywordsOptions`. */ public init(limit: Int? = nil, sentiment: Bool? = nil, emotion: Bool? = nil) { self.limit = limit self.sentiment = sentiment self.emotion = emotion } }
mit
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/VisualRecognitionV3/Models/WarningInfo.swift
1
1094
/** * Copyright IBM Corporation 2018 * * 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 /** Information about something that went wrong. */ public struct WarningInfo: Decodable { /// Codified warning string, such as `limit_reached`. public var warningID: String /// Information about the error. public var description: String // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case warningID = "warning_id" case description = "description" } }
mit
DylanModesitt/Picryption_iOS
Picryption/Extensions.swift
1
3419
// // Extensions.swift // Picryption // // Created by Dylan Modesitt on 4/21/17. // Copyright © 2017 Modesitt Systems. All rights reserved. // import Foundation import UIKit extension String { // obvious extensions for the purpose of taking strings in and out of binary // sequences func toBinary() -> Data? { return self.data(using: String.Encoding.utf8, allowLossyConversion: false) } func toBinaryString(withFormat: String) -> String? { return self.toBinary()?.reduce("", { String(describing: $0) + String(format: withFormat, $1)}) } func toBinaryArray() -> [[Int]] { var binaryRepresentation: [[Int]] = [] let binary = self.toBinary()! for byte in binary { print(byte) binaryRepresentation.append(Int(byte).toBinaryArray()) } return binaryRepresentation } } extension Int { // returns the nuymber in binary form (as an array of ints 0, or 1) func toBinaryArray() -> [Int] { var binaryBuilder: [Int] = [] var number = self while number != 1 { binaryBuilder.append(number % 2) number /= 2 } binaryBuilder.append(1) return binaryBuilder.reversed() } } extension UIAlertView { static func simpleAlert(withTitle title: String, andMessage message: String) -> UIAlertView { let alert = self.init() alert.title = title alert.message = message alert.addButton(withTitle: "Ok") return alert } } extension UIColor { // Create a color for iOS from a hexCode static func fromHex(rgbValue:UInt32)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:1.0) } } extension Dictionary { mutating func update(other:Dictionary) { for (key,value) in other { self.updateValue(value, forKey:key) } } } extension UIViewController { func setStatusBarLight() { UIApplication.shared.statusBarStyle = .lightContent } func setStatusBarDefault() { UIApplication.shared.statusBarStyle = .default } } extension String { func toDate() -> NSDate? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy" return dateFormatter.date(from: self) as NSDate? } } extension String { func toTime() -> NSDate? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm" return dateFormatter.date(from: self) as NSDate? } } extension NSDate { func toDateString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy" return dateFormatter.string(from: self as Date) } func toTimeString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm" return dateFormatter.string(from: self as Date) } func toDateTraditionallyFormatted() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd, yyyy" return dateFormatter.string(from: self as Date) } }
mit
mattfenwick/TodoRx
TodoRx/LocalPersistence/CoreDataController.swift
1
4965
// // CoreDataController.swift // TodoRx // // Created by Matt Fenwick on 8/4/17. // Copyright © 2017 mf. All rights reserved. // import Foundation import CoreData import UIKit private let kMocIdentifier: NSString = "moc identifier" protocol CoreDataControllerDelegate: class { func coreDataControllerDidSave(controller: CoreDataController, result: CoreDataControllerSaveResult) } @objc class CoreDataController: NSObject { static func createCoreDataController(storeURL: URL, modelURL: URL) throws -> CoreDataController { let storeType = NSSQLiteStoreType let storeOptions = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] guard let model = NSManagedObjectModel(contentsOf: modelURL) else { throw CoreDataInitializationError.unableToInitializeModel } let psc = NSPersistentStoreCoordinator(managedObjectModel: model) do { try psc.addPersistentStore(ofType: storeType, configurationName: nil, at: storeURL, options: storeOptions) } catch let e as NSError { throw CoreDataInitializationError.unableToAddPersistentStore(e) } return CoreDataController(persistentStoreCoordinator: psc) } weak var delegate: CoreDataControllerDelegate? = nil let uiContext: NSManagedObjectContext func childContext(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.parent = masterContext context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy context.performAndWait { context.userInfo.setObject("child context", forKey: kMocIdentifier) } return context } private let masterContext: NSManagedObjectContext private init(persistentStoreCoordinator: NSPersistentStoreCoordinator) { masterContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) masterContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy masterContext.persistentStoreCoordinator = persistentStoreCoordinator masterContext.userInfo.setObject("master context", forKey: kMocIdentifier) uiContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) uiContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy uiContext.parent = masterContext uiContext.userInfo.setObject("main queue context", forKey: kMocIdentifier) super.init() NotificationCenter.default.addObserver( self, selector: #selector(handleMasterContextObjectsDidChangeNotification(notification:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: masterContext) NotificationCenter.default.addObserver( self, selector: #selector(handleMasterContextDidSaveNotification(notification:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: masterContext) let application = UIApplication.shared NotificationCenter.default.addObserver( self, selector: #selector(handleDidEnterBackgroundNotification(notification:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: application) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func handleMasterContextObjectsDidChangeNotification(notification: Notification) { if let context = notification.object as? NSManagedObjectContext, context == masterContext { saveMasterContext() } } @objc private func handleMasterContextDidSaveNotification(notification: Notification) { if let context = notification.object as? NSManagedObjectContext, context == masterContext { uiContext.perform { self.uiContext.mergeChanges(fromContextDidSave: notification) } } } @objc private func handleDidEnterBackgroundNotification(notification: Notification) { saveMasterContext() } private func saveMasterContext() { let identifier = UIApplication.shared.beginBackgroundTask(withName: "background-moc-save") { self.delegate?.coreDataControllerDidSave(controller: self, result: .backgroundTaskDidExpire) } masterContext.perform { do { try self.masterContext.save() self.delegate?.coreDataControllerDidSave(controller: self, result: .success) } catch let error as NSError { self.delegate?.coreDataControllerDidSave(controller: self, result: .saveException(error)) } UIApplication.shared.endBackgroundTask(identifier) } } }
mit
roytornado/RSLoadingView
Example/RSLoadingView/ViewController.swift
1
791
import UIKit import RSLoadingView class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func showOnView() { let loadingView = RSLoadingView() loadingView.shouldTapToDismiss = true loadingView.show(on: view) } @IBAction func showOnViewTwins() { let loadingView = RSLoadingView(effectType: RSLoadingView.Effect.twins) loadingView.shouldTapToDismiss = true loadingView.show(on: view) } @IBAction func showOnWindow() { let loadingView = RSLoadingView() loadingView.shouldTapToDismiss = true loadingView.variantKey = "inAndOut" loadingView.speedFactor = 2.0 loadingView.lifeSpanFactor = 2.0 loadingView.mainColor = UIColor.red loadingView.showOnKeyWindow() } }
mit
orlandoamorim/FamilyKey
FamilyKey/Sumary.swift
1
2946
// // Sumary.swift // FamilyKey // // Created by Orlando Amorim on 01/06/17. // Copyright © 2017 Orlando Amorim. All rights reserved. // import Foundation import RealmSwift class SumaryRealm: Object { dynamic var fantasyName = "" dynamic var name = "" let keys = List<KeyRealm>() dynamic var id = 0 func delete() { let realm = try! Realm() for key in keys { key.delete() try! realm.write { realm.delete(key) } } } } class Sumary : NSObject, NSCoding{ var descriptionField : String! var id : Int! var image : [AnyObject]! var key : String! var name : String! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ descriptionField = dictionary["description"] as? String id = dictionary["id"] as? Int image = dictionary["image"] as? [AnyObject] key = dictionary["key"] as? String name = dictionary["name"] as? String } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if descriptionField != nil{ dictionary["description"] = descriptionField } if id != nil{ dictionary["id"] = id } if image != nil{ dictionary["image"] = image } if key != nil{ dictionary["key"] = key } if name != nil{ dictionary["name"] = name } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { descriptionField = aDecoder.decodeObject(forKey: "description") as? String id = aDecoder.decodeObject(forKey: "id") as? Int image = aDecoder.decodeObject(forKey: "image") as? [AnyObject] key = aDecoder.decodeObject(forKey: "key") as? String name = aDecoder.decodeObject(forKey: "name") as? String } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if descriptionField != nil{ aCoder.encode(descriptionField, forKey: "description") } if id != nil{ aCoder.encode(id, forKey: "id") } if image != nil{ aCoder.encode(image, forKey: "image") } if key != nil{ aCoder.encode(key, forKey: "key") } if name != nil{ aCoder.encode(name, forKey: "name") } } }
mit
tkremenek/swift
validation-test/stdlib/Slice/Slice_Of_MinimalMutableCollection_WithPrefixAndSuffix.swift
21
3300
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [-9999, -9998, -9997, -9996, -9995] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<MinimalMutableCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = MinimalMutableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<MinimalMutableCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = MinimalMutableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<MinimalMutableCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = MinimalMutableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: prefix.count) let endIndex = base.index( base.startIndex, offsetBy: prefix.count + elements.count) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addMutableCollectionTests( "Slice_Of_MinimalMutableCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
noppoMan/aws-sdk-swift
Sources/Soto/Services/EMR/EMR_Paginator.swift
1
22834
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension EMR { /// Provides information about the bootstrap actions associated with a cluster. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBootstrapActionsPaginator<Result>( _ input: ListBootstrapActionsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBootstrapActionsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBootstrapActions, tokenKey: \ListBootstrapActionsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBootstrapActionsPaginator( _ input: ListBootstrapActionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBootstrapActionsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBootstrapActions, tokenKey: \ListBootstrapActionsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provides the status of all clusters visible to this AWS account. Allows you to filter the list of clusters based on certain criteria; for example, filtering by cluster creation date and time or by status. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListClusters calls. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listClustersPaginator<Result>( _ input: ListClustersInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListClustersOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listClusters, tokenKey: \ListClustersOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listClustersPaginator( _ input: ListClustersInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListClustersOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listClusters, tokenKey: \ListClustersOutput.marker, on: eventLoop, onPage: onPage ) } /// Lists all available details about the instance fleets in a cluster. The instance fleet configuration is available only in Amazon EMR versions 4.8.0 and later, excluding 5.0.x versions. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listInstanceFleetsPaginator<Result>( _ input: ListInstanceFleetsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListInstanceFleetsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listInstanceFleets, tokenKey: \ListInstanceFleetsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listInstanceFleetsPaginator( _ input: ListInstanceFleetsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListInstanceFleetsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listInstanceFleets, tokenKey: \ListInstanceFleetsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provides all available details about the instance groups in a cluster. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listInstanceGroupsPaginator<Result>( _ input: ListInstanceGroupsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListInstanceGroupsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listInstanceGroups, tokenKey: \ListInstanceGroupsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listInstanceGroupsPaginator( _ input: ListInstanceGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListInstanceGroupsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listInstanceGroups, tokenKey: \ListInstanceGroupsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provides information for all active EC2 instances and EC2 instances terminated in the last 30 days, up to a maximum of 2,000. EC2 instances in any of the following states are considered active: AWAITING_FULFILLMENT, PROVISIONING, BOOTSTRAPPING, RUNNING. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listInstancesPaginator<Result>( _ input: ListInstancesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListInstancesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listInstances, tokenKey: \ListInstancesOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listInstancesPaginator( _ input: ListInstancesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListInstancesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listInstances, tokenKey: \ListInstancesOutput.marker, on: eventLoop, onPage: onPage ) } /// Provides summaries of all notebook executions. You can filter the list based on multiple criteria such as status, time range, and editor id. Returns a maximum of 50 notebook executions and a marker to track the paging of a longer notebook execution list across multiple ListNotebookExecution calls. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listNotebookExecutionsPaginator<Result>( _ input: ListNotebookExecutionsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListNotebookExecutionsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listNotebookExecutions, tokenKey: \ListNotebookExecutionsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listNotebookExecutionsPaginator( _ input: ListNotebookExecutionsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListNotebookExecutionsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listNotebookExecutions, tokenKey: \ListNotebookExecutionsOutput.marker, on: eventLoop, onPage: onPage ) } /// Lists all the security configurations visible to this account, providing their creation dates and times, and their names. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListSecurityConfigurations calls. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSecurityConfigurationsPaginator<Result>( _ input: ListSecurityConfigurationsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSecurityConfigurationsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSecurityConfigurations, tokenKey: \ListSecurityConfigurationsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSecurityConfigurationsPaginator( _ input: ListSecurityConfigurationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSecurityConfigurationsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSecurityConfigurations, tokenKey: \ListSecurityConfigurationsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provides a list of steps for the cluster in reverse order unless you specify stepIds with the request of filter by StepStates. You can specify a maximum of ten stepIDs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listStepsPaginator<Result>( _ input: ListStepsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListStepsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSteps, tokenKey: \ListStepsOutput.marker, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listStepsPaginator( _ input: ListStepsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListStepsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSteps, tokenKey: \ListStepsOutput.marker, on: eventLoop, onPage: onPage ) } } extension EMR.ListBootstrapActionsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListBootstrapActionsInput { return .init( clusterId: self.clusterId, marker: token ) } } extension EMR.ListClustersInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListClustersInput { return .init( clusterStates: self.clusterStates, createdAfter: self.createdAfter, createdBefore: self.createdBefore, marker: token ) } } extension EMR.ListInstanceFleetsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListInstanceFleetsInput { return .init( clusterId: self.clusterId, marker: token ) } } extension EMR.ListInstanceGroupsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListInstanceGroupsInput { return .init( clusterId: self.clusterId, marker: token ) } } extension EMR.ListInstancesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListInstancesInput { return .init( clusterId: self.clusterId, instanceFleetId: self.instanceFleetId, instanceFleetType: self.instanceFleetType, instanceGroupId: self.instanceGroupId, instanceGroupTypes: self.instanceGroupTypes, instanceStates: self.instanceStates, marker: token ) } } extension EMR.ListNotebookExecutionsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListNotebookExecutionsInput { return .init( editorId: self.editorId, from: self.from, marker: token, status: self.status, to: self.to ) } } extension EMR.ListSecurityConfigurationsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListSecurityConfigurationsInput { return .init( marker: token ) } } extension EMR.ListStepsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EMR.ListStepsInput { return .init( clusterId: self.clusterId, marker: token, stepIds: self.stepIds, stepStates: self.stepStates ) } }
apache-2.0
noppoMan/aws-sdk-swift
Sources/Soto/Services/Support/Support_API.swift
1
21988
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS Support service. AWS Support The AWS Support API reference is intended for programmers who need detailed information about the AWS Support operations and data types. This service enables you to manage your AWS Support cases programmatically. It uses HTTP methods that return results in JSON format. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. The AWS Support service also exposes a set of AWS Trusted Advisor features. You can retrieve a list of checks and their descriptions, get check results, specify checks to refresh, and get the refresh status of checks. The following list describes the AWS Support case management operations: Service names, issue categories, and available severity levels. The DescribeServices and DescribeSeverityLevels operations return AWS service names, service codes, service categories, and problem severity levels. You use these values when you call the CreateCase operation. Case creation, case details, and case resolution. The CreateCase, DescribeCases, DescribeAttachment, and ResolveCase operations create AWS Support cases, retrieve information about cases, and resolve cases. Case communication. The DescribeCommunications, AddCommunicationToCase, and AddAttachmentsToSet operations retrieve and add communications and attachments to AWS Support cases. The following list describes the operations available from the AWS Support service for Trusted Advisor: DescribeTrustedAdvisorChecks returns the list of checks that run against your AWS resources. Using the checkId for a specific check returned by DescribeTrustedAdvisorChecks, you can call DescribeTrustedAdvisorCheckResult to obtain the results for the check that you specified. DescribeTrustedAdvisorCheckSummaries returns summarized results for one or more Trusted Advisor checks. RefreshTrustedAdvisorCheck requests that Trusted Advisor rerun a specified check. DescribeTrustedAdvisorCheckRefreshStatuses reports the refresh status of one or more checks. For authentication of requests, AWS Support uses Signature Version 4 Signing Process. See About the AWS Support API in the AWS Support User Guide for information about how to use this service to create and manage your support cases, and how to call Trusted Advisor for results of checks on your resources. */ public struct Support: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the Support client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "AWSSupport_20130415", service: "support", serviceProtocol: .json(version: "1.1"), apiVersion: "2013-04-15", endpoint: endpoint, serviceEndpoints: ["aws-cn-global": "support.cn-north-1.amazonaws.com.cn", "aws-global": "support.us-east-1.amazonaws.com", "aws-iso-b-global": "support.us-isob-east-1.sc2s.sgov.gov", "aws-iso-global": "support.us-iso-east-1.c2s.ic.gov", "aws-us-gov-global": "support.us-gov-west-1.amazonaws.com"], partitionEndpoints: [.aws: (endpoint: "aws-global", region: .useast1), .awscn: (endpoint: "aws-cn-global", region: .cnnorth1), .awsiso: (endpoint: "aws-iso-global", region: .usisoeast1), .awsisob: (endpoint: "aws-iso-b-global", region: .usisobeast1), .awsusgov: (endpoint: "aws-us-gov-global", region: .usgovwest1)], errorType: SupportErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Adds one or more attachments to an attachment set. An attachment set is a temporary container for attachments that you add to a case or case communication. The set is available for 1 hour after it's created. The expiryTime returned in the response is when the set expires. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func addAttachmentsToSet(_ input: AddAttachmentsToSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AddAttachmentsToSetResponse> { return self.client.execute(operation: "AddAttachmentsToSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds additional customer communication to an AWS Support case. Use the caseId parameter to identify the case to which to add communication. You can list a set of email addresses to copy on the communication by using the ccEmailAddresses parameter. The communicationBody value contains the text of the communication. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func addCommunicationToCase(_ input: AddCommunicationToCaseRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AddCommunicationToCaseResponse> { return self.client.execute(operation: "AddCommunicationToCase", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a case in the AWS Support Center. This operation is similar to how you create a case in the AWS Support Center Create Case page. The AWS Support API doesn't support requesting service limit increases. You can submit a service limit increase in the following ways: Submit a request from the AWS Support Center Create Case page. Use the Service Quotas RequestServiceQuotaIncrease operation. A successful CreateCase request returns an AWS Support case number. You can use the DescribeCases operation and specify the case number to get existing AWS Support cases. After you create a case, use the AddCommunicationToCase operation to add additional communication or attachments to an existing case. The caseId is separate from the displayId that appears in the AWS Support Center. Use the DescribeCases operation to get the displayId. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func createCase(_ input: CreateCaseRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateCaseResponse> { return self.client.execute(operation: "CreateCase", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the attachment that has the specified ID. Attachments can include screenshots, error logs, or other files that describe your issue. Attachment IDs are generated by the case management system when you add an attachment to a case or case communication. Attachment IDs are returned in the AttachmentDetails objects that are returned by the DescribeCommunications operation. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeAttachment(_ input: DescribeAttachmentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAttachmentResponse> { return self.client.execute(operation: "DescribeAttachment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of cases that you specify by passing one or more case IDs. You can use the afterTime and beforeTime parameters to filter the cases by date. You can set values for the includeResolvedCases and includeCommunications parameters to specify how much information to return. The response returns the following in JSON format: One or more CaseDetails data types. One or more nextToken values, which specify where to paginate the returned records represented by the CaseDetails objects. Case data is available for 12 months after creation. If a case was created more than 12 months ago, a request might return an error. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeCases(_ input: DescribeCasesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeCasesResponse> { return self.client.execute(operation: "DescribeCases", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns communications and attachments for one or more support cases. Use the afterTime and beforeTime parameters to filter by date. You can use the caseId parameter to restrict the results to a specific case. Case data is available for 12 months after creation. If a case was created more than 12 months ago, a request for data might cause an error. You can use the maxResults and nextToken parameters to control the pagination of the results. Set maxResults to the number of cases that you want to display on each page, and use nextToken to specify the resumption of pagination. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeCommunications(_ input: DescribeCommunicationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeCommunicationsResponse> { return self.client.execute(operation: "DescribeCommunications", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the current list of AWS services and a list of service categories for each service. You then use service names and categories in your CreateCase requests. Each AWS service has its own set of categories. The service codes and category codes correspond to the values that appear in the Service and Category lists on the AWS Support Center Create Case page. The values in those fields don't necessarily match the service codes and categories returned by the DescribeServices operation. Always use the service codes and categories that the DescribeServices operation returns, so that you have the most recent set of service and category codes. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeServices(_ input: DescribeServicesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeServicesResponse> { return self.client.execute(operation: "DescribeServices", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the list of severity levels that you can assign to an AWS Support case. The severity level for a case is also a field in the CaseDetails data type that you include for a CreateCase request. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeSeverityLevels(_ input: DescribeSeverityLevelsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeSeverityLevelsResponse> { return self.client.execute(operation: "DescribeSeverityLevels", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the refresh status of the AWS Trusted Advisor checks that have the specified check IDs. You can get the check IDs by calling the DescribeTrustedAdvisorChecks operation. Some checks are refreshed automatically, and you can't return their refresh statuses by using the DescribeTrustedAdvisorCheckRefreshStatuses operation. If you call this operation for these checks, you might see an InvalidParameterValue error. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeTrustedAdvisorCheckRefreshStatuses(_ input: DescribeTrustedAdvisorCheckRefreshStatusesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTrustedAdvisorCheckRefreshStatusesResponse> { return self.client.execute(operation: "DescribeTrustedAdvisorCheckRefreshStatuses", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the results of the AWS Trusted Advisor check that has the specified check ID. You can get the check IDs by calling the DescribeTrustedAdvisorChecks operation. The response contains a TrustedAdvisorCheckResult object, which contains these three objects: TrustedAdvisorCategorySpecificSummary TrustedAdvisorResourceDetail TrustedAdvisorResourcesSummary In addition, the response contains these fields: status - The alert status of the check: "ok" (green), "warning" (yellow), "error" (red), or "not_available". timestamp - The time of the last refresh of the check. checkId - The unique identifier for the check. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeTrustedAdvisorCheckResult(_ input: DescribeTrustedAdvisorCheckResultRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTrustedAdvisorCheckResultResponse> { return self.client.execute(operation: "DescribeTrustedAdvisorCheckResult", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the results for the AWS Trusted Advisor check summaries for the check IDs that you specified. You can get the check IDs by calling the DescribeTrustedAdvisorChecks operation. The response contains an array of TrustedAdvisorCheckSummary objects. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeTrustedAdvisorCheckSummaries(_ input: DescribeTrustedAdvisorCheckSummariesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTrustedAdvisorCheckSummariesResponse> { return self.client.execute(operation: "DescribeTrustedAdvisorCheckSummaries", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns information about all available AWS Trusted Advisor checks, including the name, ID, category, description, and metadata. You must specify a language code. The AWS Support API currently supports English ("en") and Japanese ("ja"). The response contains a TrustedAdvisorCheckDescription object for each check. You must set the AWS Region to us-east-1. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func describeTrustedAdvisorChecks(_ input: DescribeTrustedAdvisorChecksRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTrustedAdvisorChecksResponse> { return self.client.execute(operation: "DescribeTrustedAdvisorChecks", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Refreshes the AWS Trusted Advisor check that you specify using the check ID. You can get the check IDs by calling the DescribeTrustedAdvisorChecks operation. Some checks are refreshed automatically. If you call the RefreshTrustedAdvisorCheck operation to refresh them, you might see the InvalidParameterValue error. The response contains a TrustedAdvisorCheckRefreshStatus object. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func refreshTrustedAdvisorCheck(_ input: RefreshTrustedAdvisorCheckRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RefreshTrustedAdvisorCheckResponse> { return self.client.execute(operation: "RefreshTrustedAdvisorCheck", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Resolves a support case. This operation takes a caseId and returns the initial and final state of the case. You must have a Business or Enterprise support plan to use the AWS Support API. If you call the AWS Support API from an account that does not have a Business or Enterprise support plan, the SubscriptionRequiredException error message appears. For information about changing your support plan, see AWS Support. public func resolveCase(_ input: ResolveCaseRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ResolveCaseResponse> { return self.client.execute(operation: "ResolveCase", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension Support { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: Support, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
noprom/VPNOn
VPNOn/Theme/LTDarkPurpleTheme.swift
24
1013
// // LTDarkPurpleTheme.swift // VPNOn // // Created by Lex Tang on 1/30/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit struct LTDarkPurpleTheme : LTTheme { var name = "DarkPurple" var defaultBackgroundColor = UIColor.blackColor() var navigationBarColor = UIColor(red:0.06, green:0.03, blue:0.06, alpha:1) var tintColor = UIColor(red:0.7 , green:0.29, blue:0.8 , alpha:1) var textColor = UIColor(red:0.55, green:0.45, blue:0.55, alpha:1) var placeholderColor = UIColor(red:0.35, green:0.25, blue:0.35, alpha:1) var textFieldColor = UIColor(red:0.7 , green:0.5 , blue:0.7 , alpha:1) var tableViewBackgroundColor = UIColor.blackColor() var tableViewLineColor = UIColor(red:0.2 , green:0.15, blue:0.2 , alpha:1) var tableViewCellColor = UIColor(red:0.09, green:0.07, blue:0.09, alpha:1) var switchBorderColor = UIColor(red:0.25, green:0.2 , blue:0.25, alpha:1) }
mit
dche/FlatCG
Sources/Line.swift
1
1640
// // FlatCG - Line.swift // // Copyright (c) 2016 The GLMath authors. // Licensed under MIT License. import simd import GLMath /// Strait line in Euclidean space. public struct Line<T: Point> { public typealias DirectionType = Normal<T> /// A point on the line. public let origin: T /// Direction of the `Line`. public let direction: DirectionType /// Constructs a `Line` with given `origin` and `direction`. public init (origin: T, direction: DirectionType) { self.origin = origin self.direction = direction } public init? (origin: T, to: T) { guard let seg = Segment<T>(start: origin, end: to) else { return nil } self.init (origin: origin, direction: seg.direction) } public static prefix func - (rhs: Line) -> Line { return Line(origin: rhs.origin, direction: -rhs.direction) } } extension Line: CustomDebugStringConvertible { public var debugDescription: String { return "Line(origin: \(origin), direction: \(direction))" } } public typealias Line2D = Line<Point2D> public typealias Line3D = Line<Point3D> // MARK: Line point relationship. extension Line { /// Returns the point on the line that public func point(at t: T.VectorType.Component) -> T { return origin + direction.vector * t } /// Returns the minimal distance from `point` to the receiver. public func distance(to point: T) -> T.VectorType.Component { let v = point - self.origin let cos = dot(self.direction.vector, normalize(v)) return sqrt(v.dot(v) * (1 - cos * cos)) } }
mit
xwu/swift
stdlib/public/core/Zip.swift
22
5525
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. @inlinable // generic-performance public func zip<Sequence1, Sequence2>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(sequence1, sequence2) } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" @frozen // generic-performance public struct Zip2Sequence<Sequence1: Sequence, Sequence2: Sequence> { @usableFromInline // generic-performance internal let _sequence1: Sequence1 @usableFromInline // generic-performance internal let _sequence2: Sequence2 /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. @inlinable // generic-performance internal init(_ sequence1: Sequence1, _ sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } } extension Zip2Sequence { /// An iterator for `Zip2Sequence`. @frozen // generic-performance public struct Iterator { @usableFromInline // generic-performance internal var _baseStream1: Sequence1.Iterator @usableFromInline // generic-performance internal var _baseStream2: Sequence2.Iterator @usableFromInline // generic-performance internal var _reachedEnd: Bool = false /// Creates an instance around a pair of underlying iterators. @inlinable // generic-performance internal init( _ iterator1: Sequence1.Iterator, _ iterator2: Sequence2.Iterator ) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } } } extension Zip2Sequence.Iterator: IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Sequence1.Element, Sequence2.Element) /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable // generic-performance public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } } extension Zip2Sequence: Sequence { public typealias Element = (Sequence1.Element, Sequence2.Element) /// Returns an iterator over the elements of this sequence. @inlinable // generic-performance public __consuming func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } @inlinable // generic-performance public var underestimatedCount: Int { return Swift.min( _sequence1.underestimatedCount, _sequence2.underestimatedCount ) } }
apache-2.0
radex/swift-compiler-crashes
crashes-duplicates/13496-swift-sourcemanager-getmessage.swift
11
256
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { { case { extension String { protocol a { let start = [ { func a { class case ,
mit
konovalov-aleks/snake-game
client/platform/ios/Game/Game/AppDelegate.swift
3
292
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
gpl-3.0
radex/swift-compiler-crashes
crashes-duplicates/20814-swift-parser-skipsingle.swift
11
258
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { { let f = h [ { protocol b { struct S { class case , { [ [ [ { { { [ [ [ { [ { [ { { {
mit
radex/swift-compiler-crashes
crashes-fuzzing/09706-swift-typebase-isspecialized.swift
11
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{class a{class A:A protocol A let a{struct A{func b<h:A.b
mit
radex/swift-compiler-crashes
crashes-fuzzing/02791-swift-functiontype-get.swift
11
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{protocol A{ func c func c:b func b typealias b
mit
radex/swift-compiler-crashes
crashes-fuzzing/21760-swift-constraints-constraintsystem-simplifyconformstoconstraint.swift
11
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where B : P } [ ] func b( ) { var f = B
mit
jlandon/Alexandria
Sources/Alexandria/Int+Extensions.swift
1
5977
// // Int+Extensions.swift // // Created by Jonathan Landon on 11/19/15. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension Int { /// Determine if self is even (equivalent to `self % 2 == 0`) public var isEven: Bool { return (self % 2 == 0) } /// Determine if self is odd (equivalent to `self % 2 != 0`) public var isOdd: Bool { return (self % 2 != 0) } /// Determine if self is positive (equivalent to `self > 0`) public var isPositive: Bool { return (self > 0) } /// Determine if self is negative (equivalent to `self < 0`) public var isNegative: Bool { return (self < 0) } /** Convert self to a Double. Most useful when operating on Int optionals. For example: ``` let number: Int? = 5 // instead of var double: Double? if let number = number { double = Double(number) } // use let double = number?.double ``` */ public var double: Double { return Double(self) } /** Convert self to a Float. Most useful when operating on Int optionals. For example: ``` let number: Int? = 5 // instead of var float: Float? if let number = number { float = Float(number) } // use let float = number?.float ``` */ public var float: Float { return Float(self) } /** Convert self to a CGFloat. Most useful when operating on Int optionals. For example: ``` let number: Int? = 5 // instead of var cgFloat: CGFloat? if let number = number { cgFloat = CGFloat(number) } // use let cgFloat = number?.cgFloat ``` */ public var cgFloat: CGFloat { return CGFloat(self) } /** Convert self to a String. Most useful when operating on Int optionals. For example: ``` let number: Int? = 5 // instead of var string: String? if let number = number { string = String(number) } // use let string = number?.string ``` */ public var string: String { return String(self) } /** Convert self to an abbreviated String. Examples: ``` Value : 598 -> 598 Value : -999 -> -999 Value : 1000 -> 1K Value : -1284 -> -1.3K Value : 9940 -> 9.9K Value : 9980 -> 10K Value : 39900 -> 39.9K Value : 99880 -> 99.9K Value : 399880 -> 0.4M Value : 999898 -> 1M Value : 999999 -> 1M Value : 1456384 -> 1.5M Value : 12383474 -> 12.4M ``` - author: http://stackoverflow.com/a/35504720/1737738 */ public var abbreviatedString: String { typealias Abbreviation = (threshold: Double, divisor: Double, suffix: String) let abbreviations: [Abbreviation] = [(0, 1, ""), (1000.0, 1000.0, "K"), (100_000.0, 1_000_000.0, "M"), (100_000_000.0, 1_000_000_000.0, "B")] // you can add more ! let startValue = Double(abs(self)) let abbreviation: Abbreviation = { var prevAbbreviation = abbreviations[0] for tmpAbbreviation in abbreviations where tmpAbbreviation.threshold <= startValue { prevAbbreviation = tmpAbbreviation } return prevAbbreviation }() let numFormatter = NumberFormatter() let value = Double(self) / abbreviation.divisor numFormatter.positiveSuffix = abbreviation.suffix numFormatter.negativeSuffix = abbreviation.suffix numFormatter.allowsFloats = true numFormatter.minimumIntegerDigits = 1 numFormatter.minimumFractionDigits = 0 numFormatter.maximumFractionDigits = 1 return numFormatter.string(from: NSNumber(value: value)) ?? "\(self)" } /** Repeat a block `self` times. - parameter block: The block to execute (includes the current execution index) */ public func `repeat`(_ block: (Int) throws -> Void) rethrows { guard self > 0 else { return } try (1...self).forEach(block) } /// Generate a random Int bounded by a closed interval range. public static func random(_ range: ClosedRange<Int>) -> Int { return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound + 1))) } /// Generate a random Int bounded by a range from min to max. public static func random(min: Int, max: Int) -> Int { return random(min...max) } }
mit
devpunk/velvet_room
Source/View/Connecting/VConnectingError.swift
1
3022
import UIKit final class VConnectingError:View<ArchConnecting> { private let kMarginHorizontal:CGFloat = 45 required init(controller:CConnecting) { super.init(controller:controller) isUserInteractionEnabled = false factoryViews() } required init?(coder:NSCoder) { return nil } //MARK: private private func factoryViews() { guard let message:NSAttributedString = factoryMessage() else { return } let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.textAlignment = NSTextAlignment.center labelTitle.numberOfLines = 0 labelTitle.attributedText = message addSubview(labelTitle) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.equalsHorizontal( view:labelTitle, toView:self, margin:kMarginHorizontal) } private func factoryMessage() -> NSAttributedString? { guard let subtitle:NSAttributedString = factorySubtitle() else { return nil } let title:NSAttributedString = factoryTitle() let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(title) mutableString.append(subtitle) return mutableString } private func factoryTitle() -> NSAttributedString { let string:String = String.localizedView( key:"VConnectingError_labelTitle") let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.medium(size:22), NSAttributedStringKey.foregroundColor: UIColor.white] let attributed:NSAttributedString = NSAttributedString( string:string, attributes:attributes) return attributed } private func factorySubtitle() -> NSAttributedString? { guard let status:MConnectingStatusError = controller.model.status as? MConnectingStatusError else { return nil } let string:String = String.localizedView( key:status.errorMessage) let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:15), NSAttributedStringKey.foregroundColor: UIColor(white:1, alpha:0.9)] let attributed:NSAttributedString = NSAttributedString( string:string, attributes:attributes) return attributed } }
mit
lennet/bugreporter
BugreporterTests/ScreenRecorderSettingsTests.swift
1
1392
// // ScreenRecorderSettingsTests.swift // Bugreporter // // Created by Leo Thomas on 31/07/16. // Copyright © 2016 Leonard Thomas. All rights reserved. // import XCTest @testable import Bugreporter class ScreenRecorderSettingsTests: XCTestCase { func testCompareRecorderDurationOptions() { XCTAssert(RecorderDurationOptions.infinite == RecorderDurationOptions.infinite) XCTAssert(RecorderDurationOptions.finite(seconds: 50) == RecorderDurationOptions.finite(seconds: 50)) XCTAssertEqual(RecorderDurationOptions.infinite.seconds, 0) XCTAssertFalse(RecorderDurationOptions.infinite == RecorderDurationOptions.finite(seconds: 0)) XCTAssertFalse(RecorderDurationOptions.finite(seconds: 50) == RecorderDurationOptions.infinite) XCTAssertFalse(RecorderDurationOptions.finite(seconds: 50) == RecorderDurationOptions.finite(seconds: 60)) } func testRecorderDurationOptionsInit() { XCTAssert(RecorderDurationOptions(seconds: 0) == RecorderDurationOptions.infinite) let fiftySeconds = RecorderDurationOptions(seconds:50) if case .finite(let seconds) = fiftySeconds { XCTAssertEqual(seconds, 50) } else { XCTAssert(false == true, "getting seconds parameter from RecorderDurationOptions failed: \(fiftySeconds)") } } }
mit
LYM-mg/MGDS_Swift
MGDS_Swift/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQInvocation.swift
3
1751
// // IQInvocation.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-20 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @available(iOSApplicationExtension, unavailable) @objc public final class IQInvocation: NSObject { @objc public weak var target: AnyObject? @objc public var action: Selector @objc public init(_ target: AnyObject, _ action: Selector) { self.target = target self.action = action } @objc public func invoke(from: Any) { if let target = target { UIApplication.shared.sendAction(action, to: target, from: from, for: UIEvent()) } } deinit { target = nil } }
mit
carlynorama/learningSwift
Projects/RememberMe/RememberMe/AppDelegate.swift
1
4593
// // AppDelegate.swift // RememberMe // // Created by Carlyn Maw on 9/7/16. // Copyright © 2016 carlynorama. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "RememberMe") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
unlicense
mlgoogle/viossvc
viossvc/General/CommenClass/CommonDefine.swift
1
9271
// // CommonDefine.swift // HappyTravel // // Created by 陈奕涛 on 16/9/26. // Copyright © 2016年 陈奕涛. All rights reserved. // import Foundation //MARK: -- 颜色全局方法 func colorWithHexString(hex: String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if (cString.hasPrefix("#")) { cString = (cString as NSString).substringFromIndex(1) } let rString = (cString as NSString).substringToIndex(2) let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2) let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner(string: rString).scanHexInt(&r) NSScanner(string: gString).scanHexInt(&g) NSScanner(string: bString).scanHexInt(&b) return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1)) } //MARK: -- 字体大小全局变量 let ScreenWidth = UIScreen.mainScreen().bounds.size.width let ScreenHeight = UIScreen.mainScreen().bounds.size.height let Timestamp = NSDate().timeIntervalSince1970 let S18 = AtapteWidthValue(18) let S16 = AtapteWidthValue(16) let S15 = AtapteWidthValue(15) let S14 = AtapteWidthValue(14) let S13 = AtapteWidthValue(13) let S12 = AtapteWidthValue(12) let S10 = AtapteWidthValue(10) func AtapteWidthValue(value: CGFloat) -> CGFloat { let mate = ScreenWidth/375.0 let atapteValue = value*mate return atapteValue } func AtapteHeightValue(value: CGFloat) -> CGFloat { let mate = ScreenHeight/667.0 let atapteValue = value*mate return atapteValue } func getServiceDateString(start:Int, end:Int) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" // 8 * 3600 = 28800 let startTime = dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(start * 60 - 28800))) let endTime = dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(end * 60 - 28800))) return "\(startTime) - \(endTime)" } //MARK: --正则表达 func isTelNumber(num:NSString)->Bool { let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$" let CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$" let CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$" let CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$" let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile) let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM ) let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU) let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT) if ((regextestmobile.evaluateWithObject(num) == true) || (regextestcm.evaluateWithObject(num) == true) || (regextestct.evaluateWithObject(num) == true) || (regextestcu.evaluateWithObject(num) == true)) { return true } else { return false } } class CommonDefine: NSObject { static let DeviceToken = "deviceToken" static let UserName = "UserName" static let Passwd = "Passwd" static let UserType = "UserType" static let qiniuImgStyle = "?imageView2/2/w/160/h/160/interlace/0/q/100" static let errorMsgs: [Int: String] = [-1000:"mysql执行错误", -1001:"登陆json格式错误", -1002:"手机号格式有误", -1003:"手机号或密码错误", -1004:"获取附近导游json格式错误", -1005:"附近没有V领队", -1006:"心跳包json格式错误", -1007:"没有V领队", -1008:"推荐领队json格式错误", -1009:"没有推荐V领队", -1010:"邀约json格式错误", -1011:"修改密码json格式错误", -1012:"用户不在缓存", -1013:"旧密码错误", -1014:"聊天包json错误", -1015:"新建订单错误", -1016:"聊天记录json格式错误", -1017:"没有聊天记录", -1018:"获取验证码json格式错误", -1019:"注册账号json错误", -1020:"验证码过期", -1021:"验证码错误", -1022:"完善资料json错误", -1023:"我的行程json错误", -1024:"服务详情json错误", -1025:"没有该用户", -1026:"开票json错误", -1027:"没有改用户的设备号", -1028:"设备号错误", -1029:"消息读取json失败", -1030:"评价行程json错误", -1031:"回复邀约json错误", -1032:"订单状态有误", -1033:"开票记录json错误", -1034:"黑卡服务表无数据", -1035:"黑卡信息json错误", -1036:"黑卡消费记录json错误", -1037:"预约json错误", -1038:"已请求过开票了", -1039:"订单未支付完成", -1040:"当前没有在线客服", -1041:"发票详情json错误", -1042:"微信下单json错误", -1043:"下单金额有误", -1044:"客户端微信支付结果通知json错误", -1045:"身份证信息json错误", -1046:"V领队详情json错误", -1047:"身份认证状态json错误", -1048:"分享旅游列表json错误", -1049:"分享旅游详情json错误", -1050:"用户余额json错误", -1051:"身份认证状态json错误", -1052:"评价信息json错误", -1053:"没有评价信息:", -1054:"预约记录json错误", -1055:"预约记录为空(没有多记录了)", -1056:"技能分享详情json错误", -1057:"技能分享讨论json错误", -1058:"技能分享报名json错误", -1059:"请求数据错误", -1060:"微信服务回调错误", -1061:"微信下单失败", -1062:"验证密码 密码错误", -1063:"已经设置过支付密码了", -1064:"不能直接设置登录"] class BuriedPoint { static let register = "register" static let registerBtn = "registerBtn" static let registerNext = "registerNext" static let registerSure = "registerSure" static let login = "login" static let loginBtn = "loginBtn" static let loginAction = "loginAction" static let walletbtn = "walletbtn" static let rechargeBtn = "rechargeBtn" static let recharfeTextField = "recharfeTextField" static let paySureBtn = "paySureBtn" static let payWithWechat = "payWithWechat" static let paySuccess = "paySuccess" static let payForOrder = "payForOrder" static let payForOrderSuccess = "payForOrderSuccess" static let payForOrderFail = "payForOrderFail" static let vippage = "vippage" static let vipLvpay = "vipLvpay" } }
apache-2.0
ulidev/WWDC2015
Joan Molinas/Joan Molinas/BottomCollectionViewCell.swift
1
262
// // BottomCollectionViewCell.swift // Joan Molinas // // Created by Joan Molinas on 23/4/15. // Copyright (c) 2015 Joan. All rights reserved. // import UIKit class BottomCollectionViewCell: UICollectionViewCell { @IBOutlet var image : UIImageView! }
mit
RickPasveer/RPSwiftExtension
Sources/Extensions/UILabelExtension.swift
1
918
// // UILabelExtension.swift // // Created by Rick Pasveer on 24-06-16. // Copyright © 2016 Rick Pasveer. All rights reserved. // extension UILabel { /** Changes the `UILabel`s regular font. - Parameter substituteFontName: Font regular name */ var substituteFont : String { get { return self.font.fontName } set { if self.font.fontName.range(of: "Regular") != nil { self.font = UIFont(name: newValue, size: self.font.pointSize) } } } /** Changes the `UILabel`s bold font. - Parameter substituteFontName: Font bold name */ var substituteFontBold : String { get { return self.font.fontName } set { if self.font.fontName.range(of: "Bold") != nil { self.font = UIFont(name: newValue, size: self.font.pointSize) } } } }
mit
AndreaMiotto/NASApp
NASApp/DailyTableViewController.swift
1
1895
// // DailyTableViewController.swift // NASApp // // Created by Andrea Miotto on 23/03/17. // Copyright © 2017 Andrea Miotto. All rights reserved. // import UIKit import Alamofire class DailyTableViewController: UITableViewController { //---------------------- // MARK: - Variables //---------------------- /** It keep track of the daily*/ var daily: Daily? //---------------------- // MARK: - Outlets //---------------------- @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var explanationLabel: UILabel! //---------------------- // MARK: - View Functions //---------------------- override func viewDidLoad() { super.viewDidLoad() setLayout() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //---------------------- // MARK: - Methods //---------------------- ///It updates the layout with the right info func setLayout() { self.titleLabel.text = daily?.title self.imageView.image = daily?.image self.explanationLabel.text = daily?.explanation } //---------------------- // MARK: - Table view data source //---------------------- override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } }
apache-2.0
tonystone/tracelog
Tests/TraceLogTests/TraceLogTests.swift
1
16831
/// /// TraceLogTests.swift /// /// Copyright 2015 Tony Stone /// /// 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. /// /// Created by Tony Stone on 11/1/15. //// import XCTest import Dispatch import TraceLog /// /// Main test class for Swift /// class TraceLogTestsSwift: XCTestCase { let testTag = "Test Tag" // MARK: - Configuration func testConfigureWithNoArgs() { TraceLog.configure() } func testConfigureWithLogWriters() { let testMessage = "TraceLog Configured using: {\n\tglobal: {\n\n\t\tALL = INFO\n\t}\n}" let testWriter = ValidateExpectedValuesTestWriter(level: .info, tag: "TraceLog", message: testMessage) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "INFO"]) self.wait(for: [testWriter.expectation], timeout: 2) } func testConfigureWithLogWritersAndEnvironment() { let testMessage = "TraceLog Configured using: {\n\ttags: {\n\n\t\tTraceLog = TRACE4\n\t}\n\tprefixes: {\n\n\t\tNS = ERROR\n\t}\n\tglobal: {\n\n\t\tALL = TRACE4\n\t}\n}" let testWriter = ValidateExpectedValuesTestWriter(level: .info, tag: "TraceLog", message: testMessage) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE4", "LOG_PREFIX_NS": "ERROR", "LOG_TAG_TraceLog": "TRACE4"]) self.wait(for: [testWriter.expectation], timeout: 2) } func testConfigureWithLogWritersAndEnvironmentGlobalInvalidLogLevel() { let testEntries: [ValidateExpectedValuesTestWriter.ExpectedLogEntry] = [ (timestamp: nil, level: .info, tag: "TraceLog", message: "TraceLog Configured using: {\n\tglobal: {\n\n\t\tALL = INFO\n\t}\n}", runtimeContext: nil, staticContext: nil), (timestamp: nil, level: .warning, tag: "TraceLog", message: "Variable \'LOG_ALL\' has an invalid logLevel of \'TRACE5\'. \'LOG_ALL\' will be set to INFO.", runtimeContext: nil, staticContext: nil) ] let testWriter = ValidateExpectedValuesTestWriter(expected: testEntries) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE5"]) self.wait(for: [testWriter.expectation], timeout: 2) } func testConfigureWithLogWritersAndEnvironmentPrefixInvalidLogLevel() { let testEntries: [ValidateExpectedValuesTestWriter.ExpectedLogEntry] = [ (timestamp: nil, level: .info, tag: "TraceLog", message: "TraceLog Configured using: {\n\tglobal: {\n\n\t\tALL = INFO\n\t}\n}", runtimeContext: nil, staticContext: nil), (timestamp: nil, level: .warning, tag: "TraceLog", message: "Variable \'LOG_PREFIX_NS\' has an invalid logLevel of \'TRACE5\'. \'LOG_PREFIX_NS\' will NOT be set.", runtimeContext: nil, staticContext: nil) ] let testWriter = ValidateExpectedValuesTestWriter(expected: testEntries) TraceLog.configure(writers: [testWriter], environment: ["LOG_PREFIX_NS": "TRACE5"]) self.wait(for: [testWriter.expectation], timeout: 2) } func testConfigureWithLogWritersAndEnvironmentTagInvalidLogLevel() { let testEntries: [ValidateExpectedValuesTestWriter.ExpectedLogEntry] = [ (timestamp: nil, level: .info, tag: "TraceLog", message: "TraceLog Configured using: {\n\tglobal: {\n\n\t\tALL = INFO\n\t}\n}", runtimeContext: nil, staticContext: nil), (timestamp: nil, level: .warning, tag: "TraceLog", message: "Variable \'LOG_TAG_TRACELOG\' has an invalid logLevel of \'TRACE5\'. \'LOG_TAG_TRACELOG\' will NOT be set.", runtimeContext: nil, staticContext: nil) ] let testWriter = ValidateExpectedValuesTestWriter(expected: testEntries) TraceLog.configure(writers: [testWriter], environment: ["LOG_TAG_TraceLog": "TRACE5"]) self.wait(for: [testWriter.expectation], timeout: 2) } // MARK: ConcurrencyMode tests func testModeDirectIsSameThread() { let input: (thread: Thread, message: String) = (Thread.current, "Random test message.") let validatingWriter = CallbackTestWriter() { (timestamp, level, tag, message, runtimeContext, staticContext) -> Void in // We ignore all but the message that is equal to our input message to avoid TraceLogs startup messages if message == input.message { XCTAssertEqual(Thread.current, input.thread) } } TraceLog.configure(writers: [.direct(validatingWriter)], environment: ["LOG_ALL": "INFO"]) logInfo { input.message } } // Note: it does not make sense to test Sync for same thread or different as there is no guarantee it will be either. func testModeAsyncIsDifferentThread() { let semaphore = DispatchSemaphore(value: 0) let input: (thread: Thread, message: String) = (Thread.current, "Random test message.") let validatingWriter = CallbackTestWriter() { (timestamp, level, tag, message, runtimeContext, staticContext) -> Void in // We ignore all but the message that is equal to our input message to avoid TraceLogs startup messages if message == input.message { XCTAssertNotEqual(Thread.current, input.thread) semaphore.signal() } } /// Setup test with Writer TraceLog.configure(writers: [.async(validatingWriter)], environment: ["LOG_ALL": "INFO"]) /// Run test. logInfo { input.message } /// Wait for the thread to return XCTAssertEqual(semaphore.wait(timeout: .now() + 0.1), .success) } func testModeSyncBlocks() { let input: (thread: Thread, message: String) = (Thread.current, "Random test message.") var logged: Bool = false let validatingWriter = CallbackTestWriter() { (timestamp, level, tag, message, runtimeContext, staticContext) -> Void in // We ignore all but the message that is equal to our input message to avoid TraceLogs startup messages if message == input.message { logged = true } } TraceLog.configure(writers: [.sync(validatingWriter)], environment: ["LOG_ALL": "INFO"]) /// This should block until our writer is called. logInfo { input.message } XCTAssertEqual(logged, true) /// Not a definitive test. } func testNoDeadLockDirectMode() { TraceLog.configure(writers: [.direct(SleepyTestWriter(sleepTime: 100))], environment: ["LOG_ALL": "INFO"]) self._testNoDeadLock() } func testNoDeadLockSyncMode() { TraceLog.configure(writers: [.sync(SleepyTestWriter(sleepTime: 100))], environment: ["LOG_ALL": "INFO"]) self._testNoDeadLock() } func testNoDeadLockAsyncMode() { TraceLog.configure(writers: [.async(SleepyTestWriter(sleepTime: 100))], environment: ["LOG_ALL": "INFO"]) self._testNoDeadLock() } func _testNoDeadLock() { let queue = DispatchQueue(label: "_testNoDeadLock.queue", attributes: .concurrent) let loggers = DispatchGroup() for _ in 0...20 { queue.async(group: loggers) { for _ in 0...1000 { logInfo { "Random test message." } } } } /// Note: Increased this wait time to 120 for iPhone 6s iOS 9.3 which was taking a little longer to run threw the test. XCTAssertEqual(loggers.wait(timeout: .now() + 120.0), .success) } // MARK: - Logging Methods func testLogError() { let testMessage = "Swift: \(#function)" let testWriter = ValidateExpectedValuesTestWriter(level: .error, tag: self.testTag, message: testMessage) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "ERROR"]) logError(testTag) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogWarning() { let testMessage = "Swift: \(#function)" let testWriter = ValidateExpectedValuesTestWriter(level: .warning, tag: self.testTag, message: testMessage) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "WARNING"]) logWarning(testTag) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogInfo() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .info, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "INFO"]) logInfo(testTag) { "Swift: \(#function)" } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogTrace() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .trace1, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE1"]) logTrace(testTag) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogTrace1() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .trace1, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE1"]) logTrace(testTag, level: 1) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogTrace2() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .trace2, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE2"]) logTrace(testTag, level: 2) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogTrace3() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .trace3, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE3"]) logTrace(testTag, level: 3) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } func testLogTrace4() { let testMessage = "Swift: " + #function let testWriter = ValidateExpectedValuesTestWriter(level: .trace4, tag: testTag, message: testMessage, filterTags: ["TraceLog"]) TraceLog.configure(writers: [testWriter], environment: ["LOG_ALL": "TRACE4"]) logTrace(testTag, level: 4) { testMessage } self.wait(for: [testWriter.expectation], timeout: 2) } // MARK: - Logging Methods when level below log level. func testLogErrorWhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logError(testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogWarningWhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logWarning(testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogInfoWhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logInfo(testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogTraceWhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logTrace(testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogTrace1WhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logTrace(1, testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogTrace2WhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logTrace(2, testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogTrace3WhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logTrace(3, testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } func testLogTrace4WhileOff() { let testMessage = "Swift: " + #function let semaphore = DispatchSemaphore(value: 0) let writer = FailWhenFiredWriter(semaphore: semaphore) TraceLog.configure(writers: [writer], environment: ["LOG_ALL": "OFF"]) logTrace(4, testTag) { testMessage } let result = semaphore.wait(wallTimeout: DispatchWallTime.now() + .seconds(1)) /// Note: success in this case means the test failed because the semaphore was signaled by the call to log the message. if result == .success { XCTAssertNil("Log level was OFF but message was written anyway.") } } }
apache-2.0
narner/AudioKit
AudioKit/iOS/AudioKit/User Interface/AKResourceAudioFileLoaderView.swift
1
15930
// // AKResourceAudioFileLoaderView.swift // AudioKit for iOS // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// View to choose from audio files to use in playgrounds @IBDesignable open class AKResourcesAudioFileLoaderView: UIView { // Default corner radius static var standardCornerRadius: CGFloat = 3.0 var player: AKAudioPlayer? var stopOuterPath = UIBezierPath() var playOuterPath = UIBezierPath() var upOuterPath = UIBezierPath() var downOuterPath = UIBezierPath() var currentIndex = 0 var titles = [String]() open var bgColor: AKColor? { didSet { setNeedsDisplay() } } open var textColor: AKColor? { didSet { setNeedsDisplay() } } open var borderColor: AKColor? { didSet { setNeedsDisplay() } } open var borderWidth: CGFloat = 3.0 { didSet { setNeedsDisplay() } } /// Handle touches override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { var isFileChanged = false guard let isPlayerPlaying = player?.isPlaying else { return } let touchLocation = touch.location(in: self) if stopOuterPath.contains(touchLocation) { player?.stop() } if playOuterPath.contains(touchLocation) { player?.play() } if upOuterPath.contains(touchLocation) { currentIndex -= 1 isFileChanged = true } if downOuterPath.contains(touchLocation) { currentIndex += 1 isFileChanged = true } if currentIndex < 0 { currentIndex = titles.count - 1 } if currentIndex >= titles.count { currentIndex = 0 } if isFileChanged { player?.stop() let filename = titles[currentIndex] if let file = try? AKAudioFile(readFileName: "\(filename)", baseDir: .resources) { do { try player?.replace(file: file) } catch { AKLog("Could not replace file") } } if isPlayerPlaying { player?.play() } setNeedsDisplay() } } } /// Initialize the resource loader public convenience init(player: AKAudioPlayer, filenames: [String], frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60)) { self.init(frame: frame) self.player = player self.titles = filenames } /// Initialization with no details override public init(frame: CGRect) { self.titles = ["File One", "File Two", "File Three"] super.init(frame: frame) self.backgroundColor = UIColor.clear contentMode = .redraw } /// Initialize in Interface Builder required public init?(coder aDecoder: NSCoder) { self.titles = ["File One", "File Two", "File Three"] super.init(coder: aDecoder) self.backgroundColor = UIColor.clear contentMode = .redraw } // Default background color per theme var bgColorForTheme: AKColor { if let bgColor = bgColor { return bgColor } switch AKStylist.sharedInstance.theme { case .basic: return AKColor(white: 0.8, alpha: 1.0) case .midnight: return AKColor(white: 0.7, alpha: 1.0) } } // Default border color per theme var borderColorForTheme: AKColor { if let borderColor = borderColor { return borderColor } switch AKStylist.sharedInstance.theme { case .basic: return AKColor(white: 0.3, alpha: 1.0).withAlphaComponent(0.8) case .midnight: return AKColor.white.withAlphaComponent(0.8) } } // Default text color per theme var textColorForTheme: AKColor { if let textColor = textColor { return textColor } switch AKStylist.sharedInstance.theme { case .basic: return AKColor(white: 0.3, alpha: 1.0) case .midnight: return AKColor.white } } func drawAudioFileLoader(sliderColor: AKColor = AKStylist.sharedInstance.colorForFalseValue, fileName: String = "None") { //// General Declarations let rect = bounds let cornerRadius: CGFloat = AKResourcesAudioFileLoaderView.standardCornerRadius //// Color Declarations let backgroundColor = bgColorForTheme let color = AKStylist.sharedInstance.colorForTrueValue let dark = textColorForTheme //// background Drawing let backgroundPath = UIBezierPath(rect: CGRect(x: borderWidth, y: borderWidth, width: rect.width - borderWidth * 2.0, height: rect.height - borderWidth * 2.0)) backgroundColor.setFill() backgroundPath.fill() //// stopButton //// stopOuter Drawing stopOuterPath = UIBezierPath(rect: CGRect(x: borderWidth, y: borderWidth, width: rect.width * 0.13, height: rect.height - borderWidth * 2.0)) sliderColor.setFill() stopOuterPath.fill() //// stopInner Drawing let stopInnerPath = UIBezierPath(roundedRect: CGRect(x: (rect.width * 0.13 - rect.height * 0.5) / 2 + cornerRadius, y: rect.height * 0.25, width: rect.height * 0.5, height: rect.height * 0.5), cornerRadius: cornerRadius) dark.setFill() stopInnerPath.fill() //// playButton //// playOuter Drawing playOuterPath = UIBezierPath(rect: CGRect(x: rect.width * 0.13 + borderWidth, y: borderWidth, width: rect.width * 0.13, height: rect.height - borderWidth * 2.0)) color.setFill() playOuterPath.fill() //// playInner Drawing let playRect = CGRect(x: (rect.width * 0.13 - rect.height * 0.5) / 2 + borderWidth + rect.width * 0.13 + borderWidth, y: rect.height * 0.25, width: rect.height * 0.5, height: rect.height * 0.5) let playInnerPath = UIBezierPath() playInnerPath.move(to: CGPoint(x: playRect.minX + cornerRadius / 2.0, y: playRect.maxY)) playInnerPath.addLine(to: CGPoint(x: playRect.maxX - cornerRadius / 2.0, y: playRect.midY + cornerRadius / 2.0)) playInnerPath.addCurve(to: CGPoint(x: playRect.maxX - cornerRadius / 2.0, y: playRect.midY - cornerRadius / 2.0), controlPoint1: CGPoint(x: playRect.maxX, y: playRect.midY), controlPoint2: CGPoint(x: playRect.maxX, y: playRect.midY)) playInnerPath.addLine(to: CGPoint(x: playRect.minX + cornerRadius / 2.0, y: playRect.minY)) playInnerPath.addCurve(to: CGPoint(x: playRect.minX, y: playRect.minY + cornerRadius / 2.0), controlPoint1: CGPoint(x: playRect.minX, y: playRect.minY), controlPoint2: CGPoint(x: playRect.minX, y: playRect.minY)) playInnerPath.addLine(to: CGPoint(x: playRect.minX, y: playRect.maxY - cornerRadius / 2.0)) playInnerPath.addCurve(to: CGPoint(x: playRect.minX + cornerRadius / 2.0, y: playRect.maxY), controlPoint1: CGPoint(x: playRect.minX, y: playRect.maxY), controlPoint2: CGPoint(x: playRect.minX, y: playRect.maxY)) playInnerPath.close() dark.setFill() playInnerPath.fill() dark.setStroke() playInnerPath.stroke() // stopButton border Path let stopButtonBorderPath = UIBezierPath() stopButtonBorderPath.move(to: CGPoint(x: rect.width * 0.13 + borderWidth, y: borderWidth)) stopButtonBorderPath.addLine(to: CGPoint(x: rect.width * 0.13 + borderWidth, y: rect.height - borderWidth)) borderColorForTheme.setStroke() stopButtonBorderPath.lineWidth = borderWidth / 2.0 stopButtonBorderPath.stroke() // playButton border Path let playButtonBorderPath = UIBezierPath() playButtonBorderPath.move(to: CGPoint(x: rect.width * 0.13 * 2.0 + borderWidth, y: borderWidth)) playButtonBorderPath.addLine(to: CGPoint(x: rect.width * 0.13 * 2.0 + borderWidth, y: rect.height - borderWidth)) borderColorForTheme.setStroke() playButtonBorderPath.lineWidth = borderWidth / 2.0 playButtonBorderPath.stroke() //// upButton //// upOuter Drawing downOuterPath = UIBezierPath(rect: CGRect(x: rect.width * 0.9, y: rect.height * 0.5, width: rect.width * 0.07, height: rect.height * 0.5)) //// upInner Drawing let downArrowRect = CGRect(x: rect.width * 0.9, y: rect.height * 0.58, width: rect.width * 0.07, height: rect.height * 0.3) let downInnerPath = UIBezierPath() downInnerPath.move(to: CGPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.minY)) downInnerPath.addLine(to: CGPoint(x: downArrowRect.maxX - cornerRadius / 2.0, y: downArrowRect.minY)) downInnerPath.addCurve(to: CGPoint(x: downArrowRect.maxX - cornerRadius / 2.0, y: downArrowRect.minY + cornerRadius / 2.0), controlPoint1: CGPoint(x: downArrowRect.maxX, y: downArrowRect.minY), controlPoint2: CGPoint(x: downArrowRect.maxX, y: downArrowRect.minY)) downInnerPath.addLine(to: CGPoint(x: downArrowRect.midX + cornerRadius / 2.0, y: downArrowRect.maxY - cornerRadius / 2.0)) downInnerPath.addCurve(to: CGPoint(x: downArrowRect.midX - cornerRadius / 2.0, y: downArrowRect.maxY - cornerRadius / 2.0), controlPoint1: CGPoint(x: downArrowRect.midX, y: downArrowRect.maxY), controlPoint2: CGPoint(x: downArrowRect.midX, y: downArrowRect.maxY)) downInnerPath.addLine(to: CGPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.minY + cornerRadius / 2.0)) downInnerPath.addCurve(to: CGPoint(x: downArrowRect.minX + cornerRadius / 2.0, y: downArrowRect.minY), controlPoint1: CGPoint(x: downArrowRect.minX, y: downArrowRect.minY), controlPoint2: CGPoint(x: downArrowRect.minX, y: downArrowRect.minY)) textColorForTheme.setStroke() downInnerPath.lineWidth = borderWidth downInnerPath.stroke() upOuterPath = UIBezierPath(rect: CGRect(x: rect.width * 0.9, y: 0, width: rect.width * 0.07, height: rect.height * 0.5)) //// downInner Drawing let upperArrowRect = CGRect(x: rect.width * 0.9, y: rect.height * 0.12, width: rect.width * 0.07, height: rect.height * 0.3) let upInnerPath = UIBezierPath() upInnerPath.move(to: CGPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.maxY)) upInnerPath.addLine(to: CGPoint(x: upperArrowRect.maxX - cornerRadius / 2.0, y: upperArrowRect.maxY)) upInnerPath.addCurve(to: CGPoint(x: upperArrowRect.maxX - cornerRadius / 2.0, y: upperArrowRect.maxY - cornerRadius / 2.0), controlPoint1: CGPoint(x: upperArrowRect.maxX, y: upperArrowRect.maxY), controlPoint2: CGPoint(x: upperArrowRect.maxX, y: upperArrowRect.maxY)) upInnerPath.addLine(to: CGPoint(x: upperArrowRect.midX + cornerRadius / 2.0, y: upperArrowRect.minY + cornerRadius / 2.0)) upInnerPath.addCurve(to: CGPoint(x: upperArrowRect.midX - cornerRadius / 2.0, y: upperArrowRect.minY + cornerRadius / 2.0), controlPoint1: CGPoint(x: upperArrowRect.midX, y: upperArrowRect.minY), controlPoint2: CGPoint(x: upperArrowRect.midX, y: upperArrowRect.minY)) upInnerPath.addLine(to: CGPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.maxY - cornerRadius / 2.0)) upInnerPath.addCurve(to: CGPoint(x: upperArrowRect.minX + cornerRadius / 2.0, y: upperArrowRect.maxY), controlPoint1: CGPoint(x: upperArrowRect.minX, y: upperArrowRect.maxY), controlPoint2: CGPoint(x: upperArrowRect.minX, y: upperArrowRect.maxY)) textColorForTheme.setStroke() upInnerPath.lineWidth = borderWidth upInnerPath.stroke() //// nameLabel Drawing let nameLabelRect = CGRect(x: 120, y: 0, width: 320, height: 60) let nameLabelStyle = NSMutableParagraphStyle() nameLabelStyle.alignment = .left let nameLabelFontAttributes = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 24.0), NSAttributedStringKey.foregroundColor: textColorForTheme, NSAttributedStringKey.paragraphStyle: nameLabelStyle] let nameLabelInset: CGRect = nameLabelRect.insetBy(dx: 10, dy: 0) let nameLabelTextHeight: CGFloat = NSString(string: fileName).boundingRect( with: CGSize(width: nameLabelInset.width, height: CGFloat.infinity), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: nameLabelFontAttributes, context: nil).size.height let nameLabelTextRect: CGRect = CGRect( x: nameLabelInset.minX, y: nameLabelInset.minY + (nameLabelInset.height - nameLabelTextHeight) / 2, width: nameLabelInset.width, height: nameLabelTextHeight) NSString(string: fileName).draw(in: nameLabelTextRect.offsetBy(dx: 0, dy: 0), withAttributes: nameLabelFontAttributes) let outerRect = CGRect(x: rect.origin.x + borderWidth / 2.0, y: rect.origin.y + borderWidth / 2.0, width: rect.width - borderWidth, height: rect.height - borderWidth) let outerPath = UIBezierPath(roundedRect: outerRect, cornerRadius: cornerRadius) borderColorForTheme.setStroke() outerPath.lineWidth = borderWidth outerPath.stroke() } open override func draw(_ rect: CGRect) { drawAudioFileLoader(fileName: titles[currentIndex]) } }
mit
cnbin/WordPress-iOS
WordPress/Classes/ViewRelated/Views/RichTextView/UITextView+RichTextView.swift
7
504
import Foundation extension UITextView { func frameForTextInRange(range: NSRange) -> CGRect { let firstPosition = positionFromPosition(beginningOfDocument, offset: range.location) let lastPosition = positionFromPosition(beginningOfDocument, offset: range.location + range.length) let textRange = textRangeFromPosition(firstPosition!, toPosition: lastPosition!) let textFrame = firstRectForRange(textRange!) return textFrame } }
gpl-2.0
BenchR267/TouchPresenter
Example/TouchPresenter/AppDelegate.swift
1
587
// // AppDelegate.swift // TouchPresenter // // Created by Benjamin Herzog on 07/17/2016. // Copyright (c) 2016 Benjamin Herzog. All rights reserved. // import UIKit import TouchPresenter @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? override init() { let config = TouchPresenterConfiguration(viewType: UIImageView.self, enable3DTouch: true) { $0.image = UIImage(named: "oval") } window = TPWindow(frame: UIScreen.main.bounds, configuration: config) super.init() } }
mit
adly-holler/Bond
Bond/OSX/Bond+NSMenuItem.swift
12
2846
// // The MIT License (MIT) // // Copyright (c) 2015 Tony Arnold (@tonyarnold) // // 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 Cocoa var enabledDynamicHandleNSMenuItem: UInt8 = 0; var stateDynamicHandleNSMenuItem: UInt8 = 0; extension NSMenuItem: Bondable, Dynamical { public var designatedDynamic: Dynamic<Bool> { return self.dynEnabled } public var designatedBond: Bond<Bool> { return self.designatedDynamic.valueBond } public var dynEnabled: Dynamic<Bool> { if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleNSMenuItem) { return (d as? Dynamic<Bool>)! } else { let d = InternalDynamic<Bool>(self.enabled) let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &enabledDynamicHandleNSMenuItem, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } public var dynState: Dynamic<Int> { if let d: AnyObject = objc_getAssociatedObject(self, &stateDynamicHandleNSMenuItem) { return (d as? Dynamic<Int>)! } else { let d = InternalDynamic<Int>(self.state) let bond = Bond<Int>() { [weak self] v in if let s = self { s.state = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &stateDynamicHandleNSMenuItem, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } }
mit
guille969/Licensy
Licensy/Sources/Licenses/Model/LicenseTypes/BSD3ClauseLicense.swift
1
1830
// // BSD3ClauseLicense.swift // Licensy // // Created by Guillermo Garcia Rebolo on 22/2/17. // Copyright © 2017 RetoLabs. All rights reserved. // /// BSD 3-Clause License public class BSD3ClauseLicense: License { fileprivate var company: String = "" fileprivate var copyright: String = "" /// The initializer of the license public init() { } /// The identifier of the license public var identifier: String { get { return "BSD3" } } /// The name of the license public var name: String { get { return "BSD 3-Clause License" } } /// The license text public var text: String { get { guard let value: String = LicenseParser.getContent("bsd3") else { return "" } return String(format: value, company) } } /// The minimal license text public var minimalText: String { get { guard let value: String = LicenseParser.getContent("bsd3_minimal") else { return "" } return String(format: value, company) } } /// The license version public var version: String { get { return "" } } /// The license URL public var url: String { get { return "http://opensource.org/licenses/BSD-3-Clause" } } /// Configure the company and the copyright of the library for the license /// /// - Parameters: /// - company: the company of the library /// - copyright: the copyright of the library public func formatLicenseText(with company: String, copyright: String) { self.company = company self.copyright = copyright } }
mit
luoboding/sagittarius-swift
sagittarius-swift/common/extension/Array+find.swift
1
518
// // Array+find.swift // sagittarius-swift // // Created by bonedeng on 5/15/16. // Copyright © 2016 xingdongyou. All rights reserved. // import UIKit public extension Array { func find(block:Element->Bool) -> (data: Element?, index:Int) { let length = self.count let idx = -1; for (var i = 0; i < length; i++) { if block(self[i]) { return (data: self[i], index: i) } } return (data: nil, index:idx) } }
apache-2.0
sunzeboy/realm-cocoa
RealmSwift-swift1.2/List.swift
10
12881
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase, Printable { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the list. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", type, _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this list. public var count: Int { return Int(_rlmArray.count) } } /** `List<T>` is the container type in Realm used to define to-many relationships. Lists hold a single `Object` subclass (`T`) which defines the "type" of the list. Lists can be filtered and sorted with the same predicates as `Results<T>`. When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { // MARK: Properties /// The Realm the objects in this list belong to, or `nil` if the list's owning /// object does not belong to a realm (the list is standalone). public var realm: Realm? { if let rlmRealm = _rlmArray.realm { return Realm(rlmRealm) } else { return nil } } /// Indicates if the list can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds objects of type `T`. public override init() { super.init(array: RLMArray(objectClassName: T.className())) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the list. :param: object The object whose index is being queried. :returns: The index of the given object, or `nil` if the object is not in the list. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. :param: predicate The `NSPredicate` used to filter the objects. :returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. :param: predicateFormat The predicate format string, optionally followed by a variable number of arguments. :returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } // MARK: Object Retrieval /** Returns the object at the given `index` on get. Replaces the object at the given `index` on set. :warning: You can only set an object during a write transaction. :param: index The index. :returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = newValue } } /// Returns the first object in the list, or `nil` if empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the list, or `nil` if empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. :param: key The name of the property. :returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. :warning: This method can only be called during a write transaction. :param: value The object value. :param: key The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns `Results` containing list elements that match the given predicate. :param: predicateFormat The predicate format string which can accept variable arguments. :returns: `Results` containing list elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args)))) } /** Returns `Results` containing list elements that match the given predicate. :param: predicate The predicate to filter the objects. :returns: `Results` containing list elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` containing list elements sorted by the given property. :param: property The property name to sort by. :param: ascending The direction to sort by. :returns: `Results` containing list elements sorted by the given property. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. :param: sortDescriptors `SortDescriptor`s to sort by. :returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(map(sortDescriptors) { $0.rlmSortDescriptorValue })) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is from a different Realm it is copied to the List's Realm. :warning: This method can only be called during a write transaction. :param: object An object. */ public func append(object: T) { _rlmArray.addObject(unsafeBitCast(object, RLMObject.self)) } /** Appends the objects in the given sequence to the end of the list. :warning: This method can only be called during a write transaction. :param: objects A sequence of objects. */ public func extend<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in SequenceOf<T>(objects) { _rlmArray.addObject(unsafeBitCast(obj, RLMObject.self)) } } /** Inserts the given object at the given index. :warning: This method can only be called during a write transaction. :warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. :param: object An object. :param: index The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index)) } /** Removes the object at the given index from the list. Does not remove the object from the Realm. :warning: This method can only be called during a write transaction. :warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. :param: index The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the list. Does not remove the object from the Realm. :warning: This method can only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the List. Does not remove the objects from the Realm. :warning: This method can only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. :warning: This method can only be called during a write transaction. :warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. :param: index The list index of the object to be replaced. :param: object An object to replace at the specified index. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self)) } /** Moves the object at the given source index to the given destination index. :warning: This method can only be called during a write transaction. :warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. :param: from The index of the object to be moved. :param: to The index to which the object at `from` should be moved. */ public func move(#from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the list at given indexes. :warning: Throws an exception when either index exceeds the bounds of the list. :warning: This method can only be called during a write transaction. :param: index1 The index of the object with which to replace the object at index `index2`. :param: index2 The index of the object with which to replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } } extension List: ExtensibleCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the list. public func generate() -> GeneratorOf<T> { let base = NSFastGenerator(_rlmArray) return GeneratorOf<T>() { let accessor = base.next() as! T? RLMInitializeSwiftListAccessor(accessor) return accessor } } // MARK: ExtensibleCollection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return count } /// This method has no effect. public func reserveCapacity(capacity: Int) { } }
apache-2.0
tahseen0amin/TZSegmentedControl
TZSegmentedControl/Classes/TZSegmentedControl.swift
1
44009
// // TZSegmentedControl.swift // Pods // // Created by Tasin Zarkoob on 05/05/17. // // import UIKit /// Selection Style for the Segmented control /// /// - Parameter textWidth : Indicator width will only be as big as the text width /// - Parameter fullWidth : Indicator width will fill the whole segment /// - Parameter box : A rectangle that covers the whole segment /// - Parameter arrow : An arrow in the middle of the segment pointing up or down depending /// on `TZSegmentedControlSelectionIndicatorLocation` /// public enum TZSegmentedControlSelectionStyle { case textWidth case fullWidth case box case arrow } public enum TZSegmentedControlSelectionIndicatorLocation{ case up case down case none // No selection indicator } public enum TZSegmentedControlSegmentWidthStyle { case fixed // Segment width is fixed case dynamic // Segment width will only be as big as the text width (including inset) } public enum TZSegmentedControlSegmentAlignment { case edge // Segments align to the edges of the view case center // Selected segments are always centered in the view } public enum TZSegmentedControlBorderType { case none // 0 case top // (1 << 0) case left // (1 << 1) case bottom // (1 << 2) case right // (1 << 3) } public enum TZSegmentedControlType { case text case images case textImages } public let TZSegmentedControlNoSegment = -1 public typealias IndexChangeBlock = ((Int) -> Void) public typealias TZTitleFormatterBlock = ((_ segmentedControl: TZSegmentedControl, _ title: String, _ index: Int, _ selected: Bool) -> NSAttributedString) open class TZSegmentedControl: UIControl { public var sectionTitles : [String]! { didSet { self.updateSegmentsRects() self.setNeedsLayout() self.setNeedsDisplay() } } public var sectionImages: [UIImage]! { didSet { self.updateSegmentsRects() self.setNeedsLayout() self.setNeedsDisplay() } } public var sectionSelectedImages : [UIImage]! /// Provide a block to be executed when selected index is changed. /// Alternativly, you could use `addTarget:action:forControlEvents:` public var indexChangeBlock : IndexChangeBlock? /// Used to apply custom text styling to titles when set. /// When this block is set, no additional styling is applied to the `NSAttributedString` object /// returned from this block. public var titleFormatter : TZTitleFormatterBlock? /// Text attributes to apply to labels of the unselected segments public var titleTextAttributes: [NSAttributedString.Key:Any]? /// Text attributes to apply to selected item title text. /// Attributes not set in this dictionary are inherited from `titleTextAttributes`. public var selectedTitleTextAttributes: [NSAttributedString.Key: Any]? /// Segmented control background color. /// Default is `[UIColor whiteColor]` dynamic override open var backgroundColor: UIColor! { set { TZSegmentedControl.appearance().backgroundColor = newValue } get { return TZSegmentedControl.appearance().backgroundColor } } /// Color for the selection indicator stripe public var selectionIndicatorColor: UIColor = .black { didSet { self.selectionIndicator.backgroundColor = self.selectionIndicatorColor self.selectionIndicatorBoxColor = self.selectionIndicatorColor } } public lazy var selectionIndicator: UIView = { let selectionIndicator = UIView() selectionIndicator.backgroundColor = self.selectionIndicatorColor selectionIndicator.translatesAutoresizingMaskIntoConstraints = false return selectionIndicator }() /// Color for the selection indicator box /// Default is selectionIndicatorColor public var selectionIndicatorBoxColor : UIColor = .black /// Color for the vertical divider between segments. /// Default is `[UIColor blackColor]` public var verticalDividerColor = UIColor.black //TODO Add other visual apperance properities /// Specifies the style of the control /// Default is `text` public var type: TZSegmentedControlType = .text /// Specifies the style of the selection indicator. /// Default is `textWidth` public var selectionStyle: TZSegmentedControlSelectionStyle = .textWidth /// Specifies the style of the segment's width. /// Default is `fixed` public var segmentWidthStyle: TZSegmentedControlSegmentWidthStyle = .dynamic { didSet { if self.segmentWidthStyle == .dynamic && self.type == .images { self.segmentWidthStyle = .fixed } } } /// Specifies the location of the selection indicator. /// Default is `up` public var selectionIndicatorLocation: TZSegmentedControlSelectionIndicatorLocation = .down { didSet { if self.selectionIndicatorLocation == .none { self.selectionIndicatorHeight = 0.0 } } } public var segmentAlignment: TZSegmentedControlSegmentAlignment = .edge /// Specifies the border type. /// Default is `none` public var borderType: TZSegmentedControlBorderType = .none { didSet { self.setNeedsDisplay() } } /// Specifies the border color. /// Default is `black` public var borderColor = UIColor.black /// Specifies the border width. /// Default is `1.0f` public var borderWidth: CGFloat = 1.0 /// Default is NO. Set to YES to show a vertical divider between the segments. public var verticalDividerEnabled = false /// Index of the currently selected segment. public var selectedSegmentIndex: Int = 0 /// Height of the selection indicator stripe. public var selectionIndicatorHeight: CGFloat = 5.0 public var edgeInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) public var selectionEdgeInset = UIEdgeInsets.zero public var verticalDividerWidth = 1.0 public var selectionIndicatorBoxOpacity : Float = 0.3 ///MARK: Private variable internal var selectionIndicatorStripLayer = CALayer() internal var selectionIndicatorBoxLayer = CALayer() { didSet { self.selectionIndicatorBoxLayer.opacity = self.selectionIndicatorBoxOpacity self.selectionIndicatorBoxLayer.borderWidth = self.borderWidth } } internal var selectionIndicatorArrowLayer = CALayer() internal var segmentWidth : CGFloat = 0.0 internal var segmentWidthsArray : [CGFloat] = [] internal var scrollView : TZScrollView! = { let scroll = TZScrollView() scroll.scrollsToTop = false scroll.showsVerticalScrollIndicator = false scroll.showsHorizontalScrollIndicator = false return scroll }() //MARK: - Init Methods /// Initialiaze the segmented control with only titles. /// /// - Parameter sectionTitles: array of strings for the section title public convenience init(sectionTitles titles: [String]) { self.init() self.setup() self.sectionTitles = titles self.type = .text self.postInitMethod() } /// Initialiaze the segmented control with only images/icons. /// /// - Parameter sectionImages: array of images for the section images. /// - Parameter selectedImages: array of images for the selected section images. public convenience init(sectionImages images: [UIImage], selectedImages sImages: [UIImage]) { self.init() self.setup() self.sectionImages = images self.sectionSelectedImages = sImages self.type = .images self.segmentWidthStyle = .fixed self.postInitMethod() } /// Initialiaze the segmented control with both titles and images/icons. /// /// - Parameter sectionTitles: array of strings for the section title /// - Parameter sectionImages: array of images for the section images. /// - Parameter selectedImages: array of images for the selected section images. public convenience init(sectionTitles titles: [String], sectionImages images: [UIImage], selectedImages sImages: [UIImage]) { self.init() self.setup() self.sectionTitles = titles self.sectionImages = images self.sectionSelectedImages = sImages self.type = .textImages assert(sectionTitles.count == sectionSelectedImages.count, "Titles and images are not in correct count") self.postInitMethod() } open override func awakeFromNib() { self.setup() self.postInitMethod() } private func setup(){ self.addSubview(self.scrollView) self.backgroundColor = UIColor.lightGray self.isOpaque = false self.contentMode = .redraw } open func postInitMethod(){ } //MARK: - View LifeCycle open override func willMove(toSuperview newSuperview: UIView?) { if newSuperview == nil { // Control is being removed return } if self.sectionTitles != nil || self.sectionImages != nil { self.updateSegmentsRects() } } //MARK: - Drawing private func measureTitleAtIndex(index : Int) -> CGSize { if index >= self.sectionTitles.count { return CGSize.zero } let title = self.sectionTitles[index] let selected = (index == self.selectedSegmentIndex) var size = CGSize.zero if self.titleFormatter == nil { var attributes : [NSAttributedString.Key: Any] if selected { attributes = self.finalSelectedTitleAttributes() } else { attributes = self.finalTitleAttributes() } size = (title as NSString).size(withAttributes: attributes) } else { size = self.titleFormatter!(self, title, index, selected).size() } return size } private func attributedTitleAtIndex(index : Int) -> NSAttributedString { let title = self.sectionTitles[index] let selected = (index == self.selectedSegmentIndex) var str = NSAttributedString() if self.titleFormatter == nil { let attr = selected ? self.finalSelectedTitleAttributes() : self.finalTitleAttributes() str = NSAttributedString(string: title, attributes: attr) } else { str = self.titleFormatter!(self, title, index, selected) } return str } override open func draw(_ rect: CGRect) { self.backgroundColor.setFill() UIRectFill(self.bounds) self.selectionIndicatorArrowLayer.backgroundColor = self.selectionIndicatorColor.cgColor self.selectionIndicatorStripLayer.backgroundColor = self.selectionIndicatorColor.cgColor self.selectionIndicatorBoxLayer.backgroundColor = self.selectionIndicatorBoxColor.cgColor self.selectionIndicatorBoxLayer.borderColor = self.selectionIndicatorBoxColor.cgColor // Remove all sublayers to avoid drawing images over existing ones self.scrollView.layer.sublayers = nil let oldrect = rect if self.type == .text { if sectionTitles == nil { return } for (index, _) in self.sectionTitles.enumerated() { let size = self.measureTitleAtIndex(index: index) let strWidth = size.width let strHeight = size.height var rectDiv = CGRect.zero var fullRect = CGRect.zero // Text inside the CATextLayer will appear blurry unless the rect values are rounded let isLocationUp : CGFloat = (self.selectionIndicatorLocation != .up) ? 0.0 : 1.0 let isBoxStyle : CGFloat = (self.selectionStyle != .box) ? 0.0 : 1.0 let a : CGFloat = (self.frame.height - (isBoxStyle * self.selectionIndicatorHeight)) / 2 let b : CGFloat = (strHeight / 2) + (self.selectionIndicatorHeight * isLocationUp) let yPosition : CGFloat = CGFloat(roundf(Float(a - b))) var newRect = CGRect.zero if self.segmentWidthStyle == .fixed { let xPosition : CGFloat = CGFloat((self.segmentWidth * CGFloat(index)) + (self.segmentWidth - strWidth) / 2) newRect = CGRect(x: xPosition, y: yPosition, width: strWidth, height: strHeight) rectDiv = self.calculateRectDiv(at: index, xoffSet: nil) fullRect = CGRect(x: self.segmentWidth * CGFloat(index), y: 0.0, width: self.segmentWidth, height: oldrect.size.height) } else { // When we are drawing dynamic widths, we need to loop the widths array to calculate the xOffset var xOffset : CGFloat = 0.0 var i = 0 for width in self.segmentWidthsArray { if index == i { break } xOffset += width i += 1 } let widthForIndex = self.segmentWidthsArray[index] newRect = CGRect(x: xOffset, y: yPosition, width: widthForIndex, height: strHeight) fullRect = CGRect(x: self.segmentWidth * CGFloat(index), y: 0.0, width: widthForIndex, height: oldrect.size.height) rectDiv = self.calculateRectDiv(at: index, xoffSet: xOffset) } // Fix rect position/size to avoid blurry labels newRect = CGRect(x: ceil(newRect.origin.x), y: ceil(newRect.origin.y), width: ceil(newRect.size.width), height: ceil(newRect.size.height)) let titleLayer = CATextLayer() titleLayer.frame = newRect titleLayer.alignmentMode = CATextLayerAlignmentMode.center if (UIDevice.current.systemVersion as NSString).floatValue < 10.0 { titleLayer.truncationMode = CATextLayerTruncationMode.end } titleLayer.string = self.attributedTitleAtIndex(index: index) titleLayer.contentsScale = UIScreen.main.scale self.scrollView.layer.addSublayer(titleLayer) // Vertical Divider self.addVerticalLayer(at: index, rectDiv: rectDiv) self.addBgAndBorderLayer(with: fullRect) } } else if self.type == .images { if sectionImages == nil { return } for (index, image) in self.sectionImages.enumerated() { let imageWidth = image.size.width let imageHeight = image.size.height let a = (self.frame.height - self.selectionIndicatorHeight) / 2 let b = (imageHeight/2) + (self.selectionIndicatorLocation == .up ? self.selectionIndicatorHeight : 0.0) let y : CGFloat = CGFloat(roundf(Float(a - b))) let x : CGFloat = (self.segmentWidth * CGFloat(index)) + (self.segmentWidth - imageWidth) / 2.0 let newRect = CGRect(x: x, y: y, width: imageWidth, height: imageHeight) let imageLayer = CALayer() imageLayer.frame = newRect imageLayer.contents = image.cgImage if self.selectedSegmentIndex == index && self.sectionSelectedImages.count > index { let highlightedImage = self.sectionSelectedImages[index] imageLayer.contents = highlightedImage.cgImage } self.scrollView.layer.addSublayer(imageLayer) //vertical Divider self.addVerticalLayer(at: index, rectDiv: self.calculateRectDiv(at: index, xoffSet: nil)) self.addBgAndBorderLayer(with: newRect) } } else if self.type == .textImages { if sectionImages == nil { return } for (index, image) in self.sectionImages.enumerated() { let imageWidth = image.size.width let imageHeight = image.size.height let stringHeight = self.measureTitleAtIndex(index: index).height let yOffset : CGFloat = CGFloat(roundf(Float( ((self.frame.height - self.selectionIndicatorHeight) / 2) - (stringHeight / 2) ))) var imagexOffset : CGFloat = self.edgeInset.left var textxOffset : CGFloat = self.edgeInset.left var textWidth : CGFloat = 0.0 if self.segmentWidthStyle == .fixed { imagexOffset = (self.segmentWidth * CGFloat(index)) + (self.segmentWidth / 2) - (imageWidth / 2.0) textxOffset = self.segmentWidth * CGFloat(index) textWidth = self.segmentWidth } else { // When we are drawing dynamic widths, we need to loop the widths array to calculate the xOffset let a = self.getDynamicWidthTillSegmentIndex(index: index) imagexOffset = a.0 + (a.1 / 2) - (imageWidth / 2) textxOffset = a.0 textWidth = self.segmentWidthsArray[index] } let imageyOffset : CGFloat = CGFloat(roundf(Float( ((self.frame.height - self.selectionIndicatorHeight) / 2) + 8.0))) let imageRect = CGRect(x: imagexOffset, y: imageyOffset, width: imageWidth, height: imageHeight) var textRect = CGRect(x: textxOffset, y: yOffset, width: textWidth, height: stringHeight) // Fix rect position/size to avoid blurry labels textRect = CGRect(x: ceil(textRect.origin.x), y: ceil(textRect.origin.y), width: ceil(textRect.size.width), height: ceil(textRect.size.height)) let titleLayer = CATextLayer() titleLayer.frame = textRect titleLayer.alignmentMode = CATextLayerAlignmentMode.center if (UIDevice.current.systemVersion as NSString).floatValue < 10.0 { titleLayer.truncationMode = CATextLayerTruncationMode.end } titleLayer.string = self.attributedTitleAtIndex(index: index) titleLayer.contentsScale = UIScreen.main.scale let imageLayer = CALayer() imageLayer.frame = imageRect imageLayer.contents = image.cgImage if self.selectedSegmentIndex == index && self.sectionSelectedImages.count > index { let highlightedImage = self.sectionSelectedImages[index] imageLayer.contents = highlightedImage.cgImage } self.scrollView.layer.addSublayer(imageLayer) self.scrollView.layer.addSublayer(titleLayer) self.addBgAndBorderLayer(with: imageRect) } } // Add the selection indicators if self.selectedSegmentIndex != TZSegmentedControlNoSegment { if self.selectionStyle == .arrow { if (self.selectionIndicatorArrowLayer.superlayer == nil) { self.setArrowFrame() self.scrollView.layer.addSublayer(self.selectionIndicatorArrowLayer) } } else { if (self.selectionIndicatorStripLayer.superlayer == nil) { self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() self.scrollView.layer.addSublayer(self.selectionIndicatorStripLayer) if self.selectionStyle == .box && self.selectionIndicatorBoxLayer.superlayer == nil { self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() self.selectionIndicatorBoxLayer.opacity = self.selectionIndicatorBoxOpacity self.scrollView.layer.insertSublayer(self.selectionIndicatorBoxLayer, at: 0) } } } } } private func calculateRectDiv(at index: Int, xoffSet: CGFloat?) -> CGRect { var a :CGFloat if xoffSet != nil { a = xoffSet! } else { a = self.segmentWidth * CGFloat(index) } let xPosition = CGFloat( a - CGFloat(self.verticalDividerWidth / 2)) let rectDiv = CGRect(x: xPosition, y: self.selectionIndicatorHeight * 2, width: CGFloat(self.verticalDividerWidth), height: self.frame.size.height - (self.selectionIndicatorHeight * 4)) return rectDiv } // Add Vertical Divider Layer private func addVerticalLayer(at index: Int, rectDiv: CGRect) { if self.verticalDividerEnabled && index > 0 { let vDivLayer = CALayer() vDivLayer.frame = rectDiv vDivLayer.backgroundColor = self.verticalDividerColor.cgColor self.scrollView.layer.addSublayer(vDivLayer) } } private func addBgAndBorderLayer(with rect: CGRect){ // Background layer let bgLayer = CALayer() bgLayer.frame = rect self.layer.insertSublayer(bgLayer, at: 0) // Border layer if self.borderType != .none { let borderLayer = CALayer() borderLayer.backgroundColor = self.borderColor.cgColor var borderRect = CGRect.zero switch self.borderType { case .top: borderRect = CGRect(x: 0, y: 0, width: rect.size.width, height: self.borderWidth) break case .left: borderRect = CGRect(x: 0, y: 0, width: self.borderWidth, height: rect.size.height) break case .bottom: borderRect = CGRect(x: 0, y: rect.size.height, width: rect.size.width, height: self.borderWidth) break case .right: borderRect = CGRect(x: 0, y: rect.size.width, width: self.borderWidth, height: rect.size.height) break case .none: break } borderLayer.frame = borderRect bgLayer.addSublayer(borderLayer) } } private func setArrowFrame(){ self.selectionIndicatorArrowLayer.frame = self.frameForSelectionIndicator() self.selectionIndicatorArrowLayer.mask = nil; let arrowPath = UIBezierPath() var p1 = CGPoint.zero; var p2 = CGPoint.zero; var p3 = CGPoint.zero; if self.selectionIndicatorLocation == .down { p1 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width / 2, y: 0); p2 = CGPoint(x: 0, y: self.selectionIndicatorArrowLayer.bounds.size.height); p3 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width, y: self.selectionIndicatorArrowLayer.bounds.size.height) } else if self.selectionIndicatorLocation == .up { p1 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width / 2, y: self.selectionIndicatorArrowLayer.bounds.size.height); p2 = CGPoint(x: self.selectionIndicatorArrowLayer.bounds.size.width, y:0); } arrowPath.move(to: p1) arrowPath.addLine(to: p2) arrowPath.addLine(to: p3) arrowPath.close() let maskLayer = CAShapeLayer() maskLayer.frame = self.selectionIndicatorArrowLayer.bounds maskLayer.path = arrowPath.cgPath self.selectionIndicatorArrowLayer.mask = maskLayer } /// Stripe width in range(0.0 - 1.0). /// Default is 1.0 public var indicatorWidthPercent : Double = 1.0 { didSet { if !(indicatorWidthPercent <= 1.0 && indicatorWidthPercent >= 0.0){ indicatorWidthPercent = max(0.0, min(indicatorWidthPercent, 1.0)) } } } private func frameForSelectionIndicator() -> CGRect { var indicatorYOffset : CGFloat = 0 if self.selectionIndicatorLocation == .down { indicatorYOffset = self.bounds.size.height - self.selectionIndicatorHeight + self.edgeInset.bottom } else if self.selectionIndicatorLocation == .up { indicatorYOffset = self.edgeInset.top } var sectionWidth : CGFloat = 0.0 if self.type == .text { sectionWidth = self.measureTitleAtIndex(index: self.selectedSegmentIndex).width } else if self.type == .images { sectionWidth = self.sectionImages[self.selectedSegmentIndex].size.width } else if self.type == .textImages { let stringWidth = self.measureTitleAtIndex(index: self.selectedSegmentIndex).width let imageWidth = self.sectionImages[self.selectedSegmentIndex].size.width sectionWidth = max(stringWidth, imageWidth) } var indicatorFrame = CGRect.zero if self.selectionStyle == .arrow { var widthToStartOfSelIndex : CGFloat = 0.0 var widthToEndOfSelIndex : CGFloat = 0.0 if (self.segmentWidthStyle == .dynamic) { let a = self.getDynamicWidthTillSegmentIndex(index: self.selectedSegmentIndex) widthToStartOfSelIndex = a.0 widthToEndOfSelIndex = widthToStartOfSelIndex + a.1 } else { widthToStartOfSelIndex = CGFloat(self.selectedSegmentIndex) * self.segmentWidth widthToEndOfSelIndex = widthToStartOfSelIndex + self.segmentWidth } let xPos = widthToStartOfSelIndex + ((widthToEndOfSelIndex - widthToStartOfSelIndex) / 2) - (self.selectionIndicatorHeight) indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: self.selectionIndicatorHeight * 2, height: self.selectionIndicatorHeight) } else { if self.selectionStyle == .textWidth && sectionWidth <= self.segmentWidth && self.segmentWidthStyle != .dynamic { let widthToStartOfSelIndex : CGFloat = CGFloat(self.selectedSegmentIndex) * self.segmentWidth let widthToEndOfSelIndex : CGFloat = widthToStartOfSelIndex + self.segmentWidth var xPos = (widthToStartOfSelIndex - (sectionWidth / 2)) + ((widthToEndOfSelIndex - widthToStartOfSelIndex) / 2) xPos += self.edgeInset.left indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: (sectionWidth - self.edgeInset.right), height: self.selectionIndicatorHeight) } else { if self.segmentWidthStyle == .dynamic { var selectedSegmentOffset : CGFloat = 0 var i = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } selectedSegmentOffset += width i += 1 } indicatorFrame = CGRect(x: selectedSegmentOffset + self.edgeInset.left, y: indicatorYOffset, width: self.segmentWidthsArray[self.selectedSegmentIndex] - self.edgeInset.right - self.edgeInset.left, height: self.selectionIndicatorHeight + self.edgeInset.bottom) } else { let xPos = (self.segmentWidth * CGFloat(self.selectedSegmentIndex)) + self.edgeInset.left indicatorFrame = CGRect(x: xPos, y: indicatorYOffset, width: (self.segmentWidth - self.edgeInset.right - self.edgeInset.left), height: self.selectionIndicatorHeight) } } } if self.selectionStyle != .arrow { let currentIndicatorWidth = indicatorFrame.size.width let widthToMinus = CGFloat(1 - self.indicatorWidthPercent) * currentIndicatorWidth // final width indicatorFrame.size.width = currentIndicatorWidth - widthToMinus // frame position indicatorFrame.origin.x += widthToMinus / 2 } return indicatorFrame } private func getDynamicWidthTillSegmentIndex(index: Int) -> (CGFloat, CGFloat){ var selectedSegmentOffset : CGFloat = 0 var i = 0 var selectedSegmentWidth : CGFloat = 0 for width in self.segmentWidthsArray { if index == i { selectedSegmentWidth = width break } selectedSegmentOffset += width i += 1 } return (selectedSegmentOffset, selectedSegmentWidth) } private func frameForFillerSelectionIndicator() -> CGRect { if self.segmentWidthStyle == .dynamic { var selectedSegmentOffset : CGFloat = 0 var i = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } selectedSegmentOffset += width i += 1 } return CGRect(x: selectedSegmentOffset, y: 0, width:self.segmentWidthsArray[self.selectedSegmentIndex], height: self.frame.height) } return CGRect(x: self.segmentWidth * CGFloat(self.selectedSegmentIndex), y: 0, width: self.segmentWidth, height: self.frame.height) } private func updateSegmentsRects() { self.scrollView.contentInset = UIEdgeInsets.zero self.scrollView.frame = CGRect(origin: CGPoint.zero, size: self.frame.size) let count = self.sectionCount() if count > 0 { self.segmentWidth = self.frame.size.width / CGFloat(count) } if self.type == .text { if self.segmentWidthStyle == .fixed { for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(stringWidth, self.segmentWidth) } } else if self.segmentWidthStyle == .dynamic { var arr = [CGFloat]() for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right arr.append(stringWidth) } self.segmentWidthsArray = arr } } else if self.type == .images { for image in self.sectionImages { let imageWidth = image.size.width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(imageWidth, self.segmentWidth) } } else if self.type == .textImages { if self.segmentWidthStyle == .fixed { for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.left + self.edgeInset.right self.segmentWidth = max(stringWidth, self.segmentWidth) } } else if self.segmentWidthStyle == .dynamic { var arr = [CGFloat]() for (index, _) in self.sectionTitles.enumerated() { let stringWidth = self.measureTitleAtIndex(index: index).width + self.edgeInset.right let imageWidth = self.sectionImages[index].size.width + self.edgeInset.left arr.append(max(stringWidth, imageWidth)) } self.segmentWidthsArray = arr } } self.scrollView.isScrollEnabled = true self.scrollView.contentSize = CGSize(width: self.totalSegmentedControlWidth(), height: self.frame.height) switch segmentAlignment { case .center: let count = self.sectionCount() - 1 self.scrollView.contentInset = UIEdgeInsets(top: 0, left: self.scrollView.bounds.size.width / 2.0 - widthOfSegment(index:0) / 2.0, bottom: 0, right: self.scrollView.bounds.size.width / 2.0 - widthOfSegment(index:count) / 2.0 ) break case .edge: break } scrollToSelectedSegmentIndex(animated: false) } private func widthOfSegment(index: NSInteger) -> CGFloat { return index < (self.segmentWidthsArray.count - 1) ? CGFloat(self.segmentWidthsArray[index]) : 0.0 } private func sectionCount() -> Int { if self.type == .text { return self.sectionTitles.count } else { return self.sectionImages.count } } var enlargeEdgeInset = UIEdgeInsets.zero //MARK: - Touch Methods open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first guard let touchesLocation = touch?.location(in: self) else { assert(false, "Touch Location not found") return } //check to see if there are sections, if not then just return var sectionTitleCount = 0 var sectionImagesCount = 0 if sectionTitles != nil{ sectionTitleCount = sectionTitles.count } if sectionImages != nil{ sectionImagesCount = sectionImages.count } if sectionTitleCount == 0 && sectionImagesCount == 0{ return } //end check to see if there are sections let enlargeRect = CGRect(x: self.bounds.origin.x - self.enlargeEdgeInset.left, y: self.bounds.origin.y - self.enlargeEdgeInset.top, width: self.bounds.size.width + self.enlargeEdgeInset.left + self.enlargeEdgeInset.right, height: self.bounds.size.height + self.enlargeEdgeInset.top + self.enlargeEdgeInset.bottom) if enlargeRect.contains(touchesLocation) { var segment = 0 if self.segmentWidthStyle == .fixed { segment = Int((touchesLocation.x + self.scrollView.contentOffset.x) / self.segmentWidth) } else { // To know which segment the user touched, we need to loop over the widths and substract it from the x position. var widthLeft = touchesLocation.x + self.scrollView.contentOffset.x for width in self.segmentWidthsArray { widthLeft -= width // When we don't have any width left to substract, we have the segment index. if widthLeft <= 0 { break } segment += 1 } } var sectionsCount = 0 if self.type == .images { sectionsCount = self.sectionImages.count } else { sectionsCount = self.sectionTitles.count } if segment != self.selectedSegmentIndex && segment < sectionsCount { // Check if we have to do anything with the touch event self.setSelected(forIndex: segment, animated: true, shouldNotify: true) } } } //MARK: - Scrolling private func totalSegmentedControlWidth() -> CGFloat { if self.type != .images { if self.segmentWidthStyle == .fixed { return CGFloat(self.sectionTitles.count) * self.segmentWidth } else { let sum = self.segmentWidthsArray.reduce(0,+) return sum } } else { return CGFloat(self.sectionImages.count) * self.segmentWidth } } func scrollToSelectedSegmentIndex(animated: Bool) { var rectForSelectedIndex = CGRect.zero var selectedSegmentOffset : CGFloat = 0 if self.segmentWidthStyle == .fixed { rectForSelectedIndex = CGRect(x: (self.segmentWidth * CGFloat(self.selectedSegmentIndex)), y: 0, width: self.segmentWidth, height: self.frame.height) selectedSegmentOffset = (self.frame.width / 2) - (self.segmentWidth / 2) } else { var i = 0 var offsetter: CGFloat = 0 for width in self.segmentWidthsArray { if self.selectedSegmentIndex == i { break } offsetter += width i += 1 } rectForSelectedIndex = CGRect(x: offsetter, y: 0, width: self.segmentWidthsArray[self.selectedSegmentIndex], height: self.frame.height) selectedSegmentOffset = (self.frame.width / 2) - (self.segmentWidthsArray[self.selectedSegmentIndex] / 2) } rectForSelectedIndex.origin.x -= selectedSegmentOffset rectForSelectedIndex.size.width += selectedSegmentOffset * 2 // Scroll to segment and apply segment alignment switch (self.segmentAlignment) { case .center: var contentOffset:CGPoint = self.scrollView.contentOffset contentOffset.x = rectForSelectedIndex.origin.x; self.scrollView.setContentOffset(contentOffset, animated: true) break; case .edge: break } } //MARK: - Index Change public func setSelected(forIndex index: Int, animated: Bool) { self.setSelected(forIndex: index, animated: animated, shouldNotify: false) } public func setSelected(forIndex index: Int, animated: Bool, shouldNotify: Bool) { self.selectedSegmentIndex = index self.setNeedsDisplay() if index == TZSegmentedControlNoSegment { self.selectionIndicatorBoxLayer.removeFromSuperlayer() self.selectionIndicatorArrowLayer.removeFromSuperlayer() self.selectionIndicatorStripLayer.removeFromSuperlayer() } else { self.scrollToSelectedSegmentIndex(animated: animated) if animated { // If the selected segment layer is not added to the super layer, that means no // index is currently selected, so add the layer then move it to the new // segment index without animating. if self.selectionStyle == .arrow { if self.selectionIndicatorArrowLayer.superlayer == nil { self.scrollView.layer.addSublayer(self.selectionIndicatorArrowLayer) self.setSelected(forIndex: index, animated: false, shouldNotify: true) return } } else { if self.selectionIndicatorStripLayer.superlayer == nil { self.scrollView.layer.addSublayer(self.selectionIndicatorStripLayer) if self.selectionStyle == .box && self.selectionIndicatorBoxLayer.superlayer == nil { self.scrollView.layer.insertSublayer(self.selectionIndicatorBoxLayer, at: 0) } self.setSelected(forIndex: index, animated: false, shouldNotify: true) return } } if shouldNotify { self.notifyForSegmentChange(toIndex: index) } // Restore CALayer animations self.selectionIndicatorArrowLayer.actions = nil self.selectionIndicatorStripLayer.actions = nil self.selectionIndicatorBoxLayer.actions = nil // Animate to new position CATransaction.begin() CATransaction.setAnimationDuration(0.15) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)) self.setArrowFrame() self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() CATransaction.commit() } else { // Disable CALayer animations self.selectionIndicatorArrowLayer.actions = nil self.setArrowFrame() self.selectionIndicatorStripLayer.actions = nil self.selectionIndicatorStripLayer.frame = self.frameForSelectionIndicator() self.selectionIndicatorBoxLayer.actions = nil self.selectionIndicatorBoxLayer.frame = self.frameForFillerSelectionIndicator() if shouldNotify { self.notifyForSegmentChange(toIndex: index) } } } } private func notifyForSegmentChange(toIndex index:Int){ if self.superview != nil { self.sendActions(for: .valueChanged) } self.indexChangeBlock?(index) } //MARK: - Styliing Support private func finalTitleAttributes() -> [NSAttributedString.Key:Any] { var defaults : [NSAttributedString.Key:Any] = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.black] if self.titleTextAttributes != nil { defaults.merge(dict: self.titleTextAttributes!) } return defaults } private func finalSelectedTitleAttributes() -> [NSAttributedString.Key:Any] { var defaults : [NSAttributedString.Key:Any] = self.finalTitleAttributes() if self.selectedTitleTextAttributes != nil { defaults.merge(dict: self.selectedTitleTextAttributes!) } return defaults } } extension Dictionary { mutating func merge<K, V>(dict: [K: V]){ for (k, v) in dict { self.updateValue(v as! Value, forKey: k as! Key) } } }
mit
sammeadley/TopStories
TopStoriesTests/TestableURLSession.swift
1
1187
// // TestableURLSession.swift // TopStories // // Created by Sam Meadley on 20/04/2016. // Copyright © 2016 Sam Meadley. All rights reserved. // import Foundation class TestableURLSession: URLSession { var stubTask: URLSessionTask? // Not possible to override init(configuration:delegate:delegateQueue:) so we'll manage // the delegate property internally. fileprivate var internalDelegate: URLSessionDelegate? init(delegate: URLSessionDelegate?) { self.internalDelegate = delegate } override var delegate: URLSessionDelegate? { get { return internalDelegate } set { internalDelegate = newValue } } override func dataTask(with url: URL) -> URLSessionDataTask { // Failing to set dataTask is a programmer error, so we are safe to force unwrap here. return stubTask as! TestableURLSessionDataTask } override func downloadTask(with url: URL) -> URLSessionDownloadTask { // Failing to set dataTask is a programmer error, so we are safe to force unwrap here. return stubTask as! TestableURLSessionDownloadTask } }
mit
dnevera/ImageMetalling
ImageMetalling-08/ImageMetalling-08/IMPPaletteListView.swift
1
4484
// // IMPPaletteListView.swift // ImageMetalling-08 // // Created by denis svinarchuk on 02.01.16. // Copyright © 2016 ImageMetalling. All rights reserved. // import Cocoa import IMProcessing /// /// Класс представления цветовой палитры /// public class IMPPaletteListView: NSView, NSTableViewDataSource, NSTableViewDelegate { /// Список цветов public var colorList:[IMPColor] = [ IMPColor(red: 0, green: 0, blue: 0, alpha: 1), IMPColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1), IMPColor(red: 1, green: 1, blue: 1, alpha: 1), ]{ didSet{ colorListView.reloadData() } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) scrollView = NSScrollView(frame: self.bounds) scrollView.drawsBackground = false scrollView.allowsMagnification = false scrollView.autoresizingMask = [.ViewHeightSizable, .ViewWidthSizable] colorListView = NSTableView(frame: self.bounds) colorListView.backgroundColor = IMPColor.clearColor() colorListView.headerView = nil colorListView.intercellSpacing = IMPSize(width: 5,height: 5) colorListView.columnAutoresizingStyle = .UniformColumnAutoresizingStyle scrollView.documentView = colorListView let column1 = NSTableColumn(identifier: "Color") let column2 = NSTableColumn(identifier: "Value") column1.width = 300 column2.width = 200 column1.title = "" column2.title = "Value" colorListView.addTableColumn(column1) colorListView.addTableColumn(column2) colorListView.setDataSource(self) colorListView.setDelegate(self) self.addSubview(scrollView) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var scrollView:NSScrollView! private var colorListView:NSTableView! public func numberOfRowsInTableView(tableView: NSTableView) -> Int { return colorList.count } public func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 36 } public func tableView(tableView: NSTableView, willDisplayCell cell: AnyObject, forTableColumn tableColumn: NSTableColumn?, row: Int) { (cell as! NSView).wantsLayer = true (cell as! NSView).layer?.backgroundColor = IMPColor.clearColor().CGColor } public func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var result:NSView? let color = colorList[row] if tableColumn?.identifier == "Color"{ let id = "Color" result = tableView.makeViewWithIdentifier(id, owner: self) if result == nil { result = NSView(frame: NSRect(x: 0, y: 0, width: 320, height: 40)) result?.wantsLayer = true result?.identifier = id } result?.layer?.backgroundColor = color.CGColor } else{ let id = "Value" result = tableView.makeViewWithIdentifier(id, owner: self) as? NSTextField if result == nil { result = NSTextField(frame: NSRect(x: 0, y: 0, width: 320, height: 40)) (result as? NSTextField)?.bezeled = false (result as? NSTextField)?.drawsBackground = false (result as? NSTextField)?.editable = false (result as? NSTextField)?.selectable = true (result as? NSTextField)?.alignment = .Right result?.identifier = id } let rgb = color.rgb * 255 (result as! NSTextField).stringValue = String(format: "[%.0f,%.0f,%.0f]", rgb.r,rgb.g,rgb.b) (result as! NSTextField).textColor = color * 2 } let rowView = colorListView.rowViewAtRow(row, makeIfNecessary:false) rowView?.backgroundColor = IMPColor.clearColor() return result } public func reloadData(){ colorListView.sizeLastColumnToFit() colorListView.reloadData() } override public func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) self.reloadData() // Drawing code here. } }
mit
cbrentharris/swift
validation-test/compiler_crashers/27911-swift-declcontext-getdeclaredtypeincontext.swift
1
302
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{struct e{class B<d where g=F>:B}}class S<T{func a<h{func b<T where h.g=c
apache-2.0
RevenueCat/purchases-ios
Tests/UnitTests/FoundationExtensions/NSError+RCExtensionsTests.swift
1
1163
// // Created by RevenueCat on 2/26/20. // Copyright (c) 2020 Purchases. All rights reserved. // import Nimble import XCTest @testable import RevenueCat class NSErrorRCExtensionsTests: TestCase { func testSubscriberAttributesErrorsNilIfNoAttributesErrors() { let errorCode = ErrorCode.purchaseNotAllowedError.rawValue let error = NSError( domain: RCPurchasesErrorCodeDomain, code: errorCode, userInfo: [:] ) expect(error.subscriberAttributesErrors).to(beNil()) } func testSubscriberAttributesErrorsReturnsAttributesErrorsInUserInfo() { let errorCode = ErrorCode.purchaseNotAllowedError.rawValue let attributeErrors = ["$phoneNumber": "phone number is in invalid format", "$email": "email is too long"] let error = NSError( domain: RCPurchasesErrorCodeDomain, code: errorCode, userInfo: [ErrorDetails.attributeErrorsKey: attributeErrors] ) expect(error.subscriberAttributesErrors).toNot(beNil()) expect(error.subscriberAttributesErrors) == attributeErrors } }
mit
ravenzino/Dim-Sum
dummyapp/dummyapp/DummyDataSet.swift
1
218
// // DummyDataSet.swift // dummyapp // // Created by raven on 15/5/31. // Copyright (c) 2015年 raven. All rights reserved. // import Foundation // Nothing so far... // Suppose to put all the data models here...
gpl-2.0
jmgc/swift
stdlib/public/core/Slice.swift
1
19197
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A view into a subsequence of elements of another collection. /// /// A slice stores a base collection and the start and end indices of the view. /// It does not copy the elements from the collection into separate storage. /// Thus, creating a slice has O(1) complexity. /// /// Slices Share Indices /// -------------------- /// /// Indices of a slice can be used interchangeably with indices of the base /// collection. An element of a slice is located under the same index in the /// slice and in the base collection, as long as neither the collection nor /// the slice has been mutated since the slice was created. /// /// For example, suppose you have an array holding the number of absences from /// each class during a session. /// /// var absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You're tasked with finding the day with the most absences in the second /// half of the session. To find the index of the day in question, follow /// these steps: /// /// 1) Create a slice of the `absences` array that holds the second half of the /// days. /// 2) Use the `max(by:)` method to determine the index of the day with the /// most absences. /// 3) Print the result using the index found in step 2 on the original /// `absences` array. /// /// Here's an implementation of those steps: /// /// let secondHalf = absences.suffix(absences.count / 2) /// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) { /// print("Highest second-half absences: \(absences[i])") /// } /// // Prints "Highest second-half absences: 3" /// /// Slices Inherit Semantics /// ------------------------ /// /// A slice inherits the value or reference semantics of its base collection. /// That is, if a `Slice` instance is wrapped around a mutable collection that /// has value semantics, such as an array, mutating the original collection /// would trigger a copy of that collection, and not affect the base /// collection stored inside of the slice. /// /// For example, if you update the last element of the `absences` array from /// `0` to `2`, the `secondHalf` slice is unchanged. /// /// absences[7] = 2 /// print(absences) /// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]" /// print(secondHalf) /// // Prints "[0, 3, 1, 0]" /// /// Use slices only for transient computation. A slice may hold a reference to /// the entire storage of a larger collection, not just to the portion it /// presents, even after the base collection's lifetime ends. Long-term /// storage of a slice may therefore prolong the lifetime of elements that are /// no longer otherwise accessible, which can erroneously appear to be memory /// leakage. /// /// - Note: Using a `Slice` instance with a mutable collection requires that /// the base collection's `subscript(_: Index)` setter does not invalidate /// indices. If mutations need to invalidate indices in your custom /// collection type, don't use `Slice` as its subsequence type. Instead, /// define your own subsequence type that takes your index invalidation /// requirements into account. @frozen // generic-performance public struct Slice<Base: Collection> { public var _startIndex: Base.Index public var _endIndex: Base.Index @usableFromInline // generic-performance internal var _base: Base /// Creates a view into the given collection that allows access to elements /// within the specified range. /// /// It is unusual to need to call this method directly. Instead, create a /// slice of a collection by using the collection's range-based subscript or /// by using methods that return a subsequence. /// /// let singleDigits = 0...9 /// let subSequence = singleDigits.dropFirst(5) /// print(Array(subSequence)) /// // Prints "[5, 6, 7, 8, 9]" /// /// In this example, the expression `singleDigits.dropFirst(5))` is /// equivalent to calling this initializer with `singleDigits` and a /// range covering the last five items of `singleDigits.indices`. /// /// - Parameters: /// - base: The collection to create a view into. /// - bounds: The range of indices to allow access to in the new slice. @inlinable // generic-performance public init(base: Base, bounds: Range<Base.Index>) { self._base = base self._startIndex = bounds.lowerBound self._endIndex = bounds.upperBound } /// The underlying collection of the slice. /// /// You can use a slice's `base` property to access its base collection. The /// following example declares `singleDigits`, a range of single digit /// integers, and then drops the first element to create a slice of that /// range, `singleNonZeroDigits`. The `base` property of the slice is equal /// to `singleDigits`. /// /// let singleDigits = 0..<10 /// let singleNonZeroDigits = singleDigits.dropFirst() /// // singleNonZeroDigits is a Slice<Range<Int>> /// /// print(singleNonZeroDigits.count) /// // Prints "9" /// print(singleNonZeroDigits.base.count) /// // Prints "10" /// print(singleDigits == singleNonZeroDigits.base) /// // Prints "true" @inlinable // generic-performance public var base: Base { return _base } } extension Slice: Collection { public typealias Index = Base.Index public typealias Indices = Base.Indices public typealias Element = Base.Element public typealias SubSequence = Slice<Base> public typealias Iterator = IndexingIterator<Slice<Base>> @inlinable // generic-performance public var startIndex: Index { return _startIndex } @inlinable // generic-performance public var endIndex: Index { return _endIndex } @inlinable // generic-performance public subscript(index: Index) -> Base.Element { get { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) return _base[index] } } @inlinable // generic-performance public subscript(bounds: Range<Index>) -> Slice<Base> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: _base, bounds: bounds) } } public var indices: Indices { return _base.indices[_startIndex..<_endIndex] } @inlinable // generic-performance public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(after: i) } @inlinable // generic-performance public func formIndex(after i: inout Index) { // FIXME: swift-3-indexing-model: range check. _base.formIndex(after: &i) } @inlinable // generic-performance public func index(_ i: Index, offsetBy n: Int) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(i, offsetBy: n) } @inlinable // generic-performance public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check. return _base.index(i, offsetBy: n, limitedBy: limit) } @inlinable // generic-performance public func distance(from start: Index, to end: Index) -> Int { // FIXME: swift-3-indexing-model: range check. return _base.distance(from: start, to: end) } @inlinable // generic-performance public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _base._failEarlyRangeCheck(index, bounds: bounds) } @inlinable // generic-performance public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) { _base._failEarlyRangeCheck(range, bounds: bounds) } @_alwaysEmitIntoClient @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { try _base.withContiguousStorageIfAvailable { buffer in let start = _base.distance(from: _base.startIndex, to: _startIndex) let count = _base.distance(from: _startIndex, to: _endIndex) let slice = UnsafeBufferPointer(rebasing: buffer[start ..< start + count]) return try body(slice) } } } extension Slice: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // generic-performance public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(before: i) } @inlinable // generic-performance public func formIndex(before i: inout Index) { // FIXME: swift-3-indexing-model: range check. _base.formIndex(before: &i) } } extension Slice: MutableCollection where Base: MutableCollection { @inlinable // generic-performance public subscript(index: Index) -> Base.Element { get { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) return _base[index] } set { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) _base[index] = newValue // MutableSlice requires that the underlying collection's subscript // setter does not invalidate indices, so our `startIndex` and `endIndex` // continue to be valid. } } @inlinable // generic-performance public subscript(bounds: Range<Index>) -> Slice<Base> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: _base, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } @_alwaysEmitIntoClient @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { // We're calling `withContiguousMutableStorageIfAvailable` twice here so // that we don't calculate index distances unless we know we'll use them. // The expectation here is that the base collection will make itself // contiguous on the first try and the second call will be relatively cheap. guard _base.withContiguousMutableStorageIfAvailable({ _ in }) != nil else { return nil } let start = _base.distance(from: _base.startIndex, to: _startIndex) let count = _base.distance(from: _startIndex, to: _endIndex) return try _base.withContiguousMutableStorageIfAvailable { buffer in var slice = UnsafeMutableBufferPointer( rebasing: buffer[start ..< start + count]) let copy = slice defer { _precondition( slice.baseAddress == copy.baseAddress && slice.count == copy.count, "Slice.withUnsafeMutableBufferPointer: replacing the buffer is not allowed") } return try body(&slice) } } } extension Slice: RandomAccessCollection where Base: RandomAccessCollection { } extension Slice: RangeReplaceableCollection where Base: RangeReplaceableCollection { @inlinable // generic-performance public init() { self._base = Base() self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @inlinable // generic-performance public init(repeating repeatedValue: Base.Element, count: Int) { self._base = Base(repeating: repeatedValue, count: count) self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @inlinable // generic-performance public init<S>(_ elements: S) where S: Sequence, S.Element == Base.Element { self._base = Base(elements) self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @inlinable // generic-performance public mutating func replaceSubrange<C>( _ subRange: Range<Index>, with newElements: C ) where C: Collection, C.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = _base.distance(from: _startIndex, to: subRange.lowerBound) + _base.distance(from: subRange.upperBound, to: _endIndex) + newElements.count _base.replaceSubrange(subRange, with: newElements) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @inlinable // generic-performance public mutating func insert(_ newElement: Base.Element, at i: Index) { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count + 1 _base.insert(newElement, at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @inlinable // generic-performance public mutating func insert<S>(contentsOf newElements: S, at i: Index) where S: Collection, S.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count + newElements.count _base.insert(contentsOf: newElements, at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @inlinable // generic-performance public mutating func remove(at i: Index) -> Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count - 1 let result = _base.remove(at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) return result } @inlinable // generic-performance public mutating func removeSubrange(_ bounds: Range<Index>) { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count - distance(from: bounds.lowerBound, to: bounds.upperBound) _base.removeSubrange(bounds) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } } extension Slice where Base: RangeReplaceableCollection, Base: BidirectionalCollection { @inlinable // generic-performance public mutating func replaceSubrange<C>( _ subRange: Range<Index>, with newElements: C ) where C: Collection, C.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. if subRange.lowerBound == _base.startIndex { let newSliceCount = _base.distance(from: _startIndex, to: subRange.lowerBound) + _base.distance(from: subRange.upperBound, to: _endIndex) + newElements.count _base.replaceSubrange(subRange, with: newElements) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = subRange.lowerBound == _startIndex let lastValidIndex = _base.index(before: subRange.lowerBound) let newEndIndexOffset = _base.distance(from: subRange.upperBound, to: _endIndex) + newElements.count + 1 _base.replaceSubrange(subRange, with: newElements) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @inlinable // generic-performance public mutating func insert(_ newElement: Base.Element, at i: Index) { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count + 1 _base.insert(newElement, at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) + 2 _base.insert(newElement, at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @inlinable // generic-performance public mutating func insert<S>(contentsOf newElements: S, at i: Index) where S: Collection, S.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count + newElements.count _base.insert(contentsOf: newElements, at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) + newElements.count + 1 _base.insert(contentsOf: newElements, at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @inlinable // generic-performance public mutating func remove(at i: Index) -> Base.Element { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count - 1 let result = _base.remove(at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) return result } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) let result = _base.remove(at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) return result } } @inlinable // generic-performance public mutating func removeSubrange(_ bounds: Range<Index>) { // FIXME: swift-3-indexing-model: range check. if bounds.lowerBound == _base.startIndex { let newSliceCount = count - _base.distance(from: bounds.lowerBound, to: bounds.upperBound) _base.removeSubrange(bounds) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = bounds.lowerBound == _startIndex let lastValidIndex = _base.index(before: bounds.lowerBound) let newEndIndexOffset = _base.distance(from: bounds.lowerBound, to: _endIndex) - _base.distance(from: bounds.lowerBound, to: bounds.upperBound) + 1 _base.removeSubrange(bounds) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } }
apache-2.0
cocoascientist/Passengr
PassengrTests/DataSourceTests.swift
1
1035
// // DataSourceTests.swift // Passengr // // Created by Andrew Shepard on 12/9/15. // Copyright © 2015 Andrew Shepard. All rights reserved. // import XCTest @testable import Passengr class DataSourceTests: XCTestCase { class TestableDataSource: PassDataSource { let initializedModelExpectation: XCTestExpectation init(expectation: XCTestExpectation) { self.initializedModelExpectation = expectation super.init() } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } let dataSource = PassDataSource() 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() } }
mit
DarrenKong/firefox-ios
Shared/Prefs.swift
1
6646
/* 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 public struct PrefsKeys { public static let KeyLastRemoteTabSyncTime = "lastRemoteTabSyncTime" public static let KeyLastSyncFinishTime = "lastSyncFinishTime" public static let KeyDefaultHomePageURL = "KeyDefaultHomePageURL" public static let KeyNoImageModeStatus = "NoImageModeStatus" public static let KeyNightModeButtonIsInMenu = "NightModeButtonIsInMenuPrefKey" public static let KeyNightModeStatus = "NightModeStatus" public static let KeyMailToOption = "MailToOption" public static let HasFocusInstalled = "HasFocusInstalled" public static let HasPocketInstalled = "HasPocketInstalled" public static let IntroSeen = "IntroViewControllerSeen" //Activity Stream public static let KeyTopSitesCacheIsValid = "topSitesCacheIsValid" public static let KeyTopSitesCacheSize = "topSitesCacheSize" public static let KeyNewTab = "NewTabPrefKey" public static let ASPocketStoriesVisible = "ASPocketStoriesVisible" public static let ASRecentHighlightsVisible = "ASRecentHighlightsVisible" public static let ASBookmarkHighlightsVisible = "ASBookmarkHighlightsVisible" public static let ASLastInvalidation = "ASLastInvalidation" public static let KeyUseCustomSyncService = "useCustomSyncService" public static let KeyCustomSyncToken = "customSyncTokenServer" public static let KeyCustomSyncProfile = "customSyncProfileServer" public static let KeyCustomSyncOauth = "customSyncOauthServer" public static let KeyCustomSyncAuth = "customSyncAuthServer" public static let KeyCustomSyncWeb = "customSyncWebServer" } public struct PrefsDefaults { public static let ChineseHomePageURL = "http://mobile.firefoxchina.cn/" public static let ChineseNewTabDefault = "HomePage" } public protocol Prefs { func getBranchPrefix() -> String func branch(_ branch: String) -> Prefs func setTimestamp(_ value: Timestamp, forKey defaultName: String) func setLong(_ value: UInt64, forKey defaultName: String) func setLong(_ value: Int64, forKey defaultName: String) func setInt(_ value: Int32, forKey defaultName: String) func setString(_ value: String, forKey defaultName: String) func setBool(_ value: Bool, forKey defaultName: String) func setObject(_ value: Any?, forKey defaultName: String) func stringForKey(_ defaultName: String) -> String? func objectForKey<T: Any>(_ defaultName: String) -> T? func boolForKey(_ defaultName: String) -> Bool? func intForKey(_ defaultName: String) -> Int32? func timestampForKey(_ defaultName: String) -> Timestamp? func longForKey(_ defaultName: String) -> Int64? func unsignedLongForKey(_ defaultName: String) -> UInt64? func stringArrayForKey(_ defaultName: String) -> [String]? func arrayForKey(_ defaultName: String) -> [Any]? func dictionaryForKey(_ defaultName: String) -> [String: Any]? func removeObjectForKey(_ defaultName: String) func clearAll() } open class MockProfilePrefs: Prefs { let prefix: String open func getBranchPrefix() -> String { return self.prefix } // Public for testing. open var things: NSMutableDictionary = NSMutableDictionary() public init(things: NSMutableDictionary, prefix: String) { self.things = things self.prefix = prefix } public init() { self.prefix = "" } open func branch(_ branch: String) -> Prefs { return MockProfilePrefs(things: self.things, prefix: self.prefix + branch + ".") } private func name(_ name: String) -> String { return self.prefix + name } open func setTimestamp(_ value: Timestamp, forKey defaultName: String) { self.setLong(value, forKey: defaultName) } open func setLong(_ value: UInt64, forKey defaultName: String) { setObject(NSNumber(value: value as UInt64), forKey: defaultName) } open func setLong(_ value: Int64, forKey defaultName: String) { setObject(NSNumber(value: value as Int64), forKey: defaultName) } open func setInt(_ value: Int32, forKey defaultName: String) { things[name(defaultName)] = NSNumber(value: value as Int32) } open func setString(_ value: String, forKey defaultName: String) { things[name(defaultName)] = value } open func setBool(_ value: Bool, forKey defaultName: String) { things[name(defaultName)] = value } open func setObject(_ value: Any?, forKey defaultName: String) { things[name(defaultName)] = value } open func stringForKey(_ defaultName: String) -> String? { return things[name(defaultName)] as? String } open func boolForKey(_ defaultName: String) -> Bool? { return things[name(defaultName)] as? Bool } open func objectForKey<T: Any>(_ defaultName: String) -> T? { return things[name(defaultName)] as? T } open func timestampForKey(_ defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } open func unsignedLongForKey(_ defaultName: String) -> UInt64? { return things[name(defaultName)] as? UInt64 } open func longForKey(_ defaultName: String) -> Int64? { return things[name(defaultName)] as? Int64 } open func intForKey(_ defaultName: String) -> Int32? { return things[name(defaultName)] as? Int32 } open func stringArrayForKey(_ defaultName: String) -> [String]? { if let arr = self.arrayForKey(defaultName) { if let arr = arr as? [String] { return arr } } return nil } open func arrayForKey(_ defaultName: String) -> [Any]? { let r: Any? = things.object(forKey: name(defaultName)) as Any? if r == nil { return nil } if let arr = r as? [Any] { return arr } return nil } open func dictionaryForKey(_ defaultName: String) -> [String: Any]? { return things.object(forKey: name(defaultName)) as? [String: Any] } open func removeObjectForKey(_ defaultName: String) { self.things.removeObject(forKey: name(defaultName)) } open func clearAll() { let dictionary = things as! [String: Any] let keysToDelete: [String] = dictionary.keys.filter { $0.hasPrefix(self.prefix) } things.removeObjects(forKeys: keysToDelete) } }
mpl-2.0
VirgilSecurity/virgil-sdk-keys-x
Source/Keyknox/KeyknoxManager/KeyknoxManager+Obj-C.swift
2
4497
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> // import Foundation import VirgilCrypto // MARK: - Obj-C extension extension KeyknoxManager { /// Pushes value /// /// - Parameters: /// - params: Push params /// - data: data to push /// - previousHash: Previous hash /// - publicKeys: public keys to encrypt /// - privateKey: private key to sign /// - completion: completion handler @objc open func pushValue(params: KeyknoxPushParams? = nil, data: Data, previousHash: Data?, publicKeys: [VirgilPublicKey], privateKey: VirgilPrivateKey, completion: @escaping (DecryptedKeyknoxValue?, Error?) -> Void) { self.pushValue(params: params, data: data, previousHash: previousHash, publicKeys: publicKeys, privateKey: privateKey) .start(completion: completion) } /// Pulls value /// /// - Parameters: /// - params: Pull params /// - publicKeys: public keys to verify signature /// - privateKey: private key to decrypt /// - completion: completion handler @objc open func pullValue(params: KeyknoxPullParams? = nil, publicKeys: [VirgilPublicKey], privateKey: VirgilPrivateKey, completion: @escaping (DecryptedKeyknoxValue?, Error?) -> Void) { self.pullValue(params: params, publicKeys: publicKeys, privateKey: privateKey) .start(completion: completion) } /// Returns set of keys /// /// - Parameter params: Get keys params /// - completion: completion handler @objc open func getKeys(params: KeyknoxGetKeysParams, completion: @escaping (Set<String>?, Error?) -> Void) { self.getKeys(params: params).start(completion: completion) } /// Resets Keyknox value (makes it empty) /// /// - params: Reset pararms /// - completion: completion handler @objc open func resetValue(params: KeyknoxResetParams? = nil, completion: @escaping(DecryptedKeyknoxValue?, Error?) -> Void) { self.resetValue(params: params).start(completion: completion) } /// Deletes recipient from list of shared /// /// - Parameters: /// - params: Delete recipient params /// - completion: completion handler @objc open func deleteRecipient(params: KeyknoxDeleteRecipientParams, completion: @escaping (DecryptedKeyknoxValue?, Error?) -> Void) { self.deleteRecipient(params: params).start(completion: completion) } }
bsd-3-clause
VirgilSecurity/virgil-sdk-keys-x
Source/Keyknox/Client/KeyknoxClientProtocol.swift
2
3374
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> // import Foundation /// Protocol for KeyknoxClient /// /// See: KeyknoxClient for default implementation @objc(VSSKeyknoxClientProtocol) public protocol KeyknoxClientProtocol: AnyObject { /// Push value to Keyknox service /// /// - Parameters: /// - params: params /// - meta: meta data /// - value: encrypted blob /// - previousHash: hash of previous blob /// - Returns: EncryptedKeyknoxValue /// - Throws: Depends on implementation @objc func pushValue(params: KeyknoxPushParams?, meta: Data, value: Data, previousHash: Data?) throws -> EncryptedKeyknoxValue /// Pulls values from Keyknox service /// /// - Parameter params: Pull params /// - Returns: EncryptedKeyknoxValue /// - Throws: Depends on implementation @objc func pullValue(params: KeyknoxPullParams?) throws -> EncryptedKeyknoxValue /// Get keys for given root /// /// - Parameter params: Get keys params /// - Returns: Array of keys /// - Throws: Depends on implementation @objc func getKeys(params: KeyknoxGetKeysParams) throws -> Set<String> /// Resets Keyknox value (makes it empty) /// /// - Parameter params: Reset params /// - Returns: DecryptedKeyknoxValue /// - Throws: Depends on implementation @objc func resetValue(params: KeyknoxResetParams?) throws -> DecryptedKeyknoxValue /// Deletes recipient /// /// - Parameter params: Delete recipient params /// - Returns: DecryptedKeyknoxValue /// - Throws: Depends on implementation @objc func deleteRecipient(params: KeyknoxDeleteRecipientParams) throws -> DecryptedKeyknoxValue }
bsd-3-clause
mumbler/PReVo-iOS
PoshReVo/Chefaj Paghoj/KonservitajViewController.swift
1
3729
// // KonservitajViewController.swift // PoshReVo // // Created by Robin Hill on 3/12/16. // Copyright © 2016 Robin Hill. All rights reserved. // import ReVoDatumbazo import Foundation import UIKit let konservitajChelIdent = "konservitajChelo" /* Pagho por vidi konservitaj artikoloj */ class KonservitajViewController : UIViewController, Chefpagho, Stilplena { @IBOutlet var vortoTabelo: UITableView? init() { super.init(nibName: "KonservitajViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { vortoTabelo?.delegate = self vortoTabelo?.dataSource = self vortoTabelo?.register(UITableViewCell.self, forCellReuseIdentifier: konservitajChelIdent) NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeDidChange(forChildContentContainer:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) efektivigiStilon() } func aranghiNavigaciilo() { parent?.title = NSLocalizedString("konservitaj titolo", comment: "") parent?.navigationItem.rightBarButtonItem = nil } func efektivigiStilon() { vortoTabelo?.indicatorStyle = UzantDatumaro.stilo.scrollKoloro vortoTabelo?.backgroundColor = UzantDatumaro.stilo.bazKoloro vortoTabelo?.separatorColor = UzantDatumaro.stilo.apartigiloKoloro vortoTabelo?.reloadData() } } // MARK: - UITableViewDelegate & UITableViewDataSource extension KonservitajViewController : UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return UzantDatumaro.konservitaj.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let novaChelo: UITableViewCell if let trovChelo = vortoTabelo?.dequeueReusableCell(withIdentifier: konservitajChelIdent) { novaChelo = trovChelo } else { novaChelo = UITableViewCell() } novaChelo.backgroundColor = UzantDatumaro.stilo.bazKoloro novaChelo.textLabel?.textColor = UzantDatumaro.stilo.tekstKoloro novaChelo.textLabel?.text = UzantDatumaro.konservitaj[indexPath.row].nomo novaChelo.isAccessibilityElement = true novaChelo.accessibilityLabel = novaChelo.textLabel?.text return novaChelo } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let indekso = UzantDatumaro.konservitaj[indexPath.row].indekso if let artikolo = VortaroDatumbazo.komuna.artikolo(porIndekso: indekso) { (navigationController as? ChefaNavigationController)?.montriArtikolon(artikolo) } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } // MARK: - Helpiloj // Respondi al mediaj shanghoj extension KonservitajViewController { func didChangePreferredContentSize(notification: NSNotification) -> Void { vortoTabelo?.reloadData() } }
mit
for-meng/BuDeJie-Swift-
BSBuDeJie/BSBuDeJie/Classess/Mine/View/BSCollectionViewCell.swift
1
753
// // BSCollectionViewCell.swift // BSBuDeJie // // Created by mh on 16/4/21. // Copyright © 2016年 BS. All rights reserved. // import UIKit import SDWebImage class BSCollectionViewCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! var model:BSCollectionModel?{ didSet{ if let newModel = model{ nameLabel.text = newModel.name iconImage.sd_setImageWithURL(NSURL.init(string: newModel.icon!)) } } } }
apache-2.0
Thongpak21/NongBeer-MVVM-iOS-Demo
NongBeer/Classes/History/View/HistoryCollectionViewCell.swift
1
871
// // HistoryCollectionViewCell.swift // NongBeer // // Created by Thongpak on 4/10/2560 BE. // Copyright © 2560 Thongpak. All rights reserved. // import UIKit class HistoryCollectionViewCell: UICollectionViewCell { static let identifier = "HistoryCollectionViewCell" @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var unitLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { setNeedsLayout() layoutIfNeeded() let size = contentView.systemLayoutSizeFitting(layoutAttributes.size) var newFrame = layoutAttributes.frame newFrame.size.height = ceil(size.height) layoutAttributes.frame = newFrame return layoutAttributes } }
apache-2.0
exyte/Macaw-Examples
GettingStarted/UI/Main/ViewController.swift
1
278
// // ViewController.swift // GettingStarted // // Created by Victor Sukochev on 02/11/2016. // Copyright © 2016 Exyte. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
mit
practicalswift/swift
validation-test/compiler_crashers_fixed/28693-swift-genericenvironment-queryinterfacetypesubstitutions-operator-swift-substitu.swift
53
412
// 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 -emit-ir protocol b:Self
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKitMock/CustodialBalanceServiceAPIMock.swift
1
799
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import MoneyKit @testable import PlatformKit class TradingBalanceServiceAPIMock: TradingBalanceServiceAPI { var underlyingBalanceState: CustodialAccountBalanceState = .absent var underlyingBalanceStates: CustodialAccountBalanceStates = .absent var balances: AnyPublisher<CustodialAccountBalanceStates, Never> { .just(underlyingBalanceStates) } func balance(for currencyType: CurrencyType) -> AnyPublisher<CustodialAccountBalanceState, Never> { .just(underlyingBalanceState) } func fetchBalances() -> AnyPublisher<CustodialAccountBalanceStates, Never> { .just(underlyingBalanceStates) } func invalidateTradingAccountBalances() { // no-op } }
lgpl-3.0
fthomasmorel/insapp-iOS
Insapp/AttendesViewController.swift
1
1484
// // AttendesViewController.swift // Insapp // // Created by Florent THOMAS-MOREL on 10/2/16. // Copyright © 2016 Florent THOMAS-MOREL. All rights reserved. // import Foundation import UIKit class AttendesViewController: UIViewController, ListUserDelegate { var going:[String] = [] var notgoing:[String] = [] var maybe:[String] = [] var listUserViewController: ListUserViewController? override func viewDidLoad() { super.viewDidLoad() self.listUserViewController = self.childViewControllers.last as? ListUserViewController self.listUserViewController?.userIds = [going, maybe, notgoing] self.listUserViewController?.fetchUsers() self.listUserViewController?.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.notifyGoogleAnalytics() self.lightStatusBar() self.hideNavBar() } func didTouchUser(_ user:User){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "UserViewController") as! UserViewController vc.user_id = user.id vc.setEditable(false) vc.canReturn(true) self.navigationController?.pushViewController(vc, animated: true) } @IBAction func dismissAction(_ sender: AnyObject) { self.navigationController!.popViewController(animated: true) } }
mit
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/GuessItem.swift
1
392
// // GuessItem.swift // XMLYDemo // // Created by xiudou on 2016/12/22. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit class GuessItem: BaseModel { var id : Int64 = 0 var albumId : Int64 = 0 var uid : Int64 = 0 var title : String = "" var playsCounts : Int64 = 0 var trackTitle : String = "" var albumCoverUrl290 :String = "" }
mit
huonw/swift
test/Migrator/prefix_typeof_expr_unneeded.swift
15
410
// RUN: %empty-directory(%t) && %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t.result // RUN: diff -u %s.expected %t.result // RUN: %target-swift-frontend -typecheck %t.result -swift-version 4 class HasTypeMethod { var type: Int { _ = type(of: 1) return 1 } } class NoTypeMethod { func meth() { _ = type(of: 1) // Don't need to add prefix } }
apache-2.0
fuji2013/UtilANDExt
UtilANDExt/ViewController.swift
1
522
// // ViewController.swift // UtilANDExt // // Created by FUJISAWAHIROYUKI on 2015/04/27. // Copyright (c) 2015年 swift-studying. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
AndreyPanov/ApplicationCoordinator
ApplicationCoordinator/Flows/OnboardingFlow/Controllers/OnboardingView.swift
1
80
protocol OnboardingView: BaseView { var onFinish: (() -> Void)? { get set } }
mit
moked/iuob
iUOB 2/Views/CourseCVCell.swift
1
414
// // CourseCVCell.swift // iUOB 2 // // Created by Miqdad Altaitoon on 10/9/16. // Copyright © 2016 Miqdad Altaitoon. All rights reserved. // import UIKit class CourseCVCell: UICollectionViewCell { @IBOutlet weak var courseTitleLabel: UILabel! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! }
mit
osorioabel/my-location-app
My Locations/My Locations/View/Utils/HudView.swift
1
2138
// // HudView.swift // My Locations // // Created by Abel Osorio on 2/17/16. // Copyright © 2016 Abel Osorio. All rights reserved. // import UIKit class HudView: UIView { var text = "" class func hubInView(view:UIView, animated: Bool) -> HudView{ let hudView = HudView(frame: view.bounds) hudView.opaque = false view.addSubview(hudView) view.userInteractionEnabled = false hudView.showAnimated(animated) return hudView } override func drawRect(rect: CGRect) { let boxWidth: CGFloat = 96 let boxHeight: CGFloat = 96 let boxRect = CGRect( x: round((bounds.size.width - boxWidth) / 2), y: round((bounds.size.height - boxHeight) / 2), width: boxWidth, height: boxHeight) let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10) UIColor(white: 0.3, alpha: 0.8).setFill() roundedRect.fill() if let image = UIImage(named: "Checkmark") { let imagePoint = CGPoint(x: center.x - round(image.size.width / 2),y: center.y - round(image.size.height / 2) - boxHeight / 8) image.drawAtPoint(imagePoint) } let attribs = [ NSFontAttributeName: UIFont.systemFontOfSize(16), NSForegroundColorAttributeName: UIColor.whiteColor() ] let textSize = text.sizeWithAttributes(attribs) let textPoint = CGPoint(x: center.x - round(textSize.width / 2),y: center.y - round(textSize.height / 2) + boxHeight / 4) text.drawAtPoint(textPoint, withAttributes: attribs) } func showAnimated(animated: Bool) { if animated { alpha = 0 transform = CGAffineTransformMakeScale(1.3, 1.3) UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: { self.alpha = 1 self.transform = CGAffineTransformIdentity }, completion: nil) } } }
mit
jovito-royeca/Decktracker
osx/DataSource/DataSource/Color.swift
1
1355
// // CardColor.swift // DataSource // // Created by Jovit Royeca on 29/06/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import Foundation import CoreData class Color: NSManagedObject { struct Keys { static let Name = "name" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Color", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) update(dictionary) } func update(dictionary: [String : AnyObject]) { name = dictionary[Keys.Name] as? String if let name = name { if name == "Black" { symbol = "B" } else if name == "Blue" { symbol = "U" } else if name == "Green" { symbol = "G" } else if name == "Red" { symbol = "R" } else if name == "White" { symbol = "W" } else if name == "Colorless" { symbol = "C" } } } }
apache-2.0
rhcad/ShapeAnimation-Swift
ShapeAnimation_UnitTests/SwiftUtilities_Tests.swift
3
3436
// // SwiftUtilities_Tests.swift // SwiftUtilities Tests // // Created by Zhang Yungui on 8/12/14. // Copyright (c) 2014 github.com/rhcad. All rights reserved. // import Cocoa import XCTest import SwiftUtilities class SwiftUtilities_Tests: 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 testCGPointExtensions() { let value1 = CGPoint(x:10) XCTAssertNotEqual(value1, CGPointZero) XCTAssertEqual(value1, CGPoint(x:10, y:0)) let value2 = value1 + CGPoint(y:20) XCTAssertEqual(value2, CGPoint(x:10, y:20)) let value3 = value2 * 2 XCTAssertEqual(value3, CGPoint(x:20, y:40)) let value4 = value3 - CGPoint(x:1, y:1) XCTAssertEqual(value4, CGPoint(x:19, y:39)) } func testCGSizeExtensions() { let value1 = CGSize(width:10) XCTAssertNotEqual(value1, CGSizeZero) XCTAssertEqual(value1, CGSize(width:10, height:0)) let value2 = value1 + CGSize(height:20) XCTAssertEqual(value2, CGSize(width:10, height:20)) let value3 = value2 * 2 XCTAssertEqual(value3, CGSize(width:20, height:40)) } func testCGRectExtensions() { let value1 = CGRect(width:100, height:200) XCTAssertEqual(value1, CGRect(x:0, y:0, width:100, height:200)) let value2 = CGRect(size:CGSize(width:100,height:200)) XCTAssertEqual(value2, CGRect(x:0, y:0, width:100, height:200)) } func testQuadrants() { XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:10, y:10)), Quadrant.TopRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:-10, y:10)), Quadrant.TopLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:10, y:-10)), Quadrant.BottomRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:-10, y:-10)), Quadrant.BottomLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:0, y:0)), Quadrant.TopRight) let origin = CGPoint(x:10, y:10) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:15, y:15), origin:origin), Quadrant.TopRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:5, y:15), origin:origin), Quadrant.TopLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:15, y:5), origin:origin), Quadrant.BottomRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:5, y:5), origin:origin), Quadrant.BottomLeft) let rect = CGRect(width:100, height:50) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x:15, y:15), rect:rect), Quadrant.BottomLeft) XCTAssertEqual(Quadrant.TopRight.quadrantRectOfRect(rect), CGRect(x:50, y:25, width: 50, height:25)) XCTAssertEqual(Quadrant.BottomLeft.quadrantRectOfRect(rect), CGRect(x:0, y:0, width: 50, height:25)) } func testBoolEnum() { let b = BoolEnum(false) XCTAssertEqual(b, false) XCTAssertEqual(b, BoolEnum.False) } // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock() { // // Put the code you want to measure the time of here. // } // } }
bsd-2-clause
iOS-mamu/SS
P/PotatsoBase/Localized.swift
1
4308
// // Strings.swift // Potatso // // Created by LEI on 1/23/16. // Copyright © 2016 TouchingApp. All rights reserved. // import Foundation /// Internal current language key let LCLCurrentLanguageKey = "LCLCurrentLanguageKey" /// Default language. English. If English is unavailable defaults to base localization. let LCLDefaultLanguage = "en" /// Name for language change notification public let LCLLanguageChangeNotification = "LCLLanguageChangeNotification" public extension String { /** Swift 2 friendly localization syntax, replaces NSLocalizedString - Returns: The localized string. */ public func localized() -> String { if let path = Bundle.main.path(forResource: Localize.currentLanguage(), ofType: "lproj"), let bundle = Bundle(path: path) { return bundle.localizedString(forKey: self, value: nil, table: nil) }else if let path = Bundle.main.path(forResource: "Base", ofType: "lproj"), let bundle = Bundle(path: path) { return bundle.localizedString(forKey: self, value: nil, table: nil) } return self } /** Swift 2 friendly localization syntax with format arguments, replaces String(format:NSLocalizedString) - Returns: The formatted localized string with arguments. */ public func localizedFormat(_ arguments: CVarArg...) -> String { return String(format: localized(), arguments: arguments) } /** Swift 2 friendly plural localization syntax with a format argument - parameter argument: Argument to determine pluralisation - returns: Pluralized localized string. */ public func localizedPlural(_ argument: CVarArg) -> String { return NSString.localizedStringWithFormat(localized() as NSString, argument) as String } } // MARK: Language Setting Functions open class Localize: NSObject { /** List available languages - Returns: Array of available languages. */ open class func availableLanguages() -> [String] { return Bundle.main.localizations } /** Current language - Returns: The current language. String. */ open class func currentLanguage() -> String { if let currentLanguage = UserDefaults.standard.object(forKey: LCLCurrentLanguageKey) as? String { return currentLanguage } return defaultLanguage() } /** Change the current language - Parameter language: Desired language. */ open class func setCurrentLanguage(_ language: String) { let selectedLanguage = availableLanguages().contains(language) ? language : defaultLanguage() if (selectedLanguage != currentLanguage()){ UserDefaults.standard.set(selectedLanguage, forKey: LCLCurrentLanguageKey) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name(rawValue: LCLLanguageChangeNotification), object: nil) } } /** Default language - Returns: The app's default language. String. */ open class func defaultLanguage() -> String { var defaultLanguage: String = String() guard let preferredLanguage = Bundle.main.preferredLocalizations.first else { return LCLDefaultLanguage } let availableLanguages: [String] = self.availableLanguages() if (availableLanguages.contains(preferredLanguage)) { defaultLanguage = preferredLanguage } else { defaultLanguage = LCLDefaultLanguage } return defaultLanguage } /** Resets the current language to the default */ open class func resetCurrentLanguageToDefault() { setCurrentLanguage(self.defaultLanguage()) } /** Get the current language's display name for a language. - Parameter language: Desired language. - Returns: The localized string. */ open class func displayNameForLanguage(_ language: String) -> String { let locale : Locale = Locale(identifier: currentLanguage()) if let displayName = (locale as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: language) { return displayName } return String() } }
mit
chausson/Swift-Design-Patterns-for-iOS
Demo/Swift-Design-Demo/Swift-Design-DemoUITests/Swift_Design_DemoUITests.swift
1
1274
// // Swift_Design_DemoUITests.swift // Swift-Design-DemoUITests // // Created by Chausson on 2016/12/19. // Copyright © 2016年 Chausson. All rights reserved. // import XCTest class Swift_Design_DemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
newlix/orz-swift
Tests/LinkReferencesTests.swift
1
1658
// // LinkReferencesTests.swift // Orz // // Created by newlix on 1/26/16. // Copyright © 2016 newlix. All rights reserved. // import XCTest @testable import Orz import RealmSwift class LinkReferencesTests: XCTestCase { let orz:Orz = Orz(URL: "http://example.com", version: 1) let realm = try! Realm() override func setUp() { super.setUp() clearBeforeTesting() } override func tearDown() { super.tearDown() } func testReferenceOfNil() { XCTAssertNil(orz.referenceOf("Fake", id: "")) } func testReferenceOfCreate() { orz.referenceOf("Fake", id: "fake") let object = realm.objectForPrimaryKey(Fake.self, key: "fake")! XCTAssertEqualWithAccuracy(object.updateTimestamp, 0, accuracy: 0.001) } func testReferenceOfExisting() { realm.beginWrite() let value = [ "id":"fake", "updateTimestamp": 0.4 ] realm.create(Fake.self, value: value, update: false) try! realm.commitWrite() let object = orz.referenceOf("Fake", id: "fake")! let timestamp = object.valueForKey("updateTimestamp") as! Double XCTAssertEqualWithAccuracy(timestamp, 0.4, accuracy: 0.001) } func testLinkReferences() { let parent = Parent() realm.beginWrite() realm.add(parent) try! realm.commitWrite() orz.linkReferences(parent, dict: [ "id": "parent", "fakeId": "fake", "_hiddenFakeId": "hiddenfFake" ]) XCTAssertNotNil(parent.fake) XCTAssertNil(parent._hiddenFake) } }
mit
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/Admin/AdminCardTestingViewController.swift
2
2085
import Foundation import RxSwift import Keys class AdminCardTestingViewController: UIViewController { lazy var keys = EidolonKeys() var cardHandler: CardHandler! @IBOutlet weak var logTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() self.logTextView.text = "" if AppSetup.sharedState.useStaging { cardHandler = CardHandler(apiKey: self.keys.cardflightStagingAPIClientKey(), accountToken: self.keys.cardflightStagingMerchantAccountToken()) } else { cardHandler = CardHandler(apiKey: self.keys.cardflightProductionAPIClientKey(), accountToken: self.keys.cardflightProductionMerchantAccountToken()) } cardHandler.cardStatus .subscribe { (event) in switch event { case .next(let message): self.log("\(message)") case .error(let error): self.log("\n====Error====\n\(error)\nThe card reader may have become disconnected.\n\n") if self.cardHandler.card != nil { self.log("==\n\(self.cardHandler.card!)\n\n") } case .completed: guard let card = self.cardHandler.card else { // Restarts the card reader self.cardHandler.startSearching() return } let cardDetails = "Card: \(card.name) - \(card.last4) \n \(card.cardToken)" self.log(cardDetails) } } .addDisposableTo(rx_disposeBag) cardHandler.startSearching() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cardHandler.end() } func log(_ string: String) { self.logTextView.text = "\(self.logTextView.text ?? "")\n\(string)" } @IBAction func backTapped(_ sender: AnyObject) { _ = navigationController?.popViewController(animated: true) } }
mit
teaxus/TSAppEninge
Source/Basic/Controller/TSImagePicker/TSImagePickCollectionViewCell.swift
1
598
// // TSImagePickCollectionViewCell.swift // StandardProject // // Created by teaxus on 15/12/31. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit public class TSImagePickCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var view_hook: TSGeneralHook! var bool_select:Bool = false{ didSet{ view_hook.isHidden = !bool_select } } public override func awakeFromNib() { super.awakeFromNib() // Initialization code view_hook.isHidden = true } }
mit
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/SLV_917_MyPageEventViewController.swift
1
3223
// // SLV_917_MyPageEventViewController.swift // selluv-ios // // Created by 김택수 on 2017. 2. 12.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit class SLV_917_MyPageEventViewController: SLVBaseStatusShowController { @IBOutlet weak var tableView:UITableView! let myPageEventCellReuseIdentifier = "myPageEventCell" var events:[Event]! = [] //MARK: //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() tabController.animationTabBarHidden(true) self.tableView.register(UINib(nibName: "SLV917MyPageEventCell", bundle: nil), forCellReuseIdentifier: myPageEventCellReuseIdentifier) self.settingUI() } //MARK: //MARK: Private func settingUI() { tabController.hideFab() self.title = "이벤트" self.navigationItem.hidesBackButton = true let back = UIButton() back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal) back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20) back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26) back.addTarget(self, action: #selector(SLV_917_MyPageEventViewController.clickBackButton(_:)), for: .touchUpInside) let item = UIBarButtonItem(customView: back) self.navigationItem.leftBarButtonItem = item } //MARK: //MARK: IBAction func clickBackButton(_ sender:UIButton) { self.navigationController?.popViewController() } //MARK: //MARK: Override } extension SLV_917_MyPageEventViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 244 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! SLV917MyPageEventCell cell.setSelected(false, animated: true) let board = UIStoryboard(name:"Me", bundle: nil) let controller = board.instantiateViewController(withIdentifier: "SLV_917_MyPageEventDetailViewController") as! SLV_917_MyPageEventDetailViewController self.navigationController?.pushViewController(controller, animated: true) controller.event = self.events[indexPath.row] } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.events.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: myPageEventCellReuseIdentifier, for: indexPath) as! SLV917MyPageEventCell let event = self.events[indexPath.row] let titleImage = event.titleImage ?? "" if titleImage != "" { let path = "\(dnImage)/\(event.titleImage!)" let url = URL(string: path)! SLVDnImageModel.shared.setupImageView(view: cell.eventImageView, from: url) } return cell } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/06095-swift-constraints-constraintsystem-opengeneric.swift
11
248
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { struct c<I : A? { struct c<T where T.Element == c let end = g<T, g = c
mit
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Controllers/Review Prompt/ApplicationAppStateProviding.swift
2
173
import UIKit struct ApplicationAppStateProviding: AppStateProviding { var isAppActive: Bool { return UIApplication.shared.applicationState == .active } }
mit
ello/ello-ios
Sources/Controllers/Stream/Cells/NoPostsCell.swift
1
2083
//// /// NoPostsCell.swift // class NoPostsCell: CollectionViewCell { static let reuseIdentifier = "NoPostsCell" struct Size { static let headerTop: CGFloat = 14 static let bodyTop: CGFloat = 17 static let labelInsets: CGFloat = 10 } private let noPostsHeader = StyledLabel(style: .largeBold) private let noPostsBody = StyledLabel() var isCurrentUser: Bool = false { didSet { updateText() } } override func style() { noPostsHeader.textAlignment = .left noPostsBody.textAlignment = .left } override func arrange() { contentView.addSubview(noPostsHeader) contentView.addSubview(noPostsBody) noPostsHeader.snp.makeConstraints { make in make.top.equalTo(contentView).inset(Size.headerTop) make.leading.trailing.equalTo(contentView).inset(Size.labelInsets) } noPostsBody.snp.makeConstraints { make in make.leading.trailing.equalTo(contentView).inset(Size.labelInsets) make.top.equalTo(noPostsHeader.snp.bottom).offset(Size.bodyTop) } } private func updateText() { let noPostsHeaderText: String let noPostsBodyText: String if isCurrentUser { noPostsHeaderText = InterfaceString.Profile.CurrentUserNoResultsTitle noPostsBodyText = InterfaceString.Profile.CurrentUserNoResultsBody } else { noPostsHeaderText = InterfaceString.Profile.NoResultsTitle noPostsBodyText = InterfaceString.Profile.NoResultsBody } noPostsHeader.text = noPostsHeaderText noPostsHeader.font = UIFont.regularBoldFont(18) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 let attrString = NSMutableAttributedString( string: noPostsBodyText, attributes: [ .font: UIFont.defaultFont(), .paragraphStyle: paragraphStyle, ] ) noPostsBody.attributedText = attrString } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16039-swift-sourcemanager-getmessage.swift
11
251
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a { var d = [ { func a { p( { class A { } let a { ( " let { class case ,
mit
BenziAhamed/Nevergrid
NeverGrid/Source/PriorityQueue.swift
1
1032
// // PriorityQueue.swift // MrGreen // // Created by Benzi on 03/09/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation struct PriorityQueueNode<T> { var item:T var priority:Int } class PriorityQueue<T> { var q = [PriorityQueueNode<T>]() var count:Int { return q.count } func put(item:T, priority:Int) { let node = PriorityQueueNode(item: item, priority: priority) if q.count == 0 { q.append(node) } else { var insertIndex = 0 while insertIndex < count && q[insertIndex].priority <= priority { insertIndex++ } if insertIndex < q.count { q.insert(node, atIndex: insertIndex) } else { q.append(node) } } } func get() -> T? { if q.count == 0 { return nil } else { return q.removeAtIndex(0).item } } }
isc
austinzheng/swift-compiler-crashes
crashes-duplicates/16618-no-stacktrace.swift
11
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { for { let a { init( ) { protocol a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/19719-swift-parentype-get.swift
10
230
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{ protocol b:A protocol A{ typealias b typealias e:b.j
mit
bannzai/ResourceKit
Sources/ResourceKitCore/Image/ImageOutputer.swift
1
2580
// // ImageOutputer.swift // ResourceKit // // Created by Yudai.Hirose on 2017/08/09. // Copyright © 2017年 kingkong999yhirose. All rights reserved. // import Foundation public protocol ImageOutputer: Output { var begin: String { get } var body: String { get } var end: String { get } } public extension ImageOutputer { var declaration: String { return [begin, body, end].joined(separator: Const.newLine) } } public struct ImageOutputerImpl: ImageOutputer { let assetsOutputer: ImageOutputer let resourcesOutputer: ImageOutputer let config: Config static func imageFunction(_ withName: String) -> String { return "UIImage(named: \"\(withName)\")!" } public var begin: String { return "extension UIImage {" } public var body: String { guard config.image.assetCatalog || config.image.projectResource else { return "" } if !config.image.assetCatalog { return resourcesOutputer.declaration } if !config.image.projectResource { return assetsOutputer.declaration } return assetsOutputer.declaration + Const.newLine + resourcesOutputer.declaration } public var end: String { return "}" + Const.newLine } } extension ImageOutputerImpl { public struct AssetsOutputer: ImageOutputer { let imageNames: [String] public var begin: String { return "\(Const.tab1)public struct Asset {" } public var body: String { let body = imageNames .flatMap { "\(Const.tab2)public static let \($0): UIImage = \(ImageOutputerImpl.imageFunction($0))" } .joined(separator: Const.newLine) return body } public var end: String { return "\(Const.tab1)}" + Const.newLine } } } extension ImageOutputerImpl { public struct ResourcesOutputer: ImageOutputer { let imageNames: [String] public var begin: String { return "\(Const.tab1)public struct Resource {" } public var body: String { let body = imageNames .flatMap { "\(Const.tab2)public static let \($0): UIImage = \(ImageOutputerImpl.imageFunction($0))" } .joined(separator: Const.newLine) return body } public var end: String { return "\(Const.tab1)}" + Const.newLine } } }
mit
austinzheng/swift-compiler-crashes
fixed/00116-swift-declname-printpretty.swift
12
309
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n
mit
eurofurence/ef-app_ios
Packages/EurofurenceApplicationSession/Tests/EurofurenceApplicationSessionTests/Firebase Notification Registration/FirebaseNotificationsTokenRegistrationTests.swift
1
5902
import EurofurenceApplicationSession import EurofurenceModel import XCTest import XCTEurofurenceModel class FirebaseRemoteNotificationsTokenRegistrationTests: XCTestCase { private struct Context { var tokenRegistration: FirebaseRemoteNotificationsTokenRegistration var capturingFirebaseAdapter: CapturingFirebaseAdapter var capturingFCMDeviceRegister: CapturingFCMDeviceRegistration func registerDeviceToken(deviceToken: Data = Data(), userAuthenticationToken: String = "", completionHandler: ((Error?) -> Void)? = nil) { tokenRegistration.registerRemoteNotificationsDeviceToken( deviceToken, userAuthenticationToken: userAuthenticationToken, completionHandler: { completionHandler?($0) } ) } } private func assembleApp( configuration: BuildConfiguration, version: String = "", cid: ConventionIdentifier = ConventionIdentifier(identifier: "") ) -> Context { let buildConfigurationProviding = StubBuildConfigurationProviding(configuration: configuration) let appVersionProviding = StubAppVersionProviding(version: version) let capturingFirebaseAdapter = CapturingFirebaseAdapter() let capturingFCMDeviceRegister = CapturingFCMDeviceRegistration() let tokenRegistration = FirebaseRemoteNotificationsTokenRegistration( buildConfiguration: buildConfigurationProviding, appVersion: appVersionProviding, conventionIdentifier: cid, firebaseAdapter: capturingFirebaseAdapter, fcmRegistration: capturingFCMDeviceRegister ) return Context( tokenRegistration: tokenRegistration, capturingFirebaseAdapter: capturingFirebaseAdapter, capturingFCMDeviceRegister: capturingFCMDeviceRegister ) } func testSubscribesToCIDTopics() { let cid = ConventionIdentifier(identifier: "EF25") let context = assembleApp(configuration: .debug, cid: cid) context.registerDeviceToken() XCTAssertTrue(context.capturingFirebaseAdapter.didSubscribeToTopic(.cid(cid.identifier))) XCTAssertTrue(context.capturingFirebaseAdapter.didSubscribeToTopic(.cidiOS(cid.identifier))) } func testSetTheTokenOntoTheNotificationsService() { let context = assembleApp(configuration: .debug) let deviceToken = "I'm a token".data(using: .utf8).unsafelyUnwrapped context.registerDeviceToken(deviceToken: deviceToken) XCTAssertEqual(deviceToken, context.capturingFirebaseAdapter.registeredDeviceToken) } func testReportTheFirebaseFCMTokenToTheFCMDeviceRegister() { let context = assembleApp(configuration: .debug) let stubFCMToken = "Stub token" context.capturingFirebaseAdapter.fcmToken = stubFCMToken context.registerDeviceToken() XCTAssertEqual(stubFCMToken, context.capturingFCMDeviceRegister.capturedFCM) } func testRegisterTheiOSTopicForDebugConfiguration() { let context = assembleApp(configuration: .debug) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredToiOSTopic) } func testRegisterTheiOSTopicForReleaseConfiguration() { let context = assembleApp(configuration: .release) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredToiOSTopic) } func testRegisterTheDebugTopicForDebugBuilds() { let context = assembleApp(configuration: .debug) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredDebugTopic) } func testNotRegisterTheDebugTopicForReleaseBuilds() { let context = assembleApp(configuration: .release) context.registerDeviceToken() XCTAssertFalse(context.capturingFCMDeviceRegister.registeredDebugTopic) } func testRegisterTheVersionTopicForReleaseBuildsUsingTheVersionFromTheProvider() { let version = "2.0.0" let context = assembleApp(configuration: .release, version: version) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredVersionTopic(with: version)) } func testRegisterTheVersionTopicForDebugBuildsUsingTheVersionFromTheProvider() { let version = "2.0.0" let context = assembleApp(configuration: .debug, version: version) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredVersionTopic(with: version)) } func testRegisterTheCIDTopic() { let cid = ConventionIdentifier(identifier: "EF25") let context = assembleApp(configuration: .debug, cid: cid) context.registerDeviceToken() XCTAssertTrue(context.capturingFCMDeviceRegister.registeredCIDTopic(with: cid.identifier)) } func testRegisteringDeviceTokenShouldProvideTheUserAuthenticationToken() { let authenticationToken = "Token" let context = assembleApp(configuration: .debug) context.registerDeviceToken(userAuthenticationToken: authenticationToken) XCTAssertEqual(authenticationToken, context.capturingFCMDeviceRegister.capturedAuthenticationToken) } func testErrorsDuringFCMRegistrationArePropogatedBackThroughTheCompletionHandler() { let context = assembleApp(configuration: .debug) var observedError: NSError? context.registerDeviceToken { observedError = $0 as NSError? } let expectedError = NSError(domain: "Test", code: 0, userInfo: nil) context.capturingFCMDeviceRegister.completionHandler?(expectedError) XCTAssertEqual(expectedError, observedError) } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/15768-swift-sourcemanager-getmessage.swift
11
259
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { deinit { if true { func c { protocol A { struct A { let a { f = [ { class case ,
mit
DianQK/LearnRxSwift
LearnRxSwift/RxNetwork/Moya/UserAPI.swift
1
756
// // UserAPI.swift // LearnRxSwift // // Created by DianQK on 16/2/22. // Copyright © 2016年 DianQK. All rights reserved. // import Moya let UserProvider = RxMoyaProvider<UserAPI>() public enum UserAPI { case Users } extension UserAPI: TargetType { public var baseURL: NSURL { return NSURL(string: host)! } public var path: String { switch self { case .Users: return "/users" } } public var method: Moya.Method { return .GET } public var parameters: [String: AnyObject]? { return nil } public var sampleData: NSData { switch self { case .Users: return "".dataUsingEncoding(NSUTF8StringEncoding)! } } }
mit