repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
colemancda/Linchi
refs/heads/master
Linchi/String-Manipulation/Percent-Encoding.swift
mit
4
// // Percent-Encoding.swift // Linchi // extension UInt8 { // TODO: find better name than "hexNumber" /** Returns: - (0, 1, ..., 14, 15) iff input is ASCII value for (0, 1, ..., E, F) - `nil` otherwise */ private static func hexNumber(asciiValue: UInt8) -> UInt8? { guard asciiValue >= 48 else { return nil } if asciiValue <= 57 { return asciiValue - 48 } else if asciiValue >= 65 && asciiValue <= 70 { return asciiValue - 55 } else if asciiValue >= 97 && asciiValue <= 102 { return asciiValue - 87 } else { return nil } } /** Returns the value of the hexadecimal number `"0x(fst)(snd)"` if `fst` and `snd` are ASCII values for hexadecimal digits. Returns nil otherwise. __Example__: `let fst = 67 // 'C'` `let snd = 50 // '2'` `// UInt8.fromHexRepresentation(fst, snd) == 194` */ private static func fromHexRepresentation(fst: UInt8, _ snd: UInt8) -> UInt8? { guard let c1 = UInt8.hexNumber(fst), let c2 = UInt8.hexNumber(snd) else { return nil } return (c1 << 4) | c2 } /** Split `self` into its four left and right bits. __Example__: `0b00101110 -> 0b0010 and 0b1110` */ private var split : (UInt8, UInt8) { return (self / 16, self % 16) } /// Percent-encode (`self` as a UTF-8 character). private func percentEncoding() -> String { return "%" + String.HEX_TABLE[Int(split.0)] + String.HEX_TABLE[Int(split.1)] } } extension String { private static func initReservedCharacters() -> [Bool] { var chars = [Bool](count: 127, repeatedValue: false) ["!", "#","$", "&", "'", "(", ")", "*", "+", "/", ":", ";", "=", "?", "@", "[", "]", "]", "%", ","].forEach { chars[Int(Character($0).toASCII())] = true } return chars } /// Reserved characters according to RFC 3986 Section 2.2. These characters have to be percent-encoded. private static let RESERVED_CHARS = String.initReservedCharacters() private static let HEX_TABLE = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] /// Creates a String from the percent-encoded UTF-8 string `bytes`. (RFC 3986 Section 2.5) public func newByRemovingPercentEncoding() -> String { let percent = Character("%").toASCII() var result : [UInt8] = [] var gen = utf8.generate() while let fst = gen.next() { guard fst == percent else { result.append(fst) continue } guard let snd = gen.next() else { result.append(fst) break } guard let thrd = gen.next() else { result.append(fst); result.append(snd) break } guard let value = UInt8.fromHexRepresentation(snd, thrd) else { result.append(fst); result.append(snd); result.append(thrd) continue } result.append(value) } return String.fromUTF8Bytes(result) } /// Creates a String equal to `self` percent-encoded. public func newByAddingPercentEncoding() -> String { return utf8.reduce("") { if $1 > 127 || String.RESERVED_CHARS[Int($1)] { return $0 + $1.percentEncoding() } else { return $0 + String(UnicodeScalar($1)) } } } }
7326c50ef9d88d231cd6f8a1eb1af2f7
28.272
162
0.506149
false
false
false
false
alblue/swift
refs/heads/master
test/attr/attr_specialize.swift
apache-2.0
14
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s struct S<T> {} public protocol P { } extension Int: P { } public protocol ProtocolWithDep { associatedtype Element } public class C1 { } class Base {} class Sub : Base {} class NonSub {} // Specialize freestanding functions with the correct number of concrete types. // ---------------------------------------------------------------------------- // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) // CHECK: @_specialize(exported: false, kind: full, where T == S<Int>) @_specialize(where T == S<Int>) @_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}}, // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} @_specialize(where T == T1) // expected-error{{use of undeclared type 'T1'}} public func oneGenericParam<T>(_ t: T) -> T { return t } // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int) @_specialize(where T == Int, U == Int) @_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'U' in '_specialize' attribute}} public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) { return (t, u) } @_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}} func nonGenericParam(x: Int) {} // Specialize contextual types. // ---------------------------- class G<T> { // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) @_specialize(where T == T) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}} @_specialize(where T == S<T>) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}} @_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}} // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} func noGenericParams() {} // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float) @_specialize(where T == Int, U == Float) // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>) @_specialize(where T == Int, U == S<Int>) @_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error {{Missing constraint for 'U' in '_specialize' attribute}} func oneGenericParam<U>(_ t: T, u: U) -> (U, T) { return (u, t) } } // Specialize with requirements. // ----------------------------- protocol Thing {} struct AThing : Thing {} // CHECK: @_specialize(exported: false, kind: full, where T == AThing) @_specialize(where T == AThing) @_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}} func oneRequirement<T : Thing>(_ t: T) {} protocol HasElt { associatedtype Element } struct IntElement : HasElt { typealias Element = Int } struct FloatElement : HasElt { typealias Element = Float } @_specialize(where T == FloatElement) @_specialize(where T == IntElement) // expected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}} func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {} @_specialize(where T == Sub) @_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}} func superTypeRequirement<T : Base>(_ t: T) {} @_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}} public func requirementOnNonGenericFunction(x: Int, y: Int) { } @_specialize(where Y == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} public func missingRequirement<X:P, Y>(x: X, y: Y) { } @_specialize(where) // expected-error{{expected type}} @_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}} public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) { } @_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{use of undeclared type 'Z'}} // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} @_specialize(where X:_Trivial(8), Y:_Trivial(32, 4)) @_specialize(where X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} @_specialize(where Y:_Trivial(32)) // expected-error {{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} @_specialize(where Y: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} @_specialize(where Y: MyClass) // expected-error{{use of undeclared type 'MyClass'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} // expected-error@-1{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where X:_Trivial(8), Y == Int) @_specialize(where X == Int, Y == Int) @_specialize(where X == Int, X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} // expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}} // expected-note@-2{{same-type constraint 'X' == 'Int' written here}} @_specialize(where Y:_Trivial(32), X == Float) @_specialize(where X1 == Int, Y1 == Int) // expected-error{{use of undeclared type 'X1'}} expected-error{{use of undeclared type 'Y1'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} // expected-error@-1 2{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) { } @_specialize(where X == Int, Y == Int) @_specialize(exported: true, where X == Int, Y == Int) @_specialize(exported: false, where X == Int, Y == Int) @_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: partial, where X == Int) @_specialize(kind: full, where X == Int, Y == Int) @_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: , where X == Int, Y == Int) @_specialize(exported: true, kind: partial, where X == Int, Y == Int) @_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}} @_specialize(kind: partial, exported: true, where X == Int, Y == Int) @_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}} @_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{use of undeclared type 'exported'}} expected-error{{use of undeclared type 'kind'}} expected-error{{use of undeclared type 'partial'}} expected-error{{expected type}} // expected-error@-1 2{{Only conformances to protocol types are supported by '_specialize' attribute}} public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) { } @_specialize(where T: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} @_specialize(where T: Int) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where T: S1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where T: C1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where Int: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-error{{Missing constraint for 'T' in '_specialize' attribute}} func funcWithForbiddenSpecializeRequirement<T>(_ t: T) { } @_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}} // expected-error@-2{{generic parameter 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}} // expected-warning@-3{{redundant constraint 'T' : '_Trivial'}} // expected-note@-4 3{{constraint 'T' : '_Trivial(32)' written here}} @_specialize(where T: _Trivial, T: _Trivial(64)) // expected-warning@-1{{redundant constraint 'T' : '_Trivial'}} // expected-note@-2 1{{constraint 'T' : '_Trivial(64)' written here}} @_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject) // expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}} // expected-note@-2 1{{constraint 'T' : '_NativeRefCountedObject' written here}} @_specialize(where Array<T> == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}} @_specialize(where T.Element == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}} public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int { return 55555 } public protocol Proto: class { } @_specialize(where T: _RefCountedObject) @_specialize(where T: _Trivial) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial' and '_NativeClass'}} @_specialize(where T: _Trivial(64)) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}} public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 { return 44444 } public struct S1 { } @_specialize(exported: false, where T == Int64) public func simpleGeneric<T>(t: T) -> T { return t } @_specialize(exported: true, where S: _Trivial(64)) // Check that any bitsize size is OK, not only powers of 8. @_specialize(where S: _Trivial(60)) @_specialize(exported: true, where S: _RefCountedObject) @inline(never) public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{ return 1 } @_specialize(exported: true, where S: _Trivial) @_specialize(exported: true, where S: _Trivial(64)) @_specialize(exported: true, where S: _Trivial(32)) @_specialize(exported: true, where S: _RefCountedObject) @_specialize(exported: true, where S: _NativeRefCountedObject) @_specialize(exported: true, where S: _Class) @_specialize(exported: true, where S: _NativeClass) @inline(never) public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{ return s } struct OuterStruct<S> { struct MyStruct<T> { @_specialize(where T == Int, U == Float) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-error{{Missing constraint for 'S' in '_specialize' attribute}} public func foo<U>(u : U) { } @_specialize(where T == Int, U == Float, S == Int) public func bar<U>(u : U) { } } } // Check _TrivialAtMostN constraints. @_specialize(exported: true, where S: _TrivialAtMost(64)) @inline(never) public func copy2<S>(_ t: S, s: inout S) -> S where S: P{ return s } // Check missing alignment. @_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}} // Check non-numeric size. @_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}} // Check non-numeric alignment. @_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}} @inline(never) public func copy3<S>(_ s: S) -> S { return s } public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}} } // rdar://problem/29333056 public protocol P1 { associatedtype DP1 associatedtype DP11 } public protocol P2 { associatedtype DP2 : P1 } public struct H<T> { } public struct MyStruct3 : P1 { public typealias DP1 = Int public typealias DP11 = H<Int> } public struct MyStruct4 : P2 { public typealias DP2 = MyStruct3 } @_specialize(where T==MyStruct4) public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> { }
5c2e0e71fa4c5cdb949399c83a445926
50.13879
386
0.699443
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/506-strings-7.swift
apache-2.0
4
import assert; (int r) iid (int x) { r = x; } (float r) fid (float x) { r = x; } (string r) sid (string x) { r = x; } main { assertEqual(1234, toint("1234"), "toint"); assertEqual(-3.142, tofloat("-3.142"), "tofloat"); assert("3.142" == fromfloat(3.142), "fromfloat"); assert("4321" == fromint(4321), "fromint"); assertEqual(1234, toint(sid("1234")), "toint"); assertEqual(-3.142, tofloat(sid("-3.142")), "tofloat"); assert("3.142" == fromfloat(fid(3.142)), "fromfloat"); assert("4321" == fromint(iid(4321)), "fromint"); string a = sid("1234"); string b = sid("-3.142"); float c = fid(3.142); int d = iid(4321); wait(a,b,c,d) { assertEqual(1234, toint(a), "toint"); assertEqual(-3.142, tofloat(b), "tofloat"); assert("3.142" == fromfloat(c), "fromfloat"); assert("4321" == fromint(d), "fromint"); } }
c92c7cf04b42af58c43920639b3f87e6
22.333333
59
0.53956
false
false
false
false
gowansg/firefox-ios
refs/heads/master
StorageTests/TestTableTable.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import XCTest class TestSchemaTable: XCTestCase { // This is a very basic test. Adds an entry. Retrieves it, and then clears the database func testTable() { let files = MockFiles() var db = BrowserDB(files: files) // Test creating a table var testTable = getCreateTable() db.createOrUpdate(testTable) // Now make sure the item is in the table-table var err: NSError? = nil let table = SchemaTable<TableInfo>() var cursor = db.query(&err, callback: { (connection, err) -> Cursor in return table.query(connection, options: QueryOptions(filter: testTable.name)) }) verifyTable(cursor, table: testTable) // We have to close this cursor to ensure we don't get results from a sqlite memory cache below when // we requery the table. cursor.close() // Now test updating the table testTable = getUpgradeTable() db.createOrUpdate(testTable) cursor = db.query(&err, callback: { (connection, err) -> Cursor in return table.query(connection, options: QueryOptions(filter: testTable.name)) }) verifyTable(cursor, table: testTable) // We have to close this cursor to ensure we don't get results from a sqlite memory cache below when // we requery the table. cursor.close() // Now try updating it again to the same version. This shouldn't call create or upgrade testTable = getNoOpTable() db.createOrUpdate(testTable) // Cleanup files.remove("browser.db") } // Helper for verifying that the data in a cursor matches whats in a table private func verifyTable(cursor: Cursor, table: TestTable) { XCTAssertEqual(cursor.count, 1, "Cursor is the right size") var data = cursor[0] as? TableInfoWrapper XCTAssertNotNil(data, "Found an object of the right type") XCTAssertEqual(data!.name, table.name, "Table info has the right name") XCTAssertEqual(data!.version, table.version, "Table info has the right version") } // A test class for fake table creation/upgrades class TestTable : Table { var name: String { return "testName" } var _version: Int = -1 var version: Int { return _version } typealias Type = Int // Called if the table is created let createCallback: () -> Bool // Called if the table is upgraded let updateCallback: (from: Int, to: Int) -> Bool let dropCallback: (() -> Void)? init(version: Int, createCallback: () -> Bool, updateCallback: (from: Int, to: Int) -> Bool, dropCallback: (() -> Void)? = nil) { self._version = version self.createCallback = createCallback self.updateCallback = updateCallback self.dropCallback = dropCallback } func exists(db: SQLiteDBConnection) -> Bool { let res = db.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name=?", factory: StringFactory, withArgs: [name]) return res.count > 0 } func drop(db: SQLiteDBConnection) -> Bool { if let dropCallback = dropCallback { dropCallback() } let sqlStr = "DROP TABLE IF EXISTS \(name)" let err = db.executeChange(sqlStr, withArgs: []) return err == nil } func create(db: SQLiteDBConnection, version: Int) -> Bool { // BrowserDB uses a different query to determine if a table exists, so we need to ensure it actually happens db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (ID INTEGER PRIMARY KEY AUTOINCREMENT)") return createCallback() } func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool { return updateCallback(from: from, to: to) } // These are all no-ops for testing func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return -1 } func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor { return Cursor(status: .Failure, msg: "Shouldn't hit this") } } // This function will create a table with appropriate callbacks set. Pass "create" if you expect the table to // be created. Pass "update" if it should be updated. Pass anythign else if neither callback should be called. func getCreateTable() -> TestTable { let t = TestTable(version: 1, createCallback: { _ -> Bool in XCTAssert(true, "Should have created table") return true }, updateCallback: { (from, to) -> Bool in XCTFail("Should not try to update table") return false }) return t } func getUpgradeTable() -> TestTable { var upgraded = false var dropped = false let t = TestTable(version: 2, createCallback: { _ -> Bool in XCTAssertTrue(dropped, "Create should be called after upgrade attempt") return true }, updateCallback: { (from, to) -> Bool in XCTAssert(true, "Should try to update table") XCTAssertEqual(from, 1, "From is correct") XCTAssertEqual(to, 2, "To is correct") // We'll return false here. The db will take that as a sign to drop and recreate our table. upgraded = true return false }, dropCallback: { () -> Void in XCTAssertTrue(upgraded, "Should try to drop table") dropped = true }) return t } func getNoOpTable() -> TestTable { let t = TestTable(version: 2, createCallback: { _ -> Bool in XCTFail("Should not try to create table") return false }, updateCallback: { (from, to) -> Bool in XCTFail("Should not try to update table") return false }) return t } }
8686d84b7c52dfc48f56f84cc6e13ae1
40.038217
145
0.604842
false
true
false
false
austinzheng/swift
refs/heads/master
stdlib/public/core/ContiguouslyStored.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// @usableFromInline internal protocol _HasContiguousBytes { func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R var _providesContiguousBytesNoCopy: Bool { get } } extension _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return true } } } extension Array: _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { #if _runtime(_ObjC) return _buffer._isNative #else return true #endif } } } extension ContiguousArray: _HasContiguousBytes {} extension UnsafeBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeMutableBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress._unsafelyUnwrappedUnchecked) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(self) } } extension UnsafeMutableRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } extension String: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._guts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(self._guts.isFastUTF8) { return try self._guts.withFastUTF8 { try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } } extension Substring: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._wholeGuts.isFastUTF8 } } @inlinable @inline(__always) internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { if _fastPath(_wholeGuts.isFastUTF8) { return try _wholeGuts.withFastUTF8(range: self._offsetRange) { return try body($0) } } return try ContiguousArray(self.utf8).withUnsafeBufferPointer { try body($0) } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self._withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } }
bbbcd079d916d98a6d2db12967bd31ad
28.816794
80
0.668203
false
false
false
false
alessioborraccino/reviews
refs/heads/master
reviews/Networking/ReviewAPI.swift
mit
1
// // ReviewAPI.swift // reviews // // Created by Alessio Borraccino on 14/05/16. // Copyright © 2016 Alessio Borraccino. All rights reserved. // import Alamofire import ObjectMapper import ReactiveCocoa import Result enum ReviewAPIError : ErrorType { case ParsingFailed case NetworkFailed case APIError(message: String) } protocol ReviewAPIType { func reviews(count count: Int, pageNumber: Int) -> SignalProducer<[Review],ReviewAPIError> func addReview(review: Review) -> SignalProducer<Int,ReviewAPIError> } class ReviewAPI : ReviewAPIType { //MARK : Constants private let host : String = "https://www.getyourguide.com" private let city : String = "berlin-l17" private let tour : String = "tempelhof-2-hour-airport-history-tour-berlin-airlift-more-t23776" // MARK: Dependencies /** Used to get maximum Review ID to give back. Would not be needed in a production environment */ private let reviewEntityManager : ReviewEntityManagerType init(reviewEntityManager: ReviewEntityManagerType = ReviewEntityManager()) { self.reviewEntityManager = reviewEntityManager } // MARK: Public Methods func reviews(count count: Int, pageNumber: Int) -> SignalProducer<[Review],ReviewAPIError> { return SignalProducer { observer, disposable in let request = ReviewAPIRequestBuilder.SearchReviews( city: self.city, tour: self.tour, count: count, page: pageNumber).URLRequest(host: self.host) Alamofire.request(request).validate().responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) in if let _ = response.result.error { observer.sendFailed(.NetworkFailed) } else if let success = Mapper<ReviewSuccessResponse>().map(response.result.value), reviews = success.reviews { observer.sendNext(reviews) } else if let error = Mapper<ReviewErrorResponse>().map(response.result.value), message = error.message { observer.sendFailed(.APIError(message: message)) } else { observer.sendFailed(.ParsingFailed) } observer.sendCompleted() }) } } func addReview(review: Review) -> SignalProducer<Int,ReviewAPIError> { return SignalProducer { [unowned self] observer, disposable in let _ = ReviewAPIRequestBuilder.AddReview( city: self.city, tour: self.tour, author: review.author, title: review.title, message: review.message, rating: review.rating, date: NSDate(), travelerType: review.travelerType ).URLRequest(host: self.host) //Should send request to backend, which will return the id for the review //Request should be for example: //https://www.getyourguide.com/berlin-l17/tempelhof-2-hour-airport-history-tour-berlin-airlift-more-t23776/addreview.json?author=alessio&title=super&message=super&rating=5&type=solo&date_of_review=date //Response would be as a json for example: // { // "review_id" : 456 // } let id = self.reviewEntityManager.maxReviewID() + 1 //Should be managed by backend observer.sendNext(id) observer.sendCompleted() } } }
6a51853c8389234a324b699cf7452733
34.089109
213
0.623483
false
false
false
false
muneebm/AsterockX
refs/heads/master
AsterockX/MissDistance.swift
mit
1
// // MissDistance.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/10/16. // Copyright © 2016 beenum. All rights reserved. // import Foundation import CoreData import NEOWS class MissDistance: NSManagedObject { @NSManaged var astronomical: String? @NSManaged var lunar: String? @NSManaged var kilometers: String? @NSManaged var miles: String? @NSManaged var closeApproach: CloseApproachData? override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(distance: Distance?, context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("MissDistance", inManagedObjectContext: context)! super.init(entity: entity, insertIntoManagedObjectContext: context) astronomical = distance?.astronomical lunar = distance?.lunar kilometers = distance?.kilometers miles = distance?.miles } }
fbe3567fe425443a74f018cb7d12bafb
28.378378
113
0.697332
false
false
false
false
ifyoudieincanada/above-average
refs/heads/master
above-average/ChangeSemesterViewController.swift
gpl-3.0
1
// // ChangeSemesterViewController.swift // above-average // // Created by Kyra Drake on 1/16/16. // Copyright © 2016 Kyra Drake. All rights reserved. // import UIKit class ChangeSemesterViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var changeSemesterTable: UITableView! func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return semesterArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.accessoryType = .DetailDisclosureButton cell.textLabel?.text = semesterArray[indexPath.row].term return cell } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { let index = indexPath.row //print(index) semesterArrayIndex = index } 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. } }
1b2216c39a8817c16d4c30f67812572d
30.785714
109
0.692135
false
false
false
false
Norod/Filterpedia
refs/heads/swift-3
Filterpedia/customFilters/VImageFilters.swift
gpl-3.0
1
// // VImageFilters.swift // Filterpedia // // Created by Simon Gladman on 21/04/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // These filters don't work nicely in background threads! Execute in dispatch_get_main_queue()! // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage import Accelerate // Circular Bokeh class CircularBokeh: CIFilter, VImageFilter { var inputImage: CIImage? var inputBlurRadius: CGFloat = 2 var inputBokehRadius: CGFloat = 15 { didSet { probe = nil } } var inputBokehBias: CGFloat = 0.25 { didSet { probe = nil } } private var probe: [UInt8]? override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Circular Bokeh", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputBokehRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 15, kCIAttributeDisplayName: "Bokeh Radius", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputBlurRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 2, kCIAttributeDisplayName: "Blur Radius", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar], "inputBokehBias": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.25, kCIAttributeDisplayName: "Bokeh Bias", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], ] } lazy var ciContext: CIContext = { return CIContext() }() override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let imageRef = ciContext.createCGImage( inputImage, from: inputImage.extent) var imageBuffer = vImage_Buffer() vImageBuffer_InitWithCGImage( &imageBuffer, &format, nil, imageRef!, UInt32(kvImageNoFlags)) let pixelBuffer = malloc((imageRef?.bytesPerRow)! * (imageRef?.height)!) var outBuffer = vImage_Buffer( data: pixelBuffer, height: UInt((imageRef?.height)!), width: UInt((imageRef?.width)!), rowBytes: (imageRef?.bytesPerRow)!) let probeValue = UInt8((1 - inputBokehBias) * 30) let radius = Int(inputBokehRadius) let diameter = (radius * 2) + 1 if probe == nil { probe = stride(from: 0, to: (diameter * diameter), by: 1).map { let x = Float(($0 % diameter) - radius) let y = Float(($0 / diameter) - radius) let r = Float(radius) let length = hypot(Float(x), Float(y)) / r if length <= 1 { let distanceToEdge = 1 - length return UInt8(distanceToEdge * Float(probeValue)) } return 255 } } vImageDilate_ARGB8888( &imageBuffer, &outBuffer, 0, 0, probe!, UInt(diameter), UInt(diameter), UInt32(kvImageEdgeExtend)) let outImage = CIImage(fromvImageBuffer: outBuffer) free(pixelBuffer) free(imageBuffer.data) return outImage!.applyingFilter( "CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: inputBlurRadius]) } } // Histogram Equalization class HistogramEqualization: CIFilter, VImageFilter { var inputImage: CIImage? override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Histogram Equalization", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage] ] } lazy var ciContext: CIContext = { return CIContext() }() override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let imageRef = ciContext.createCGImage( inputImage, from: inputImage.extent) var imageBuffer = vImage_Buffer() vImageBuffer_InitWithCGImage( &imageBuffer, &format, nil, imageRef!, UInt32(kvImageNoFlags)) let pixelBuffer = malloc((imageRef?.bytesPerRow)! * (imageRef?.height)!) var outBuffer = vImage_Buffer( data: pixelBuffer, height: UInt((imageRef?.height)!), width: UInt((imageRef?.width)!), rowBytes: (imageRef?.bytesPerRow)!) vImageEqualization_ARGB8888( &imageBuffer, &outBuffer, UInt32(kvImageNoFlags)) let outImage = CIImage(fromvImageBuffer: outBuffer) free(imageBuffer.data) free(pixelBuffer) return outImage! } } // MARK: EndsInContrastStretch class EndsInContrastStretch: CIFilter, VImageFilter { var inputImage: CIImage? var inputPercentLowRed: CGFloat = 0 var inputPercentLowGreen: CGFloat = 0 var inputPercentLowBlue: CGFloat = 0 var inputPercentHiRed: CGFloat = 0 var inputPercentHiGreen: CGFloat = 0 var inputPercentHiBlue: CGFloat = 0 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Ends In Contrast Stretch", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputPercentLowRed": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent Low Red", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], "inputPercentLowGreen": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent Low Green", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], "inputPercentLowBlue": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent Low Blue", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], "inputPercentHiRed": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent High Red", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], "inputPercentHiGreen": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent High Green", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], "inputPercentHiBlue": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0, kCIAttributeDisplayName: "Percent High Blue", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 49, kCIAttributeType: kCIAttributeTypeScalar], ] } lazy var ciContext: CIContext = { return CIContext() }() override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let imageRef = ciContext.createCGImage( inputImage, from: inputImage.extent) var imageBuffer = vImage_Buffer() vImageBuffer_InitWithCGImage( &imageBuffer, &format, nil, imageRef!, UInt32(kvImageNoFlags)) let pixelBuffer = malloc((imageRef?.bytesPerRow)! * (imageRef?.height)!) var outBuffer = vImage_Buffer( data: pixelBuffer, height: UInt((imageRef?.height)!), width: UInt((imageRef?.width)!), rowBytes: (imageRef?.bytesPerRow)!) let low = [inputPercentLowRed, inputPercentLowGreen, inputPercentLowBlue, 0].map { return UInt32($0) } let hi = [inputPercentHiRed, inputPercentHiGreen, inputPercentHiBlue, 0].map { return UInt32($0) } vImageEndsInContrastStretch_ARGB8888( &imageBuffer, &outBuffer, low, hi, UInt32(kvImageNoFlags)) let outImage = CIImage(fromvImageBuffer: outBuffer) free(imageBuffer.data) free(pixelBuffer) return outImage! } } // MARK: Contrast Stretch class ContrastStretch: CIFilter, VImageFilter { var inputImage: CIImage? override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Contrast Stretch", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage] ] } lazy var ciContext: CIContext = { return CIContext() }() override var outputImage: CIImage? { guard let inputImage = inputImage else { return nil } let imageRef = ciContext.createCGImage( inputImage, from: inputImage.extent) var imageBuffer = vImage_Buffer() vImageBuffer_InitWithCGImage( &imageBuffer, &format, nil, imageRef!, UInt32(kvImageNoFlags)) let pixelBuffer = malloc((imageRef?.bytesPerRow)! * (imageRef?.height)!) var outBuffer = vImage_Buffer( data: pixelBuffer, height: UInt((imageRef?.height)!), width: UInt((imageRef?.width)!), rowBytes: (imageRef?.bytesPerRow)!) vImageContrastStretch_ARGB8888( &imageBuffer, &outBuffer, UInt32(kvImageNoFlags)) let outImage = CIImage(fromvImageBuffer: outBuffer) free(imageBuffer.data) free(pixelBuffer) return outImage! } } // MARK: HistogramSpecification class HistogramSpecification: CIFilter, VImageFilter { var inputImage: CIImage? var inputHistogramSource: CIImage? override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Histogram Specification", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputHistogramSource": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Histogram Source", kCIAttributeType: kCIAttributeTypeImage], ] } lazy var ciContext: CIContext = { return CIContext() }() override var outputImage: CIImage? { guard let inputImage = inputImage, let inputHistogramSource = inputHistogramSource else { return nil } let imageRef = ciContext.createCGImage( inputImage, from: inputImage.extent) var imageBuffer = vImageBufferFromCIImage(inputImage, ciContext: ciContext) var histogramSourceBuffer = vImageBufferFromCIImage(inputHistogramSource, ciContext: ciContext) let alpha = [UInt](repeating: 0, count: 256) let red = [UInt](repeating: 0, count: 256) let green = [UInt](repeating: 0, count: 256) let blue = [UInt](repeating: 0, count: 256) let alphaMutablePointer = UnsafeMutablePointer<vImagePixelCount>(mutating: alpha) as UnsafeMutablePointer<vImagePixelCount>? let redMutablePointer = UnsafeMutablePointer<vImagePixelCount>(mutating: red) as UnsafeMutablePointer<vImagePixelCount>? let greenMutablePointer = UnsafeMutablePointer<vImagePixelCount>(mutating: green) as UnsafeMutablePointer<vImagePixelCount>? let blueMutablePointer = UnsafeMutablePointer<vImagePixelCount>(mutating: blue) as UnsafeMutablePointer<vImagePixelCount>? let rgba = [redMutablePointer, greenMutablePointer, blueMutablePointer, alphaMutablePointer] let histogram = UnsafeMutablePointer<UnsafeMutablePointer<vImagePixelCount>?>(mutating: rgba) vImageHistogramCalculation_ARGB8888(&histogramSourceBuffer, histogram, UInt32(kvImageNoFlags)) let pixelBuffer = malloc((imageRef?.bytesPerRow)! * (imageRef?.height)!) var outBuffer = vImage_Buffer( data: pixelBuffer, height: UInt((imageRef?.height)!), width: UInt((imageRef?.width)!), rowBytes: (imageRef?.bytesPerRow)!) let alphaPointer = UnsafePointer<vImagePixelCount>?(alpha) let redPointer = UnsafePointer<vImagePixelCount>?(red) let greenPointer = UnsafePointer<vImagePixelCount>?(green) let bluePointer = UnsafePointer<vImagePixelCount>?(blue) let rgba2 = [redPointer, greenPointer, bluePointer, alphaPointer] let rgbaMutablePointer = UnsafeMutablePointer<UnsafePointer<vImagePixelCount>?>(mutating: rgba2) vImageHistogramSpecification_ARGB8888(&imageBuffer, &outBuffer, rgbaMutablePointer, UInt32(kvImageNoFlags)) let outImage = CIImage(fromvImageBuffer: outBuffer) free(imageBuffer.data) free(histogramSourceBuffer.data) free(pixelBuffer) return outImage! } } // MARK Support protocol VImageFilter { } let bitmapInfo:CGBitmapInfo = CGBitmapInfo( rawValue: CGImageAlphaInfo.last.rawValue) var format = vImage_CGImageFormat( bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .defaultIntent) func vImageBufferFromCIImage(_ ciImage: CIImage, ciContext: CIContext) -> vImage_Buffer { let imageRef = ciContext.createCGImage( ciImage, from: ciImage.extent) var buffer = vImage_Buffer() vImageBuffer_InitWithCGImage( &buffer, &format, nil, imageRef!, UInt32(kvImageNoFlags)) return buffer } extension CIImage { convenience init?(fromvImageBuffer: vImage_Buffer) { var mutableBuffer = fromvImageBuffer var error = vImage_Error() let cgImage = vImageCreateCGImageFromBuffer( &mutableBuffer, &format, nil, nil, UInt32(kvImageNoFlags), &error) self.init(cgImage: (cgImage?.takeRetainedValue())!) } }
32c2e0dd5317e7c21ad80176db68d197
30.162544
132
0.573421
false
false
false
false
FishMage/SmartSprinkler
refs/heads/master
SmartSprinkler_ios/SmartSprinkler_ios/LocationController.swift
apache-2.0
1
// // LocationController.swift // SmartSprinkler_ios // // Created by Richard Chen on 3/10/17. // Copyright © 2017 Richard Chen. All rights reserved. // import UIKit import MapKit import CoreLocation import Foundation class LocationController:UIViewController,CLLocationManagerDelegate,MKMapViewDelegate { @IBOutlet weak var txtZipcode: UITextField! @IBOutlet weak var btnSelectLocation: UIButton! @IBOutlet weak var cityName: UILabel! @IBOutlet weak var zipcode: UILabel! @IBOutlet weak var btnSearch: UIButton! @IBOutlet weak var LocMap: MKMapView! @IBOutlet weak var imgWeather: UIImageView! //Map View - Automatically drop pin let locationManager = CLLocationManager() //define alerts let alert = UIAlertController(title: "Location", message: "Madison, WI, 53715", preferredStyle: UIAlertControllerStyle.alert) let alertSearch = UIAlertController(title: "Warning", message: "Enter your City or Zipcode", preferredStyle: UIAlertControllerStyle.alert) let alertConfirmInfo = UIAlertController(title: "City", message: "Madison, WI, 53715", preferredStyle: UIAlertControllerStyle.alert) //Weather services private let apiKey = "6638a13657b81ecbe08a47749ecfa9b7" override func viewDidLoad() { super.viewDidLoad() txtZipcode.placeholder = "zipcode" //self.txtCityName.placeholder = "city name" imgWeather.isHidden = true btnSelectLocation.isEnabled = false locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if #available(iOS 8.0, *) { locationManager.requestAlwaysAuthorization() } else { // Fallback on earlier versions } locationManager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last! as CLLocation let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) //set region on the map self.LocMap.setRegion(region, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //Dispose of any resources that can be recreated. } func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "locationToController") { let svc = segue!.destination as! FirstViewController svc.passedZip = "53715" } } @IBAction func btnSearchOnClick(_ sender: Any) { if txtZipcode.text != ""{ let zipCode = txtZipcode.text let geocoder = CLGeocoder() geocoder.geocodeAddressString(zipCode!) { (placemarks, error) -> Void in // Placemarks is an optional array of CLPlacemarks, first item in array is best guess of Address if let placemark = placemarks?[0] { if let city = placemark.addressDictionary!["City"] as? String! { print(city) self.cityName.text = city self.zipcode.text = self.txtZipcode.text self.imgWeather.isHidden = false self.btnSelectLocation.isEnabled = true self.btnSelectLocation.backgroundColor = #colorLiteral(red: 0.4767096639, green: 0.7372747064, blue: 0.09030196816, alpha: 1) self.view.endEditing(true) //Pass zipcode between viewControllers Shared.shared.zipcode = self.zipcode.text } } } } else if txtZipcode.text == ""{ alertSearch.addAction(UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default, handler: nil)) self.present(alertSearch, animated: true, completion: nil) //alertSearch.Action } } @IBAction func btnSelectLocationOnClick(_ sender: Any) { // self.performSegue(withIdentifier: "locationToController", sender: self) } }
c17b4c3403220a58e26874704010e684
38.544643
151
0.631971
false
false
false
false
flexih/Cafe
refs/heads/master
coffee/City.swift
mit
1
// // City.swift // coffee // // Created by flexih on 1/9/16. // Copyright © 2016 flexih. All rights reserved. // import Foundation struct City { let name: String let cafes: [Cafe] init(dict: [String: AnyObject]) { name = dict["city"] as? String ?? "" var cafesArray = [Cafe]() if let cafeDicts = dict["cafes"] as? [[String: AnyObject]] { for cafeDict in cafeDicts { let cafe = Cafe(dict: cafeDict) cafesArray.append(cafe) } } cafes = cafesArray } func cafeWithName(_ name: String) -> Cafe? { return cafes.filter{$0.name == name}.first } } struct CityList { fileprivate struct Keys { static let selectedCityKey = "selectedCity" } let citys: [City] var cafes:[Cafe] { get { let possible = citys.filter{$0.name == selectedCity} if let city = possible.first { return city.cafes } return citys.first!.cafes } } var selectedCity: String! { didSet { UserDefaults.standard.set(selectedCity, forKey: Keys.selectedCityKey) } } func takenCity(_ name: String) -> String? { let city = citys.filter{name.hasPrefix($0.name)}.first return city?.name } func sameCity(_ name: String, other: String) -> Bool { if let name = takenCity(name), let other = takenCity(other) { return name == other } return false } func cityWithName(_ name: String) -> City? { return (citys.filter{$0.name == name}).first } static func readData(_ jsonData: Data) -> [City] { var citys = [City]() if let jsonWrapper = try? JSONSerialization.jsonObject(with: jsonData, options: []) { if let json = jsonWrapper as? [[String: AnyObject]] { for cityJson in json { let city = City(dict: cityJson) citys.append(city) } } } return citys } static func storeData(_ jsonData: Data?) { try? jsonData?.write(to: cachedDataURL, options: [.atomic]) } static var cachedDataURL: URL = { let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return URL(string: "cafes.json", relativeTo: documentURL)! } () init(jsonData: Data) { citys = CityList.readData(jsonData) selectedCity = UserDefaults.standard.object(forKey: Keys.selectedCityKey).map{$0 as! String} ?? citys.first!.name } init?(URL: Foundation.URL) { guard let jsonData = try? Data(contentsOf: URL) else { return nil } self.init(jsonData: jsonData) } fileprivate init() { citys = [] } static func defaultList() -> CityList { if let cityList = CityList(URL: cachedDataURL), !cityList.citys.isEmpty { return cityList } return CityList(URL: Bundle.main.url(forResource: "cafes", withExtension: "json")!)! } }
76f34bbaf6f8af2ac0d4015230dbd7bc
24.603175
121
0.540608
false
false
false
false
Natoto/HBFastTableViewCotroller
refs/heads/master
FastTableView_Swift/Class/HB_BaseTableViewCell.swift
mit
1
// // HB_TableViewCell.swift // FastTableView_Swift // // Created by zeno on 15/10/9. // Copyright © 2015年 nonato. All rights reserved. // import UIKit //@objc(HB_BaseTableViewCell) //自动转换的方法名 class HB_BaseTableViewCell: UITableViewCell { var indexPath:NSIndexPath? var selector:Selector? var delegate:AnyObject? var dictionary:[String:AnyObject]? var object:AnyObject? override required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setcelldictionary(dictionary:[String:AnyObject]?) { self.dictionary = dictionary; } func setcellobject(object:AnyObject?) { self.object = object } func setcelldelegate(delegate:AnyObject) { self.delegate = delegate } func setcellProfile(profile:String?){} func setcellTitle(title:String?){ if title != nil { self.textLabel?.text = title; } } func setcellObject(object:AnyObject?){ self.object = object; } func setcellTitleColor(color:String?){} func setcellValue(value:String?){} func setcellValue2(value:String?){} func setcellRightValue(value:String?){} func setcellplaceholder(placeholder:String?){ if placeholder != nil { } } func setcellArray(array:[AnyObject]){} func setinputAccessoryView(inputAccessoryView:String?){} // -(void)setinputView:(NSString *)inputView; // -(void)setcelldetailtitle:(NSString *)detailtitle; // -(void)setcellimageCornerRadius:(BOOL)CornerRadius; }
c0c1c861d54eeb566bab8cf3dafc2f27
26.546667
83
0.655373
false
false
false
false
makeandbuild/watchkit-activity-builder
refs/heads/master
ActivityBuilder WatchKit Extension/ActiveStepConfig.swift
apache-2.0
1
// // ActiveStepConfig.swift // ActivityBuilder // // Created by Lindsay Thurmond on 2/26/15. // Copyright (c) 2015 Make and Build. All rights reserved. // import WatchKit import WatchCoreDataProxy class ActiveStepConfig: NSObject { var index: Int = 0 var activeStep:Step? var steps:[Step] = [] init(index: Int, steps:[Step]) { super.init() self.index = index self.steps = steps if (self.steps.count > self.index) { activeStep = self.steps[self.index] } } func numSteps() ->Int { return steps.count } func isLastStep() -> Bool { return index >= numSteps() - 1 } func isFirstStep() -> Bool { return index == 0 } func isOnlyStep() -> Bool { return numSteps() == 1 } func nextStep() -> Step? { if index + 1 < numSteps() { return steps[index+1] } return nil } // func prevStep() -> Step? { // if index - 1 >= 0 { // return steps[index-1] // } // return nil // } }
4815059ba079e3527ed21127a83c4dc6
18.877193
59
0.503972
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
Floral/Pods/Kingfisher/Sources/Image/ImageProgressive.swift
apache-2.0
5
// // ImageProgressive.swift // Kingfisher // // Created by lixiang on 2019/5/10. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) public struct ImageProgressive { /// A default `ImageProgressive` could be used across. public static let `default` = ImageProgressive( isBlur: true, isFastestScan: true, scanInterval: 0 ) /// Whether to enable blur effect processing let isBlur: Bool /// Whether to enable the fastest scan let isFastestScan: Bool /// Minimum time interval for each scan let scanInterval: TimeInterval public init(isBlur: Bool, isFastestScan: Bool, scanInterval: TimeInterval) { self.isBlur = isBlur self.isFastestScan = isFastestScan self.scanInterval = scanInterval } } protocol ImageSettable: AnyObject { var image: Image? { get set } } final class ImageProgressiveProvider: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { update(data: task.mutableData, with: task.callbacks) } private let option: ImageProgressive private let refresh: (Image) -> Void private let decoder: ImageProgressiveDecoder private let queue = ImageProgressiveSerialQueue() init?(_ options: KingfisherParsedOptionsInfo, refresh: @escaping (Image) -> Void) { guard let option = options.progressiveJPEG else { return nil } self.option = option self.refresh = refresh self.decoder = ImageProgressiveDecoder( option, processingQueue: options.processingQueue ?? sharedProcessingQueue, creatingOptions: options.imageCreatingOptions ) } func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { guard !data.isEmpty else { return } queue.add(minimum: option.scanInterval) { completion in guard self.onShouldApply() else { self.queue.clean() completion() return } func decode(_ data: Data) { self.decoder.decode(data, with: callbacks) { image in defer { completion() } guard self.onShouldApply() else { return } guard let image = image else { return } self.refresh(image) } } if self.option.isFastestScan { decode(self.decoder.scanning(data) ?? Data()) } else { self.decoder.scanning(data).forEach { decode($0) } } } } } private final class ImageProgressiveDecoder { private let option: ImageProgressive private let processingQueue: CallbackQueue private let creatingOptions: ImageCreatingOptions private(set) var scannedCount = 0 private(set) var scannedIndex = -1 init(_ option: ImageProgressive, processingQueue: CallbackQueue, creatingOptions: ImageCreatingOptions) { self.option = option self.processingQueue = processingQueue self.creatingOptions = creatingOptions } func scanning(_ data: Data) -> [Data] { guard data.kf.contains(jpeg: .SOF2) else { return [] } guard scannedIndex + 1 < data.count else { return [] } var datas: [Data] = [] var index = scannedIndex + 1 var count = scannedCount while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { if count > 0 { datas.append(data[0 ..< index]) } count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return [] } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 else { return [] } return datas } func scanning(_ data: Data) -> Data? { guard data.kf.contains(jpeg: .SOF2) else { return nil } guard scannedIndex + 1 < data.count else { return nil } var index = scannedIndex + 1 var count = scannedCount var lastSOSIndex = 0 while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { lastSOSIndex = index count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return nil } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 && lastSOSIndex > 0 else { return nil } return data[0 ..< lastSOSIndex] } func decode(_ data: Data, with callbacks: [SessionDataTask.TaskCallback], completion: @escaping (Image?) -> Void) { guard data.kf.contains(jpeg: .SOF2) else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } func processing(_ data: Data) { let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: processingQueue ) processor.onImageProcessed.delegate(on: self) { (self, result) in guard let image = try? result.0.get() else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } CallbackQueue.mainCurrentOrAsync.execute { completion(image) } } processor.process() } // Blur partial images. let count = scannedCount if option.isBlur, count < 6 { processingQueue.execute { // Progressively reduce blur as we load more scans. let image = KingfisherWrapper<Image>.image( data: data, options: self.creatingOptions ) let radius = max(2, 14 - count * 4) let temp = image?.kf.blurred(withRadius: CGFloat(radius)) processing(temp?.kf.data(format: .JPEG) ?? data) } } else { processing(data) } } } private final class ImageProgressiveSerialQueue { typealias ClosureCallback = ((@escaping () -> Void)) -> Void private let queue: DispatchQueue = .init(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue") private var items: [DispatchWorkItem] = [] private var notify: (() -> Void)? private var lastTime: TimeInterval? var count: Int { return items.count } func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { let completion = { [weak self] in guard let self = self else { return } self.queue.async { [weak self] in guard let self = self else { return } guard !self.items.isEmpty else { return } self.items.removeFirst() if let next = self.items.first { self.queue.asyncAfter( deadline: .now() + interval, execute: next ) } else { self.lastTime = Date().timeIntervalSince1970 self.notify?() self.notify = nil } } } queue.async { [weak self] in guard let self = self else { return } let item = DispatchWorkItem { closure(completion) } if self.items.isEmpty { let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0) let delay = difference < interval ? interval - difference : 0 self.queue.asyncAfter(deadline: .now() + delay, execute: item) } self.items.append(item) } } func notify(_ closure: @escaping () -> Void) { self.notify = closure } func clean() { queue.async { [weak self] in guard let self = self else { return } self.items.forEach { $0.cancel() } self.items.removeAll() } } }
00fca70aa6fcf285a81678255ff667c4
33.453074
106
0.55852
false
false
false
false
okerivy/AlgorithmLeetCode
refs/heads/master
AlgorithmLeetCode/AlgorithmLeetCode/E-26-RemoveDuplicatesFromSortedArray.swift
mit
1
// // E-26-RemoveDuplicatesFromSortedArray.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/7. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/remove-duplicates-from-sorted-array import Foundation // MARK: - 题目名称: 26. Remove Duplicates from Sorted Array /* MARK: - 所属类别: 标签: Array, Two Pointers 相关题目: (E) Remove Element */ /* MARK: - 题目英文: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. */ /* MARK: - 题目翻译: 给定一个排好顺序的数组,删除重复的元素,这样每个元素只出现一次,并返回新数组的长度。 不要为另一个数组分配额外的空间,你必须使用常量的内存空间。 例如:给定输入数组 nums = [1,1,2], 你的函数应该返回长度 2 , 并且 nums 的前两个元素分别是1和 2。新数组 2 以后的元素是什么无关紧要。 */ /* MARK: - 解题思路: 1. 两个指针 在一个排序好的数组里面删除重复的元素。 首先我们需要知道,对于一个排好序的数组来说,A[N + 1] >= A[N],我们仍然使用两个游标i和j来处理,假设现在i = j + 1,如果A[i] == A[j],那么我们递增i,直到A[i] != A[j],这时候我们再设置A[j + 1] = A[i],同时递增i和j,重复上述过程直到遍历结束。 2. 由于给定的数组是排好顺序的,所以遍历数组的时候,只需要判断当前元素是否跟前一个元素相等。 如果相等,则需要从数组中将当前元素删除; 若不相等,则继续下一个循环,判断下一个元素。 */ /* MARK: - 复杂度分析: 遍历一次数组,时间复杂度 O(n), 空间复杂度 O(1). */ // MARK: - 代码: private class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { // 如果count < 2 肯定不会重复,直接返回 if nums.count < 2 { return nums.count } var j = 0 for i in 1..<nums.count { // 如果i 和 j 对应的元素相等, 那么就继续寻找,但是 j的位置不变 if nums[i] != nums[j] { // 如果找到这个不相等的元素, 那么就把把这个元素移动到 j的下一个位置. // 移动到j的下一个位置并不会覆盖其他元素 // 因为 如果 i>j+1 那么i和j中间的元素都是和j相同的,所以覆盖也没事 // 如果 i = j+1 ,那么就是 自己替换自己, 所以也不会有影响 j += 1 nums[j] = nums[i] } } // j是下标, j+1 才是元素的个数 return j + 1 } // 用swift方法,简单容易理解 func removeDuplicates2(_ nums: inout [Int]) -> Int { if nums.count < 2 { return nums.count } var index = 1 while index < nums.count { if nums[index] == nums[index-1] { // 直接用swift方法remove掉. nums.remove(at: index) } else { index += 1 } } return index } } // MARK: - 测试代码: func removeDuplicatesFromSortedArray() { var array = [1,2,3,4,4,5,6,6,6] print("改变前的数组 \(array)") let count = Solution().removeDuplicates(&array) print("改变后的的数组的长度为 \(count) \(array)") // [1,2,3,4,5,6] }
314c2c99d0cd381d0ca19b8cc62a54f2
20.139706
160
0.561043
false
false
false
false
AbelSu131/SimpleMemo
refs/heads/master
Memo/Memo/MemoListViewController.swift
mit
1
// // MemoListViewController.swift // EverMemo // // Created by  李俊 on 15/8/5. // Copyright (c) 2015年  李俊. All rights reserved. // import UIKit import CoreData import WatchConnectivity let reuseIdentifier = "Cell" let backColor = UIColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1) class MemoListViewController: MemoCollectionViewController, NSFetchedResultsControllerDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate { private lazy var searchBar = UISearchBar() let context = CoreDataStack.shardedCoredataStack.managedObjectContext! var fetchedResultsController: NSFetchedResultsController? private lazy var searchView = UIView() var isSearching: Bool = false var searchResults: [Memo] = [] var didSelectedSearchResultIndexPath: NSIndexPath? // 被选中的搜索结果的索引 var wcsession: AnyObject? private lazy var addItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addMemo") return item }() private lazy var settingItem: UIBarButtonItem = { let item = UIBarButtonItem(image: UIImage(named: "EverNoteIcon"), style: UIBarButtonItemStyle.Plain, target: self, action: "setting") return item }() private lazy var searchItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "search") return item }() /// 加载fetchedResultsController private func loadFetchedResultsController() -> NSFetchedResultsController { let request = NSFetchRequest(entityName: "Memo") let sortDescriptor = NSSortDescriptor(key: "changeDate", ascending: false) request.sortDescriptors = [sortDescriptor] let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) controller.delegate = self return controller } override init() { super.init() fetchedResultsController = loadFetchedResultsController() do{ try fetchedResultsController!.performFetch() }catch { print(error) } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fetchedResultsController = loadFetchedResultsController() do{ try fetchedResultsController!.performFetch() }catch { print(error) } } override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = backColor if #available(iOS 9.0, *) { wcsession = wcSession() } setNavigationBar() // Register cell classes self.collectionView!.registerClass(MemoCell.self, forCellWithReuseIdentifier: reuseIdentifier) check3DTouch() } // 3D Touch Preview private func check3DTouch(){ if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .Available { registerForPreviewingWithDelegate(self, sourceView: view) } } else { // Fallback on earlier versions } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if isSearching { searchBar.becomeFirstResponder() } if ENSession.sharedSession().isAuthenticated { uploadMemoToEvernote() } sharedDataToWatch() } private lazy var titleLabel: UILabel = { let label = UILabel() label.text = "便签" label.font = UIFont.systemFontOfSize(18) label.sizeToFit() return label }() private func setNavigationBar(){ navigationItem.titleView = titleLabel navigationItem.rightBarButtonItems = [addItem] settingItem.tintColor = ENSession.sharedSession().isAuthenticated ? UIColor(red: 23/255.0, green: 127/255.0, blue: 251/255.0, alpha: 1) : UIColor.grayColor() navigationItem.leftBarButtonItems = [settingItem, searchItem] } func setting(){ if ENSession.sharedSession().isAuthenticated { let alert = UIAlertController(title: "退出印象笔记?", message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "退出", style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in ENSession.sharedSession().unauthenticate() self.settingItem.tintColor = UIColor.grayColor() })) presentViewController(alert, animated: true, completion: nil) } else { ENSession.sharedSession().authenticateWithViewController(self, preferRegistration: false, completion: { (error: NSError?) -> Void in if error == nil { self.settingItem.tintColor = UIColor(red: 23/255.0, green: 127/255.0, blue: 251/255.0, alpha: 1) } }) } } /// 搜索 func search(){ navigationItem.rightBarButtonItems?.removeAll(keepCapacity: true) navigationItem.leftBarButtonItems?.removeAll(keepCapacity: true) searchBar.searchBarStyle = .Minimal searchBar.setShowsCancelButton(true, animated: true) searchBar.delegate = self searchBar.backgroundColor = backColor // 如果将searchView直接添加到navigationBar上, 但push到下一个界面时, searchView还在navigationBar上 // navigationController?.navigationBar.addSubview(searchView) navigationItem.titleView = searchView searchView.frame = navigationController!.navigationBar.bounds searchView.addSubview(searchBar) var margin: CGFloat! if deviceModel == "iPad" || deviceModel == "iPad Simulator" { margin = 30 }else { margin = 10 } searchBar.frame = CGRect(x: 0, y: 0, width: searchView.bounds.width - margin, height: searchView.bounds.height) searchBar.becomeFirstResponder() isSearching = true if !searchBar.text!.isEmpty { fetchSearchResults(searchBar.text!) } collectionView?.reloadData() } private func fetchSearchResults(searchText: String){ let request = NSFetchRequest(entityName: "Memo") request.predicate = NSPredicate(format: "text CONTAINS[cd] %@", searchText) let sortDescriptor = NSSortDescriptor(key: "changeDate", ascending: false) request.sortDescriptors = [sortDescriptor] var results: [AnyObject]? do { results = try CoreDataStack.shardedCoredataStack.managedObjectContext?.executeFetchRequest(request) }catch{ print(error) } if let resultmemos = results as? [Memo] { searchResults = resultmemos } } // MARK: searchBarDelegate func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { fetchSearchResults(searchText) collectionView?.reloadData() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchView.removeFromSuperview() setNavigationBar() isSearching = false searchResults.removeAll(keepCapacity: false) collectionView?.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } override func statusBarOrientationChange(notification: NSNotification) { super.statusBarOrientationChange(notification) searchBarCancelButtonClicked(searchBar) } func addMemo(){ let memoVC = MemoViewController() navigationController?.pushViewController(memoVC, animated: true) } // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (isSearching ? searchResults.count : fetchedResultsController!.fetchedObjects!.count) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MemoCell var memo: Memo! if isSearching { memo = searchResults[indexPath.row] }else{ memo = fetchedResultsController!.objectAtIndexPath(indexPath) as! Memo // 删除笔记的闭包 cell.deleteMemo = {(memo: Memo) -> () in let alert = UIAlertController(title: "删除便签", message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) // .Destructive 需要谨慎操作的工作,文字会自动设为红色 alert.addAction(UIAlertAction(title: "删除", style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in memo.deleteFromEvernote() CoreDataStack.shardedCoredataStack.managedObjectContext?.deleteObject(memo) CoreDataStack.shardedCoredataStack.saveContext() // if #available(iOS 9.0, *) { // self.deleteSearchableIndex("\(indexPath.row)") // } self.sharedDataToWatch() })) self.presentViewController(alert, animated: true, completion: nil) } } cell.memo = memo return cell } // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ searchBar.resignFirstResponder() var memo: Memo! if isSearching{ memo = searchResults[indexPath.row] didSelectedSearchResultIndexPath = indexPath }else{ memo = fetchedResultsController?.objectAtIndexPath(indexPath) as! Memo } let MemoView = MemoViewController() MemoView.memo = memo navigationController?.pushViewController(MemoView, animated: true) } // MARK: - NSFetchedResultsControllerDelegate func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { // 如果处于搜索状态, 内容更新了,就重新搜索,重新加载数据 if isSearching { fetchSearchResults(searchBar.text!) collectionView?.reloadData() return } switch(type){ case .Insert: collectionView!.insertItemsAtIndexPaths([newIndexPath!]) case .Update: collectionView?.reloadItemsAtIndexPaths([indexPath!]) case .Delete: collectionView?.deleteItemsAtIndexPaths([indexPath!]) case .Move: collectionView?.moveItemAtIndexPath(indexPath!, toIndexPath:newIndexPath!) collectionView?.reloadItemsAtIndexPaths([newIndexPath!]) } } // MARK: - 上传便签到印象笔记 private func uploadMemoToEvernote(){ // 取出所有没有上传的memo let predicate = NSPredicate(format: "isUpload == %@", false) let request = NSFetchRequest(entityName: "Memo") request.predicate = predicate var results: [AnyObject]? do { results = try CoreDataStack.shardedCoredataStack.managedObjectContext?.executeFetchRequest(request) }catch{ print(error) } if let unUploadMemos = results as? [Memo] { for unUploadMemo in unUploadMemos { let memo = unUploadMemo as Memo // 上传便签到印象笔记 memo.uploadToEvernote() } } } // MARK: - 分享数据给Apple Watch /// 分享数据给apple Watch private func sharedDataToWatch(){ let sharedDefaults = NSUserDefaults(suiteName: "group.likumb.com.Memo") var results = [[String: AnyObject]]() if fetchedResultsController?.fetchedObjects == nil { return } let count = fetchedResultsController!.fetchedObjects!.count > 10 ? 10 : fetchedResultsController!.fetchedObjects!.count for index in 0..<count { // let memo = fetchedResultsController!.fetchedObjects![index] as! Memo // var watchMemo = [String: AnyObject]() // watchMemo["text"] = memo.text // watchMemo["changeDate"] = memo.changeDate results.append(memoTransformToDictionary(index)) } // let sharedMemos = ["sharedMemos" : results] sharedDefaults?.setObject(results, forKey: "WatchMemo") sharedDefaults!.synchronize() if #available(iOS 9.0, *) { shareMessage(["sharedMemos" : results]) } else { // Fallback on earlier versions } } func memoTransformToDictionary(index: Int) -> [String : AnyObject]{ let memo = fetchedResultsController!.fetchedObjects![index] as! Memo var watchMemo = [String: AnyObject]() watchMemo["text"] = memo.text watchMemo["changeDate"] = memo.changeDate return watchMemo } }
5f23ff4c5d9e1d26e0c7f769736af27c
28.367387
211
0.577268
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/IRGen/sr6844.swift
apache-2.0
38
// RUN: %target-swift-frontend -emit-ir %s -import-objc-header %S/Inputs/sr6844.h | %FileCheck %s // REQUIRES: objc_interop import Foundation // CHECK-LABEL: @_PROTOCOL_INSTANCE_METHODS_MyJSONSerializing = {{.+}} @"\01L_selector_data(JSONKeyPathsByPropertyKey)" // CHECK: [[OBJC_PROPNAME:@.+]] = private unnamed_addr constant [{{.+}} x i8] c"JSONKeyPathsByPropertyKey\00" // CHECK: [[PROPKIND:@.+]] = private unnamed_addr constant [{{.+}} x i8] c"T@\22NSDictionary\22,N,R\00" // CHECK: @_PROTOCOL_PROPERTIES_MyJSONSerializing = // CHECK-SAME: [[OBJC_PROPNAME]] // CHECK-SAME: [[PROPKIND]] // CHECK-LABEL: @_PROTOCOL_INSTANCE_METHODS__TtP6sr684418MyJSONSerializing2_ = {{.+}} @"\01L_selector_data(JSONKeyPathsByPropertyKey2)" // CHECK: [[SWIFT_PROPNAME:@.+]] = private unnamed_addr constant [{{.+}} x i8] c"JSONKeyPathsByPropertyKey2\00" // CHECK: @_PROTOCOL_PROPERTIES__TtP6sr684418MyJSONSerializing2_ = // CHECK-SAME: [[SWIFT_PROPNAME]] // CHECK-SAME: [[PROPKIND]] @objc public protocol MyJSONSerializing2 { var JSONKeyPathsByPropertyKey2: [String: MyJSONKeyPath]? { get } } extension MyJSONAdapter { public func model<Model: MyJSONSerializing>(of _: Model.Type = Model.self) throws -> Model { return __model() as! Model } public func model<Model: MyJSONSerializing2>(of _: Model.Type = Model.self) throws -> Model { return __model() as! Model } }
318fcd40ad0d4e99487ac42b2381d33e
44.733333
135
0.702624
false
false
false
false
xcodeswift/xcproj
refs/heads/master
Tests/XcodeProjTests/Objects/SwiftPackage/XCSwiftPackageProductDependencyTests.swift
mit
1
import Foundation import XCTest @testable import XcodeProj final class XCSwiftPackageProductDependencyTests: XCTestCase { func test_init() throws { // Given let decoder = XcodeprojPropertyListDecoder() let encoder = PropertyListEncoder() let plist = ["reference": "reference", "productName": "xcodeproj", "package": "packageReference"] let data = try encoder.encode(plist) // When let got = try decoder.decode(XCSwiftPackageProductDependency.self, from: data) // Then XCTAssertEqual(got.productName, "xcodeproj") XCTAssertEqual(got.packageReference?.value, "packageReference") } func test_plistValues() throws { // Given let proj = PBXProj() let package = XCRemoteSwiftPackageReference(repositoryURL: "repository") let subject = XCSwiftPackageProductDependency(productName: "product", package: package) // When let got = try subject.plistKeyAndValue(proj: proj, reference: "reference") // Then XCTAssertEqual(got.value, .dictionary([ "isa": "XCSwiftPackageProductDependency", "productName": "product", "package": .string(.init(package.reference.value, comment: "XCRemoteSwiftPackageReference \"\(package.name ?? "")\"")), ])) } func test_equal() { // Given let package = XCRemoteSwiftPackageReference(repositoryURL: "repository") let first = XCSwiftPackageProductDependency(productName: "product", package: package) let second = XCSwiftPackageProductDependency(productName: "product", package: package) // Then XCTAssertEqual(first, second) } }
31979e1cd977f153ea3c62ce141d125a
35.132075
131
0.586945
false
true
false
false
bustosalex/productpal
refs/heads/master
productpal/ViewController.swift
mit
1
// // ViewController.swift // productpal // // Created by Francisco Mateo on 4/6/16. // Copyright © 2016 University of Wisconsin Parkisde. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Product Cell") as! CustomCell cell.itemName.text = "Cock" cell.itemImage!.image = UIImage(named: "canon") cell.returnDate.text = "5/25/16" cell.protectionDate.text = "5/25/17" cell.warranyDate.text = "12/25/16" return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
4d9e1777a5b0c3fb9d13af214031f724
25.545455
107
0.65839
false
false
false
false
CodaFi/swift
refs/heads/main
test/SILGen/protocol_extensions.swift
apache-2.0
13
// RUN: %target-swift-emit-silgen -module-name protocol_extensions -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s public protocol P1 { func reqP1a() subscript(i: Int) -> Int { get set } } struct Box { var number: Int } extension P1 { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions2P1PAAE6extP1a{{[_0-9a-zA-Z]*}}F : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): func extP1a() { // CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a : {{.*}} : $@convention(witness_method: P1) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method: P1) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () reqP1a() // CHECK: return } // CHECK-LABEL: sil [ossa] @$s19protocol_extensions2P1PAAE6extP1b{{[_0-9a-zA-Z]*}}F : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () { // CHECK: bb0([[SELF:%[0-9]+]] : $*Self): public func extP1b() { // CHECK: [[FN:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE6extP1a{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () // CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () extP1a() // CHECK: return } subscript(i: Int) -> Int { // modify can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance) get { return 0 } set {} } func callSubscript() -> Int { // But here we have to do a witness method call: // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions2P1PAAE13callSubscript{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Self): // CHECK: witness_method $Self, #P1.subscript!getter // CHECK: return return self[0] } static var staticReadOnlyProperty: Int { return 0 } static var staticReadWrite1: Int { get { return 0 } set { } } static var staticReadWrite2: Box { get { return Box(number: 0) } set { } } } // ---------------------------------------------------------------------------- // Using protocol extension members with concrete types // ---------------------------------------------------------------------------- class C : P1 { func reqP1a() { } } // (modify test from above) // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s19protocol_extensions1CCAA2P1A2aDPyS2iciMTW // CHECK: bb0(%0 : $Int, %1 : $*τ_0_0): // CHECK: function_ref @$s19protocol_extensions2P1PAAEyS2icig // CHECK: return class D : C { } struct S : P1 { func reqP1a() { } } struct G<T> : P1 { func reqP1a() { } } struct MetaHolder { var d: D.Type = D.self var s: S.Type = S.self } struct GenericMetaHolder<T> { var g: G<T>.Type = G<T>.self } func inout_func(_ n: inout Int) {} // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions5testD_2dd1dyAA10MetaHolderV_AA1DCmAHtF : $@convention(thin) (MetaHolder, @thick D.Type, @guaranteed D) -> () // CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : @guaranteed $D): func testD(_ m: MetaHolder, dd: D.Type, d: D) { // CHECK: [[D2:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[RESULT:%.*]] = project_box [[D2]] // CHECK: [[MATERIALIZED_BORROWED_D:%[0-9]+]] = alloc_stack $D // CHECK: store_borrow [[D]] to [[MATERIALIZED_BORROWED_D]] // CHECK: [[FN:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE11returnsSelf{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FN]]<D>([[RESULT]], [[MATERIALIZED_BORROWED_D]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK-NEXT: dealloc_stack [[MATERIALIZED_BORROWED_D]] var d2: D = d.returnsSelf() // CHECK: metatype $@thick D.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = D.staticReadOnlyProperty // CHECK: metatype $@thick D.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ D.staticReadWrite1 = 1 // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Int // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack D.staticReadWrite1 += 1 // CHECK: metatype $@thick D.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ D.staticReadWrite2 = Box(number: 2) // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack D.staticReadWrite2.number += 5 // CHECK: metatype $@thick D.Type // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&D.staticReadWrite2.number) // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = dd.staticReadOnlyProperty // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ dd.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack dd.staticReadWrite1 += 1 // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ dd.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack dd.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&dd.staticReadWrite2.number) // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = m.d.staticReadOnlyProperty // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ m.d.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack m.d.staticReadWrite1 += 1 // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ m.d.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack m.d.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&m.d.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions5testS_2ssyAA10MetaHolderV_AA1SVmtF func testS(_ m: MetaHolder, ss: S.Type) { // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = S.staticReadOnlyProperty // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ S.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack S.staticReadWrite1 += 1 // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ S.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack S.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&S.staticReadWrite2.number) // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = ss.staticReadOnlyProperty // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ ss.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack ss.staticReadWrite1 += 1 // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ ss.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack ss.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&ss.staticReadWrite2.number) // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = m.s.staticReadOnlyProperty // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ m.s.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack m.s.staticReadWrite1 += 1 // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ m.s.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack m.s.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick S.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&m.s.staticReadWrite2.number) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions5testG{{[_0-9a-zA-Z]*}}F func testG<T>(_ m: GenericMetaHolder<T>, gg: G<T>.Type) { // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = G<T>.staticReadOnlyProperty // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ G<T>.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack G<T>.staticReadWrite1 += 1 // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ G<T>.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack G<T>.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&G<T>.staticReadWrite2.number) // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = gg.staticReadOnlyProperty // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ gg.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack gg.staticReadWrite1 += 1 // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ gg.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack gg.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&gg.staticReadWrite2.number) // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ let _ = m.g.staticReadOnlyProperty // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ m.g.staticReadWrite1 = 1 // CHECK: alloc_stack $Int // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite1SivsZ // CHECK: dealloc_stack m.g.staticReadWrite1 += 1 // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ m.g.staticReadWrite2 = Box(number: 2) // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack m.g.staticReadWrite2.number += 5 // CHECK: alloc_stack $Box // CHECK: metatype $@thick G<T>.Type // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ // CHECK: store // CHECK: function_ref @$s19protocol_extensions10inout_funcyySizF // CHECK: load // CHECK: function_ref @$s19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ // CHECK: dealloc_stack inout_func(&m.g.staticReadWrite2.number) // CHECK: return } // ---------------------------------------------------------------------------- // Using protocol extension members with existentials // ---------------------------------------------------------------------------- extension P1 { func f1() { } subscript (i: Int64) -> Bool { get { return true } } var prop: Bool { get { return true } } func returnsSelf() -> Self { return self } var prop2: Bool { get { return true } set { } } subscript (b: Bool) -> Bool { get { return b } set { } } } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions17testExistentials1{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool, [[I:%[0-9]+]] : $Int64): func testExistentials1(_ p1: P1, b: Bool, i: Int64) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) // CHECK: [[F1:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE2f1{{[_0-9a-zA-Z]*}}F // CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> () p1.f1() // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAEySbs5Int64Vcig // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool // CHECK: store{{.*}} : $*Bool // CHECK: destroy_addr [[POPENED_COPY]] // CHECK: dealloc_stack [[POPENED_COPY]] var b2 = p1[i] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE4propSbvg // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool // CHECK: store{{.*}} : $*Bool // CHECK: dealloc_stack [[POPENED_COPY]] var b3 = p1.prop } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions17testExistentials2{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentials2(_ p1: P1) { // CHECK: [[P1A:%[0-9]+]] = alloc_box ${ var P1 } // CHECK: [[PB:%.*]] = project_box [[P1A]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[FN:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE11returnsSelf{{[_0-9a-zA-Z]*}}F // CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1 // CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0 var p1a: P1 = p1.returnsSelf() } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions23testExistentialsGetters{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%[0-9]+]] : $*P1): func testExistentialsGetters(_ p1: P1) { // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[FN:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE5prop2Sbvg // CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool let b: Bool = p1.prop2 // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] : // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAEyS2bcig // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool let b2: Bool = p1[b] } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions22testExistentialSetters{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool): func testExistentialSetters(_ p1: P1, b: Bool) { var p1 = p1 // CHECK: [[PBOX:%[0-9]+]] = alloc_box ${ var P1 } // CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]] // CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1 // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBP]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr mutable_access [[WRITE]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE5prop2Sbvs // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr p1.prop2 = b // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBP]] // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr mutable_access [[WRITE]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAEyS2bcis // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> () // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1 p1[b] = b // CHECK: return } struct HasAP1 { var p1: P1 var someP1: P1 { get { return p1 } set { p1 = newValue } } } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions29testLogicalExistentialSetters{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[HASP1:%[0-9]+]] : $*HasAP1, [[B:%[0-9]+]] : $Bool) func testLogicalExistentialSetters(_ hasAP1: HasAP1, _ b: Bool) { var hasAP1 = hasAP1 // CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box ${ var HasAP1 } // CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]] // CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1 // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBHASP1]] // CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1 // CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1 // CHECK-NEXT: copy_addr [[WRITE]] to [initialization] [[HASP1_COPY]] : $*HasAP1 // CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @$s19protocol_extensions6HasAP1V6someP1AA0F0_pvg : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], [[HASP1_COPY]]) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1 // CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr mutable_access [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1 // CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @$s19protocol_extensions2P1PAAE5prop2Sbvs : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> () // CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @$s19protocol_extensions6HasAP1V6someP1AA0F0_pvs : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[WRITE]]) : $@convention(method) (@in P1, @inout HasAP1) -> () // CHECK-NOT: deinit_existential_addr hasAP1.someP1.prop2 = b // CHECK: return } func plusOneP1() -> P1 {} // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions38test_open_existential_semantics_opaque{{[_0-9a-zA-Z]*}}F func test_open_existential_semantics_opaque(_ guaranteed: P1, immediate: P1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var P1 } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access %0 // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) guaranteed.f1() // -- Need a guaranteed copy because it's immutable // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: copy_addr [[READ]] to [initialization] [[IMMEDIATE:%.*]] : // CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_addr [[IMMEDIATE]] // CHECK: dealloc_stack [[IMMEDIATE]] immediate.f1() // CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1 // CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // -- Can consume the value from our own copy // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_addr [[PLUS_ONE]] // CHECK: dealloc_stack [[PLUS_ONE]] plusOneP1().f1() } protocol CP1: class {} extension CP1 { func f1() { } } func plusOneCP1() -> CP1 {} // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions37test_open_existential_semantics_class{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG0:%.*]] : @guaranteed $CP1, [[ARG1:%.*]] : @guaranteed $CP1): func test_open_existential_semantics_class(_ guaranteed: CP1, immediate: CP1) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var CP1 } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: copy_value [[ARG0]] // CHECK: [[VALUE:%.*]] = open_existential_ref [[ARG0]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_value [[VALUE]] // CHECK-NOT: destroy_value [[ARG0]] guaranteed.f1() // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[READ]] // CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[VALUE]] // CHECK-NOT: destroy_value [[IMMEDIATE]] immediate.f1() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1 // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[VALUE]] // CHECK-NOT: destroy_value [[PLUS_ONE]] plusOneCP1().f1() } // CHECK: } // end sil function '$s19protocol_extensions37test_open_existential_semantics_class{{[_0-9a-zA-Z]*}}F' protocol InitRequirement { init(c: C) } extension InitRequirement { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(d: D) { // CHECK: [[SELF_BOX:%.*]] = alloc_box // CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]] // CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]] // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator : {{.*}} : $@convention(witness_method: InitRequirement) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY_CAST]], [[SELF_TYPE]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG]] // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[SELF_BOX_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: destroy_value [[UNINIT_SELF]] // CHECK: return self.init(c: d) } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions15InitRequirementPAAE2d2xAA1DC_tcfC : $@convention(method) // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(d2: D) { // CHECK: [[SELF_BOX:%.*]] = alloc_box // CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]] // CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[DELEGATEE:%.*]] = function_ref @$s19protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC // CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY]], [[SELF_TYPE]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG]] // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[SELF_BOX_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: destroy_value [[UNINIT_SELF]] // CHECK: return self.init(d: d2) } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions15InitRequirementPAAE2c2xAA1CC_tcfC : $@convention(method) // CHECK: bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : @owned $C, [[SELF_TYPE:%.*]] : $@thick Self.Type): init(c2: C) { // CHECK: [[SELF_BOX:%.*]] = alloc_box // CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]] // CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self // CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thick Self.Type // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator // CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY]], [[SELF_TYPE]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG]] // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_BOX_ADDR]] // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: destroy_value [[UNINIT_SELF]] // CHECK: return self = Self(c: c2) } } protocol ClassInitRequirement: class { init(c: C) } extension ClassInitRequirement { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions20ClassInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC : $@convention(method) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]] // CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator : {{.*}} : $@convention(witness_method: ClassInitRequirement) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0 // CHECK: apply [[DELEGATEE]]<Self>([[ARG_COPY_CAST]], [[SELF_TYPE]]) // CHECK: end_borrow [[BORROWED_ARG]] // CHECK: } // end sil function '$s19protocol_extensions20ClassInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC' init(d: D) { self.init(c: d) } } @objc class OC {} @objc class OD: OC {} @objc protocol ObjCInitRequirement { init(c: OC, d: OC) } func foo(_ t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement { return t.init(c: OC(), d: OC()) } extension ObjCInitRequirement { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions19ObjCInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC : $@convention(method) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self // CHECK: bb0([[ARG:%.*]] : @owned $OD, [[SELF_TYPE:%.*]] : $@thick Self.Type): // CHECK: [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]] // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self // CHECK: [[BORROWED_ARG_1:%.*]] = begin_borrow [[ARG]] // CHECK: [[BORROWED_ARG_1_UPCAST:%.*]] = upcast [[BORROWED_ARG_1]] // CHECK: [[BORROWED_ARG_2:%.*]] = begin_borrow [[ARG]] // CHECK: [[BORROWED_ARG_2_UPCAST:%.*]] = upcast [[BORROWED_ARG_2]] // CHECK: [[WITNESS:%.*]] = objc_method [[SELF]] : $Self, #ObjCInitRequirement.init!initializer.foreign : {{.*}}, $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0 // CHECK: apply [[WITNESS]]<Self>([[BORROWED_ARG_1_UPCAST]], [[BORROWED_ARG_2_UPCAST]], [[SELF]]) // CHECK: end_borrow [[BORROWED_ARG_2]] // CHECK: end_borrow [[BORROWED_ARG_1]] // CHECK: } // end sil function '$s19protocol_extensions19ObjCInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC' init(d: OD) { self.init(c: d, d: d) } } // rdar://problem/21370992 - delegation from an initializer in a // protocol extension to an @objc initializer in a class. class ObjCInitClass { @objc required init() { } } protocol ProtoDelegatesToObjC { } extension ProtoDelegatesToObjC where Self : ObjCInitClass { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions20ProtoDelegatesToObjCPA2A0F10CInitClassC{{[_0-9a-zA-Z]*}}fC // CHECK: bb0([[STR:%[0-9]+]] : @owned $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : ObjCInitClass, τ_0_0 : ProtoDelegatesToObjC> { var τ_0_0 } <Self> // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[SELF_META_C:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick ObjCInitClass.Type // CHECK: [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_META_C]] : $@thick ObjCInitClass.Type, #ObjCInitClass.init!allocator // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_META_C]]) // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[PB_SELF_BOX]] : $*Self self.init() } } // Delegating from an initializer in a protocol extension where Self // has a superclass to a required initializer of that class. class RequiredInitClass { required init() { } } protocol ProtoDelegatesToRequired { } extension ProtoDelegatesToRequired where Self : RequiredInitClass { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions24ProtoDelegatesToRequiredPA2A0F9InitClassC{{[_0-9a-zA-Z]*}}fC // CHECK: bb0([[STR:%[0-9]+]] : @owned $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type): init(string: String) { // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : RequiredInitClass, τ_0_0 : ProtoDelegatesToRequired> { var τ_0_0 } <Self> // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type // CHECK: [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator : (RequiredInitClass.Type) -> () -> RequiredInitClass, $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass // CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self // CHECK: assign [[SELF_RESULT_AS_SELF]] to [[PB_SELF_BOX]] : $*Self self.init() } } // ---------------------------------------------------------------------------- // Default implementations via protocol extensions // ---------------------------------------------------------------------------- protocol P2 { associatedtype A func f1(_ a: A) func f2(_ a: A) var x: A { get } } extension P2 { // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions2P2PAAE2f1{{[_0-9a-zA-Z]*}}F // CHECK: witness_method $Self, #P2.f2 : // CHECK: function_ref @$s19protocol_extensions2P2PAAE2f3{{[_0-9a-zA-Z]*}}F // CHECK: return func f1(_ a: A) { f2(a) f3(a) } // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions2P2PAAE2f2{{[_0-9a-zA-Z]*}}F // CHECK: witness_method $Self, #P2.f1 : // CHECK: function_ref @$s19protocol_extensions2P2PAAE2f3{{[_0-9a-zA-Z]*}}F // CHECK: return func f2(_ a: A) { f1(a) f3(a) } func f3(_ a: A) {} // CHECK-LABEL: sil hidden [ossa] @$s19protocol_extensions2P2PAAE2f4{{[_0-9a-zA-Z]*}}F // CHECK: witness_method $Self, #P2.f1 : // CHECK: witness_method $Self, #P2.f2 : // CHECK: return func f4() { f1(x) f2(x) } }
bf67eefb2b665f06c90f5dbedfc00c5c
42.424917
277
0.643254
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/ChatsControllers/ChatLogPresenter.swift
gpl-3.0
1
// // ChatLogPresenter.swift // FalconMessenger // // Created by Roman Mizin on 9/20/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase let chatLogPresenter = ChatLogPresenter() class ChatLogPresenter: NSObject { fileprivate var chatLogController: ChatLogViewController? fileprivate var messagesFetcher: MessagesFetcher? // fileprivate func controller() -> UIViewController? { // guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return nil } // guard let tabBarController = appDelegate.tabBarController else { return nil } // // if DeviceType.isIPad { // return appDelegate.splitViewController // } // // switch CurrentTab.shared.index { // case 0: // let controller = tabBarController.contactsController // return controller // case 1: // let controller = tabBarController.chatsController // return controller // case 2: // let controller = tabBarController.settingsController // return controller // default: return nil // } // } fileprivate func deselectItem(controller: UIViewController) { guard DeviceType.isIPad else { return } guard let controller = controller as? UITableViewController else { return } if let indexPath = controller.tableView.indexPathForSelectedRow { controller.tableView.deselectRow(at: indexPath, animated: true) } } public func tryDeallocate(force: Bool = false) { chatLogController = nil messagesFetcher?.delegate = nil messagesFetcher = nil print("deallocate") } fileprivate var isChatLogAlreadyOpened = false public func open(_ conversation: Conversation, controller: UIViewController) { isChatLogAlreadyOpened = false chatLogController = ChatLogViewController() messagesFetcher = MessagesFetcher() messagesFetcher?.delegate = self let newMessagesReceived = (conversation.badge.value ?? 0) > 0 let isEnoughData = conversation.messages.count >= 3 if !newMessagesReceived && isEnoughData { let needUpdate = RealmKeychain.defaultRealm.object( ofType: Conversation.self, forPrimaryKey: conversation.chatID ?? "")?.shouldUpdateRealmRemotelyBeforeDisplaying.value if let needUpdate = needUpdate, needUpdate { try! RealmKeychain.defaultRealm.safeWrite { RealmKeychain.defaultRealm.object( ofType: Conversation.self, forPrimaryKey: conversation.chatID ?? "")?.shouldUpdateRealmRemotelyBeforeDisplaying.value = false } messagesFetcher?.loadMessagesData(for: conversation, controller: controller) } else { openChatLog(for: conversation, controller: controller) } print("loading from realm") } messagesFetcher?.loadMessagesData(for: conversation, controller: controller) } fileprivate func openChatLog(for conversation: Conversation, controller: UIViewController) { guard isChatLogAlreadyOpened == false else { return } isChatLogAlreadyOpened = true chatLogController?.hidesBottomBarWhenPushed = true chatLogController?.messagesFetcher = messagesFetcher chatLogController?.conversation = conversation chatLogController?.getMessages() chatLogController?.observeBlockChanges() chatLogController?.deleteAndExitDelegate = controller as? DeleteAndExitDelegate if let uid = Auth.auth().currentUser?.uid, conversation.chatParticipantsIDs.contains(uid) { chatLogController?.configureTitleViewWithOnlineStatus() } chatLogController?.messagesFetcher?.collectionDelegate = chatLogController guard let destination = chatLogController else { return } if DeviceType.isIPad { let navigationController = UINavigationController(rootViewController: destination) controller.showDetailViewController(navigationController, sender: self) } else { controller.navigationController?.pushViewController(destination, animated: true) } deselectItem(controller: controller) } } extension ChatLogPresenter: MessagesDelegate { func messages(shouldChangeMessageStatusToReadAt reference: DatabaseReference, controller: UIViewController) { print("shouldChangeMessageStatusToReadAt ") chatLogController?.updateMessageStatus(messageRef: reference) } func messages(shouldBeUpdatedTo messages: [Message], conversation: Conversation, controller: UIViewController) { print("shouldBeUpdatedTo in presenter") addMessagesToRealm(messages: messages, conversation: conversation, controller: controller) } fileprivate func addMessagesToRealm(messages: [Message], conversation: Conversation, controller: UIViewController) { guard messages.count > 0 else { openChatLog(for: conversation, controller: controller) return } autoreleasepool { guard !RealmKeychain.defaultRealm.isInWriteTransaction else { return } RealmKeychain.defaultRealm.beginWrite() for message in messages { if message.senderName == nil { message.senderName = RealmKeychain.defaultRealm.object(ofType: Message.self, forPrimaryKey: message.messageUID ?? "")?.senderName } if message.isCrooked.value == nil { message.isCrooked.value = RealmKeychain.defaultRealm.object(ofType: Message.self, forPrimaryKey: message.messageUID ?? "")?.isCrooked.value } if message.thumbnailImage == nil { message.thumbnailImage = RealmKeychain.defaultRealm.object(ofType: RealmImage.self, forPrimaryKey: (message.messageUID ?? "") + "thumbnail") } if message.localImage == nil { message.localImage = RealmKeychain.defaultRealm.object(ofType: RealmImage.self, forPrimaryKey: message.messageUID ?? "") } RealmKeychain.defaultRealm.create(Message.self, value: message, update: .modified) } try! RealmKeychain.defaultRealm.commitWrite() openChatLog(for: conversation, controller: controller) } } }
060b57e68e608fe93ac0a6baa8ae7ea4
35.944444
145
0.732999
false
false
false
false
msahins/myTV
refs/heads/master
SwiftRadio/PopUpMenuViewController.swift
mit
1
import UIKit class PopUpMenuViewController: UIViewController { @IBOutlet weak var popupView: UIView! @IBOutlet weak var backgroundView: UIImageView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) modalPresentationStyle = .Custom } //***************************************************************** // MARK: - ViewDidLoad //***************************************************************** override func viewDidLoad() { super.viewDidLoad() // Round corners popupView.layer.cornerRadius = 10 // Set background color to clear view.backgroundColor = UIColor.clearColor() // Add gesture recognizer to dismiss view when touched let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("closeButtonPressed")) backgroundView.userInteractionEnabled = true backgroundView.addGestureRecognizer(gestureRecognizer) } //***************************************************************** // MARK: - IBActions //***************************************************************** @IBAction func closeButtonPressed() { dismissViewControllerAnimated(true, completion: nil) } @IBAction func websiteButtonPressed(sender: UIButton) { // Use your own website URL here if let url = NSURL(string: "http://83colors.com/") { UIApplication.sharedApplication().openURL(url) } } }
3c3109b169619484d5d7f481f7f05eae
31.125
108
0.528228
false
false
false
false
Fluci/CPU-Spy
refs/heads/master
CPU Spy/lib/Icon/FSIcon.swift
mit
1
// // FSIcon.swift // CPU Spy // // Created by Felice Serena on 14.6.15. // Copyright (c) 2015 Serena. All rights reserved. // import Cocoa /** Implements general mechanisms an Icon class might find useful. */ public class FSIcon: Icon, IconDrawerDelegate { public var delegate: IconDelegate? public var drawer: IconDrawer { didSet { drawer.delegate = self } } // MARK: Methods init (aDrawer: IconDrawer = FSIconDrawer()) { drawer = aDrawer drawer.delegate = self } // MARK: delegate-sending /// informs delegate /// /// delegate decides, if redrawing should proceed internal func delegateWillRedraw() -> Bool { if let answer = self.delegate?.willRedraw(self) { return answer } return true } // MARK: delegate-receiving public func willRedraw(sender: IconDrawer) -> Bool { return delegateWillRedraw() } }
3453a78bd1564d6d5234e687e7e8daf3
18.836735
66
0.605967
false
false
false
false
3drobotics/SwiftIO
refs/heads/develop
TestApp/LogViewController.swift
mit
2
// // LogViewController.swift // SwiftIO // // Created by Jonathan Wight on 1/9/16. // Copyright © 2016 schwa.io. All rights reserved. // import Cocoa import SwiftIO class LogViewController: NSViewController { dynamic var logText: String = "" @IBOutlet var logTextView: NSTextView! override func viewDidLoad() { super.viewDidLoad() SwiftIO.logHandler = self.logHandler } func logHandler(subject: Any?) { dispatch_async(dispatch_get_main_queue()) { if let subject = subject { let message = String(subject) self.logText += message + "\n" } else { self.logText += "nil" + "\n" } self.logTextView.scrollToEndOfDocument(nil) } } }
16a841ca39a664e91e7375ca878d5831
19.615385
55
0.568408
false
false
false
false
erkekin/EERegression
refs/heads/master
EERegression/RegressionView.swift
gpl-2.0
1
// // RegressionView.swift // EERegression // // Created by Erk EKİN on 22/11/15. // Copyright © 2015 ekin. All rights reserved. // import UIKit class Node { var point:CGPoint! var layer:CAShapeLayer! init(point:CGPoint, layer:CAShapeLayer){ self.point = point self.layer = layer } } class RegressionView: UIView { var regressionDegree = 1 var nodes:[Node] = [] var reg = Regression() var modelLine:CAShapeLayer? @IBOutlet weak var label:UILabel! let gridWidth: CGFloat = 0.5 var columns: Int = 25 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.opaque = false; self.backgroundColor = UIColor.whiteColor() let tap = UITapGestureRecognizer(target: self, action: "tapped:") self.addGestureRecognizer(tap) let pan = UIPanGestureRecognizer(target: self, action: "tapped:") self.addGestureRecognizer(pan) let longTap = UILongPressGestureRecognizer(target: self, action: "removeAll") self.addGestureRecognizer(longTap) } @IBAction func changeDegree(sender: UIStepper) { regressionDegree = Int(sender.value) label.text = "\(regressionDegree). degree" if nodes.count == 0 {return} self.reg = self.regressionForValues(regressionDegree) self.drawModelWithReg(self.reg) } @IBAction func tapped(sender: UITapGestureRecognizer) { switch sender.state{ case .Began: label.text = "\(regressionDegree). degree" break case .Ended: label.text = "Draw with one or multiple fingers, long press to delete all" break case .Cancelled: label.text = "Draw with one or multiple fingers, long press to delete all" break case .Failed: label.text = "Draw with one or multiple fingers, long press to delete all" break case .Changed: let tapPositionOneFingerTap = sender.locationInView(self) let node = Node(point: tapPositionOneFingerTap, layer: self.drawPoint(tapPositionOneFingerTap, color: UIColor.redColor().CGColor)) self.nodes.append(node) self.layer.addSublayer(node.layer) self.reg = self.regressionForValues(regressionDegree) self.drawModelWithReg(self.reg) break default: break } } func removeAll(){ modelLine?.removeFromSuperlayer() for onelayer in nodes{ onelayer.layer.removeFromSuperlayer() } self.nodes = [] } func regressionForValues(degree: Int) -> Regression{ var X = matrix(columns: 1, rows: nodes.count) X.flat.grid = nodes.map({ (nodea) -> Double in return Double(nodea.point.x) }) var Y = matrix(columns: 1, rows: nodes.count) Y.flat.grid = nodes.map({ (nodea) -> Double in return Double(nodea.point.y) }) return Regression(X: X, Y: Y, degree: degree) } // MARK: Drawing func drawModelWithReg(reg: Regression){ modelLine?.removeFromSuperlayer() if reg.degree == 1 { modelLine = drawLinearModel(reg) }else{ modelLine = drawQuadraticModel(reg) } self.layer.addSublayer(self.modelLine!) } func drawQuadraticModel(withReg:Regression) -> CAShapeLayer { let width = Int(frame.width) let rwColor = UIColor.blueColor() let rwPath = UIBezierPath() let rwLayer = CAShapeLayer() rwLayer.lineWidth = 1.0 rwLayer.fillColor = UIColor.clearColor().CGColor rwLayer.strokeColor = rwColor.CGColor for i in 0..<width{ let value = Double(i) var X = matrix(columns: 1, rows: 1) X.flat.grid = [value] let predictedValue = withReg.predict(X).flat.grid.first let point = CGPointMake(CGFloat(value), CGFloat(predictedValue!)) if i == 0 { rwPath.moveToPoint(point) }else{ rwPath.addLineToPoint(point) } } rwLayer.path = rwPath.CGPath return rwLayer } func drawLinearModel(withReg:Regression) -> CAShapeLayer { let width = Double(frame.width) var axeStartX = matrix(columns: 1, rows: 1) axeStartX.flat.grid = [0] let axeStartY = withReg.predict(axeStartX).flat.grid.first var axeEndX = matrix(columns: 1, rows: 1) axeEndX.flat.grid = [width] let axeEndY = withReg.predict(axeEndX).flat.grid.first let axialPoints = (x: CGPointMake(0, CGFloat(axeStartY!)),y: CGPointMake(CGFloat(width), CGFloat(axeEndY!))) return lineBetweenPoints(axialPoints.x, p2: axialPoints.y) } func lineBetweenPoints(p1:CGPoint, p2: CGPoint) -> CAShapeLayer{ let rwColor = UIColor.blueColor() let rwPath = UIBezierPath() let rwLayer = CAShapeLayer() rwPath.moveToPoint(p1) rwPath.addLineToPoint(p2) rwPath.closePath() rwLayer.path = rwPath.CGPath rwLayer.lineWidth = 1.0 rwLayer.fillColor = rwColor.CGColor rwLayer.strokeColor = rwColor.CGColor return rwLayer } func drawPoint(point:CGPoint, color:CGColor) -> CAShapeLayer{ let layer = CAShapeLayer() layer.path = UIBezierPath(roundedRect: CGRect(x: point.x - 2.5, y: point.y - 2.5, width: 5, height: 5), cornerRadius: 2.5).CGPath layer.fillColor = color return layer } override func drawRect(rect: CGRect) { let context: CGContextRef = UIGraphicsGetCurrentContext()! CGContextSetLineWidth(context, gridWidth) CGContextSetStrokeColorWithColor(context, UIColor(red:0.73, green:0.84, blue:0.95, alpha:1).CGColor) // Calculate basic dimensions let columnWidth: CGFloat = self.frame.size.width / (CGFloat(self.columns) + 1.0) let rowHeight: CGFloat = columnWidth; let numberOfRows: Int = Int(self.frame.size.height)/Int(rowHeight); // --------------------------- // Drawing column lines // --------------------------- for i in 1...self.columns { let startPoint: CGPoint = CGPoint(x: columnWidth * CGFloat(i), y: 0.0) let endPoint: CGPoint = CGPoint(x: startPoint.x, y: self.frame.size.height) CGContextMoveToPoint(context, startPoint.x, startPoint.y); CGContextAddLineToPoint(context, endPoint.x, endPoint.y); CGContextStrokePath(context); } // --------------------------- // Drawing row lines // --------------------------- for j in 1...numberOfRows { let startPoint: CGPoint = CGPoint(x: 0.0, y: rowHeight * CGFloat(j)) let endPoint: CGPoint = CGPoint(x: self.frame.size.width, y: startPoint.y) CGContextMoveToPoint(context, startPoint.x, startPoint.y); CGContextAddLineToPoint(context, endPoint.x, endPoint.y); CGContextStrokePath(context); } } } // //// 3 //func setUpRWLayer() { // rwLayer.path = rwPath.CGPath // rwLayer.fillColor = rwColor.CGColor // rwLayer.fillRule = kCAFillRuleNonZero // rwLayer.lineCap = kCALineCapButt // rwLayer.lineDashPattern = nil // rwLayer.lineDashPhase = 0.0 // rwLayer.lineJoin = kCALineJoinMiter // rwLayer.lineWidth = 1.0 // rwLayer.miterLimit = 10.0 // rwLayer.strokeColor = rwColor.CGColor //}
4f6be11c358a4a6164be4bd5b47b2ef5
29.215328
142
0.554361
false
false
false
false
Raizlabs/ios-template
refs/heads/master
{{ cookiecutter.project_name | replace(' ', '') }}/app/Services/Utilities/RequestProtocol.swift
mit
1
// // RequestProtocol.swift // Services // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import Alamofire public protocol RequestProtocol: class { var isFinished: Bool { get } func cancel() @discardableResult func onCompletion(_ closure: @escaping () -> Void) -> Self } extension DataRequest: RequestProtocol { public var isFinished: Bool { return progress.isFinished } public func onCompletion(_ closure: @escaping () -> Void) -> Self { return response { _ in closure() } } } public class RequestBatch { private var completions = [() -> Void]() private var requests: [RequestProtocol] = [] public init() { } @discardableResult public func perform(_ requests: [RequestProtocol]) -> Self { self.requests = requests let group = DispatchGroup() requests.forEach { group.enter() $0.onCompletion { group.leave() } } group.notify(queue: .main) { self.completions.forEach { $0() } self.completions = [] self.requests = [] } return self } } extension RequestBatch: RequestProtocol { public var isFinished: Bool { return requests.allSatisfy { $0.isFinished } } public func cancel() { requests.forEach { $0.cancel() } } public func onCompletion(_ closure: @escaping () -> Void) -> Self { self.completions.append(closure) return self } }
2923c0b3b5a9687b5494d2a3431498c6
20.972973
91
0.579336
false
false
false
false
LearningSwift2/LearningApps
refs/heads/master
SimpleDatePicker/SimpleDatePicker/ViewController.swift
apache-2.0
1
// // ViewController.swift // SimpleDatePicker // // Created by Phil Wright on 12/6/15. // Copyright © 2015 Touchopia, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { let dateFormatter = NSDateFormatter() @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! @IBOutlet weak var dateLabel: UILabel! var datePickerIsHidden = false override func viewDidLoad() { super.viewDidLoad() // setup datePicker // note: datePickerMode must be set before minuteInterval datePicker.datePickerMode = .Time datePicker.minuteInterval = 15 // setup formatter dateFormatter.timeStyle = .ShortStyle } override func viewWillAppear(animated: Bool) { self.bottomConstraint.constant -= self.datePicker.frame.size.height datePickerIsHidden = true dateHasChanged() } @IBAction func chooseDate() { if datePickerIsHidden == true { showDatePicker() } else { hideDatePicker() } } @IBAction func dateHasChanged() { dateLabel.text = dateFormatter.stringFromDate(datePicker.date) } func showDatePicker() { if datePickerIsHidden == true { datePickerIsHidden = false UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { self.bottomConstraint.constant += self.datePicker.frame.size.height self.view.layoutIfNeeded() }, completion: nil) } } func hideDatePicker() { if datePickerIsHidden == false { datePickerIsHidden = true UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { self.bottomConstraint.constant -= self.datePicker.frame.size.height self.view.layoutIfNeeded() }, completion: nil) } } }
5776d76864487854e2fdc292a1de2b53
25.4625
93
0.591875
false
false
false
false
mibaldi/IOS_MIMO_APP
refs/heads/master
iosAPP/models/Recipe.swift
apache-2.0
1
// // Recipe.swift // iosAPP // // Created by mikel balduciel diaz on 17/2/16. // Copyright © 2016 mikel balduciel diaz. All rights reserved. // import Foundation enum FavoriteTypes: Int64{ case favorite = 1 case noFavorite = 0 } class Recipe : NSObject { var recipeId = Int64() var recipeIdServer = Int64() var name = String() var portions = Int64() var favorite : FavoriteTypes? = FavoriteTypes.noFavorite var author = String() var score = Int64() var photo = String() var measures = [MeasureIngredients]() var tasks = [Task]() static func createRecipe(recipe: Recipe) -> Recipe{ var recipeTMI: Recipe? var measuresArray = [MeasureIngredients]() do{ recipeTMI = recipe let tasks = try TaskDataHelper.findAllRecipe(recipe.recipeId)! as [Task] recipeTMI!.tasks = tasks let measures = try MeasureDataHelper.findAllRecipe(recipe.recipeId)! as [MeasureIngredients] for m in measures { var measure : MeasureIngredients measure = m measure.ingredient = try IngredientDataHelper.find(measure.ingredientId)! measuresArray.append(measure) } recipeTMI?.measures = measuresArray }catch _ { } return recipeTMI! } static func saveFavorite(recipe: Recipe) -> Bool { var correcto = true let recipeIns = recipe var measure : MeasureIngredients var RecipeId : Int64? recipeIns.favorite = FavoriteTypes.favorite do{ let r = try RecipeDataHelper.findIdServer((recipeIns.recipeIdServer)) if r == nil { RecipeId = try RecipeDataHelper.insert(recipe) }else { correcto = false } }catch _ { correcto = false print("error al crear receta favorita") } if correcto { var ingredient: Ingredient for m in (recipe.measures) { do { measure = m measure.recipeId = RecipeId! ingredient = measure.ingredient let i = try IngredientDataHelper.findIdServer(ingredient.ingredientIdServer) if i == nil { let IngredientId = try IngredientDataHelper.insert(ingredient) measure.ingredientId = IngredientId }else { measure.ingredientId = (i?.ingredientId)! } }catch _ { correcto = false print("error al crear ingrediente de receta") } if correcto { do { try MeasureDataHelper.insert(measure) }catch _ { correcto = false print("error al crear medida de ingrediente") } } } } if correcto { var _: Task for t in (recipe.tasks) { do{ t.recipeId = RecipeId! try TaskDataHelper.insert(t) } catch _ { print("error al crear la tarea") } } print("receta agregada") } return correcto } }
21badd8d1d056b01caaf3dfb496fd05f
29.931624
104
0.485627
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectHeaderCell.swift
apache-2.0
1
import Library import Prelude import UIKit public enum ProjectHeaderCellStyles { public enum Layout { public static let insets: CGFloat = Styles.grid(200) } } final class ProjectHeaderCell: UITableViewCell, ValueCell { // MARK: - Properties private lazy var titleTextLabel: UILabel = { UILabel(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.bindStyles() self.configureViews() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Styles override func bindStyles() { super.bindStyles() // The separatorInset removes the bottom separator line from the view _ = self |> baseTableViewCellStyle() |> \.separatorInset .~ .init( top: 0, left: 0, bottom: 0, right: self.bounds.size.width + ProjectHeaderCellStyles.Layout.insets ) _ = self.contentView |> \.layoutMargins .~ .init( topBottom: Styles.grid(3), leftRight: Styles.grid(3) ) _ = self.titleTextLabel |> titleLabelStyle } // MARK: - Configuration func configureWith(value: String) { _ = self.titleTextLabel |> \.text .~ value return } private func configureViews() { _ = (self.titleTextLabel, self.contentView) |> ksr_addSubviewToParent() |> ksr_constrainViewToMarginsInParent() } } // MARK: - Styles private let titleLabelStyle: LabelStyle = { view in view |> \.backgroundColor .~ .ksr_white |> \.font .~ UIFont.ksr_title1().bolded |> \.lineBreakMode .~ .byWordWrapping |> \.numberOfLines .~ 0 |> \.textColor .~ .ksr_support_700 }
81e174495777ce3b116f71eb01d153c1
21.719512
77
0.640365
false
false
false
false
shridharmalimca/Shridhar.github.io
refs/heads/master
iOS/Components/CustomTabBar/CustomTabBar/ExampleProvider.swift
apache-2.0
2
// // ExampleProvider.swift // ESTabBarControllerExample // // Created by lihao on 2017/2/9. // Copyright © 2017年 Vincent Li. All rights reserved. // import UIKit enum ExampleProvider { static func systemStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.tabBar.shadowImage = nil tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func mixtureStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func systemMoreStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = UITabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = UITabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = UITabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func customMoreStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = ESTabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = ESTabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = ESTabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func mixtureMoreStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() let v6 = ExampleViewController() let v7 = ExampleViewController() let v8 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v6.tabBarItem = UITabBarItem.init(title: "Message", image: UIImage(named: "message"), selectedImage: UIImage(named: "message_1")) v7.tabBarItem = ESTabBarItem.init(title: "Shop", image: UIImage(named: "shop"), selectedImage: UIImage(named: "shop_1")) v8.tabBarItem = UITabBarItem.init(title: "Cardboard", image: UIImage(named: "cardboard"), selectedImage: UIImage(named: "cardboard_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5, v6, v7, v8] return tabBarController } static func navigationWithTabbarStyle() -> ExampleNavigationController { let tabBarController = ExampleProvider.customStyle() let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func tabbarWithNavigationStyle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) let n1 = ExampleNavigationController.init(rootViewController: v1) let n2 = ExampleNavigationController.init(rootViewController: v2) let n3 = ExampleNavigationController.init(rootViewController: v3) let n4 = ExampleNavigationController.init(rootViewController: v4) let n5 = ExampleNavigationController.init(rootViewController: v5) v1.title = "Home" v2.title = "Find" v3.title = "Photo" v4.title = "List" v5.title = "Me" tabBarController.viewControllers = [n1, n2, n3, n4, n5] return tabBarController } static func customColorStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customBouncesStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customBackgroundColorStyle(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleBackgroundContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customHighlightableStyle() -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleHighlightableContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customIrregularityStyle(delegate: UITabBarControllerDelegate?) -> ExampleNavigationController { let tabBarController = ESTabBarController() tabBarController.delegate = delegate tabBarController.title = "Irregularity" tabBarController.tabBar.shadowImage = UIImage(named: "transparent") tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark") tabBarController.shouldHijackHandler = { tabbarController, viewController, index in if index == 2 { return true } return false } tabBarController.didHijackHandler = { [weak tabBarController] tabbarController, viewController, index in DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet) let takePhotoAction = UIAlertAction(title: "Take a photo", style: .default, handler: nil) alertController.addAction(takePhotoAction) let selectFromAlbumAction = UIAlertAction(title: "Select from album", style: .default, handler: nil) alertController.addAction(selectFromAlbumAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) tabBarController?.present(alertController, animated: true, completion: nil) } } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleIrregularityContentView(), title: nil, image: UIImage(named: "photo_verybig"), selectedImage: UIImage(named: "photo_verybig")) v4.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleIrregularityBasicContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customTipsStyle(delegate: UITabBarControllerDelegate?) -> ExampleNavigationController { let tabBarController = ESTabBarController() tabBarController.delegate = delegate tabBarController.title = "Irregularity" tabBarController.tabBar.shadowImage = UIImage(named: "transparent") tabBarController.tabBar.backgroundImage = UIImage(named: "background_dark") let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(ExampleTipsBasicContentView(), title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleTipsContentView(), title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func systemRemindStyle() -> UITabBarController { let tabBarController = UITabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = UITabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = UITabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = UITabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = UITabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) v1.tabBarItem.badgeValue = "New" v2.tabBarItem.badgeValue = "99+" v3.tabBarItem.badgeValue = "1" if let tabBarItem = v3.tabBarItem as? ESTabBarItem { tabBarItem.badgeColor = UIColor.blue } v4.tabBarItem.badgeValue = "" v5.tabBarItem.badgeValue = nil tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customRemindStyle() -> UITabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(title: "Home", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(title: "Find", image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(title: "Photo", image: UIImage(named: "photo"), selectedImage: UIImage(named: "photo_1")) v4.tabBarItem = ESTabBarItem.init(title: "Favor", image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(title: "Me", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) if let tabBarItem = v1.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "New" } if let tabBarItem = v2.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "99+" } if let tabBarItem = v3.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "1" tabBarItem.badgeColor = UIColor.blue } if let tabBarItem = v4.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = "" } if let tabBarItem = v5.tabBarItem as? ESTabBarItem { tabBarItem.badgeValue = nil } tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } static func customAnimateRemindStyle(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customAnimateRemindStyle2(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView2(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func customAnimateRemindStyle3(implies: Bool) -> ExampleNavigationController { let tabBarController = ESTabBarController() if let tabBar = tabBarController.tabBar as? ESTabBar { tabBar.itemCustomPositioning = .fillIncludeSeparator } let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3.init(specialWithAutoImplies: implies), title: nil, image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big_1")) v4.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleAnimateTipsContentView3(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] if let tabBarItem = v2.tabBarItem as? ESTabBarItem { DispatchQueue.main.asyncAfter(deadline: .now() + 2 ) { tabBarItem.badgeValue = "1" } } let navigationController = ExampleNavigationController.init(rootViewController: tabBarController) tabBarController.title = "Example" return navigationController } static func lottieSytle() -> ESTabBarController { let tabBarController = ESTabBarController() let v1 = ExampleViewController() let v2 = ExampleViewController() let v3 = ExampleViewController() let v4 = ExampleViewController() let v5 = ExampleViewController() v1.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1")) v2.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "find"), selectedImage: UIImage(named: "find_1")) v3.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateContentView(), title: nil, image: nil, selectedImage: nil) v4.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "favor"), selectedImage: UIImage(named: "favor_1")) v5.tabBarItem = ESTabBarItem.init(ExampleLottieAnimateBasicContentView(), title: nil, image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1")) tabBarController.viewControllers = [v1, v2, v3, v4, v5] return tabBarController } }
c0881d698532687d7fe46a74b3d2dacb
58.129344
205
0.675014
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/TXTReader/BookDetail/Views/QSBatteryView.swift
mit
1
// // QSBatteryView.swift // zhuishushenqi // // Created by Nory Cao on 2017/4/19. // Copyright © 2017年 QS. All rights reserved. // import UIKit class QSBatteryView: UIView { var batteryLevel:CGFloat = 1.0 { didSet{ setNeedsLayout() } } var batteryColor:UIColor = UIColor.darkGray { didSet { header.backgroundColor = batteryColor external.layer.borderColor = batteryColor.cgColor `internal`.backgroundColor = batteryColor } } private var `internal`:UIView! private var external:UIView! private var header:UIView! private var headerWidth:CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupSubviews(){ self.backgroundColor = UIColor.clear external = UIView() external.backgroundColor = UIColor.clear external.layer.borderColor = UIColor.darkGray.cgColor external.layer.borderWidth = 1 `internal` = UIView() `internal`.backgroundColor = UIColor.darkGray header = UIView() header.backgroundColor = UIColor.darkGray self.addSubview(external) self.addSubview(`internal`) self.addSubview(header) } override func layoutSubviews() { super.layoutSubviews() let spaceX:CGFloat = 2 let spaceY:CGFloat = 2 let headerHeight = self.bounds.height/2 let headerWidth = self.bounds.height/3 if batteryLevel < 0 { batteryLevel = 1.0 } let width = (self.bounds.width - 4 - headerWidth)*batteryLevel `internal`.frame = CGRect(x: spaceX, y: spaceY, width: width, height: self.bounds.height - 4) external.frame = CGRect(x: 0, y: 0, width: self.bounds.width - headerWidth, height: self.bounds.height) header.frame = CGRect(x: self.bounds.width - headerWidth, y: self.bounds.height/2 - headerHeight/2, width: headerWidth, height: headerHeight) } }
f8d4b260ed11c1f5e6a1006cde363470
27.792208
149
0.60848
false
false
false
false
toddkramer/AnimatedViewController
refs/heads/master
AnimatedViewController/AnimatedViewControllerPresenter.swift
mit
1
// // AnimatedViewControllerPresenter.swift // Copyright (c) 2014 Todd Kramer. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public enum Side { case Left case Right case Top case Bottom } public enum AnimationStyle { case ExpandFromCenter case Slide(dismissOpposite: Bool, side: Side) } public enum PresentationStyle { case Drawer(side: Side, phoneWantsFullScreen: Bool, screenRatio: Float) case FormSheet(horizontalRatio: Float, verticalRatio: Float, animationStyle: AnimationStyle) } public class AnimatedViewControllerPresenter: NSObject { let transitioningDelegate: UIViewControllerTransitioningDelegate let presentingViewController: UIViewController let presentedViewController: UIViewController convenience override public init() { self.init(presentingViewController: UIViewController(), presentedViewController: UIViewController()) } public init(presentingViewController: UIViewController, presentedViewController: UIViewController, style: PresentationStyle = .FormSheet(horizontalRatio: 0.6, verticalRatio: 0.6, animationStyle: .ExpandFromCenter)) { self.presentingViewController = presentingViewController self.presentedViewController = presentedViewController self.transitioningDelegate = AnimatedTransitioner(style: style) super.init() } public func presentAnimatedController() { presentedViewController.transitioningDelegate = transitioningDelegate presentingViewController.transitioningDelegate = transitioningDelegate presentedViewController.modalPresentationStyle = .Custom presentingViewController.presentViewController(presentedViewController, animated: true, completion: nil) } }
61c73dd8c946c925fa4471e9d0adf10d
41.074627
220
0.765874
false
false
false
false
tekezo/Karabiner-Elements
refs/heads/master
src/apps/EventViewer/src/EventQueue.swift
unlicense
1
import Cocoa private func callback(_ deviceId: UInt64, _ usagePage: Int32, _ usage: Int32, _ eventType: libkrbn_hid_value_event_type, _ context: UnsafeMutableRawPointer?) { let obj: EventQueue! = unsafeBitCast(context, to: EventQueue.self) DispatchQueue.main.async { [weak obj] in guard let obj = obj else { return } if !libkrbn_is_momentary_switch_event(usagePage, usage) { return } var buffer = [Int8](repeating: 0, count: 256) let entry = EventQueueEntry() // // entry.code // if UserSettings.shared.showHex { entry.code = String(format: "0x%02x,0x%02x", usagePage, usage) } else { entry.code = String(format: "%d,%d", usagePage, usage) } // // entry.name // libkrbn_get_momentary_switch_event_json_string(&buffer, buffer.count, usagePage, usage) let jsonString = String(cString: buffer) entry.name = jsonString // // modifierFlags // if libkrbn_is_modifier_flag(usagePage, usage) { libkrbn_get_modifier_flag_name(&buffer, buffer.count, usagePage, usage) let modifierFlagName = String(cString: buffer) if obj.modifierFlags[deviceId] == nil { obj.modifierFlags[deviceId] = Set() } if eventType == libkrbn_hid_value_event_type_key_down { obj.modifierFlags[deviceId]!.insert(modifierFlagName) } else { obj.modifierFlags[deviceId]!.remove(modifierFlagName) } } // // entry.eventType // switch eventType { case libkrbn_hid_value_event_type_key_down: entry.eventType = "down" case libkrbn_hid_value_event_type_key_up: entry.eventType = "up" case libkrbn_hid_value_event_type_single: break default: break } // // entry.misc // if let set = obj.modifierFlags[deviceId] { if set.count > 0 { let flags = set.sorted().joined(separator: ",") entry.misc = "flags \(flags)" } } // // EventQueue.queue // obj.append(entry) // // simpleModificationJsonString // libkrbn_get_simple_modification_json_string(&buffer, buffer.count, usagePage, usage) let simpleModificationJsonString = String(cString: buffer) if simpleModificationJsonString != "" { libkrbn_get_momentary_switch_event_usage_name(&buffer, buffer.count, usagePage, usage) let usageName = String(cString: buffer) obj.simpleModificationJsonString = simpleModificationJsonString obj.updateAddSimpleModificationButton("Add \(usageName) to Karabiner-Elements") } } } @objcMembers public class EventQueueEntry: NSObject { var eventType: String = "" var code: String = "" var name: String = "" var misc: String = "" } public class EventQueue: NSObject, NSTableViewDataSource { var queue: [EventQueueEntry] = [] let maxQueueCount = 256 var modifierFlags: [UInt64: Set<String>] = [:] var simpleModificationJsonString: String = "" @IBOutlet var view: NSTableView! @IBOutlet var addSimpleModificationButton: NSButton! deinit { libkrbn_disable_hid_value_monitor() } public func setup() { updateAddSimpleModificationButton(nil) let obj = unsafeBitCast(self, to: UnsafeMutableRawPointer.self) libkrbn_enable_hid_value_monitor(callback, obj) } public func observed() -> Bool { return libkrbn_hid_value_monitor_observed() } public func append(_ entry: EventQueueEntry) { queue.append(entry) if queue.count > maxQueueCount { queue.removeFirst() } refresh() } func refresh() { view.reloadData() view.scrollRowToVisible(queue.count - 1) } public func updateAddSimpleModificationButton(_ title: String?) { if title != nil { addSimpleModificationButton.title = title! addSimpleModificationButton.isHidden = false } else { addSimpleModificationButton.isHidden = true } } @IBAction func clear(_: NSButton) { queue.removeAll() updateAddSimpleModificationButton(nil) refresh() } @IBAction func copy(_: NSButton) { var string = "" queue.forEach { entry in let eventType = "type:\(entry.eventType)".padding(toLength: 20, withPad: " ", startingAt: 0) let code = "HID usage:\(entry.code)".padding(toLength: 20, withPad: " ", startingAt: 0) let name = "name:\(entry.name)".padding(toLength: 60, withPad: " ", startingAt: 0) let misc = "misc:\(entry.misc)" string.append("\(eventType) \(code) \(name) \(misc)\n") } if !string.isEmpty { let pboard = NSPasteboard.general pboard.clearContents() pboard.writeObjects([string as NSString]) } } @IBAction func addSimpleModification(_: NSButton) { guard let string = simpleModificationJsonString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return } guard let url = URL(string: "karabiner://karabiner/simple_modifications/new?json=\(string)") else { return } NSWorkspace.shared.open(url) } // // Mouse event handling // func modifierFlagsString(_ flags: NSEvent.ModifierFlags) -> String { var names: [String] = [] if flags.contains(.capsLock) { names.append("caps") } if flags.contains(.shift) { names.append("shift") } if flags.contains(.control) { names.append("ctrl") } if flags.contains(.option) { names.append("opt") } if flags.contains(.command) { names.append("cmd") } if flags.contains(.numericPad) { names.append("numpad") } if flags.contains(.help) { names.append("help") } if flags.contains(.function) { names.append("fn") } return names.joined(separator: ",") } func pushMouseEvent(event: NSEvent, eventType: String) { let entry = EventQueueEntry() entry.eventType = eventType entry.code = String(event.buttonNumber) entry.name = "button\(event.buttonNumber + 1)" entry.misc = String(format: "{x:%d,y:%d} click_count:%d", Int(event.locationInWindow.x), Int(event.locationInWindow.y), Int(event.clickCount)) let flags = modifierFlagsString(event.modifierFlags) if !flags.isEmpty { entry.misc.append(" flags:\(flags)") } append(entry) } func pushScrollWheelEvent(event: NSEvent, eventType: String) { let entry = EventQueueEntry() entry.eventType = eventType entry.misc = String(format: "dx:%.03f dy:%.03f dz:%.03f", event.deltaX, event.deltaY, event.deltaZ) append(entry) } func pushMouseEvent(_ event: NSEvent) { switch event.type { case .leftMouseDown, .rightMouseDown, .otherMouseDown, .leftMouseUp, .rightMouseUp, .otherMouseUp: // Do nothing break case .leftMouseDragged, .rightMouseDragged, .otherMouseDragged: pushMouseEvent(event: event, eventType: "mouse_dragged") case .scrollWheel: pushScrollWheelEvent(event: event, eventType: "scroll_wheel") default: // Do nothing break } } // // NSTableViewDataSource // public func numberOfRows(in _: NSTableView) -> Int { return queue.count } public func tableView(_: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { guard let identifier = tableColumn?.identifier else { return nil } return queue[row].value(forKey: identifier.rawValue) } }
9dd8cae37552ca791a75dfe2a87a1bd9
28.077703
134
0.556524
false
false
false
false
apple/swift-docc-symbolkit
refs/heads/main
Tests/SymbolKitTests/SymbolGraph/Relationship/HashableTests.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ import Foundation import XCTest import SymbolKit class HashableTests: XCTestCase { /// Test hasing works as expected if Mixins conform to Hashable func testHashingWithHashableMixins() throws { var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins[SymbolGraph.Relationship.SourceOrigin.mixinKey] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.1.origin", displayName: "a.1.origin") var a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins[SymbolGraph.Relationship.SourceOrigin.mixinKey] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.2.origin", displayName: "a.2.origin") XCTAssertEqual(Set([a1, a2]).count, 2) } /// Check that Mixins that do not implement Hashable are ignored, so that /// they don't render the Hashable implementation of Relationship useless. func testHashingWithNonHashableMixins() throws { var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins[NotHashableMixin<String>.mixinKey] = NotHashableMixin(value: "a.1.value") var a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins[NotHashableMixin<String>.mixinKey] = NotHashableMixin(value: "a.2.value") XCTAssertEqual(Set([a1, a2]).count, 1) } /// Check that Hashable Mixins without any Mixin for the respective `mixinKey` on the other /// relationship fail equality. func testHashingWithMissingEquatableMixin() throws { var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins["1"] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.1.origin", displayName: "a.1.origin") var a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins["2"] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.2.origin", displayName: "a.2.origin") XCTAssertEqual(Set([a1, a2]).count, 2) } /// Check that Non-Hashable Mixins without any Mixin for the respective `mixinKey` on the other /// relationship do not fail equality. func testHashingWithMissingNonEquatableMixin() throws { var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins["1"] = NotHashableMixin(value: 1) let a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) XCTAssertEqual(Set([a1, a2]).count, 1) } /// Check that Mixins of different type that both do not implement Hashable /// are considered equal. func testHashingWithDifferentTypeNonHashableMixins() throws { var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins[NotHashableMixin<String>.mixinKey] = NotHashableMixin(value: "a.1.value") var a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins[NotHashableMixin<Int>.mixinKey] = NotHashableMixin(value: 2) XCTAssertEqual(Set([a1, a2]).count, 1) } /// Check that Mixins of different type where one does implement Hashable /// are considered unequal. func testHashingWithDifferentTypeOneHashableMixinOneNonHashable() throws { // in this first test, equality should return false based on the count of equatable mixins var a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins["a"] = NotHashableMixin(value: "a.1.value") var a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins["a"] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.2.origin", displayName: "a.2.origin") XCTAssertEqual(Set([a1, a2]).count, 2) // This test is interesting because the equality implementation of relationship // only iterates over the `lhs` mixins. Thus, depending on what relationship comes out // as the `lhs`, the equality might fail at different times (though it will always fail). // In this example, if `a1` is `lhs`, the comparison for `"a"` will be skipped (since the // lhs is not `Equatable`), but the comparision for `"b"` will return false. // In contrast, if `a2` is `lhs`, the comparison for `"a"` will return false right away. a1 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a1.mixins["a"] = NotHashableMixin(value: "a.1.value") a1.mixins["b"] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.1.origin", displayName: "a.1.origin") a2 = SymbolGraph.Relationship(source: "a.source", target: "a.target", kind: .conformsTo, targetFallback: nil) a2.mixins["a"] = SymbolGraph.Relationship.SourceOrigin(identifier: "a.2.origin", displayName: "a.2.origin") a2.mixins["b"] = NotHashableMixin(value: "a.2.value") XCTAssertEqual(Set([a1, a2]).count, 2) XCTAssertEqual(Set([a2, a1]).count, 2) } } private struct NotHashableMixin<T>: Mixin where T: Codable { static var mixinKey: String { "nothashable" } let value: T }
887cd0e2ac1336166392d0e0958ad866
54.550459
158
0.682246
false
true
false
false
AdilVirani/IntroiOS
refs/heads/master
Alamofire-swift-2.0/Tests/ResponseTests.swift
apache-2.0
36
// ResponseTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class ResponseDataTestCase: BaseTestCase { func testThatResponseDataReturnsSuccessResultWithValidData() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<NSData>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseData { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertTrue(result.error == nil, "result error should be nil") } func testThatResponseDataReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<NSData>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseData { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertTrue(result.error != nil, "result error should not be nil") } } // MARK: - class ResponseStringTestCase: BaseTestCase { func testThatResponseStringReturnsSuccessResultWithValidString() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<String>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseString { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertTrue(result.error == nil, "result error should be nil") } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<String>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseString { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertTrue(result.error != nil, "result error should not be nil") } } // MARK: - class ResponseJSONTestCase: BaseTestCase { func testThatResponseJSONReturnsSuccessResultWithValidJSON() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertTrue(result.error == nil, "result error should be nil") } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertTrue(result.error != nil, "result error should not be nil") } func testThatResponseJSONReturnsSuccessResultForGETRequest() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") // The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info. // - https://openradar.appspot.com/radar?id=5517037090635776 if let args = result.value?["args" as NSString] as? [String: String] { XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") } else { XCTFail("args should not be nil") } } func testThatResponseJSONReturnsSuccessResultForPOSTRequest() { // Given let URLString = "https://httpbin.org/post" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.POST, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") // The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info. // - https://openradar.appspot.com/radar?id=5517037090635776 if let form = result.value?["form" as NSString] as? [String: String] { XCTAssertEqual(form, ["foo": "bar"], "form should match parameters") } else { XCTFail("form should not be nil") } } } // MARK: - class RedirectResponseTestCase: BaseTestCase { func testThatRequestWillPerformHTTPRedirectionByDefault() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatRequestWillPerformRedirectionMultipleTimesByDefault() { // Given let redirectURLString = "https://httpbin.org/get" let URLString = "https://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanPerformHTTPRedirection() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, request in return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanCancelHTTPRedirection() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should not redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, _ in return nil } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", URLString, "response URL should match the origin URL") XCTAssertEqual(response?.statusCode ?? -1, 302, "response should have a 302 status code") } func testThatTaskOverrideClosureIsCalledMultipleTimesForMultipleHTTPRedirects() { // Given let redirectURLString = "https://httpbin.org/get" let URLString = "https://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate var totalRedirectCount = 0 delegate.taskWillPerformHTTPRedirection = { _, _, _, request in ++totalRedirectCount return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") XCTAssertEqual(totalRedirectCount, 5, "total redirect count should be 5") } }
312329fa7da046f8f46f59c224eaa9df
38.325726
119
0.652018
false
false
false
false
MiniDOM/MiniDOM
refs/heads/master
Sources/MiniDOM/MiniDOM.swift
mit
1
// // MiniDOM.swift // MiniDOM // // Copyright 2017-2020 Anodized Software, Inc. // // 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. // /* This file contains the protocols and classes used to define the Document Object Model. This is intended to provided a subset of the behavior described in the [DOM Level 1 specification][1] and the [DOM Level 2 specification][2]. Much of this file's documentation is adapted from those documents. [1]: https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html [2]: https://www.w3.org/TR/DOM-Level-2-Core/core.html */ import Foundation /// An `enum` indicating the type of a `Node` object. public enum NodeType { /// A `Document` object case document /// An `Element` object case element /// A `Text` object case text /// A `ProcessingInstruction` object case processingInstruction /// A `Comment` object case comment /// A `CDATASection` object case cdataSection } // MARK: - Node Protocol /** The `Node` protocol is the primary data type for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the `Node` protocol expose functionality related to children, not all objects implementing the `Node` protocol may have children. To address this distinction, there are two additional protocols implemented by node types: - `ParentNode` provides a getter and setter on the `children` property - `LeafNode` provides a getter on the `children` property that always returns an empty array. This is a departure from the standard DOM which would throw an error when attempting to modify the `children` array of a leaf node. The attributes `nodeName`, `nodeValue`, and `attributes` are included as a mechanism to get at node information without casting down to the specific derived type. In cases where there is no obvious mapping of these attributes for a specific `nodeType` (e.g., `nodeValue` for an Element or `attributes` for a Comment), this returns `nil`. The values of `nodeName`, `nodeValue`, and `attributes` vary according to the node type. */ public protocol Node: Visitable { /** Indicates which type of node this is. - SeeAlso: [`Document.nodeType`](Document.html#//apple_ref/swift/Property/nodeType) - SeeAlso: [`Element.nodeType`](Element.html#//apple_ref/swift/Property/nodeType) - SeeAlso: [`Text.nodeType`](Text.html#//apple_ref/swift/Property/nodeType) - SeeAlso: [`ProcessingInstruction.nodeType`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeType) - SeeAlso: [`Comment.nodeType`](Comment.html#//apple_ref/swift/Property/nodeType) - SeeAlso: [`CDATASection.nodeType`](CDATASection.html#//apple_ref/swift/Property/nodeType) */ static var nodeType: NodeType { get } /** The name of this node, depending on its type. - SeeAlso: [`Document.nodeName`](Document.html#//apple_ref/swift/Property/nodeName) - SeeAlso: [`Element.nodeName`](Element.html#//apple_ref/swift/Property/nodeName) - SeeAlso: [`Text.nodeName`](Text.html#//apple_ref/swift/Property/nodeName) - SeeAlso: [`ProcessingInstruction.nodeName`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeName) - SeeAlso: [`Comment.nodeName`](Comment.html#//apple_ref/swift/Property/nodeName) - SeeAlso: [`CDATASection.nodeName`](CDATASection.html#//apple_ref/swift/Property/nodeName) */ var nodeName: String { get } /** The value of this node, depending on its type. - SeeAlso: [`Document.nodeValue`](Document.html#//apple_ref/swift/Property/nodeValue) - SeeAlso: [`Element.nodeValue`](Element.html#//apple_ref/swift/Property/nodeValue) - SeeAlso: [`Text.nodeValue`](Text.html#//apple_ref/swift/Property/nodeValue) - SeeAlso: [`ProcessingInstruction.nodeValue`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeValue) - SeeAlso: [`Comment.nodeValue`](Comment.html#//apple_ref/swift/Property/nodeValue) - SeeAlso: [`CDATASection.nodeValue`](CDATASection.html#//apple_ref/swift/Property/nodeValue) */ var nodeValue: String? { get } /** The attributes of this node, depending on its type. - SeeAlso: [`Document.attributes`](Document.html#//apple_ref/swift/Property/attributes) - SeeAlso: [`Element.attributes`](Element.html#//apple_ref/swift/Property/attributes) - SeeAlso: [`Text.attributes`](Text.html#//apple_ref/swift/Property/attributes) - SeeAlso: [`ProcessingInstruction.attributes`](ProcessingInstruction.html#//apple_ref/swift/Property/attributes) - SeeAlso: [`Comment.attributes`](Comment.html#//apple_ref/swift/Property/attributes) - SeeAlso: [`CDATASection.attributes`](CDATASection.html#//apple_ref/swift/Property/attributes) */ var attributes: [String : String]? { get } /** The children of this node. - SeeAlso: [`Document.children`](Document.html#//apple_ref/swift/Property/children) - SeeAlso: [`Element.children`](Element.html#//apple_ref/swift/Property/children) - SeeAlso: [`Text.children`](Text.html#//apple_ref/swift/Property/children) - SeeAlso: [`ProcessingInstruction.children`](ProcessingInstruction.html#//apple_ref/swift/Property/children) - SeeAlso: [`Comment.children`](Comment.html#//apple_ref/swift/Property/children) - SeeAlso: [`CDATASection.children`](CDATASection.html#//apple_ref/swift/Property/children) */ var children: [Node] { get } /** Puts all `Text` nodes in the full depth of the sub-tree underneath this `Node`, into a "normal" form where only structure (e.g., elements, comments, processing instructions, and CDATA sections) separates `Text` nodes, i.e., there are neither adjacent `Text` nodes nor empty `Text` nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded. */ mutating func normalize() } public extension Node { /// Convenience accessor for the static `nodeType` property. var nodeType: NodeType { return Self.nodeType } /** Filters the `children` array, keeping only nodes of the specified type. Casts the nodes in the resulting array to the specified type. - parameter type: Include children of this type in the resulting array - returns: The nodes in the `children` array of the specified type */ func children<T: Node>(ofType type: T.Type) -> [T] { return children.only(ofType: T.self) } /// A Boolean value indicating whether the `children` array is not empty. var hasChildren: Bool { return !children.isEmpty } /// The first node in the `children` array. var firstChild: Node? { return children.first } /// The last node in the `children` array. var lastChild: Node? { return children.last } /** Returns an array of children with the given `nodeName`. - parameter name: The node name to find. - returns: The children with the given node name. */ func children(withName name: String) -> [Node] { return children.nodes(withName: name) } /// Returns the `Element` objects from the `children` array. var childElements: [Element] { return self.children(ofType: Element.self) } /// A Boolean value indicating whether the `childElements` array is not empty var hasChildElements: Bool { return !childElements.isEmpty } /// The first element in the `childElements` array. var firstChildElement: Element? { return childElements.first } /// The last element in the `childElements` array. var lastChildElement: Element? { return childElements.last } /** Returns an array of child `Element` objects with the given `nodeName`. - parameter name: The node name to find. - returns: The child elements with the given node name. */ func childElements(withName name: String) -> [Element] { return children.elements(withName: name) } } // MARK: - Leaf Protocol /** Represents a node that cannot have children. */ public protocol LeafNode: Node { /** A leaf node does not have children. The value of this property is always an empty array. */ var children: [Node] { get } } public extension LeafNode { /** A leaf node does not have children. The value of this property is always an empty array. */ var children: [Node] { return [] } mutating func normalize() { } } // MARK: - Parent Protocol /** Represents a node that can have children. */ public protocol ParentNode: Node { /// The children of this node. var children: [Node] { get set } } public extension ParentNode { /** Appends the specified node to the end of the `children` array. - parameter child: The node to append */ mutating func append(child: Node) { children.append(child) } mutating func normalize() { var newChildren: [Node] = [] for var currNode in children { if let currText = currNode as? Text, let prevText = newChildren.last as? Text { prevText.append(currText) } else { newChildren.append(currNode) } if currNode.hasChildren { currNode.normalize() } } children = newChildren } } // MARK: - TextNode Protocol /** Represents a node with a text value. */ public protocol TextNode: LeafNode { /// The text value associated with this node. var text: String { get set } } public extension TextNode { /// The `nodeValue` of a `TextNode` node is its `text` property. var nodeValue: String? { return text } } // MARK: - Document /** The `Document` class represents the entire document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data. */ public final class Document: ParentNode { // MARK: Node /// The `nodeType` of a `Document` is `.document`. public static let nodeType: NodeType = .document /// The `nodeName` of a `Document` is `#document`. public final let nodeName: String = "#document" /// The `nodeValue` of a `Document` is `nil`. public final let nodeValue: String? = nil /** The children of the document will contain the document element and any processing instructions or comments that are siblings of the documnent element. */ public final var children: [Node] = [] /// The `attributes` dictionary of a `Document` is `nil`. public final let attributes: [String : String]? = nil // MARK: Document /** This is a convenience attribute that allows direct access to the child node that is the root element of the document. */ public final var documentElement: Element? { return children.first(ofType: Element.self) } /** Creates a new `Document` node. */ public init() { } } // MARK: - Element /** By far the vast majority of objects (apart from text) that authors encounter when traversing a document are Element nodes. Assume the following XML document: ```xml <elementExample id="demo"> <subelement1/> <subelement2><subsubelement/></subelement2> </elementExample> ``` When represented using the DOM, the top node is an `Element` node for `elementExample`, which contains two child `Element` nodes, one for `subelement1` and one for `subelement2`. `subelement1` contains no child nodes. Elements may have attributes associated with them; since the `Element` class implements the `Node` protocol, the `attributes` property of the `Node` protocol may be used to retrieve a dictionary of the attributes for an element. */ public final class Element: ParentNode { // MARK: Node /// The `nodeType` of an `Element` is `.element`. public static let nodeType: NodeType = .element /// The `nodeName` of an `Element` is its `tagName`. public final var nodeName: String { return tagName } /// The `nodeValue` of an `Element` is `nil`. public final let nodeValue: String? = nil /// The children of the element. public final var children: [Node] // MARK: Element /** The name of the element. For example, in: ```xml <elementExample id="demo"> ... </elementExample> ``` `tagName` has the value `"elementExample"`. */ public final var tagName: String /** A dictionary that contains any attributes associated with the element. Keys are the names of attributes, and values are attribute values. */ public final var attributes: [String : String]? /** If an element has only a single child, and that child is a text node, return that text node's value. Otherwise, return nil. It is recommended first to normalize the document or this element (see `Node.normalize()`). This method will return the text as it is represented in the single child text node. Whitespace will not be stripped or normalized (see `String.trimmed` and `String.normalized`). */ public final var textValue: String? { if children.count == 1 && firstChild?.nodeType == .text { return firstChild?.nodeValue } return nil } // MARK: Initializer /** Creates a new `Element` node. - parameter tagName: A string that is the name of an element (in its start tag). - parameter attributes: A dictionary that contains any attributes associated with the element. Keys are the names of attributes, and values are attribute values. */ public init(tagName: String, attributes: [String : String] = [:], children: [Node] = []) { self.tagName = tagName self.attributes = attributes self.children = children } } // MARK: - Text /** The `Text` class represents the textual content (termed character data in XML) of an `Element`. If there is no markup inside an element's content, the text is contained in a single object implementing the `Text` protocol that is the only child of the element. If there is markup, it is parsed into a sequence of elements and `Text` nodes that form the array of children of the element. */ public final class Text: TextNode { // MARK: Node /// The `nodeType` of a `Text` node is `.text`. public static let nodeType: NodeType = .text /// The `nodeName` of a `Text` node is `#text`. public final let nodeName: String = "#text" /// The `attributes` dictionary of a `Text` node is `nil`. public final let attributes: [String : String]? = nil // MARK: TextNode /// The string contents of this text node. public final var text: String // MARK: Initializer /** Creates a new `Text` node. - parameter text: The string contents of this text node. */ public init(text: String) { self.text = text } final func append(_ other: Text) { text = text + other.text } } // MARK: - ProcessingInstruction /** The `ProcessingInstruction` class represents a "processing instruction", used in XML as a way to keep processor-secific information in the text of the document. */ public final class ProcessingInstruction: LeafNode { // MARK: Node /// The `nodeType` of a `ProcessingInstruction` is `.processingInstruction`. public static let nodeType: NodeType = .processingInstruction /// The `nodeName` of a `ProcessingInstruction` is its `target`. public final var nodeName: String { return target } /// The `nodeValue` of a `ProcessingInstruction` is its `data`. public final var nodeValue: String? { return data } /// The `attributes` dictionary of a `ProcessingInstruction` is `nil`. public final let attributes: [String : String]? = nil // MARK: ProcessingInstruction /** The target of this processing instruction. XML defines this as being the first token following the `<?` that begins the processing instruction. */ public final var target: String /** The content of this processing instruction. This is from the first non-whitespace character after the target to the character immediately preceding the `?>`. */ public final var data: String? // MARK: Initializer /** Creates a new `ProcessingInstruction' node. - parameter target: The target of this processing instruction. XML defines this as being the first token following the `<?` that begins the processing instruction. - parameter data: The content of this processing instruction. This is from the first non-whitespace character after the target to the character immediately preceding the `?>`. */ public init(target: String, data: String?) { self.target = target self.data = data } } // MARK: - Comment /** This represents the content of a comment, i.e., all the characters between the starting `<!--` and ending `-->`. */ public final class Comment: TextNode { // MARK: Node /// The `nodeType` of a `Comment` is `.comment`. public static let nodeType: NodeType = .comment /// The `nodeName` of a `Comment` is `#comment`. public final let nodeName: String = "#comment" /// The `attributes` dictionary of a `Comment` is `nil`. public final let attributes: [String : String]? = nil // MARK: TextNode /// The string contents of this comment. public final var text: String // MARK: Initializer /** Creates a new `Comment` node. - parameter text: The string contents of this comment. */ public init(text: String) { self.text = text } } // MARK: - CDATASection /** CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. The only delimiter that is recognized in a CDATA section is the `"]]>"` string that ends the CDATA section. CDATA sections can not be nested. The primary purpose is for including material such as XML fragments, without needing to escape all the delimiters. The `text` property holds the text that is contained by the CDATA section. Note that this may contain characters that need to be escaped outside of CDATA sections. */ public final class CDATASection: TextNode { // MARK: Node /// The `nodeType` of a `CDATASection` is `.cdataSection`. public static let nodeType: NodeType = .cdataSection /// The `nodeName` of a `CDATASection` is `#cdata-section`. public final let nodeName: String = "#cdata-section" /// The `attributes` dictionary of a `CDATASection` is `nil`. public final let attributes: [String : String]? = nil // MARK: TextNode /// The string contents of this CDATA section. public final var text: String // MARK: Initializer /** Creates a new `CDATASection node. - parameter text: The string contents of this CDATA secion. */ public init(text: String) { self.text = text } }
16d6cfd663f0b39c138027ff67cb96c8
30.61838
118
0.673531
false
false
false
false
russbishop/swift
refs/heads/master
stdlib/public/SDK/Dispatch/Queue.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // dispatch/queue.h public struct DispatchQueueAttributes : OptionSet { public let rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } public static let serial = DispatchQueueAttributes(rawValue: 0<<0) public static let concurrent = DispatchQueueAttributes(rawValue: 1<<1) @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static let initiallyInactive = DispatchQueueAttributes(rawValue: 1<<2) @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static let autoreleaseInherit = DispatchQueueAttributes(rawValue: 1<<3) @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static let autoreleaseWorkItem = DispatchQueueAttributes(rawValue: 1<<4) @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public static let autoreleaseNever = DispatchQueueAttributes(rawValue: 1<<5) @available(OSX 10.10, iOS 8.0, *) public static let qosUserInteractive = DispatchQueueAttributes(rawValue: 1<<6) @available(OSX 10.10, iOS 8.0, *) public static let qosUserInitiated = DispatchQueueAttributes(rawValue: 1<<7) @available(OSX 10.10, iOS 8.0, *) public static let qosDefault = DispatchQueueAttributes(rawValue: 1<<8) @available(OSX 10.10, iOS 8.0, *) public static let qosUtility = DispatchQueueAttributes(rawValue: 1<<9) @available(OSX 10.10, iOS 8.0, *) public static let qosBackground = DispatchQueueAttributes(rawValue: 1<<10) @available(*, deprecated, message: ".noQoS has no effect, it should not be used") public static let noQoS = DispatchQueueAttributes(rawValue: 1<<11) private var attr: __OS_dispatch_queue_attr? { var attr: __OS_dispatch_queue_attr? if self.contains(.concurrent) { attr = _swift_dispatch_queue_concurrent() } if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { if self.contains(.initiallyInactive) { attr = __dispatch_queue_attr_make_initially_inactive(attr) } if self.contains(.autoreleaseWorkItem) { // DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(1)) } else if self.contains(.autoreleaseInherit) { // DISPATCH_AUTORELEASE_FREQUENCY_INHERIT attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(0)) } else if self.contains(.autoreleaseNever) { // DISPATCH_AUTORELEASE_FREQUENCY_NEVER attr = __dispatch_queue_attr_make_with_autorelease_frequency(attr, __dispatch_autorelease_frequency_t(2)) } } if #available(OSX 10.10, iOS 8.0, *) { if self.contains(.qosUserInteractive) { attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_USER_INTERACTIVE, 0) } else if self.contains(.qosUserInitiated) { attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_USER_INITIATED, 0) } else if self.contains(.qosDefault) { attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_DEFAULT, 0) } else if self.contains(.qosUtility) { attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_UTILITY, 0) } else if self.contains(.qosBackground) { attr = __dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_BACKGROUND, 0) } } return attr } } public final class DispatchSpecificKey<T> { public init() {} } internal class _DispatchSpecificValue<T> { internal let value: T internal init(value: T) { self.value = value } } public extension DispatchQueue { public struct GlobalAttributes : OptionSet { public let rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } @available(OSX 10.10, iOS 8.0, *) public static let qosUserInteractive = GlobalAttributes(rawValue: 1<<0) @available(OSX 10.10, iOS 8.0, *) public static let qosUserInitiated = GlobalAttributes(rawValue: 1<<1) @available(OSX 10.10, iOS 8.0, *) public static let qosDefault = GlobalAttributes(rawValue: 1<<2) @available(OSX 10.10, iOS 8.0, *) public static let qosUtility = GlobalAttributes(rawValue: 1<<3) @available(OSX 10.10, iOS 8.0, *) public static let qosBackground = GlobalAttributes(rawValue: 1<<4) // Avoid using our own deprecated constants here by declaring // non-deprecated constants and then basing the public ones on those. internal static let _priorityHigh = GlobalAttributes(rawValue: 1<<5) internal static let _priorityDefault = GlobalAttributes(rawValue: 1<<6) internal static let _priorityLow = GlobalAttributes(rawValue: 1<<7) internal static let _priorityBackground = GlobalAttributes(rawValue: 1<<8) @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(*, deprecated: 8.0, message: "Use qos attributes instead") public static let priorityHigh = _priorityHigh @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(*, deprecated: 8.0, message: "Use qos attributes instead") public static let priorityDefault = _priorityDefault @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(*, deprecated: 8.0, message: "Use qos attributes instead") public static let priorityLow = _priorityLow @available(OSX, deprecated: 10.10, message: "Use qos attributes instead") @available(*, deprecated: 8.0, message: "Use qos attributes instead") public static let priorityBackground = _priorityBackground internal var _translatedValue: Int { if #available(OSX 10.10, iOS 8.0, *) { if self.contains(.qosUserInteractive) { return Int(QOS_CLASS_USER_INTERACTIVE.rawValue) } else if self.contains(.qosUserInitiated) { return Int(QOS_CLASS_USER_INITIATED.rawValue) } else if self.contains(.qosDefault) { return Int(QOS_CLASS_DEFAULT.rawValue) } else if self.contains(.qosUtility) { return Int(QOS_CLASS_UTILITY.rawValue) } else { return Int(QOS_CLASS_BACKGROUND.rawValue) } } if self.contains(._priorityHigh) { return 2 } // DISPATCH_QUEUE_PRIORITY_HIGH else if self.contains(._priorityDefault) { return 0 } // DISPATCH_QUEUE_PRIORITY_DEFAULT else if self.contains(._priorityLow) { return -2 } // // DISPATCH_QUEUE_PRIORITY_LOW else if self.contains(._priorityBackground) { return Int(Int16.min) } // // DISPATCH_QUEUE_PRIORITY_BACKGROUND return 0 } } public class func concurrentPerform(iterations: Int, execute work: @noescape (Int) -> Void) { _swift_dispatch_apply_current(iterations, work) } public class var main: DispatchQueue { return _swift_dispatch_get_main_queue() } public class func global(attributes: GlobalAttributes = []) -> DispatchQueue { return __dispatch_get_global_queue(attributes._translatedValue, 0) } public class func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? { let k = Unmanaged.passUnretained(key).toOpaque() if let p = __dispatch_get_specific(k) { let v = Unmanaged<_DispatchSpecificValue<T>> .fromOpaque(p) .takeUnretainedValue() return v.value } return nil } public convenience init( label: String, attributes: DispatchQueueAttributes = .serial, target: DispatchQueue? = nil) { if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { self.init(__label: label, attr: attributes.attr, queue: target) } else { self.init(__label: label, attr: attributes.attr) if let tq = target { self.setTarget(queue: tq) } } } public var label: String { return String(validatingUTF8: __dispatch_queue_get_label(self))! } @available(OSX 10.10, iOS 8.0, *) public func sync(execute workItem: DispatchWorkItem) { // _swift_dispatch_sync preserves the @convention(block) for // work item blocks. _swift_dispatch_sync(self, workItem._block) } @available(OSX 10.10, iOS 8.0, *) public func async(execute workItem: DispatchWorkItem) { // _swift_dispatch_{group,}_async preserves the @convention(block) // for work item blocks. if let g = workItem._group { _swift_dispatch_group_async(g, self, workItem._block) } else { _swift_dispatch_async(self, workItem._block) } } public func async(group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) { if group == nil && qos == .unspecified && flags.isEmpty { // Fast-path route for the most common API usage __dispatch_async(self, work) return } if #available(OSX 10.10, iOS 8.0, *), (qos != .unspecified || !flags.isEmpty) { let workItem = DispatchWorkItem(qos: qos, flags: flags, block: work) if let g = group { _swift_dispatch_group_async(g, self, workItem._block) } else { _swift_dispatch_async(self, workItem._block) } } else { if let g = group { __dispatch_group_async(g, self, work) } else { __dispatch_async(self, work) } } } private func _syncBarrier(block: @noescape () -> ()) { __dispatch_barrier_sync(self, block) } private func _syncHelper<T>( fn: (@noescape () -> ()) -> (), execute work: @noescape () throws -> T, rescue: ((ErrorProtocol) throws -> (T))) rethrows -> T { var result: T? var error: ErrorProtocol? fn { do { result = try work() } catch let e { error = e } } if let e = error { return try rescue(e) } else { return result! } } @available(OSX 10.10, iOS 8.0, *) private func _syncHelper<T>( fn: (DispatchWorkItem) -> (), flags: DispatchWorkItemFlags, execute work: @noescape () throws -> T, rescue: ((ErrorProtocol) throws -> (T))) rethrows -> T { var result: T? var error: ErrorProtocol? let workItem = DispatchWorkItem(flags: flags, noescapeBlock: { do { result = try work() } catch let e { error = e } }) fn(workItem) if let e = error { return try rescue(e) } else { return result! } } public func sync<T>(execute work: @noescape () throws -> T) rethrows -> T { return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 }) } public func sync<T>(flags: DispatchWorkItemFlags, execute work: @noescape () throws -> T) rethrows -> T { if flags == .barrier { return try self._syncHelper(fn: _syncBarrier, execute: work, rescue: { throw $0 }) } else if #available(OSX 10.10, iOS 8.0, *), !flags.isEmpty { return try self._syncHelper(fn: sync, flags: flags, execute: work, rescue: { throw $0 }) } else { return try self._syncHelper(fn: sync, execute: work, rescue: { throw $0 }) } } public func after(when: DispatchTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) { if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) __dispatch_after(when.rawValue, self, item._block) } else { __dispatch_after(when.rawValue, self, work) } } @available(OSX 10.10, iOS 8.0, *) public func after(when: DispatchTime, execute: DispatchWorkItem) { __dispatch_after(when.rawValue, self, execute._block) } public func after(walltime when: DispatchWallTime, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) { if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) __dispatch_after(when.rawValue, self, item._block) } else { __dispatch_after(when.rawValue, self, work) } } @available(OSX 10.10, iOS 8.0, *) public func after(walltime when: DispatchWallTime, execute: DispatchWorkItem) { __dispatch_after(when.rawValue, self, execute._block) } @available(OSX 10.10, iOS 8.0, *) public var qos: DispatchQoS { var relPri: Int32 = 0 let cls = DispatchQoS.QoSClass(qosClass: __dispatch_queue_get_qos_class(self, &relPri))! return DispatchQoS(qosClass: cls, relativePriority: Int(relPri)) } public func getSpecific<T>(key: DispatchSpecificKey<T>) -> T? { let k = Unmanaged.passUnretained(key).toOpaque() if let p = __dispatch_queue_get_specific(self, k) { let v = Unmanaged<_DispatchSpecificValue<T>> .fromOpaque(p) .takeUnretainedValue() return v.value } return nil } public func setSpecific<T>(key: DispatchSpecificKey<T>, value: T) { let v = _DispatchSpecificValue(value: value) let k = Unmanaged.passUnretained(key).toOpaque() let p = Unmanaged.passRetained(v).toOpaque() __dispatch_queue_set_specific(self, k, p, _destructDispatchSpecificValue) } } extension DispatchQueue { @available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)") public func synchronously(execute work: @noescape () -> ()) { sync(execute: work) } @available(OSX, introduced: 10.10, deprecated: 10.12, renamed: "DispatchQueue.sync(self:execute:)") @available(iOS, introduced: 8.0, deprecated: 10.0, renamed: "DispatchQueue.sync(self:execute:)") @available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)") public func synchronously(execute workItem: DispatchWorkItem) { sync(execute: workItem) } @available(OSX, introduced: 10.10, deprecated: 10.12, renamed: "DispatchQueue.async(self:execute:)") @available(iOS, introduced: 8.0, deprecated: 10.0, renamed: "DispatchQueue.async(self:execute:)") @available(*, deprecated, renamed: "DispatchQueue.async(self:execute:)") public func asynchronously(execute workItem: DispatchWorkItem) { async(execute: workItem) } @available(*, deprecated, renamed: "DispatchQueue.async(self:group:qos:flags:execute:)") public func asynchronously(group: DispatchGroup? = nil, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], execute work: @convention(block) () -> Void) { async(group: group, qos: qos, flags: flags, execute: work) } @available(*, deprecated, renamed: "DispatchQueue.sync(self:execute:)") public func synchronously<T>(execute work: @noescape () throws -> T) rethrows -> T { return try sync(execute: work) } @available(*, deprecated, renamed: "DispatchQueue.sync(self:flags:execute:)") public func synchronously<T>(flags: DispatchWorkItemFlags, execute work: @noescape () throws -> T) rethrows -> T { return try sync(flags: flags, execute: work) } @available(*, deprecated, renamed: "DispatchQueue.concurrentPerform(iterations:execute:)") public func apply(applier iterations: Int, execute block: @noescape (Int) -> Void) { DispatchQueue.concurrentPerform(iterations: iterations, execute: block) } @available(*, deprecated, renamed: "DispatchQueue.setTarget(self:queue:)") public func setTargetQueue(queue: DispatchQueue) { self.setTarget(queue: queue) } } private func _destructDispatchSpecificValue(ptr: UnsafeMutablePointer<Void>?) { if let p = ptr { Unmanaged<AnyObject>.fromOpaque(p).release() } } @_silgen_name("_swift_dispatch_queue_concurrent") internal func _swift_dispatch_queue_concurrent() -> __OS_dispatch_queue_attr @_silgen_name("_swift_dispatch_get_main_queue") internal func _swift_dispatch_get_main_queue() -> DispatchQueue @_silgen_name("_swift_dispatch_apply_current_root_queue") internal func _swift_dispatch_apply_current_root_queue() -> DispatchQueue @_silgen_name("_swift_dispatch_async") internal func _swift_dispatch_async(_ queue: DispatchQueue, _ block: _DispatchBlock) @_silgen_name("_swift_dispatch_group_async") internal func _swift_dispatch_group_async(_ group: DispatchGroup, _ queue: DispatchQueue, _ block: _DispatchBlock) @_silgen_name("_swift_dispatch_sync") internal func _swift_dispatch_sync(_ queue: DispatchQueue, _ block: _DispatchBlock) @_silgen_name("_swift_dispatch_apply_current") internal func _swift_dispatch_apply_current(_ iterations: Int, _ block: @convention(block) @noescape (Int) -> Void)
c13b2f39e56c22cb8a8f8e0d1e0ebfb8
36.671329
171
0.698595
false
false
false
false
liuche/FirefoxAccounts-ios
refs/heads/master
FxAUtils/FxAViewController.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Account import WebKit import SwiftyJSON protocol FxAContentViewControllerDelegate: class { func contentViewControllerDidSignIn(_ viewController: FxAViewController, withFlags: FxALoginFlags) func contentViewControllerDidCancel(_ viewController: FxAViewController) } open class FxAViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler { var fxaOptions = FxALaunchParams() let profile: Profile let url: URL! // The web view that displays content. var webView: WKWebView! weak var delegate: FxAContentViewControllerDelegate? fileprivate enum RemoteCommand: String { case canLinkAccount = "can_link_account" case loaded = "loaded" case login = "login" case sessionStatus = "session_status" case signOut = "sign_out" } public init() { let fxaLoginHelper = FxALoginHelper.sharedInstance let profile = BrowserProfile(localName: "profile") fxaLoginHelper.application(didLoadProfile: profile) self.profile = profile self.url = self.profile.accountConfiguration.signInURL super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.webView = makeWebView() webView.navigationDelegate = self view.addSubview(webView) let constraints = [ webView.leadingAnchor.constraint(equalTo: view.leadingAnchor), webView.trailingAnchor.constraint(equalTo: view.trailingAnchor), webView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor), webView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor) ] NSLayoutConstraint.activate(constraints, translatesAutoresizingMaskIntoConstraints: false) webView.load(URLRequest(url: profile.accountConfiguration.signInURL)) } func makeWebView() -> WKWebView { let source = getJS() let userScript = WKUserScript( source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true ) // Handle messages from the content server (via our user script). let contentController = WKUserContentController() contentController.addUserScript(userScript) contentController.add(LeakAvoider(delegate:self), name: "accountsCommandHandler") let config = WKWebViewConfiguration() config.userContentController = contentController let webView = WKWebView( frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: config ) return webView } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Handle a message coming from the content server. func handleRemoteCommand(_ rawValue: String, data: JSON) { print(rawValue) if let command = RemoteCommand(rawValue: rawValue) { switch command { case .loaded: print("loaded") case .login: print("login") onLogin(data) case .canLinkAccount: onCanLinkAccount(data) case .sessionStatus: print("sessionStatus") case .signOut: print("signout") } } } // Send a message to the content server. func injectData(_ type: String, content: [String: Any]) { let data = [ "type": type, "content": content, ] as [String : Any] let json = JSON(data).stringValue() ?? "" let script = "window.postMessage(\(json), '\(self.url.absoluteString)');" webView.evaluateJavaScript(script, completionHandler: nil) } fileprivate func onCanLinkAccount(_ data: JSON) { // // We need to confirm a relink - see shouldAllowRelink for more // let ok = shouldAllowRelink(accountData.email); let ok = true injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]]) } // The user has signed in to a Firefox Account. We're done! fileprivate func onLogin(_ data: JSON) { injectData("message", content: ["status": "login"]) let app = UIApplication.shared let helper = FxALoginHelper.sharedInstance helper.delegate = self helper.application(app, didReceiveAccountJSON: data) } // Dispatch webkit messages originating from our child webview. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { // Make sure we're communicating with a trusted page. That is, ensure the origin of the // message is the same as the origin of the URL we initially loaded in this web view. // Note that this exploit wouldn't be possible if we were using WebChannels; see // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/WebChannel.jsm let origin = message.frameInfo.securityOrigin guard origin.`protocol` == url.scheme && origin.host == url.host && origin.port == (url.port ?? 0) else { print("Ignoring message - \(origin) does not match expected origin \(url.origin)") return } if message.name == "accountsCommandHandler" { let body = JSON(message.body) let detail = body["detail"] handleRemoteCommand(detail["command"].stringValue, data: detail["data"]) } } } fileprivate func getJS() -> String { let fileRoot = Bundle.main.path(forResource: "FxASignIn", ofType: "js") return (try! NSString(contentsOfFile: fileRoot!, encoding: String.Encoding.utf8.rawValue)) as String } extension FxAViewController: FxAPushLoginDelegate { func accountLoginDidSucceed(withFlags flags: FxALoginFlags) { DispatchQueue.main.async { let token = self.profile.getAccount()!.syncAuthState.token(Date.now(), canBeExpired: false) token.upon { result in print("token result!") guard let tst = token.value.successValue?.token, let key = token.value.successValue?.forKey else { print("No token") return } // TODO: Return SyncClient object, for making get* calls let client = FxASyncClient(token: tst, key: key) client.getHistory() } self.dismiss(animated: true, completion: nil) } } func accountLoginDidFail() { DispatchQueue.main.async { self.delegate?.contentViewControllerDidCancel(self) } } } struct FxALaunchParams { var view: String? var email: String? var access_code: String? } /* LeakAvoider prevents leaks with WKUserContentController http://stackoverflow.com/questions/26383031/wkwebview-causes-my-view-controller-to-leak */ class LeakAvoider: NSObject, WKScriptMessageHandler { weak var delegate: WKScriptMessageHandler? init(delegate: WKScriptMessageHandler) { self.delegate = delegate super.init() } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { self.delegate?.userContentController(userContentController, didReceive: message) } }
d3f1c0a11149929a4df0c7554112e810
36.183099
126
0.648232
false
false
false
false
ArnavChawla/InteliChat
refs/heads/hd-callouts
Apps/Forum17/2017/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift
apache-2.0
19
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents /** Represents a parameter name of the Facebook Analytics application event. */ public enum AppEventParameterName { /// Identifier for the specific piece of content. case contentId /// Type of the content, e.g. "music"/"photo"/"video". case contentType /// Currency. E.g. "USD"/"EUR"/"GBP". See ISO-4217 for specific values. case currency /// Appropriate description for the event. case Description /// Current level or level achieved. case level /// Maximum rating available. E.g. "5"/"10". case maxRatingValue /// Count of items being proccessed. case itemCount /// Boolean value indicating whether payment information is available. case paymentInfoAvailable /// Registration method used. E.g. "Facebook"/"email"/"sms". case registrationMethod /// String provided by the user for a search operation. case searchedString /// Boolean value indicating wehtehr an activity being logged was succesful. case successful /// Custom name of the parameter that is represented by a string. case custom(String) /** Create an `AppEventParameterName` from `String`. - parameter string: String to create an app event name from. */ public init(_ string: String) { self = .custom(string) } } extension AppEventParameterName: RawRepresentable { /** Create an `AppEventParameterName` from `String`. - parameter rawValue: String to create an app event name from. */ public init?(rawValue: String) { self = .custom(rawValue) } /// The corresponding `String` value. public var rawValue: String { switch self { case .contentId: return FBSDKAppEventParameterNameContentID case .contentType: return FBSDKAppEventParameterNameContentType case .currency: return FBSDKAppEventParameterNameCurrency case .Description: return FBSDKAppEventParameterNameDescription case .level: return FBSDKAppEventNameAchievedLevel case .maxRatingValue: return FBSDKAppEventParameterNameMaxRatingValue case .itemCount: return FBSDKAppEventParameterNameNumItems case .paymentInfoAvailable: return FBSDKAppEventParameterNamePaymentInfoAvailable case .registrationMethod: return FBSDKAppEventParameterNameRegistrationMethod case .searchedString: return FBSDKAppEventParameterNameSearchString case .successful: return FBSDKAppEventParameterNameSuccess case .custom(let string): return string } } } extension AppEventParameterName: ExpressibleByStringLiteral { /** Create an `AppEventParameterName` from a string literal. - parameter value: The string literal to create from. */ public init(stringLiteral value: StringLiteralType) { self = .custom(value) } /** Create an `AppEventParameterName` from a unicode scalar literal. - parameter value: The string literal to create from. */ public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } /** Create an `AppEventParameterName` from an extended grapheme cluster. - parameter value: The string literal to create from. */ public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } } extension AppEventParameterName: Hashable { /// The hash value. public var hashValue: Int { return self.rawValue.hashValue } /** Compare two `AppEventParameterName`s for equality. - parameter lhs: The first parameter name to compare. - parameter rhs: The second parameter name to compare. - returns: Whether or not the parameter names are equal. */ public static func == (lhs: AppEventParameterName, rhs: AppEventParameterName) -> Bool { return lhs.rawValue == rhs.rawValue } } extension AppEventParameterName: CustomStringConvertible { /// Textual representation of an app event parameter name. public var description: String { return rawValue } }
3c96d70019cf48acef7c90784c01189f
34.140845
90
0.746894
false
false
false
false
accepton/accepton-apple
refs/heads/master
Pod/Classes/AcceptOnUIMachine/AcceptOnUIMachine.swift
mit
1
import StripePrivate @objc public protocol AcceptOnUIMachineDelegate { //Start-up optional func acceptOnUIMachineDidFailBegin(error: NSError) optional func acceptOnUIMachineDidFinishBeginWithFormOptions(options: AcceptOnUIMachineFormOptions) //Credit-card form optional func acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName(name: String, withMessage msg: String) optional func acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName(name: String, withMessage msg: String) optional func acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName(name: String) optional func acceptOnUIMachineCreditCardTypeDidChange(type: String) optional func acceptOnUIMachineDidSetInitialFieldValueWithName(name: String, withValue value: String) //Mid-cycle optional func acceptOnUIMachinePaymentIsProcessing(paymentType: String) optional func acceptOnUIMachinePaymentDidAbortPaymentMethodWithName(name: String) optional func acceptOnUIMachinePaymentErrorWithMessage(message: String) optional func acceptOnUIMachinePaymentDidSucceedWithCharge(chargeInfo: [String:AnyObject]) //Requests showing additional fields based on the requirements dictated by the userInfo structure. On as successful completion (i.e. wasCancelled is false) //the metadata returned is merged into the formOptions.metadata func acceptOnUIMachineDidRequestAdditionalUserInfo(userInfo: AcceptOnUIMachineOptionalUserInfo, completion: (wasCancelled: Bool, info: AcceptOnUIMachineExtraFieldsMetadataInfo?)->()) //Spec related optional func acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName(name: String, withValue value: String) //Field updated, no validation error } //Contains error codes for AcceptOnUIMachine & convenience methods public struct AcceptOnUIMachineError { public static let domain = "com.accepton.UIMachine.error" public enum Code: Int { case DeveloperError = -5555 } //Creates an NSError given the error code and failure reason public static func errorWithCode(code: Code, failureReason: String) -> NSError { let info = [NSLocalizedFailureReasonErrorKey: failureReason] return NSError(domain: domain, code: code.rawValue, userInfo: info) } } public class AcceptOnUIMachineFormOptions : NSObject { let token: AcceptOnAPITransactionToken! public let paymentMethods: AcceptOnAPIPaymentMethodsInfo! public var itemDescription: String { return token.desc } public var amountInCents: Int { return token.amountInCents } /* The different sections available, credit-card, paypal, etc. */ public var hasCreditCardForm: Bool { return paymentMethods.supportsCreditCard } public var hasPaypalButton: Bool { return paymentMethods.supportsPaypal } public var hasApplePay: Bool { return paymentMethods.supportsApplePay && AcceptOnUIMachineApplePayDriver.checkAvailability() != .NotSupported } //Converts amountInCents into a $xx.xx style string. E.g. 349 -> $3.49 public var uiAmount: String { let formatter = NSNumberFormatter() formatter.numberStyle = .CurrencyStyle formatter.locale = NSLocale(localeIdentifier: "en_US") return formatter.stringFromNumber(Double(amountInCents) / 100.0) ?? "<error>" } public init(token: AcceptOnAPITransactionToken, paymentMethods: AcceptOnAPIPaymentMethodsInfo, userInfo: AcceptOnUIMachineOptionalUserInfo?=nil) { self.token = token self.paymentMethods = paymentMethods self.userInfo = userInfo super.init() } //Additional user information public var userInfo: AcceptOnUIMachineOptionalUserInfo? //Credit card transactions post the email & all fields of the credit-card public var creditCardParams: AcceptOnAPICreditCardParams? //Extra information, either provided by the 'extra' enabled fields //or user added public var metadata: [String:AnyObject] = [:] } enum AcceptOnUIMachineState: String { case Initialized = "Initialized" //begin has not been called case BeginWasCalled = "BeginWasCalled" //In the middle of the begin case PaymentForm = "PaymentForm" //begin succeeded case ExtraFields = "ExtraFields" //Showing extra fields dialog case WaitingForTransaction = "WaitingForTransaction" //In the middle of a transaction request (like apple-pay, credit-card, paypal, etc) case PaymentComplete = "PaymentComplete" //Payment has completed } //Various informations about a user like email //that can be used for things like pre-populating forms @objc public class AcceptOnUIMachineOptionalUserInfo: NSObject { public override init() {} //-------------------------------------------------------------------------------- //Autofill the user's email address //-------------------------------------------------------------------------------- public var emailAutofillHint: String? //-------------------------------------------------------------------------------- //Collect, and require, billing address information //-------------------------------------------------------------------------------- public var requestsAndRequiresBillingAddress: Bool = false public var billingAddressAutofillHints: AcceptOnAPIAddress? //-------------------------------------------------------------------------------- //Collect, and require, shipping information. For payment systems that require //that shipping costs be provided, such as apple-pay, we automatically //set these as "Shipping Included" and set the shipping fee to `$0` on //any necessary shipping information fields. //-------------------------------------------------------------------------------- public var requestsAndRequiresShippingAddress: Bool = false public var shippingAddressAutofillHints: AcceptOnAPIAddress? //-------------------------------------------------------------------------------- //Additional metadata to pass in, this will just be passed through to the final //output and placed into the metadata field //-------------------------------------------------------------------------------- public var extraMetadata: [String:AnyObject]? } //Provided on completion of 'extra fields' @objc public class AcceptOnUIMachineExtraFieldsMetadataInfo: NSObject { public override init() {} public var email: String? public var billingAddress: AcceptOnAPIAddress? public var shippingAddress: AcceptOnAPIAddress? public var billingSameAsShipping: Bool? func toDictionary() -> [String:AnyObject] { var out: [String:AnyObject] = [:] if let email = email { out["email"] = email } if let billingAddress = billingAddress { out["billing_address"] = billingAddress.toDictionary() } if let shippingAddress = shippingAddress { out["shipping_address"] = shippingAddress.toDictionary() } if let billingSameAsShipping = billingSameAsShipping { out["billing_same_as_shipping"] = billingSameAsShipping } return out } } public class AcceptOnUIMachine: NSObject, AcceptOnUIMachinePaymentDriverDelegate { /* ######################################################################################### */ /* Constructors & Members (Stage I) */ /* ######################################################################################### */ var userInfo: AcceptOnUIMachineOptionalUserInfo? public convenience init(publicKey: String, isProduction: Bool, userInfo: AcceptOnUIMachineOptionalUserInfo? = nil) { self.init(api: AcceptOnAPI(publicKey: publicKey, isProduction: isProduction), userInfo: userInfo) } public convenience init(secretKey: String, isProduction: Bool, userInfo: AcceptOnUIMachineOptionalUserInfo? = nil) { self.init(api: AcceptOnAPI(secretKey: secretKey, isProduction: isProduction), userInfo: userInfo) } public var api: AcceptOnAPI //This is the networking API object public init(api: AcceptOnAPI, userInfo: AcceptOnUIMachineOptionalUserInfo? = nil) { self.api = api self.userInfo = userInfo } //Controls the state transitions var state: AcceptOnUIMachineState = .Initialized { didSet { self.stateInfo = nil GoogleAnalytics.trackPageNamed(state.rawValue) } } var stateInfo: Any? public var isProduction: Bool { return api.isProduction } //This is typically the vc that created us public weak var delegate: AcceptOnUIMachineDelegate? /* ######################################################################################### */ /* Stage II Initializers */ /* ######################################################################################### */ //Signal from controller that we are ready to fetch data on the form configuration //and signal to the controller the didLoadFormWithConfig event for the given transaction //request var tokenObject: AcceptOnAPITransactionToken? //Transaction token that was created during beginForItemWithDescription for the given parameters var amountInCents: Int? //Amount in cents of this transaction var itemDescription: String? //Description of this transaction var paymentMethods: AcceptOnAPIPaymentMethodsInfo? //Retrieved by the AcceptOnAPI containing the form configuration (payment types accepted) public func beginForItemWithDescription(description: String, forAmountInCents amountInCents: Int) { //Prevent race-conditions on didBegin check dispatch_async(dispatch_get_main_queue()) { [weak self] in //Can only be called at the start once. It's a stage II initializer if (self?.state != .Initialized) { self?.delegate?.acceptOnUIMachineDidFailBegin?(AcceptOnUIMachineError.errorWithCode(.DeveloperError, failureReason: "You already called beginForItemWithDescription; this should have been called once at the start. You will have to make a new AcceptOnUIMachine for a new form")) return } self?.state = .BeginWasCalled //Create a transaction token self?.api.createTransactionTokenWithDescription(description, forAmountInCents: amountInCents) { (tokenObject, error) -> () in if let error = error { //Non-Recoverable, recreate UIMachine to start-over dispatch_async(dispatch_get_main_queue()) { self?.delegate?.acceptOnUIMachineDidFailBegin?(error) } return } self?.tokenObject = tokenObject self?.amountInCents = amountInCents self?.itemDescription = description //Request the form configuration self?.api.getAvailablePaymentMethodsForTransactionWithId(tokenObject!.id, completion: { (paymentMethods, error) -> () in //Make sure we got back a response if let error = error { //Non-Recoverable, recreate UIMachine to start-over dispatch_async(dispatch_get_main_queue()) { self?.delegate?.acceptOnUIMachineDidFailBegin?(error) } return } //Save the paymentMethods self?.paymentMethods = paymentMethods! //Notify that we are loaded self?.state = .PaymentForm self?.postBegin() }) } } } //Called at the end of the beginForItemWithDescription sequence. By now, we've //loaded the tokenId & paymentMethods. var options: AcceptOnUIMachineFormOptions! func postBegin() { options = AcceptOnUIMachineFormOptions(token: self.tokenObject!, paymentMethods: self.paymentMethods!, userInfo: userInfo) //Signal that we should show the form dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineDidFinishBeginWithFormOptions?(self.options) } } /* ######################################################################################### */ /* Credit Card Form Specifics */ /* ######################################################################################### */ //User targets a credit-card field, or untargets a field. Field names //are specified in the example form in https://github.com/sotownsend/accepton-apple/blob/master/docs/AcceptOnUIMachine.md var _currentFocusedCreditCardFieldName: String? var currentFocusedCreditCardFieldName: String? { set (newFieldName) { //Validate the old field if it existed if let _currentFocusedCreditCardFieldName = _currentFocusedCreditCardFieldName { validateCreditCardFieldWithName(_currentFocusedCreditCardFieldName) } _currentFocusedCreditCardFieldName = newFieldName } get { return _currentFocusedCreditCardFieldName } } public func creditCardFieldDidFocusWithName(name: String) { guard state == .PaymentForm else { return } currentFocusedCreditCardFieldName = name } public func creditCardFieldDidLoseFocus() { guard state == .PaymentForm else { return } currentFocusedCreditCardFieldName = nil } public func creditCardFieldWithName(name: String, didUpdateWithString string: String) { if (name == "email") { updateCreditCardEmailFieldWithString(string)} else if (name == "cardNum") { updateCreditCardCardNumFieldWithString(string)} else if (name == "expMonth") { updateCreditCardExpMonthFieldWithString(string)} else if (name == "expYear") { updateCreditCardExpYearFieldWithString(string)} else if (name == "security") { updateCreditCardSecurityFieldWithString(string)} } func validateCreditCardFieldWithName(name: String) { if (name == "email") { validateCreditCardEmailField() } else if (name == "cardNum") { validateCreditCardCardNumField() } else if (name == "expMonth") { validateCreditCardExpMonthField() } else if (name == "expYear") { validateCreditCardExpYearField() } else if (name == "security") { validateCreditCardSecurityField() } } //Must be always called, will auto-fill out credit-card form with email if available public func didSwitchToCreditCardForm() { //If user info received email, update the email field if let email = self.userInfo?.emailAutofillHint { dispatch_async(dispatch_get_main_queue()) { if self.delegate?.acceptOnUIMachineDidSetInitialFieldValueWithName != nil { self.delegate?.acceptOnUIMachineDidSetInitialFieldValueWithName!("email", withValue: email) self.updateCreditCardEmailFieldWithString(email) self.validateCreditCardEmailField() } } } } //Optional, allows you to use on apps that contain a payment selection form public func didSwitchFromCreditCardForm() { _emailFieldValue = "" _cardNumFieldValue = "" _expMonthFieldValue = "" _expYearFieldValue = "" _securityFieldValue = "" _creditCardType = "unknown" emailFieldHasValidationError = false cardNumFieldHasValidationError = false expMonthFieldHasValidationError = false expYearFieldHasValidationError = false securityFieldHasValidationError = false } //Email field ///////////////////////////////////////////////////////////////////// var _emailFieldValue: String? var emailFieldValue: String { get { return _emailFieldValue ?? "" } set { _emailFieldValue = newValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } var emailFieldHasValidationError: Bool = false func validateCreditCardEmailField() -> Bool { var errorStr: String? = nil if emailFieldValue == "" { errorStr = "Please enter an email" } else { let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) if emailTest.evaluateWithObject(emailFieldValue) != true { errorStr = "Please check your email" } } if let errorStr = errorStr { //We have a new validation error if (emailFieldHasValidationError == false) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName?("email", withMessage: errorStr) } emailFieldHasValidationError = true } else { //We still have a validation error dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName?("email", withMessage: errorStr) } } } else { //We no longer have a validation error if emailFieldHasValidationError == true { emailFieldHasValidationError = false dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName?("email") } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName?("email", withValue: self.emailFieldValue) } } return errorStr == nil ? true : false } func updateCreditCardEmailFieldWithString(string: String) { emailFieldValue = string } ///////////////////////////////////////////////////////////////////// //cardNum field ///////////////////////////////////////////////////////////////////// var _cardNumFieldValue: String? var _creditCardType: String = "unknown" var creditCardType: String { get { return _creditCardType } set { if newValue != _creditCardType { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineCreditCardTypeDidChange?(newValue) } } _creditCardType = newValue } } var cardNumFieldValue: String { get { return _cardNumFieldValue ?? "" } set { _cardNumFieldValue = newValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } var cardNumFieldHasValidationError: Bool = false func validateCreditCardCardNumField() -> Bool { var errorStr: String? = nil if cardNumFieldValue == "" { errorStr = "Please enter an card number" } else { let cardNumValidationState = STPCardValidator.validationStateForNumber(cardNumFieldValue, validatingCardBrand: true) if cardNumValidationState != .Valid { errorStr = "Please check your card number" } } if let errorStr = errorStr { //We have a new validation error if (cardNumFieldHasValidationError == false) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName?("cardNum", withMessage: errorStr) } cardNumFieldHasValidationError = true } else { //We still have a validation error dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName?("cardNum", withMessage: errorStr) } } } else { //We no longer have a validation error if cardNumFieldHasValidationError == true { cardNumFieldHasValidationError = false dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName?("cardNum") } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName?("cardNum", withValue: self.cardNumFieldValue) } } return errorStr == nil ? true : false } func updateCreditCardCardNumFieldWithString(string: String) { cardNumFieldValue = string let cardBrand = STPCardValidator.brandForNumber(string) switch (cardBrand) { case .Visa: creditCardType = "visa" case .Amex: creditCardType = "amex" case .Discover: creditCardType = "discover" case .MasterCard: creditCardType = "master_card" default: creditCardType = "unknown" } } ///////////////////////////////////////////////////////////////////// //expMonth field ///////////////////////////////////////////////////////////////////// var _expMonthFieldValue: String? var expMonthFieldValue: String? { get { return _expMonthFieldValue } set { _expMonthFieldValue = newValue?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } var expMonthFieldHasValidationError: Bool = false func validateCreditCardExpMonthField() -> Bool { var errorStr: String? = nil if expMonthFieldValue == "" { errorStr = "Please enter the expiration month" } else { let expMonthValidationState = STPCardValidator.validationStateForExpirationMonth(expMonthFieldValue ?? "<no month>") if expMonthValidationState != .Valid { errorStr = "Please check your card number" } } if let errorStr = errorStr { //We have a new validation error if (expMonthFieldHasValidationError == false) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName?("expMonth", withMessage: errorStr) } expMonthFieldHasValidationError = true } else { //We still have a validation error dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName?("expMonth", withMessage: errorStr) } } } else { //We no longer have a validation error if expMonthFieldHasValidationError == true { expMonthFieldHasValidationError = false dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName?("expMonth") } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName?("expMonth", withValue: self.expMonthFieldValue ?? "<no month>") } } return errorStr == nil ? true : false } func updateCreditCardExpMonthFieldWithString(string: String) { expMonthFieldValue = string } ///////////////////////////////////////////////////////////////////// //expYear field ///////////////////////////////////////////////////////////////////// var _expYearFieldValue: String? var expYearFieldValue: String { get { return _expYearFieldValue ?? "" } set { _expYearFieldValue = newValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } var expYearFieldHasValidationError: Bool = false func validateCreditCardExpYearField() -> Bool { var errorStr: String? = nil if expYearFieldValue == "" { errorStr = "Please enter the expiration year" } else { let expYearValidationState = STPCardValidator.validationStateForExpirationYear(expYearFieldValue, inMonth: expMonthFieldValue ?? "01") if expYearValidationState != .Valid { errorStr = "Please check your card number" } } if let errorStr = errorStr { //We have a new validation error if (expYearFieldHasValidationError == false) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName?("expYear", withMessage: errorStr) } expYearFieldHasValidationError = true } else { //We still have a validation error dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName?("expYear", withMessage: errorStr) } } } else { //We no longer have a validation error if expYearFieldHasValidationError == true { expYearFieldHasValidationError = false dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName?("expYear") } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName?("expYear", withValue: self.expYearFieldValue) } } return errorStr == nil ? true : false } func updateCreditCardExpYearFieldWithString(string: String) { expYearFieldValue = string } ///////////////////////////////////////////////////////////////////// //security field ///////////////////////////////////////////////////////////////////// var _securityFieldValue: String? var securityFieldValue: String { get { return _securityFieldValue ?? "" } set { _securityFieldValue = newValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } var securityFieldHasValidationError: Bool = false func validateCreditCardSecurityField() -> Bool { var errorStr: String? = nil if securityFieldValue == "" { errorStr = "Please enter the security code" } else { let securityValidationState = STPCardValidator.validationStateForCVC(securityFieldValue, cardBrand: STPCardValidator.brandForNumber(cardNumFieldValue)) if securityValidationState != .Valid { errorStr = "Please check your security code" } } if let errorStr = errorStr { //We have a new validation error if (securityFieldHasValidationError == false) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineShowValidationErrorForCreditCardFieldWithName?("security", withMessage: errorStr) } securityFieldHasValidationError = true } else { //We still have a validation error dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineEmphasizeValidationErrorForCreditCardFieldWithName?("security", withMessage: errorStr) } } } else { //We no longer have a validation error if securityFieldHasValidationError == true { securityFieldHasValidationError = false dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineHideValidationErrorForCreditCardFieldWithName?("security") } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineSpecFieldUpdatedSuccessfullyWithName?("security", withValue: self.securityFieldValue) } } return errorStr == nil ? true : false } func updateCreditCardSecurityFieldWithString(string: String) { securityFieldValue = string } ///////////////////////////////////////////////////////////////////// //User hits the 'pay' button for the credit-card form public func creditCardPayClicked() { //startTransaction changes the state if state != .PaymentForm { return } //Don't use &&: optimizer might attempt short-circuit some //statements and we want all these to execute even if some fail let resEmail = validateCreditCardEmailField() let resCardNum = validateCreditCardCardNumField() let resCardExpMonth = validateCreditCardExpMonthField() let resCardExpYear = validateCreditCardExpYearField() let resCardSecurity = validateCreditCardSecurityField() //Are we good on all the validations? if (resEmail && resCardNum && resCardExpMonth && resCardExpYear && resCardSecurity == true) { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate?.acceptOnUIMachinePaymentIsProcessing?("credit_card") }) //Create our helper struct to pass to our drivers let cardParams = AcceptOnAPICreditCardParams(number: cardNumFieldValue, expMonth: expMonthFieldValue ?? "", expYear: expYearFieldValue, cvc: securityFieldValue, email: emailFieldValue) self.options!.creditCardParams = cardParams self.startTransactionWithDriverOfClass(AcceptOnUIMachineCreditCardDriver.self) } } /* ######################################################################################### */ /* Paypal specifics */ /* ######################################################################################### */ public func paypalClicked() { if state != .PaymentForm { return } //Wait 1.5 seconds so it has time to show a loading screen of sorts startTransactionWithDriverOfClass(AcceptOnUIMachinePayPalDriver.self, withDelay: 1.3) } /* ######################################################################################### */ /* ApplePay specifics */ /* ######################################################################################### */ public func applePayClicked() { if state != .PaymentForm { return } //Wait 1.5 seconds so it has time to show a loading screen of sorts startTransactionWithDriverOfClass(AcceptOnUIMachineApplePayDriver.self, withDelay: 1.3) } //----------------------------------------------------------------------------------------------------- //AcceptOnUIMachinePaymentDriverDelegate //----------------------------------------------------------------------------------------------------- public func transactionDidCancelForDriver(driver: AcceptOnUIMachinePaymentDriver) { if state != .WaitingForTransaction { return } state = .PaymentForm dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachinePaymentDidAbortPaymentMethodWithName?(driver.dynamicType.name) } } public func transactionDidFailForDriver(driver: AcceptOnUIMachinePaymentDriver, withMessage message: String) { if state != .WaitingForTransaction { return } state = .PaymentForm dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachinePaymentDidAbortPaymentMethodWithName?(driver.dynamicType.name) self.delegate?.acceptOnUIMachinePaymentErrorWithMessage?(message) } } public func transactionDidSucceedForDriver(driver: AcceptOnUIMachinePaymentDriver, withChargeRes chargeRes: [String : AnyObject]) { state = .PaymentComplete dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachinePaymentDidSucceedWithCharge?(chargeRes) } } //----------------------------------------------------------------------------------------------------- //Starts the transaction process for a driver //----------------------------------------------------------------------------------------------------- var activeDriver: AcceptOnUIMachinePaymentDriver! func startTransactionWithDriverOfClass(driverClass: AcceptOnUIMachinePaymentDriver.Type, withDelay delay: Double=0.0) { dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachinePaymentIsProcessing?(driverClass.name) } //Switch to 'extra fields', store the parameters to use when extra fields completes self.state = .ExtraFields let block = { [weak self] in if self == nil { return } if self?.state != .ExtraFields { return } self?.displayExtraFieldsIfNecessaryAndCompleteByTransactingWithDriver(driverClass) //Loads the 'metadata' information } if delay == 0 { block() } else { let delay = Int64(delay*1000) * Int64(NSEC_PER_MSEC) let time = dispatch_time(DISPATCH_TIME_NOW, delay) dispatch_after(time, dispatch_get_main_queue()) { block() } } } //Show extra fields and load the formOptions.metadata if necessary. Then continue on with the transaction func displayExtraFieldsIfNecessaryAndCompleteByTransactingWithDriver(driverClass: AcceptOnUIMachinePaymentDriver.Type) { self.state = .WaitingForTransaction //Executing this block would begin the driver transaction, but we want to check //to see if we need to show any extra fields first let startDriverTransaction = { self.activeDriver = driverClass.init(formOptions: self.options!) self.activeDriver.delegate = self self.activeDriver.beginTransaction() } //if userInfo was provided which holds things like 'should we show address' if let userInfo = self.userInfo { //Append any extra metadata if let extraMetaData = userInfo.extraMetadata { self.options.metadata = extraMetaData } //Determine if we should show the extra fields form by looking at the provided userInfo //Credit-card transactions don't require credit-card fields if (userInfo.requestsAndRequiresBillingAddress || userInfo.requestsAndRequiresShippingAddress) != true { startDriverTransaction() return } //Call up to retrieve any more metadata dispatch_async(dispatch_get_main_queue()) { self.delegate?.acceptOnUIMachineDidRequestAdditionalUserInfo(userInfo, completion: { wasCancelled, extraFieldInfo in if wasCancelled { self.state = .PaymentForm self.delegate?.acceptOnUIMachinePaymentDidAbortPaymentMethodWithName?(driverClass.name) } else { if let extraFieldInfo = extraFieldInfo { for (k, v) in extraFieldInfo.toDictionary() { self.options.metadata[k] = v } } //Start rest of driver transaction startDriverTransaction() } }) } } else { //No requirements or additional information provided. Show no fields, start the driver transaction now startDriverTransaction() } } }
876ed55bb4889283df110b3ccc2f0d33
45.361042
293
0.584098
false
false
false
false
steelwheels/KiwiControls
refs/heads/master
Source/Controls/KCGraphics2DView.swift
lgpl-2.1
1
/** * @file KCGraphics2DView.swift * @brief Define KCGraphics2DView class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import CoconutData import CoreGraphics #if os(OSX) import Cocoa #else import UIKit #endif open class KCGraphics2DView: KCLayerView { private var mContext: CNGraphicsContext private var mForegroundColor: CNColor public override init(frame : CGRect){ mContext = CNGraphicsContext() let pref = CNPreference.shared.viewPreference mForegroundColor = pref.foregroundColor super.init(frame: frame) } public convenience init(){ let frame = CGRect(x: 0.0, y: 0.0, width: 480, height: 270) self.init(frame: frame) } required public init?(coder: NSCoder) { mContext = CNGraphicsContext() let pref = CNPreference.shared.viewPreference mForegroundColor = pref.foregroundColor super.init(coder: coder) } public var foregroundColor: CNColor { get { return mForegroundColor }} open override func draw(context ctxt: CGContext, count cnt: Int32) { self.mContext.begin(context: ctxt, logicalFrame: self.logicalFrame, physicalFrame: self.frame) /* Set default parameters */ if cnt == 0 { self.mContext.setFillColor(color: self.mForegroundColor) self.mContext.setStrokeColor(color: self.mForegroundColor) self.mContext.setPenSize(width: self.logicalFrame.size.width / 100.0) } self.draw(graphicsContext: self.mContext, count: cnt) self.mContext.end() } open func draw(graphicsContext ctxt: CNGraphicsContext, count cnt: Int32) { CNLog(logLevel: .error, message: "must be override", atFunction: #function, inFile: #file) } open override func accept(visitor vis: KCViewVisitor){ vis.visit(graphics2DView: self) } }
db0a4d5c0fd252cbe15ad1f9158b5d07
26.206349
96
0.743874
false
false
false
false
cbrentharris/swift
refs/heads/master
stdlib/public/core/Collection.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @available(*, unavailable, message="access the 'count' property on the collection") public func count <T : CollectionType>(x: T) -> T.Index.Distance { fatalError("unavailable function can't be called") } /// A protocol representing the minimal requirements of /// `CollectionType`. /// /// - Note: In most cases, it's best to ignore this protocol and use /// `CollectionType` instead, as it has a more complete interface. // // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Generator` type from a minimal collection, but it is also used in // exposed places like as a constraint on IndexingGenerator. public protocol Indexable { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. typealias Index : ForwardIndexType /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(1) var startIndex: Index {get} /// 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()`. /// /// - Complexity: O(1) var endIndex: Index {get} // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a CollectionType.Generator.Element that can // be used as IndexingGenerator<T>'s Element. Here we arrange for the // CollectionType itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this // Element to be the same as CollectionType.Generator.Element (see // below), but we have no way of expressing it today. typealias _Element /// Returns the element at the given `position`. /// /// - Complexity: O(1) subscript(position: Index) -> _Element {get} } public protocol MutableIndexable { typealias Index : ForwardIndexType var startIndex: Index {get} var endIndex: Index {get} typealias _Element subscript(position: Index) -> _Element {get set} } /// A *generator* for an arbitrary *collection*. Provided `C` /// conforms to the other requirements of `Indexable`, /// `IndexingGenerator<C>` can be used as the result of `C`'s /// `generate()` method. For example: /// /// struct MyCollection : CollectionType { /// struct Index : ForwardIndexType { /* implementation hidden */ } /// subscript(i: Index) -> MyElement { /* implementation hidden */ } /// func generate() -> IndexingGenerator<MyCollection> { // <=== /// return IndexingGenerator(self) /// } /// } public struct IndexingGenerator<Elements : Indexable> : GeneratorType, SequenceType { /// Create a *generator* over the given collection. public init(_ elements: Elements) { self._elements = elements self._position = elements.startIndex } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Elements._Element? { return _position == _elements.endIndex ? .None : .Some(_elements[_position++]) } internal let _elements: Elements internal var _position: Elements.Index } /// A multi-pass *sequence* with addressable positions. /// /// Positions are represented by an associated `Index` type. Whereas /// an arbitrary *sequence* may be consumed as it is traversed, a /// *collection* is multi-pass: any element may be revisited merely by /// saving its index. /// /// The sequence view of the elements is identical to the collection /// view. In other words, the following code binds the same series of /// values to `x` as does `for x in self {}`: /// /// for i in startIndex..<endIndex { /// let x = self[i] /// } public protocol CollectionType : Indexable, SequenceType { /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. /// /// By default, a `CollectionType` satisfies `SequenceType` by /// supplying an `IndexingGenerator` as its associated `Generator` /// type. typealias Generator: GeneratorType = IndexingGenerator<Self> // FIXME: Needed here so that the Generator is properly deduced from // a custom generate() function. Otherwise we get an // IndexingGenerator. <rdar://problem/21539115> func generate() -> Generator // FIXME: should be constrained to CollectionType // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A `SequenceType` that can represent a contiguous subrange of `self`'s /// elements. /// /// - Note: This associated type appears as a requirement in /// `SequenceType`, but is restated here with stricter /// constraints: in a `CollectionType`, the `SubSequence` should /// also be a `CollectionType`. typealias SubSequence: Indexable, SequenceType = Slice<Self> /// Returns the element at the given `position`. subscript(position: Index) -> Generator.Element {get} /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence {get} /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result func prefixUpTo(end: Index) -> SubSequence /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result func suffixFrom(start: Index) -> SubSequence /// Returns `prefixUpTo(position.successor())` /// /// - Complexity: O(1) @warn_unused_result func prefixThrough(position: Index) -> SubSequence /// Returns `true` iff `self` is empty. var isEmpty: Bool { get } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`; /// O(N) otherwise. var count: Index.Distance { get } // The following requirement enables dispatching for indexOf when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(N). @warn_unused_result func _customIndexOfEquatableElement(element: Generator.Element) -> Index?? /// Returns the first element of `self`, or `nil` if `self` is empty. var first: Generator.Element? { get } } /// Supply the default `generate()` method for `CollectionType` models /// that accept the default associated `Generator`, /// `IndexingGenerator<Self>`. extension CollectionType where Generator == IndexingGenerator<Self> { public func generate() -> IndexingGenerator<Self> { return IndexingGenerator(self) } } /// Supply the default "slicing" `subscript` for `CollectionType` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension CollectionType where SubSequence == Slice<Self> { public subscript(bounds: Range<Index>) -> Slice<Self> { Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return Slice(base: self, bounds: bounds) } } extension CollectionType where SubSequence == Self { /// If `!self.isEmpty`, remove the first element and return it, otherwise /// return `nil`. /// /// - Complexity: O(`self.count`) @warn_unused_result public mutating func popFirst() -> Generator.Element? { guard !isEmpty else { return nil } let element = first! self = self[startIndex.successor()..<endIndex] return element } /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(`self.count`) @warn_unused_result public mutating func popLast() -> Generator.Element? { guard !isEmpty else { return nil } let lastElementIndex = startIndex.advancedBy(numericCast(count) - 1) let element = self[lastElementIndex] self = self[startIndex..<lastElementIndex] return element } } /// Default implementations of core requirements extension CollectionType { /// Returns `true` iff `self` is empty. /// /// - Complexity: O(1) public var isEmpty: Bool { return startIndex == endIndex } /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) public var first: Generator.Element? { return isEmpty ? nil : self[startIndex] } /// Returns a value less than or equal to the number of elements in /// `self`, *nondestructively*. /// /// - Complexity: O(N). public func underestimateCount() -> Int { return numericCast(count) } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`; /// O(N) otherwise. public var count: Index.Distance { return startIndex.distanceTo(endIndex) } /// Customization point for `SequenceType.indexOf()`. /// /// Define this method if the collection can find an element in less than /// O(N) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(N). @warn_unused_result public // dispatching func _customIndexOfEquatableElement(_: Generator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for CollectionType //===----------------------------------------------------------------------===// extension CollectionType { /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i++])) } _expectEnd(i, self) return Array(result) } /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = startIndex.advancedBy(numericCast(n), limit: endIndex) return self[start..<endIndex] } /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let amount = max(0, numericCast(count) - n) let end = startIndex.advancedBy(numericCast(amount), limit: endIndex) return self[startIndex..<end] } /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func prefix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = startIndex.advancedBy(numericCast(maxLength), limit: endIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = max(0, numericCast(count) - maxLength) let start = startIndex.advancedBy(numericCast(amount), limit: endIndex) return self[start..<endIndex] } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result public func prefixUpTo(end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result public func suffixFrom(start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns `prefixUpTo(position.successor())` /// /// - Complexity: O(1) @warn_unused_result public func prefixThrough(position: Index) -> SubSequence { return prefixUpTo(position.successor()) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( maxSplit: Int = Int.max, allowEmptySlices: Bool = false, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [SubSequence] { _precondition(maxSplit >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end end: Index) -> Bool { if subSequenceStart == end && !allowEmptySlices { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplit == 0 || isEmpty { appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) ++subSequenceEnd subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplit { break } continue } ++subSequenceEnd } if subSequenceStart != cachedEndIndex || allowEmptySlices { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension CollectionType where Generator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around a /// `separator` element. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( separator: Generator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { return split(maxSplit, allowEmptySlices: allowEmptySlices, isSeparator: { $0 == separator }) } } extension CollectionType where Index : BidirectionalIndexType { /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let end = endIndex.advancedBy(numericCast(-n), limit: startIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = endIndex.advancedBy(numericCast(-maxLength), limit: startIndex) return self[start..<endIndex] } } extension CollectionType where SubSequence == Self { /// Remove the element at `startIndex` and return it. /// /// - Complexity: O(1) /// - Requires: `!self.isEmpty`. public mutating func removeFirst() -> Generator.Element { _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[startIndex.successor()..<endIndex] return element } /// Remove the first `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndexType` /// - O(n) otherwise /// - Requires: `n >= 0 && self.count >= n`. public mutating func removeFirst(n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex.advancedBy(numericCast(n))..<endIndex] } } extension CollectionType where SubSequence == Self, Index : BidirectionalIndexType { /// Remove an element from the end. /// /// - Complexity: O(1) /// - Requires: `!self.isEmpty` public mutating func removeLast() -> Generator.Element { let element = last! self = self[startIndex..<endIndex.predecessor()] return element } /// Remove the last `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndexType` /// - O(n) otherwise /// - Requires: `n >= 0 && self.count >= n`. public mutating func removeLast(n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex..<endIndex.advancedBy(numericCast(-n))] } } extension SequenceType where Self : _ArrayType, Self.Element == Self.Generator.Element { // A fast implementation for when you are backed by a contiguous array. public func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> { let s = self._baseAddressIfContiguous if s != nil { let count = self.count ptr.initializeFrom(s, count: count) _fixLifetime(self._owner) return ptr + count } else { var p = ptr for x in self { p++.initialize(x) } return p } } } extension CollectionType { public func _preprocessingPass<R>(preprocess: (Self)->R) -> R? { return preprocess(self) } } /// Returns `true` iff `x` is empty. @available(*, unavailable, message="access the 'isEmpty' property on the collection") public func isEmpty<C: CollectionType>(x: C) -> Bool { fatalError("unavailable function can't be called") } /// Returns the first element of `x`, or `nil` if `x` is empty. @available(*, unavailable, message="access the 'first' property on the collection") public func first<C: CollectionType>(x: C) -> C.Generator.Element? { fatalError("unavailable function can't be called") } /// Returns the last element of `x`, or `nil` if `x` is empty. @available(*, unavailable, message="access the 'last' property on the collection") public func last<C: CollectionType where C.Index: BidirectionalIndexType>( x: C ) -> C.Generator.Element? { fatalError("unavailable function can't be called") } /// A *collection* that supports subscript assignment. /// /// For any instance `a` of a type conforming to /// `MutableCollectionType`, : /// /// a[i] = x /// let y = a[i] /// /// is equivalent to: /// /// a[i] = x /// let y = x /// public protocol MutableCollectionType : MutableIndexable, CollectionType { // FIXME: should be constrained to MutableCollectionType // (<rdar://problem/20715009> Implement recursive protocol // constraints) typealias SubSequence : CollectionType /*: MutableCollectionType*/ = MutableSlice<Self> /// Access the element at `position`. /// /// - Requires: `position` indicates a valid position in `self` and /// `position != endIndex`. /// /// - Complexity: O(1) subscript(position: Index) -> Generator.Element {get set} /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) for the getter, O(`bounds.count`) for the setter. subscript(bounds: Range<Index>) -> SubSequence {get set} /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape body: (UnsafeMutablePointer<Generator.Element>, Int) throws -> R ) rethrows -> R? // FIXME: the signature should use UnsafeMutableBufferPointer, but the // compiler can't handle that. // // <rdar://problem/21933004> Restore the signature of // _withUnsafeMutableBufferPointerIfSupported() that mentions // UnsafeMutableBufferPointer } extension MutableCollectionType { public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape body: (UnsafeMutablePointer<Generator.Element>, Int) throws -> R ) rethrows -> R? { return nil } public subscript(bounds: Range<Index>) -> MutableSlice<Self> { get { Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MutableSlice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } internal func _writeBackMutableSlice< Collection : MutableCollectionType, Slice_ : CollectionType where Collection._Element == Slice_.Generator.Element, Collection.Index == Slice_.Index >(inout self_: Collection, bounds: Range<Collection.Index>, slice: Slice_) { Collection.Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: self_.startIndex, boundsEnd: self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.startIndex let selfElementsEndIndex = bounds.endIndex var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] ++selfElementIndex ++newElementIndex } _precondition( selfElementIndex == selfElementsEndIndex, "Can not replace a slice of a MutableCollectionType with a slice of a larger size") _precondition( newElementIndex == newElementsEndIndex, "Can not replace a slice of a MutableCollectionType with a slice of a smaller size") } /// Returns the range of `x`'s valid index values. /// /// The result's `endIndex` is the same as that of `x`. Because /// `Range` is half-open, iterating the values of the result produces /// all valid subscript arguments for `x`, omitting its `endIndex`. @available(*, unavailable, message="access the 'indices' property on the collection") public func indices< C : CollectionType>(x: C) -> Range<C.Index> { fatalError("unavailable function can't be called") } /// A *generator* that adapts a *collection* `C` and any *sequence* of /// its `Index` type to present the collection's elements in a /// permuted order. public struct PermutationGenerator< C: CollectionType, Indices: SequenceType where C.Index == Indices.Generator.Element > : GeneratorType, SequenceType { var seq : C var indices : Indices.Generator /// The type of element returned by `next()`. public typealias Element = C.Generator.Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Element? { return indices.next().map { seq[$0] } } /// Construct a *generator* over a permutation of `elements` given /// by `indices`. /// /// - Requires: `elements[i]` is valid for every `i` in `indices`. public init(elements: C, indices: Indices) { self.seq = elements self.indices = indices.generate() } } /// A *collection* with mutable slices. /// /// For example, /// /// x[i..<j] = someExpression /// x[i..<j].mutatingMethod() public protocol MutableSliceable : CollectionType, MutableCollectionType { subscript(_: Range<Index>) -> SubSequence { get set } } @available(*, unavailable, message="Use the dropFirst() method instead.") public func dropFirst<Seq : CollectionType>(s: Seq) -> Seq.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the dropLast() method instead.") public func dropLast< S : CollectionType where S.Index: BidirectionalIndexType >(s: S) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the prefix() method.") public func prefix<S : CollectionType>(s: S, _ maxLength: Int) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the suffix() method instead.") public func suffix< S : CollectionType where S.Index: BidirectionalIndexType >(s: S, _ maxLength: Int) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="CollectionType") public struct Sliceable {}
b5be24fd3866ee85517404dc54ede7fe
32.606357
93
0.667661
false
false
false
false
airspeedswift/swift
refs/heads/master
test/attr/attr_originally_definedin_backward_compatibility.swift
apache-2.0
2
// REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios // UNSUPPORTED: DARWIN_SIMULATOR=ios // rdar://problem/64298096 // XFAIL: OS=ios && CPU=arm64 // rdar://problem/65399527 // XFAIL: OS=ios && CPU=armv7s // // RUN: %empty-directory(%t) // // ----------------------------------------------------------------------------- // --- Prepare SDK (.swiftmodule). // RUN: %empty-directory(%t/SDK) // // --- Build original high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevelOriginal.swift -Xlinker -install_name -Xlinker @rpath/HighLevel.framework/HighLevel -enable-library-evolution // --- Build an executable using the original high level framework // RUN: %target-build-swift -emit-executable %s -g -o %t/HighlevelRunner -F %t/SDK/Frameworks/ -framework HighLevel \ // RUN: %target-rpath(@executable_path/SDK/Frameworks) // --- Run the executable // RUN: %target-run %t/HighlevelRunner %t/SDK/Frameworks/HighLevel.framework/HighLevel | %FileCheck %s -check-prefix=BEFORE_MOVE // --- Build low level framework. // RUN: mkdir -p %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/LowLevel.framework/LowLevel) -module-name LowLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/LowLevel.swift -Xlinker -install_name -Xlinker @rpath/LowLevel.framework/LowLevel -enable-library-evolution // --- Build high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevel.swift -F %t/SDK/Frameworks -Xlinker -reexport_framework -Xlinker LowLevel -enable-library-evolution // --- Run the executable // RUN: %target-run %t/HighlevelRunner %t/SDK/Frameworks/HighLevel.framework/HighLevel %t/SDK/Frameworks/LowLevel.framework/LowLevel | %FileCheck %s -check-prefix=AFTER_MOVE import HighLevel printMessage() printMessageMoved() // BEFORE_MOVE: Hello from HighLevel // BEFORE_MOVE: Hello from HighLevel // AFTER_MOVE: Hello from LowLevel // AFTER_MOVE: Hello from LowLevel let e = Entity() print(e.location()) // BEFORE_MOVE: Entity from HighLevel // AFTER_MOVE: Entity from LowLevel print(CandyBox(Candy()).ItemKind) // BEFORE_MOVE: candy // AFTER_MOVE: candy print(CandyBox(Candy()).shape()) // BEFORE_MOVE: square // AFTER_MOVE: round print(LanguageKind.Cpp.rawValue) // BEFORE_MOVE: -1 // AFTER_MOVE: 1 print("\(Vehicle().currentSpeed)") // BEFORE_MOVE: -40 // AFTER_MOVE: 40 class Bicycle: Vehicle {} let bicycle = Bicycle() bicycle.currentSpeed = 15.0 print("\(bicycle.currentSpeed)") // BEFORE_MOVE: 15.0 // AFTER_MOVE: 15.0
244acd026f6c993d80f577e803fbf8f0
40
173
0.725083
false
false
false
false
MengQuietly/MQDouYuTV
refs/heads/master
MQDouYuTV/MQDouYuTV/Classes/Live/ViewModel/MQLiveCommonViewModel.swift
mit
1
// // MQLiveCommonViewModel.swift // MQDouYuTV // // Created by mengmeng on 17/1/5. // Copyright © 2017年 mengQuietly. All rights reserved. // MQLiveCommonViewModel import UIKit class MQLiveCommonViewModel: NSObject { // MARK:- 懒加载 /// common List lazy var commonLists:[MQLiveCommonModel] = [MQLiveCommonModel]() } // MARK:- 网络请求 extension MQLiveCommonViewModel{ // MARK: 获取直播:常用列表 func getCommonWithLiveList(finishCallBack: @escaping()->()) { let commonUrl = HOST_URL.appending(LIVE_GET_COMMON_LIST) // let commonDict = ["shortName":"game"] parameters:commonDict, MQNetworkingTool.sendRequest(url: commonUrl, succeed: { (responseObject, isBadNet) in // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)") guard let resultDict = responseObject as? [String:NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return} for dict in dataArray{ self.commonLists.append(MQLiveCommonModel(dict: dict)) } finishCallBack() }) { (error, isBadNet) in MQLog("error=\(error),isBadNet=\(isBadNet)") } } }
b166cc7df37b3755cd05be6ae89382cd
29.853659
93
0.617391
false
false
false
false
JGiola/swift
refs/heads/main
benchmark/single-source/ObserverPartiallyAppliedMethod.swift
apache-2.0
10
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 TestsUtils public let benchmarks = BenchmarkInfo( name: "ObserverPartiallyAppliedMethod", runFunction: run_ObserverPartiallyAppliedMethod, tags: [.validation], legacyFactor: 20) class Observer { @inline(never) func receive(_ value: Int) { } } class Signal { var observers: [(Int) -> ()] = [] func subscribe(_ observer: @escaping (Int) -> ()) { observers.append(observer) } func send(_ value: Int) { for observer in observers { observer(value) } } } public func run_ObserverPartiallyAppliedMethod(_ iterations: Int) { let signal = Signal() let observer = Observer() for _ in 0 ..< 500 * iterations { signal.subscribe(observer.receive) } signal.send(1) }
322b0c58dc3d243b77df3085cdf7d439
24.55102
80
0.595048
false
false
false
false
BetterVoice/phonertc
refs/heads/master
src/ios/WebSocket.swift
apache-2.0
1
import Foundation class WebSocket { // Cordova Stuff var plugin: PhoneRTCPlugin var callbackId: String // State Stuff var sessionKey: String // Web Socket Stuff. var socket: SRWebSocket? var socketDelegate: WebSocketDelegate var url: NSURL var protocols: [String]? init(url: String, protocols: [String]?, plugin: PhoneRTCPlugin, callbackId: String, sessionKey: String ) { self.url = NSURL(string: url)! self.protocols = protocols self.plugin = plugin self.callbackId = callbackId self.sessionKey = sessionKey let request = NSMutableURLRequest(URL: self.url) request.networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeVoIP if(self.protocols == nil) { self.socket = SRWebSocket(URLRequest: request) } else { self.socket = SRWebSocket(URLRequest: request, protocols: protocols) } self.socketDelegate = WebSocketDelegate(plugin: plugin, callbackId: callbackId) self.socket!.delegate = self.socketDelegate self.socket!.open() } func close(code: Int?, reason: String?) { if code != nil { self.socket!.closeWithCode(code!, reason: reason) } else { self.socket!.close() } self.plugin.destroyWebSocket(self.sessionKey) } func send(data: AnyObject) { self.socket!.send(data) } }
afbbfb623424d228db16b8fe08553320
29.08
90
0.612109
false
false
false
false
Dougly/2For1
refs/heads/master
2for1/CheckMarkView.swift
mit
1
// // CheckMarkView.swift // 2for1 // // Created by Douglas Galante on 2/6/17. // Copyright © 2017 Flatiron. All rights reserved. // import UIKit class CheckMarkView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var checkBackgroundView: UIView! @IBOutlet weak var checkImageView: UIImageView! @IBOutlet weak var restartLabel: UILabel! @IBOutlet weak var shadowView: UIView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { Bundle.main.loadNibNamed("CheckMarkView", owner: self, options: nil) self.addSubview(contentView) self.constrain(contentView) } func setCornerRadius(with size: CGFloat) { let constraintMultiplier: CGFloat = 1 let cornerRadius = (size * constraintMultiplier) / 2 checkBackgroundView.layer.cornerRadius = cornerRadius checkImageView.layer.cornerRadius = cornerRadius shadowView.layer.cornerRadius = cornerRadius } }
ea74eddbbcf675080c8d0be5dac46008
23.645833
76
0.647506
false
false
false
false
ianfelzer1/ifelzer-advprog
refs/heads/master
Last Year/IOS Development- J Term 2017/WordCollage-lesson01/WordCollage/ViewController.swift
gpl-3.0
1
/* This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, by Yong Bakos. */ 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. } @IBAction func changeBackgroundColorFromSwitch(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: self.view.backgroundColor = UIColor.red case 1: self.view.backgroundColor = UIColor.orange case 2: self.view.backgroundColor = UIColor.yellow case 3: self.view.backgroundColor = UIColor.green case 4: self.view.backgroundColor = UIColor.blue default: break } } }
e0bf985ff4070e22d5350082c0024ec0
25.578947
83
0.652475
false
false
false
false
631106979/WCLImagePickerController
refs/heads/master
WCLImagePickerController/WCLImagePickerController/Others/WCLPickerManager.swift
mit
1
// // WCLPickerManager.swift // WCLImagePickrController-swift // // ************************************************** // * _____ * // * __ _ __ ___ \ / * // * \ \/ \/ / / __\ / / * // * \ _ / | (__ / / * // * \/ \/ \___/ / /__ * // * /_____/ * // * * // ************************************************** // Github :https://github.com/631106979 // HomePage:https://imwcl.com // CSDN :http://blog.csdn.net/wang631106979 // // Created by 王崇磊 on 16/9/14. // Copyright © 2016年 王崇磊. All rights reserved. // // @class WCLPickerManager // @abstract WCLPicker的管理类 // @discussion 通过这个类来获取照片和相册 // import UIKit import Photos public class WCLPickerManager: NSObject { //全部相册的数组 private(set) var photoAlbums = [[String: PHFetchResult<PHAsset>]]() private(set) var selectPhotoArr = [PHAsset]() //是否同步请求图片 public var isSynchronous: Bool = false { didSet{ self.photoOption.isSynchronous = isSynchronous } } //pickerCell照片的size class public var pickerPhotoSize: CGSize { assert(WCLImagePickerOptions.photoLineNum > 2, "列数最小为2") let sreenBounds = UIScreen.main.bounds let screenWidth = sreenBounds.width > sreenBounds.height ? sreenBounds.height : sreenBounds.width let width = (screenWidth - CGFloat(WCLImagePickerOptions.photoInterval) * (CGFloat(WCLImagePickerOptions.photoLineNum) - 1)) / CGFloat(WCLImagePickerOptions.photoLineNum) return CGSize(width: width, height: width) } private var photoManage = PHCachingImageManager() private let photoOption = PHImageRequestOptions() private let photoCreationDate = "creationDate" //MARK: Override override init() { super.init() //图片请求设置成快速获取 self.photoOption.resizeMode = .fast self.photoOption.deliveryMode = .opportunistic getPhotoAlbum() } //MARK: Public Methods /** 获取相册的title - parameter index: 相册的index - returns: 相册的title */ public func getAblumTitle(_ ablumIndex: Int) -> String { if let ablum = self.photoAlbums[wcl_safe: ablumIndex] { if let result = ablum.keys.first { return "\(result)(\(getAblumCount(ablumIndex)))" } } return "" } //MARK: photo数据的操作 /** 通过下标返回相册中照片的个数 - parameter index: 选择的index - returns: 相册中照片的个数 */ public func getAblumCount(_ ablumIndex: Int) -> Int { if let ablum = self.photoAlbums[wcl_safe: ablumIndex] { if let result = ablum.values.first { return result.count } } return 0 } /** 通过下标返回相册的PHFetchResult - parameter index: 选择相册的index - returns: 相册的PHFetchResult */ public func getAblumResult(_ ablumIndex: Int) -> PHFetchResult<PHAsset>? { if let ablum = self.photoAlbums[wcl_safe: ablumIndex] { if let result = ablum.values.first { return result } } return nil } /** 根据index获取PHAsset - parameter ablumIndex: 相册的index - parameter photoIndex: 相册里图片的index - returns: PHAsset */ public func getPHAsset(_ ablumIndex: Int, photoIndex: Int) -> PHAsset? { let ablumResult = getAblumResult(ablumIndex) if ablumResult != nil { if ablumResult?.count != 0 { let photoAsset:PHAsset? = ablumResult![photoIndex] return photoAsset } } return nil } /** PHAsset是否已经在SelectPhotoArr里 - parameter alasset: PHAsset对象 - returns: 返回值 */ public func isContains(formSelect alasset: PHAsset) -> Bool { return selectPhotoArr.contains(alasset) } /** PHAsset在SelectPhotoArr的index - parameter alasset: PHAsset对象 - returns: PHAsset在选择的数组的index */ public func index(ofSelect alasset: PHAsset) -> Int? { return selectPhotoArr.index(of: alasset) } /** 删除SelectPhotoArr里的PHAsset - parameter alasset: PHAsset对象 */ func remove(formSelect alasset: PHAsset) { if let index = index(ofSelect: alasset) { selectPhotoArr.wcl_removeSafe(at: index) } } /** 添加PHAsset到SelectPhotoArr - parameter alasset: 要添加的PHAsset */ public func append(toSelect alasset: PHAsset) { selectPhotoArr.append(alasset) } //MARK: 通过请求获取photo的数据 /** 根据index获取photo - parameter ablumIndex: 相册的index - parameter photoIndex: 相册里图片的index - parameter photoSize: 图片的size - parameter resultHandler: 返回照片的回调 */ public func getPhoto(_ ablumIndex: Int, photoIndex: Int, photoSize: CGSize, resultHandler: ((UIImage?, [AnyHashable: Any]?) -> Void)?) { let photoAsset:PHAsset? = getPHAsset(ablumIndex, photoIndex: photoIndex) if photoAsset != nil { let scale = UIScreen.main.scale let photoScaleSize = CGSize(width: photoSize.width*scale, height: photoSize.height*scale) self.photoManage.requestImage(for: photoAsset!, targetSize: photoScaleSize, contentMode: .aspectFill, options: self.photoOption, resultHandler: { (image, infoDic) in if image != nil { resultHandler?(image, infoDic) }else { let image_buffer = WCLImagePickerBundle.imageFromBundle("image-buffer") resultHandler?(image_buffer, infoDic) } }) } } /** 根据PHAsset获取photo - parameter ablumIndex: 相册的index - parameter alasset: 相册里图片的PHAsset - parameter photoSize: 图片的size - parameter resultHandler: 返回照片的回调 */ public func getPhoto(_ photoSize: CGSize, alasset: PHAsset?, resultHandler: ((UIImage?, [AnyHashable: Any]?) -> Void)?) { if alasset != nil { let scale = UIScreen.main.scale let photoScaleSize = CGSize(width: photoSize.width*scale, height: photoSize.height*scale) self.photoManage.requestImage(for: alasset!, targetSize: photoScaleSize, contentMode: .aspectFill, options: self.photoOption, resultHandler: { (image, infoDic) in if image != nil { resultHandler?(image, infoDic) }else { let image_buffer = WCLImagePickerBundle.imageFromBundle("image-buffer") resultHandler?(image_buffer, infoDic) } }) } } /** 根据PHAsset获取photo的元数据 - parameter alasset: 相册里图片的PHAsset - parameter resultHandler: 返回照片元数据的回调 */ public func getPhotoData(alasset: PHAsset?, resultHandler: ((Data?, UIImageOrientation) -> Void)?) { if alasset != nil { self.photoManage.requestImageData(for: alasset!, options: nil, resultHandler: { (data, str, orientation, hashable) in resultHandler?(data, orientation) }) } } /** 获取默认大小的图片 */ public func getPhotoDefalutSize(_ ablumIndex: Int, photoIndex: Int, resultHandler: ((UIImage?, [AnyHashable: Any]?) -> Void)?) { getPhoto(ablumIndex, photoIndex: photoIndex, photoSize: WCLPickerManager.pickerPhotoSize, resultHandler: resultHandler) } //MARK: Private Methods /** 开始获取获取相册列表 */ private func getPhotoAlbum() { //创建一个PHFetchOptions对象检索照片 let options = PHFetchOptions() //通过创建时间来检索 options.sortDescriptors = [NSSortDescriptor.init(key: photoCreationDate, ascending: false)] //通过数据类型来检索,这里为只检索照片 options.predicate = NSPredicate.init(format: "mediaType in %@", [PHAssetMediaType.image.rawValue]) //通过检索条件检索出符合检索条件的所有数据,也就是所有的照片 let allResult = PHAsset.fetchAssets(with: options) //获取用户创建的相册 let userResult = PHAssetCollection.fetchTopLevelUserCollections(with: nil) //获取智能相册 let smartResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) //将获取的相册加入到相册的数组中 photoAlbums.append([WCLImagePickerBundle.localizedString(key: "全部照片"): allResult]) userResult.enumerateObjects(options: .concurrent) { (collection, index, stop) in let assetcollection = collection as! PHAssetCollection //通过检索条件从assetcollection中检索出结果 let assetResult = PHAsset.fetchAssets(in: assetcollection, options: options) if assetResult.count != 0 { self.photoAlbums.append([assetcollection.localizedTitle!:assetResult]) } } smartResult.enumerateObjects(options: .concurrent) { (collection, index, stop) in //通过检索条件从assetcollection中检索出结果 let assetResult = PHAsset.fetchAssets(in: collection, options: options) if assetResult.count != 0 { self.photoAlbums.append([collection.localizedTitle!:assetResult]) } } } }
3441a9e40988ca59961ce131d014a696
32.516014
178
0.578891
false
false
false
false
CD1212/Doughnut
refs/heads/master
Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeedAuthor.swift
gpl-3.0
2
// // AtomFeedAuthor.swift // // Copyright (c) 2017 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /// The "atom:author" element is a Person construct that indicates the /// author of the entry or feed. /// /// If an atom:entry element does not contain atom:author elements, then /// the atom:author elements of the contained atom:source element are /// considered to apply. In an Atom Feed Document, the atom:author /// elements of the containing atom:feed element are considered to apply /// to the entry if there are no atom:author elements in the locations /// described above. public class AtomFeedAuthor { /// The "atom:name" element's content conveys a human-readable name for /// the person. The content of atom:name is Language-Sensitive. Person /// constructs MUST contain exactly one "atom:name" element. public var name: String? /// The "atom:email" element's content conveys an e-mail address /// associated with the person. Person constructs MAY contain an /// atom:email element, but MUST NOT contain more than one. Its content /// MUST conform to the "addr-spec" production in [RFC2822]. public var email: String? /// The "atom:uri" element's content conveys an IRI associated with the /// person. Person constructs MAY contain an atom:uri element, but MUST /// NOT contain more than one. The content of atom:uri in a Person /// construct MUST be an IRI reference [RFC3987]. public var uri: String? } // MARK: - Equatable extension AtomFeedAuthor: Equatable { public static func ==(lhs: AtomFeedAuthor, rhs: AtomFeedAuthor) -> Bool { return lhs.name == rhs.name && lhs.email == rhs.email && lhs.uri == rhs.uri } }
d5952d5d9f9fa762b11e14e60886ef7d
41.088235
82
0.707547
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClient/Sources/Requests/Creation/FetchCreationsForHubResponseHandler.swift
mit
1
// // FetchCreationsForHubResponseHandler.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ObjectMapper class FetchCreationsForHubResponseHandler: ResponseHandler { fileprivate let completion: CreationsClosure? init(completion: CreationsClosure?) { self.completion = completion } override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) { if let response = response, let mappers = Mapper<CreationMapper>().mapArray(JSONObject: response["data"]) { let metadata = MappingUtils.metadataFromResponse(response) let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata) let creations = mappers.map({ Creation(mapper: $0, dataMapper: dataMapper, metadata: metadata) }) executeOnMainQueue { self.completion?(creations, nil, ErrorTransformer.errorFromResponse(response, error: error)) } } else { executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) } } } }
c6a20a0bb4b592753af8a8143dd486c0
47.021277
127
0.724413
false
false
false
false
mmllr/CleanTweeter
refs/heads/master
CleanTweeter/UseCases/TweetList/Interactor/TweetListInteractor.swift
mit
1
import Foundation class TweetListInteractor: TweetListInteractorInput { var output: TweetListInteractorOutput? var repository: UserRepository let dateFormatter: DateComponentsFormatter init(repository: UserRepository) { self.repository = repository let formatter = DateComponentsFormatter() formatter.unitsStyle = .abbreviated formatter.allowedUnits = [.year, .day, .hour, .minute] formatter.maximumUnitCount = 1 self.dateFormatter = formatter } func requestTweetsForUserName(_ userName:String) { if let user = self.repository.findUser(userName) { let followedUserTweets: [[Tweet]] = user.followedUsers.map { if let follower = self.repository.findUser($0) { return follower.tweets } return [] } let sortedTweets = (user.tweets + followedUserTweets.flatMap{ $0 }).sorted() let result: [TweetListResponseModel] = sortedTweets.map { if let avatar = repository.findUser($0.author)?.avatar { return TweetListResponseModel(user: $0.author, content: $0.content, age: self.dateFormatter.string(from: $0.publicationDate, to: Date())!, avatar: avatar) } return TweetListResponseModel(user: $0.author, content: $0.content, age: self.dateFormatter.string(from: $0.publicationDate, to: Date())!, avatar: "") } output?.foundTweets(result) } } }
3820235afed7f462cd6ae6e597567f41
33.526316
159
0.730183
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Auxiliary Components/Settings/SettingsTableViewC.swift
mit
1
// // SettingsTableViewC.swift // BlocFit // // Created by Colin Conduff on 10/1/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class SettingsTableViewC: UITableViewController { @IBOutlet weak var unitsLabel: UILabel! @IBOutlet weak var fbLoginView: UIView! @IBOutlet weak var newFriendsSettingLabel: UILabel! @IBOutlet weak var shareFirstNameLabel: UILabel! var controller: SettingsControllerProtocol! { didSet { controller.unitsDidChange = { [unowned self] controller in self.unitsLabel?.text = controller.units } controller.defaultTrustedDidChange = { [unowned self] controller in self.newFriendsSettingLabel?.text = controller.defaultTrusted } controller.shareFirstNameDidChange = { [unowned self] controller in self.shareFirstNameLabel?.text = controller.shareFirstName } } } override func viewDidLoad() { super.viewDidLoad() self.controller = SettingsController() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() controller.resetLabelValues() setUpFB() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } struct Loc { static let friendsDefaultToTrustedCell = (sec: 1, row: 0) static let shareNameCell = (sec: 2, row: 0) static let unitConversionCell = (sec: 3, row: 0) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == Loc.unitConversionCell.sec && indexPath.row == Loc.unitConversionCell.row { controller.toggleUnitsSetting() } else if indexPath.section == Loc.friendsDefaultToTrustedCell.sec && indexPath.row == Loc.friendsDefaultToTrustedCell.row { controller.toggleTrustedDefaultSetting() } else if indexPath.section == Loc.shareNameCell.sec && indexPath.row == Loc.shareNameCell.row { controller.toggleShareFirstNameSetting() } tableView.deselectRow(at: indexPath, animated: true) } func setUpFB() { let loginButton = FBSDKLoginButton() loginButton.center = fbLoginView.center fbLoginView.addSubview(loginButton) // Move to FB View Model loginButton.readPermissions = [ "public_profile" ] FBSDKProfile.enableUpdates(onAccessTokenChange: true) } }
a427f4991eda31bc4ffb1691fb00b9fa
30.241758
79
0.614492
false
false
false
false
XCEssentials/FunctionalState
refs/heads/master
Sources/Declare/State.swift
mit
2
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** Special container object that represents a single state for 'Subject' type. */ struct State<Subject: AnyObject> { /** Internal state identifier that helps to distinguish one state from another. It is supposed to be unique per stateful object, regardless of the rest of the state internal member values. */ let identifier: StateIdentifier /** A helper typealias that represents Subject-specific pure mutation combined with transition that is supposed to be used to apply that mutation. */ typealias MutationWithTransition = (mutation: BasicClosure, transition: Transition<Subject>) /** Mutation and transition that must be used to apply this state (when this state is NOT current yet, or current state is undefined yet, to make it current). */ let onSet: MutationWithTransition /** Mutation and transition that must be used to apply this state when this state IS already current. This might be useful to update some parameters that the state captures from the outer scope when gets called/created, while entire state stays the same. */ let onUpdate: MutationWithTransition? //--- /** The only designated constructor, intentionally inaccessible from outer scope to make the static `state(...)` functions of `Stateful` protocol exclusive way of defining states for a given class. */ init( identifier: String, onSet: MutationWithTransition, onUpdate: MutationWithTransition? ) { self.identifier = identifier self.onSet = onSet self.onUpdate = onUpdate } } //--- extension State: Equatable { public static func == (left: State, right: State) -> Bool { return left.identifier == right.identifier } }
2f81b843f23ce800100818932d6f3522
35.518519
255
0.719067
false
false
false
false
ngquerol/Diurna
refs/heads/master
App/Sources/Views/SelfSizingTextView.swift
mit
1
// // SelfSizingTextView.swift // Diurna // // Created by Nicolas Gaulard-Querol on 08/01/2018. // Copyright © 2018 Nicolas Gaulard-Querol. All rights reserved. // import AppKit @IBDesignable class SelfSizingTextView: NSTextView { // MARK: Properties override var intrinsicContentSize: NSSize { guard let container = textContainer, let manager = layoutManager else { return NSSize(width: NSView.noIntrinsicMetric, height: NSView.noIntrinsicMetric) } guard attributedStringValue.length > 0 else { return .zero } let availableWidth = frame.width - textContainerInset.width container.size = NSSize(width: availableWidth, height: .greatestFiniteMagnitude) manager.ensureLayout(for: container) let boundingRect = manager.usedRect(for: container) return NSSize( width: NSView.noIntrinsicMetric, height: boundingRect.height + textContainerInset.height ) } override var string: String { didSet { invalidateIntrinsicContentSize() } } override var attributedStringValue: NSAttributedString { didSet { invalidateIntrinsicContentSize() } } // MARK: Methods override func layout() { super.layout() invalidateIntrinsicContentSize() } override func didChangeText() { super.didChangeText() invalidateIntrinsicContentSize() } }
b70986f4b218e90d684659a19a403c7d
22.84375
92
0.632372
false
false
false
false
SunChJ/functional-swift
refs/heads/master
Fundational-Swift/FilterDemo/FilterDefine.swift
mit
1
// // FilterDefine.swift // FilterDemo // // Created by 孙超杰 on 2017/3/2. // Copyright © 2017年 Chaojie Sun. All rights reserved. // import UIKit // 定义Filter类型为一个函数 typealias Filter = (CIImage) -> CIImage // 构建滤镜 //func myFilter(/*parameters*/) -> Filter // 模糊滤镜 func blur(radius: Double) -> Filter { return { image in let parameters = [ kCIInputRadiusKey: radius, kCIInputImageKey: image ] as [String : Any] guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} return outputImage } } // 颜色叠层(固定颜色+定义合成滤镜) // 生产固定颜色的滤镜 func colorGenerator(color: UIColor) -> Filter { return { _ in let c = CIColor(color: color) let parameters = [kCIInputColorKey: c] guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} return outputImage } } // 定义合成滤镜 func compositeSourceOver(overlay: CIImage) -> Filter { return { image in let parameters = [ kCIInputBackgroundImageKey: image, kCIInputImageKey: overlay ] guard let filter = CIFilter(name: "CISourceOverCompositing", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} let cropRect = image.extent return outputImage.cropping(to: cropRect) } } // 最后的合成 func colorOverlay(color: UIColor) -> Filter { return { image in let overlay = colorGenerator(color: color)(image) return compositeSourceOver(overlay: overlay)(image) } } // 定义一个用于组合滤镜的函数 func composeFilter(filter1: @escaping Filter, _ filter2: @escaping Filter) -> Filter { return { image in filter2(filter1(image))} } // 自定义运算符 // 为了让代码更具有可读性, 我们可以再进一步, 为组合滤镜引入运算符 // 诚然, 随意自定义运算符并不一定对提升代码可读性有帮助。不过,在图像处理库中, 滤镜的组合式一个反复背讨论的问题, 所以引入运算符极有意义 precedencegroup FilterCopositivePrecedence { associativity: left higherThan: MultiplicationPrecedence } infix operator >>>: FilterCopositivePrecedence func >>>(filter1: @escaping Filter, filter2: @escaping Filter) -> Filter { return {image in filter2(filter1(image))} }
5df951867359a39714a61a26265c0858
27.756098
122
0.677693
false
false
false
false
sotownsend/flok-apple
refs/heads/master
Example/flok/PipeViewController.swift
mit
1
//Provides the remote pipe used in testing that talks directly to the JS environment import Foundation import CocoaAsyncSocket import flok class PipeViewController : UIViewController, GCDAsyncSocketDelegate, FlokEnginePipeDelegate, FlokEngineDelegate { var socketQueue: dispatch_queue_t! = nil var listenSocket: GCDAsyncSocket! = nil var connectedSockets: NSMutableArray! = nil var flok: FlokEngine! = nil static var sharedInstance: PipeViewController! override func viewDidLoad() { PipeViewController.sharedInstance = self socketQueue = dispatch_queue_create("socketQueue", nil) listenSocket = GCDAsyncSocket(delegate: self, delegateQueue: socketQueue) do { try listenSocket!.acceptOnPort(6969) } catch { NSException.raise("PipeViewControllerSocketListenError", format: "Could not listen on port 6969", arguments: getVaList([])) } connectedSockets = NSMutableArray(capacity: 9999) let srcPath = NSBundle.mainBundle().pathForResource("app", ofType: "js") let srcData = NSData(contentsOfFile: srcPath!) let src = NSString(data: srcData!, encoding: NSUTF8StringEncoding) as! String flok = FlokEngine(src: src, inPipeMode: true) flok.delegate = self flok.pipeDelegate = self flok.ready() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Override point for customization after application launch. // FlokViewConceierge.preload() } func socket(sock: GCDAsyncSocket!, didAcceptNewSocket newSocket: GCDAsyncSocket!) { dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in if (self == nil) { return } NSLog("Accepted host, id: \(self!.connectedSockets!.count-1)") self!.connectedSockets.addObject(newSocket) let helloPayload = NSString(string: "HELLO\r\n").dataUsingEncoding(NSUTF8StringEncoding) newSocket.writeData(helloPayload, withTimeout: -1, tag: 0) newSocket.readDataWithTimeout(-1, tag: 0) } } var stream: NSString = "" func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String stream = stream.stringByAppendingString(str) let process = { (e: String) in do { var out: AnyObject try out = NSJSONSerialization.JSONObjectWithData(e.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData(), options: NSJSONReadingOptions.AllowFragments) as AnyObject dispatch_async(dispatch_get_main_queue(), { if let out = out as? [AnyObject] { self.flok.if_dispatch(out) } else { NSLog("Couldn't parse out: \(out)") } }) } catch let error { NSLog("failed to parse JSON...: \(str), \(error)") } } let components = stream.componentsSeparatedByString("\r\n") for (i, e) in components.enumerate() { if i == components.count-1 { stream = NSString(string: e) } else { process(e) } } sock.readDataWithTimeout(-1, tag: 0) } //The engine, which is just stubbed atm, received a request (which is just forwarded externally for now) func flokEngineDidReceiveIntDispatch(q: [AnyObject]) { //Send out to 'stdout' of network pipe let lastSocket = connectedSockets.lastObject if let lastSocket = lastSocket { do { var payload: NSData? try payload = NSJSONSerialization.dataWithJSONObject(q, options: NSJSONWritingOptions(rawValue: 0)) if let payload = payload { lastSocket.writeData(payload, withTimeout: -1, tag: 0) lastSocket.writeData(("\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding), withTimeout: -1, tag: 0) } else { puts("couldn't convert object \(q) into JSON") } } catch { puts("Couldn't create payload for int_dispatch to send to pipe") } } } //----------------------------------------------------------------------------------------------------- //FlokEngineDelegate //----------------------------------------------------------------------------------------------------- func flokEngineRootView(engine: FlokEngine) -> UIView { return self.view } func flokEngine(engine: FlokEngine, didPanicWithMessage message: String) { NSLog("flok engine panic: \(message)") } }
e0ceebe950bdfa13d15f4036d0b9630c
39.770492
178
0.567464
false
false
false
false
MattFoley/IQKeyboardManager
refs/heads/master
KeyboardTextFieldDemo/IQKeyboardManager Swift/SpecialCaseViewController.swift
mit
3
// // SpecialCaseViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKIt class SpecialCaseViewController: UIViewController, UISearchBarDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet private var textField6 : UITextField!; @IBOutlet private var textField7 : UITextField!; @IBOutlet private var textField8 : UITextField!; @IBOutlet private var switchInteraction1 : UISwitch!; @IBOutlet private var switchInteraction2 : UISwitch!; @IBOutlet private var switchInteraction3 : UISwitch!; @IBOutlet private var switchEnabled1 : UISwitch!; @IBOutlet private var switchEnabled2 : UISwitch!; @IBOutlet private var switchEnabled3 : UISwitch!; override func viewDidLoad() { super.viewDidLoad() textField6.userInteractionEnabled = switchInteraction1.on; textField7.userInteractionEnabled = switchInteraction2.on; textField8.userInteractionEnabled = switchInteraction3.on; textField6.enabled = switchEnabled1.on; textField7.enabled = switchEnabled2.on; textField8.enabled = switchEnabled3.on; updateUI() } @IBAction func showAlertClicked (barButton : UIBarButtonItem!) { var alertView : UIAlertView = UIAlertView(title: "IQKeyboardManager", message: "It doesn't affect UIAlertView (Doesn't add IQToolbar on it's textField", delegate: nil, cancelButtonTitle: "OK") alertView.alertViewStyle = UIAlertViewStyle.LoginAndPasswordInput alertView.show() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func updateUI() { textField6.placeholder = (textField6.enabled ? "enabled" : "" ) + "," + (textField6.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField7.placeholder = (textField7.enabled ? "enabled" : "" ) + "," + (textField7.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField8.placeholder = (textField8.enabled ? "enabled" : "" ) + "," + (textField8.userInteractionEnabled ? "userInteractionEnabled" : "" ) } func switch1UserInteractionAction(sender: UISwitch) { textField6.userInteractionEnabled = sender.on; updateUI() } func switch2UserInteractionAction(sender: UISwitch) { textField7.userInteractionEnabled = sender.on; updateUI() } func switch3UserInteractionAction(sender: UISwitch) { textField8.userInteractionEnabled = sender.on; updateUI() } func switch1Action(sender: UISwitch) { textField6.enabled = sender.on; updateUI() } func switch2Action(sender: UISwitch) { textField7.enabled = sender.on; updateUI() } func switch3Action(sender: UISwitch) { textField8.enabled = sender.on; updateUI() } func textFieldDidBeginEditing(textField: UITextField) { switchEnabled1.enabled = false; switchEnabled2.enabled = false; switchEnabled3.enabled = false; switchInteraction1.enabled = false; switchInteraction2.enabled = false; switchInteraction3.enabled = false; } func textFieldDidEndEditing(textField: UITextField) { switchEnabled1.enabled = true; switchEnabled2.enabled = true; switchEnabled3.enabled = true; switchInteraction1.enabled = true; switchInteraction2.enabled = true; switchInteraction3.enabled = true; } }
51b788c5ae6869ba3dc14927ab5d2c38
34.035714
200
0.67788
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/ColorSpace/ColorSpaceBase/CalibratedRGBColorSpace/AdobeRGB.swift
mit
1
// // AdobeRGB.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @usableFromInline final class _adobeRGB: CalibratedGammaRGBColorSpace { @inlinable init() { super.init(CIEXYZColorSpace(white: CIE1931.D65.rawValue, luminance: 160.00, contrastRatio: 287.9), red: Point(x: 0.6400, y: 0.3300), green: Point(x: 0.2100, y: 0.7100), blue: Point(x: 0.1500, y: 0.0600), gamma: (2.19921875, 2.19921875, 2.19921875)) } @inlinable override var localizedName: String? { return "Adobe RGB (1998)" } @inlinable override func __equalTo(_ other: CalibratedRGBColorSpace) -> Bool { return type(of: other) == _adobeRGB.self } @inlinable override func hash(into hasher: inout Hasher) { hasher.combine("CalibratedRGBColorSpace") hasher.combine(".adobeRGB") } } extension ColorSpace where Model == RGBColorModel { public static let adobeRGB = ColorSpace(base: _adobeRGB()) }
6a79dc70f1210fcb78bdc0e7e92b469d
36.672414
106
0.678261
false
false
false
false
CodaFi/SwiftCheck
refs/heads/master
Sources/SwiftCheck/WitnessedArbitrary.swift
mit
1
// // WitnessedArbitrary.swift // SwiftCheck // // Created by Robert Widmann on 12/15/15. // Copyright © 2016 Typelift. All rights reserved. // extension Array : Arbitrary where Element : Arbitrary { /// Returns a generator of `Array`s of arbitrary `Element`s. public static var arbitrary : Gen<Array<Element>> { return Element.arbitrary.proliferate } /// The default shrinking function for `Array`s of arbitrary `Element`s. public static func shrink(_ bl : Array<Element>) -> [[Element]] { let rec : [[Element]] = shrinkOne(bl) return Int.shrink(bl.count).reversed().flatMap({ k in removes((k + 1), n: bl.count, xs: bl) }) + rec } } extension AnyBidirectionalCollection : Arbitrary where Element : Arbitrary { /// Returns a generator of `AnyBidirectionalCollection`s of arbitrary `Element`s. public static var arbitrary : Gen<AnyBidirectionalCollection<Element>> { return [Element].arbitrary.map(AnyBidirectionalCollection.init) } /// The default shrinking function for `AnyBidirectionalCollection`s of arbitrary `Element`s. public static func shrink(_ bl : AnyBidirectionalCollection<Element>) -> [AnyBidirectionalCollection<Element>] { return [Element].shrink([Element](bl)).map(AnyBidirectionalCollection.init) } } extension AnySequence : Arbitrary where Element : Arbitrary { /// Returns a generator of `AnySequence`s of arbitrary `Element`s. public static var arbitrary : Gen<AnySequence<Element>> { return [Element].arbitrary.map(AnySequence.init) } /// The default shrinking function for `AnySequence`s of arbitrary `Element`s. public static func shrink(_ bl : AnySequence<Element>) -> [AnySequence<Element>] { return [Element].shrink([Element](bl)).map(AnySequence.init) } } extension ArraySlice : Arbitrary where Element : Arbitrary { /// Returns a generator of `ArraySlice`s of arbitrary `Element`s. public static var arbitrary : Gen<ArraySlice<Element>> { return [Element].arbitrary.map(ArraySlice.init) } /// The default shrinking function for `ArraySlice`s of arbitrary `Element`s. public static func shrink(_ bl : ArraySlice<Element>) -> [ArraySlice<Element>] { return [Element].shrink([Element](bl)).map(ArraySlice.init) } } extension CollectionOfOne : Arbitrary where Element : Arbitrary { /// Returns a generator of `CollectionOfOne`s of arbitrary `Element`s. public static var arbitrary : Gen<CollectionOfOne<Element>> { return Element.arbitrary.map(CollectionOfOne.init) } } /// Generates an Optional of arbitrary values of type A. extension Optional : Arbitrary where Wrapped : Arbitrary { /// Returns a generator of `Optional`s of arbitrary `Wrapped` values. public static var arbitrary : Gen<Optional<Wrapped>> { return Gen<Optional<Wrapped>>.frequency([ (1, Gen<Optional<Wrapped>>.pure(.none)), (3, liftM(Optional<Wrapped>.some, Wrapped.arbitrary)), ]) } /// The default shrinking function for `Optional`s of arbitrary `Wrapped`s. public static func shrink(_ bl : Optional<Wrapped>) -> [Optional<Wrapped>] { if let x = bl { let rec : [Optional<Wrapped>] = Wrapped.shrink(x).map(Optional<Wrapped>.some) return [.none] + rec } return [] } } extension ContiguousArray : Arbitrary where Element : Arbitrary { /// Returns a generator of `ContiguousArray`s of arbitrary `Element`s. public static var arbitrary : Gen<ContiguousArray<Element>> { return [Element].arbitrary.map(ContiguousArray.init) } /// The default shrinking function for `ContiguousArray`s of arbitrary `Element`s. public static func shrink(_ bl : ContiguousArray<Element>) -> [ContiguousArray<Element>] { return [Element].shrink([Element](bl)).map(ContiguousArray.init) } } /// Generates an dictionary of arbitrary keys and values. extension Dictionary : Arbitrary where Key : Arbitrary, Value : Arbitrary { /// Returns a generator of `Dictionary`s of arbitrary `Key`s and `Value`s. public static var arbitrary : Gen<Dictionary<Key, Value>> { return [Key].arbitrary.flatMap { (k : [Key]) in return [Value].arbitrary.flatMap { (v : [Value]) in return Gen.pure(Dictionary(zip(k, v)) { $1 }) } } } /// The default shrinking function for `Dictionary`s of arbitrary `Key`s and /// `Value`s. public static func shrink(_ d : Dictionary<Key, Value>) -> [Dictionary<Key, Value>] { return d.map { t in Dictionary(zip(Key.shrink(t.key), Value.shrink(t.value)), uniquingKeysWith: { (_, v) in v }) } } } extension EmptyCollection : Arbitrary { /// Returns a generator of `EmptyCollection`s of arbitrary `Element`s. public static var arbitrary : Gen<EmptyCollection<Element>> { return Gen.pure(EmptyCollection()) } } extension Range : Arbitrary where Bound : Arbitrary { /// Returns a generator of `HalfOpenInterval`s of arbitrary `Bound`s. public static var arbitrary : Gen<Range<Bound>> { return Bound.arbitrary.flatMap { l in return Bound.arbitrary.flatMap { r in return Gen.pure((Swift.min(l, r) ..< Swift.max(l, r))) } } } /// The default shrinking function for `HalfOpenInterval`s of arbitrary `Bound`s. public static func shrink(_ bl : Range<Bound>) -> [Range<Bound>] { return zip(Bound.shrink(bl.lowerBound), Bound.shrink(bl.upperBound)).map(Range.init) } } extension LazySequence : Arbitrary where Base : Arbitrary { /// Returns a generator of `LazySequence`s of arbitrary `Base`s. public static var arbitrary : Gen<LazySequence<Base>> { return Base.arbitrary.map({ $0.lazy }) } } extension Repeated : Arbitrary where Element : Arbitrary { /// Returns a generator of `Repeat`s of arbitrary `Element`s. public static var arbitrary : Gen<Repeated<Element>> { let constructor: (Element, Int) -> Repeated<Element> = { (element, count) in return repeatElement(element , count: count) } return Gen<(Element, Int)>.zip(Element.arbitrary, Int.arbitrary).map({ t in constructor(t.0, t.1) }) } } extension Set : Arbitrary where Element : Arbitrary { /// Returns a generator of `Set`s of arbitrary `Element`s. public static var arbitrary : Gen<Set<Element>> { return Gen.sized { n in return Gen<Int>.choose((0, n)).flatMap { k in if k == 0 { return Gen.pure(Set([])) } return sequence(Array((0...k)).map { _ in Element.arbitrary }).map(Set.init) } } } /// The default shrinking function for `Set`s of arbitrary `Element`s. public static func shrink(_ s : Set<Element>) -> [Set<Element>] { return [Element].shrink([Element](s)).map(Set.init) } } // MARK: - Implementation Details private func removes<A : Arbitrary>(_ k : Int, n : Int, xs : [A]) -> [[A]] { let xs2 : [A] = Array(xs.suffix(max(0, xs.count - k))) if k > n { return [] } else if xs2.isEmpty { return [[]] } else { let xs1 : [A] = Array(xs.prefix(k)) let rec : [[A]] = removes(k, n: n - k, xs: xs2).map({ xs1 + $0 }) return [xs2] + rec } } private func shrinkOne<A : Arbitrary>(_ xs : [A]) -> [[A]] { guard let x : A = xs.first else { return [[A]]() } let xss = [A](xs[1..<xs.endIndex]) let a : [[A]] = A.shrink(x).map({ [$0] + xss }) let b : [[A]] = shrinkOne(xss).map({ [x] + $0 }) return a + b }
d002b8c55171cb4d523015d66e2c2ba3
34.19403
116
0.693243
false
false
false
false
HiyakashiGroupHoldings/ExtensionCollection
refs/heads/master
ExtensionCollection/QueryParser.swift
apache-2.0
1
// // QueryParser.swift // ExtensionCollection // // Created by Oka Yuya on 2017/08/01. // Copyright © 2017年 Oka Yuya. All rights reserved. // import Foundation public class QueryParser { public class func queryDictionary(query: String) -> [AnyHashable: Any] { var queries = [AnyHashable: Any]() let pairs = query.components(separatedBy: "&") for pair in pairs { let elements = pair.components(separatedBy: "=") let key = elements.first?.removingPercentEncoding let value = elements.last?.removingPercentEncoding if let key = key, let value = value { queries[key] = value } } return queries } }
96aa17aede3a01015b9baadb73419512
24.137931
76
0.599451
false
false
false
false
connienguyen/volunteers-iOS
refs/heads/development
VOLA/VOLA/Resources/Theme+Colors.swift
gpl-2.0
1
// // Theme+Colors.swift // VOLA // // Created by Bruno Henriques on 31/05/2017. // Copyright © 2017 Systers-Opensource. All rights reserved. // /// Constants for color palette used for styling app struct ThemeColors { static let crimson = UIColor(hex: 0xEF4135) static let caribbean = UIColor(hex: 0x54BCEB) static let sublime = UIColor(hex: 0xC1D82F) static let tangerine = UIColor(hex: 0xF89728) static let richBlack = UIColor(hex: 0x101B20) static let mediumGrey = UIColor(hex: 0x888B8D) static let lightGrey = UIColor(hex: 0xB1B3B3) static let white = UIColor(hex: 0xFFFFFF) static let emerald = UIColor(hex: 0x00833E) static let marineBlue = UIColor(hex: 0x0076A9) }
3e43fc28e5e0493ce28f15d0fc22f4c4
33.190476
61
0.710306
false
false
false
false
nohana/NohanaImagePicker
refs/heads/master
NohanaImagePicker/AssetDateSectionCreater.swift
apache-2.0
1
/* * Copyright (C) 2021 nohana, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an &quot;AS IS&quot; BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Photos final class AssetDateSectionCreater { func createSections(assetList: PHAssetCollection, options: PHFetchOptions) -> [AssetDateSection] { var albumDateSectionList = [AssetDateSection]() let fetchAssetlist = PHAsset.fetchAssets(in: assetList, options: options) let allAssets = fetchAssetlist.objects(at: IndexSet(0..<fetchAssetlist.count)) let calender = Calendar.current var assetsByDate = [(DateComponents, [PHAsset])]() var assetsByDateIndex = 0 for asset in allAssets { if assetsByDateIndex > 0 { if assetsByDate[assetsByDateIndex - 1].0 == calender.dateComponents([.day, .year, .month], from: (asset.creationDate ?? Date(timeIntervalSince1970: 0))) { assetsByDate[assetsByDateIndex - 1].1.append(asset) } else { let value = (calender.dateComponents([.day, .year, .month], from: (asset.creationDate ?? Date(timeIntervalSince1970: 0))), [asset]) assetsByDate.append(value) assetsByDateIndex += 1 } } else if assetsByDate.count == assetsByDateIndex { let value = (calender.dateComponents([.day, .year, .month], from: (asset.creationDate ?? Date(timeIntervalSince1970: 0))), [asset]) assetsByDate.append(value) assetsByDateIndex += 1 } } albumDateSectionList = assetsByDate.map { AssetDateSection(creationDate: calender.date(from: $0.0) ?? Date(timeIntervalSince1970: 0), assetResult: $0.1) } return albumDateSectionList } }
6a5c89f822ca04944bf1a4eb5c3a9eb6
47.978261
170
0.653795
false
false
false
false
CodaFi/swift
refs/heads/main
test/SILGen/cf.swift
apache-2.0
13
// RUN: %target-swift-emit-silgen -module-name cf -enable-objc-interop -import-cf-types -sdk %S/Inputs %s -o - | %FileCheck %s import CoreCooling // CHECK: sil hidden [ossa] @$s2cf8useEmAllyySo16CCMagnetismModelCF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $CCMagnetismModel): func useEmAll(_ model: CCMagnetismModel) { // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply> let power = CCPowerSupplyGetDefault() // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (Optional<CCPowerSupply>) -> Optional<Unmanaged<CCRefrigerator>> let unmanagedFridge = CCRefrigeratorCreate(power) // CHECK: function_ref @CCRefrigeratorSpawn : $@convention(c) (Optional<CCPowerSupply>) -> @owned Optional<CCRefrigerator> let managedFridge = CCRefrigeratorSpawn(power) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (Optional<CCRefrigerator>) -> () CCRefrigeratorOpen(managedFridge) // CHECK: function_ref @CCRefrigeratorCopy : $@convention(c) (Optional<CCRefrigerator>) -> @owned Optional<CCRefrigerator> let copy = CCRefrigeratorCopy(managedFridge) // CHECK: function_ref @CCRefrigeratorClone : $@convention(c) (Optional<CCRefrigerator>) -> @autoreleased Optional<CCRefrigerator> let clone = CCRefrigeratorClone(managedFridge) // CHECK: function_ref @CCRefrigeratorDestroy : $@convention(c) (@owned Optional<CCRefrigerator>) -> () CCRefrigeratorDestroy(clone) // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.refrigerator!foreign : (CCMagnetismModel) -> () -> Unmanaged<CCRefrigerator>?, $@convention(objc_method) (CCMagnetismModel) -> @unowned_inner_pointer Optional<Unmanaged<CCRefrigerator>> let f0 = model.refrigerator() // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.getRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f1 = model.getRefrigerator() // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.takeRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @owned Optional<CCRefrigerator> let f2 = model.takeRefrigerator() // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.borrowRefrigerator!foreign : (CCMagnetismModel) -> () -> CCRefrigerator?, $@convention(objc_method) (CCMagnetismModel) -> @autoreleased Optional<CCRefrigerator> let f3 = model.borrowRefrigerator() // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.setRefrigerator!foreign : (CCMagnetismModel) -> (CCRefrigerator?) -> (), $@convention(objc_method) (Optional<CCRefrigerator>, CCMagnetismModel) -> () model.setRefrigerator(copy) // CHECK: objc_method [[ARG]] : $CCMagnetismModel, #CCMagnetismModel.giveRefrigerator!foreign : (CCMagnetismModel) -> (CCRefrigerator?) -> (), $@convention(objc_method) (@owned Optional<CCRefrigerator>, CCMagnetismModel) -> () model.giveRefrigerator(copy) // rdar://16846555 let prop: CCRefrigerator = model.fridgeProp } // Ensure that accessors are emitted for fields used as protocol witnesses. protocol Impedance { associatedtype Component var real: Component { get } var imag: Component { get } } extension CCImpedance: Impedance {} // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo11CCImpedanceV2cf9ImpedanceA2cDP4real9ComponentQzvgTW // CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo11CCImpedanceV4realSdvg // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$sSo11CCImpedanceV2cf9ImpedanceA2cDP4imag9ComponentQzvgTW // CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo11CCImpedanceV4imagSdvg class MyMagnetism : CCMagnetismModel { // CHECK-LABEL: sil hidden [thunk] [ossa] @$s2cf11MyMagnetismC15getRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func getRefrigerator() -> CCRefrigerator { return super.getRefrigerator() } // CHECK-LABEL: sil hidden [thunk] [ossa] @$s2cf11MyMagnetismC16takeRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @owned CCRefrigerator override func takeRefrigerator() -> CCRefrigerator { return super.takeRefrigerator() } // CHECK-LABEL: sil hidden [thunk] [ossa] @$s2cf11MyMagnetismC18borrowRefrigerator{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (MyMagnetism) -> @autoreleased CCRefrigerator override func borrowRefrigerator() -> CCRefrigerator { return super.borrowRefrigerator() } }
2f3fb69487c3d13ddf9f123af1f2e3fb
56.475
254
0.750979
false
false
false
false
FearfulFox/sacred-tiles
refs/heads/master
Sacred Tiles/GameTileSprite.swift
gpl-2.0
1
// // GameTileSprite.swift // Sacred Tiles // // Created by Fox on 3/5/15. // Copyright (c) 2015 eCrow. All rights reserved. // import SpriteKit; class GameTileSprite: TileSprite { private var pressClosure: (SKNode)->() = {(SKNode)->() in } var flipTouch = true; init(type: Tile.TYPE){ super.init(type: type, isFlipped: false); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if(flipTouch){ self.flipBack(); }else{ self.pressClosure(self); } } override func flipBack() { if(!isFlipping){ //runAction(SKAction.playSoundFileNamed("flip_up.caf", waitForCompletion: false)); SoundManager.playSound("flip_up.caf"); self.isFlipped = false; self.isFlipping = true; self.runAction(TILE_RESOURCE.tileFlipBackActions[self.type.rawValue], completion: self.flipComplete); } } private func flipComplete(){ self.isFlipping = false; self.pressClosure(self); } func onPress(closure:(selfNode: SKNode)->()){ self.pressClosure = closure; } }
af822ff24bb1dbbc6675b9ac88e890d5
24.705882
113
0.591915
false
false
false
false
HJliu1123/LearningNotes-LHJ
refs/heads/master
April/Xbook/Xbook/push/Model/HJPushBookCell.swift
apache-2.0
1
// // HJPushBookCell.swift // Xbook // // Created by liuhj on 16/4/11. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit class HJPushBookCell: SWTableViewCell { var bookName : UILabel? var editor : UILabel? var more : UILabel? var cover : UIImageView? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier:reuseIdentifier) for view in self.contentView.subviews { view.removeFromSuperview() } self.bookName = UILabel(frame: CGRectMake(78, 8, 242, 25)) self.editor = UILabel(frame: CGRectMake(78, 33, 242, 25)) self.more = UILabel(frame: CGRectMake(78, 66, 242, 25)) self.bookName?.font = UIFont(name: MY_FONT, size: 15) self.editor?.font = UIFont(name: MY_FONT, size: 15) self.more?.font = UIFont(name: MY_FONT, size: 13) self.more?.textColor = UIColor.grayColor() self.contentView.addSubview(bookName!) self.contentView.addSubview(editor!) self.contentView.addSubview(more!) self.cover = UIImageView(frame: CGRectMake(8, 9, 56, 70)) self.contentView.addSubview(cover!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
06e72c6b3d103905d8cb290197f06518
26.015873
74
0.608108
false
false
false
false
ngageoint/mage-ios
refs/heads/master
Mage/FormDefaultsViewController.swift
apache-2.0
1
// // FormDefaultsViewController.swift // MAGE // // Created by Daniel Barela on 2/8/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation class FormDefaultsViewController: UIViewController { var didSetupConstraints = false; var formDefaultsCoordinator: FormDefaultsCoordinator?; var observationFormView: ObservationFormView?; var navController: UINavigationController!; var event: Event!; var eventForm: Form!; var scheme: MDCContainerScheming?; let card = MDCCard(forAutoLayout: ()); let formNameLabel = UILabel.newAutoLayout(); let formDescriptionLabel = UILabel.newAutoLayout(); let defaultsLabel = UILabel.newAutoLayout(); let defaultDescriptionLabel = UILabel.newAutoLayout(); let image = UIImageView(image: UIImage(systemName: "doc.text.fill")); private lazy var managedObjectContext: NSManagedObjectContext = { var managedObjectContext: NSManagedObjectContext = .mr_newMainQueue(); managedObjectContext.parent = .mr_rootSaving(); managedObjectContext.stalenessInterval = 0.0; managedObjectContext.mr_setWorkingName("Form Default Temporary Context"); return managedObjectContext; } () private lazy var divider: UIView = { let divider = UIView(forAutoLayout: ()); divider.autoSetDimension(.height, toSize: 1); return divider; }() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView.newAutoLayout(); return scrollView; }() private lazy var stackView: UIStackView = { let stackView = UIStackView.newAutoLayout(); stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = 8 stackView.distribution = .fill stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 0, trailing: 8) stackView.isLayoutMarginsRelativeArrangement = true; stackView.translatesAutoresizingMaskIntoConstraints = false; return stackView; }() private lazy var resetButton: MDCButton = { let button = MDCButton(forAutoLayout: ()); button.accessibilityLabel = "reset defaults"; button.setTitle("Reset To Server Defaults", for: .normal); button.addTarget(self, action: #selector(resetDefaults), for: .touchUpInside); return button; }() private lazy var header: UIView = { let stack = UIStackView.newAutoLayout(); stack.alignment = .fill; stack.distribution = .fill; stack.axis = .vertical; stack.spacing = 4; formNameLabel.text = eventForm.name; formDescriptionLabel.text = eventForm.formDescription formDescriptionLabel.numberOfLines = 0; formDescriptionLabel.lineBreakMode = .byWordWrapping; stack.addArrangedSubview(formNameLabel); stack.addArrangedSubview(formDescriptionLabel); let header = UIView.newAutoLayout(); header.addSubview(image); header.addSubview(stack); image.autoPinEdge(toSuperviewEdge: .left); image.autoSetDimensions(to: CGSize(width: 36, height: 36)); stack.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .left); stack.autoPinEdge(.left, to: .right, of: image, withOffset: 16); image.autoAlignAxis(.horizontal, toSameAxisOf: stack); return header; }() init(frame: CGRect) { super.init(nibName: nil, bundle: nil); } @objc convenience public init(event: Event, eventForm: Form, navigationController: UINavigationController, scheme: MDCContainerScheming, formDefaultsCoordinator: FormDefaultsCoordinator?) { self.init(frame: CGRect.zero); self.event = event; self.eventForm = eventForm; self.scheme = scheme; self.navController = navigationController; self.formDefaultsCoordinator = formDefaultsCoordinator; } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } @objc public func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) { guard let containerScheme = containerScheme else { return } self.scheme = containerScheme; self.view.backgroundColor = containerScheme.colorScheme.backgroundColor; formNameLabel.textColor = containerScheme.colorScheme.onBackgroundColor.withAlphaComponent(0.87); formNameLabel.font = containerScheme.typographyScheme.headline6; formDescriptionLabel.textColor = containerScheme.colorScheme.onBackgroundColor.withAlphaComponent(0.6); formDescriptionLabel.font = containerScheme.typographyScheme.subtitle2; defaultsLabel.textColor = containerScheme.colorScheme.onSurfaceColor.withAlphaComponent(0.87); defaultsLabel.font = containerScheme.typographyScheme.subtitle1; defaultDescriptionLabel.textColor = containerScheme.colorScheme.onSurfaceColor.withAlphaComponent(0.6); defaultDescriptionLabel.font = containerScheme.typographyScheme.caption; observationFormView?.applyTheme(withScheme: containerScheme); card.applyTheme(withScheme: containerScheme); if let color = eventForm.color { image.tintColor = UIColor(hex: color); } else { image.tintColor = containerScheme.colorScheme.primaryColor } resetButton.applyTextTheme(withScheme: globalErrorContainerScheme()); divider.backgroundColor = containerScheme.colorScheme.onSurfaceColor.withAlphaComponent(0.12); } @objc func resetDefaults() { observationFormView?.removeFromSuperview(); var newForm: [String: AnyHashable] = [:]; let fields: [[String : AnyHashable]] = eventForm.fields ?? []; let filteredFields: [[String: AnyHashable]] = fields.filter {(($0[FieldKey.archived.key] as? Bool) == nil || ($0[FieldKey.archived.key] as? Bool) == false) } for (_, field) in filteredFields.enumerated() { // grab the server default from the form fields value property if let value: AnyHashable = field[FieldKey.value.key] { newForm[field[FieldKey.name.key] as! String] = value; } } let observation: Observation = Observation(context: managedObjectContext); observation.properties = [ObservationKey.forms.key: [newForm]]; observationFormView = ObservationFormView(observation: observation, form: newForm, eventForm: eventForm, formIndex: 0, viewController: navController, delegate: formDefaultsCoordinator); stackView.insertArrangedSubview(observationFormView!, at: 2); observationFormView?.applyTheme(withScheme: self.scheme!); } func buildObservationFormView() { var newForm: [String: AnyHashable] = [:]; let defaults: FormDefaults = FormDefaults(eventId: self.event.remoteId as! Int, formId: eventForm.formId?.intValue ?? -1); let formDefaults: [String: AnyHashable] = defaults.getDefaults() as! [String: AnyHashable]; let fields: [[String : AnyHashable]] = eventForm.fields ?? []; let filteredFields: [[String: AnyHashable]] = fields.filter {(($0[FieldKey.archived.key] as? Bool) == nil || ($0[FieldKey.archived.key] as? Bool) == false) } if (formDefaults.count > 0) { // user defaults for (_, field) in filteredFields.enumerated() { var value: AnyHashable? = nil; if let defaultField: AnyHashable = formDefaults[field[FieldKey.name.key] as! String] { value = defaultField } if (value != nil) { newForm[field[FieldKey.name.key] as! String] = value; } } } else { // server defaults for (_, field) in filteredFields.enumerated() { // grab the server default from the form fields value property if let value: AnyHashable = field[FieldKey.value.key] { newForm[field[FieldKey.name.key] as! String] = value; } } } let observation: Observation = Observation(context: managedObjectContext); observation.properties = [ObservationKey.forms.key: [newForm]]; observationFormView = ObservationFormView(observation: observation, form: newForm, eventForm: eventForm, formIndex: 0, viewController: navController, delegate: formDefaultsCoordinator, includeAttachmentFields: false); } override func viewDidLoad() { super.viewDidLoad(); self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Apply", style: .done, target: self, action: #selector(self.saveDefaults)); self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(self.cancel)); view.addSubview(scrollView); scrollView.addSubview(card); card.addSubview(stackView); scrollView.addSubview(header); defaultsLabel.text = "Custom Form Defaults"; defaultDescriptionLabel.text = "Personalize the default values MAGE will autofill when you add this form to an observation."; defaultDescriptionLabel.lineBreakMode = .byWordWrapping; defaultDescriptionLabel.numberOfLines = 0; stackView.addArrangedSubview(defaultsLabel); stackView.addArrangedSubview(defaultDescriptionLabel); stackView.setCustomSpacing(16, after: defaultDescriptionLabel); buildObservationFormView(); if let formView = observationFormView { stackView.addArrangedSubview(formView); } stackView.addArrangedSubview(divider); let buttonContainer = UIView.newAutoLayout(); buttonContainer.addSubview(resetButton); resetButton.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 0, bottom: 16, right: 0), excludingEdge: .left); stackView.addArrangedSubview(buttonContainer); view.setNeedsUpdateConstraints(); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); applyTheme(withContainerScheme: scheme); } override func updateViewConstraints() { if (!didSetupConstraints) { scrollView.autoPinEdgesToSuperviewEdges(with: .zero); stackView.autoPinEdgesToSuperviewEdges(); card.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), excludingEdge: .top); card.autoMatch(.width, to: .width, of: view, withOffset: -16); header.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 8, right: 16), excludingEdge: .bottom); card.autoPinEdge(.top, to: .bottom, of: header, withOffset: 16); didSetupConstraints = true; } super.updateViewConstraints(); } @objc func saveDefaults() { let valid = observationFormView?.checkValidity(enforceRequired: false) ?? false; if (!valid) { if let fieldViews = observationFormView?.fieldViews { for (_, subview) in fieldViews { if !subview.isValid(enforceRequired: false) { var yOffset = subview.frame.origin.y var superview = subview.superview while (superview != nil) { yOffset += superview?.frame.origin.y ?? 0.0 superview = superview?.superview } let newFrame = CGRect(x: 0, y: yOffset, width: subview.frame.size.width, height: subview.frame.size.height) scrollView.scrollRectToVisible(newFrame, animated: true) return } } } return } let currentDefaults: [String: AnyHashable] = (observationFormView?.observation.properties!["forms"] as! [[String: AnyHashable]])[0]; formDefaultsCoordinator?.save(defaults: currentDefaults); } @objc func cancel() { formDefaultsCoordinator?.cancel(); } }
bb6b30ac867788571d3628705d5a3c1d
45.225926
225
0.65107
false
false
false
false
ppoh71/motoRoutes
refs/heads/master
motoRoutes/MenuButton.swift
apache-2.0
1
// // ActionButton.swift // motoRoutes // // Created by Peter Pohlmann on 22.01.2017. // Copyright © 2016 Peter Pohlmann. All rights reserved. // import UIKit class MenuButton: UIView{ //var initFrame = CGRect(x: 0, y: 0, width: menuButtonWidth, height: menuButtonHeight) var menuButton = UIButton() var menuType = MenuButtonType() let padding = menuLabelPadding var yPos: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, menuType: MenuButtonType, buttonNumber: Int, xOff: Bool, offset: Int) { self.init(frame: frame) print("buttonclass frame \(frame)") self.menuType = menuType self.frame.origin.y = frame.height * CGFloat(buttonNumber) + CGFloat(padding/2 * buttonNumber) self.backgroundColor = UIColor.cyan if xOff { //set off screen by x self.frame.origin.x = CGFloat(offset) } setupButton(frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupButton(_ frame: CGRect){ print("button frame \(frame)") menuButton.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) //assign view frame also to button menuButton.setTitle(menuType.buttonText, for: .normal) menuButton.setTitleColor(blue4, for: .normal) menuButton.titleLabel!.font = menuFont menuButton.backgroundColor = UIColor.white menuButton.menuType = menuType menuButton.isUserInteractionEnabled = true menuButton.addTarget(self, action: #selector(pressedButton), for: .touchUpInside) self.addSubview(menuButton) } func pressedButton(_ sender: UIButton){ let notifyObj = [sender.menuType] NotificationCenter.default.post(name: Notification.Name(rawValue: motoMenuActionNotificationKey), object: notifyObj) } }
dae1026b19bc6766b7a0e418777755bc
34.446429
124
0.657935
false
false
false
false
vapor/vapor
refs/heads/main
Sources/Vapor/Content/PlaintextDecoder.swift
mit
1
/// Decodes data as plaintext, utf8. public struct PlaintextDecoder: ContentDecoder { public init() { } /// `ContentDecoder` conformance. public func decode<D>(_ decodable: D.Type, from body: ByteBuffer, headers: HTTPHeaders) throws -> D where D : Decodable { let string = body.getString(at: body.readerIndex, length: body.readableBytes) return try D(from: _PlaintextDecoder(plaintext: string)) } } // MARK: Private private final class _PlaintextDecoder: Decoder { let codingPath: [CodingKey] let userInfo: [CodingUserInfoKey: Any] let plaintext: String? init(plaintext: String?) { self.codingPath = [] self.userInfo = [:] self.plaintext = plaintext } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { throw DecodingError.typeMismatch(type, DecodingError.Context( codingPath: codingPath, debugDescription: "Plaintext decoding does not support dictionaries." )) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { throw DecodingError.typeMismatch(String.self, DecodingError.Context( codingPath: codingPath, debugDescription: "Plaintext decoding does not support arrays." )) } func singleValueContainer() throws -> SingleValueDecodingContainer { DataDecodingContainer(decoder: self) } } private final class DataDecodingContainer: SingleValueDecodingContainer { var codingPath: [CodingKey] { decoder.codingPath } let decoder: _PlaintextDecoder init(decoder: _PlaintextDecoder) { self.decoder = decoder } func decodeNil() -> Bool { if let plaintext = decoder.plaintext { return plaintext.isEmpty } return true } func losslessDecode<L: LosslessStringConvertible>(_ type: L.Type) throws -> L { if let plaintext = decoder.plaintext, let decoded = L(plaintext) { return decoded } throw DecodingError.dataCorruptedError( in: self, debugDescription: "Failed to get \(type) from \"\(decoder.plaintext ?? "")\"" ) } func decode(_ type: Bool.Type) throws -> Bool { try losslessDecode(type) } func decode(_ type: String.Type) throws -> String { decoder.plaintext ?? "" } func decode(_ type: Double.Type) throws -> Double { try losslessDecode(type) } func decode(_ type: Float.Type) throws -> Float { try losslessDecode(type) } func decode(_ type: Int.Type) throws -> Int { try losslessDecode(type) } func decode(_ type: Int8.Type) throws -> Int8 { try losslessDecode(type) } func decode(_ type: Int16.Type) throws -> Int16 { try losslessDecode(type) } func decode(_ type: Int32.Type) throws -> Int32 { try losslessDecode(type) } func decode(_ type: Int64.Type) throws -> Int64 { try losslessDecode(type) } func decode(_ type: UInt.Type) throws -> UInt { try losslessDecode(type) } func decode(_ type: UInt8.Type) throws -> UInt8 { try losslessDecode(type) } func decode(_ type: UInt16.Type) throws -> UInt16 { try losslessDecode(type) } func decode(_ type: UInt32.Type) throws -> UInt32 { try losslessDecode(type) } func decode(_ type: UInt64.Type) throws -> UInt64 { try losslessDecode(type) } func decode<T>(_ type: T.Type) throws -> T where T : Decodable { throw DecodingError.typeMismatch(type, DecodingError.Context( codingPath: codingPath, debugDescription: "Plaintext decoding does not support nested types." )) } }
86de7de57de50554b8804c6120826aa6
37.712766
109
0.655675
false
false
false
false
AjayOdedara/CoreKitTest
refs/heads/master
CoreKit/Pods/SwiftDate/Sources/SwiftDate/CalendarName.swift
mit
5
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - CalendarName Shortcut /// This enum allows you set a valid calendar using swift's type safe support public enum CalendarName { case current, currentAutoUpdating case gregorian, buddhist, chinese, coptic, ethiopicAmeteMihret, ethiopicAmeteAlem, hebrew, iso8601, indian, islamic, islamicCivil, japanese, persian, republicOfChina, islamicTabular, islamicUmmAlQura /// Return a new `Calendar` instance from a given identifier public var calendar: Calendar { var identifier: Calendar.Identifier switch self { case .current: return Calendar.current case .currentAutoUpdating: return Calendar.autoupdatingCurrent case .gregorian: identifier = Calendar.Identifier.gregorian case .buddhist: identifier = Calendar.Identifier.buddhist case .chinese: identifier = Calendar.Identifier.chinese case .coptic: identifier = Calendar.Identifier.coptic case .ethiopicAmeteMihret: identifier = Calendar.Identifier.ethiopicAmeteMihret case .ethiopicAmeteAlem: identifier = Calendar.Identifier.ethiopicAmeteAlem case .hebrew: identifier = Calendar.Identifier.hebrew case .iso8601: identifier = Calendar.Identifier.iso8601 case .indian: identifier = Calendar.Identifier.indian case .islamic: identifier = Calendar.Identifier.islamic case .islamicCivil: identifier = Calendar.Identifier.islamicCivil case .japanese: identifier = Calendar.Identifier.japanese case .persian: identifier = Calendar.Identifier.persian case .republicOfChina: identifier = Calendar.Identifier.republicOfChina case .islamicTabular: identifier = Calendar.Identifier.islamicTabular case .islamicUmmAlQura: identifier = Calendar.Identifier.islamicUmmAlQura } return Calendar(identifier: identifier) } } //MARK: Calendar.Component Extension extension Calendar.Component { fileprivate var cfValue: CFCalendarUnit { return CFCalendarUnit(rawValue: self.rawValue) } } extension Calendar.Component { /// https://github.com/apple/swift-corelibs-foundation/blob/swift-DEVELOPMENT-SNAPSHOT-2016-09-10-a/CoreFoundation/Locale.subproj/CFCalendar.h#L68-L83 internal var rawValue: UInt { switch self { case .era: return 1 << 1 case .year: return 1 << 2 case .month: return 1 << 3 case .day: return 1 << 4 case .hour: return 1 << 5 case .minute: return 1 << 6 case .second: return 1 << 7 case .weekday: return 1 << 9 case .weekdayOrdinal: return 1 << 10 case .quarter: return 1 << 11 case .weekOfMonth: return 1 << 12 case .weekOfYear: return 1 << 13 case .yearForWeekOfYear: return 1 << 14 case .nanosecond: return 1 << 15 case .calendar: return 1 << 16 case .timeZone: return 1 << 17 } } internal init?(rawValue: UInt) { switch rawValue { case Calendar.Component.era.rawValue: self = .era case Calendar.Component.year.rawValue: self = .year case Calendar.Component.month.rawValue: self = .month case Calendar.Component.day.rawValue: self = .day case Calendar.Component.hour.rawValue: self = .hour case Calendar.Component.minute.rawValue: self = .minute case Calendar.Component.second.rawValue: self = .second case Calendar.Component.weekday.rawValue: self = .weekday case Calendar.Component.weekdayOrdinal.rawValue: self = .weekdayOrdinal case Calendar.Component.quarter.rawValue: self = .quarter case Calendar.Component.weekOfMonth.rawValue: self = .weekOfMonth case Calendar.Component.weekOfYear.rawValue: self = .weekOfYear case Calendar.Component.yearForWeekOfYear.rawValue: self = .yearForWeekOfYear case Calendar.Component.nanosecond.rawValue: self = .nanosecond case Calendar.Component.calendar.rawValue: self = .calendar case Calendar.Component.timeZone.rawValue: self = .timeZone default: return nil } } } //MARK: - Calendar Extension extension Calendar { // The code below is part of the Swift.org code. It is included as rangeOfUnit is a very useful // function for the startOf and endOf functions. // As always we would prefer using Foundation code rather than inventing code ourselves. typealias CFType = CFCalendar private var cfObject: CFType { return unsafeBitCast(self as NSCalendar, to: CFCalendar.self) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// `public func rangeOfUnit(unit: NSCalendarUnit, startDate datep: /// AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: /// UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool` /// which is not implementable on Linux due to the lack of being able to properly implement /// AutoreleasingUnsafeMutablePointer. /// /// - parameters: /// - component: the unit to determine the range for /// - date: the date to wrap the unit around /// - returns: the range (date interval) of the unit around the date /// /// - Experiment: This is a draft API currently under consideration for official import into /// Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the /// near future /// public func rangex(of component: Calendar.Component, for date: Date) -> DateTimeInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp -> Bool in return withUnsafeMutablePointer(to: &ti) { tip -> Bool in let startPtr: UnsafeMutablePointer<CFAbsoluteTime> = startp let tiPtr: UnsafeMutablePointer<CFTimeInterval> = tip return CFCalendarGetTimeRangeOfUnit(cfObject, component.cfValue, date.timeIntervalSinceReferenceDate, startPtr, tiPtr) } } if res { let startDate = Date(timeIntervalSinceReferenceDate: start) return DateTimeInterval(start: startDate, duration: ti) } return nil } /// Create a new NSCalendar instance from CalendarName structure. You can also use /// <CalendarName>.calendar to get a new instance of NSCalendar with picked type. /// /// - parameter type: type of the calendar /// /// - returns: instance of the new Calendar public static func fromType(_ type: CalendarName) -> Calendar { return type.calendar } }
41e58bc5d11add0321c759f3fef1e82f
42.270718
151
0.718335
false
false
false
false
VishnuUnnikrishnan/swiftToDo
refs/heads/master
ToDo/ToDoListTableViewController.swift
gpl-3.0
1
// // ToDoListTableViewController.swift // ToDo // // Created by Vishnu Unnikrishnan on 13/09/2015. // Copyright (c) 2015 Tutorial. All rights reserved. // import UIKit class ToDoListTableViewController: UITableViewController{ @IBOutlet weak var gdgdh: UITableViewCell! var toDoItems: NSMutableArray = [] override func viewDidLoad() { super.viewDidLoad() loadInitialData() // Uncomment the following line to preserve selection between presentations //self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadInitialData(){ var item1 = ToDoItem(name: "Buy Milk") self.toDoItems.addObject(item1) var item2 = ToDoItem(name: "Buy Eggs") self.toDoItems.addObject(item2) var item3 = ToDoItem(name: "Read a Book") self.toDoItems.addObject(item3) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.toDoItems.count } @IBAction func unwindToList(segue: UIStoryboardSegue) { var source: AddToDoItemViewController = segue.sourceViewController as! AddToDoItemViewController if let var item: ToDoItem = source.toDoItem{ var item: ToDoItem = source.toDoItem if !(item.isEqual(nil)){ self.toDoItems.addObject(item) self.tableView.reloadData() } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListPrototypeCell", forIndexPath: indexPath) as! UITableViewCell var toDoItem: ToDoItem = self.toDoItems.objectAtIndex(indexPath.row) as! ToDoItem cell.textLabel!.text = toDoItem.itemName as String // Configure the cell... if toDoItem.completed{ cell.accessoryType = .Checkmark } else{ cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: false) var tappedItem: ToDoItem = self.toDoItems.objectAtIndex(indexPath.row) as! ToDoItem tappedItem.completed = !tappedItem.completed tableView.reloadData() } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
5b69a74e9786c200055741b85dfbd927
32.019868
157
0.645407
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/develop
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/RemoveSectionController.swift
apache-2.0
4
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit protocol RemoveSectionControllerDelegate: class { func removeSectionControllerWantsRemoved(_ sectionController: RemoveSectionController) } final class RemoveSectionController: ListSectionController, RemoveCellDelegate { weak var delegate: RemoveSectionControllerDelegate? private var number: Int? override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: RemoveCell.self, for: self, at: index) as? RemoveCell else { fatalError() } cell.text = "Cell: \((number ?? 0) + 1)" cell.delegate = self return cell } override func didUpdate(to object: Any) { number = object as? Int } // MARK: RemoveCellDelegate func removeCellDidTapButton(_ cell: RemoveCell) { delegate?.removeSectionControllerWantsRemoved(self) } }
6c44c1d245e7afbbfb1c4e1ab5498994
33.111111
128
0.717155
false
false
false
false
PokeMapCommunity/PokeMap-iOS
refs/heads/master
PokeMap/View Controllers/MapViewController.swift
mit
1
// // ViewController.swift // PokeMap // // Created by Ivan Bruel on 20/07/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import UIKit import MapKit import RxSwift import NSObject_Rx import Permission import MKMapView_ZoomLevel class MapViewController: UIViewController { @IBOutlet private weak var mapView: MKMapView! private let viewModel = PokemonMapViewModel() private var centerLocation: Variable<CLLocationCoordinate2D>! private var userLocation: Variable<CLLocationCoordinate2D>! override func viewDidLoad() { super.viewDidLoad() centerLocation = Variable(mapView.centerCoordinate) userLocation = Variable(mapView.userLocation.coordinate) bindViewModel() Permission.LocationAlways.request { _ in } } private func bindViewModel() { viewModel.viewModels .subscribeNext { [weak self] viewModels in guard let `self` = self else { return } self.setupAnnotations(viewModels) }.addDisposableTo(rx_disposeBag) centerLocation.asObservable() .throttle(1, scheduler: MainScheduler.instance) .subscribeNext { [weak self] location in guard let `self` = self else { return } self.loadPokemons(location) }.addDisposableTo(rx_disposeBag) userLocation.asObservable() .throttle(1, scheduler: MainScheduler.instance) .subscribeNext { [weak self] location in guard let `self` = self else { return } self.loadPokemons(location) }.addDisposableTo(rx_disposeBag) userLocation.asObservable() .throttle(1, scheduler: MainScheduler.instance).take(1) .subscribeNext { [weak self] location in self?.mapView.setCenterCoordinate(location, zoomLevel: 14, animated: true) }.addDisposableTo(rx_disposeBag) } func loadPokemons(location: CLLocationCoordinate2D) { viewModel.loadPokemons(location.latitude, longitude: location.longitude, jobId: nil) .subscribe() .addDisposableTo(rx_disposeBag) } @IBAction func openPokemonGo() { UIApplication.sharedApplication() .openURL(NSURL(string: "b335b2fc-69dc-472c-9e88-e6c97f84091c-3://")!) } @IBAction func center() { mapView.setCenterCoordinate(mapView.userLocation.coordinate, animated: true) } @IBAction func scan() { let coordinate = mapView.centerCoordinate Network .request(API.Scan(latitude: coordinate.latitude, longitude: coordinate.longitude)) .mapObject(ScanJob) .flatMap { return self.viewModel .loadPokemons(coordinate.latitude, longitude: coordinate.longitude, jobId: $0.jobId) }.take(1) .subscribe() .addDisposableTo(rx_disposeBag) } private func setupAnnotations(viewModels: [PokemonMapItemViewModel]) { let annotations = mapView.annotations.flatMap { $0 as? PokemonAnnotation } let expiredAnnotations = annotations.filter { $0.expired } mapView.removeAnnotations(expiredAnnotations) let validAnnotations = mapView.annotations.flatMap { $0 as? PokemonAnnotation } let pokemonIds = validAnnotations.map { $0.identifier } let newViewModels = viewModels.filter { !pokemonIds.contains($0.identifier) } mapView.addAnnotations(newViewModels.map { $0.annotation }) } } extension MapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { self.userLocation.value = userLocation.coordinate } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard let pokemonAnnotation = annotation as? PokemonAnnotation else { return nil } return pokemonAnnotation.annotationView } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { centerLocation.value = mapView.centerCoordinate } }
4954c2c0b0cf3b80386bfced495e75c9
32.112069
94
0.721687
false
false
false
false
mweibel/esrscan
refs/heads/master
ESRScan/ESR.swift
mit
1
// // ESR parser & model // // Copyright © 2015 Michael Weibel. All rights reserved. // License: MIT // import Foundation enum ESRError : ErrorType { case AngleNotFound case RefNumNotFound } public class ESR { var fullStr: String var amountCheckDigit: Int? var amount: Amount? var refNum: ReferenceNumber var refNumCheckDigit: Int var accNum: AccountNumber var transmitted = false init(fullStr : String, amountCheckDigit : Int?, amount : Amount?, refNum : ReferenceNumber, refNumCheckDigit : Int, accNum : AccountNumber) { self.fullStr = fullStr self.amountCheckDigit = amountCheckDigit self.amount = amount self.refNum = refNum self.refNumCheckDigit = refNumCheckDigit self.accNum = accNum } static func parseText(str : String) throws -> ESR { let newStr = str.stringByReplacingOccurrencesOfString(" ", withString: "") let newStrLength = newStr.characters.count let angleRange = newStr.rangeOfString(">") if angleRange == nil { throw ESRError.AngleNotFound } let angleIndex = newStr.startIndex.distanceTo(angleRange!.startIndex) let afterAngle = angleIndex + 1 let start = newStr.startIndex.advancedBy(angleIndex - 1) let end = newStr.startIndex.advancedBy(angleIndex) let amountCheckDigit = Int(newStr.substringWithRange( start..<end )) var amount : Amount? if angleIndex > 3 { let amountValue = Double(newStr.substringWithRange( newStr.startIndex.advancedBy(2)..<newStr.startIndex.advancedBy(angleIndex - 1) )) amount = Amount.init(value: amountValue! / 100.0) } let refNumStart = newStr.startIndex.advancedBy(afterAngle) var refNumLength = 27 let plusRange = newStr.rangeOfString("+") if plusRange != nil { refNumLength = refNumStart.distanceTo(plusRange!.startIndex) } if newStr.startIndex.distanceTo(refNumStart)+refNumLength > newStrLength { throw ESRError.RefNumNotFound } let refNum = ReferenceNumber.init(num: newStr.substringWithRange( refNumStart..<refNumStart.advancedBy(refNumLength) )) let idx = refNum.num.endIndex.advancedBy(-1) let refNumCheckDigit = Int(refNum.num.substringFromIndex(idx))! let accNum = newStr.substringWithRange( newStr.endIndex.advancedBy(-10)..<newStr.endIndex.advancedBy(-1) ) let accountNumber = AccountNumber.init(num: accNum) return ESR.init( fullStr: newStr, amountCheckDigit: amountCheckDigit, amount: amount, refNum: refNum, refNumCheckDigit: refNumCheckDigit, accNum: accountNumber ) } func amountCheckDigitValid() -> Bool { let angleRange = self.fullStr.rangeOfString(">") if angleRange == nil { return false } let angleIndex = self.fullStr.startIndex.distanceTo(angleRange!.startIndex) let str = self.fullStr.substringWithRange( self.fullStr.startIndex..<self.fullStr.startIndex.advancedBy(angleIndex - 1) ) return self.amountCheckDigit == calcControlDigit(str) } func refNumCheckDigitValid() -> Bool { let idx = self.refNum.num.endIndex.advancedBy(-1) let refNum = self.refNum.num.substringToIndex(idx) return self.refNumCheckDigit == calcControlDigit(refNum) } func string() -> String { var str = "Reference number: \(self.refNum.string())" if !self.refNumCheckDigitValid() { str.appendContentsOf(" ⚠︎") } str.appendContentsOf("\nAccount number: \(self.accNum.string())") if self.amount != nil { str.appendContentsOf("\nAmount: CHF \(self.amount!.string())") if !self.amountCheckDigitValid() { str.appendContentsOf(" ⚠︎") } } return str } func dictionary() -> [String : AnyObject] { var dict = [String : AnyObject]() dict["referenceNumber"] = self.refNum.string() dict["amount"] = self.amount?.string() dict["accountNumber"] = self.accNum.string() dict["amountCorrect"] = self.amountCheckDigitValid() dict["referenceNumberCorrect"] = self.refNumCheckDigitValid() return dict } private func calcControlDigit(str: String) -> Int { let table = [0, 9, 4, 6, 8, 2, 7, 1, 3, 5] var carry = 0 for char in str.characters { let num = Int.init(String(char), radix: 10) if num == nil { return -1 } carry = table[(carry + num!) % 10] } return (10 - carry) % 10 } // only CHF for now // ref: ESR Handbuch Postfinance static let validTypeCodes: Set<String> = [ "01", "03", "04", "11", "14" ] static func isValidTypeCode(str: String) -> Bool { for typeCode in validTypeCodes { if(str.hasPrefix(typeCode)) { return true } } return false } }
c8e7b199dfbee7931c377a51674e5cf3
30.508982
145
0.600266
false
false
false
false
burhanaksendir/swift-disk-status
refs/heads/master
DiskStatus/ViewController.swift
mit
1
// // ViewController.swift // DiskStatus // // Created by Cuong Lam on 3/29/15. // Copyright (c) 2015 BE Studio. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var totalView: UIView! @IBOutlet var usedLabel: UILabel! @IBOutlet var freeLabel: UILabel! var diskUsedView:UIView? 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. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.updateDiskStatus() } // MARK: update disk space status func updateDiskStatus() { usedLabel!.text = String(format:NSLocalizedString("Used %@", comment: ""), DiskStatus.usedDiskSpace) freeLabel!.text = String(format:NSLocalizedString("Free %@", comment: ""), DiskStatus.freeDiskSpace) var frame:CGRect = self.totalView!.frame frame.size.width = CGFloat(Double(DiskStatus.usedDiskSpaceInBytes)/Double(DiskStatus.totalDiskSpaceInBytes)) * frame.size.width diskUsedView = UIView(frame: frame) diskUsedView!.backgroundColor = self.usedLabel.textColor self.view!.addSubview(diskUsedView!) } }
187d5a1fd4de05eadb0d74c3c7cd4800
28.489796
135
0.666436
false
false
false
false
gyro-n/PaymentsIos
refs/heads/master
Example/Tests/ChargeTests.swift
mit
1
// // ChargeTests.swift // GyronPayments // // Created by Ye David on 11/11/16. // Copyright © 2016 gyron. All rights reserved. // // // PaymentNodeTests.swift // PaymentNodeTests // // Created by Ye David on 10/24/16. // Copyright © 2016 gyron. All rights reserved. // import XCTest import PromiseKit @testable import GyronPayments class ChargeTests: BaseTest { func testChargeList() { let asyncExpectation = expectation(description: "longRunningFunction") let data: ChargeListRequestData = ChargeListRequestData() var charges: Charges? self.api?.chargeResource?.delegate = self self.api?.chargeResource?.list(data: data, callback: { (c, e) in charges = c asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charges, "No Charges") XCTAssert((charges?.items.count)! > 0, "No Charges Found") } } func testChargeListPromise() { let asyncExpectation = expectation(description: "longRunningFunction") let data: ChargeListRequestData = ChargeListRequestData() var charges: Charges? self.api?.chargeResource?.delegate = self self.api?.chargeResource?.list(data: data, callback: nil).then(execute: { c -> Void in charges = c asyncExpectation.fulfill() }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charges, "No Charges") XCTAssert((charges?.items.count)! > 0, "No Charges Found") } } func testChargeListByStore() { let asyncExpectation = expectation(description: "longRunningFunction") let data: ChargeListRequestData = ChargeListRequestData() var charges: Charges? self.api?.chargeResource?.delegate = self self.api?.chargeResource?.list(data: data, callback: { (c, e) in if (c != nil && c!.items.count > 0) { let ch = c!.items.first! self.api?.chargeResource?.listByStore(storeId: ch.storeId, data: data, callback: { (c, e) in charges = c asyncExpectation.fulfill() }) } else { asyncExpectation.fulfill() } }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charges, "No Charges") XCTAssert((charges?.items.count)! > 0, "No Charges Found") } } func testChargeListByStorePromise() { let asyncExpectation = expectation(description: "longRunningFunction") let data: ChargeListRequestData = ChargeListRequestData() var charges: Charges? self.api?.chargeResource?.delegate = self self.api?.chargeResource?.list(data: data, callback: nil).then(execute: { c -> Void in if (!c.items.isEmpty) { self.api?.chargeResource?.listByStore(storeId: c.items.first!.storeId, data: data, callback: nil).then(execute: { c -> Void in charges = c asyncExpectation.fulfill() }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) } else { asyncExpectation.fulfill() } }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charges, "No Charges") XCTAssert((charges?.items.count)! > 0, "No Charges Found") } } func testChargeGetPromise() { let asyncExpectation = self.expectation(description: "longRunningFunction") let data: ChargeListRequestData = ChargeListRequestData() var charge: Charge? self.api?.chargeResource?.list(data: data, callback: nil).then(execute: { c -> Void in if (!c.items.isEmpty) { self.api?.chargeResource?.get(storeId: c.items.last!.storeId, id: c.items.last!.id, callback: nil).then(execute: { ch -> Void in charge = ch asyncExpectation.fulfill() }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) } else { asyncExpectation.fulfill() } }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charge, "No Charge") } } /* func testChargePoll() { let asyncExpectation = self.expectation(description: "longRunningFunction") let updateData: ChargeUpdateRequestData = ChargeUpdateRequestData(status: ChargeStatus.successful, metadata: nil) var charge: Charge? self.createTransactionToken(api: self.api!, callback: { (t, e) in let data: ChargeCreateRequestData = ChargeCreateRequestData(transactionTokenId: t!.id, amount: 1000, currency: "JPY") self.api?.chargeResource?.create(data: data, callback: { (c, e) in self.api?.chargeResource?.poll(storeId: c!.storeId, id: c!.id, callback: { (cr, e) in charge = cr asyncExpectation.fulfill() }) DispatchQueue.global(qos: .background).async { self.api?.chargeResource?.update(storeId: c!.storeId, id: c!.id, data: updateData, callback: nil).then(execute: { ch -> Void in print(ch) }) } }) }) self.waitForExpectations(timeout: 610) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charge, "No Charge") } } func testChargePollPromise() { let asyncExpectation = self.expectation(description: "longRunningFunction") let updateData: ChargeUpdateRequestData = ChargeUpdateRequestData(status: ChargeStatus.successful, metadata: nil) var charge: Charge? var err: Error? self.createTransactionToken(api: self.api!, callback: nil).then(execute: { t -> Void in let data: ChargeCreateRequestData = ChargeCreateRequestData(transactionTokenId: t.id, amount: 1000, currency: "JPY") self.api?.chargeResource?.create(data: data, callback: nil).then(execute: { c -> Void in self.api?.chargeResource?.poll(storeId: c.storeId, id: c.id, callback: nil).then(execute: { cr -> Void in charge = cr asyncExpectation.fulfill() }).catch(execute: { e -> Void in err = e asyncExpectation.fulfill() }) DispatchQueue.global(qos: .background).async { self.api?.chargeResource?.update(storeId: c.storeId, id: c.id, data: updateData, callback: nil).then(execute: { ch -> Void in print(ch) }) } }).catch(execute: { e -> Void in err = e asyncExpectation.fulfill() }) }) /*self.api?.storeResource?.list(data: nil, callback: nil).then(execute: { stores -> Void in self.api?.chargeResource?.poll(storeId: stores.items.first!.id, id: , callback: nil).then(execute: { c -> Void in charge = c asyncExpectation.fulfill() }).catch(execute: { e -> Void in err = e asyncExpectation.fulfill() }) })*/ self.waitForExpectations(timeout: 610) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNil(err, "Something went horribly wrong") XCTAssertNotNil(charge, "No Charge") } } */ func testChargeCreatePromise() { let asyncExpectation = expectation(description: "longRunningFunction") var charge: Charge? self.api?.chargeResource?.delegate = self self.createTransactionToken(api: self.api!, callback: nil).then(execute: { t -> Void in let data: ChargeCreateRequestData = ChargeCreateRequestData(transactionTokenId: t.id, amount: 1000, currency: "JPY") self.api?.chargeResource?.create(data: data, callback: nil).then(execute: { c -> Void in charge = c asyncExpectation.fulfill() }).catch(execute: { e -> Void in asyncExpectation.fulfill() }) }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNotNil(charge, "No Charge Created") } } func testChargeUpdatePromise() { let asyncExpectation = self.expectation(description: "longRunningFunction") let updateData: ChargeUpdateRequestData = ChargeUpdateRequestData(metadata: ["id": "testid" as AnyObject]) var charge: Charge? var err: Error? self.createTransactionToken(api: self.api!, callback: nil).then(execute: { t -> Void in let createData: ChargeCreateRequestData = ChargeCreateRequestData(transactionTokenId: t.id, amount: 1000, currency: "JPY") self.api?.chargeResource?.create(data: createData, callback: nil).then(execute: { c -> Void in self.api?.chargeResource?.update(storeId: c.storeId, id: c.id, data: updateData, callback: nil).then(execute: { ch -> Void in charge = ch asyncExpectation.fulfill() }).catch(execute: { e -> Void in err = e asyncExpectation.fulfill() }) }).catch(execute: { e -> Void in err = e asyncExpectation.fulfill() }) }) self.waitForExpectations(timeout: 15) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNil(err, "Something went horribly wrong") XCTAssertNotNil(charge, "No Charge") XCTAssert(charge?.metadata?["id"] as! String == updateData.metadata?["id"] as! String, "Meta data not updated") } } func createStore(api: SDK, callback: ResponseCallback<Store>?) { let data: StoreCreateRequestData = StoreCreateRequestData(name: "my store \(Int(arc4random()))", configuration: nil) api.storeResource?.delegate = self api.storeResource?.create(data: data, callback: { (s, e) in callback?(s, e) }) } func createTransactionToken(api: SDK, callback: ResponseCallback<TransactionToken>?) -> Promise<TransactionToken> { let cardData: TransactionTokenCardRequestData = TransactionTokenCardRequestData( cardholder: "TEST TEST", cardNumber: "5521773406855719", expMonth: "10", expYear: "2019", cvv: "234") let data: TransactionTokenCreateRequestData = TransactionTokenCreateRequestData( paymentType: "card", email: "[email protected]", data: cardData) api.transactionTokenResource?.delegate = self return (api.transactionTokenResource?.create(data: data, callback: { (t, e) in callback?(t, e) }))! } }
a9c56ae929005bb1840ed9eca0cc2e71
41.875
147
0.57501
false
true
false
false
Piwigo/Piwigo-Mobile
refs/heads/master
piwigo/Image/Extensions/ImageViewController+Menus.swift
mit
1
// // ImageViewController+Menus.swift // piwigo // // Created by Eddy Lelièvre-Berna on 19/06/2022. // Copyright © 2022 Piwigo.org. All rights reserved. // import Foundation import UIKit import piwigoKit @available(iOS 14.0, *) extension ImageViewController { // MARK: - Albums related Actions & Menus /// - for copying images to another album /// - for moving images to another album /// - for setting an image as album thumbnail func albumMenu() -> UIMenu { if NetworkVars.hasAdminRights { return UIMenu(title: "", image: nil, identifier: UIMenu.Identifier("org.piwigo.piwigoImage.album"), options: .displayInline, children: [copyAction(), moveAction(), setAsThumbnailAction()]) } else { return UIMenu(title: "", image: nil, identifier: UIMenu.Identifier("org.piwigo.piwigoImage.album"), options: .displayInline, children: [copyAction(), moveAction()]) } } private func copyAction() -> UIAction { // Copy image to album let action = UIAction(title: NSLocalizedString("copyImage_title", comment: "Copy to Album"), image: UIImage(systemName: "rectangle.stack.badge.plus"), handler: { [unowned self] _ in // Disable buttons during action setEnableStateOfButtons(false) // Present album selector for copying image selectCategory(withAction: .copyImage) }) action.accessibilityIdentifier = "Copy" return action } private func moveAction() -> UIAction { let action = UIAction(title: NSLocalizedString("moveImage_title", comment: "Move to Album"), image: UIImage(systemName: "arrowshape.turn.up.right"), handler: { [unowned self] _ in // Disable buttons during action setEnableStateOfButtons(false) // Present album selector for moving image selectCategory(withAction: .moveImage) }) action.accessibilityIdentifier = "Move" return action } private func setAsThumbnailAction() -> UIAction { let action = UIAction(title: NSLocalizedString("imageOptions_setAlbumImage", comment:"Set as Album Thumbnail"), image: UIImage(systemName: "rectangle.and.paperclip"), handler: { [unowned self] _ in // Present album selector for setting album thumbnail self.setAsAlbumImage() }) action.accessibilityIdentifier = "SetThumbnail" return action } // MARK: - Images related Actions & Menus /// - for editing image parameters func editMenu() -> UIMenu { return UIMenu(title: "", image: nil, identifier: UIMenu.Identifier("org.piwigo.piwigoImage.edit"), options: .displayInline, children: [editParamsAction()]) } private func editParamsAction() -> UIAction { // Edit image parameters let action = UIAction(title: NSLocalizedString("imageOptions_properties", comment: "Modify Information"), image: UIImage(systemName: "pencil"), handler: { _ in // Edit image informations self.editImage() }) action.accessibilityIdentifier = "Edit Parameters" return action } }
2ec3413c945309f5eebdc3f6376fe47c
37.9375
100
0.55511
false
false
false
false
adolfrank/Swift_practise
refs/heads/master
22-day/22-day/MagicMoveTransion.swift
mit
1
// // MagicMoveTransion.swift // MagicMove // // Created by BourneWeng on 15/7/13. // Copyright (c) 2015年 Bourne. All rights reserved. // import UIKit class MagicMoveTransion: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { //1.获取动画的源控制器和目标控制器 let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! HomeViewController let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController let container = transitionContext.containerView() //2.创建一个 Cell 中 imageView 的截图,并把 imageView 隐藏,造成使用户以为移动的就是 imageView 的假象 let snapshotView = fromVC.selectedCell.cardImage.snapshotViewAfterScreenUpdates(false) snapshotView.frame = container!.convertRect(fromVC.selectedCell.cardImage.frame, fromView: fromVC.selectedCell) fromVC.selectedCell.cardImage.hidden = true //3.设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1 toVC.view.frame = transitionContext.finalFrameForViewController(toVC) toVC.view.alpha = 0 //4.都添加到 container 中。注意顺序不能错了 container!.addSubview(toVC.view) container!.addSubview(snapshotView) //5.执行动画 /* 这时avatarImageView.frame的值只是跟在IB中一样的, 如果换成屏幕尺寸不同的模拟器运行时avatarImageView会先移动到IB中的frame,动画结束后才会突然变成正确的frame。 所以需要在动画执行前执行一次toVC.avatarImageView.layoutIfNeeded() update一次frame */ toVC.avatarImage.layoutIfNeeded() UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in snapshotView.frame = toVC.avatarImage.frame toVC.view.alpha = 1 }) { (finish: Bool) -> Void in fromVC.selectedCell.cardImage.hidden = false toVC.avatarImage.image = toVC.image snapshotView.removeFromSuperview() //一定要记得动画完成后执行此方法,让系统管理 navigation transitionContext.completeTransition(true) } } }
ac568df2c18b516ea1410f965121ac15
42.222222
159
0.695373
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Tests/Source/Model/Messages/ZMClientMessageTests+Editing.swift
gpl-3.0
1
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import WireDataModel class ZMClientMessageTests_Editing: BaseZMClientMessageTests { func testThatItEditsTheMessage() throws { // GIVEN let conversationID = UUID.create() let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.remoteIdentifier = conversationID let user = ZMUser.insertNewObject(in: uiMOC) user.remoteIdentifier = UUID.create() let nonce = UUID.create() let message = ZMClientMessage(nonce: nonce, managedObjectContext: uiMOC) message.sender = user try message.setUnderlyingMessage(GenericMessage(content: Text(content: "text"))) conversation.append(message) let edited = MessageEdit.with { $0.replacingMessageID = nonce.transportString() $0.text = Text(content: "editedText") } let genericMessage = GenericMessage(content: edited) let updateEvent = createUpdateEvent(nonce, conversationID: conversationID, genericMessage: genericMessage, senderID: message.sender!.remoteIdentifier) // WHEN var editedMessage: ZMClientMessage? performPretendingUiMocIsSyncMoc { editedMessage = ZMClientMessage.editMessage(withEdit: edited, forConversation: conversation, updateEvent: updateEvent, inContext: self.uiMOC, prefetchResult: ZMFetchRequestBatchResult()) } // THEN XCTAssertEqual(editedMessage?.messageText, "editedText") } } class ZMClientMessageTests_TextMessageData: BaseZMClientMessageTests { func testThatItUpdatesTheMesssageText_WhenEditing() { // given let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: "hello") as! ZMClientMessage message.delivered = true // when message.textMessageData?.editText("good bye", mentions: [], fetchLinkPreview: false) // then XCTAssertEqual(message.textMessageData?.messageText, "good bye") } func testThatItClearReactions_WhenEditing() { // given let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: "hello") as! ZMClientMessage message.delivered = true message.addReaction("🤠", forUser: selfUser) XCTAssertFalse(message.reactions.isEmpty) // when message.textMessageData?.editText("good bye", mentions: [], fetchLinkPreview: false) // then XCTAssertTrue(message.reactions.isEmpty) } func testThatItKeepsQuote_WhenEditing() { // given let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.remoteIdentifier = UUID.create() let quotedMessage = try! conversation.appendText(content: "Let's grab some lunch") as! ZMClientMessage let message = try! conversation.appendText(content: "Yes!", replyingTo: quotedMessage) as! ZMClientMessage message.delivered = true XCTAssertTrue(message.hasQuote) // when message.textMessageData?.editText("good bye", mentions: [], fetchLinkPreview: false) // then XCTAssertTrue(message.hasQuote) } } // MARK: - Payload creation extension ZMClientMessageTests_Editing { private func checkThatItCanEditAMessageFrom(sameSender: Bool, shouldEdit: Bool) { // given let oldText = "Hallo" let newText = "Hello" let sender = sameSender ? self.selfUser : ZMUser.insertNewObject(in: self.uiMOC) if !sameSender { sender?.remoteIdentifier = UUID.create() } let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMClientMessage message.sender = sender message.markAsSent() message.serverTimestamp = Date.init(timeIntervalSinceNow: -20) let originalNonce = message.nonce XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertEqual(conversation.allMessages.count, 1) XCTAssertEqual(conversation.hiddenMessages.count, 0) // when message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: true) // then XCTAssertEqual(conversation.allMessages.count, 1) if shouldEdit { XCTAssertEqual(message.textMessageData?.messageText, newText) XCTAssertEqual(message.normalizedText, newText.lowercased()) XCTAssertEqual(message.underlyingMessage?.edited.replacingMessageID, originalNonce!.transportString()) XCTAssertNotEqual(message.nonce, originalNonce) } else { XCTAssertEqual(message.textMessageData?.messageText, oldText) } } func testThatItCanEditAMessage_SameSender() { checkThatItCanEditAMessageFrom(sameSender: true, shouldEdit: true) } func testThatItCanNotEditAMessage_DifferentSender() { checkThatItCanEditAMessageFrom(sameSender: false, shouldEdit: false) } func testThatExtremeCombiningCharactersAreRemovedFromTheMessage() { // GIVEN let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() // WHEN let message: ZMMessage = try! conversation.appendText(content: "ť̹̱͉̥̬̪̝ͭ͗͊̕e͇̺̳̦̫̣͕ͫͤ̅s͇͎̟͈̮͎̊̾̌͛ͭ́͜t̗̻̟̙͑ͮ͊ͫ̂") as! ZMMessage // THEN XCTAssertEqual(message.textMessageData?.messageText, "test̻̟̙") } func testThatItResetsTheLinkPreviewState() { // given let oldText = "Hallo" let newText = "Hello" let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMClientMessage message.serverTimestamp = Date.init(timeIntervalSinceNow: -20) message.linkPreviewState = ZMLinkPreviewState.done message.markAsSent() XCTAssertEqual(message.linkPreviewState, ZMLinkPreviewState.done) // when message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: true) // then XCTAssertEqual(message.linkPreviewState, ZMLinkPreviewState.waitingToBeProcessed) } func testThatItDoesNotFetchLinkPreviewIfExplicitlyToldNotTo() { // given let oldText = "Hallo" let newText = "Hello" let fetchLinkPreview = false let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText, mentions: [], fetchLinkPreview: fetchLinkPreview, nonce: UUID.create()) as! ZMClientMessage message.serverTimestamp = Date.init(timeIntervalSinceNow: -20) message.markAsSent() XCTAssertEqual(message.linkPreviewState, ZMLinkPreviewState.done) // when message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: fetchLinkPreview) // then XCTAssertEqual(message.linkPreviewState, ZMLinkPreviewState.done) } func testThatItDoesNotEditAMessageThatFailedToSend() { // given let oldText = "Hallo" let newText = "Hello" let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message: ZMMessage = try! conversation.appendText(content: oldText) as! ZMMessage message.serverTimestamp = Date.init(timeIntervalSinceNow: -20) message.expire() XCTAssertEqual(message.deliveryState, ZMDeliveryState.failedToSend) // when message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: true) // then XCTAssertEqual(message.textMessageData?.messageText, oldText) } func testThatItUpdatesTheUpdatedTimestampAfterSuccessfulUpdate() { // given let oldText = "Hallo" let newText = "Hello" let originalDate = Date.init(timeIntervalSinceNow: -50) let updateDate: Date = Date.init(timeIntervalSinceNow: -20) let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMMessage message.serverTimestamp = originalDate message.markAsSent() conversation.lastModifiedDate = originalDate conversation.lastServerTimeStamp = originalDate XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertEqual(conversation.allMessages.count, 1) XCTAssertEqual(conversation.hiddenMessages.count, 0) message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: false) // when message.update(withPostPayload: ["time": updateDate], updatedKeys: nil) // then XCTAssertEqual(message.serverTimestamp, originalDate) XCTAssertEqual(message.updatedAt, updateDate) XCTAssertEqual(message.textMessageData?.messageText, newText) } func testThatItDoesNotOverwritesEditedTextWhenMessageExpiresButReplacesNonce() { // given let oldText = "Hallo" let newText = "Hello" let originalDate = Date.init(timeIntervalSinceNow: -50) let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMMessage message.serverTimestamp = originalDate message.markAsSent() conversation.lastModifiedDate = originalDate conversation.lastServerTimeStamp = originalDate let originalNonce = message.nonce XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertEqual(conversation.allMessages.count, 1) XCTAssertEqual(conversation.hiddenMessages.count, 0) message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: false) // when message.expire() // then XCTAssertEqual(message.nonce, originalNonce) } func testThatWhenResendingAFailedEditItReappliesTheEdit() { // given let oldText = "Hallo" let newText = "Hello" let originalDate = Date.init(timeIntervalSinceNow: -50) let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message: ZMClientMessage = try! conversation.appendText(content: oldText) as! ZMClientMessage message.serverTimestamp = originalDate message.markAsSent() conversation.lastModifiedDate = originalDate conversation.lastServerTimeStamp = originalDate let originalNonce = message.nonce XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertEqual(conversation.allMessages.count, 1) XCTAssertEqual(conversation.hiddenMessages.count, 0) message.textMessageData?.editText(newText, mentions: [], fetchLinkPreview: false) let editNonce1 = message.nonce message.expire() // when message.resend() let editNonce2 = message.nonce // then XCTAssertFalse(message.isExpired) XCTAssertNotEqual(editNonce2, editNonce1) XCTAssertEqual(message.underlyingMessage?.edited.replacingMessageID, originalNonce?.transportString()) } private func createMessageEditUpdateEvent(oldNonce: UUID, newNonce: UUID, conversationID: UUID, senderID: UUID, newText: String) -> ZMUpdateEvent? { let genericMessage: GenericMessage = GenericMessage(content: MessageEdit(replacingMessageID: oldNonce, text: Text(content: newText, mentions: [], linkPreviews: [], replyingTo: nil)), nonce: newNonce) let data = try? genericMessage.serializedData().base64String() let payload: NSMutableDictionary = [ "conversation": conversationID.transportString(), "from": senderID.transportString(), "time": Date().transportString(), "data": [ "text": data ?? "" ], "type": "conversation.otr-message-add" ] return ZMUpdateEvent.eventFromEventStreamPayload(payload, uuid: UUID.create()) } private func createTextAddedEvent(nonce: UUID, conversationID: UUID, senderID: UUID) -> ZMUpdateEvent? { let genericMessage: GenericMessage = GenericMessage(content: Text(content: "Yeah!", mentions: [], linkPreviews: [], replyingTo: nil), nonce: nonce) let data = try? genericMessage.serializedData().base64String() let payload: NSMutableDictionary = [ "conversation": conversationID.transportString(), "from": senderID.transportString(), "time": Date().transportString(), "data": [ "text": data ?? "" ], "type": "conversation.otr-message-add" ] return ZMUpdateEvent.eventFromEventStreamPayload(payload, uuid: UUID.create()) } func testThatItEditsMessageWithQuote() { // given let oldText = "Hallo" let newText = "Hello" let senderID = self.selfUser.remoteIdentifier let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let quotedMessage = try! conversation.appendText(content: "Quote") as! ZMMessage let message = try! conversation.appendText(content: oldText, mentions: [], replyingTo: quotedMessage, fetchLinkPreview: false, nonce: UUID.create()) as! ZMMessage self.uiMOC.saveOrRollback() let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: senderID!, newText: newText) let oldNonce = message.nonce // when self.performPretendingUiMocIsSyncMoc { ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertEqual(message.textMessageData?.messageText, newText) XCTAssertTrue(message.textMessageData!.hasQuote) XCTAssertNotEqual(message.nonce, oldNonce) XCTAssertEqual(message.textMessageData?.quoteMessage as! ZMMessage, quotedMessage) } func testThatReadExpectationIsKeptAfterEdit() { // given let oldText = "Hallo" let newText = "Hello" let senderID = self.selfUser.remoteIdentifier self.selfUser.readReceiptsEnabled = true let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() conversation.conversationType = ZMConversationType.oneOnOne let message = try! conversation.appendText(content: oldText, mentions: [], fetchLinkPreview: false, nonce: UUID.create()) as! ZMClientMessage var genericMessage = message.underlyingMessage! genericMessage.setExpectsReadConfirmation(true) do { try message.setUnderlyingMessage(genericMessage) } catch { XCTFail() } let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: senderID!, newText: newText) let oldNonce = message.nonce // when self.performPretendingUiMocIsSyncMoc { ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertEqual(message.textMessageData?.messageText, newText) XCTAssertNotEqual(message.nonce, oldNonce) XCTAssertTrue(message.needsReadConfirmation) } func checkThatItEditsMessageFor(sameSender: Bool, shouldEdit: Bool) { // given let oldText = "Hallo" let newText = "Hello" let senderID = sameSender ? self.selfUser.remoteIdentifier : UUID.create() let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMMessage message.addReaction("👻", forUser: self.selfUser) self.uiMOC.saveOrRollback() let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: senderID!, newText: newText) let oldNonce = message.nonce // when self.performPretendingUiMocIsSyncMoc { ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then if shouldEdit { XCTAssertEqual(message.textMessageData?.messageText, newText) XCTAssertNotEqual(message.nonce, oldNonce) XCTAssertTrue(message.reactions.isEmpty) XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertNil(message.hiddenInConversation) } else { XCTAssertEqual(message.textMessageData?.messageText, oldText) XCTAssertEqual(message.nonce, oldNonce) XCTAssertEqual(message.visibleInConversation, conversation) XCTAssertNil(message.hiddenInConversation) } } func testThatEditsMessageWhenSameSender() { checkThatItEditsMessageFor(sameSender: true, shouldEdit: true) } func testThatDoesntEditMessageWhenSenderIsDifferent() { checkThatItEditsMessageFor(sameSender: false, shouldEdit: false) } func testThatItDoesNotInsertAMessageWithANonceBelongingToAHiddenMessage() { // given let oldText = "Hallo" let senderID = self.selfUser.remoteIdentifier let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMMessage message.visibleInConversation = nil message.hiddenInConversation = conversation let updateEvent = createTextAddedEvent(nonce: message.nonce!, conversationID: conversation.remoteIdentifier!, senderID: senderID!) // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertNil(newMessage) } func testThatItSetsTheTimestampsOfTheOriginalMessage() { // given let oldText = "Hallo" let newText = "Hello" let oldDate = Date.init(timeIntervalSinceNow: -20) let sender = ZMUser.insertNewObject(in: self.uiMOC) sender.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message = try! conversation.appendText(content: oldText) as! ZMMessage message.sender = sender message.serverTimestamp = oldDate conversation.lastModifiedDate = oldDate conversation.lastServerTimeStamp = oldDate conversation.lastReadServerTimeStamp = oldDate XCTAssertEqual(conversation.estimatedUnreadCount, 0) let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: sender.remoteIdentifier, newText: newText) // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertEqual(conversation.lastModifiedDate, oldDate) XCTAssertEqual(conversation.lastServerTimeStamp, oldDate) XCTAssertEqual(newMessage?.serverTimestamp, oldDate) XCTAssertEqual(newMessage?.updatedAt, updateEvent!.timestamp) XCTAssertEqual(conversation.estimatedUnreadCount, 0) } func testThatItDoesNotReinsertAMessageThatHasBeenPreviouslyHiddenLocally() { // given let oldText = "Hallo" let newText = "Hello" let oldDate = Date.init(timeIntervalSinceNow: -20) let sender = ZMUser.insertNewObject(in: self.uiMOC) sender.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() // insert message locally let message: ZMMessage = try! conversation.appendText(content: oldText) as! ZMMessage message.sender = sender message.serverTimestamp = oldDate // hide message locally ZMMessage.hideMessage(message) XCTAssertTrue(message.isZombieObject) let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: sender.remoteIdentifier, newText: newText) // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertNil(newMessage) XCTAssertNil(message.visibleInConversation) XCTAssertTrue(message.isZombieObject) XCTAssertTrue(message.hasBeenDeleted) XCTAssertNil(message.textMessageData) XCTAssertNil(message.sender) XCTAssertNil(message.senderClientID) let clientMessage = message as! ZMClientMessage XCTAssertNil(clientMessage.underlyingMessage) XCTAssertEqual(clientMessage.dataSet.count, 0) } func testThatItClearsReactionsWhenAMessageIsEdited() { // given let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message: ZMMessage = try! conversation.appendText(content: "Hallo") as! ZMMessage let otherUser = ZMUser.insertNewObject(in: self.uiMOC) otherUser.remoteIdentifier = UUID.create() message.addReaction("😱", forUser: self.selfUser) message.addReaction("🤗", forUser: otherUser) XCTAssertFalse(message.reactions.isEmpty) let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: message.sender!.remoteIdentifier!, newText: "Hello") // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertTrue(message.reactions.isEmpty) XCTAssertEqual(conversation.allMessages.count, 1) let editedMessage = conversation.lastMessage as! ZMMessage XCTAssertTrue(editedMessage.reactions.isEmpty) XCTAssertEqual(editedMessage.textMessageData?.messageText, "Hello") } func testThatItClearsReactionsWhenAMessageIsEditedRemotely() { // given let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message: ZMMessage = try! conversation.appendText(content: "Hallo") as! ZMMessage let otherUser = ZMUser.insertNewObject(in: self.uiMOC) otherUser.remoteIdentifier = UUID.create() message.addReaction("😱", forUser: self.selfUser) message.addReaction("🤗", forUser: otherUser) XCTAssertFalse(message.reactions.isEmpty) let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: message.sender!.remoteIdentifier, newText: "Hello") // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertTrue(message.reactions.isEmpty) let editedMessage = conversation.lastMessage as! ZMMessage XCTAssertTrue(editedMessage.reactions.isEmpty) XCTAssertEqual(editedMessage.textMessageData?.messageText, "Hello") } func testThatMessageNonPersistedIdentifierDoesNotChangeAfterEdit() { // given let oldText = "Mamma mia" let newText = "here we go again" let oldNonce = UUID.create() let sender = ZMUser.insertNewObject(in: self.uiMOC) sender.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.uiMOC) conversation.remoteIdentifier = UUID.create() let message: ZMMessage = try! conversation.appendText(content: oldText) as! ZMMessage message.sender = sender message.nonce = oldNonce let oldIdentifier = message.nonpersistedObjectIdentifer let updateEvent = createMessageEditUpdateEvent(oldNonce: message.nonce!, newNonce: UUID.create(), conversationID: conversation.remoteIdentifier!, senderID: message.sender!.remoteIdentifier!, newText: newText) // when var newMessage: ZMClientMessage? self.performPretendingUiMocIsSyncMoc { newMessage = ZMClientMessage.createOrUpdate(from: updateEvent!, in: self.uiMOC, prefetchResult: nil) } // then XCTAssertNotEqual(oldNonce, newMessage!.nonce) XCTAssertEqual(oldIdentifier, newMessage!.nonpersistedObjectIdentifer) } }
221c6b5118a89166664e72d73ed21bc2
39.336735
207
0.669148
false
false
false
false
wow1881/flybu-hangman
refs/heads/master
Hangman/ViewController.swift
mit
1
// // ViewController.swift // Hangman // // Created by Alex Banh on 8/8/16. // Copyright © 2016 Flybu. All rights reserved. // // ViewController.swift provides code for the interaction between the storyboard and // HangmanBrain. It receives input from the view, sends relevant information to the // brain, and then updates elements of the view accordingly import UIKit class ViewController: UIViewController { // MARK: Properties // The current "code" presented to the user @IBOutlet weak var HangmanWord: UILabel! // The current informational message displayed (Good luck, try again, etc) @IBOutlet weak var Message: UILabel! // Displays the number of guesses left @IBOutlet weak var GuessesLeft: UILabel! // Class which contains paths and methods for drawing the hangman @IBOutlet weak var hangmanView: HangmanView! // Set which contains the Buttons used in the game var buttonsSet = Set<UIButton>() // Class which processes the actual game mechanics. See HangmanBrain.swift comments for more private var Brain = HangmanBrain() // Boolean which represents whether a game is currently occurring or not private var gameOver = true // Keeps track of the remaining number of guesses private var numGuessesLeft = 5 // MARK: Actions // pre: Start_Reset takes a sender of type UIButton // post: On button press, Start_Reset uses HangmanBrain to reset the game to an initial // state. It additionally resets the number of wrongs in hangmanView. @IBAction func Start_Reset(sender: UIButton) { hangmanView.wrongs = 0 HangmanWord.text = Brain.startOrResetGame() Message.text = "Good Luck!" sender.setTitle("Reset", forState: UIControlState.Normal) gameOver = false numGuessesLeft = 6 GuessesLeft.text = "Guesses Left: " + String(numGuessesLeft) for button in buttonsSet { button.enabled = true } } // pre: Letter takes a sender of type UIButton which represents the guessed letter // post: Letter uses HangmanBrain to check to see if the letter has been used. If it has // not been used, the func then uses HangmanBrain to see if the letter is contained // within the target word and whether the target word has been found. Also fades the button used. // Letter then updates var Message with a new message depending on the outcome. @IBAction func Letter(sender: UIButton) { if (!gameOver) { buttonsSet.insert(sender) let oldCode = HangmanWord.text var newCode = "" if let letter = sender.currentTitle { if (!Brain.checkIfUsed(letter)) { sender.adjustsImageWhenDisabled = true sender.enabled = false Brain.markAsUsed(letter) newCode = Brain.checkLetter(letter, oldCode: oldCode!) HangmanWord.text = newCode if (oldCode == newCode) { Message.text = "Try Again!" hangmanView.wrongs += 1 numGuessesLeft -= 1 GuessesLeft.text = "Guesses Left: " + String(numGuessesLeft) } else { Message.text = "Nice Job!" if (newCode.rangeOfString("_") == nil) { Message.text = "You win!" gameOver = true for button in buttonsSet { button.enabled = true } } } if (hangmanView.wrongs == 6) { Message.text = "Game Over!" gameOver = true HangmanWord.text = Brain.showAnswer() for button in buttonsSet { button.enabled = true } } } else { Message.text = "You already tried that!" } } } } // pre: hintButton takes a sender of type UIButton // gameOver is false (the game is currently running) // post: Updates var Message to print out hint (what letter to guess) @IBAction func hintButton(sender: UIButton) { if (gameOver == false) { Message.text = "Try '" + Brain.getHint() + "'" } } }
5ef74eafb5e4edeeb9bf25a2b15c79a5
38.724138
102
0.56467
false
false
false
false
Ahyufei/swift3-weibo
refs/heads/master
WeiBo/WeiBo/Classes/ViewModel(视图模型)/WBStatusListViewModel.swift
apache-2.0
1
// // WBStatusListViewModel.swift // WeiBo // // Created by 豪康 on 2017/8/2. // Copyright © 2017年 ahyufei. All rights reserved. // import Foundation /// 上拉 fileprivate let maxPullupTryTimes = 3 /* 字典转模型 刷新处理 */ /// 微博数据列表视图模型 class WBStatusListViewModel { /// 微博模型数组 lazy var statusList = [WBStatus]() /// 上拉刷新错误次数 fileprivate var pullupErrorTimes = 0 func loadStatus(pullup: Bool, completion: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) { // 判断是否上拉,同时检查刷新错误 if pullup && pullupErrorTimes > maxPullupTryTimes { completion(true, false) return } let since_id = pullup ? 0 : (statusList.first?.id ?? 0) // 上拉 let max_id = !pullup ? 0 : (statusList.last?.id ?? 0) WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in // 字典转模型 guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else { completion(isSuccess, false) return } // 拼接数据 // 上拉刷新, 将结果拼接数组在后 if pullup { self.statusList += array }else { // 下拉刷新, 将结果拼接数组在前 self.statusList = array + self.statusList } // 判断上拉刷新的数据量 if pullup && array.count == 0 { self.pullupErrorTimes += 1 completion(isSuccess, false) }else { // 完成回调 completion(isSuccess, true) } } } }
951e66fda59002897730fa1cbe77d9d7
25.045455
112
0.493892
false
false
false
false
roadfire/SwiftFonts
refs/heads/master
SwiftFonts/MasterViewController.swift
mit
1
// // MasterViewController.swift // SwiftFonts // // Created by Josh Brown on 6/3/14. // Copyright (c) 2014 Roadfire Software. All rights reserved. // import UIKit class MasterViewController: UITableViewController { let viewModel = MasterViewModel() override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.viewModel.numberOfSections() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.numberOfRowsInSection(section) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath); return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let label = UILabel(frame: CGRectMake(0, 0, 280, 200)) label.text = viewModel.titleAtIndexPath(indexPath) label.font = self.fontAtIndexPath(indexPath) label.sizeToFit() return max(label.font.lineHeight + label.font.ascender + -label.font.descender, 44) } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { cell.textLabel?.text = viewModel.titleAtIndexPath(indexPath) cell.textLabel?.font = self.fontAtIndexPath(indexPath) } func fontAtIndexPath(indexPath: NSIndexPath) -> UIFont { let fontName = viewModel.titleAtIndexPath(indexPath) return UIFont(name:fontName, size: UIFont.systemFontSize())! } }
419f979f3072627dc1f95c9b51239301
32.25
116
0.70561
false
false
false
false
gpancio/iOS-Prototypes
refs/heads/master
VehicleID/VehicleID/Classes/DataSetTableViewController.swift
mit
1
// // DataMapTableViewController.swift // VehicleID // import UIKit import GPUIKit public class DataSetTableViewController: ATViewController, UITableViewDataSource, UITableViewDelegate { var dataSet: DataSet? { didSet { if dataSet != nil && dataSet!.validSet.isEmpty { dataSet!.populate() { self.updateUI() } } } } var dataSetProvider: DataSetProvider? public weak var rootViewController: UIViewController? @IBOutlet weak var tableView: UITableView! @IBAction func donePressed(sender: AnyObject) { if let navController = navigationController, rootVC = rootViewController { navController.popToViewController(rootVC, animated: true) } } override public func viewDidLoad() { super.viewDidLoad() if let selectedString = dataSet?.selectedValue { if let index = dataSet?.validSet.indexOf(selectedString) { tableView.selectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.Middle) nextButton?.enabled = true } } } // MARK: - UITableViewDataSource public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSet?.validSet.count ?? 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) if let value = dataSet?.validSet[indexPath.row] { cell.textLabel?.text = value let selectedString = dataSet?.selectedValue if selectedString != nil && value == selectedString { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } } return cell } // MARK: - UITableViewDelegate public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { dataSet?.selectIndex(indexPath.row) if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.accessoryType = .Checkmark } nextButton?.enabled = true } public func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { dataSet?.deselectValue() if let cell = tableView.cellForRowAtIndexPath(indexPath) { cell.accessoryType = .None } nextButton?.enabled = false } func updateUI() { if let tableView = self.tableView { let range = NSMakeRange(0, self.tableView.numberOfSections) let sections = NSIndexSet(indexesInRange: range) tableView.reloadSections(sections, withRowAnimation: UITableViewRowAnimation.Fade) } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let vc = segue.destinationViewController as? DataSetTableViewController { if let key = segue.identifier { if let nextDataSet = dataSetProvider?.dataSet(forKey: key) { vc.dataSetProvider = dataSetProvider vc.dataSet = nextDataSet vc.rootViewController = rootViewController } } } } }
c78b6ad6a8c9fe9c40376d82850f980d
32.925926
155
0.623362
false
false
false
false
StephenVinouze/FlickrGallery
refs/heads/master
FlickrGallery/Classes/Transitions/GalleryPresentationAnimator.swift
apache-2.0
1
// // GalleryPresentationAnimator.swift // FlickrGallery // // Created by Stephen Vinouze on 18/11/2015. // // import UIKit class GalleryPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning { var openingFrame: CGRect? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let containerView = transitionContext.containerView() let animationDuration = self .transitionDuration(transitionContext) // add blurred background to the view let fromViewFrame = fromViewController.view.frame UIGraphicsBeginImageContext(fromViewFrame.size) fromViewController.view.drawViewHierarchyInRect(fromViewFrame, afterScreenUpdates: true) UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let snapshotView = toViewController.view.resizableSnapshotViewFromRect(toViewController.view.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero) snapshotView.frame = openingFrame! containerView?.addSubview(snapshotView) toViewController.view.alpha = 0.0 containerView?.addSubview(toViewController.view) UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 20.0, options: [], animations: { () -> Void in snapshotView.frame = fromViewController.view.frame }, completion: { (finished) -> Void in snapshotView.removeFromSuperview() toViewController.view.alpha = 1.0 transitionContext.completeTransition(finished) }) } }
fc28538c24d91978eb28fd44c9729ae8
40
166
0.707795
false
false
false
false
banxi1988/BXAppKit
refs/heads/master
BXiOSUtils/UIImageExtensions.swift
mit
1
// // UIImageExtensions.swift // Pods // // Created by Haizhen Lee on 15/12/6. // // import UIKit public enum BorderPosition{ case inside case center case outside } public enum CornerStyle{ case oval case semiCircle case radius(CGFloat) case none } public extension BanxiExtensions where Base:UIImage{ public static func roundImage(fillColor:UIColor? = nil, size:CGSize=CGSize(width: 32, height: 32), insets:CGPoint = .zero, cornerStyle:CornerStyle = .radius(4), borderPosition:BorderPosition = .inside, borderWidth:CGFloat = 0, borderColor:UIColor? = nil ) -> UIImage{ // 为 border 腾出点地方 // size 参数定义的是画而大小, inset 之后的才是绘制的大小. let inset:CGFloat if borderWidth > 0 { switch borderPosition { case .inside: inset = borderWidth case .outside: inset = 0 case .center: inset = borderWidth * 0.5 } }else{ inset = 0 } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let pathRect = rect.insetBy(dx: inset + insets.x, dy: inset + insets.y) UIGraphicsBeginImageContextWithOptions(size, false, 0) let ctx = UIGraphicsGetCurrentContext() UIColor.clear.setFill() ctx?.fill(rect) fillColor?.setFill() borderColor?.setStroke() let path:UIBezierPath switch cornerStyle { case .oval: path = UIBezierPath(ovalIn: pathRect) case .semiCircle: let radius = pathRect.height * 0.5 path = UIBezierPath(roundedRect: pathRect, cornerRadius: radius) case .radius(let rd): path = UIBezierPath(roundedRect: pathRect, cornerRadius: rd) case .none: path = UIBezierPath(rect: pathRect) } path.lineWidth = borderWidth if fillColor != nil{ path.fill() } if borderWidth > 0 && borderColor != nil { path.stroke() } let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public static func circleImage(fillColor:UIColor,radius:CGFloat,padding:CGFloat = 0) -> UIImage{ let size = CGSize(width: radius * 2, height: radius * 2) let cornerRadius = radius return roundImage(fillColor:fillColor, size: size, insets: CGPoint(x:padding, y:padding), cornerStyle: .radius(cornerRadius)) } public static func transparentImage(size:CGSize=CGSize(width: 1, height: 1)) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) let ctx = UIGraphicsGetCurrentContext() UIColor.clear.setFill() ctx?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public static func image(fillColor:UIColor,width:CGFloat) -> UIImage{ return image(fillColor:fillColor, size: CGSize(width: width, height: width)) } public static func image(fillColor:UIColor,size:CGSize=CGSize(width: 1, height: 1)) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, true, 0) let ctx = UIGraphicsGetCurrentContext() fillColor.setFill() ctx?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public static func placeholder(_ width:CGFloat) -> UIImage{ return placeholder(size:CGSize(width: width, height: width)) } public static func placeholder(size:CGSize) -> UIImage{ return image(fillColor:UIColor.white, size: size) } public static func createImage(text:String, backgroundColor:UIColor, textColor:UIColor, font:UIFont, diameter:CGFloat) -> UIImage { let frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) let attrs = [NSAttributedStringKey.font:font, NSAttributedStringKey.foregroundColor:textColor ] let textFrame = text.boundingRect(with: frame.size, options:.usesFontLeading, attributes: attrs, context: nil) let dx = frame.midX - textFrame.midX let dy = frame.midY - textFrame.midY let drawPoint = CGPoint(x: dx, y: dy) UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() backgroundColor.setFill() ctx?.fill(frame) text.draw(at: drawPoint, withAttributes: attrs) let image = UIGraphicsGetImageFromCurrentImageContext() ctx?.restoreGState() UIGraphicsEndImageContext() return image! } /** diameter:直径 **/ public func circularImage(diameter:CGFloat, highlightedColor:UIColor? = nil) -> UIImage { let frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) UIGraphicsBeginImageContextWithOptions(frame.size, false,0.0) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() let imgPath = UIBezierPath(ovalIn: frame) imgPath.addClip() base.draw(in: frame) if let color = highlightedColor{ color.setFill() ctx?.fillEllipse(in: frame) } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func highlightImage(highlightedColor:UIColor? = nil,circular:Bool=true) -> UIImage { let frame = CGRect(x: 0, y: 0, width: base.size.width , height: base.size.height ) let color = highlightedColor ?? UIColor(white: 0.1, alpha: 0.3) UIGraphicsBeginImageContextWithOptions(frame.size, false,base.scale) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() if circular{ let imgPath = UIBezierPath(ovalIn: frame) imgPath.addClip() }else{ let imgPath = UIBezierPath(roundedRect: frame, cornerRadius: 10) imgPath.addClip() } base.draw(in: frame) color.setFill() if circular{ ctx?.fillEllipse(in: frame) }else{ ctx?.fill(frame) } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } /** * 判断一张图是否不存在 alpha 通道,注意 “不存在 alpha 通道” 不等价于 “不透明”。一张不透明的图有可能是存在 alpha 通道但 alpha 值为 1。 */ public var isOpaque:Bool{ guard let alphaInfo = base.cgImage?.alphaInfo else{ return true } return alphaInfo == .noneSkipLast || alphaInfo == .noneSkipFirst || alphaInfo == .none } public func withAlpha(_ alpha:CGFloat) -> UIImage{ UIGraphicsBeginImageContextWithOptions(base.size, false,base.scale) let drawingRect = CGRect(origin: .zero, size: base.size) base.draw(in: drawingRect, blendMode: .normal, alpha: alpha) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func grayImage() -> UIImage?{ // CGBitmapContextCreate 是无倍数的,所以要自己换算成1倍 let width = base.size.width * base.scale let height = base.size.height * base.scale let colorSpace = CGColorSpaceCreateDeviceGray() guard let ctx = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: (0 << 12)) else{ return nil } let imgRect = CGRect(x: 0, y: 0, width: width, height: height) ctx.draw(base.cgImage!, in: imgRect) guard let img = ctx.makeImage() else{ return nil } if isOpaque{ return UIImage(cgImage: img, scale: base.scale, orientation: base.imageOrientation) }else{ let space = CGColorSpaceCreateDeviceRGB() guard let alphaCtx = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue) else{ return nil } alphaCtx.draw(base.cgImage!, in: imgRect) guard let mask = alphaCtx.makeImage() else{ return nil } let maskedGrayImg = img.masking(mask) // 用 CGBitmapContextCreateImage 方式创建出来的图片,CGImageAlphaInfo 总是为 CGImageAlphaInfoNone,导致 qmui_opaque 与原图不一致,所以这里再做多一步 let grayImage = UIImage(cgImage: maskedGrayImg!, scale: base.scale, orientation: base.imageOrientation) UIGraphicsBeginImageContextWithOptions(grayImage.size, false, grayImage.scale) grayImage.draw(in: imgRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return finalImage } } // public func withTintColor(_ tintColor:UIColor) -> UIImage{ // let imgRect = CGRect(origin: .zero, size: base.size) // UIGraphicsBeginImageContextWithOptions(base.size, isOpaque, base.scale) // let ctx = UIGraphicsGetCurrentContext() // ctx?.translateBy(x: 0, y: imgRect.height) // ctx?.scaleBy(x: 1.0, y: -1.0) // ctx?.setBlendMode(.normal) // ctx?.clip(to: imgRect, mask: base.cgImage!) // ctx?.setFillColor(tintColor.cgColor) // ctx?.fill(imgRect) // let newImage = UIGraphicsGetImageFromCurrentImageContext() // UIGraphicsEndImageContext() // return newImage! // } public func withTintColor(_ tintColor:UIColor) -> UIImage{ let templateImage = base.withRenderingMode(.alwaysTemplate) UIGraphicsBeginImageContextWithOptions(templateImage.size, false, templateImage.scale) tintColor.set() templateImage.draw(at: CGPoint.zero) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func withPaddings(_ paddings:UIEdgeInsets) -> UIImage{ let newWidth = base.size.width + paddings.left + paddings.right let newHeight = base.size.height + paddings.top + paddings.bottom let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, isOpaque, base.scale) base.draw(at: CGPoint(x: paddings.left, y: paddings.right)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } public extension UIImage{ @available(*,deprecated, renamed: "bx.transparentImage") public class func bx_transparentImage(_ size:CGSize=CGSize(width: 1, height: 1)) -> UIImage{ return bx.transparentImage(size:size) } @available(*,deprecated, renamed: "bx.circleImage") public static func bx_circleImage(_ color:UIColor,radius:CGFloat) -> UIImage{ return bx.circleImage(fillColor:color,radius:radius) } @available(*,deprecated, renamed: "bx.roundImage") public static func bx_roundImage(_ color:UIColor,size:CGSize=CGSize(width: 32, height: 32),cornerRadius:CGFloat = 4) -> UIImage{ return bx.roundImage(fillColor:color, size: size, cornerStyle: .radius(cornerRadius), borderWidth: 0, borderColor: nil) } } public extension UIImage{ @available(*,deprecated, renamed: "rawImage") public var bx_rawImage:UIImage{ return self.withRenderingMode(.alwaysOriginal) } public var rawImage:UIImage{ return self.withRenderingMode(.alwaysOriginal) } public var templateImage:UIImage{ return self.withRenderingMode(.alwaysTemplate) } }
61a5b16e98fdb1dda67b64c1590d7233
32.754491
193
0.678109
false
false
false
false
CoderCYLee/CYInKeLive
refs/heads/master
CM/Pods/ReactiveSwift/Sources/Bag.swift
agpl-3.0
20
// // Bag.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-07-10. // Copyright (c) 2014 GitHub. All rights reserved. // /// A uniquely identifying token for removing a value that was inserted into a /// Bag. public final class RemovalToken {} /// An unordered, non-unique collection of values of type `Element`. public struct Bag<Element> { fileprivate var elements: ContiguousArray<BagElement<Element>> = [] public init() {} /// Insert the given value into `self`, and return a token that can /// later be passed to `remove(using:)`. /// /// - parameters: /// - value: A value that will be inserted. @discardableResult public mutating func insert(_ value: Element) -> RemovalToken { let token = RemovalToken() let element = BagElement(value: value, token: token) elements.append(element) return token } /// Remove a value, given the token returned from `insert()`. /// /// - note: If the value has already been removed, nothing happens. /// /// - parameters: /// - token: A token returned from a call to `insert()`. public mutating func remove(using token: RemovalToken) { let tokenIdentifier = ObjectIdentifier(token) // Removal is more likely for recent objects than old ones. for i in elements.indices.reversed() { if ObjectIdentifier(elements[i].token) == tokenIdentifier { elements.remove(at: i) break } } } } extension Bag: Collection { public typealias Index = Array<Element>.Index public var startIndex: Index { return elements.startIndex } public var endIndex: Index { return elements.endIndex } public subscript(index: Index) -> Element { return elements[index].value } public func index(after i: Index) -> Index { return i + 1 } public func makeIterator() -> BagIterator<Element> { return BagIterator(elements) } } private struct BagElement<Value> { let value: Value let token: RemovalToken } extension BagElement: CustomStringConvertible { var description: String { return "BagElement(\(value))" } } /// An iterator of `Bag`. public struct BagIterator<Element>: IteratorProtocol { private let base: ContiguousArray<BagElement<Element>> private var nextIndex: Int private let endIndex: Int fileprivate init(_ base: ContiguousArray<BagElement<Element>>) { self.base = base nextIndex = base.startIndex endIndex = base.endIndex } public mutating func next() -> Element? { let currentIndex = nextIndex if currentIndex < endIndex { nextIndex = currentIndex + 1 return base[currentIndex].value } return nil } }
271f0e2910493dbaeb3f688a7275d781
22.768519
78
0.703935
false
false
false
false
google/android-auto-companion-ios
refs/heads/main
Plugins/ProtoSourceGenerator/plugin.swift
apache-2.0
1
import PackagePlugin import Foundation /// Swift Package Manager Plugin that generates Swift sources for corresponding proto files. /// /// The `protoc` and `protoc-gen-swift` executables must be installed at `/usr/local/bin`. These /// tools may be installed through https://github.com/Homebrew/brew. /// /// The Swift sources will be output to the plugin's working directory. The generated types will /// have `public` access and belong to a module whose name matches the target containing the proto /// files. For example, if the plugin is applied to `AndroidAutoCompanionProtos` then a Swift file /// will be generated for each proto in `AndroidAutoCompanionProtos`, each type in the file will /// have public access, and they will belong to a module named `AndroidAutoCompanionProtos`. @main struct ProtoSourceGenerator: BuildToolPlugin { func createBuildCommands( context: PackagePlugin.PluginContext, target: PackagePlugin.Target ) async throws -> [PackagePlugin.Command] { print("ProtoSourceGenerator generating Swift source files for the proto files.") guard let target = target as? SourceModuleTarget else { print("ProtoSourceGenerator bailing due to non source module target: \(target).") return [] } return target.sourceFiles(withSuffix: "proto").map { proto in let input = proto.path print("Generating Swift Source for proto: \(input)") let output = context.pluginWorkDirectory.appending(["\(input.stem).pb.swift"]) let executable = Path("/usr/local/bin/protoc") let protoDir = input.removingLastComponent() let arguments = [ "--swift_opt=Visibility=Public", "--plugin=protoc-gen-swift=/usr/local/bin/protoc-gen-swift", "\(input.lastComponent)", "--swift_out=\(context.pluginWorkDirectory)/.", "--proto_path=\(protoDir)" ] return .buildCommand( displayName: "Generating Swift for: \(input)", executable: executable, arguments: arguments, inputFiles: [input], outputFiles: [output] ) } } }
afb6b85bb3c68eb92f252d8c8f33a5a6
42.4375
98
0.698801
false
false
false
false
mercadopago/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/PromoViewController.swift
mit
1
// // PromoViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 22/5/15. // Copyright (c) 2015 MercadoPago. All rights reserved. // import UIKit import Foundation public class PromoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var publicKey : String? @IBOutlet weak private var tableView : UITableView! var loadingView : UILoadingView! var promos : [Promo]! var bundle : NSBundle? = MercadoPago.getBundle() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(publicKey: String) { super.init(nibName: "PromoViewController", bundle: self.bundle) self.publicKey = publicKey } public init() { super.init(nibName: "PromoViewController", bundle: self.bundle) } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override public func viewDidLoad() { super.viewDidLoad() self.title = "Promociones".localized self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.tableView.registerNib(UINib(nibName: "PromoTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromoTableViewCell") self.tableView.registerNib(UINib(nibName: "PromosTyCTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromosTyCTableViewCell") self.tableView.registerNib(UINib(nibName: "PromoEmptyTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromoEmptyTableViewCell") self.tableView.estimatedRowHeight = 44.0 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.delegate = self self.tableView.dataSource = self self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) self.view.addSubview(self.loadingView) var mercadoPago : MercadoPago mercadoPago = MercadoPago(keyType: MercadoPago.PUBLIC_KEY, key: self.publicKey) mercadoPago.getPromos({ (promos) -> Void in self.promos = promos self.tableView.reloadData() self.loadingView.removeFromSuperview() }, failure: { (error) -> Void in if error.code == MercadoPago.ERROR_API_CODE { self.tableView.reloadData() self.loadingView.removeFromSuperview() } }) } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return promos == nil ? 1 : promos.count + 1 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if self.promos != nil && self.promos.count > 0 { if indexPath.row < self.promos.count { let promoCell : PromoTableViewCell = tableView.dequeueReusableCellWithIdentifier("PromoTableViewCell", forIndexPath: indexPath) as! PromoTableViewCell promoCell.setPromoInfo(self.promos[indexPath.row]) return promoCell } else { return tableView.dequeueReusableCellWithIdentifier("PromosTyCTableViewCell", forIndexPath: indexPath) as! PromosTyCTableViewCell } } else { return tableView.dequeueReusableCellWithIdentifier("PromoEmptyTableViewCell", forIndexPath: indexPath) as! PromoEmptyTableViewCell } } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if self.promos != nil && self.promos.count > 0 { if indexPath.row == self.promos.count { return 55 } else { return 151 } } else { return 80 } } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.promos.count { self.navigationController?.pushViewController(PromosTyCViewController(promos: self.promos), animated: true) } } }
afdceda4e89937e9508ef6be5e78964c
33.1875
154
0.75111
false
false
false
false
0x73/SwiftIconFont
refs/heads/master
SwiftIconFont/Classes/AppKit/SwiftIconFont+NSButton.swift
mit
1
// // SwiftIconFont+NSButton.swift // SwiftIconFont // // Created by Sedat G. ÇİFTÇİ on 7.06.2020. // Copyright © 2020 Sedat Gökbek ÇİFTÇİ. All rights reserved. // #if os(OSX) import Cocoa public extension NSButton { func parseIcon() { guard let currentTitle = self.title as NSString? else { return } let text = replace(withText: currentTitle) var fontSize: CGFloat = 17.0 let attrs = self.attributedTitle.attributes(at: 0, effectiveRange: nil) if let font = attrs[NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue)] as? Font { fontSize = font.pointSize } let attrTitle = getAttributedString(text, ofSize: fontSize) self.attributedTitle = attrTitle } } #endif
f7c991d01399d4e161de564867e39b43
28.481481
110
0.648241
false
false
false
false
d3st1ny94/LiquidHazard
refs/heads/master
LiquidHazard/ViewController.swift
gpl-3.0
1
// // ViewController.swift // LiquidHazard // // Created by adan de la pena on 6/20/16. // Copyright © 2016 adan de la pena. All rights reserved. // import UIKit import CoreMotion class ViewController: UIViewController { let gravity: Float = 9.80665 let ptmRatio: Float = 32 let particleRadius: Float = 4 var particleSystem: UnsafeMutablePointer<Void>! var uniformBuffer: MTLBuffer! = nil let motionManager: CMMotionManager = CMMotionManager() var device: MTLDevice! = nil var metalLayer: CAMetalLayer! = nil var vertexData:[Float] = [] var particleCount: Int = 0 var vertexBuffer: MTLBuffer! = nil var secondBuffer: MTLBuffer! = nil var GridMember: Grid? var gridData: [[Float]] = [[]] var pipelineGoalState: MTLRenderPipelineState! = nil var pipelineState: MTLRenderPipelineState! = nil var pipelineWallState: MTLRenderPipelineState! = nil var commandQueue: MTLCommandQueue! = nil var goalBuffer: MTLBuffer! = nil var StarterNumber: Int = 0 override func viewDidLoad() { super.viewDidLoad() resetGame() /* LiquidFun.createEdgeWithOrigin(Vector2D(x: 0, y: 0), destination: Vector2D(x: screenWidth / ptmRatio, y: screenHeight / ptmRatio)) */ createMetalLayer() gridData = (GridMember?.getVertexData())! refreshVertexBuffer() refreshUniformBuffer() buildRenderPipeline() render() let displayLink = CADisplayLink(target: self, selector: Selector("update:")) displayLink.frameInterval = 1 displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: { (accelerometerData, error) -> Void in if let data = accelerometerData { let acceleration = data.acceleration let gravityX = self.gravity * Float(acceleration.x) let gravityY = self.gravity * Float(acceleration.y) LiquidFun.setGravity(Vector2D(x: gravityX, y: gravityY)) } }) } func resetGame(){ LiquidFun.resetWorldWithGravity(Vector2D(x: 0, y: -gravity)) particleSystem = LiquidFun.createParticleSystemWithRadius(particleRadius / ptmRatio, dampingStrength: 0.2, gravityScale: 1, density: 1.2) LiquidFun.setParticleLimitForSystem(particleSystem, maxParticles: 1500) let screenSize: CGSize = UIScreen.mainScreen().bounds.size let screenWidth = Float(screenSize.width) let screenHeight = Float(screenSize.height) LiquidFun.createParticleBoxForSystem(particleSystem, position: Vector2D(x: screenWidth * 0.5 / ptmRatio, y: screenHeight * 0.5 / ptmRatio), size: Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio)) //count our particles for goal StarterNumber = Int(LiquidFun.particleCountForSystem(particleSystem)) LiquidFun.createEdgeBoxWithOrigin(Vector2D(x: 0, y: 0), size: Size2D(width: screenWidth / ptmRatio, height: screenHeight / ptmRatio)) GridMember = Grid(NumberOfCols: 18, NumberOfRows: 12, screenSize: Size2D(width : screenWidth, height: screenHeight), ptmRatio: ptmRatio) LiquidFun.createGoalWithSizeAndOrigin(Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio), origin: Vector2D(x: 0,y: 0)) vertexData = [ 0.0, 0.0, 0.0, 0, 100, 0.0, 100, 00, 0.0, 100, 100, 0.0] } func yodatime(vData: [Float]) -> MTLBuffer { let vSize = vData.count * sizeofValue(vData[0]) let ret:MTLBuffer? = device?.newBufferWithBytes(vData, length: vSize, options: []) return ret! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func update(displayLink:CADisplayLink) { autoreleasepool { LiquidFun.worldStep(displayLink.duration, velocityIterations: 8, positionIterations: 5) self.refreshVertexBuffer() self.render() } } func createMetalLayer() { device = MTLCreateSystemDefaultDevice() metalLayer = CAMetalLayer() metalLayer.device = device metalLayer.pixelFormat = .BGRA8Unorm metalLayer.framebufferOnly = true metalLayer.frame = view.layer.frame view.layer.addSublayer(metalLayer) } func refreshVertexBuffer () { particleCount = Int(LiquidFun.particleCountForSystem(particleSystem)) let positions = LiquidFun.particlePositionsForSystem(particleSystem) let bufferSize = sizeof(Float) * particleCount * 2 vertexBuffer = device.newBufferWithBytes(positions, length: bufferSize, options: []) } func makeOrthographicMatrix(left left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> [Float] { let ral = right + left let rsl = right - left let tab = top + bottom let tsb = top - bottom let fan = far + near let fsn = far - near return [2.0 / rsl, 0.0, 0.0, 0.0, 0.0, 2.0 / tsb, 0.0, 0.0, 0.0, 0.0, -2.0 / fsn, 0.0, -ral / rsl, -tab / tsb, -fan / fsn, 1.0] } func printParticleInfo() { let count = Int(LiquidFun.particleCountForSystem(particleSystem)) print("There are \(count) particles present") let positions = UnsafePointer<Vector2D>(LiquidFun.particlePositionsForSystem(particleSystem)) for i in 0..<count { let position = positions[i] print("particle: \(i) position: (\(position.x), \(position.y))") } } func refreshUniformBuffer () { // 1 let screenSize: CGSize = UIScreen.mainScreen().bounds.size let screenWidth = Float(screenSize.width) let screenHeight = Float(screenSize.height) let ndcMatrix = makeOrthographicMatrix(left: 0, right: screenWidth, bottom: 0, top: screenHeight, near: -1, far: 1) var radius = particleRadius var ratio = ptmRatio // 2 let floatSize = sizeof(Float) let float4x4ByteAlignment = floatSize * 4 let float4x4Size = floatSize * 16 let paddingBytesSize = float4x4ByteAlignment - floatSize * 2 let uniformsStructSize = float4x4Size + floatSize * 2 + paddingBytesSize // 3 uniformBuffer = device.newBufferWithLength(uniformsStructSize, options: []) let bufferPointer = uniformBuffer.contents() memcpy(bufferPointer, ndcMatrix, float4x4Size) memcpy(bufferPointer + float4x4Size, &ratio, floatSize) memcpy(bufferPointer + float4x4Size + floatSize, &radius, floatSize) } func buildRenderPipeline() { // 1 let defaultLibrary = device.newDefaultLibrary() var fragmentProgram = defaultLibrary?.newFunctionWithName("basic_fragment") var vertexProgram = defaultLibrary?.newFunctionWithName("particle_vertex") // 2 let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexProgram pipelineDescriptor.fragmentFunction = fragmentProgram pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm do { pipelineState = try device.newRenderPipelineStateWithDescriptor(pipelineDescriptor) } catch { print("Error occurred when creating render pipeline state: \(error)"); } fragmentProgram = defaultLibrary!.newFunctionWithName("wall_fragment") vertexProgram = defaultLibrary!.newFunctionWithName("basic_vertex") let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm do{ pipelineWallState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) } catch { } fragmentProgram = defaultLibrary!.newFunctionWithName("goal_fragment") vertexProgram = defaultLibrary!.newFunctionWithName("basic_vertex") let pipelineStateDescriptor2 = MTLRenderPipelineDescriptor() pipelineStateDescriptor2.vertexFunction = vertexProgram pipelineStateDescriptor2.fragmentFunction = fragmentProgram pipelineStateDescriptor2.colorAttachments[0].pixelFormat = .BGRA8Unorm do{ pipelineGoalState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor2) } catch { } // 3 commandQueue = device.newCommandQueue() } func youBallin() -> Bool{ let ballsin = Int(LiquidFun.getBallIn()); if ballsin == StarterNumber - 1 { return true } else { return false } } func render() { if let drawable = metalLayer.nextDrawable() { let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .Clear renderPassDescriptor.colorAttachments[0].storeAction = .Store renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) let commandBuffer = commandQueue.commandBuffer() let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) renderEncoder.setRenderPipelineState(pipelineState) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0) renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, atIndex: 1) if particleCount > 1 { renderEncoder.drawPrimitives(.Point, vertexStart: 0, vertexCount: particleCount, instanceCount: 1) } else { if youBallin() { //win resetGame(); } else { //lose } } renderEncoder.setRenderPipelineState(pipelineWallState) for i in 1...gridData.count{ secondBuffer = yodatime(gridData[i-1]) renderEncoder.setVertexBuffer(secondBuffer, offset: 0, atIndex: 2) renderEncoder.drawPrimitives(.LineStrip, vertexStart: 0, vertexCount: 4) } renderEncoder.setRenderPipelineState(pipelineGoalState) goalBuffer = yodatime(vertexData) renderEncoder.setVertexBuffer(goalBuffer, offset: 0, atIndex: 2) renderEncoder.drawPrimitives(.TriangleStrip, vertexStart: 0, vertexCount: 4) renderEncoder.endEncoding() commandBuffer.presentDrawable(drawable) commandBuffer.commit() } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // for touch in touches { /* let touchLocation = touch.locationInView(view) let position = Vector2D(x: Float(touchLocation.x) / ptmRatio, y: Float(view.bounds.height - touchLocation.y) / ptmRatio) let size = Size2D(width: 100 / ptmRatio, height: 100 / ptmRatio) LiquidFun.createParticleBoxForSystem(particleSystem, position: position, size: size)*/ // } super.touchesBegan(touches, withEvent:event) } }
a25480da0f037efdf8dd22d3d5489fa9
38.61794
208
0.633543
false
false
false
false
richeterre/jumu-nordost-ios
refs/heads/master
JumuNordost/Application/PerformanceView.swift
mit
1
// // PerformanceView.swift // JumuNordost // // Created by Martin Richter on 23/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Cartography class PerformanceView: UIView { private let categoryLabel = Label(fontWeight: .Bold, fontStyle: .Normal, fontSize: .Large) private let ageGroupLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Large) private let stageTimeIcon = UIImageView(image: UIImage(named: "IconDate")) private let stageTimeLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let venueIcon = UIImageView(image: UIImage(named: "IconLocation")) private let venueLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let appearancesSeparator = SeparatorView() private let mainAppearancesLabel = Label(fontWeight: .Bold, fontStyle: .Normal, fontSize: .Medium) private let accompanistsLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let predecessorInfoLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let piecesSeparator = SeparatorView() private let piecesStackView: UIStackView // MARK: - Lifecycle init(performance: FormattedPerformance) { mainAppearancesLabel.numberOfLines = 0 accompanistsLabel.numberOfLines = 0 accompanistsLabel.textColor = Color.secondaryTextColor categoryLabel.text = performance.category ageGroupLabel.text = performance.ageGroup stageTimeLabel.text = performance.stageTime venueLabel.text = performance.venue mainAppearancesLabel.text = performance.mainAppearances accompanistsLabel.text = performance.accompanists predecessorInfoLabel.text = performance.predecessorInfo let pieceViews = performance.pieces.map(PieceView.init) piecesStackView = UIStackView(arrangedSubviews: pieceViews) piecesStackView.axis = .Vertical piecesStackView.spacing = 8 super.init(frame: CGRectZero) addSubview(categoryLabel) addSubview(ageGroupLabel) addSubview(stageTimeIcon) addSubview(stageTimeLabel) addSubview(venueIcon) addSubview(venueLabel) addSubview(appearancesSeparator) addSubview(mainAppearancesLabel) addSubview(accompanistsLabel) addSubview(predecessorInfoLabel) addSubview(piecesSeparator) addSubview(piecesStackView) makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout private func makeConstraints() { constrain(categoryLabel, self) { categoryLabel, superview in categoryLabel.top == superview.top categoryLabel.left == superview.left categoryLabel.right <= superview.right } constrain(ageGroupLabel, categoryLabel, self) { ageGroupLabel, categoryLabel, superview in ageGroupLabel.top == categoryLabel.bottom ageGroupLabel.right <= superview.right } constrain(stageTimeIcon, stageTimeLabel, ageGroupLabel) { stageTimeIcon, stageTimeLabel, ageGroupLabel in stageTimeLabel.top == ageGroupLabel.bottom + 16 stageTimeLabel.left == stageTimeIcon.right + 8 align(centerY: stageTimeIcon, stageTimeLabel) } constrain(venueIcon, venueLabel, stageTimeLabel) { venueIcon, venueLabel, stageTimeLabel in venueLabel.top == stageTimeLabel.bottom + 4 venueLabel.left == venueIcon.right + 8 align(centerY: venueIcon, venueLabel) } constrain(appearancesSeparator, venueLabel, self) { appearancesSeparator, venueLabel, superview in appearancesSeparator.top == venueLabel.bottom + 16 appearancesSeparator.centerX == superview.centerXWithinMargins appearancesSeparator.width == superview.width * 0.7 } constrain(mainAppearancesLabel, appearancesSeparator, self) { mainAppearancesLabel, appearancesSeparator, superview in mainAppearancesLabel.top == appearancesSeparator.bottom + 16 mainAppearancesLabel.right <= superview.right } constrain(accompanistsLabel, mainAppearancesLabel, self) { accompanistsLabel, mainAppearancesLabel, superview in accompanistsLabel.top == mainAppearancesLabel.bottom accompanistsLabel.right <= superview.right } constrain(predecessorInfoLabel, accompanistsLabel, self) { predecessorInfoLabel, accompanistsLabel, superview in predecessorInfoLabel.top == accompanistsLabel.bottom + 8 predecessorInfoLabel.right <= superview.right } constrain(piecesSeparator, predecessorInfoLabel, self) { piecesSeparator, predecessorInfoLabel, superview in piecesSeparator.top == predecessorInfoLabel.bottom + 16 } constrain(piecesStackView, piecesSeparator, self) { piecesStackView, piecesSeparator, superview in piecesStackView.top == piecesSeparator.bottom + 16 piecesStackView.right <= superview.right } constrain(piecesStackView, self) { piecesStackView, superview in piecesStackView.bottom == superview.bottom } constrain(categoryLabel, ageGroupLabel, stageTimeIcon, venueIcon, mainAppearancesLabel) { categoryLabel, ageGroupLabel, stageTimeIcon, venueIcon, mainAppearancesLabel in align(left: categoryLabel, ageGroupLabel, stageTimeIcon, venueIcon, mainAppearancesLabel) } constrain(mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel, piecesStackView) { mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel, piecesStackView in align(left: mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel, piecesStackView) } constrain(appearancesSeparator, piecesSeparator) { appearancesSeparator, piecesSeparator in align(left: appearancesSeparator, piecesSeparator) align(right: appearancesSeparator, piecesSeparator) } } }
1608aac89d0a637e3e9c5931a49dda8e
43.163121
181
0.707564
false
false
false
false
nghialv/Sapporo
refs/heads/master
Sapporo/Extension/ArrayExt.swift
mit
1
// // ArrayExt.swift // Example // // Created by Le VanNghia on 6/29/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import Foundation extension Array { var isNotEmpty: Bool { return !isEmpty } func hasIndex(_ index: Int) -> Bool { return indices ~= index } func getSafeIndex(_ index: Int) -> Int { let mIndex = Swift.max(0, index) return Swift.min(count, mIndex) } func getSafeRange(_ range: CountableRange<Int>) -> CountableRange<Int>? { let start = Swift.max(0, range.lowerBound) let end = Swift.min(count, range.upperBound) return start <= end ? start..<end : nil } func getSafeRange(_ range: CountableClosedRange<Int>) -> CountableRange<Int>? { let start = Swift.max(0, range.lowerBound) let end = Swift.min(count, range.upperBound) return start <= end ? start..<end : nil } func get(_ index: Int) -> Element? { return hasIndex(index) ? self[index] : nil } @discardableResult mutating func append(_ newArray: Array) -> CountableRange<Int> { let range = count..<(count + newArray.count) self += newArray return range } @discardableResult mutating func insert(_ newArray: Array, atIndex index: Int) -> CountableRange<Int> { let mIndex = Swift.max(0, index) let start = Swift.min(count, mIndex) let end = start + newArray.count let left = self[0..<start] let right = self[start..<count] self = left + newArray + right return start..<end } @discardableResult mutating func move(fromIndex from: Int, toIndex to: Int) -> Bool { if !hasIndex(from) || !hasIndex(to) || from == to { return false } if let fromItem = get(from) { remove(from) insert(fromItem, at: to) return true } return false } @discardableResult mutating func remove(_ index: Int) -> CountableRange<Int>? { if !hasIndex(index) { return nil } self.remove(at: index) return index..<(index + 1) } @discardableResult mutating func remove(_ range: CountableRange<Int>) -> CountableRange<Int>? { if let sr = getSafeRange(range) { removeSubrange(sr) return sr } return nil } @discardableResult mutating func remove(_ range: CountableClosedRange<Int>) -> CountableRange<Int>? { if let sr = getSafeRange(range) { removeSubrange(sr) return sr } return nil } mutating func remove<T: AnyObject> (_ element: T) { let anotherSelf = self removeAll(keepingCapacity: true) anotherSelf.each { (index: Int, current: Element) in if (current as! T) !== element { self.append(current) } } } @discardableResult mutating func removeLast() -> CountableRange<Int>? { return remove(count - 1) } func each(_ exe: (Int, Element) -> ()) { for (index, item) in enumerated() { exe(index, item) } } }
e96dcf7e2aa7b22245145cafc8f36c99
25.926829
88
0.5468
false
false
false
false
hanhailong/practice-swift
refs/heads/master
Gesture/TouchExplorer/TouchExplorer/ViewController.swift
mit
2
// // ViewController.swift // TouchExplorer // // Created by Domenico on 01/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var messageLabel:UILabel! @IBOutlet var tapsLabel:UILabel! @IBOutlet var touchesLabel:UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func updateLabelsFromTouches(touches:Set<NSObject>!) { let touch = touches.first as! UITouch let numTaps = touch.tapCount let tapsMessage = "\(numTaps) taps detected" tapsLabel.text = tapsMessage let numTouches = touches.count let touchMsg = "\(numTouches) touches detected" touchesLabel.text = touchMsg } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { messageLabel.text = "Touches Began" updateLabelsFromTouches(event.allTouches()) } override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent) { messageLabel.text = "Touches Cancelled" updateLabelsFromTouches(event.allTouches()) } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { messageLabel.text = "Touches Ended" updateLabelsFromTouches(event.allTouches()) } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { messageLabel.text = "Drag Detected" updateLabelsFromTouches(event.allTouches()) } }
51bb3ea3bf67b1046002b31136c5c26a
29.055556
86
0.669747
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
Client/Frontend/Browser/SavedTab.swift
mpl-2.0
10
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared class SavedTab: NSObject, NSCoding { let isSelected: Bool let title: String? let isPrivate: Bool var sessionData: SessionData? var screenshotUUID: UUID? var faviconURL: String? var jsonDictionary: [String: AnyObject] { let title: String = self.title ?? "null" let faviconURL: String = self.faviconURL ?? "null" let uuid: String = self.screenshotUUID?.uuidString ?? "null" var json: [String: AnyObject] = [ "title": title as AnyObject, "isPrivate": String(self.isPrivate) as AnyObject, "isSelected": String(self.isSelected) as AnyObject, "faviconURL": faviconURL as AnyObject, "screenshotUUID": uuid as AnyObject ] if let sessionDataInfo = self.sessionData?.jsonDictionary { json["sessionData"] = sessionDataInfo as AnyObject? } return json } init?(tab: Tab, isSelected: Bool) { assert(Thread.isMainThread) self.screenshotUUID = tab.screenshotUUID as UUID? self.isSelected = isSelected self.title = tab.displayTitle self.isPrivate = tab.isPrivate self.faviconURL = tab.displayFavicon?.url super.init() if tab.sessionData == nil { let currentItem: WKBackForwardListItem! = tab.webView?.backForwardList.currentItem // Freshly created web views won't have any history entries at all. // If we have no history, abort. if currentItem == nil { return nil } let backList = tab.webView?.backForwardList.backList ?? [] let forwardList = tab.webView?.backForwardList.forwardList ?? [] let urls = (backList + [currentItem] + forwardList).map { $0.url } let currentPage = -forwardList.count self.sessionData = SessionData(currentPage: currentPage, urls: urls, lastUsedTime: tab.lastExecutedTime ?? Date.now()) } else { self.sessionData = tab.sessionData } } required init?(coder: NSCoder) { self.sessionData = coder.decodeObject(forKey: "sessionData") as? SessionData self.screenshotUUID = coder.decodeObject(forKey: "screenshotUUID") as? UUID self.isSelected = coder.decodeBool(forKey: "isSelected") self.title = coder.decodeObject(forKey: "title") as? String self.isPrivate = coder.decodeBool(forKey: "isPrivate") self.faviconURL = coder.decodeObject(forKey: "faviconURL") as? String } func encode(with coder: NSCoder) { coder.encode(sessionData, forKey: "sessionData") coder.encode(screenshotUUID, forKey: "screenshotUUID") coder.encode(isSelected, forKey: "isSelected") coder.encode(title, forKey: "title") coder.encode(isPrivate, forKey: "isPrivate") coder.encode(faviconURL, forKey: "faviconURL") } func configureSavedTabUsing(_ tab: Tab, imageStore: DiskImageStore? = nil) -> Tab { // Since this is a restored tab, reset the URL to be loaded as that will be handled by the SessionRestoreHandler tab.url = nil if let faviconURL = faviconURL { let icon = Favicon(url: faviconURL, date: Date()) icon.width = 1 tab.favicons.append(icon) } if let screenshotUUID = screenshotUUID, let imageStore = imageStore { tab.screenshotUUID = screenshotUUID imageStore.get(screenshotUUID.uuidString) >>== { screenshot in if tab.screenshotUUID == screenshotUUID { tab.setScreenshot(screenshot, revUUID: false) } } } tab.sessionData = sessionData tab.lastTitle = title return tab } }
b88a15ba4a2c47afbd1af9f8fd70b9f0
36.772727
130
0.611793
false
false
false
false
rasmusth/BluetoothKit
refs/heads/master
Example/Vendor/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift
mit
1
// // Collection+Extension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 02/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int { func toUInt32Array() -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt32>.size) { var val: UInt32 = 0 val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0 val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0 val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0 val |= self.count > 0 ? UInt32(self[idx]) : 0 result.append(val) } return result } func toUInt64Array() -> Array<UInt64> { var result = Array<UInt64>() result.reserveCapacity(32) for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt64>.size) { var val:UInt64 = 0 val |= self.count > 7 ? UInt64(self[idx.advanced(by: 7)]) << 56 : 0 val |= self.count > 6 ? UInt64(self[idx.advanced(by: 6)]) << 48 : 0 val |= self.count > 5 ? UInt64(self[idx.advanced(by: 5)]) << 40 : 0 val |= self.count > 4 ? UInt64(self[idx.advanced(by: 4)]) << 32 : 0 val |= self.count > 3 ? UInt64(self[idx.advanced(by: 3)]) << 24 : 0 val |= self.count > 2 ? UInt64(self[idx.advanced(by: 2)]) << 16 : 0 val |= self.count > 1 ? UInt64(self[idx.advanced(by: 1)]) << 8 : 0 val |= self.count > 0 ? UInt64(self[idx.advanced(by: 0)]) << 0 : 0 result.append(val) } return result } /// Initialize integer from array of bytes. Caution: may be slow! @available(*, deprecated: 0.6.0, message: "Dont use it. Too generic to be fast") func toInteger<T:Integer>() -> T where T: ByteConvertible, T: BitshiftOperationsType { if self.count == 0 { return 0; } let size = MemoryLayout<T>.size var bytes = self.reversed() //FIXME: check it this is equivalent of Array(...) if bytes.count < size { let paddingCount = size - bytes.count if (paddingCount > 0) { bytes += Array<UInt8>(repeating: 0, count: paddingCount) } } if size == 1 { return T(truncatingBitPattern: UInt64(bytes[0])) } var result: T = 0 for byte in bytes.reversed() { result = result << 8 | T(byte) } return result } }
0f5a2e45814202f3cfef21cf224e5cd9
37.8
100
0.546392
false
false
false
false
MaddTheSane/WWDC
refs/heads/master
WWDC/Preferences.swift
bsd-2-clause
9
// // Preferences.swift // WWDC // // Created by Guilherme Rambo on 01/05/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa let LocalVideoStoragePathPreferenceChangedNotification = "LocalVideoStoragePathPreferenceChangedNotification" let TranscriptPreferencesChangedNotification = "TranscriptPreferencesChangedNotification" let AutomaticRefreshPreferenceChangedNotification = "AutomaticRefreshPreferenceChangedNotification" private let _SharedPreferences = Preferences(); class Preferences { class func SharedPreferences() -> Preferences { return _SharedPreferences } private let defaults = NSUserDefaults.standardUserDefaults() private let nc = NSNotificationCenter.defaultCenter() // keys for NSUserDefault's dictionary private struct Keys { static let mainWindowFrame = "mainWindowFrame" static let localVideoStoragePath = "localVideoStoragePath" static let lastVideoWindowScale = "lastVideoWindowScale" static let autoplayLiveEvents = "autoplayLiveEvents" static let liveEventCheckInterval = "liveEventCheckInterval" static let userKnowsLiveEventThing = "userKnowsLiveEventThing" static let automaticRefreshEnabled = "automaticRefreshEnabled" static let floatOnTopEnabled = "floatOnTopEnabled" struct transcript { static let font = "transcript.font" static let textColor = "transcript.textColor" static let bgColor = "transcript.bgColor" } struct VideosController { static let selectedItem = "VideosController.selectedItem" static let searchTerm = "VideosController.searchTerm" static let dividerPosition = "VideosController.dividerPosition" } } // default values if preferences were not set private struct DefaultValues { static let localVideoStoragePath = NSString.pathWithComponents([NSHomeDirectory(), "Library", "Application Support", "WWDC"]) static let lastVideoWindowScale = CGFloat(100.0) static let autoplayLiveEvents = true static let liveEventCheckInterval = 15.0 static let userKnowsLiveEventThing = false static let automaticRefreshEnabled = true static let automaticRefreshInterval = 60.0 static let floatOnTopEnabled = false struct transcript { static let font = NSFont(name: "Avenir Next", size: 16.0)! static let textColor = NSColor.blackColor() static let bgColor = NSColor.whiteColor() } struct VideosController { static let selectedItem = -1 static let searchTerm = "" static let dividerPosition = 260.0 } } // the main window's frame var mainWindowFrame: NSRect { set { defaults.setObject(NSStringFromRect(newValue), forKey: Keys.mainWindowFrame) } get { if let rectString = defaults.objectForKey(Keys.mainWindowFrame) as? String { return NSRectFromString(rectString) } else { return NSZeroRect } } } // the selected session on the list var selectedSession: Int { set { defaults.setObject(newValue, forKey: Keys.VideosController.selectedItem) } get { if let item = defaults.objectForKey(Keys.VideosController.selectedItem) as? Int { return item } else { return DefaultValues.VideosController.selectedItem } } } // the splitView's divider position var dividerPosition: CGFloat { set { defaults.setObject(NSNumber(double: Double(newValue)), forKey: Keys.VideosController.dividerPosition) } get { if let width = defaults.objectForKey(Keys.VideosController.dividerPosition) as? NSNumber { return CGFloat(width.doubleValue) } else { return CGFloat(DefaultValues.VideosController.dividerPosition) } } } // the search term var searchTerm: String { set { defaults.setObject(newValue, forKey: Keys.VideosController.searchTerm) } get { if let term = defaults.objectForKey(Keys.VideosController.searchTerm) as? String { return term } else { return DefaultValues.VideosController.searchTerm } } } // where to save downloaded videos var localVideoStoragePath: String { set { defaults.setObject(newValue, forKey: Keys.localVideoStoragePath) nc.postNotificationName(LocalVideoStoragePathPreferenceChangedNotification, object: newValue) } get { if let path = defaults.objectForKey(Keys.localVideoStoragePath) as? String { return path } else { return DefaultValues.localVideoStoragePath } } } // the transcript font var transcriptFont: NSFont { set { // NSFont can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob let data = NSKeyedArchiver.archivedDataWithRootObject(newValue) defaults.setObject(data, forKey: Keys.transcript.font) nc.postNotificationName(TranscriptPreferencesChangedNotification, object: nil) } get { if let fontData = defaults.dataForKey(Keys.transcript.font) { if let font = NSKeyedUnarchiver.unarchiveObjectWithData(fontData) as? NSFont { return font } else { return DefaultValues.transcript.font } } else { return DefaultValues.transcript.font } } } // the transcript's text color var transcriptTextColor: NSColor { // NSColor can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob set { let colorData = NSKeyedArchiver.archivedDataWithRootObject(newValue) defaults.setObject(colorData, forKey: Keys.transcript.textColor) nc.postNotificationName(TranscriptPreferencesChangedNotification, object: nil) } get { if let colorData = defaults.dataForKey(Keys.transcript.textColor) { if let color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? NSColor { return color } else { return DefaultValues.transcript.textColor } } else { return DefaultValues.transcript.textColor } } } // the transcript's background color var transcriptBgColor: NSColor { // NSColor can't be put into NSUserDefaults directly, so we archive It and store as a NSData blob set { let colorData = NSKeyedArchiver.archivedDataWithRootObject(newValue) defaults.setObject(colorData, forKey: Keys.transcript.bgColor) nc.postNotificationName(TranscriptPreferencesChangedNotification, object: nil) } get { if let colorData = defaults.dataForKey(Keys.transcript.bgColor) { if let color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? NSColor { return color } else { return DefaultValues.transcript.bgColor } } else { return DefaultValues.transcript.bgColor } } } // the last scale selected for the video window var lastVideoWindowScale: CGFloat { get { if let scale = defaults.objectForKey(Keys.lastVideoWindowScale) as? NSNumber { return CGFloat(scale.doubleValue) } else { return DefaultValues.lastVideoWindowScale } } set { defaults.setObject(NSNumber(double: Double(newValue)), forKey: Keys.lastVideoWindowScale) } } // play live events automatically or not // TODO: expose this preference to the user var autoplayLiveEvents: Bool { get { if let object = defaults.objectForKey(Keys.autoplayLiveEvents) as? NSNumber { return object.boolValue } else { return DefaultValues.autoplayLiveEvents } } set { defaults.setObject(NSNumber(bool: newValue), forKey: Keys.autoplayLiveEvents) } } // how often to check for live events (in seconds) var liveEventCheckInterval: Double { get { if let object = defaults.objectForKey(Keys.liveEventCheckInterval) as? NSNumber { return object.doubleValue } else { return DefaultValues.liveEventCheckInterval } } set { defaults.setObject(NSNumber(double: newValue), forKey: Keys.liveEventCheckInterval) } } // user was informed about the possibility to watch the live keynote here :) var userKnowsLiveEventThing: Bool { get { if let object = defaults.objectForKey(Keys.userKnowsLiveEventThing) as? NSNumber { return object.boolValue } else { return DefaultValues.userKnowsLiveEventThing } } set { defaults.setObject(NSNumber(bool: newValue), forKey: Keys.userKnowsLiveEventThing) } } // periodically refresh the list of sessions var automaticRefreshEnabled: Bool { get { if let object = defaults.objectForKey(Keys.automaticRefreshEnabled) as? NSNumber { return object.boolValue } else { return DefaultValues.automaticRefreshEnabled } } set { defaults.setObject(NSNumber(bool: newValue), forKey: Keys.automaticRefreshEnabled) nc.postNotificationName(AutomaticRefreshPreferenceChangedNotification, object: nil) } } var automaticRefreshInterval: Double { get { return DefaultValues.automaticRefreshInterval } } var floatOnTopEnabled: Bool { get { if let object = defaults.objectForKey(Keys.floatOnTopEnabled) as? NSNumber { return object.boolValue } else { return DefaultValues.floatOnTopEnabled } } set { defaults.setObject(NSNumber(bool: newValue), forKey: Keys.floatOnTopEnabled) } } }
08477506ef24a6742cc2cd0d282fbb28
34.989967
133
0.616543
false
false
false
false
marty-suzuki/QiitaApiClient
refs/heads/master
QiitaApiClient/Extension/NSHTTPURLResponse+QiitaApiClient.swift
mit
1
// // NSHTTPURLResponse+QiitaApiClient.swift // QiitaApiClient // // Created by Taiki Suzuki on 2016/08/21. // // import Foundation extension NSHTTPURLResponse { enum StatusCodeType: Int { case Unknown = 0 case OK = 200 case Created = 201 case NoContent = 204 case BadRequest = 400 case Unauthorized = 401 case Forbidden = 403 case NotFound = 404 case InternalServerError = 500 } var statusCodeType: StatusCodeType { return StatusCodeType(rawValue: statusCode) ?? .Unknown } public var totalCount: Int? { return Int(allHeaderFields["Total-Count"] as? String ?? "") } }
4b8a49b4f1be2e45a12ba43b9bc53c55
21.451613
67
0.614388
false
false
false
false
ayunav/AudioKit
refs/heads/master
Examples/iOS/Swift/AudioKitDemo/AudioKitDemo/Analysis/AnalysisViewController.swift
mit
3
// // AnalysisViewController.swift // AudioKitDemo // // Created by Nicholas Arner on 3/1/15. // Copyright (c) 2015 AudioKit. All rights reserved. // class AnalysisViewController: UIViewController { @IBOutlet var frequencyLabel: UILabel! @IBOutlet var amplitudeLabel: UILabel! @IBOutlet var noteNameLabel: UILabel! @IBOutlet var amplitudePlot: AKInstrumentPropertyPlot! @IBOutlet var frequencyPlot: AKInstrumentPropertyPlot! @IBOutlet var normalizedFrequencyPlot: AKFloatPlot! let microphone = Microphone() var analyzer: AKAudioAnalyzer! let noteFrequencies = [16.35,17.32,18.35,19.45,20.6,21.83,23.12,24.5,25.96,27.5,29.14,30.87] let noteNamesWithSharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"] let noteNamesWithFlats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"] var normalizedFrequency = AKInstrumentProperty(value: 0, minimum: 16.35, maximum: 30.87) let analysisSequence = AKSequence() let updateAnalysis = AKEvent() override func viewDidLoad() { super.viewDidLoad() analyzer = AKAudioAnalyzer(audioSource: microphone.auxilliaryOutput) AKOrchestra.addInstrument(microphone) AKOrchestra.addInstrument(analyzer) amplitudePlot.property = analyzer.trackedAmplitude frequencyPlot.property = analyzer.trackedFrequency normalizedFrequencyPlot.minimum = 15 normalizedFrequencyPlot.maximum = 32 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) analyzer.start() microphone.start() let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateUI"), userInfo: nil, repeats: true) } func updateUI() { if analyzer.trackedAmplitude.value > 0.1 { frequencyLabel.text = String(format: "%0.1f", analyzer.trackedFrequency.value) var frequency = analyzer.trackedFrequency.value while (frequency > Float(noteFrequencies[noteFrequencies.count-1])) { frequency = frequency / 2.0 } while (frequency < Float(noteFrequencies[0])) { frequency = frequency * 2.0 } normalizedFrequency.value = frequency normalizedFrequencyPlot.updateWithValue(frequency) var minDistance: Float = 10000.0 var index = 0 for (var i = 0; i < noteFrequencies.count; i++){ var distance = fabsf(Float(noteFrequencies[i]) - frequency) if (distance < minDistance){ index = i minDistance = distance } } var octave = Int(log2f(analyzer.trackedFrequency.value / frequency)) var noteName = String(format: "%@%d", noteNamesWithSharps[index], octave, noteNamesWithFlats[index], octave) noteNameLabel.text = noteName } amplitudeLabel.text = String(format: "%0.2f", analyzer.trackedAmplitude.value) } }
7ee4e6b1784502a659db98ae23184a9a
35.62069
139
0.608791
false
false
false
false
gu704823/ofo
refs/heads/master
ofo/songlistViewController.swift
mit
1
// // songlistViewController.swift // ofo // // Created by swift on 2017/5/15. // Copyright © 2017年 swift. All rights reserved. // import UIKit import SwiftyJSON import Kingfisher import AVFoundation class songlistViewController: UIViewController { //拖 @IBOutlet weak var songlist: UITableView! @IBOutlet weak var albumimg: UIImageView! @IBOutlet weak var progres: UIImageView! @IBOutlet weak var songpic: roundbutton! @IBOutlet weak var songname: UILabel! @IBOutlet weak var artist: UILabel! @IBOutlet weak var playpause: UIButton! @IBOutlet weak var currenttime: UILabel! @IBOutlet weak var totaltime: UILabel! @IBOutlet weak var nextbutton: UIButton! //定义属性 var songmodel:httpmodel = httpmodel() var songdict:[[String:JSON]] = [] var id:JSON = 0 var albumdict:[String:JSON]?{ didSet{ guard let urlrequest = albumdict?["albumimg"] else { return } let url = URL(string: "\(urlrequest)") albumimg.kf.setImage(with: url) } } var avplayer = AVPlayer() var isplay:Bool = true var timer:Timer? var index:Int = 0 override func viewDidLoad() { super.viewDidLoad() setupui() loaddata() threebutton() } } //ui extension songlistViewController{ fileprivate func setupui(){ //1.修改导航条样式 self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true let customFont = UIFont(name: "heiti SC", size: 12.0)! UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName:customFont], for: .normal) //tableview数据源代理 songlist.delegate = self songlist.dataSource = self // } } //tableview extension songlistViewController:UITableViewDataSource,UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songdict.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "songlist", for: indexPath) as! songlistTableViewCell let urladdr = songdict[indexPath.row]["pict"] let url = URL(string: "\(urladdr!)") cell.author.kf.setImage(with:url ) cell.singer.text = "\(songdict[indexPath.row]["author"]!)" cell.title.text = "\(songdict[indexPath.row]["title"]!)" guard let timedurtation = Int(songdict[indexPath.row]["file_duration"]! .stringValue) else{ return cell } cell.time.text = lengthtime.length(all: timedurtation) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 92 } } //loaddata extension songlistViewController{ fileprivate func loaddata(){ songmodel.onsearhlist(type: "\(id)") { ( data1, data2) in self.songdict = data2 self.albumdict = data1 self.songlist.reloadData() } } } //点击cell处理逻辑 extension songlistViewController{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { onselectrow(index: indexPath.row) } func onselectrow(index:Int){ let indexpatch = IndexPath(item: index, section: 0) songlist.selectRow(at: indexpatch, animated: true, scrollPosition: .top) songname.text = "\(songdict[indexpatch.row]["title"]!)" artist.text = "\(songdict[indexpatch.row]["author"]!)" let urladdr = songdict[indexpatch.row]["pict"] guard let songpicurl = URL(string: "\(urladdr!)") else { return } songpic.kf.setImage(with: songpicurl, for: .normal) songpic.onrotation() let songid = songdict[indexpatch.row]["songid"]! songmodel.getmusicdata(songid: "\(songid)") { (filelink) in self.onplaymusic(filelinkurl: "\(filelink)") } //时间 timer?.invalidate() currenttime.text = "00:00" timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(onupdate), userInfo: nil, repeats: true) } func onplaymusic(filelinkurl:String){ let url = URL(string: filelinkurl) self.avplayer = AVPlayer(url: url!) self.avplayer.play() } //最下面三个按钮的方法 fileprivate func threebutton(){ playpause.addTarget(self, action: #selector(play), for: .touchUpInside) nextbutton.addTarget(self, action: #selector(nextmusic), for: .touchUpInside) } } extension songlistViewController{ //更新时间方法 @objc fileprivate func onupdate(){ let currenttimer = CMTimeGetSeconds(self.avplayer.currentTime()) let totaltimer = TimeInterval((avplayer.currentItem?.duration.value)!)/TimeInterval((avplayer.currentItem?.duration.timescale)!) let progr = CGFloat(currenttimer/totaltimer) if currenttimer>0.0{ currenttime.text = lengthtime.length(all: Int(currenttimer)) totaltime.text = lengthtime.length(all: Int(totaltimer)) self.progres.frame.size.width = view.frame.size.width * progr } } @objc fileprivate func play(){ if isplay{ avplayer.pause() playpause.setBackgroundImage(#imageLiteral(resourceName: "pause"), for: .normal) isplay = !isplay songpic.pause() }else{ avplayer.play() playpause.setBackgroundImage(#imageLiteral(resourceName: "play"), for: .normal) isplay = !isplay songpic.onrotation() } } @objc fileprivate func nextmusic(btn:UIButton){ if btn == nextbutton{ index += 1 if index>self.songdict.count - 1{ index = 0 } } onselectrow(index: index) playpause.setBackgroundImage(#imageLiteral(resourceName: "pause"), for: .normal) isplay = !isplay } }
22b7468612703c051de471ec7969782c
32.787234
136
0.627047
false
false
false
false
Qmerce/ios-sdk
refs/heads/master
Sources/Helpers/Constants.swift
mit
1
// // Constants.swift // ApesterKit // // Created by Hasan Sa on 24/02/2019. // Copyright © 2019 Apester. All rights reserved. // import Foundation struct Constants { /// Payload Keys struct Payload { static let advertisingId = "advertisingId" static let trackingEnabled = "trackingEnabled" static let bundleId = "bundleId" static let appName = "appName" static let appVersion = "appVersion" static let appStoreUrl = "appStoreUrl" static let sdkVersion = "sdkVersion" } /// WebView shared functions or keys struct WebView { static let apesterAdsCompleted = "apester_ads_completed" // functions static let close = "window.__closeApesterStory()" // static func sendApesterEvent(with message: String) -> String { "window.__sendApesterEvent(\(message))" } // static func setViewVisibilityStatus(_ isVisible: Bool) -> String { "window.__setApesterViewabiity(\(isVisible))" } // static let getHeight = "window.__getHeight()" static let refreshContent = "window.__refreshApesterContent()" static let pause = "window.__storyPause()" static let resume = "window.__storyResume()" static let restart = "window.__storyRestart()" static let fullscreenOff = "fullscreen_off" } /// Strip Keys struct Strip { // urls static let stripPath = "/apester-detatched-strip.html" static let stripStoryPath = "/apester-detatched-story.html" // events static let proxy = "apesterStripProxy" static let initial = "apester_strip_units" static let loaded = "strip_loaded" static let isReady = "apester_interaction_loaded" static let open = "strip_open_unit" static let next = "strip_next_unit" static let off = "fullscreen_off" static let destroy = "apester_strip_removed" static let showStripStory = "showApesterStory" static let hideStripStory = "hideApesterStory" static let stripHeight = "mobileStripHeight" static let stripResizeHeight = "strip_resize" static let validateStripViewVisibity = "validateStripViewVisibity" } struct Unit { static let isReady = "apester_interaction_loaded" static let unitPath = "/v2/static/in-app-unit-detached.html" static let proxy = "apesterUnitProxy" static let resize = "apester_resize_unit" static let height = "height" static let width = "width" static let validateUnitViewVisibility = "validateUnitViewVisibity" static let initInAppParams = "init_inapp_params" } struct Monetization { static let adMob = "adMob" static let pubMatic = "pubMatic" static let profileId = "iosProfileId" static let adProvider = "provider" static let adMobUnitId = "adUnitId" static let publisherId = "publisherId" static let appStoreUrl = "iosAppStoreUrl" static let initNativeAd = "apester_init_native_ad" static let initInUnit = "apester_init_inunit" static let killInUnit = "apester_kill_native_ad" static let pubMaticUnitId = "iosAdUnitId" static let isCompanionVariant = "isCompanionVariant" static let adType = "adType" static let appDomain = "appDomain" static let testMode = "testMode" static let debugLogs = "debugLogs" static let bidSummaryLogs = "bidSummaryLogs" static let timeInView = "timeInView" static let playerMonImpression = "player_mon_impression" static let playerMonLoadingPass = "player_mon_loading_pass" static let playerMonImpressionPending = "player_mon_impression_pending" static let playerMonLoadingImpressionFailed = "player_mon_loading_impression_failed" } }
6d58009e90098b2c069e296ac2b4911c
39.039604
93
0.627349
false
false
false
false